diff --git a/App_Code/ClsCompras.vb b/App_Code/ClsCompras.vb index d51086b15..dfda922b1 100644 --- a/App_Code/ClsCompras.vb +++ b/App_Code/ClsCompras.vb @@ -2164,10 +2164,10 @@ Public Class ClsCompras End Try Return Retorno - End Function - + End Function + #End Region - + #Region " DEVOLUCIONES COMPRAS - IPP FEBRERO 2018 " Public Function ComprasDetalleDevolucionesAdd(CveCompraDetalle As Integer, CveCompraNC As Integer, Cantidad As Double, CveEmpresa As Integer) As Boolean Dim Retorno As Boolean = False diff --git a/App_Code/ClsInventarios.vb b/App_Code/ClsInventarios.vb index 9048034c3..270e9143a 100644 --- a/App_Code/ClsInventarios.vb +++ b/App_Code/ClsInventarios.vb @@ -25,11 +25,11 @@ Public Class ClsInventarios End Function Public Sub RollBack() - SqlTransacc.Rollback() + If SqlTransacc.Connection IsNot Nothing Then SqlTransacc.Rollback() End Sub Public Sub Commit() - SqlTransacc.Commit() + If SqlTransacc.Connection IsNot Nothing Then SqlTransacc.Commit() End Sub #Region " PROPIEDADES " diff --git a/App_Code/Modelos.vb b/App_Code/Modelos.vb index 41b6f6116..58a1b50f4 100644 --- a/App_Code/Modelos.vb +++ b/App_Code/Modelos.vb @@ -2681,7 +2681,7 @@ Namespace Modelos CveCuentaContabilizacion = 0 End If - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuesto) Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuesto, TipoCambio:=tipoCambio) Then ErrorPrepoliza = True Else ObjFactura.SeGuardoPrePoliza = True @@ -2750,8 +2750,8 @@ Namespace Modelos If idCuentaContabilizacion > 0 Then If ObjConta.ContabilizarPrePoliza(ObjFactura.CvePrePoliza, ObjFactura.CveUsuario, UsuarioActual.Empresa, ObjConta:=objContPaqi) Then Else - ErrorList.Add("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico") - ErrorPrepoliza = True + 'ErrorList.Add("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico") + 'ErrorPrepoliza = True End If Else ErrorList.Add(String.Format("Falta asignación de las siguientes cuentas contables: {0}", CuentasContablesInvalidas)) diff --git a/Bancos/IE.aspx.vb b/Bancos/IE.aspx.vb index 992eadfb5..f718db096 100644 --- a/Bancos/IE.aspx.vb +++ b/Bancos/IE.aspx.vb @@ -727,8 +727,8 @@ Partial Class Bancos_IE End If End If - End Sub - + End Sub + #Region " CARGA DATOS " Private Sub CargaDatos() Dim ObjIE As New ClsBancos() @@ -3803,7 +3803,7 @@ Partial Class Bancos_IE Banc.IniciaTransacSQL() Dim ObjAC As ClsContPAQi = Nothing - If UsuarioActual.Empresa.UsaAC Then + If UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad Then ObjAC = New ClsContPAQi(UsuarioActual.Empresa) ObjAC.IniciaTransacSQL() End If @@ -3814,7 +3814,7 @@ Partial Class Bancos_IE Dim IdPolizaNueva = -1 Dim FolioPolizaNueva = -1 - If (IDPoliza > 0 AndAlso UsuarioActual.Empresa.UsaAC) Then + If (IDPoliza > 0 AndAlso (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad)) Then If ObjAC Is Nothing Then ErrorCancelar = True @@ -4013,7 +4013,7 @@ Partial Class Bancos_IE Dim ObjConta As New ClsContabilidad(Banc.IniciaTransacSQL) Dim ObjAC As ClsContPAQi = Nothing - If UsuarioActual.Empresa.UsaAC Then + If UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad Then ObjAC = New ClsContPAQi(UsuarioActual.Empresa) ObjAC.IniciaTransacSQL() End If @@ -4023,7 +4023,7 @@ Partial Class Bancos_IE Dim IdPolizaNueva = -1 Dim FolioPolizaNueva = -1 - If (IDPoliza > 0 AndAlso UsuarioActual.Empresa.UsaAC) Then + If (IDPoliza > 0 AndAlso (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad)) Then If ObjAC Is Nothing Then ErrorCancelar = True diff --git a/Bin/APP_Code_CSharp.dll b/Bin/APP_Code_CSharp.dll index 64377defa..1eeb8c17e 100644 Binary files a/Bin/APP_Code_CSharp.dll and b/Bin/APP_Code_CSharp.dll differ diff --git a/Bin/APP_Code_CSharp.pdb b/Bin/APP_Code_CSharp.pdb index 16f4d3b4d..dd15603d0 100644 Binary files a/Bin/APP_Code_CSharp.pdb and b/Bin/APP_Code_CSharp.pdb differ diff --git a/Compras/Compras.aspx.vb b/Compras/Compras.aspx.vb index 1019c0ea2..cc75184c1 100644 --- a/Compras/Compras.aspx.vb +++ b/Compras/Compras.aspx.vb @@ -1,18768 +1,18768 @@ -Option Explicit On -Option Strict On - -Imports Extensiones -Imports System.Data -Imports System.Xml -Imports System.Globalization -Imports System.Linq -Imports System -Imports System.IO -Imports ADServerControl -Imports System.Threading.Tasks -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 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 - - 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 CveCuentaProveedor As Integer - Get - Return ViewState("CveCuentaProveedor").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 CveCuentaProveedorDeudores As Integer - Get - Return ViewState("CveCuentaProveedorDeudores").ToString.ToEntero - End Get - End Property - Private ReadOnly Property CveCuentaProveedorAcreedores As Integer - Get - Return ViewState("CveCuentaProveedorAcreedores").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 CveCuentaProveedorAnticipos As Integer - Get - Return ViewState("CveCuentaProveedorAnticipos").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 CveCuentaProveedorAnticiposExtranjera As Integer - Get - Return ViewState("CveCuentaProveedorAnticiposExtranjera").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 CveCuentaProveedorAnticiposComplementaria As Integer - Get - Return ViewState("CveCuentaProveedorAnticiposComplementaria").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 CveCuentaProveedorRetIVA As Integer - Get - Return ViewState("CveCuentaProveedorRetIVA").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 CveCuentaProveedorRetISR As Integer - Get - Return ViewState("CveCuentaProveedorRetISR").ToString.ToEntero - End Get - End Property - - Private ReadOnly Property CveCuentaIEPS As Integer - Get - Return ViewState("CveCuentaIEPS").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 CveCuentaProveedorExtranjera As Integer - Get - Return ViewState("CveCuentaProveedorExtranjera").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 CveCuentaProveedorComplementaria As Integer - Get - Return ViewState("CveCuentaProveedorComplementaria").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 CveCuentaBancaria As Integer - Get - Return ViewState("CveCuentaBancaria").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveCuentaBancaria") = 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 - - 'Private ReadOnly Property Ruta As String - ' Get - ' Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\" & UsuarioActual.CveEmpresa & "\" - ' End Get - 'End Property - - - Public Class Anticipos - Public Property TipoMovto As String - Public Property CveIE As Integer - Public Property Importe 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 - 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 -#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 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 Double - Get - Return ViewState("TipoCambio").ToString.ToDouble - End Get - Set(value As Double) - 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 - -#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 IVAOriginal As Double - Get - Return ViewState("IVAOriginal").ToString.ToDouble - 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 - Return ViewState("TotalOriginal").ToString.ToDouble - 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 - - 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() - Modalidad = "" - Version = "" - CveMetodoPago = -1 - RFCProv = "" - CargaDdlTipoGasto() - CreaTmpAcarreos() - EsContado = False - CierrePeriodo = False - NCDevolucion = False - CompraCargada = False - Saldo = 0 - SubTotalOriginal = 0 - CveConceptoContableAlmacen = 0 - EsNoDeducible = False - - '******** 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 - CveCuentaBancaria = 0 - End If - - 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("CveCompra") = "0" - 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 - - '[IPP] Eliminar 22Junio2018 - 'If UsuarioActual.Empresa.UsaInventarios Then - ' TabAlmacen.Enabled = Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 - 'End If - - 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.Empresa.GralSoloProyecto Then - - ' LitHProyecto.Text = "Sucursal" - ' DdlSubProyecto.Items.Clear() - ' DdlSubProyecto.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)) - ' DdlSubProyecto.DataBind() - ' DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - ' DdlAsignaSubProyecto.Items.Clear() - ' DdlAsignaSubProyecto.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)) - ' DdlAsignaSubProyecto.DataBind() - ' DdlAsignaSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - ' divproyecto.Visible = False - ' divasignaproyecto.Visible = False - ' DdlProyecto.Visible = False - ' DdlProyecto.Items(0).Text = "" - - 'End If - - 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) - DdlPersonal.DataSource = ObjPersonal.DtResultados - DdlPersonalReembolso.DataSource = ObjPersonal.DtResultados - ObjPersonal.Dispose() - DdlPersonal.DataBind() - DdlPersonalReembolso.DataBind() - ObjPersonal.Dispose() - - - '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) - DdlProveedor.Visible = False - HplProveedor.Visible = True - GvInv.Visible = True - CargaProveedor(-1, RFC) - - If Not DdlTipoComprobante.SelectedValue = "NC" 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, TxtSubTotal.Text.ToDouble) - InicializaAplicaNCFact() - DivReembolso.Visible = False - RBLPago.Items(2).Enabled = False - - End If - - - - If UsuarioActual.Empresa.UsaAC Then - CambiaEjercicioAC() - End If - - ' ''Fecha limite para ingreso de facturas - ''Dim DtEmpresa As DataTable = GlobalDTEmpresas(UsuarioActual.CveEmpresa) - ''If DtEmpresa.Rows.Count > 0 Then - '' Dim FechaLimite = DateSerial(DtEmpresa.Rows(0)("EjercicioActual").ToString.ToEntero, DtEmpresa.Rows(0)("PeriodoActual").ToString.ToEntero, DtEmpresa.Rows(0)("DiasPermitidos").ToString.ToEntero) - '' If Month(TxtFecha.Text.ToDate) < (Month(FechaLimite) - 1) Or (Month(TxtFecha.Text.ToDate) = (Month(FechaLimite) - 1) And Day(Date.Now) > Day(FechaLimite)) Then - '' Alert("La factura actual ya no aplica para ingresarse al sístema.", TipoMensaje.MsgAdvertencia) - '' BtnGuardar.Enabled = False - '' Else - '' Alert("En tiempo") - '' End If - ''Else - '' Alert("No se pudieron cargar los datos de la empresa", TipoMensaje.MsgAdvertencia) - ''End If - 'Carga Compra - - If UsuarioActual.Empresa.Funcionalidad(123).ToEntero > 0 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) - - 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 - - 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 - - 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO - LblSaldoFactura.Text = If(CveCompra > 0, Saldo.FormatoNumero, TxtTotal.Text.FormatoNumero) - - - If UsuarioActual.CveEmpresa = 126 And CveCompra > 0 Then - LnkExportaGv.Visible = True - End If - - 'Condiciones de la Compra - Dim dt As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario) - 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 - 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 - - If UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then - LitHProyecto.Text = "Proyecto" - LthProyectoP.Text = "Proyecto" - - LblSubProyectoHeader.Text = "" - LblSubProyectoPHeader.Text = "" - - LblSubProyecto.InnerText = "Proyecto" - 'LblSubProyectoDivAplica.InnerText = "Proyecto" - - DdlSubProyecto.Items.Clear() - 'DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - DdlSubProyecto.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)) - DdlSubProyecto.DataBind() - DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - 'DdlAsignaSubProyecto.Items.Clear() - 'DdlAsignaSubProyecto.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)) - 'DdlAsignaSubProyecto.DataBind() - 'DdlAsignaSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - divproyecto.Visible = False - 'divasignaproyecto.Visible = False - DdlProyecto.Visible = False - DdlProyecto.Items(0).Text = "" - - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then - LitHProyecto.Text = "Sucursal" - LthProyectoP.Text = "Sucursal" - - LblSubProyectoHeader.Text = "" - LblSubProyectoPHeader.Text = "" - - LblSubProyecto.InnerText = "Sucursal" - 'LblSubProyectoDivAplica.InnerText = "Sucursal" - - DdlSubProyecto.Items.Clear() - 'DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - DdlSubProyecto.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)) - DdlSubProyecto.DataBind() - DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - 'DdlAsignaSubProyecto.Items.Clear() - 'DdlAsignaSubProyecto.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)) - 'DdlAsignaSubProyecto.DataBind() - 'DdlAsignaSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - divproyecto.Visible = False - 'divasignaproyecto.Visible = False - DdlProyecto.Visible = False - DdlProyecto.Items(0).Text = "" - - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then - LitHProyecto.Text = "Sucursal" - LthProyectoP.Text = "Sucursal" - - LblSubProyectoHeader.Text = "Proyecto" - LblSubProyectoPHeader.Text = "Proyecto" - - 'LblSubProyectoDivAplica.InnerText = "Sucursal" - 'LblProyectoDivAplica.InnerText = "Proyecto" - LblSubProyecto.InnerText = "Sucursal" - LblProyecto.InnerText = "Proyecto" - - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then - LitHProyecto.Text = "Proyecto" - LthProyectoP.Text = "Proyecto" - - LblSubProyectoHeader.Text = "Sucursal" - LblSubProyectoPHeader.Text = "Sucursal" - - 'LblSubProyectoDivAplica.InnerText = "Proyecto" - 'LblProyectoDivAplica.InnerText = "Sucursal" - LblSubProyecto.InnerText = "Proyecto" - LblProyecto.InnerText = "Sucursal" - End If - - CargaGvPersonal() - CargaDdlPersonal() - - - InicializaDevolucionAlmacen() - HabilitaEdicionManualAgregar() - InicializaActualizarTC() - 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();") - End Sub - -#Region "C A R G A S" - 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() - 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 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 IVA del CFDi no tiene un comportamiento normal, por favor verifique que sea correcto.

NOTA: 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(-3), 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}Empresas\{1}\Compras\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, dr("RFCDe"), dr("XML")) - If IO.File.Exists(Archivo) Then - - Dim Validada As Boolean = True - 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 Valida As New ClsValidaCFDi(dr("UUID").ToString(), dr("RFCDe").ToString, dr("RFCPara").ToString(), dr("Total").ToString.ToDecimal) - - If UsuarioActual.CveEmpresa < 2 Then - Valida.EsValida = 1 - End If - - If Valida.EsValida > 0 Then - If Valida.EsValida = 2 Then - Validada = False - - If ObjeFacturas.UpdateEstatus(Valida.EsValida, CveFactura) 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.
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() - End If - - UpPSS.Update() - - - If Validada Then - - - - Try - - XMLDoc.Load(Archivo) - Catch ex As Exception - - Dim oReader = New StreamReader(Archivo, Encoding.GetEncoding("ISO-8859-1")) - XMLDoc.Load(oReader) - oReader.Dispose() - - End Try - - - CreaDTConceptos() - - CargaComprobanteXML(XMLDoc) - - If NuevaValidacionXML = 1 Or Version = "3.3" Then - Dim Xml As New StringBuilder - 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 = "http://www.sat.gob.mx/cfd/3" - Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) - - 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.Append(Replace(Replace(Replace(nodeconceptos.OuterXml, " 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
") - 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
") - 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
") - 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) - 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 - - - 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() - - Dim ObjSAT As New ClsSAT - Dim RFCRequest As String = Request("RFC").ToString - 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 {Estatus} en el Listado EFOS (69B) del SAT", TipoMensaje.MsgAdvertencia) - System.Threading.Thread.Sleep(5) - End If - End If - ObjSAT.Dispose() - - - Return RFC - End Function - - Private Sub CargaRetIVAConcepto(Optional Cambio As Boolean = False) - If TrRetIVA.Visible Then - TdRetIVAConcepto.Visible = True - End If - If Cambio Then - DdlRetIVAConcepto.Items.Clear() - If RFCProv.Length = 13 Then - DdlRetIVAConcepto.Items.Insert(0, New ListItem("Honorarios/Serv. Prof.", "1")) - DdlRetIVAConcepto.Items.Insert(1, New ListItem("Fletes P.F.", "2")) - ElseIf RFCProv.Length = 12 Then - DdlRetIVAConcepto.Items.Insert(0, New ListItem("Fletes P.M.", "3")) - End If - DdlRetIVAConcepto.Items.Add(New ListItem("Arrendamiento", "4")) - End If - UpPS.Update() - - End Sub - Private Sub CargaRetISRConcepto(Optional Cambio As Boolean = False) - If TrRetISR.Visible Then - TdRetISRConcepto.Visible = True - End If - If Cambio Then - DdlRetISRConcepto.Items.Clear() - DdlRetISRConcepto.Items.Insert(0, New ListItem("Honorarios", "1")) - DdlRetISRConcepto.Items.Insert(1, New ListItem("Arrendamiento", "2")) - End If - UpPS.Update() - End Sub - - Private Sub ValidacionesTotalesXml() - - Dim Msg As String = "" - Dim SubtotalTemp = TmpDT.SUM("Total") + Math.Round(TmpDT.SUM("Descuento"), 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
") - 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
") - 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
") - 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
") - 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
") - 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
({0}-{1})", Math.Round(TotalTemp, 2), Math.Round(Total, 2)) - End If - - If Msg <> "" Then - Alert($"El comprobante XML presenta las siguientes inconsistencias:

{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 - RegistraScript("$('#ModalIEPS').modal('show');") - - 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 - - - - 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) - - End Sub - - ''' - ''' Método que convierte el IEPS en un concepto para no ajustar totales - ''' - 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 Double = 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 Double = IEPS - Dim Total As Double = Cantidad * PU - Dim IVA As Double = 0 - Dim Descuento As Double = 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 - TxtDescripcion.Text = dr("Descripcion").ToString - CvePrePoliza = dr("CvePrePoliza").ToString.ToEntero - EstatusAlmacen = dr("EstatusAlmacen").ToString.ToEntero - DdlTipoCompra.SelectedValueExist(dr("CveTipoCompra")) - '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).Rows.Count > 0 Then - RowProveedorSucursal.Visible = True - DdlProveedorSucursal.Items.Clear() - DdlProveedorSucursal.DataSource = GlobalDTProveedorSucursales(CveProveedor) - 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.ToDouble - If TipoCambio > 1 Then LblTC.Text = String.Format("TC: {0}", TipoCambio.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 - 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) - - 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) - 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 - - 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 - - '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)) - - - - 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 = "Fac" 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 - 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 - 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 = "
Compras Aplicadas
" - 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 - If UsuarioActual.TienePermisoProceso(77) OrElse UsuarioActual.TienePermisoProceso(135) 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 Movimientos de Inventario 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 Poliza Asociada?", 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 - BtnEliminarCompra.Visible = False - BtnCancelarCompra.Visible = False - 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 - 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 If - - - UpEstatus.Update() - 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() - - ddlAlmacenAdd.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1).FiltraParametros("CveTipoAlmacen IN (1,2,7,14,19)") 'solo muestra tipo material y herramientas - ddlAlmacenAdd.DataBind() - 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 - - ViewState("CveProveedor") = ObjProveedor.CveProveedor - ViewState("CveTipoProveedor") = 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 - - 'Conta SIG - ViewState("CveCuentaProveedor") = ObjProveedor.CveCuentaProveedores - ViewState("CveCuentaProveedorAnticipos") = ObjProveedor.CveCuentaAnticipos - ViewState("CveCuentaProveedorAnticiposExtranjera") = ObjProveedor.CveCuentaAnticiposExtranjera - ViewState("CveCuentaProveedorAnticiposComplementaria") = ObjProveedor.CveCuentaAnticiposComplementaria - ViewState("CveCuentaProveedorDeudores") = ObjProveedor.CveCuentaDeudor - ViewState("CveCuentaProveedorAcreedores") = ObjProveedor.CveCuentaAcreedor - ViewState("CveCuentaProveedorRetISR") = ObjProveedor.CveCuentaRetISR - ViewState("CveCuentaProveedorRetIVA") = ObjProveedor.CveCuentaRetIVA - ViewState("CveCuentaProveedorExtranjera") = ObjProveedor.CveCuentaProveedoresExtranjera - ViewState("CveCuentaProveedorComplementaria") = ObjProveedor.CveCuentaProveedoresComplementaria - - - 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("{1}", 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) - 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) - CargaRetISRConcepto(True) - - If ObjProveedor.DIOTCveTipoOperacion = 1 Then '03 - Prestación de Servicios Profesionales - DdlRetIVAConcepto.SelectedValueExist("1") - DdlRetISRConcepto.SelectedValueExist("1") ' honorarios - ElseIf ObjProveedor.DIOTCveTipoOperacion = 2 Then ' 06 - Arrendamiento de inmuebles - DdlRetIVAConcepto.SelectedValueExist("4") - DdlRetISRConcepto.SelectedValueExist("2") ' arrendamiento - ElseIf ObjProveedor.DIOTCveTipoOperacion = 3 Then ' 85 - Otros - DdlRetIVAConcepto.SelectedValueExist("2") ' flete pf - DdlRetIVAConcepto.SelectedValueExist("3") ' fletes pm - DdlRetISRConcepto.SelectedValueExist("1") ' honorarios - 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) - - - 'MONEDA PREFERENTE - If CveCompra <= 0 Then - If CveFactura <= 0 Then - DdlMoneda.SelectedValueExist(ObjProveedor.CveMonedaPreferente) - End If - CambiaMoneda(False) - End If - - - 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 {Estatus} 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:=DdlMoneda.SelectedValue.ToEntero, SelectTop:=-1, TipoDocto:=FiltroTipo) AndAlso ObjMovtos.DtResultados.Rows.Count > 0 Then - GVAnticipos.DataSource = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act'") - 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() - 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(UsuarioActual.Empresa.Funcionalidad(105) = "1") - - 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 - DdlPSAlias2.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa) - DdlPSAlias2.DataBind() - 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 Double = 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 Double = 0 - Dim IEPS As Double = 0 - Dim RetISR As Double = 0 - Dim RetIVA As Double = 0 - Dim PorcentajeIVA As Double = 0 - Dim PorcentajeIEPS As Double = 0 - Dim PorcentajeRetISR As Double = 0 - Dim PorcentajeRetIVA As Double = 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 - - ''AGREGA EN TABLA TEMPORAL - 'Dim DtPSTemp = TmpDT.Clone - 'Dim Row As DataRow = Nothing - - Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) - Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" - Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) - - 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 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").ToDouble <= 0 And ValorXML(node, "importe").ToDouble > 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.ToDouble - - '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("�", "") - 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 - - - If Version = "3.3" 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() - Exit For - 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").ToDouble, 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 -#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},
", 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},
", 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------------------ - Dim EstatusCredito As Integer = 0 - 'Credito Multiple - 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 - - '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 = "True" 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 SerieNueva As String = GlobalDTProveedorSucursales(CveProveedor).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 - - '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%
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 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 - - 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 - - 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.
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: {Dr("Clasificacion").ToString}.", 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: {Dr("Clasificacion").ToString}.", 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: {Dr("Clasificacion").ToString}.", 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 - - '------------------TERMINA VALIDACIONES------------------ - - '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 - 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() - - 'si hay necesidad de actualizar el globaldtps - If RegeneraPS Then - Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDT) - Hilo.Start() - 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 - - 'VALIDA IMPORTES - If Not ValidaTotalesGuardar() Then - Exit Sub - End If - - - 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 = 1.16 - Dim ListaMovimientosAlmacen As New List(Of Integer) - - 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) - - 'TIPO CAMBIO MANUAL CON COMPRA NUEVA - Dim TipoCambioGuardar = 1.0 - If DdlMoneda.SelectedValue.ToEntero > 1 Then - TipoCambioGuardar = If(DivTC.Visible, TxtTC.Text.ToDouble, LblTC.Text.Substring(3).ToDouble) - End If - TipoCambio = If(DivTC.Visible, TipoCambioGuardar, TipoCambio) - - Try - Dim FolioFijo As Integer = 0 - 'cheque - If DdlTipoTransaccion.SelectedValue = "1" 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)) - - 'seria de contado, solo cuando no tenga vinculado ningun anticipo - If RBLPago.SelectedValue.ToEntero = 2 AndAlso ArrAnticipos.Count = 0 Then 'Contado - - If RBLContado.SelectedValue = "1" Then - '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, TxtDocumentoImporte.Text.Trim.ToDouble, DdlMoneda.SelectedValue.ToEntero, 0.0, TxtDocumentoObservaciones.Text.Trim, "", True, True, -1, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCuentaTarjeta:=If(DivTarjeta.Visible, DdlTarjeta.SelectedValue.ToEntero, -1)) - ElseIf RBLContado.SelectedValue = "6" Then - '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, TxtDocumentoImporteCaja.Text.Trim.ToDouble, DdlMoneda.SelectedValue.ToEntero, 0.0, 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.CveEmpresa.Contiene(1, 119) And 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 AndAlso TxtTotal.Text.ToDecimal = 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 And Not (CveImportacion > 0 Or CveFlete > 0) Then - CveConceptoContableAlmacen = DdlOCVinculaInv.SelectedValue.ToEntero - End If - Else - CveConceptoContableAlmacen = 225 - End If - End If - End If - - - If RBLPago.SelectedValue.ToEntero = 4 And EstatusCredito.Contiene(1, 101) Then - CveEstatusFactura = 6 - End If - - '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) 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 - ErrorMovDev = guardardevolucion(ObjInventario, ObjCompras.CveCompra, TxtSubTotal.Text.ToDouble, TxtFecha.Text.Trim.ToDate) - End If - Dim ErrorDetalles As Boolean = False - ' Dim IDPoliza As Integer - Dim IDPolizaComprometido = 0 - Dim ErrorComprometido = False - - If CveImportacion > 0 Or CveFlete > 0 Then - - - Select Case CveConceptoContableAlmacen - Case 237 - Select Case FleteImportacionOpcion - Case 1 - Dim Dr As DataRow = Nothing - If ObjInventario.GetFletes(UsuarioActual.CveEmpresa, CveFlete) Then - If ObjInventario.DtResultados.Rows.Count > 0 Then - Dr = ObjInventario.DtResultados.Rows(0) - End If - End If - If Dr IsNot Nothing Then - If Not ObjInventario.UpdateFlete(CveFlete, Dr("Descripcion").ToString, Dr("Fecha").ToString.ToDate, -1, CveCompra, UsuarioActual.CveUsuario) Then - ErrorOC = True - End If - Else - 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) 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) Then - ErrorOC = True - End If - End Select - End Select - End If - - - If UsuarioActual.Empresa.UsaAC 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 - - ''[IPP] COMENTADO A MIRAS DE ELIMINAR 21-FEBRERO-2018 - ''VERIFICA SI TIENE DESCUENTO (AMORTIZACION) - 'If TxtDescuento.Text.ToDouble > 0 Then - ' DescuentoConIVA = TxtDescuento.Text.ToDecimal * 1.16D - - ' 'Valida que el descuento con iva cuadre en los totales - ' If Math.Abs(DescuentoConIVA - (Importe - TxtTotal.Text.ToDecimal)) < 0.02 Then - ' DescuentoConIVA = Importe - TxtTotal.Text.ToDecimal - ' ElseIf DescuentoConIVA <> (Importe - TxtTotal.Text.ToDecimal) Then - ' ErrorACMEnsaje.Append(" - Valida que el descuento con iva cuadre en los totales ") - ' ErrorAC = True - ' End If - - ' 'actualizo el idcuenta del presupuesto - ' If ObjContaAC.AddMovimiento(IdPoliza, tIdContaProveedor, 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 - ' ErrorACMEnsaje.Append(" - actualizo el idcuenta del presupuesto ObjContaAC.AddMovimiento 1") - ' ErrorAC = True - ' End If - ' Else - ' ErrorACMEnsaje.Append(" - actualizo el idcuenta del presupuesto ObjContaAC.AddMovimiento 2") - ' ErrorAC = True - ' End If - 'Else - '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 Then - - ''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.ToDouble, Row("PU").ToString.ToDouble, Row("IVA").ToString.ToDouble, Row("Total").ToString.ToDouble, Row("Descuento").ToString.ToDouble, - 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.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 = "True" AndAlso EsNoDeducible, True, False)) 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" Then - If Not ObjProductosServicios.UpdateProductosServiciosSAT(Row("CvePS").ToString().ToEntero(), Row("CveSATPS").ToString().ToEntero(), UsuarioActual.CveUsuario) Then - ErrorSATPS = True - 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.ToDouble) 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) 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 = 0.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 salida de consignacion - 'folio = objinventario.getfoliosiguiente(3, usuarioactual.cveempresa) - 'cvemovimientosalida = objinventario.addmovimiento(cvealmacenconsignacion, 3, ddlmoneda.selectedvalue.toentero, fecha, folio, usuarioactual.cveusuario, usuarioactual.cveempresa, cvecompra, -1, -1, -1) - 'if cvemovimientosalida <= 0 then - ' errormovinv = true - ' exit for - 'else - ' for each dr as datarow in dtinv.rows - ' if dr("cvealmacen").tostring.toentero = tcvealmacen then - ' if not objinventario.addmovimientodetalle(cvemovimientosalida, dr("cantidad").tostring.todouble, ddlum.selectedvalue.toentero, dr("cveps").tostring.toentero, 0, -1) then - ' errormovinv = true - ' exit for - - ' end if - ' end if - ' next - 'end if - - - '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)) - 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 - - importeconcepto = If(DdlMoneda.SelectedValue.ToEntero = 1, dr("pu").ToString.ToDouble, dr("pu").ToString.ToDouble * TipoCambioGuardar) - 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.ToDouble), CveCompraDetalle:=dr("CveCompraDetalle").ToString.ToEntero) Then - - ErrorMovInv = True - Exit For - End If - End If - Next - - End If - - 'agregamos la salida gasto - 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) - 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 = 0.0 - - 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)) - - If CveMovimientoInventario <= 0 Then - ErrorMovInv = True - Else - - Dim DtDetalle As New DataTable - Dim DtEquivalencias As DataTable - Dim CveProducto As Integer - Dim CantidadInv As Double - Dim PUInv As Double - Dim CveUnidad As Integer - Dim CostoIndirecto As Double - - 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.ToDouble - PUInv = Dr("PU").ToString.ToDouble - CostoIndirecto = Dr("CostoIndirectoAlmacen").ToString.ToDouble - - 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.ToDouble, -1, SerieLote:=drr("Serie").ToString, FechaCaducidad:=drr("FechaCaducidad").ToString.ToDate, CostoIndirecto:=Dr("CostoIndirectoAlmacen").ToString.ToDouble, 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) - 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.ToDouble * drUMBase("Cantidad").ToString.ToDouble / DtEquivalencias.FiltraParametros(String.Format("CveUM = {0}", CveUnidad)).Rows(0)("Cantidad").ToString.ToDouble - PUInv = PUInv * Dr("Cantidad").ToString.ToDouble / CantidadInv - CostoIndirecto = CostoIndirecto * Dr("Cantidad").ToString.ToDouble / CantidadInv - CveUnidad = CveUnidadBase - End If - End If - - 'si no es por serie lote - ImporteConcepto = If(DdlMoneda.SelectedValue.ToEntero = 1, PUInv, PUInv * 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.ToDouble), 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 - - - - If AplicarCostoIndirecto(ObjInventario, ObjCompras) Then - ErrorMovInv = True - End If - - 'Else - ' Alert("El tipo de cambio no esta actualizado. Por favor comuniquese con un asistente SIG.", TipoMensaje.MsgError) - ' 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 CveConceptoAfectacionContado As Integer = 17 'Pago Proveedores - 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 CveAcreedor As Integer - Dim CveColectiva As Integer = -1 - - 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 - CveAcreedor = -1 - - Else - 'cuando es contado - - Select Case RBLContado.SelectedValue - Case "1", "6" 'Proveedores - CveProveedorLocal = CveProveedor - CveProveedorConcepto = CveProveedor - CveAcreedor = -1 - Case "2" ' F y E - CveProveedorLocal = CveProveedor - CveProveedorConcepto = CveProveedor - CveAcreedor = -1 - CveIE = DDlCheques.SelectedValue.ToEntero - Case "3" ' Doctos - - CveProveedorConcepto = CveProveedor - - If DdlTipoCredito.SelectedValue.ToEntero = 2 Then - CveProveedorLocal = CveProveedor - CveProveedorConcepto = CveProveedor - CveAcreedor = -1 - CveColectiva = -1 - ' CveConceptoAfectacionContado = 55 - 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 - CveAcreedor = -1 - CveColectiva = -1 - ' CveConceptoAfectacionContado = 55 - CveConceptoAfectacion = 37 - Case "5" ' Acreedores - CveProveedorLocal = CveProveedor - CveProveedorConcepto = DdlAcreedor.SelectedValue.ToEntero - CveAcreedor = -1 - CveColectiva = -1 - 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 ImporteCapital As Decimal = 0 - ' Dim ImporteCapitalIVA As Decimal = 0 - - 'Dim ImporteInteres As Decimal = 0 - ' Dim ImporteInteresIVA As Decimal = 0 - - ' 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 - 'ObjIE.UpdateCreditosDetalle(CveCreditoDetalle, "01/01/2000".ToDate, -1, -1, -1, -1, -1, -1, Estatus) - - - - 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 tipoCambioPago As Decimal - Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

" - 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 CuentasContablesInvalidasSIG 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 - - Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" - - If UsuarioActual.CveEmpresa = 119 AndAlso (DdlPersonalReembolso.SelectedValue.ToEntero > 0 Or DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero > 0) Then - AutoConta = False - End If - - If (AutoConta Or UsuarioActual.Empresa.UsaAC) And ObjContaAC Is Nothing Then - ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa) - ObjContaAC.IniciaTransacSQL() - 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 - If CveIE > 0 AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "4" Then - ConceptoPersonal = DdlDeudor.SelectedItem.ToString - importeDD = TxtContadoDeudor.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 - - - - '****** X Acreditar - 'IVA X Acreditar (14) - Dim importeIVAxAcreditar As Decimal = 0 - importeIVAxAcreditar = TxtIVA.Text.ToDecimal - - 'IEPS X Acreditar (25) - Dim ImporteIEPSxAcreditar As Decimal = 0 - ImporteIEPSxAcreditar = TxtIEPS.Text.ToDecimal - - 'Otros Impuestos (224) - Dim OtrosImpuestos As Decimal = 0 - OtrosImpuestos = TxtOtrosImpuestos.Text.ToDecimal - - 'RetIVA X Acreditar (15) - Dim importeRetIVAxAcreditar As Decimal = 0 - importeRetIVAxAcreditar = TxtRetIVA.Text.ToDecimal - - 'RetISR X Acreditar (16) - Dim importeRetISRxAcreditar As Decimal = 0 - importeRetISRxAcreditar = TxtRetISR.Text.ToDecimal - - - - '****** Movimientos Independientes - - 'Pago Proveedores (17) - Dim importePagoProv As Decimal = 0 - importePagoProv = sumaPagos - - 'If CveIE > 0 AndAlso ((RBLContado.SelectedValue = "2" AndAlso DdlFuncionarioEmpleado.SelectedValue.ToEntero > 0) Or (RBLContado.SelectedValue = "4" AndAlso DdlDeudor.SelectedValue.ToEntero > 0)) Then - ' importePagoProv = TxtDocumentoImporteFE.Text.ToDecimal - 'End If - - 'Compra (6) - 'Ya que es un foreach todo su proceso esta en el Case 6 - - '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 - - '************************************************************************************************************************** - - If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then - tipoCambioActual = GlobalTipoCambio(FechaMovimiento).ToString.ToDecimal - tipoCambioActual = If(DivTC.Visible, TipoCambio.ToDecimal, tipoCambioActual) - tipoCambioPago = GlobalTipoCambio(TxtFechaPago.Text.ToDate).ToString.ToDecimal - Else - tipoCambioActual = 1 - tipoCambioPago = 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 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 CveCuenta 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 = If(Row("Multiplicador").ToString.ToEntero = 1, 1, -1) - Dim Referencia As String = $"{TxtSerie.Text}-{TxtFolio.Text}" ' concatenation interpolation - Dim PorcentajeImpuesto As Decimal = 0 - - - Select Case ConceptoContable - - - - - Case 17 'Pago Proveedores - - importeMovimiento = importePagoProv - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - IdCtaContable = CtaProveedor - CveCuenta = CveCuentaProveedor - - - If RBLPago.SelectedValue.ToEntero = 4 And EstatusCredito.Contiene(2, 102) Then 'SI ES CRÉDITO Y ESTA PAGADO - - Dim IdSegmentoNegocio As Integer = -1 - 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}", Row2("CveClasificacion").ToString.ToEntero, Row2("CveSubProyecto").ToString.ToEntero, Row2("CveTipoGasto").ToString.ToEntero)).ToString.ToDecimal - 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero - Else - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero - End If - End If - End If - - - - - 'SEGMENTO DE NEGOCIO - - Dim drT As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero).FiltroPrimero(String.Format("CveSubProyecto = {0} ", Row2("CveSubProyecto").ToString.ToEntero)) - If drT IsNot Nothing Then - IdSegmentoNegocio = drT("IdSegNeg").ToString.ToEntero - End If - - 'AGREGA MOVIMIENTO - If importeMovimiento <> 0 Then - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - 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, Referencia, 6, Concepto, FechaMovimiento, IdCtaContable, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=ImporteSubCreMN, ImporteME:=If(tipoCambioActual = 1, 0, ImporteSubCre), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, Referencia, 41, Concepto, FechaMovimiento, CtaProveedorAcreedores, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - 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, Referencia, 41, Concepto, FechaMovimiento, CtaProveedorAcreedores, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=importeMNIn, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoIn), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoIn, Referencia, 50, Concepto, FechaMovimiento, ViewState("IdCtaContDocsXPagar").ToString.ToEntero(), IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=importeMNIn, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoIn), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - - End If - End If - - - - - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - - If tipoCambioActual = 1 Then - IdCtaContable = CtaProveedor - CveCuenta = CveCuentaProveedor - Else - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0) Then 'Cuando tiene complementaria lo dividimos en dos - importeMN = importeMovimiento - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, 0, Referencia, 201, Concepto, FechaMovimiento, IdCtaContable, -1, CveIE, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * tipoCambioActual - importeMovimiento, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - End If - - Case 30 'Bancos - importeMovimiento = importeBanco + importeCajaChica 'Uno de los dos debe ser 0 - importeMN = importeMovimiento * tipoCambioPago * Multiplicador - IdCtaContable = IdCuentaBancaria - CveCuenta = CveCuentaBancaria - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - '' falta complementaria - - Case 19 'IVA Acreditable - If UsuarioActual.Empresa.Funcionalidad(521) = "1" Then - If importePagoProv = importeProv Then - importeMovimiento = TxtIVA.Text.ToDecimal - Else - importeMovimiento = 0 - End If - Else - importeMovimiento = importeIVAAcreditable - End If - - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - - PorcentajeImpuesto = PorcentajeIVA - IdCtaContable = If(IdCtaIVAAcreditable > 0, IdCtaIVAAcreditable, 0) - - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) And Not IdCtaContable > 0 Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditableSIG").ToString.ToEntero - End If - End If - - 'Agregamos el Opuesto del 19 -> 14 - If importeMovimiento <> 0 Then - Dim IdCtaIva As Integer = 0 - Dim CveCuentaIVA As Integer = 0 - IdCtaIva = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) - - If ObjConta.GetRetCuenta(14, UsuarioActual.CveEmpresa) And Not IdCtaIva > 0 Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaIva = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditar").ToString.ToEntero - CveCuentaIVA = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero - End If - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 14, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaIva, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVA, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - Case 14 'IVA X Acreditar - importeMovimiento = importeIVAxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - PorcentajeImpuesto = PorcentajeIVA - IdCtaContable = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) - If 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero - End If - End If - Case 25 'IEPS X Acreditar - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - importeMovimiento = ImporteIEPSxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditar").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditarSIG").ToString.ToEntero - End If - End If - End If - - Case 224 'Otros impuestos - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - importeMovimiento = OtrosImpuestos - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - IdCtaContable = If(UsuarioActual.CveEmpresa = 119, 1171, -1) - CveCuenta = -1 - End If - Case 26 'IEPS Acreditable - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - importeMovimiento = ImporteIEPSAcreditable - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSAcreditable").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSAcreditableSIG").ToString.ToEntero - End If - End If - - 'Agregamos el Opuesto del 26 -> 25 - If importeMovimiento <> 0 Then - Dim IdCtaIEPS As Integer = 0 - Dim CveCuentaIEPS As Integer = 0 - If ObjConta.GetRetCuenta(25, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaIEPS = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditar").ToString.ToEntero - CveCuentaIEPS = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditarSIG").ToString.ToEntero - End If - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 25, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaIEPS, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIEPS, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - - End If - Case 22 'RetIVA Acreditable Honorarios/Serv. Prof. - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then - importeMovimiento = importeRetIVAAcreditable - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(308).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(308).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - - 'Agregamos el Opuesto del 22 -> 15 - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 15, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - 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 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then - importeMovimiento = importeRetIVAxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(307).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(307).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - Case 184 'RetIVA Acreditable Fletes P.F - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then - importeMovimiento = importeRetIVAAcreditable - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(310).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(310).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - - 'Agregamos el Opuesto del 184 -> 183 - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 183, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - End If - End If - End If - Case 183 'RetIVA X Acreditar Fletes P.F - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then - importeMovimiento = importeRetIVAxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(309).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(309).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - Case 248 'RetIVA X Acreditar Arrendamiento - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 AndAlso DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then - importeMovimiento = importeRetIVAxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(313).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(313).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - - End If - End If - Case 186 'RetIVA Acreditable Fletes P.M. - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then - importeMovimiento = importeRetIVAAcreditable - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(312).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(312).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - - 'Agregamos el Opuesto del 186 -> 185 - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 185, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - End If - End If - End If - Case 185 'RetIVA X Acreditar Fletes P.M. - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then - importeMovimiento = importeRetIVAxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(311).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(311).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - Case 249 'RetIVA Acreditable Arrendamiento - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 AndAlso DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then - importeMovimiento = importeRetIVAAcreditable - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(314).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(314).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - End If - - End If - Case 23 'RetISR Acreditable - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then - importeMovimiento = importeRetISRAcreditable - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(316).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(316).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - - 'Agregamos el Opuesto del 23 -> 16 - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 15, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - 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 = 1 Then - importeMovimiento = importeRetISRxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(315).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(315).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - Case 243 'RetISR X Acreditar Terceros y Arrendamiento - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then - importeMovimiento = importeRetISRxAcreditar - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(317).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(317).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - End If - End If - Case 244 'RetISR Acreditable Terceros y Arrendamiento - If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then - If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then - importeMovimiento = importeRetISRAcreditable - importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(318).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(318).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - 'Agregamos el Opuesto del 244 -> 243 - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 243, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" - End If - End If - Case 64 'Ganancia - If tipoCambioActual <> 1 AndAlso TxtFechaPago.Text <> TxtFecha.Text Then - IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - If tipoCambioPago < tipoCambioActual Then - importeMovimiento = Math.Abs(tipoCambioPago - tipoCambioActual) * importePagoProv - importeMovimiento -= Math.Abs(tipoCambioPago - tipoCambioActual) * importeIVAAcreditable - importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetIVAAcreditable - importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetISRAcreditable - importeMN = importeMovimiento - End If - Else - importeMovimiento = 0 - End If - - Case 65 'Perdida - If tipoCambioActual <> 1 AndAlso TxtFechaPago.Text <> TxtFecha.Text Then - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - If tipoCambioActual < tipoCambioPago Then - importeMovimiento = Math.Abs(tipoCambioPago - tipoCambioActual) * importePagoProv - importeMovimiento -= Math.Abs(tipoCambioPago - tipoCambioActual) * importeIVAAcreditable - importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetIVAAcreditable - importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetISRAcreditable - importeMN = importeMovimiento - End If - Else - importeMovimiento = 0 - End If - - Case 6 'Compra - - If RBLPago.SelectedValue.ToEntero = 4 Then - Exit Select 'Es credito el concepto 6 se agrega en CASE 17 - End If - - If 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 ObjConta.GetRetCuenta(49, Row2("CveActivoFijo").ToString.ToEntero) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijo").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijoSIG").ToString.ToEntero - End If - End If - - If importeMovimiento <> 0 Then - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString) - CveCuentaContabilizacion = 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - Next - End If - - 'LIMPIA - importeMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 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 - 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 - 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(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 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero - End If - End If - If importeMovimiento <> 0 Then - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 68, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveMovimientoAlmacen:=CveMovimientoInventario, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - Next - End If - End If - - 'LIMPIA - importeMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 0 - - ''FLETES - 'If UsuarioActual.CveEmpresa.Contiene(119) And UsuarioActual.Empresa.UsaInventarios And DdlTipoComprobante.SelectedValue <> "NC" And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And CveConceptoContableAlmacen.Contiene(237, 240) Then - - 'End If - Dim CostoIndirectoAcum176 As Decimal = 0 - 'INV [MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA) ] - If UsuarioActual.CveEmpresa.Contiene(1, 119) And UsuarioActual.Empresa.UsaInventarios And Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And 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 - - Select Case ConceptoContabilizacion - Case 176 - ConceptoContabilizacionME = 228 - ConceptoContabilizacionMEComp = 229 - Case 205 - ConceptoContabilizacionME = 230 - ConceptoContabilizacionMEComp = 231 - 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 - - - '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 - 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}" - 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 - Dim TCAjuste As Decimal = ObjOC.DtResultados.FiltroPrimeroValor("TipoCambioAjuste").ToDecimal - 'RMF. falta verificar el costo indirecto de la OC - If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then - ImporteCI176 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteCI228").ToDecimal - CostoIndirectoAcum176 += ImporteCI176 - '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, CveCuenta:=CveCuenta, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, TipoCambio:=TCAjuste, Contabilizable:=SeContabiliza) Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, Importe229, Referencia, ConceptoContabilizacionMEComp, Concepto, FechaMovimiento, IdCtaContableMEComp, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=ImporteMN229, ImporteME:=ImporteME229, CveCuenta:=CveCuenta, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, TipoCambio:=TCAjuste, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - Else - ErrorPrepoliza = True - Exit For - End If - Else - CostoIndirectoAcum176 += ImporteCI176 - '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, CveCuenta:=CveCuenta, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, 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 - 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 - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {CveClasificacionCostoOC}").ToString.ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"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, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - End If - Case 205, 237, 240 - 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), CveCuenta:=CveCuenta, 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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - Else - ErrorPrepoliza = True - End If - Else - - 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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - End Select - 'End If - - End If - - - 'NC CON PRODUCTOS - CUENTA PUENTE - If UsuarioActual.CveEmpresa.Contiene(119) AndAlso UsuarioActual.Empresa.UsaInventarios AndAlso DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") AndAlso Not UsuarioActual.Empresa.Funcionalidad(126) = "1" 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 ISNULL(CveTipoPS,0) = 2").ToString.ToDecimal - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - - Dim ConceptoContabilizacionNC = 225 - - If 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 Then - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContabilizacionNC, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - - End If - - Dim ContienePSNeteoBonif As Boolean = False - For Each Dr As DataRow In TmpDT.Rows - If Dr("CveClasificacion").ToString.ToEntero.Contiene(20319) 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 ").ToString.ToDecimal - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - If importeMovimiento <> 0 Then - Dim IdCtaContableDescCompra As Integer = UsuarioActual.Empresa.Funcionalidad(405).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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) 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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - Else - ErrorPrepoliza = True - End If - End If - End If - - End If - - - - If 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 - 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 - DT.AcceptChanges() - DtAlmacenes.Dispose() - - 'QUITA 1-[MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA)] 2-[NC CON PRODUCTOS] - If UsuarioActual.CveEmpresa.Contiene(1, 119) And UsuarioActual.Empresa.UsaInventarios And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" Then - DT = DT.FiltraParametros("ISNULL(CveTipoPS,0) <> 2") - End If - - Dim DTDistinct = DT.Copy - If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then - DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF, 0) <> 2", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"}) - Else - DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And ISNULL(AplicaCostoIndirecto,0) <> 1", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "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 Then - DTDistinct.Clear() - 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(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 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero - Else - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero - End If - End If - End If - - 'SEGMENTO DE NEGOCIO - Dim IdSegmentoNegocio As Integer = -1 - Dim drT As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero).FiltroPrimero(String.Format("CveSubProyecto = {0} ", Row2("CveSubProyecto").ToString.ToEntero)) - If drT IsNot Nothing Then - IdSegmentoNegocio = drT("IdSegNeg").ToString.ToEntero - End If - - 'AGREGA MOVIMIENTO - If importeMovimiento.RoundSQL <> 0 Then - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - 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 - - Dim usacomplementariaProveedor As Boolean = False - usacomplementariaProveedor = If(tipoCambioActual > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), 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, TipoMovimiento, importeMovimiento, Referencia, 266, Concepto, FechaMovimiento, tidctacon, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, 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 ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, tcvecon, Concepto, FechaMovimiento, tidctacon, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveTipoGasto:=Row2("CveTipoGasto").ToString.ToEntero, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - - - - - End If - - Next - End If - End If - - - 'LIMPIA - importeMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 0 - End If - Case 5 'Proveedores - If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then - - importeMovimiento = importeProv - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - - If tipoCambioActual = 1 Then - IdCtaContable = CtaProveedor - CveCuenta = CveCuentaProveedor - Else - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsuarioActual.CveEmpresa = 119) Then 'Cuando tiene complementaria lo dividimos en dos Then - importeMN = importeMovimiento - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, 0, Referencia, 201, Concepto, FechaMovimiento, IdCtaContable, -1, CveIE, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * tipoCambioActual - importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - End If - End If - - Case 59 'Documentos - importeMovimiento = importeCreditos - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - If 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero - End If - End If - End If - - Case 37 'Deudores - 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 - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - IdCtaContable = CtaProveedorDeudores - CveCuenta = CveCuentaProveedorDeudores - - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - Next - Else - For Each rw As GridViewRow In GvDeudores.Rows - If rw.FCCheckBox("Chk").Checked Then - importeMovimiento = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - IdCtaContable = CtaProveedorDeudores - CveCuenta = CveCuentaProveedorDeudores - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 254, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - Next - End If - - importeMovimiento = 0 - - Case 41 'Acreedores - importeMovimiento = importeAcreedores - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - - IdCtaContable = CtaProveedorAcreedores - CveCuenta = CveCuentaProveedorAcreedores - - Case 42 'Acreedores - importeMovimiento = importeAcreedoresTarjeta - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - IdCtaContable = CtaProveedorAcreedores - CveCuenta = CveCuentaProveedorAcreedores - - Case 18 'NC - Notas de Credito - importeMovimiento = importeNC - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" - IdCtaContable = CtaProveedor - CveCuenta = CveCuentaProveedor - If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - End If - - If importeMovimiento <> 0 Then - GuardoConcepto18 = True - If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then - - 'PROVISION - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMN - importeMovimiento, Referencia, 234, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN - importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) 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 importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador - Dim TipoCambioNC = Gvr.DataKey("TipoCambio").ToDecimal - - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, False, importeMovimientoNC, Referencia, 17, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, False, importeMNNC - importeMovimientoNC, Referencia, 206, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - Else - ErrorPrepoliza = True - Exit For - End If - - - importeMNNC = importeMovimientoNC * TipoCambioNC * Multiplicador - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, True, importeMNNC - importeMovimientoNC, Referencia, 235, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, 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 - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - ElseIf importeMovimiento < 0 Then - ConceptoContable = 65 - TipoMovimiento = False - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - End If - - importeMovimiento = importeMovimiento.Abs.RoundSQL() - importeMN = importeMovimiento - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - End If - End If - - - ObjConta.PrePolizaUnificacion(CvePrePoliza, CvePrePolizaTemp) - End If - Next - - If ErrorPrepoliza Then - Exit Select - End If - - Else - IdCtaContable = CtaProveedor - CveCuenta = CveCuentaProveedor - - If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, 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(CvePrePolizaTemp, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoNC), CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoNC), CveCuenta:=CveCuenta, 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 ObjConta.GetRetCuenta(ConceptoContable, CvePersonal) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContPersonal").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContPersonalSIG").ToString.ToEntero - End If - End If - - Case 21 'Anticipo - - If ArrAnticipos.Count > 0 Then - - - Dim CtaIvaxAcreditar As Integer = 0 - Dim CtaIvaAcreditable As Integer = 0 - Dim CveCuentaIvaxAcreditar As Integer = 0 - Dim PorcentajeImpuestoAnticipo = PorcentajeIVA - CtaIvaxAcreditar = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) - CtaIvaAcreditable = If(IdCtaIVAAcreditable > 0, IdCtaIVAAcreditable, 0) - If ObjConta.GetRetCuenta(14, UsuarioActual.CveEmpresa) And Not CtaIvaxAcreditar > 0 Then - If ObjConta.DtResultados.Rows.Count > 0 Then - CtaIvaxAcreditar = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditar").ToString.ToEntero - CveCuentaIvaxAcreditar = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero - End If - End If - If ObjConta.GetRetCuenta(19, UsuarioActual.CveEmpresa) And Not CtaIvaAcreditable > 0 Then - If ObjConta.DtResultados.Rows.Count > 0 Then - CtaIvaAcreditable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero - End If - End If - - '** PRUEBA CUANDO SE AMORTIZA NC ANTES DE QUE SE REGISTRE NO DEBE TENER CONCEPTO 19 ** JMURUAM 01/06/2017 SE HIZO ESTO PARA LA FACTURA HRFA-8012831 DE VIGILANCIA - 'Dim CtaIvaAcreditable As Integer = 0 - 'If ObjConta.GetRetCuenta(19, UsuarioActual.CveEmpresa) Then - ' If ObjConta.DtResultados.Rows.Count > 0 Then - ' CtaIvaAcreditable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero - ' End If - 'End If - - For Each Ant As Anticipos In ArrAnticipos - - 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 - CveCuenta = CveCuentaProveedor - Case "Egsc" - ConceptoContableAnticipo = 21 - IdCtaContable = CtaProveedorAnticipos - CveCuenta = CveCuentaProveedorAnticipos - - Case "DD" - ConceptoContableAnticipo = 37 - IdCtaContable = CtaProveedorDeudores - CveCuenta = CveCuentaProveedorDeudores - Case "Ant" - ConceptoContableAnticipo = 265 - ConceptoContableAnticipoComplementaria = 266 - CveCompraNC = Ant.CveCompra - IdCtaContable = CtaProveedorAnticipos - CveCuenta = CveCuentaProveedorAnticipos - End Select - - importeMovimiento = Ant.Importe - importeMN = importeMovimiento * tipoCambioActual * Multiplicador - - If importeMovimiento <> 0 Then - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidas.Append("
" & 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 And UsuarioActual.CveEmpresa.Contiene(119) Then - Dim importeMovimientoNC = Ant.Importe - Dim importeMNNC = 0.0D - Dim TipoCambioNC = Ant.TCCompra - - importeMNNC = importeMovimientoNC * TipoCambioNC * Multiplicador - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMNNC - importeMovimientoNC, Referencia, 235, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - Else - ErrorPrepoliza = True - Exit For - End If - - importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMNNC - importeMovimientoNC, Referencia, 206, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, 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 - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - ElseIf importeMovimiento < 0 Then - ConceptoContable = 65 - TipoMovimiento = False - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - 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, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - End If - End If - - ElseIf ConceptoContableAnticipo.Contiene(265) And DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then - Dim importeMovimientoNC = Ant.Importe - Dim importeMNNC = 0.0D - Dim TipoCambioNC = Ant.TCCompra - - importeMNNC = importeMovimientoNC * TipoCambioNC * Multiplicador - IdCtaContable = CtaProveedorAnticiposExtranjera - CveCuenta = CveCuentaProveedorAnticiposExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoNC, Referencia, 265, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - IdCtaContable = CtaProveedorAnticiposComplementaria - CveCuenta = CveCuentaProveedorAnticiposComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMNNC - importeMovimientoNC, Referencia, 266, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - Else - ErrorPrepoliza = True - Exit For - End If - - If TxtTotal.Text.ToDouble > 0 Then - importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador - IdCtaContable = CtaProveedorExtranjera ' CtaProveedorAnticiposExtranjera - CveCuenta = CveCuentaProveedorExtranjera 'CveCuentaProveedorAnticiposExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, CveCompraAmortizacion:=CveCompraNC, Contabilizable:=SeContabiliza) Then - IdCtaContable = CtaProveedorExtranjera 'CtaProveedorAnticiposComplementaria - CveCuenta = CveCuentaProveedorExtranjera 'CveCuentaProveedorAnticiposComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMNNC - importeMovimientoNC, Referencia, 206, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - Else - ErrorPrepoliza = True - Exit For - End If - - If Ant.TipoMovto.Contiene("Ant") Then - Dim PorcentajePagoAnt As Decimal = importeMovimientoNC / If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDecimal) - Dim ImporteIVA As Decimal = Math.Round(PorcentajePagoAnt * TxtIVA.Text.ToDecimal, 2) - - 'Agregamos el 14 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteIVA, Referencia, 14, Concepto, FechaMovimiento, CtaIvaxAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), CveCuenta:=CveCuentaIvaxAcreditar, PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - 'Agregamos el 19 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, ImporteIVA, Referencia, 19, Concepto, FechaMovimiento, CtaIvaAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - Dim ImporteIEPS As Decimal = Math.Round(PorcentajePagoAnt * TxtIEPS.Text.ToDecimal, 2) - - 'Agregamos el 25 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteIEPS, Referencia, 25, Concepto, FechaMovimiento, CtaIvaxAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), CveCuenta:=CveCuentaIvaxAcreditar, PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - 'Agregamos el 26 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, ImporteIEPS, Referencia, 26, Concepto, FechaMovimiento, CtaIvaAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - 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 - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - ElseIf importeMovimiento < 0 Then - ConceptoContable = 65 - TipoMovimiento = False - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - 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, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - End If - End If - End If - - Else - - - Dim usacomplementariaAnticipo As Boolean = False - usacomplementariaAnticipo = If(Ant.TCCompra > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), True, False) - Dim TipoCambioAnt = Ant.TCCompra - - - Dim ImporteAnt As Decimal = importeMovimiento - Dim ImporteAntMN As Decimal = ImporteAnt * TipoCambioAnt - If usacomplementariaAnticipo Then - IdCtaContable = CtaProveedorAnticiposComplementaria - CveCuenta = CveCuentaProveedorAnticiposComplementaria - ImporteAntMN = TipoCambioAnt * ImporteAnt - ImporteAnt - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteAnt, Referencia, 266, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=ImporteAntMN, ImporteME:=ImporteAnt, TipoCambio:=TipoCambioAnt, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - ImporteAntMN = ImporteAnt - End If - - If TipoCambioAnt > 1 Then - IdCtaContable = CtaProveedorAnticiposExtranjera - CveCuenta = CveCuentaProveedorAnticiposExtranjera - End If - - 'Agregamos el 21/37/60 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteAnt, Referencia, ConceptoContableAnticipo, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteAntMN, ImporteME:=If(tipoCambioActual = 1, 0, ImporteAnt), TipoCambio:=TipoCambioAnt, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - If TxtTotal.Text.ToDouble > 0 Then - Dim IdCtaContablePago As Integer = CtaProveedor - Dim CveCuentaPago As Integer = CveCuentaProveedor - Dim usacomplementariaProveedor As Boolean = False - usacomplementariaProveedor = If(tipoCambioActual > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), True, False) - If usacomplementariaProveedor Then - Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}" - importeMN = tipoCambioActual * importeMovimiento - importeMovimiento - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 201, Concepto, FechaMovimiento, CtaProveedorComplementaria, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaProveedorComplementaria, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - importeMN = importeMovimiento - End If - - If tipoCambioActual > 1 Then - IdCtaContablePago = CtaProveedorExtranjera - CveCuentaPago = CveCuentaProveedorExtranjera - End If - - 'Agregamos el 17 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 17, Concepto, FechaMovimiento, IdCtaContablePago, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaPago, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - End If - ' FLUCTUACION CAMBIARIA - If tipoCambioActual <> TipoCambioAnt Then - Dim importeFluctuacion = (ImporteAnt * tipoCambioActual) - (ImporteAnt * TipoCambioAnt) - - If importeFluctuacion > 0 Then - ConceptoContable = 64 - TipoMovimiento = True - IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - ElseIf importeFluctuacion < 0 Then - ConceptoContable = 65 - TipoMovimiento = False - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - End If - - importeFluctuacion = importeFluctuacion.Abs.RoundSQL() - If importeFluctuacion <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeFluctuacion, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeFluctuacion, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - End If - 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 PorcentajePagoAnt As Decimal = importeMovimiento / If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDecimal) - Dim ImporteIVA As Decimal = Math.Round(PorcentajePagoAnt * TxtIVA.Text.ToDecimal, 2) - - 'Agregamos el 14 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteIVA, Referencia, 14, Concepto, FechaMovimiento, CtaIvaxAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), CveCuenta:=CveCuentaIvaxAcreditar, PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - - 'Agregamos el 19 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, ImporteIVA, Referencia, 19, Concepto, FechaMovimiento, CtaIvaAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - - End If - - ''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.PrePolizaSimplificacion(Ant.CvePrePoliza, UsuarioActual.CveEmpresa) Then - ' ErrorPrepoliza = True - ' Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) - ' End If - 'End If - - Next - importeMovimiento = 0 - - End If - End Select - - If ErrorPrepoliza Then - Exit For - End If - - If importeMovimiento <> 0 Or (ConceptoContable.Contiene(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("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'COnta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=Math.Round(importeMN, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - End If - - End If - - Next - - 'EMPIEZA REFACTURACION - If 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 UsuarioActual.Empresa.Funcionalidad(220) <> "" Then - If Not ObjConta.PrePolizaSimplificacion(CvePrePoliza, UsuarioActual.CveEmpresa) Then - ErrorPrepolizaDescuadre = True - End If - End If - - If 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.UsaContabilidad 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:
{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 - ' CveIE = ObjIE.AddBancos_IE(DdlCuenta.SelectedValue.ToEntero, DdlTipoTransaccion.SelectedValue.ToEntero, TxtFecha.Text.Trim.ToDate, TxtDocumentoFolio.Text.Trim, DdlProveedor.SelectedItem.Text.Trim, TxtDocumentoImporte.Text.Trim.ToDouble, 1, 0.0, TxtDocumentoObservaciones.Text.Trim, True, True, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - If CveIE > 0 Then - - 'inserto los movimientos de la conta para abonar al saldo - - 'Se agregamovimiento de pago de proveedor - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteCompra, " ", CveConceptoAfectacionContado, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then - ErrorMovtosCxP = True - End If - - 'Compra - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtSubTotal2.Text.ToDecimal, " ", 30, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then - ErrorMovtosCxP = True - End If - - 'IVA por Acreditar . siempre se registra aunque sea cero - If Not ErrorMovtosCxP Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal, " ", 19, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then - ErrorMovtosCxP = True - End If - End If - - If Not ErrorMovtosCxP AndAlso TxtRetIVA.Text.ToDouble > 0 Then - 'Agrego el RetIVA - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then - ErrorMovtosCxP = True - End If - End If - - If Not ErrorMovtosCxP AndAlso TxtRetISR.Text.ToDouble > 0 Then - 'Agrego el RetIVA - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva) Then - ErrorMovtosCxP = True - End If - 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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 Anticipos In ArrAnticipos - CveCompraNC = CveCompra - Dim CveConceptoPago As Integer = 17 - 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, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, 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 - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoCompra, Ant.Importe, " ", CveConceptoPago, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=Ant.Importe) Then - ErrorMovtosCxP = True - End If - PorcentajePago = (Ant.Importe) / TxtTotal.Text.ToDecimal - - 'IVA por Acreditar . siempre se registra aunque sea cero - If Not ErrorMovtosCxP Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", 19, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True - End If - - 'Agrego el RetIVA - If Not ErrorMovtosCxP AndAlso TxtRetIVA.Text.ToDouble > 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True - End If - - 'Agrego el RetISR - If Not ErrorMovtosCxP AndAlso TxtRetISR.Text.ToDouble > 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True - End If - 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 - 'Siempre: Se agrega IVA aunque sea cero - If TxtIVA.Text.ToDouble <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then - ErrorMovtosIVA = True - End If - End If - - 'Se agregan las Ret IVA - If TxtRetIVA.Text.ToDouble <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then - ErrorMovtosRetIVA = True - End If - End If - - 'Se agregan las Ret ISR - If TxtRetISR.Text.ToDouble > 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetISR, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then - ErrorMovtosRetISR = True - End If - End If - - 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 - - 'CvePrePoliza = ObjConta.AddPrePolizas("Banc", 2, ImporteAPagarFE, ImporteAPagarFE, DdlMoneda.SelectedValue.ToEntero, TxtFecha.Text.ToDate, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - If CvePrePoliza > 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImportePagar, " ", 29, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CvePersonal:=DdlFuncionarioEmpleado.SelectedValue.ToEntero, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveColectiva:=CveColectiva, CveIE:=CveIE, ImporteMX:=ImportePagar) Then - ErrorMovtosCxP = True - End If - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImportePagar, " ", 17, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CvePersonal:=DdlFuncionarioEmpleado.SelectedValue.ToEntero, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveColectiva:=CveColectiva, CveIE:=CveIE, ImporteMX:=ImportePagar) Then - ErrorMovtosCxP = True - End If - - - Dim PorcentajePago As Decimal = (ImportePagar) / TxtTotal.Text.ToDecimal - - 'IVA por Acreditar . siempre se registra aunque sea cero - If Not ErrorMovtosCxP Then - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", 19, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True - - End If - - If Not ErrorMovtosCxP AndAlso TxtRetIVA.Text.ToDouble > 0 Then - 'Agrego el RetIVA - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True - - End If - - If Not ErrorMovtosCxP AndAlso TxtRetISR.Text.ToDouble > 0 Then - 'Agrego el RetISR - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True - - End If - - - 'sino alcanzo a cubrir se regitran los ivas por acreditar - If TxtTotal.Text.ToDouble - ImportePagar > 0 Then - PorcentajePago = (TxtTotal.Text.ToDecimal - ImportePagar) / TxtTotal.Text.ToDecimal - 'Movimiento, se omite, porque se esta registrando la totalidad de la deuda - 'If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtTotal.Text.ToDouble - ImporteAnticipo, " ", 5, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then - ' ErrorMovtosCxP = True - 'End If - 'Siempre: Se agrega IVA aunque sea cero - If TxtIVA.Text.ToDouble <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then - ErrorMovtosIVA = True - End If - End If - - 'Se agregan las Ret IVA - If TxtRetIVA.Text.ToDouble <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then - ErrorMovtosRetIVA = True - End If - End If - - 'Se agregan las Ret ISR - If TxtRetISR.Text.ToDouble > 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetISR, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then - ErrorMovtosRetISR = True - End If - End If - - End If - - 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 - 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 - - - If tDTAcarreos.Rows.Count > 0 Then - If TotAcarreos = TxtSubTotal.Text.ToDouble Then - 'ACARREOS - For Each tDTAcar As DataRow In tDTAcarreos.Rows - If Not ObjAcar.UpdatePreEstimacion(CInt(tDTAcar("CvePreEstimacion")), CveCompra) Then - ErrorAddAcarreos = True - Exit For - End If - Next - Else - ErrorAddAcarreos = 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 - - 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, "", 17, "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.
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.
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.
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.
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.
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.
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.
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.
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 - ErrorOC = 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) 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 - ObjContaAC.AjustaPoliza(IdPoliza) - Msg.AppendFormat("

Ver Póliza", IdPoliza) - End If - - If CveMovimientoInventario > 0 Then - Dim TempParametros = Encripta(String.Format("OP=Alm&CveMovimiento={0}", CveMovimientoInventario)) - Msg.AppendFormat("
Ver Movimiento de Almacen", CveMovimientoInventario) - Msg.AppendFormat("
Imprimir Entrada Almacen", TempParametros) - End If - - ObjCompras.UpdateCompraPrePoliza(TxtFecha.Text.ToDate, PolizaFolio.ToString, IdPoliza, CvePrePoliza, CveCompra, 0) - - If EntregaDirecta Then - Msg.AppendFormat($"
Recibir mercancía de entrega directa.") - End If - - 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("

El proveedor tiene evaluaciones pendientes
") - Msg.Append("¿Desea realizar una evaluacion al proveedor?") - Msg.AppendFormat($"
Evaluar Proveedor.") - End If - - Alert(Msg.ToString, TipoMensaje.MsgInformacion, MsgAccionAceptar) - - 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.
Revise sus datos de pago y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia) - ObjCompras.RollBack() - End If - - - Catch ex As Exception - ObjCompras.RollBack() - If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack() - Alert("Ocurrió un error al registrar la compra y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgError) - GuardaLog($"Ocurrió un error al registrar la compra y 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 - - 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 ErrorCompra = False - - If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 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 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() - 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) - - '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 - - '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, CveCuenta As Integer - - Dim PorcentajePago, ImporteMovimiento, sumaAmortizacion, sumaAmortizacionCompleto As Decimal - Dim ConceptoPoliza As String = $"Amortización {NombreProveedor} - {TxtSerie.Text}-{TxtFolio.Text}" - Dim CompraUnificada As Boolean = False - Dim IVACompleto As Boolean = False - Dim IdCtaIVAXAcreditar As Integer = 0 - Dim IdCtaIVAAcreditable As Integer = 0 - 'PorcentajeIVA - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("IVAPorcentaje").ToDouble).Rows.Count > 0 Then - IdCtaIVAXAcreditar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("IVAPorcentaje").ToDouble).Rows(0)("IdCtaIVAXAcreditar").ToString.ToEntero - IdCtaIVAAcreditable = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("IVAPorcentaje").ToDouble).Rows(0)("IdCtaIVAAcreditable").ToString.ToEntero - End If - - Try - Dim CveIE As Integer = -1 - - If EmpresaPrueba Then - Dim CvePlantillaPoliza = 52 - Dim tipoCambio As Decimal - Dim tipoCambioNC As Decimal - Dim alertaContabilizacion As New StringBuilder - Dim idCuentaContabilizacion As Long = 1 - Dim CveCuentaContabilizacion As Long = 1 - Dim CvePrepolizaPadre As Integer = CvePrePoliza - Dim CuentasContablesInvalidas As New StringBuilder - Dim CuentasContablesInvalidasSIG As New StringBuilder - - If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then - tipoCambio = GlobalTipoCambio(Fecha).ToString.ToDecimal - Else - tipoCambio = 1 - End If - - '[IPP] PARCHE PARA AMORTIZACIÓN NC - Dim TipoCambioCompra = Me.TipoCambio.ToDecimal - - 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 - tipoCambioNC = gvr.DataKey("TCCompra").ToDecimal - sumaAmortizacion = 0 - - If CvePrePolizaNueva > 0 Then - If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPoliza) 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) - ImporteMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 0 - Dim Concepto As String = "" - Dim importeMN As Decimal = 0 - Dim Multiplicador As Integer = If(Row("Multiplicador").ToString.ToEntero = 1, 1, -1) - Dim PorcentajeImpuesto As Decimal = 0 - Dim ConceptoPartida As String = String.Format("{0}-{1}", TxtSerie.Text, TxtFolio.Text) - - - Select Case ConceptoContable - Case 265 'Amortización Anticipos Compras - If gvr.DataKey("TipoDocto").Contiene("Ant") Then - CveIE = -1 - ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal - importeMN = ImporteMovimiento * tipoCambioNC - sumaAmortizacion += ImporteMovimiento - sumaAmortizacionCompleto += ImporteMovimiento - - If DdlMoneda.SelectedValue.ToEntero <> 1 Then - IdCtaContable = CtaProveedorAnticiposExtranjera - CveCuenta = CveCuentaProveedorAnticiposExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, "", ConceptoContable, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then - If UsuarioActual.CveEmpresa.Contiene(119) Then - IdCtaContable = CtaProveedorAnticiposComplementaria - CveCuenta = CveCuentaProveedorAnticiposComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeMN - ImporteMovimiento, "", 266, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN - ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - Exit Select - End If - End If - Else - ErrorMovtosCxP = 1 - Exit Select - End If - Else - IdCtaContable = CtaProveedorAnticipos - CveCuenta = CveCuentaProveedorAnticipos - If ImporteMovimiento <> 0 Then - PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, "", ConceptoContable, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - End If - End If - End If - End If - - ImporteMovimiento = 0 - Case 60 'Nota de Credito - If gvr.DataKey("TipoDocto").Contiene("NC", "DEV") Then - CveIE = -1 - ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal - importeMN = ImporteMovimiento * tipoCambioNC - sumaAmortizacion += ImporteMovimiento - sumaAmortizacionCompleto += ImporteMovimiento - - If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, ConceptoPartida, ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeMN - ImporteMovimiento, ConceptoPartida, 235, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN - ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - Exit Select - End If - Else - ErrorMovtosCxP = 1 - Exit Select - End If - Else - IdCtaContable = CtaProveedor - CveCuenta = CveCuentaProveedor - If ImporteMovimiento <> 0 Then - PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, ConceptoPartida, ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - End If - End If - End If - End If - - ImporteMovimiento = 0 - Case 21 'Anticipo - If gvr.DataKey("TipoDocto") = "Egsc" Then - CveCompraNC = -1 - CveIE = gvr.DataKey("CveIE").ToEntero - ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal - sumaAmortizacion += ImporteMovimiento - sumaAmortizacionCompleto += ImporteMovimiento - IdCtaContable = CtaProveedorAnticipos - CveCuenta = CveCuentaProveedorAnticipos - If ImporteMovimiento <> 0 Then - PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal - - Dim TipoCambioAnt = gvr.DataKey("TCCompra").ToDecimal - Dim usacomplementariaAnticipo As Boolean = False - usacomplementariaAnticipo = If(TipoCambioAnt > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), True, False) - - - Dim ImporteAnt As Decimal = ImporteMovimiento - Dim ImporteAntMN As Decimal = ImporteAnt * TipoCambioAnt - If usacomplementariaAnticipo Then - IdCtaContable = CtaProveedorAnticiposComplementaria - CveCuenta = CveCuentaProveedorAnticiposComplementaria - ImporteAntMN = TipoCambioAnt * ImporteAnt - ImporteAnt - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteAnt, "", 266, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CvePersonal:=CvePersonal, ImporteMX:=ImporteAntMN, ImporteME:=ImporteAnt, TipoCambio:=TipoCambioAnt, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - End If - ImporteAntMN = ImporteAnt - End If - - If TipoCambioAnt > 1 Then - IdCtaContable = CtaProveedorAnticiposExtranjera - CveCuenta = CveCuentaProveedorAnticiposExtranjera - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteAnt, "", ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteAntMN, CvePrePolizaOriginal:=CvePrePolizaNueva, ImporteME:=If(tipoCambio = 1, 0, ImporteAnt), CveCompraAmortizacion:=CveCompraNC, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - End If - - If tipoCambio <> TipoCambioAnt Then - Dim importeFluctuacion = (ImporteAnt * tipoCambio) - (ImporteAnt * TipoCambioAnt) - - If importeFluctuacion > 0 Then - ConceptoContable = 64 - TipoMovimiento = True - IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - ElseIf importeFluctuacion < 0 Then - ConceptoContable = 65 - TipoMovimiento = False - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - End If - - importeFluctuacion = importeFluctuacion.Abs.RoundSQL() - If importeFluctuacion <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeFluctuacion, "", ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeFluctuacion, CvePrePolizaOriginal:=CvePrePolizaNueva, ImporteME:=0, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - End If - End If - End If - - End If - End If - - ImporteMovimiento = 0 - - Case 37 'Deudores Diversos - If gvr.DataKey("TipoDocto") = "DD" Then - CveCompraNC = -1 - CveIE = gvr.DataKey("CveIE").ToEntero - ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal - sumaAmortizacion += ImporteMovimiento - sumaAmortizacionCompleto += ImporteMovimiento - IdCtaContable = CtaProveedorDeudores - CveCuenta = CveCuentaProveedorDeudores - - If ImporteMovimiento <> 0 Then - PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, "", ConceptoContable, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento * tipoCambio, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCompraAmortizacion:=CveCompraNC, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - End If - End If - End If - - ImporteMovimiento = 0 - - Case 17 'Pago Proveedores - Dim TipoCambio17 = tipoCambio - If gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant", "Egsc") Then - TipoCambio17 = TipoCambioCompra - End If - If gvr.DataKey("TipoDocto").Contiene("NC", "DEV") Then - ConceptoContable = 272 - End If - - ImporteMovimiento = sumaAmortizacion - importeMN = ImporteMovimiento * TipoCambio17 - - If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then - IdCtaContable = CtaProveedorExtranjera - CveCuenta = CveCuentaProveedorExtranjera - If ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=TipoCambio17, CveCuenta:=CveCuenta) Then - IdCtaContable = CtaProveedorComplementaria - CveCuenta = CveCuentaProveedorComplementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeMN - ImporteMovimiento, Concepto, 206, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN - ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=TipoCambio17, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - Exit Select - End If - Else - ErrorMovtosCxP = 1 - Exit Select - End If - Else - IdCtaContable = CtaProveedor - CveCuenta = CveCuentaProveedor - If ImporteMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(TipoCambio17 = 1, 0, ImporteMovimiento), CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - Exit For - End If - End If - End If - - ImporteMovimiento = 0 - Case 14 'Iva X Acreditar - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If UsuarioActual.Empresa.Funcionalidad(521) = "1" Then - If sumaAmortizacion = CompraSaldo Then - ImporteMovimiento = TxtIVA.Text.ToDecimal - IVACompleto = True - Else - ImporteMovimiento = 0 - End If - Else - ImporteMovimiento = Math.Round(PorcentajePago * TxtIVA.Text.ToDecimal, 2) - End If - importeMN = ImporteMovimiento * tipoCambio - PorcentajeImpuesto = TmpDT.MAX("IVAPorcentaje").ToDecimal - IdCtaContable = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) - If 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero - End If - End If - End If - Case 19 'Iva Acreditado - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If UsuarioActual.Empresa.Funcionalidad(521) = "1" Then - If sumaAmortizacion = CompraSaldo Then - ImporteMovimiento = TxtIVA.Text.ToDecimal - IVACompleto = True - Else - ImporteMovimiento = 0 - End If - Else - ImporteMovimiento = Math.Round(PorcentajePago * TxtIVA.Text.ToDecimal, 2) - End If - importeMN = ImporteMovimiento * tipoCambio - PorcentajeImpuesto = TmpDT.MAX("IVAPorcentaje").ToDecimal - IdCtaContable = If(IdCtaIVAAcreditable > 0, IdCtaIVAAcreditable, 0) - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) And Not IdCtaContable > 0 Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditableSIG").ToString.ToEntero - End If - End If - End If - Case 15 'RetIVA x Acreditar Honorarios/Serv. Prof. - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(307).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(307).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - Case 22 'RetIVA Acreditable Honorarios/Serv. Prof. - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(308).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(308).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - - Case 183 'RetIVA x Acreditar Fletes P.F. - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(309).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(309).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - - Case 184 'RetIVA Acreditable Fletes P.F. - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(310).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(310).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - - Case 185 'RetIVA x Acreditar Fletes P.M. - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(311).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(311).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - - Case 186 'RetIVA Acreditable Fletes P.M. - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(312).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(312).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - Case 248 'RetIVA x Acreditar Arrendamiento - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(313).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(313).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - - Case 249 'RetIVA Acreditable Arrendamiento - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetIVAConcepto.Items.Count > 0 Then - If DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetIVA > 0 Then - IdCtaContable = CtaProveedorRetIVA - CveCuenta = CveCuentaProveedorRetIVA - ElseIf UsuarioActual.Empresa.Funcionalidad(314).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(314).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - End If - Case 16 'RetISR x Acreditar - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(315).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(315).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - - Case 23 'RetISR Acreditable - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(316).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(316).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - Case 243 'RetISR X Acreditar Terceros y Arrendamiento - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(317).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(317).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - Case 244 'RetISR Acreditable Terceros y Arrendamiento - If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then - If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) - importeMN = ImporteMovimiento * tipoCambio - If CtaProveedorRetISR > 0 Then - IdCtaContable = CtaProveedorRetISR - CveCuenta = CveCuentaProveedorRetISR - ElseIf UsuarioActual.Empresa.Funcionalidad(318).ToEntero > 0 Then - IdCtaContable = UsuarioActual.Empresa.Funcionalidad(318).ToEntero - Else - If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - End If - Case 64 'GANANCIA - If gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then 'SOLO SE IMPLEMENTÓ PARA NC - If DdlMoneda.SelectedValue.ToEntero <> 1 Or gvr.DataKey("CveMoneda").ToEntero <> 1 Then - IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - If TipoCambioCompra > tipoCambioNC Then - ImporteMovimiento = (sumaAmortizacion * TipoCambioCompra) - (sumaAmortizacion * tipoCambioNC) - ImporteMovimiento = ImporteMovimiento.RoundSQL() - importeMN = ImporteMovimiento - End If - - If ImporteMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - Exit For - End If - End If - - End If - End If - ImporteMovimiento = 0 - Case 65 'PERDIDA - If gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then 'SOLO SE IMPLEMENTÓ PARA NC - If DdlMoneda.SelectedValue.ToEntero <> 1 Or gvr.DataKey("CveMoneda").ToEntero <> 1 Then - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - If tipoCambioNC > TipoCambioCompra Then - ImporteMovimiento = (sumaAmortizacion * tipoCambioNC) - (sumaAmortizacion * TipoCambioCompra) - ImporteMovimiento = ImporteMovimiento.RoundSQL() - importeMN = ImporteMovimiento - End If - - If ImporteMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta) Then - ErrorMovtosCxP = 1 - Exit For - End If - End If - - End If - End If - ImporteMovimiento = 0 - End Select - - If ImporteMovimiento <> 0 Then - 'Conta ContPAQ - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - 'Conta SIG - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then - ErrorMovtosCxP = 1 - Exit For - End If - - End If - Next - - End If - - End If - - '[IPP] COMENTADO PORQUE REUNIFICABA AMORTIZACIÓN NC 27/Agosto/2018 - 'If Not CompraUnificada Then - ' 'Unificacion de PrePolizas - ' If UsuarioActual.Empresa.Funcionalidad(219) = "1" Then - ' If Not ObjConta.PrePolizaUnificacion(gvr.DataKey("CvePrePoliza").ToEntero, CvePrepolizaPadre) Then - ' ErrorMovtosCxP = 1 - ' Alert("No se pudo unificar la prepoliza", TipoMensaje.MsgError) - ' End If - ' End If - 'End If - End If - Next - - 'Si el importe total de la amortizacion es igual al saldo de la compra se registra IVA - If IVACompleto = False AndAlso UsuarioActual.Empresa.Funcionalidad(521) = "1" Then - If sumaAmortizacionCompleto = CompraSaldo Then - Dim PorcentajeImpuesto As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, True, TxtIVA.Text.ToDecimal, "", 14, "", Fecha, IdCtaIVAXAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=TxtIVA.Text.ToDecimal * tipoCambio, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, TxtIVA.Text.ToDecimal), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then - ErrorMovtosCxP = 1 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, False, TxtIVA.Text.ToDecimal, "", 19, "", Fecha, IdCtaIVAAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=TxtIVA.Text.ToDecimal * tipoCambio, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, TxtIVA.Text.ToDecimal), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then - ErrorMovtosCxP = 1 - End If - End If - End If - - 'Unificacion de PrePolizas - If UsuarioActual.Empresa.Funcionalidad(219) = "1" Then - If Not ObjConta.PrePolizaUnificacion(CvePrepolizaPadre, CvePrePolizaNueva) Then - ErrorMovtosCxP = 1 - 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.PrePolizaSimplificacion(CvePrepolizaPadre, UsuarioActual.CveEmpresa) Then - ErrorMovtosCxP = 1 - Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) - End If - End If - - 'Validacion de prepolizas - If ObjConta.ValidacionPrePolizaCuadre(CvePrePolizaNueva, 4) Then - If ObjConta.ValorPolizaDescuadre > 0 Then - GuardaLogAD($"Compras/Compras-Anticipos | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas") - 'ErrorMovtosCxP = 1 - End If - End If - - 'Conta ContPAQ - If UsuarioActual.Empresa.Funcionalidad(200) = "1" And ErrorMovtosCxP = 0 And UsuarioActual.Empresa.UsaContabilidad Then - If idCuentaContabilizacion > 0 Then - If ObjConta.ContabilizarPrePoliza(CvePrePolizaNueva, UsuarioActual.CveUsuario, UsuarioActual.Empresa) Then - alertaContabilizacion.AppendFormat("{1}<\a>
", ObjConta.ContaIdPoliza, ObjConta.ContaFolio) - Else - ErrorMovtosCxP = 1 - End If - If ErrorMovtosCxP = 0 Then - Alert("Se enviaron correctamente las siguientes pólizas:

" & alertaContabilizacion.ToString, ModExtensiones.TipoMensaje.MsgInformacion) - Else - 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:
{0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia) - End If - End If - - - Else 'Empresa Prueba - - 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 CveConceptoPago As Integer = 17 - Dim TipoMovimientoCompra As Boolean = True - Select Case gvr.DataKey("TipoDocto") - Case "NC", "DEV" - CveConceptoCompra = 60 - CveIE = -1 - CveConceptoPago = 272 - Case "Egsc" - CveConceptoCompra = 21 - 'vinculo la compra actual, y no la compra como si fuera nota de credito - CveCompraNC = -1 - CveIE = gvr.DataKey("CveIE").ToEntero - Case "DD" - CveConceptoCompra = 37 - '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 - - 'Se agrega la nota de credito - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimientoCompra, gvr.FCTextBox("TxtAnticipo").Text.ToDecimal, " ", CveConceptoCompra, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, CveCompraAmortizacion:=CveCompraNC, ImporteMX:=gvr.FCTextBox("TxtAnticipo").Text.ToDecimal) Then - ErrorMovtosCxP = 1 - Exit For - End If - - 'movimiento de pago proveedor - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoCompra, gvr.FCTextBox("TxtAnticipo").Text.ToDecimal, " ", CveConceptoPago, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, CveCompraAmortizacion:=CveCompraNC, ImporteMX:=gvr.FCTextBox("TxtAnticipo").Text.ToDecimal) Then - ErrorMovtosCxP = 1 - Exit For - End If - - 'si tiene iva y su proporcion - ImporteMovimiento = Math.Round(PorcentajePago * TxtIVA.Text.ToDecimal, 2) - If ImporteMovimiento > 0 Then - Dim PorcentajeImpuesto As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, " ", 14, " ", TxtFechaPago.Text.ToDate, IdCtaIVAXAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, PorcentajeImpuesto:=PorcentajeImpuesto) Then ErrorMovtosCxP = 1 : Exit For - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, " ", 19, " ", TxtFechaPago.Text.ToDate, IdCtaIVAAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, PorcentajeImpuesto:=PorcentajeImpuesto) Then ErrorMovtosCxP = 1 : Exit For - - End If - - 'si tiene Ret iva y su proporcion - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) - If ImporteMovimiento > 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, " ", 15, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For - - End If - - 'si tiene Ret ISR y su proporcion - ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) - If ImporteMovimiento > 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, " ", 16, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For - - End If - - - 'actualizo una tabla de vinculaciones - - 'actualizo la cantidad en amortizaciones - - If gvr.DataKey("TipoDocto").Contiene("NC", "DEV") Then - If Not ObjCompra.AmortizarCompra(CveCompra, CveCompraNC, gvr.FCTextBox("TxtAnticipo").Text.ToDouble, UsuarioActual.CveUsuario) Then - ErrorMovtosCxP = 2 - Exit For - - End If - - End If - - - End If - - End If - - Next - - End If 'Empresa Prueba - - - - Select Case ErrorMovtosCxP - Case 0 - 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
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
Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia) - ObjCompra.RollBack() - End Select - - Catch ex As Exception - ObjCompra.RollBack() - End Try - 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, .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 Anticipos In ArrAnticipos - ImporteAnticipo += Ant.Importe - Next - End If - - LblAmortizacion.Text = ImporteAnticipo.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 - - '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 - - 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.
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 = New ClsContPAQi(UsuarioActual.Empresa) - - 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 - - 'PORCENTAJE IVA - Dim PorcentajeIVA As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal - - 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) 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 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 And 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) - - 'COMENTADO 15/3/2016 - 'cuando hay algo que ingresar a inventarios - 'Dim x As Integer = 0 - 'For Each Dr As DataRow In TmpDT.Rows - ' If GvInv.Rows.Count > 0 Then - ' If GvInv.Rows(x).FCCheckBox("cbInv").Checked Then - ' Dr("CveAlmacen") = GvInv.Rows(x).FCDropDownList("ddlEAlmacen").SelectedValue.ToEntero - ' Else 'limpio el valor para que no truene en linq mas abajo - ' Dr("CveAlmacen") = 0 - ' End If - ' x = x + 1 - ' Else - ' Exit For - ' End If - 'Next - - ''previamente si hay un ingreso a inventarios - 'Dim CtaAlmacen As Integer - 'If ContadorInventario > 0 Then - ' Dim drr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", TmpDT.Rows(0)("CveAlmacen").ToString)) - ' If drr IsNot Nothing Then - ' CtaAlmacen = drr("IdCtaContable").ToString.ToEntero - ' End If - 'End If - - 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) - ' tDiferenciaIVA -= tIVA - ' 'identifico si es el ultimo registro, para ver si es necesario un ajuste - ' If ipresup = GvPS.Rows.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 - tImporte += ttIVA - - 'PU = tImporte / gvr.DataKey("Cantidad").ToDouble - 'If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, gvr.DataKey("Cantidad").ToDouble, gvr.DataKey("CveUM").ToEntero, gvr.DataKey("CvePS").ToEntero, PU, -1) Then - ' ErrorAC = True - ' Exit For - 'End If - 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 - 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 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 = "True" AndAlso EsNoDeducible, True, False)) Then - - Retorno = False - Exit For - End If - - '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 - Dim ObjCompras As New ClsCompras - If Not ObjCompras.DeleteCompraDetalle(item.ToEntero) Then - Retorno = False - End If - Next - - If Retorno Then - If ViewState("IdPoliza").ToString.ToEntero > 0 Then - ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa) - ObjContaAC.IniciaTransacSQL() - - 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.") - 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 - Catch ex As Exception - Alert("Ocurrió un error al actualizar la compra", TipoMensaje.MsgError) - ObjCompra.RollBack() - 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("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.ToDecimal > 0, TipoCambio.ToDecimal, tipoCambioActual) - tipoCambioPago = GlobalTipoCambio(TxtFechaPago.Text.ToDate).ToString.ToDecimal - Else - tipoCambioActual = 1 - tipoCambioPago = 1 - End If - - 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 CveCuenta 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, CveAcreedor As Integer = 0, CveIE As Integer = 0, CveColectiva As Integer = 0, CveCreditoDetalle As Integer = 0 - Dim ConceptoPersonal As String = "", Concepto As String = "" - - If Not ObjConta.GetPrePolizasDetalle(CvePrePoliza) Then - ErrorPrepoliza = True - Else - If ObjConta.DtResultados.FiltraParametros("CveConceptoContable IN (6,68,49,205,176)").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 - CveAcreedor = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveAcreedor").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 - CveColectiva = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveColectiva").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 - - 'Removemos los conceptos de la prepoliza - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 6, CveCompra, 1) 'GASTO - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 68, CveCompra, 1) 'ALMACEN - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 49, CveCompra, 1) 'AF - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 205, CveCompra, 1) 'PS YA RECIBIDO - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 230, CveCompra, 1) 'PS YA RECIBIDO - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 231, CveCompra, 1) 'PS YA RECIBIDO - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 176, CveCompra, 1) 'PS NO RECIBIDO - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 228, CveCompra, 1) 'PS NO RECIBIDO - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 229, CveCompra, 1) '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" And ConceptoContabilizacionAlmacen = 0 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijoSIG").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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - End If - End If - Next - End If - - 'LIMPIA - importeMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 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 - 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 - 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero - End If - End If - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 68, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveMovimientoAlmacen:=CveMovimientoInventario, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - End If - End If - Next - End If - End If - - 'LIMPIA - importeMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 0 - - 'INV [MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA) ] - If UsuarioActual.CveEmpresa.Contiene(119) And 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), CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - End If - End If - - End If - - 'NC CON PRODUCTOS - CUENTA PUENTE - If UsuarioActual.CveEmpresa.Contiene(119) And 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), CveCuenta:=CveCuenta) 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 - 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 - DT.AcceptChanges() - DtAlmacenes.Dispose() - - 'QUITA 1-[MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA)] 2-[NC CON PRODUCTOS] - If UsuarioActual.CveEmpresa.Contiene(119) And 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", "CveProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"}) - Else - DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) = 0 AND ISNULL(AplicaCostoIndirecto,0) <> 1", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero - Else - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero - End If - End If - End If - - 'SEGMENTO DE NEGOCIO - Dim IdSegmentoNegocio As Integer = -1 - Dim drT As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero).FiltroPrimero(String.Format("CveSubProyecto = {0} ", Row2("CveSubProyecto").ToString.ToEntero)) - If drT IsNot Nothing Then - IdSegmentoNegocio = drT("IdSegNeg").ToString.ToEntero - End If - - 'AGREGA MOVIMIENTO - If importeMovimiento <> 0 Then - Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}" - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 6, Concepto, FechaMovimiento, IdCtaContable, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveTipoGasto:=Row2("CveTipoGasto").ToString.ToEntero) Then - ErrorPrepoliza = True - End If - End If - - Next - End If - - 'LIMPIA - importeMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 0 - - End Select - - Next - End If - - If ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 4) Then - If ObjConta.ValorPolizaDescuadre > 0 Then - ErrorPrepoliza = True - 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").ToDouble - - If Version = "3.3" 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 Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) - Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" - Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) - - 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 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") - 'EmisorNombre = ValorXML(node, "nombre") - End If - 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 - - 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("04", "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 - Next - 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" Then - - For Each retencion As XmlNode In nodeRetenciones - If retencion.Attributes("Impuesto").Value = "002" Then - RetencionIVA += retencion.Attributes("Importe").Value.ToDecimal - End If - If retencion.Attributes("Impuesto").Value = "001" Then - RetencionISR += retencion.Attributes("Importe").Value.ToDecimal - End If - ' Do something. - 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 - End If - If retencion.Attributes("impuesto").Value = "ISR" Then - RetencionISR += retencion.Attributes("importe").Value.ToDecimal - End If - ' Do something. - 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" Then - - For Each traslado As XmlNode In nodeTraslados - If traslado.Attributes("Impuesto").Value = "002" Then - TrasladoIVA += traslado.Attributes("Importe").Value.ToDecimal - End If - If traslado.Attributes("Impuesto").Value = "003" Then - TrasladoIEPS += traslado.Attributes("Importe").Value.ToDecimal - End If - If traslado.Attributes("Impuesto").Value = "001" Then - 'TrasladoISR = traslado.Attributes("importe").Value - End If - ' Do something. - Next - - Else - - For Each traslado As XmlNode In nodeTraslados - If traslado.Attributes("impuesto").Value = "IVA" Then - TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal - End If - If traslado.Attributes("impuesto").Value = "IEPS" Then - TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal - End If - 'If traslado.Attributes("impuesto").Value = "ISR" Then - ' TrasladoISR = traslado.Attributes("importe").Value - 'End If - ' Do something. - 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 - OtrosImpuestosRetenciones = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal - - 'If RetencionIVA <= 0 AndAlso ValorXML(node, "TotaldeRetenciones", "0").ToDouble > 0 Then RetencionIVA = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal - - 'For Each retencion As XmlNode In nodeImpLocales - ' If retencion.Attributes("impuesto").Value = "IVA" Then - ' RetencionIVA += retencion.Attributes("importe").Value.ToDouble - ' End If - ' If retencion.Attributes("impuesto").Value = "ISR" Then - ' RetencionISR += retencion.Attributes("importe").Value.ToDouble - ' End If - ' ' Do something. - 'Next - ' SumaTotalRetenciones += RetencionIVA - ' SumaTotalRetenciones += RetencionISR - - 'TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble - - 'Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) - 'For Each traslado As XmlNode In nodeTraslados - ' If traslado.Attributes("impuesto").Value = "IVA" Then - ' TrasladoIVA += traslado.Attributes("importe").Value.ToDouble - ' End If - ' If traslado.Attributes("impuesto").Value = "IEPS" Then - ' TrasladoIEPS += traslado.Attributes("importe").Value.ToDouble - ' End If - ' 'If traslado.Attributes("impuesto").Value = "ISR" Then - ' ' TrasladoISR = traslado.Attributes("importe").Value - ' 'End If - ' ' Do something. - 'Next - 'SumaTotalTraslados += TrasladoIVA - 'SumaTotalTraslados += TrasladoIEPS - End If - - End If - - 'Try - ' _TFDUUID = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces).LastChild.Attributes("UUID").InnerText - 'Catch ex As Exception - ' _TFDUUID = "" - 'End Try - - - 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(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.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 = "" - - 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, If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDouble)))) 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO - e.Row.FCTextBox("TxtAnticipo").Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1},{2});", e.Row.FCCheckBox("Chk").ClientID, e.Row.DBCampo("Saldo"), If(CveCompra > 0, Saldo, If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDouble)))) 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO - - 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 - 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 - e.Row.Cells(0).Width = Unit.Pixel(15) - e.Row.Cells(1).Width = Unit.Pixel(45) - e.Row.Cells(2).Width = Unit.Pixel(70) - e.Row.Cells(3).Width = Unit.Pixel(230) - e.Row.Cells(4).Width = Unit.Pixel(202) - e.Row.Cells(5).Width = Unit.Pixel(155) - e.Row.Cells(6).Width = Unit.Pixel(155) - e.Row.Cells(7).Width = Unit.Pixel(50) - e.Row.Cells(8).Width = Unit.Pixel(80) - e.Row.Cells(9).Width = Unit.Pixel(80) - e.Row.Cells(10).Width = Unit.Pixel(43) - e.Row.Cells(11).Width = Unit.Pixel(43) - - If UsuarioActual.Empresa.UsaAC Then 'AndAlso (CveFactura > 0 Or CveCompra > 0) - e.Row.Cells(12).Width = Unit.Pixel(150) - 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(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("'", "").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 = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToString.ToEntero, -1) - - '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("CveSATUnidadMedida")}','{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("CveSATUnidadMedida")}','{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 - 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 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 - - 'CargaPresupuestosEgresos - If UsuarioActual.Empresa.UsaAC Then - e.Row.Cells(13).Visible = True - 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.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("NOT CodigoCOG like '1%'", 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(13).Enabled = False - e.Row.Cells(14).Enabled = False - e.Row.Cells(15).Enabled = False - e.Row.Cells(16).Enabled = False - e.Row.Cells(17).Enabled = False - End If - Else - - e.Row.Cells(13).Visible = False - e.Row.Cells(14).Visible = False - e.Row.Cells(15).Visible = False - e.Row.Cells(16).Visible = False - e.Row.Cells(17).Visible = False - End If - - 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() - - 'GVAF.DataSource = TmpDT - 'GVAF.DataBind() - ''UpnAF.Update() - - 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}"")", e.Row.FCTextBox("TxtSaldoDeudor").ClientID, total, saldo)) - 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) - Dim ObjPS As New ClsProductosServicios - - If (ObjPS.GetPSSimplificado(-1)) Then - Application("GlobalDTPSSimplificado") = ObjPS.DtResultados.AsEnumerable - End If - - If ObjPS.GetPSEquivalencias(-1, -1) Then - GlobalDTProductosServiciosEquivalencias(-1, -1) = ObjPS.DtResultados - End If - - ObjPS.Dispose() - 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.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)) - End Sub - 'Private Sub AddPS(Cantidad As Double, UM As String, PS As String, PU As Double, IVA As Double, Descuento As Double, Optional Total As Double = 0) - ' Dim Row As DataRow = Nothing - ' Row = DTConceptos.NewRow() - ' Row("Consec") = DTConceptos.Rows.Count + 1 - ' Row("Cantidad") = Cantidad - ' Row("UM") = UM - ' Row("CveClasificacion") = -1 - ' Row("PS") = PS - ' Row("PU") = PU - ' Row("IVA") = IVA - ' Row("Total") = If(Total > 0, Total, Cantidad * PU) - ' Row("Descuento") = Descuento - - ' DTConceptos.Rows.Add(Row) - '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("CveSATUnidadMedida", GetType(Integer)) - TmpDT.Columns.Add("SATClaveUnidadMedida", GetType(String)) - - '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)) - - 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("CveSATUnidadMedida", GetType(Integer)) - TmpDTOriginal.Columns.Add("SATClaveUnidadMedida", GetType(String)) - - '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)) - - - End Sub - 'Private Sub AddDTEnvio(Cantidad As Double, UM As String, CveUM As Integer, CvePS As Integer, PS As String, PU As Double, CveAlmacen As Integer, CveEq As Integer) - - ' Dim dr As DataRow = DtInv.NewRow - - ' dr("Cantidad") = Cantidad - ' dr("UM") = UM - ' dr("CveUM") = CveUM - ' dr("CvePS") = CvePS - ' dr("PS") = PS - ' dr("PU") = PU - ' dr("CveAlmacen") = CveAlmacen - ' dr("CveEq") = CveEq - - ' DtInv.Rows.InsertAt(dr, hdnIndexInv.Value.ToEntero + 1) - - ' GvInv.DataSource = DtInv - ' GvInv.DataBind() - - - '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},
", 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},
", 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() - CargaClasificaciones() - CargaPS(-1) - CargaProyecto() - 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 GVAF_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAF.RowCreated - ' If e.Row.RowType = DataControlRowType.DataRow AndAlso (e.Row.RowState = DataControlRowState.Alternate OrElse e.Row.RowState = DataControlRowState.Normal) Then - ' e.Row.FCDropDownList("DdlTipoActivoFijo").DataSource = TmpDTTiposAF - ' e.Row.FCDropDownList("DdlTipoActivoFijo").DataBind() - - ' e.Row.FCDropDownList("DdlSubTipoActivoFijo").DataSource = Nothing - ' e.Row.FCDropDownList("DdlSubTipoActivoFijo").DataBind() - ' e.Row.FCDropDownList("DdlSubTipoActivoFijo").Items.Insert(0, New ListItem("Seleccione", "-1")) - - - ' e.Row.FCDropDownList("DdlAF").DataSource = Nothing - ' e.Row.FCDropDownList("DdlAF").DataBind() - ' e.Row.FCDropDownList("DdlAF").Items.Insert(0, New ListItem("Seleccione", "-1")) - - ' End If - 'End Sub - - 'Protected Sub GVAF_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAF.RowDataBound - ' If e.Row.RowType = DataControlRowType.DataRow Then - ' If e.Row.RowIndex = 0 Then - ' e.Row.Cells(0).Width = Unit.Pixel(20) - ' e.Row.Cells(1).Width = Unit.Pixel(140) - ' e.Row.Cells(2).Width = Unit.Pixel(250) - ' End If - - ' e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Right - ' e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Left - ' e.Row.Cells(2).HorizontalAlign = HorizontalAlign.Left - ' End If - 'End Sub - - 'Protected Sub DdlTipoActivoFijo_SelectedIndexChanged(sender As Object, e As System.EventArgs) - ' Dim Array() As String = Nothing - ' Dim DdlGVSubTipoAF As DropDownList = Nothing - - ' Array = DirectCast(sender, DropDownList).ClientID.Split("_"c) - ' If Array.Length > 0 Then - ' DdlGVSubTipoAF = DirectCast(GVAF.Rows(Array(3).ToEntero).Controls(4).Controls(1), DropDownList) - ' End If - - ' If DdlGVSubTipoAF IsNot Nothing Then CargaSubTipoAF(DirectCast(sender, DropDownList), DdlGVSubTipoAF) - 'End Sub - - 'Protected Sub GvOCC2_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvOCC2.RowDataBound - ' If e.Row.RowType = DataControlRowType.DataRow Then - - ' e.Row.Cells(0).Text = (e.Row.RowIndex + 1).ToString - - ' End If - 'End Sub - - 'Protected Sub chkFuncionariosEmpleados_CheckedChanged(sender As Object, e As EventArgs) Handles chkFuncionariosEmpleados.CheckedChanged - ' PnlPagoContado.Visible = Not chkFuncionariosEmpleados.Checked - ' PnlFuncionarioEmpleado.Visible = chkFuncionariosEmpleados.Checked - ' UPCondicionesPago.Update() - 'End Sub - 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 - - 'GvOCC.DataSource = TmpDT - 'GvOCC.DataBind() - 'GvOCC2.DataSource = dt - 'GvOCC2.DataBind() - - 'UpnAF.Update() - - 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 = DirectCast(GvInv.Rows(e.RowIndex).FindControl("txtECantidad"), TextBox).Text.ToDouble - Dim CveUnidadMedida As Integer = DirectCast(GvInv.Rows(e.RowIndex).FindControl("ddlEUnidad"), DropDownList).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("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 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 - 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() - 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).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", DdlMoneda.SelectedValue)) - DdlCuenta.DataBind() - DdlCuenta.Items.Insert(0, New ListItem("Seleccione", "-1")) - - DdlCuentaCaja.Items.Clear() - DdlCuentaCaja.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", DdlMoneda.SelectedValue)) - 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() - End Sub - Protected Sub DivirInsumo(sender As Object, e As EventArgs) - Dim index2 As Integer = 0 - - '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.ToDouble - dr1("IVA") = Math.Round(dr1("IVAPorcentaje").ToString.ToDouble * dr1("Total").ToString.ToDouble, 6) - TmpDT.AcceptChanges() - - - dr("CveActivoFijo") = 0 - dr("CodAF") = "" - 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 + 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") - 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") - 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") - 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") - 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 "C O N T R A T O S" - 'Protected Sub ImgBtnBuscarContrato_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnBuscarContrato.Click - ' If CveProveedor <= 0 Then - ' Alert("Debe de Seleccionar un proveedor") - ' Exit Sub - ' End If - - ' RegistraScript(String.Format("AbrirVentana('/Contratos/PopUpBuscarContrato.aspx?V=VCCOMP',730,300,'N');")) - 'End Sub - - 'Protected Sub CargaVContrato(sender As Object, e As EventArgs) - ' CargaVContrato2(HdnVCveContrato.Value) - 'End Sub - - 'Protected Sub CargaVContrato2(CveContrato As String) - ' If TxtContrato.Text <> "" Then - ' Dim ObjContratos As New ClsContratos - ' Dim DTContratosTemp As DataTable = Nothing - - ' GvContratos1.DataSource = TmpDT - ' GvContratos1.DataBind() - ' UPGVContratos1.Update() - - ' Dim ArrayCveContratos As String() = HdnVCveContrato.Value.Split(New Char() {","c}) - ' For i As Integer = 1 To ArrayCveContratos.Count - ' If ObjContratos.GetContratosDetalle(ArrayCveContratos(i - 1).ToEntero) Then - ' If IsNothing(DTContratosTemp) Then - ' DTContratosTemp = ObjContratos.DtResultados.Copy - ' Else - ' DTContratosTemp.Merge(ObjContratos.DtResultados) - ' End If - ' Else - ' Alert("Ocurrio un ERROR al cargar el Contrato") - ' DTContratosTemp.Rows.Clear() - ' Exit For - ' End If - ' Next - - ' GvContratos2.DataSource = DTContratosTemp - ' GvContratos2.DataBind() - ' UPGVContratos2.Update() - - ' ObjContratos.Dispose() - ' End If - '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) - 'Dim TempSubTotal = TxtSubTotal.Text.ToDouble - - If TmpDT.Rows.Count > 0 Then ' si hay movimientos y si esta afectando al total, que se haga el ajuste - 'Dim ImporteAjuste As Decimal = Total - (SubTotal2 + IVA - RetencionIVA - RetencionIVA - RetencionISR + IEPS + OtrosImpuestos) - 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 - - TmpDT.Rows(Indice)("PU") = TmpDT.Rows(Indice)("PU").ToString.ToDouble + tPU - TmpDT.Rows(Indice)("Total") = TmpDT.Rows(Indice)("Total").ToString.ToDouble + ImporteAjuste - TmpDT.AcceptChanges() - End If - - SubTotal = TmpDT.SUM("Total").ToString.ToDecimal - If Not EsCarga Then - Descuentos = TmpDT.SUM("Descuento").ToString.ToDecimal - End If - TxtSubTotal.Text = (SubTotal + Descuentos).FormatoNumero() - TxtSubTotal2.Text = SubTotal.FormatoNumero - TxtDescuento.Text = Descuentos.FormatoNumero() - SubTotalConceptos = SubTotal - GvPS.DataSource = TmpDT : GvPS.DataBind() - - If TxtOtrosImpuestos.Text.ToDouble > 0 Then TxtOtrosImpuestos.Text = "" : TrOtrosImpuestos.Visible = False - - 'EN ESPERA DE ALGUN CASO QUE LO NECESITE - IPP 5 DICIEMBRE 2016 - 'TempSubTotal = TempSubTotal - SubTotal - 'If TempSubTotal > 0 Then - ' TxtTotal.Text = TempSubTotal.ToString.FormatoNumero - 'End If - - 'GVAF.DataSource = TmpDT : GVAF.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 EmpresaPrueba Then - ' dr = DtAcreedores.FiltroPrimero(String.Format("CveProveedor = {0}", DdlAcreedor.SelectedValue)) - 'Else - ' dr = DtAcreedores.FiltroPrimero(String.Format("CveProveedor = {0}", DdlDeudor.SelectedValue)) - 'End If - - - If dr IsNot Nothing Then - Dim tSaldo As Double = dr("Saldo").ToString.ToDouble - 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.ToDouble, 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 - ViewState("CveCuentaProveedorAcreedores") = ObjProveedor.CveCuentaAcreedor - 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).Rows.Count > 0 Then - RowProveedorSucursal.Visible = True - DdlProveedorSucursal.Items.Clear() - DdlProveedorSucursal.DataSource = GlobalDTProveedorSucursales(DdlProveedor.SelectedValue.ToEntero) - 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() - - - - - - - - 'DdlProveedor.Attributes.Add("onclick", "CargaProveedores();") - 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).FiltroPrimero("CveCuenta = " & DdlCuenta.SelectedValue) - - If dr IsNot Nothing Then - CveMoneda = dr("CveMoneda").ToString.ToEntero - IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero - CveCuentaBancaria = dr("IdCtaContableSIG").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).FiltroPrimero("CveCuenta = " & DdlCuentaCaja.SelectedValue) - - If dr IsNot Nothing Then - CveMoneda = dr("CveMoneda").ToString.ToEntero - IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero - CveCuentaBancaria = dr("IdCtaContableSIG").ToString.ToEntero - 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() - - - 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 = False - 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 - 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 - 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 - 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 - Case "2" ' F y E - PnlContadoFyE.Visible = True - CargaFuncionariosEmpleados() - Case "3" ' Creditos - PnlContadoCreditos.Visible = True - CargaCreditos() - Case "4" ' Deudores - PnlContadoDeudores.Visible = True - CargaDeudores() - Case "5" ' ACREEDORES - PnlContadoAcreedores.Visible = True - CargaAcreedores() - Case "6" ' Caja Chica - PnlContadoCajaChica.Visible = True - TxtDocumentoImporteCaja.Text = TxtTotal.Text - End Select - - UpContado.Update() - End Sub - - Protected Sub RblRembolso_SelectedIndexChanged(sender As Object, e As EventArgs) - TrRembolsoCajaChica.Visible = False - TrRembolsoPersonal.Visible = False - DdlRembolsoCajaChica.SelectedValueExist("-1") - DdlRembolsoPersonal.SelectedValueExist("-1") - If RblRembolso.SelectedValue.ToEntero = 1 Then - TrRembolsoPersonal.Visible = True - ElseIf RblRembolso.SelectedValue.ToEntero = 2 Then - TrRembolsoCajaChica.Visible = True - End If - End Sub -#End Region - -#Region "ARMONIZACION CONTABLE - AC - SIMPLIFICADO" - Private Sub CargaPresupuestosEgresos(Optional CargaTodo As Boolean = True) - - 'Seccion Grid - GvPS.Width = 1760 - GvPS.Columns(12).Visible = True - GvPS.Columns(13).Visible = True - GvPS.Columns(14).Visible = True - GvPS.Columns(15).Visible = True - GvPS.Columns(16).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("NOT CodigoCOG like '1%'", DistinctColumns:={"CveClasificacion", "CodigoClasificacion"}, Orderby:="CodigoClasificacion") - 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("
#{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("
#{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) - - 'DtDetalle.Rows(gvr.RowIndex)("CveClasificacionOG") = gvr.FCDropDownList("DdlAC5").SelectedValue.ToEntero - 'DtDetalle.Rows(gvr.RowIndex)("CveProgramaOperativo") = gvr.FCDropDownList("DdlAC1").SelectedValue.ToEntero - 'DtDetalle.Rows(gvr.RowIndex)("CveUnidadAdministrativa") = gvr.FCDropDownList("DdlAC2").SelectedValue.ToEntero - 'DtDetalle.Rows(gvr.RowIndex)("CveFuenteFinanciamiento") = gvr.FCDropDownList("DdlAC3").SelectedValue.ToEntero - 'DtDetalle.Rows(gvr.RowIndex)("CveTipoGasto") = gvr.FCDropDownList("DdlAC4").SelectedValue.ToEntero - - 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("Empresas\{0}\OI", UsuarioActual.CveEmpresa)) - 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 - 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 - End Sub - Protected Sub DdlCajaChica2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCuentaCajaChicaReembolso.SelectedIndexChanged - Dim dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltroPrimero("CveCuenta = " & DdlCuentaCajaChicaReembolso.SelectedValue) - - If dr IsNot Nothing Then - CveMoneda = dr("CveMoneda").ToString.ToEntero - IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero - CveCuentaBancaria = dr("IdCtaContableSIG").ToString.ToEntero - 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 Double, Fecha As Date) As Boolean - Dim ErrorMovInv As Boolean = False - Dim CveAlmacen As Integer - 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 - CveAlmacen = Dr.DataKey("CveAlmacen").ToString.ToEntero - 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 subtotal > subtotaldevolucion - 1 AndAlso subtotal < subtotaldevolucion + 1 Then - - Dim CveMovimientoEntrada = ObjInventario.AddMovimiento(CveAlmacen, 13, 1, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra, -1, -1, -1) - If CveMovimientoEntrada <= 0 Then - ErrorMovInv = True - Else - For Each Dr As GridViewRow In GVDevolucion.Rows - If Dr.FCTextBox("TxtCantidad").Text.ToDouble > 0 Then - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Dr.FCTextBox("TxtCantidad").Text.ToDouble, Dr.DataKey("CveUM").ToString.ToEntero, Dr.DataKey("CvePS").ToString.ToEntero, Dr.DataKey("PU").ToString.ToDouble, -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 - Return ErrorMovInv - 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 - Dim objcompras As New ClsCompras() - If objcompras.GetCompraDetallealmacen(DDLDevolucion.SelectedValue.ToEntero) Then - GVDevolucion.DataSource = objcompras.DtResultados - GVDevolucion.DataBind() - End If - objcompras.Dispose() - 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) - 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 TxtSubTotal.Text.ToDouble > subtotaldevolucion - 1 AndAlso TxtSubTotal.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 - - End Sub - - Private Sub VinculaDevolucion() - 'Borramos el TmpDT - TmpDT.Clear() - - 'Iteramos el GridView de la OC - For Each gvr As GridViewRow In GVDevolucion.Rows - If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Then - - 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 CvePS As Integer = gvr.DataKey("CvePS").ToString.ToEntero - 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 = 0 - Dim Descuento As Decimal = 0 - - 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.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 = 119 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 - 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:
{1}", 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: {1}", 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 - ElseIf CveMovimientoAlmacen = 0 Then - BtnCancelarCompra.Visible = True - End If - End If - End Sub - Protected Sub BtnCancelarCompra2_Click(sender As Object, e As EventArgs) - RegistraScript("$('#DivCancelarCompra').modal('hide');") - - Dim ObjAC As ClsContPAQi = Nothing - If UsuarioActual.Empresa.UsaAC 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 TxtFecha.Text.ToDate.Month < TxtFechaCancelacion.Text.ToDate.Month Or TxtFecha.Text.ToDate.Year < TxtFechaCancelacion.Text.ToDate.Year Then - - 'CREA POLIZA NEGATIVA - 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 - - 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 CvePrePoliza > 0 Then - If ObjContabilidad.GetPrePolizasDetalle(CvePrePoliza) 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, - dr("CveMovimientoAlmacen").ToString.ToEntero, dr("CveActivoFijo").ToString.ToEntero, dr("CveAcreedor").ToString.ToEntero, dr("CveColectiva").ToString.ToEntero, dr("CveCreditoDetalle").ToString.ToEntero, CveCuenta:=dr("CveCuenta").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) Then - ErrorCancelar = True - Exit For - End If - Next - Else - ErrorCancelar = True - End If - Else - ErrorCancelar = True - 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) 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) 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("

Ver Póliza de cancelación", 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 Double = dr("PU").ToString.ToDouble - Dim IVA As Double = dr("IVA").ToString.ToDouble - Dim RetIVA As Double = dr("RetIVA").ToString.ToDouble - Dim RetISR As Double = dr("RetISR").ToString.ToDouble - Dim IEPSPS As Double = dr("IEPSPSPorcentaje").ToString.ToDouble - Dim IEPSPSIVA As Double = If(dr("IEPSGrabaIVA").ToString = "True", dr("IEPSPorcentaje").ToString.ToDouble, 0) - Dim Descuento As Double = dr("Descuento").ToString.ToDouble - 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 Double = dr("Cantidad").ToString.ToDouble * (valores(1).ToDouble / 100) - Dim CveSubProyectoContrato As String = valores(0) - Dim CveProyecto As String = valores(0) - Dim Total As Double = 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 += $"
El folio {ArrayCveOC(i).ToEntero} 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:
{TextoErrorOC}

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($"OC #{FolioOC} {Promocion}
") - 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 - If UsuarioActual.CveEmpresa.Contiene(119) Then - If UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 And Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then - DivOCVinculaInv.Visible = True - End If - End If - - - 'TIPO CAMBIO - If CveCompra > 0 Then - DivTipoCambioOC.Visible = False - End If - - DTOCTemp.Columns.Add("PUTC", GetType(Double)) - DTOCTemp.Columns.Add("TotalTC", GetType(Double)) - DTOCTemp.Columns.Add("DescuentoTC", GetType(Double)) - DTOCTemp.Columns.Add("IVATC", GetType(Double)) - DTOCTemp.Columns.Add("IEPSPSTC", GetType(Double)) - DTOCTemp.Columns.Add("IEPSPSIVATC", GetType(Double)) - DTOCTemp.Columns.Add("RetIVATC", GetType(Double)) - DTOCTemp.Columns.Add("RetISRTC", GetType(Double)) - 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") - - '[IPP] - JAMEntregaAdelantado | AJUSTE DE CANITDAD POR RECIBIR EN BASE A SALDOS DE INV-COMPRAS - 'If UsuarioActual.CveUsuario = 100 Then - 'If Dr("CveTipoPS").ToString.ToEntero = 2 And UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then - ' Dr("CantidadDisponible") = If(Dr("CantidadDisponible").ToString.ToDouble > Dr("CantidadPendienteVincular").ToString.ToDouble, Dr("CantidadPendienteVincular"), Dr("CantidadDisponible")) - 'End If - 'End If - 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("CantidadDisponible > 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 And Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then - Select Case DdlOCVinculaInv.SelectedValue.ToEntero - Case 176 - DTOCGV = DTOCGV.FiltraParametros("(EstatusInventario = 3 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.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
Proyecto" - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then - GvOC1.Columns(5).HeaderText = "Proyecto
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("'", "")}', {gvr.DataKey("CantidadDisponible").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("'", "")}', {e.Row.DBCampo("CantidadDisponible").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("CantidadDisponible")}, 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 = "" - e.Row.FCLabel("LbEstatusInv").ForeColor = Drawing.Color.Red - Case 2 - e.Row.FCLabel("LbEstatusInv").Text = "" - e.Row.FCLabel("LbEstatusInv").ForeColor = Drawing.Color.DarkOrange - Case 3 - e.Row.FCLabel("LbEstatusInv").Text = "" - 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" 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 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 - - Dim SubTotalGV = 0.0D - Dim SubTotalCompra = If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteSinImpuestos"), TmpDT.SUM("Total").ToString.ToDecimal) - Dim DiferenciaPermitida = 1 - Dim Cont = 0 - 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 - Next - - If Math.Abs(SubTotalGV - SubTotalCompra) < DiferenciaPermitida Then - 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.Contiene(119) Then - If UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 And Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then - If DdlOCVinculaInv.SelectedValue.ToEntero <= 0 Then - Alert("El campo Tipo de recepción almacén es necesario. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - End If - - If (HdnIEPSModificadoOC.Value.ToDecimal <> LbIEPSOC2.Text.ToDecimal) 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 - 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 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), 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 Double = dr("RetIVAPorcentaje").ToString.ToDecimal - Dim RetISR As Double = dr("RetISRPorcentaje").ToString.ToDecimal - Dim IEPSPS As Double = dr("IEPSPSPorcentaje").ToString.ToDecimal - Dim IEPSPSIVA As Double = dr("IEPSPSIVAPorcentaje").ToString.ToDecimal - Dim Descuento As Double = If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TxtDescuento.Text.ToDouble / 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 = -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 - - 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 - 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)("CantidadDisponible") = 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(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteSinImpuestos"), TxtSubTotal2.Text.ToDouble) + TxtOtrosImpuestos.Text.ToDouble).ToDecimal - If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, 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() - - 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.ToDouble, TxtSubTotal2.Text.ToDouble, TxtIVA.Text.ToDouble, TxtRetIVA.Text.ToDouble, TxtRetISR.Text.ToDouble, TxtTotal.Text.ToDouble) - - 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 Double = dr("RetIVAPorcentaje").ToString.ToDecimal - Dim RetISR As Double = dr("RetISRPorcentaje").ToString.ToDecimal - Dim IEPSPS As Double = dr("IEPSPSPorcentaje").ToString.ToDecimal - Dim IEPSPSIVA As Double = dr("IEPSPSIVAPorcentaje").ToString.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 = -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)("CantidadDisponible") = 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.ToDouble - - 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.ToDouble - - dr("Cantidad") = dr("Cantidad").ToString.ToEntero - Cantidad - dr("Total") = dr("Cantidad").ToString.ToEntero * dr("PU").ToString.ToDouble - - 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 /<> b > En caso de vincular la OC de esta manera la cantidad especificada sera considerada como recibida.

De ser correcto Continue o de lo contrario rectifique.", TipoMensaje.MsgAdvertencia) - - - Alert($"El concepto {PS} tiene especificada la cantidad {Cantidad} pero un costo de cero ($0).

En caso de vincular la OC de esta manera la cantidad especificada sera considerada como recibida.

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) - If DdlTipo.SelectedValue.ToEntero = 1 Then - - '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() - - 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 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) - - 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 - - '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 - - '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 - - '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 - 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(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append("") - strBody.Append("

Vinculación de orden de compra a factura

") - strBody.Append("

") - strBody.AppendFormat(" Se ha vinculado la OC # {0} {1}.", row("Folio"), If(row("FolioREQ").ToString.Length > 0, $", relacionada a la(s) requisicion(es) # {row("FolioREQ")}", "")) - strBody.Append("
") - strBody.Append(" Con los siguientes productos:") - strBody.Append("

") - - 'DETALLES - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - - For Each RowM As DataRow In DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows - strBody.AppendFormat(" ") - strBody.AppendFormat(" ", RowM("Cantidad").ToString.FormatoNumero) - strBody.AppendFormat(" ", RowM("UnidadMedida")) - strBody.AppendFormat(" ", RowM("Codigo")) - strBody.AppendFormat(" ", RowM("PS")) - strBody.AppendFormat(" ") - Next - - strBody.Append("
CantidadUMCódigoProducto
{0}{0}{0}{0}
") - strBody.Append("") - strBody.Append("") - - - '' 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(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append("") - strBody.Append("

Notificación de recepción de material

") - strBody.Append("

") - strBody.AppendFormat(" Se confirma recepción de material en almacén {0} vinculado la OC # {1} {2}.", DTMovimientos.FiltroPrimeroValor("Almacen"), row("Folio").ToString, If(row("FolioREQ").ToString.Length > 0, $", relacionada a la(s) requisicion(es) # {row("FolioREQ")}", "")) - strBody.Append("
") - strBody.Append(" Con los siguientes productos:") - strBody.Append("

") - - 'DETALLES - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - - For Each RowM As DataRow In DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows - strBody.AppendFormat(" ") - strBody.AppendFormat(" ", RowM("Cantidad").ToString.FormatoNumero) - strBody.AppendFormat(" ", RowM("UnidadMedida")) - strBody.AppendFormat(" ", RowM("Codigo")) - strBody.AppendFormat(" ", RowM("PS")) - strBody.AppendFormat(" ") - Next - - strBody.Append("
CantidadUMCódigoProducto
{0}{0}{0}{0}
") - strBody.Append("") - strBody.Append("") - - '' 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 {0}-{1} a la siguiente OC", Serie, Folio) - ' strBody.Append(" ") - ' strBody.Append(" ") - ' strBody.Append(" ") - ' strBody.Append(" ") - - ' 'Cargo el detalle - ' strBody.Append("
") - ' strBody.Append("
") - ' strBody.Append(" Ordenes de compra ") - ' strBody.Append(" - ' - ' ") - - ' 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("", RowM("Folio").ToString, RowM("Tipo")) - ' Next - - ' strBody.Append("
FolioTipo
{0}{1}
") - ' strBody.Append("
") - ' strBody.Append("
") - ' strBody.Append("") - - ' 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 {SerieLote} 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() - 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), 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.ToDouble * TipoCambioTemp - Dr("IVA") = Dr("IVA").ToString.ToDouble * TipoCambioTemp - Dr("RetIVA") = Dr("RetIVA").ToString.ToDouble * TipoCambioTemp - Dr("RetISR") = Dr("RetISR").ToString.ToDouble * TipoCambioTemp - Dr("IEPSPS") = Dr("IEPSPS").ToString.ToDouble * TipoCambioTemp - Dr("Descuento") = Dr("Descuento").ToString.ToDouble * TipoCambioTemp - Dr("OtrosGastos") = Dr("OtrosGastos").ToString.ToDouble * TipoCambioTemp - - Dim Total = (Dr("Cantidad").ToString.ToDouble * Dr("PU").ToString.ToDouble) - Dr("Descuento").ToString.ToDouble + Dr("OtrosGastos").ToString.ToDouble - Dr("Total") = Total - Next - - GvPS.DataSource = TmpDT - GvPS.DataBind() - UpPS.Update() - - - TxtSubTotal.Text = (TxtSubTotal.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - TxtSubTotal2.Text = (TxtSubTotal2.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - TxtIVA.Text = (TxtIVA.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - - 'IPP CAMBIADO - 5 DICIEMBRE 2016 - 'TxtTotal.Text = (TxtSubTotal2.Text.ToDouble + TxtIVA.Text.ToDouble).ToString.FormatoNumero.Replace(","c, "") - TxtTotal.Text = (TxtTotal.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - - SubTotalOriginal = TxtSubTotal.Text.ToDouble - SubTotal2Original = TxtSubTotal2.Text.ToDouble - - If TrDescuento.Visible Then TxtDescuento.Text = (TxtDescuento.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - If TrRetIVA.Visible Then TxtRetIVA.Text = (TxtRetIVA.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - If TrRetISR.Visible Then TxtRetISR.Text = (TxtRetISR.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - If TrIEPS.Visible Then TxtIEPS.Text = (TxtIEPS.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - If TrOtrosImpuestos.Visible Then TxtOtrosImpuestos.Text = (TxtOtrosImpuestos.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") - 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") - IVA = If(TmpDT.SUM("IVA") > 0, SubTotalIVA + SubTotalIEPSIVA, 0) - '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 = TxtRetIVA.Text.ToDecimal - Retenciones += TxtRetISR.Text.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 - - 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() - - 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 TempPorcentajeRetIVA = LblRetIVA.Text.ToDouble / 100 - 'Dim TempPorcentajeRetISR = LblRetISR.Text.ToDouble / 100 - - TempSubTotal = TxtSubTotal.Text.ToDouble - SubTotalOriginal = TxtSubTotal.Text.ToDouble - SubTotal2Original = TxtSubTotal2.Text.ToDouble - TempDescuentos = TxtDescuento.Text.Trim.ToDouble '+ LblAmortizacion.Text.Trim.ToDouble - 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, 2) - DifTotales = TxtTotal.Text.ToDouble - TempTotal - Dim DiferenciaPermitida = 0.6 - - If Math.Abs(DifTotales) > DiferenciaPermitida 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 - 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")) - 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) - 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")) - End If - - - CargaSubProyecto() - - - 'DdlProyecto.SelectedValueExist(GvRow.DataKey("CveProyecto")) - - DdlSubProyecto.SelectedValueExist(GvRow.DataKey("CveSubProyecto")) - 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").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 - - 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) - 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 - 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) - 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() - - '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 - ViewState("IEPSPS") = If(PS("IEPSPorcentaje").ToString = "-1", ViewState("IEPSPS"), PS("IEPSPorcentaje").ToString).ToString - 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) - TxtIEPSModal.Text = FormatoNumero(ViewState("IEPSPS").ToString().ToDouble * 100, 0) - - UpIVA.Update() - - If DdlClasificacion.SelectedIndex = 0 Then - 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 - - 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 - Private Sub CargaProyecto() - DdlProyecto.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"})) - - 'DdlProyecto.DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) - DdlProyecto.DataBind() - 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() - If CveProyecto > 0 Or UsuarioActual.Empresa.Tipo_CentroCosto.Contiene(1, 2) Then - DdlSubProyecto.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 - 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 {DdlSubProyecto.SelectedItem.Text} con la clasificación {DdlClasificacion.SelectedItem.Text} y el tipo de gasto {DdlTipoGasto.SelectedItem.Text}. Se excede por {Diferencia.FormatoNumero}", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - End If - - ActualizaTotales = True - Select Case Modalidad - Case "A" 'ADD - AddPS(TxtCantidad.Text.Trim.ToDouble, 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.ToDouble, Total, Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2), TxtRetIVAModal.Text.ToDouble / 100, TxtRetISRModal.Text.ToDouble / 100, TxtIEPSModal.Text.ToDouble / 100, 0, TxtDescuentoModal.Text.ToDouble, OtrosGastos:=TxtOtrosGastos.Text.ToDouble, CveTipoGasto:=DdlTipoGasto.SelectedValue.ToEntero, TipoGasto:=DdlTipoGasto.SelectedItem.Text, NoDeducible:=ChkEsNoDeduciblePS.Checked) - - 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() - 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 - UpPS.Update() - CargaGvPersonal() - End Sub - ''' - ''' Regresa el INDEX del row que acaba de agregar en el TMPDT - ''' - ''' - Private Function AddPS(Cantidad As Double, 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 Double, Total As Double, IVA As Double, RetIVA As Double, RetISR As Double, IEPSPS As Double, IEPSPSIVA As Double, Descuento As Double, 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 Double = 0, - Optional CveSATPS As Integer = -1, Optional CargaXml As Boolean = False, Optional CveTipoGasto As Integer = -1, Optional TipoGasto As String = "", Optional PorcentajeIVA As Double = 0, - Optional PorcentajeIEPS As Double = 0, Optional PorcentajeRetIVA As Double = 0, Optional PorcentajeRetISR As Double = 0, Optional NoDeducible As Boolean = False) 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" And CveSATPS > 0 Then - Dim DrPSSAT As DataRow = Nothing - If CargaXml Then - 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 - 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 - End If - End If - - 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" Then - Row("IVA") = Math.Round(IVA, DecimalesPermitidos) - Row("IVAPorcentaje") = PorcentajeIVA - 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) - Row("IVA") = Math.Round(IVA * Total, DecimalesPermitidos) - Row("IVAPorcentaje") = IVA - Row("RetIVA") = Math.Round(RetIVA * Total, DecimalesPermitidos) - Row("RetIVAPorcentaje") = RetIVA - Row("RetISR") = Math.Round(RetISR * Total, DecimalesPermitidos) - Row("RetISRPorcentaje") = RetISR - Row("IEPSPS") = Math.Round(IEPSPS * Total, DecimalesPermitidos) - Row("IEPSPSPorcentaje") = IEPSPS - End If - Row("ImporteConImpuestos") = (Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble) + Row("IVA").ToString.ToDouble + Row("IEPSPS").ToString.ToDouble - (Row("RetIVA").ToString.ToDouble + Row("RetISR").ToString.ToDouble) - Row("ImporteSinImpuestos") = Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble - - 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, "") - - 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 - - - - 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 - - End Sub - Private Sub UpdatePS() - 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 - - '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 - - - 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 - DrPS("CveClasificacion") = PSRow("CveClasificacion").ToString - DrPS("Clasificacion") = PSRow("Clasificacion").ToString - DrPS("CvePS") = DdlPS.SelectedValue - DrPS("PS") = PSRow("PS").ToString - DrPS("CveTipoPS") = PSRow("CveTipoPS").ToString.ToEntero - DrPS("CveSATPS") = PSRow("CveSATPS").ToString.ToEntero - DrPS("SATClaveProductoServicio") = PSRow("SATClaveProductoServicio").ToString - - '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.ToDouble - 1, 2) - Dim RetISR = (TxtRetISRModal.Text.ToDouble / 100) - Dim RetIVA = (TxtRetIVAModal.Text.ToDouble / 100) - Dim IEPSPS = (TxtIEPSModal.Text.ToDouble / 100) - Dim IEPSPSIVA = 0 - - If Not (CveCompra > 0 Or CveFactura > 0 Or OCVinculada) Then - 'If DdlIVA.SelectedValue.ToDouble = 0 Then DrPS("IVA") = 0 Else DrPS("IVA") = IVA * Total - DrPS("IVA") = IVA * Total - DrPS("IVAPorcentaje") = IVA - DrPS("RetIVA") = RetIVA * Total - DrPS("RetIVAPorcentaje") = RetIVA - DrPS("RetISR") = RetISR * Total - DrPS("RetISRPorcentaje") = RetISR - DrPS("IEPSPS") = IEPSPS * Total - DrPS("IEPSPSPorcentaje") = IEPSPS - DrPS("IEPSPSIVA") = IEPSPSIVA * Total - DrPS("IEPSPSIVAPorcentaje") = IEPSPSIVA - 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") - 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 - Alert("No hay partidas para reclasificar el SubProyecto", TipoMensaje.MsgAdvertencia) - Exit Sub - 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 - - 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) - 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.MsgInformacion) - - 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.MsgInformacion) - - 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) - DdlUnidadAlias.DataBind() - HdnPSAliasCveClasificacion.Value = DrPS("CveClasificacion").ToString - HdnPSAliasClasificacion.Value = DrPS("Clasificacion").ToString - End If - End If - UpPSAlias.Update() - End Sub - Protected Sub BtnAddPSAlias_Click(sender As Object, e As EventArgs) Handles BtnAddPSAlias.Click - Dim PS As New ClsProductosServicios - Dim CvePS = -1 - Dim tPS = "" - - CvePS = DdlPSAlias2.SelectedValue.ToEntero - tPS = DdlPSAlias2.SelectedText - - If PS.AddPSAlias(TxtPSAlias.Text.Trim, CvePS) Then - GlobalDTProductosServiciosAlias(-1) = 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 - - '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 - Next - - TmpDT.AcceptChanges() - - GvPS.DataSource = TmpDT - GvPS.DataBind() - UpPS.Update() - - Alert("Registro actualizado con exito.", 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() - End Sub - Private Sub GeneraGlobalEquivalencias() - Dim ObjPS = New ClsProductosServicios - If ObjPS.GetPSEquivalencias(-1, -1) Then - GlobalDTProductosServiciosEquivalencias(-1, -1) = 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).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) - 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).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) - 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() - End Sub - Private Sub GeneraGlobalUM() - Dim ObjPS = New ClsProductosServicios - Dim OjbUM As New ClsUnidadesMedida - - If ObjPS.GetPSEquivalencias(-1, -1) Then - GlobalDTProductosServiciosEquivalencias(-1, -1) = 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("", 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("", 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() - 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 - LBDevolucionAlmacen.Text = " Cancelar Devolución Almacén" - LBDevolucionAlmacen.ToolTip = "¿Está seguro de Cancelar la Devolución de Almacén?" - Else - LBDevolucionAlmacen.Text = " Solicitar Devolución Almacén" - LBDevolucionAlmacen.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) - 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, UsuarioActual.CveEmpresa) 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() - 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() - - Dim SaldoAnticipo = 0.0 - Dim CveCompras As String = "" - If ChkNCInvNC.Checked 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 - 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 - End If - - - If SaldoAnticipo <= 0 Then - Alert("No hay movimientos seleccionados para aplicar", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - LbNCInvSaldo.Text = SaldoAnticipo.FormatoNumero() - - If ChkNCInvNC.Checked Then - Dim ObjInventarios As New ClsInventarios - If ObjInventarios.RecepcionAlmacenGet(-1, -1, UsuarioActual.CveEmpresa, CveProveedor) AndAlso ObjInventarios.DtResultados.FiltraParametros($"CveCompra IN ({CveCompras}) AND CantidadF > 0").Rows.Count > 0 Then - DtPendientesAlmacen = ObjInventarios.DtResultados.FiltraParametros($"CveCompra IN ({CveCompras}) AND 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() - UpNCInv.Update() - RegistraScript("$('#FacturaNC').modal('hide');", "FacturaNC") - End If - RegistraScript("$('#ModalNCInv').modal('show');", "ModalNCInv") - 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() - - 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 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 -#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 - 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("Folio: {1} Fecha: {2} {3} {4}", 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 CuentasContablesInvalidasSIG As New StringBuilder - Dim IdCtaContable As Integer = 0 - Dim CveCuenta 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijoSIG").ToString.ToEntero - End If - End If - If ImporteMovimiento <> 0 Then - If IdCtaContable = 0 Then - CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString) - End If - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & 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), CveCuenta:=CveCuenta) 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 - CveCuenta = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"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("CveCuenta") = CveCuenta - 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("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) - End If - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) - 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), CveCuenta:=Row("CveCuenta").ToString.ToEntero) Then - TieneError = True - Exit For - End If - End If - Next - End If - End If - - ImporteMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 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 - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero - Else - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", 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("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) - End If - If CveCuenta = 0 Then - CuentasContablesInvalidasSIG.Append("
" & 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), CveCuenta:=CveCuenta) 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 - - 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 - Dim Dr As DataRow = Nothing - If ObjInventario.GetFletes(UsuarioActual.CveEmpresa, CveFlete) Then - If ObjInventario.DtResultados.Rows.Count > 0 Then - Dr = ObjInventario.DtResultados.Rows(0) - End If - End If - If Dr IsNot Nothing Then - If Not ObjInventario.UpdateFlete(CveFlete, Dr("Descripcion").ToString, Dr("Fecha").ToString.ToDate, -1, CveCompra, UsuarioActual.CveUsuario) Then - ErrorTrans = True - End If - Else - 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) 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) 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.ToDecimal, 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() - - Dim ObjCompras As New ClsCompras - If ObjCompras.GetImportaciones(-1, -1, -1, "-1", "-1", UsuarioActual.CveEmpresa) Then - DdlImportaciones.DataSource = ObjCompras.DtResultados - DdlImportaciones.Items.Insert(0, New ListItem("Seleccione", "-1")) - End If - ObjCompras.Dispose() - - Dim ObjInv As New ClsInventarios - If ObjInv.GetFletes(UsuarioActual.CveEmpresa) Then - DdlFletes.DataSource = ObjInv.DtResultados - DdlFletes.Items.Insert(0, New ListItem("Seleccione", "-1")) - End If - ObjInv.Dispose() - - DdlImportaciones.DataBind() - DdlFletes.DataBind() - - 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) 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 - - - 'EMPIEZA OBJETOS Y TRANSACCIONES - 'Dim OC As New ClsOC - 'Dim OCBitacora As New ClsOIEventos(OC.IniciaTransacSQL()) - 'Dim ObjInventarios As New ClsInventarios(OC.IniciaTransacSQL()) - 'Dim ObjConta As New ClsContabilidad(OC.IniciaTransacSQL()) - - - - 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("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 'And DtInvOC.Rows.Count > 0 - 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 - - 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("") - DrInvOCDiferencias("TipoCambioAjuste") = drInv("TipoCambioAjuste").ToString.ToDecimal - DrInvOCDiferencias("Diferencia") = ((gvr.FCTextBox("TxtPU").Text.ToDecimal * drInv("TipoCambioAjuste").ToString.ToDecimal) - drInv("PU").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 - 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) 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 = -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 = Now - 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 - PUCompra = DrDiferencias("PUCompra").ToString.ToDecimal - PS = DrDiferencias("PS").ToString - - Fecha = Now - 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}", ProveedorNombre, DrDiferencias("FolioOC")) - - 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 - CveCuentaAlmacen = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {DrDiferencias("CveAlmacen").ToString.ToEntero}").ToEntero - - If DiferenciaInvOC.RoundSQL() <> 0 Then - CvePrePoliza = ObjConta.AddPrePolizas("Compras/OC-(OCAlmacen)", 74, DiferenciaInvOC, DiferenciaInvOC, 1, Fecha, ConceptoPartida, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - If CvePrePoliza > 0 Then - - If CveMoneda = 2 And UsuarioActual.CveEmpresa.Contiene(119) Then - ImporteME = (DiferenciaInvOC / TCInvOC).RoundSQL() - ImporteMEComp = (DiferenciaInvOC - ImporteME).RoundSQL() - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, -DiferenciaInvOC, SerieFolio, 177, ConceptoPartida, Fecha, IdCtaContableRecepcionOCER, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=-DiferenciaInvOC, CveOCDetalle:=CveOCDetalle) 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 Not 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 - 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, If(ConceptoSalida = 0, IdCtaContableAlmacen, IdCtaContableRecepcionOCER), -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=-DiferenciaInvOC, CveCuenta:=CveCuentaAlmacen, CveOCDetalle:=CveOCDetalle) 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) 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 - 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.") - RecargaGlobalEquivalencias() - End If - ObjPS.Dispose() - - TxtPS.Text = "" - TxtCodigoPS.Text = "" - DdlUnidadMedida.SelectedValueExist(-1) - DdlClasificacionPS.SelectedValueExist(-1) - DdlTipoPS.SelectedValueExist(-1) - - UpAgregarPS.Update() - - RegistraScript("$('#DivAgregarPS').modal('hide');") - RecargaPSGlobal() - End Sub - Private Sub RecargaPSGlobal() - Dim ObjPS As New ClsProductosServicios - - If ObjPS.GetPSSimplificado(-1) Then Application("GlobalDTPSSimplificado") = ObjPS.DtResultados.AsEnumerable() - - ObjPS.Dispose() - End Sub - -#End Region - -#Region "TIPO DE COMPRA" - - Protected Sub DdlTipoCompra_SelectedIndexChanged(sender As Object, e As EventArgs) - - End Sub - -#End Region - - - Protected Sub BtnFacturaNC_Click(sender As Object, e As EventArgs) - If ChkNCInvNC.Checked Then - CargaNCINV() - 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(10).Visible = True - UpEsNoDeduciblePS.Visible = True - Else - EsNoDeducible = False - dvNoDeducible.Visible = False - GvPS.Columns(10).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 +Option Explicit On +Option Strict On + +Imports Extensiones +Imports System.Data +Imports System.Xml +Imports System.Globalization +Imports System.Linq +Imports System +Imports System.IO +Imports ADServerControl +Imports System.Threading.Tasks +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 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 + + 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 CveCuentaProveedor As Integer + Get + Return ViewState("CveCuentaProveedor").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 CveCuentaProveedorDeudores As Integer + Get + Return ViewState("CveCuentaProveedorDeudores").ToString.ToEntero + End Get + End Property + Private ReadOnly Property CveCuentaProveedorAcreedores As Integer + Get + Return ViewState("CveCuentaProveedorAcreedores").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 CveCuentaProveedorAnticipos As Integer + Get + Return ViewState("CveCuentaProveedorAnticipos").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 CveCuentaProveedorAnticiposExtranjera As Integer + Get + Return ViewState("CveCuentaProveedorAnticiposExtranjera").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 CveCuentaProveedorAnticiposComplementaria As Integer + Get + Return ViewState("CveCuentaProveedorAnticiposComplementaria").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 CveCuentaProveedorRetIVA As Integer + Get + Return ViewState("CveCuentaProveedorRetIVA").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 CveCuentaProveedorRetISR As Integer + Get + Return ViewState("CveCuentaProveedorRetISR").ToString.ToEntero + End Get + End Property + + Private ReadOnly Property CveCuentaIEPS As Integer + Get + Return ViewState("CveCuentaIEPS").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 CveCuentaProveedorExtranjera As Integer + Get + Return ViewState("CveCuentaProveedorExtranjera").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 CveCuentaProveedorComplementaria As Integer + Get + Return ViewState("CveCuentaProveedorComplementaria").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 CveCuentaBancaria As Integer + Get + Return ViewState("CveCuentaBancaria").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveCuentaBancaria") = 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 + + 'Private ReadOnly Property Ruta As String + ' Get + ' Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\" & UsuarioActual.CveEmpresa & "\" + ' End Get + 'End Property + + + Public Class Anticipos + Public Property TipoMovto As String + Public Property CveIE As Integer + Public Property Importe 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 + 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 +#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 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 Double + Get + Return ViewState("TipoCambio").ToString.ToDouble + End Get + Set(value As Double) + 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 + +#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 IVAOriginal As Double + Get + Return ViewState("IVAOriginal").ToString.ToDouble + 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 + Return ViewState("TotalOriginal").ToString.ToDouble + 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 + + 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() + Modalidad = "" + Version = "" + CveMetodoPago = -1 + RFCProv = "" + CargaDdlTipoGasto() + CreaTmpAcarreos() + EsContado = False + CierrePeriodo = False + NCDevolucion = False + CompraCargada = False + Saldo = 0 + SubTotalOriginal = 0 + CveConceptoContableAlmacen = 0 + EsNoDeducible = False + + '******** 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 + CveCuentaBancaria = 0 + End If + + 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("CveCompra") = "0" + 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 + + '[IPP] Eliminar 22Junio2018 + 'If UsuarioActual.Empresa.UsaInventarios Then + ' TabAlmacen.Enabled = Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 + 'End If + + 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.Empresa.GralSoloProyecto Then + + ' LitHProyecto.Text = "Sucursal" + ' DdlSubProyecto.Items.Clear() + ' DdlSubProyecto.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)) + ' DdlSubProyecto.DataBind() + ' DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + ' DdlAsignaSubProyecto.Items.Clear() + ' DdlAsignaSubProyecto.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)) + ' DdlAsignaSubProyecto.DataBind() + ' DdlAsignaSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + ' divproyecto.Visible = False + ' divasignaproyecto.Visible = False + ' DdlProyecto.Visible = False + ' DdlProyecto.Items(0).Text = "" + + 'End If + + 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) + DdlPersonal.DataSource = ObjPersonal.DtResultados + DdlPersonalReembolso.DataSource = ObjPersonal.DtResultados + ObjPersonal.Dispose() + DdlPersonal.DataBind() + DdlPersonalReembolso.DataBind() + ObjPersonal.Dispose() + + + '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) + DdlProveedor.Visible = False + HplProveedor.Visible = True + GvInv.Visible = True + CargaProveedor(-1, RFC) + + If Not DdlTipoComprobante.SelectedValue = "NC" 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, TxtSubTotal.Text.ToDouble) + InicializaAplicaNCFact() + DivReembolso.Visible = False + RBLPago.Items(2).Enabled = False + + End If + + + + If UsuarioActual.Empresa.UsaAC Then + CambiaEjercicioAC() + End If + + ' ''Fecha limite para ingreso de facturas + ''Dim DtEmpresa As DataTable = GlobalDTEmpresas(UsuarioActual.CveEmpresa) + ''If DtEmpresa.Rows.Count > 0 Then + '' Dim FechaLimite = DateSerial(DtEmpresa.Rows(0)("EjercicioActual").ToString.ToEntero, DtEmpresa.Rows(0)("PeriodoActual").ToString.ToEntero, DtEmpresa.Rows(0)("DiasPermitidos").ToString.ToEntero) + '' If Month(TxtFecha.Text.ToDate) < (Month(FechaLimite) - 1) Or (Month(TxtFecha.Text.ToDate) = (Month(FechaLimite) - 1) And Day(Date.Now) > Day(FechaLimite)) Then + '' Alert("La factura actual ya no aplica para ingresarse al sístema.", TipoMensaje.MsgAdvertencia) + '' BtnGuardar.Enabled = False + '' Else + '' Alert("En tiempo") + '' End If + ''Else + '' Alert("No se pudieron cargar los datos de la empresa", TipoMensaje.MsgAdvertencia) + ''End If + 'Carga Compra + + If UsuarioActual.Empresa.Funcionalidad(123).ToEntero > 0 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) + + 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 + + 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 + + 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO + LblSaldoFactura.Text = If(CveCompra > 0, Saldo.FormatoNumero, TxtTotal.Text.FormatoNumero) + + + If UsuarioActual.CveEmpresa = 126 And CveCompra > 0 Then + LnkExportaGv.Visible = True + End If + + 'Condiciones de la Compra + Dim dt As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario) + 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 + 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 + + If UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then + LitHProyecto.Text = "Proyecto" + LthProyectoP.Text = "Proyecto" + + LblSubProyectoHeader.Text = "" + LblSubProyectoPHeader.Text = "" + + LblSubProyecto.InnerText = "Proyecto" + 'LblSubProyectoDivAplica.InnerText = "Proyecto" + + DdlSubProyecto.Items.Clear() + 'DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + DdlSubProyecto.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)) + DdlSubProyecto.DataBind() + DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + 'DdlAsignaSubProyecto.Items.Clear() + 'DdlAsignaSubProyecto.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)) + 'DdlAsignaSubProyecto.DataBind() + 'DdlAsignaSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + divproyecto.Visible = False + 'divasignaproyecto.Visible = False + DdlProyecto.Visible = False + DdlProyecto.Items(0).Text = "" + + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then + LitHProyecto.Text = "Sucursal" + LthProyectoP.Text = "Sucursal" + + LblSubProyectoHeader.Text = "" + LblSubProyectoPHeader.Text = "" + + LblSubProyecto.InnerText = "Sucursal" + 'LblSubProyectoDivAplica.InnerText = "Sucursal" + + DdlSubProyecto.Items.Clear() + 'DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + DdlSubProyecto.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)) + DdlSubProyecto.DataBind() + DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + 'DdlAsignaSubProyecto.Items.Clear() + 'DdlAsignaSubProyecto.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)) + 'DdlAsignaSubProyecto.DataBind() + 'DdlAsignaSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + divproyecto.Visible = False + 'divasignaproyecto.Visible = False + DdlProyecto.Visible = False + DdlProyecto.Items(0).Text = "" + + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then + LitHProyecto.Text = "Sucursal" + LthProyectoP.Text = "Sucursal" + + LblSubProyectoHeader.Text = "Proyecto" + LblSubProyectoPHeader.Text = "Proyecto" + + 'LblSubProyectoDivAplica.InnerText = "Sucursal" + 'LblProyectoDivAplica.InnerText = "Proyecto" + LblSubProyecto.InnerText = "Sucursal" + LblProyecto.InnerText = "Proyecto" + + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then + LitHProyecto.Text = "Proyecto" + LthProyectoP.Text = "Proyecto" + + LblSubProyectoHeader.Text = "Sucursal" + LblSubProyectoPHeader.Text = "Sucursal" + + 'LblSubProyectoDivAplica.InnerText = "Proyecto" + 'LblProyectoDivAplica.InnerText = "Sucursal" + LblSubProyecto.InnerText = "Proyecto" + LblProyecto.InnerText = "Sucursal" + End If + + CargaGvPersonal() + CargaDdlPersonal() + + + InicializaDevolucionAlmacen() + HabilitaEdicionManualAgregar() + InicializaActualizarTC() + 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();") + End Sub + +#Region "C A R G A S" + 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() + 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 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 IVA del CFDi no tiene un comportamiento normal, por favor verifique que sea correcto.

NOTA: 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(-3), 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}Empresas\{1}\Compras\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, dr("RFCDe"), dr("XML")) + If IO.File.Exists(Archivo) Then + + Dim Validada As Boolean = True + 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 Valida As New ClsValidaCFDi(dr("UUID").ToString(), dr("RFCDe").ToString, dr("RFCPara").ToString(), dr("Total").ToString.ToDecimal) + + If UsuarioActual.CveEmpresa < 2 Then + Valida.EsValida = 1 + End If + + If Valida.EsValida > 0 Then + If Valida.EsValida = 2 Then + Validada = False + + If ObjeFacturas.UpdateEstatus(Valida.EsValida, CveFactura) 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.
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() + End If + + UpPSS.Update() + + + If Validada Then + + + + Try + + XMLDoc.Load(Archivo) + Catch ex As Exception + + Dim oReader = New StreamReader(Archivo, Encoding.GetEncoding("ISO-8859-1")) + XMLDoc.Load(oReader) + oReader.Dispose() + + End Try + + + CreaDTConceptos() + + CargaComprobanteXML(XMLDoc) + + If NuevaValidacionXML = 1 Or Version = "3.3" Then + Dim Xml As New StringBuilder + 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 = "http://www.sat.gob.mx/cfd/3" + Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) + + 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.Append(Replace(Replace(Replace(nodeconceptos.OuterXml, " 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
") + 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
") + 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
") + 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) + 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 + + + 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() + + Dim ObjSAT As New ClsSAT + Dim RFCRequest As String = Request("RFC").ToString + 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 {Estatus} en el Listado EFOS (69B) del SAT", TipoMensaje.MsgAdvertencia) + System.Threading.Thread.Sleep(5) + End If + End If + ObjSAT.Dispose() + + + Return RFC + End Function + + Private Sub CargaRetIVAConcepto(Optional Cambio As Boolean = False) + If TrRetIVA.Visible Then + TdRetIVAConcepto.Visible = True + End If + If Cambio Then + DdlRetIVAConcepto.Items.Clear() + If RFCProv.Length = 13 Then + DdlRetIVAConcepto.Items.Insert(0, New ListItem("Honorarios/Serv. Prof.", "1")) + DdlRetIVAConcepto.Items.Insert(1, New ListItem("Fletes P.F.", "2")) + ElseIf RFCProv.Length = 12 Then + DdlRetIVAConcepto.Items.Insert(0, New ListItem("Fletes P.M.", "3")) + End If + DdlRetIVAConcepto.Items.Add(New ListItem("Arrendamiento", "4")) + End If + UpPS.Update() + + End Sub + Private Sub CargaRetISRConcepto(Optional Cambio As Boolean = False) + If TrRetISR.Visible Then + TdRetISRConcepto.Visible = True + End If + If Cambio Then + DdlRetISRConcepto.Items.Clear() + DdlRetISRConcepto.Items.Insert(0, New ListItem("Honorarios", "1")) + DdlRetISRConcepto.Items.Insert(1, New ListItem("Arrendamiento", "2")) + End If + UpPS.Update() + End Sub + + Private Sub ValidacionesTotalesXml() + + Dim Msg As String = "" + Dim SubtotalTemp = TmpDT.SUM("Total") + Math.Round(TmpDT.SUM("Descuento"), 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
") + 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
") + 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
") + 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
") + 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
") + 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
({0}-{1})", Math.Round(TotalTemp, 2), Math.Round(Total, 2)) + End If + + If Msg <> "" Then + Alert($"El comprobante XML presenta las siguientes inconsistencias:

{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 + RegistraScript("$('#ModalIEPS').modal('show');") + + 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 + + + + 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) + + End Sub + + ''' + ''' Método que convierte el IEPS en un concepto para no ajustar totales + ''' + 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 Double = 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 Double = IEPS + Dim Total As Double = Cantidad * PU + Dim IVA As Double = 0 + Dim Descuento As Double = 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 + TxtDescripcion.Text = dr("Descripcion").ToString + CvePrePoliza = dr("CvePrePoliza").ToString.ToEntero + EstatusAlmacen = dr("EstatusAlmacen").ToString.ToEntero + DdlTipoCompra.SelectedValueExist(dr("CveTipoCompra")) + '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).Rows.Count > 0 Then + RowProveedorSucursal.Visible = True + DdlProveedorSucursal.Items.Clear() + DdlProveedorSucursal.DataSource = GlobalDTProveedorSucursales(CveProveedor) + 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.ToDouble + If TipoCambio > 1 Then LblTC.Text = String.Format("TC: {0}", TipoCambio.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 + 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) + + 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) + 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 + + 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 + + '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)) + + + + 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 = "Fac" 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 + 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 + 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 = "
Compras Aplicadas
" + 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 + If UsuarioActual.TienePermisoProceso(77) OrElse UsuarioActual.TienePermisoProceso(135) 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 Movimientos de Inventario 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 Poliza Asociada?", 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 + BtnEliminarCompra.Visible = False + BtnCancelarCompra.Visible = False + 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 + 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 If + + + UpEstatus.Update() + 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() + + ddlAlmacenAdd.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1).FiltraParametros("CveTipoAlmacen IN (1,2,7,14,19)") 'solo muestra tipo material y herramientas + ddlAlmacenAdd.DataBind() + 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 + + ViewState("CveProveedor") = ObjProveedor.CveProveedor + ViewState("CveTipoProveedor") = 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 + + 'Conta SIG + ViewState("CveCuentaProveedor") = ObjProveedor.CveCuentaProveedores + ViewState("CveCuentaProveedorAnticipos") = ObjProveedor.CveCuentaAnticipos + ViewState("CveCuentaProveedorAnticiposExtranjera") = ObjProveedor.CveCuentaAnticiposExtranjera + ViewState("CveCuentaProveedorAnticiposComplementaria") = ObjProveedor.CveCuentaAnticiposComplementaria + ViewState("CveCuentaProveedorDeudores") = ObjProveedor.CveCuentaDeudor + ViewState("CveCuentaProveedorAcreedores") = ObjProveedor.CveCuentaAcreedor + ViewState("CveCuentaProveedorRetISR") = ObjProveedor.CveCuentaRetISR + ViewState("CveCuentaProveedorRetIVA") = ObjProveedor.CveCuentaRetIVA + ViewState("CveCuentaProveedorExtranjera") = ObjProveedor.CveCuentaProveedoresExtranjera + ViewState("CveCuentaProveedorComplementaria") = ObjProveedor.CveCuentaProveedoresComplementaria + + + 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("{1}", 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) + 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) + CargaRetISRConcepto(True) + + If ObjProveedor.DIOTCveTipoOperacion = 1 Then '03 - Prestación de Servicios Profesionales + DdlRetIVAConcepto.SelectedValueExist("1") + DdlRetISRConcepto.SelectedValueExist("1") ' honorarios + ElseIf ObjProveedor.DIOTCveTipoOperacion = 2 Then ' 06 - Arrendamiento de inmuebles + DdlRetIVAConcepto.SelectedValueExist("4") + DdlRetISRConcepto.SelectedValueExist("2") ' arrendamiento + ElseIf ObjProveedor.DIOTCveTipoOperacion = 3 Then ' 85 - Otros + DdlRetIVAConcepto.SelectedValueExist("2") ' flete pf + DdlRetIVAConcepto.SelectedValueExist("3") ' fletes pm + DdlRetISRConcepto.SelectedValueExist("1") ' honorarios + 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) + + + 'MONEDA PREFERENTE + If CveCompra <= 0 Then + If CveFactura <= 0 Then + DdlMoneda.SelectedValueExist(ObjProveedor.CveMonedaPreferente) + End If + CambiaMoneda(False) + End If + + + 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 {Estatus} 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:=DdlMoneda.SelectedValue.ToEntero, SelectTop:=-1, TipoDocto:=FiltroTipo) AndAlso ObjMovtos.DtResultados.Rows.Count > 0 Then + GVAnticipos.DataSource = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act'") + 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() + 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(UsuarioActual.Empresa.Funcionalidad(105) = "1") + + 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 + DdlPSAlias2.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa) + DdlPSAlias2.DataBind() + 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 Double = 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 Double = 0 + Dim IEPS As Double = 0 + Dim RetISR As Double = 0 + Dim RetIVA As Double = 0 + Dim PorcentajeIVA As Double = 0 + Dim PorcentajeIEPS As Double = 0 + Dim PorcentajeRetISR As Double = 0 + Dim PorcentajeRetIVA As Double = 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 + + ''AGREGA EN TABLA TEMPORAL + 'Dim DtPSTemp = TmpDT.Clone + 'Dim Row As DataRow = Nothing + + Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) + Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" + Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) + + 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 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").ToDouble <= 0 And ValorXML(node, "importe").ToDouble > 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.ToDouble + + '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("�", "") + 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 + + + If Version = "3.3" 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() + Exit For + 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").ToDouble, 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 +#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},
", 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},
", 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------------------ + Dim EstatusCredito As Integer = 0 + 'Credito Multiple + 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 + + '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 = "True" 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 SerieNueva As String = GlobalDTProveedorSucursales(CveProveedor).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 + + '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%
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 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 + + 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 + + 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.
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: {Dr("Clasificacion").ToString}.", 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: {Dr("Clasificacion").ToString}.", 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: {Dr("Clasificacion").ToString}.", 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 + + '------------------TERMINA VALIDACIONES------------------ + + '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 + 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() + + 'si hay necesidad de actualizar el globaldtps + If RegeneraPS Then + Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDT) + Hilo.Start() + 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 + + 'VALIDA IMPORTES + If Not ValidaTotalesGuardar() Then + Exit Sub + End If + + + 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 = 1.16 + Dim ListaMovimientosAlmacen As New List(Of Integer) + + 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) + + 'TIPO CAMBIO MANUAL CON COMPRA NUEVA + Dim TipoCambioGuardar = 1.0 + If DdlMoneda.SelectedValue.ToEntero > 1 Then + TipoCambioGuardar = If(DivTC.Visible, TxtTC.Text.ToDouble, LblTC.Text.Substring(3).ToDouble) + End If + TipoCambio = If(DivTC.Visible, TipoCambioGuardar, TipoCambio) + + Try + Dim FolioFijo As Integer = 0 + 'cheque + If DdlTipoTransaccion.SelectedValue = "1" 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)) + + 'seria de contado, solo cuando no tenga vinculado ningun anticipo + If RBLPago.SelectedValue.ToEntero = 2 AndAlso ArrAnticipos.Count = 0 Then 'Contado + + If RBLContado.SelectedValue = "1" Then + '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, TxtDocumentoImporte.Text.Trim.ToDouble, DdlMoneda.SelectedValue.ToEntero, 0.0, TxtDocumentoObservaciones.Text.Trim, "", True, True, -1, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCuentaTarjeta:=If(DivTarjeta.Visible, DdlTarjeta.SelectedValue.ToEntero, -1)) + ElseIf RBLContado.SelectedValue = "6" Then + '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, TxtDocumentoImporteCaja.Text.Trim.ToDouble, DdlMoneda.SelectedValue.ToEntero, 0.0, 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.CveEmpresa.Contiene(1, 119) And 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 AndAlso TxtTotal.Text.ToDecimal = 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 And Not (CveImportacion > 0 Or CveFlete > 0) Then + CveConceptoContableAlmacen = DdlOCVinculaInv.SelectedValue.ToEntero + End If + Else + CveConceptoContableAlmacen = 225 + End If + End If + End If + + + If RBLPago.SelectedValue.ToEntero = 4 And EstatusCredito.Contiene(1, 101) Then + CveEstatusFactura = 6 + End If + + '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) 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 + ErrorMovDev = guardardevolucion(ObjInventario, ObjCompras.CveCompra, TxtSubTotal.Text.ToDouble, TxtFecha.Text.Trim.ToDate) + End If + Dim ErrorDetalles As Boolean = False + ' Dim IDPoliza As Integer + Dim IDPolizaComprometido = 0 + Dim ErrorComprometido = False + + If CveImportacion > 0 Or CveFlete > 0 Then + + + Select Case CveConceptoContableAlmacen + Case 237 + Select Case FleteImportacionOpcion + Case 1 + Dim Dr As DataRow = Nothing + If ObjInventario.GetFletes(UsuarioActual.CveEmpresa, CveFlete) Then + If ObjInventario.DtResultados.Rows.Count > 0 Then + Dr = ObjInventario.DtResultados.Rows(0) + End If + End If + If Dr IsNot Nothing Then + If Not ObjInventario.UpdateFlete(CveFlete, Dr("Descripcion").ToString, Dr("Fecha").ToString.ToDate, -1, CveCompra, UsuarioActual.CveUsuario) Then + ErrorOC = True + End If + Else + 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) 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) Then + ErrorOC = True + End If + End Select + End Select + End If + + + If UsuarioActual.Empresa.UsaAC 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 + + ''[IPP] COMENTADO A MIRAS DE ELIMINAR 21-FEBRERO-2018 + ''VERIFICA SI TIENE DESCUENTO (AMORTIZACION) + 'If TxtDescuento.Text.ToDouble > 0 Then + ' DescuentoConIVA = TxtDescuento.Text.ToDecimal * 1.16D + + ' 'Valida que el descuento con iva cuadre en los totales + ' If Math.Abs(DescuentoConIVA - (Importe - TxtTotal.Text.ToDecimal)) < 0.02 Then + ' DescuentoConIVA = Importe - TxtTotal.Text.ToDecimal + ' ElseIf DescuentoConIVA <> (Importe - TxtTotal.Text.ToDecimal) Then + ' ErrorACMEnsaje.Append(" - Valida que el descuento con iva cuadre en los totales ") + ' ErrorAC = True + ' End If + + ' 'actualizo el idcuenta del presupuesto + ' If ObjContaAC.AddMovimiento(IdPoliza, tIdContaProveedor, 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 + ' ErrorACMEnsaje.Append(" - actualizo el idcuenta del presupuesto ObjContaAC.AddMovimiento 1") + ' ErrorAC = True + ' End If + ' Else + ' ErrorACMEnsaje.Append(" - actualizo el idcuenta del presupuesto ObjContaAC.AddMovimiento 2") + ' ErrorAC = True + ' End If + 'Else + '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 Then + + ''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.ToDouble, Row("PU").ToString.ToDouble, Row("IVA").ToString.ToDouble, Row("Total").ToString.ToDouble, Row("Descuento").ToString.ToDouble, + 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.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 = "True" AndAlso EsNoDeducible, True, False)) 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" Then + If Not ObjProductosServicios.UpdateProductosServiciosSAT(Row("CvePS").ToString().ToEntero(), Row("CveSATPS").ToString().ToEntero(), UsuarioActual.CveUsuario) Then + ErrorSATPS = True + 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.ToDouble) 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) 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 = 0.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 salida de consignacion + 'folio = objinventario.getfoliosiguiente(3, usuarioactual.cveempresa) + 'cvemovimientosalida = objinventario.addmovimiento(cvealmacenconsignacion, 3, ddlmoneda.selectedvalue.toentero, fecha, folio, usuarioactual.cveusuario, usuarioactual.cveempresa, cvecompra, -1, -1, -1) + 'if cvemovimientosalida <= 0 then + ' errormovinv = true + ' exit for + 'else + ' for each dr as datarow in dtinv.rows + ' if dr("cvealmacen").tostring.toentero = tcvealmacen then + ' if not objinventario.addmovimientodetalle(cvemovimientosalida, dr("cantidad").tostring.todouble, ddlum.selectedvalue.toentero, dr("cveps").tostring.toentero, 0, -1) then + ' errormovinv = true + ' exit for + + ' end if + ' end if + ' next + 'end if + + + '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)) + 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 + + importeconcepto = If(DdlMoneda.SelectedValue.ToEntero = 1, dr("pu").ToString.ToDouble, dr("pu").ToString.ToDouble * TipoCambioGuardar) + 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.ToDouble), CveCompraDetalle:=dr("CveCompraDetalle").ToString.ToEntero) Then + + ErrorMovInv = True + Exit For + End If + End If + Next + + End If + + 'agregamos la salida gasto + 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) + 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 = 0.0 + + 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)) + + If CveMovimientoInventario <= 0 Then + ErrorMovInv = True + Else + + Dim DtDetalle As New DataTable + Dim DtEquivalencias As DataTable + Dim CveProducto As Integer + Dim CantidadInv As Double + Dim PUInv As Double + Dim CveUnidad As Integer + Dim CostoIndirecto As Double + + 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.ToDouble + PUInv = Dr("PU").ToString.ToDouble + CostoIndirecto = Dr("CostoIndirectoAlmacen").ToString.ToDouble + + 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.ToDouble, -1, SerieLote:=drr("Serie").ToString, FechaCaducidad:=drr("FechaCaducidad").ToString.ToDate, CostoIndirecto:=Dr("CostoIndirectoAlmacen").ToString.ToDouble, 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) + 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.ToDouble * drUMBase("Cantidad").ToString.ToDouble / DtEquivalencias.FiltraParametros(String.Format("CveUM = {0}", CveUnidad)).Rows(0)("Cantidad").ToString.ToDouble + PUInv = PUInv * Dr("Cantidad").ToString.ToDouble / CantidadInv + CostoIndirecto = CostoIndirecto * Dr("Cantidad").ToString.ToDouble / CantidadInv + CveUnidad = CveUnidadBase + End If + End If + + 'si no es por serie lote + ImporteConcepto = If(DdlMoneda.SelectedValue.ToEntero = 1, PUInv, PUInv * 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.ToDouble), 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 + + + + If AplicarCostoIndirecto(ObjInventario, ObjCompras) Then + ErrorMovInv = True + End If + + 'Else + ' Alert("El tipo de cambio no esta actualizado. Por favor comuniquese con un asistente SIG.", TipoMensaje.MsgError) + ' 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 CveConceptoAfectacionContado As Integer = 17 'Pago Proveedores + 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 CveAcreedor As Integer + Dim CveColectiva As Integer = -1 + + 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 + CveAcreedor = -1 + + Else + 'cuando es contado + + Select Case RBLContado.SelectedValue + Case "1", "6" 'Proveedores + CveProveedorLocal = CveProveedor + CveProveedorConcepto = CveProveedor + CveAcreedor = -1 + Case "2" ' F y E + CveProveedorLocal = CveProveedor + CveProveedorConcepto = CveProveedor + CveAcreedor = -1 + CveIE = DDlCheques.SelectedValue.ToEntero + Case "3" ' Doctos + + CveProveedorConcepto = CveProveedor + + If DdlTipoCredito.SelectedValue.ToEntero = 2 Then + CveProveedorLocal = CveProveedor + CveProveedorConcepto = CveProveedor + CveAcreedor = -1 + CveColectiva = -1 + ' CveConceptoAfectacionContado = 55 + 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 + CveAcreedor = -1 + CveColectiva = -1 + ' CveConceptoAfectacionContado = 55 + CveConceptoAfectacion = 37 + Case "5" ' Acreedores + CveProveedorLocal = CveProveedor + CveProveedorConcepto = DdlAcreedor.SelectedValue.ToEntero + CveAcreedor = -1 + CveColectiva = -1 + 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 ImporteCapital As Decimal = 0 + ' Dim ImporteCapitalIVA As Decimal = 0 + + 'Dim ImporteInteres As Decimal = 0 + ' Dim ImporteInteresIVA As Decimal = 0 + + ' 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 + 'ObjIE.UpdateCreditosDetalle(CveCreditoDetalle, "01/01/2000".ToDate, -1, -1, -1, -1, -1, -1, Estatus) + + + + 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 tipoCambioPago As Decimal + Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

" + 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 CuentasContablesInvalidasSIG 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 + + Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" + + If UsuarioActual.CveEmpresa = 119 AndAlso (DdlPersonalReembolso.SelectedValue.ToEntero > 0 Or DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero > 0) Then + AutoConta = False + End If + + If (AutoConta Or UsuarioActual.Empresa.UsaAC) And ObjContaAC Is Nothing Then + ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa) + ObjContaAC.IniciaTransacSQL() + 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 + If CveIE > 0 AndAlso RBLPago.SelectedValue.ToEntero = 2 AndAlso RBLContado.SelectedValue = "4" Then + ConceptoPersonal = DdlDeudor.SelectedItem.ToString + importeDD = TxtContadoDeudor.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 + + + + '****** X Acreditar + 'IVA X Acreditar (14) + Dim importeIVAxAcreditar As Decimal = 0 + importeIVAxAcreditar = TxtIVA.Text.ToDecimal + + 'IEPS X Acreditar (25) + Dim ImporteIEPSxAcreditar As Decimal = 0 + ImporteIEPSxAcreditar = TxtIEPS.Text.ToDecimal + + 'Otros Impuestos (224) + Dim OtrosImpuestos As Decimal = 0 + OtrosImpuestos = TxtOtrosImpuestos.Text.ToDecimal + + 'RetIVA X Acreditar (15) + Dim importeRetIVAxAcreditar As Decimal = 0 + importeRetIVAxAcreditar = TxtRetIVA.Text.ToDecimal + + 'RetISR X Acreditar (16) + Dim importeRetISRxAcreditar As Decimal = 0 + importeRetISRxAcreditar = TxtRetISR.Text.ToDecimal + + + + '****** Movimientos Independientes + + 'Pago Proveedores (17) + Dim importePagoProv As Decimal = 0 + importePagoProv = sumaPagos + + 'If CveIE > 0 AndAlso ((RBLContado.SelectedValue = "2" AndAlso DdlFuncionarioEmpleado.SelectedValue.ToEntero > 0) Or (RBLContado.SelectedValue = "4" AndAlso DdlDeudor.SelectedValue.ToEntero > 0)) Then + ' importePagoProv = TxtDocumentoImporteFE.Text.ToDecimal + 'End If + + 'Compra (6) + 'Ya que es un foreach todo su proceso esta en el Case 6 + + '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 + + '************************************************************************************************************************** + + If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then + tipoCambioActual = GlobalTipoCambio(FechaMovimiento).ToString.ToDecimal + tipoCambioActual = If(DivTC.Visible, TipoCambio.ToDecimal, tipoCambioActual) + tipoCambioPago = GlobalTipoCambio(TxtFechaPago.Text.ToDate).ToString.ToDecimal + Else + tipoCambioActual = 1 + tipoCambioPago = 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 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 CveCuenta 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 = If(Row("Multiplicador").ToString.ToEntero = 1, 1, -1) + Dim Referencia As String = $"{TxtSerie.Text}-{TxtFolio.Text}" ' concatenation interpolation + Dim PorcentajeImpuesto As Decimal = 0 + + + Select Case ConceptoContable + + + + + Case 17 'Pago Proveedores + + importeMovimiento = importePagoProv + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + IdCtaContable = CtaProveedor + CveCuenta = CveCuentaProveedor + + + If RBLPago.SelectedValue.ToEntero = 4 And EstatusCredito.Contiene(2, 102) Then 'SI ES CRÉDITO Y ESTA PAGADO + + Dim IdSegmentoNegocio As Integer = -1 + 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}", Row2("CveClasificacion").ToString.ToEntero, Row2("CveSubProyecto").ToString.ToEntero, Row2("CveTipoGasto").ToString.ToEntero)).ToString.ToDecimal + 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero + Else + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero + End If + End If + End If + + + + + 'SEGMENTO DE NEGOCIO + + Dim drT As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero).FiltroPrimero(String.Format("CveSubProyecto = {0} ", Row2("CveSubProyecto").ToString.ToEntero)) + If drT IsNot Nothing Then + IdSegmentoNegocio = drT("IdSegNeg").ToString.ToEntero + End If + + 'AGREGA MOVIMIENTO + If importeMovimiento <> 0 Then + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + 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, Referencia, 6, Concepto, FechaMovimiento, IdCtaContable, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=ImporteSubCreMN, ImporteME:=If(tipoCambioActual = 1, 0, ImporteSubCre), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, Referencia, 41, Concepto, FechaMovimiento, CtaProveedorAcreedores, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + 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, Referencia, 41, Concepto, FechaMovimiento, CtaProveedorAcreedores, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=importeMNIn, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoIn), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoIn, Referencia, 50, Concepto, FechaMovimiento, ViewState("IdCtaContDocsXPagar").ToString.ToEntero(), IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=CveClasificacionDT, CveSubProyecto:=CveSubProyectoDT, ImporteMX:=importeMNIn, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoIn), CveCuenta:=CveCuenta, CveTipoGasto:=CveTipoGastoDT, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + + End If + End If + + + + + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + + If tipoCambioActual = 1 Then + IdCtaContable = CtaProveedor + CveCuenta = CveCuentaProveedor + Else + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0) Then 'Cuando tiene complementaria lo dividimos en dos + importeMN = importeMovimiento + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, 0, Referencia, 201, Concepto, FechaMovimiento, IdCtaContable, -1, CveIE, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * tipoCambioActual - importeMovimiento, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + End If + + Case 30 'Bancos + importeMovimiento = importeBanco + importeCajaChica 'Uno de los dos debe ser 0 + importeMN = importeMovimiento * tipoCambioPago * Multiplicador + IdCtaContable = IdCuentaBancaria + CveCuenta = CveCuentaBancaria + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + '' falta complementaria + + Case 19 'IVA Acreditable + If UsuarioActual.Empresa.Funcionalidad(521) = "1" Then + If importePagoProv = importeProv Then + importeMovimiento = TxtIVA.Text.ToDecimal + Else + importeMovimiento = 0 + End If + Else + importeMovimiento = importeIVAAcreditable + End If + + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + + PorcentajeImpuesto = PorcentajeIVA + IdCtaContable = If(IdCtaIVAAcreditable > 0, IdCtaIVAAcreditable, 0) + + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) And Not IdCtaContable > 0 Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditableSIG").ToString.ToEntero + End If + End If + + 'Agregamos el Opuesto del 19 -> 14 + If importeMovimiento <> 0 Then + Dim IdCtaIva As Integer = 0 + Dim CveCuentaIVA As Integer = 0 + IdCtaIva = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) + + If ObjConta.GetRetCuenta(14, UsuarioActual.CveEmpresa) And Not IdCtaIva > 0 Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaIva = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditar").ToString.ToEntero + CveCuentaIVA = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero + End If + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 14, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaIva, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVA, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + Case 14 'IVA X Acreditar + importeMovimiento = importeIVAxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + PorcentajeImpuesto = PorcentajeIVA + IdCtaContable = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) + If 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero + End If + End If + Case 25 'IEPS X Acreditar + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + importeMovimiento = ImporteIEPSxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditar").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditarSIG").ToString.ToEntero + End If + End If + End If + + Case 224 'Otros impuestos + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + importeMovimiento = OtrosImpuestos + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + IdCtaContable = If(UsuarioActual.CveEmpresa = 119, 1171, -1) + CveCuenta = -1 + End If + Case 26 'IEPS Acreditable + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + importeMovimiento = ImporteIEPSAcreditable + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSAcreditable").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSAcreditableSIG").ToString.ToEntero + End If + End If + + 'Agregamos el Opuesto del 26 -> 25 + If importeMovimiento <> 0 Then + Dim IdCtaIEPS As Integer = 0 + Dim CveCuentaIEPS As Integer = 0 + If ObjConta.GetRetCuenta(25, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaIEPS = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditar").ToString.ToEntero + CveCuentaIEPS = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxAcreditarSIG").ToString.ToEntero + End If + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 25, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaIEPS, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIEPS, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + + End If + Case 22 'RetIVA Acreditable Honorarios/Serv. Prof. + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then + importeMovimiento = importeRetIVAAcreditable + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(308).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(308).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + + 'Agregamos el Opuesto del 22 -> 15 + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 15, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + 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 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then + importeMovimiento = importeRetIVAxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(307).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(307).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + Case 184 'RetIVA Acreditable Fletes P.F + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then + importeMovimiento = importeRetIVAAcreditable + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(310).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(310).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + + 'Agregamos el Opuesto del 184 -> 183 + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 183, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + End If + End If + End If + Case 183 'RetIVA X Acreditar Fletes P.F + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then + importeMovimiento = importeRetIVAxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(309).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(309).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + Case 248 'RetIVA X Acreditar Arrendamiento + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 AndAlso DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then + importeMovimiento = importeRetIVAxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(313).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(313).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + + End If + End If + Case 186 'RetIVA Acreditable Fletes P.M. + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then + importeMovimiento = importeRetIVAAcreditable + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(312).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(312).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + + 'Agregamos el Opuesto del 186 -> 185 + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 185, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + End If + End If + End If + Case 185 'RetIVA X Acreditar Fletes P.M. + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then + importeMovimiento = importeRetIVAxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(311).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(311).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + Case 249 'RetIVA Acreditable Arrendamiento + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 AndAlso DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then + importeMovimiento = importeRetIVAAcreditable + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(314).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(314).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + End If + + End If + Case 23 'RetISR Acreditable + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then + importeMovimiento = importeRetISRAcreditable + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(316).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(316).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + + 'Agregamos el Opuesto del 23 -> 16 + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 15, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + 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 = 1 Then + importeMovimiento = importeRetISRxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(315).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(315).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + Case 243 'RetISR X Acreditar Terceros y Arrendamiento + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then + importeMovimiento = importeRetISRxAcreditar + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(317).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(317).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + End If + End If + Case 244 'RetISR Acreditable Terceros y Arrendamiento + If Not DdlTipoComprobante.SelectedValue.Contiene("Ant") Then + If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then + importeMovimiento = importeRetISRAcreditable + importeMN = Math.Round(importeMovimiento, 2) * tipoCambioPago * Multiplicador + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(318).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(318).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + 'Agregamos el Opuesto del 244 -> 243 + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 243, Concepto + If(tipoCambioActual > 1, $" TC: {tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}", ""), FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento * tipoCambioActual, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioPago} ${importeMovimiento.FormatoNumero(2)}" + End If + End If + Case 64 'Ganancia + If tipoCambioActual <> 1 AndAlso TxtFechaPago.Text <> TxtFecha.Text Then + IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + If tipoCambioPago < tipoCambioActual Then + importeMovimiento = Math.Abs(tipoCambioPago - tipoCambioActual) * importePagoProv + importeMovimiento -= Math.Abs(tipoCambioPago - tipoCambioActual) * importeIVAAcreditable + importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetIVAAcreditable + importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetISRAcreditable + importeMN = importeMovimiento + End If + Else + importeMovimiento = 0 + End If + + Case 65 'Perdida + If tipoCambioActual <> 1 AndAlso TxtFechaPago.Text <> TxtFecha.Text Then + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + If tipoCambioActual < tipoCambioPago Then + importeMovimiento = Math.Abs(tipoCambioPago - tipoCambioActual) * importePagoProv + importeMovimiento -= Math.Abs(tipoCambioPago - tipoCambioActual) * importeIVAAcreditable + importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetIVAAcreditable + importeMovimiento += Math.Abs(tipoCambioPago - tipoCambioActual) * importeRetISRAcreditable + importeMN = importeMovimiento + End If + Else + importeMovimiento = 0 + End If + + Case 6 'Compra + + If RBLPago.SelectedValue.ToEntero = 4 Then + Exit Select 'Es credito el concepto 6 se agrega en CASE 17 + End If + + If 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 ObjConta.GetRetCuenta(49, Row2("CveActivoFijo").ToString.ToEntero) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijo").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijoSIG").ToString.ToEntero + End If + End If + + If importeMovimiento <> 0 Then + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString) + CveCuentaContabilizacion = 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + Next + End If + + 'LIMPIA + importeMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 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 + 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 + 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(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 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero + End If + End If + If importeMovimiento <> 0 Then + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 68, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveMovimientoAlmacen:=CveMovimientoInventario, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + Next + End If + End If + + 'LIMPIA + importeMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 0 + + ''FLETES + 'If UsuarioActual.CveEmpresa.Contiene(119) And UsuarioActual.Empresa.UsaInventarios And DdlTipoComprobante.SelectedValue <> "NC" And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And CveConceptoContableAlmacen.Contiene(237, 240) Then + + 'End If + Dim CostoIndirectoAcum176 As Decimal = 0 + 'INV [MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA) ] + If UsuarioActual.CveEmpresa.Contiene(1, 119) And UsuarioActual.Empresa.UsaInventarios And Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV", "Ant") And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" And 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 + + Select Case ConceptoContabilizacion + Case 176 + ConceptoContabilizacionME = 228 + ConceptoContabilizacionMEComp = 229 + Case 205 + ConceptoContabilizacionME = 230 + ConceptoContabilizacionMEComp = 231 + 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 + + + '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 + 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}" + 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 + Dim TCAjuste As Decimal = ObjOC.DtResultados.FiltroPrimeroValor("TipoCambioAjuste").ToDecimal + 'RMF. falta verificar el costo indirecto de la OC + If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then + ImporteCI176 = ObjOC.DtResultados.FiltroPrimeroValor("ImporteCI228").ToDecimal + CostoIndirectoAcum176 += ImporteCI176 + '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, CveCuenta:=CveCuenta, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, TipoCambio:=TCAjuste, Contabilizable:=SeContabiliza) Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, Importe229, Referencia, ConceptoContabilizacionMEComp, Concepto, FechaMovimiento, IdCtaContableMEComp, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=ImporteMN229, ImporteME:=ImporteME229, CveCuenta:=CveCuenta, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, TipoCambio:=TCAjuste, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + Else + ErrorPrepoliza = True + Exit For + End If + Else + CostoIndirectoAcum176 += ImporteCI176 + '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, CveCuenta:=CveCuenta, CveOCDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, 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 + 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 + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {CveClasificacionCostoOC}").ToString.ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"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, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + End If + Case 205, 237, 240 + 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), CveCuenta:=CveCuenta, 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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + Else + ErrorPrepoliza = True + End If + Else + + 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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + End Select + 'End If + + End If + + + 'NC CON PRODUCTOS - CUENTA PUENTE + If UsuarioActual.CveEmpresa.Contiene(119) AndAlso UsuarioActual.Empresa.UsaInventarios AndAlso DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") AndAlso Not UsuarioActual.Empresa.Funcionalidad(126) = "1" 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 ISNULL(CveTipoPS,0) = 2").ToString.ToDecimal + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + + Dim ConceptoContabilizacionNC = 225 + + If 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 Then + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContabilizacionNC, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + + End If + + Dim ContienePSNeteoBonif As Boolean = False + For Each Dr As DataRow In TmpDT.Rows + If Dr("CveClasificacion").ToString.ToEntero.Contiene(20319) 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 ").ToString.ToDecimal + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + If importeMovimiento <> 0 Then + Dim IdCtaContableDescCompra As Integer = UsuarioActual.Empresa.Funcionalidad(405).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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) 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), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + Else + ErrorPrepoliza = True + End If + End If + End If + + End If + + + + If 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 + 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 + DT.AcceptChanges() + DtAlmacenes.Dispose() + + 'QUITA 1-[MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA)] 2-[NC CON PRODUCTOS] + If UsuarioActual.CveEmpresa.Contiene(1, 119) And UsuarioActual.Empresa.UsaInventarios And Not UsuarioActual.Empresa.Funcionalidad(126) = "1" Then + DT = DT.FiltraParametros("ISNULL(CveTipoPS,0) <> 2") + End If + + Dim DTDistinct = DT.Copy + If UsuarioActual.Empresa.Funcionalidad(126) = "1" Then + DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF, 0) <> 2", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"}) + Else + DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF,0) <> 2 And ISNULL(CveAlmacen,0) = 0 And ISNULL(AplicaCostoIndirecto,0) <> 1", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "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 Then + DTDistinct.Clear() + 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(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 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero + Else + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero + End If + End If + End If + + 'SEGMENTO DE NEGOCIO + Dim IdSegmentoNegocio As Integer = -1 + Dim drT As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero).FiltroPrimero(String.Format("CveSubProyecto = {0} ", Row2("CveSubProyecto").ToString.ToEntero)) + If drT IsNot Nothing Then + IdSegmentoNegocio = drT("IdSegNeg").ToString.ToEntero + End If + + 'AGREGA MOVIMIENTO + If importeMovimiento.RoundSQL <> 0 Then + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + 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 + + Dim usacomplementariaProveedor As Boolean = False + usacomplementariaProveedor = If(tipoCambioActual > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), 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, TipoMovimiento, importeMovimiento, Referencia, 266, Concepto, FechaMovimiento, tidctacon, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, 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 ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, tcvecon, Concepto, FechaMovimiento, tidctacon, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveTipoGasto:=Row2("CveTipoGasto").ToString.ToEntero, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + + + + + End If + + Next + End If + End If + + + 'LIMPIA + importeMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 0 + End If + Case 5 'Proveedores + If Not DdlTipoComprobante.SelectedValue.Contiene("NC", "DEV") Then + + importeMovimiento = importeProv + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + + If tipoCambioActual = 1 Then + IdCtaContable = CtaProveedor + CveCuenta = CveCuentaProveedor + Else + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsuarioActual.CveEmpresa = 119) Then 'Cuando tiene complementaria lo dividimos en dos Then + importeMN = importeMovimiento + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, 0, Referencia, 201, Concepto, FechaMovimiento, IdCtaContable, -1, CveIE, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=importeMovimiento * tipoCambioActual - importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + End If + End If + + Case 59 'Documentos + importeMovimiento = importeCreditos + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + If 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero + End If + End If + End If + + Case 37 'Deudores + 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 + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + IdCtaContable = CtaProveedorDeudores + CveCuenta = CveCuentaProveedorDeudores + + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + Next + Else + For Each rw As GridViewRow In GvDeudores.Rows + If rw.FCCheckBox("Chk").Checked Then + importeMovimiento = rw.FCTextBox("TxtSaldoDeudor").Text.ToDecimal + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + IdCtaContable = CtaProveedorDeudores + CveCuenta = CveCuentaProveedorDeudores + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 254, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + Next + End If + + importeMovimiento = 0 + + Case 41 'Acreedores + importeMovimiento = importeAcreedores + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + + IdCtaContable = CtaProveedorAcreedores + CveCuenta = CveCuentaProveedorAcreedores + + Case 42 'Acreedores + importeMovimiento = importeAcreedoresTarjeta + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + IdCtaContable = CtaProveedorAcreedores + CveCuenta = CveCuentaProveedorAcreedores + + Case 18 'NC - Notas de Credito + importeMovimiento = importeNC + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + If tipoCambioActual > 1 Then Concepto += $" TC:{tipoCambioActual} ${importeMovimiento.FormatoNumero(2)}" + IdCtaContable = CtaProveedor + CveCuenta = CveCuentaProveedor + If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + End If + + If importeMovimiento <> 0 Then + GuardoConcepto18 = True + If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then + + 'PROVISION + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMN - importeMovimiento, Referencia, 234, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN - importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) 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 importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador + Dim TipoCambioFactura = Gvr.DataKey("TipoCambio").ToDecimal + + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, False, importeMovimientoNC, Referencia, 17, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioFactura, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, False, importeMNNC - importeMovimientoNC, Referencia, 206, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioFactura, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + Else + ErrorPrepoliza = True + Exit For + End If + + + importeMNNC = importeMovimientoNC * TipoCambioFactura * Multiplicador + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, True, importeMNNC - importeMovimientoNC, Referencia, 235, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + Else + ErrorPrepoliza = True + Exit For + End If + + ' FLUCTUACION CAMBIARIA + If tipoCambioActual <> TipoCambioFactura Then + importeMovimiento = (importeMovimientoNC * TipoCambioFactura) - (importeMovimientoNC * tipoCambioActual) + + If importeMovimiento > 0 Then + ConceptoContable = 64 + TipoMovimiento = True + IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + ElseIf importeMovimiento < 0 Then + ConceptoContable = 65 + TipoMovimiento = False + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + End If + + importeMovimiento = importeMovimiento.Abs.RoundSQL() + importeMN = importeMovimiento + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + End If + End If + + + ObjConta.PrePolizaUnificacion(CvePrePoliza, CvePrePolizaTemp) + End If + Next + + If ErrorPrepoliza Then + Exit Select + End If + + Else + IdCtaContable = CtaProveedor + CveCuenta = CveCuentaProveedor + + If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, 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(CvePrePolizaTemp, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoNC), CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaTemp, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=Gvr.DataKey("CveCompra").ToEntero, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimientoNC), CveCuenta:=CveCuenta, 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 ObjConta.GetRetCuenta(ConceptoContable, CvePersonal) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContPersonal").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContPersonalSIG").ToString.ToEntero + End If + End If + + Case 21 'Anticipo + + If ArrAnticipos.Count > 0 Then + + + Dim CtaIvaxAcreditar As Integer = 0 + Dim CtaIvaAcreditable As Integer = 0 + Dim CveCuentaIvaxAcreditar As Integer = 0 + Dim PorcentajeImpuestoAnticipo = PorcentajeIVA + CtaIvaxAcreditar = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) + CtaIvaAcreditable = If(IdCtaIVAAcreditable > 0, IdCtaIVAAcreditable, 0) + If ObjConta.GetRetCuenta(14, UsuarioActual.CveEmpresa) And Not CtaIvaxAcreditar > 0 Then + If ObjConta.DtResultados.Rows.Count > 0 Then + CtaIvaxAcreditar = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditar").ToString.ToEntero + CveCuentaIvaxAcreditar = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero + End If + End If + If ObjConta.GetRetCuenta(19, UsuarioActual.CveEmpresa) And Not CtaIvaAcreditable > 0 Then + If ObjConta.DtResultados.Rows.Count > 0 Then + CtaIvaAcreditable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero + End If + End If + + '** PRUEBA CUANDO SE AMORTIZA NC ANTES DE QUE SE REGISTRE NO DEBE TENER CONCEPTO 19 ** JMURUAM 01/06/2017 SE HIZO ESTO PARA LA FACTURA HRFA-8012831 DE VIGILANCIA + 'Dim CtaIvaAcreditable As Integer = 0 + 'If ObjConta.GetRetCuenta(19, UsuarioActual.CveEmpresa) Then + ' If ObjConta.DtResultados.Rows.Count > 0 Then + ' CtaIvaAcreditable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero + ' End If + 'End If + + For Each Ant As Anticipos In ArrAnticipos + + 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 + CveCuenta = CveCuentaProveedor + Case "Egsc" + ConceptoContableAnticipo = 21 + IdCtaContable = CtaProveedorAnticipos + CveCuenta = CveCuentaProveedorAnticipos + + Case "DD" + ConceptoContableAnticipo = 37 + IdCtaContable = CtaProveedorDeudores + CveCuenta = CveCuentaProveedorDeudores + Case "Ant" + ConceptoContableAnticipo = 265 + ConceptoContableAnticipoComplementaria = 266 + CveCompraNC = Ant.CveCompra + IdCtaContable = CtaProveedorAnticipos + CveCuenta = CveCuentaProveedorAnticipos + End Select + + importeMovimiento = Ant.Importe + importeMN = importeMovimiento * tipoCambioActual * Multiplicador + + If importeMovimiento <> 0 Then + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidas.Append("
" & 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 And UsuarioActual.CveEmpresa.Contiene(119) Then + Dim importeMovimientoNC = Ant.Importe + Dim importeMNNC = 0.0D + Dim TipoCambioNC = Ant.TCCompra + + importeMNNC = importeMovimientoNC * TipoCambioNC * Multiplicador + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoNC, Referencia, 60, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMNNC - importeMovimientoNC, Referencia, 235, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + Else + ErrorPrepoliza = True + Exit For + End If + + importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMNNC - importeMovimientoNC, Referencia, 206, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, 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 + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + ElseIf importeMovimiento < 0 Then + ConceptoContable = 65 + TipoMovimiento = False + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + 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, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + End If + End If + + ElseIf ConceptoContableAnticipo.Contiene(265) And DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then + Dim importeMovimientoNC = Ant.Importe + Dim importeMNNC = 0.0D + Dim TipoCambioNC = Ant.TCCompra + + importeMNNC = importeMovimientoNC * TipoCambioNC * Multiplicador + IdCtaContable = CtaProveedorAnticiposExtranjera + CveCuenta = CveCuentaProveedorAnticiposExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimientoNC, Referencia, 265, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + IdCtaContable = CtaProveedorAnticiposComplementaria + CveCuenta = CveCuentaProveedorAnticiposComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMNNC - importeMovimientoNC, Referencia, 266, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=Ant.CveCompra, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=TipoCambioNC, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + Else + ErrorPrepoliza = True + Exit For + End If + + If TxtTotal.Text.ToDouble > 0 Then + importeMNNC = importeMovimientoNC * tipoCambioActual * Multiplicador + IdCtaContable = CtaProveedorExtranjera ' CtaProveedorAnticiposExtranjera + CveCuenta = CveCuentaProveedorExtranjera 'CveCuentaProveedorAnticiposExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimientoNC, Referencia, 272, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, CveCompraAmortizacion:=CveCompraNC, Contabilizable:=SeContabiliza) Then + IdCtaContable = CtaProveedorExtranjera 'CtaProveedorAnticiposComplementaria + CveCuenta = CveCuentaProveedorExtranjera 'CveCuentaProveedorAnticiposComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMNNC - importeMovimientoNC, Referencia, 206, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMNNC - importeMovimientoNC, ImporteME:=importeMovimientoNC, TipoCambio:=tipoCambioActual, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + Else + ErrorPrepoliza = True + Exit For + End If + + If Ant.TipoMovto.Contiene("Ant") Then + Dim PorcentajePagoAnt As Decimal = importeMovimientoNC / If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDecimal) + Dim ImporteIVA As Decimal = Math.Round(PorcentajePagoAnt * TxtIVA.Text.ToDecimal, 2) + + 'Agregamos el 14 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteIVA, Referencia, 14, Concepto, FechaMovimiento, CtaIvaxAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), CveCuenta:=CveCuentaIvaxAcreditar, PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + 'Agregamos el 19 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, ImporteIVA, Referencia, 19, Concepto, FechaMovimiento, CtaIvaAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + Dim ImporteIEPS As Decimal = Math.Round(PorcentajePagoAnt * TxtIEPS.Text.ToDecimal, 2) + + 'Agregamos el 25 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteIEPS, Referencia, 25, Concepto, FechaMovimiento, CtaIvaxAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), CveCuenta:=CveCuentaIvaxAcreditar, PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + 'Agregamos el 26 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, ImporteIEPS, Referencia, 26, Concepto, FechaMovimiento, CtaIvaAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + 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 + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + ElseIf importeMovimiento < 0 Then + ConceptoContable = 65 + TipoMovimiento = False + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + 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, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + End If + End If + End If + + Else + + + Dim usacomplementariaAnticipo As Boolean = False + usacomplementariaAnticipo = If(Ant.TCCompra > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), True, False) + Dim TipoCambioAnt = Ant.TCCompra + + + Dim ImporteAnt As Decimal = importeMovimiento + Dim ImporteAntMN As Decimal = ImporteAnt * TipoCambioAnt + If usacomplementariaAnticipo Then + IdCtaContable = CtaProveedorAnticiposComplementaria + CveCuenta = CveCuentaProveedorAnticiposComplementaria + ImporteAntMN = TipoCambioAnt * ImporteAnt - ImporteAnt + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteAnt, Referencia, 266, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=ImporteAntMN, ImporteME:=ImporteAnt, TipoCambio:=TipoCambioAnt, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + ImporteAntMN = ImporteAnt + End If + + If TipoCambioAnt > 1 Then + IdCtaContable = CtaProveedorAnticiposExtranjera + CveCuenta = CveCuentaProveedorAnticiposExtranjera + End If + + 'Agregamos el 21/37/60 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteAnt, Referencia, ConceptoContableAnticipo, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompraNC, CveCompraAmortizacion:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteAntMN, ImporteME:=If(tipoCambioActual = 1, 0, ImporteAnt), TipoCambio:=TipoCambioAnt, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + If TxtTotal.Text.ToDouble > 0 Then + Dim IdCtaContablePago As Integer = CtaProveedor + Dim CveCuentaPago As Integer = CveCuentaProveedor + Dim usacomplementariaProveedor As Boolean = False + usacomplementariaProveedor = If(tipoCambioActual > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), True, False) + If usacomplementariaProveedor Then + Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}" + importeMN = tipoCambioActual * importeMovimiento - importeMovimiento + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 201, Concepto, FechaMovimiento, CtaProveedorComplementaria, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaProveedorComplementaria, TipoCambio:=tipoCambioActual, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + importeMN = importeMovimiento + End If + + If tipoCambioActual > 1 Then + IdCtaContablePago = CtaProveedorExtranjera + CveCuentaPago = CveCuentaProveedorExtranjera + End If + + 'Agregamos el 17 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 17, Concepto, FechaMovimiento, IdCtaContablePago, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuentaPago, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + End If + ' FLUCTUACION CAMBIARIA + If tipoCambioActual <> TipoCambioAnt Then + Dim importeFluctuacion = (ImporteAnt * tipoCambioActual) - (ImporteAnt * TipoCambioAnt) + + If importeFluctuacion > 0 Then + ConceptoContable = 64 + TipoMovimiento = True + IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + ElseIf importeFluctuacion < 0 Then + ConceptoContable = 65 + TipoMovimiento = False + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + End If + + importeFluctuacion = importeFluctuacion.Abs.RoundSQL() + If importeFluctuacion <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeFluctuacion, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeFluctuacion, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + End If + 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 PorcentajePagoAnt As Decimal = importeMovimiento / If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDecimal) + Dim ImporteIVA As Decimal = Math.Round(PorcentajePagoAnt * TxtIVA.Text.ToDecimal, 2) + + 'Agregamos el 14 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteIVA, Referencia, 14, Concepto, FechaMovimiento, CtaIvaxAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), CveCuenta:=CveCuentaIvaxAcreditar, PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + + 'Agregamos el 19 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, ImporteIVA, Referencia, 19, Concepto, FechaMovimiento, CtaIvaAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=ImporteIVA * tipoCambioActual * Multiplicador, ImporteME:=If(tipoCambioActual = 1, 0, ImporteIVA), PorcentajeImpuesto:=PorcentajeImpuestoAnticipo, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + + End If + + ''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.PrePolizaSimplificacion(Ant.CvePrePoliza, UsuarioActual.CveEmpresa) Then + ' ErrorPrepoliza = True + ' Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) + ' End If + 'End If + + Next + importeMovimiento = 0 + + End If + End Select + + If ErrorPrepoliza Then + Exit For + End If + + If importeMovimiento <> 0 Or (ConceptoContable.Contiene(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("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'COnta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=Math.Round(importeMN, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, TipoCambio:=tipoCambioActual, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + End If + + End If + + Next + + 'EMPIEZA REFACTURACION + If 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 UsuarioActual.Empresa.Funcionalidad(220) <> "" Then + If Not ObjConta.PrePolizaSimplificacion(CvePrePoliza, UsuarioActual.CveEmpresa) Then + ErrorPrepolizaDescuadre = True + End If + End If + + If 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.UsaContabilidad 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:
{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 + ' CveIE = ObjIE.AddBancos_IE(DdlCuenta.SelectedValue.ToEntero, DdlTipoTransaccion.SelectedValue.ToEntero, TxtFecha.Text.Trim.ToDate, TxtDocumentoFolio.Text.Trim, DdlProveedor.SelectedItem.Text.Trim, TxtDocumentoImporte.Text.Trim.ToDouble, 1, 0.0, TxtDocumentoObservaciones.Text.Trim, True, True, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + If CveIE > 0 Then + + 'inserto los movimientos de la conta para abonar al saldo + + 'Se agregamovimiento de pago de proveedor + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteCompra, " ", CveConceptoAfectacionContado, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then + ErrorMovtosCxP = True + End If + + 'Compra + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtSubTotal2.Text.ToDecimal, " ", 30, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then + ErrorMovtosCxP = True + End If + + 'IVA por Acreditar . siempre se registra aunque sea cero + If Not ErrorMovtosCxP Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal, " ", 19, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then + ErrorMovtosCxP = True + End If + End If + + If Not ErrorMovtosCxP AndAlso TxtRetIVA.Text.ToDouble > 0 Then + 'Agrego el RetIVA + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then + ErrorMovtosCxP = True + End If + End If + + If Not ErrorMovtosCxP AndAlso TxtRetISR.Text.ToDouble > 0 Then + 'Agrego el RetIVA + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva) Then + ErrorMovtosCxP = True + End If + 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=rw.DataKey("CveIE").ToString.ToEntero, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, 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 Anticipos In ArrAnticipos + CveCompraNC = CveCompra + Dim CveConceptoPago As Integer = 17 + 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, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, 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 + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoCompra, Ant.Importe, " ", CveConceptoPago, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=Ant.CveIE, CveColectiva:=CveColectiva, ImporteMX:=Ant.Importe) Then + ErrorMovtosCxP = True + End If + PorcentajePago = (Ant.Importe) / TxtTotal.Text.ToDecimal + + 'IVA por Acreditar . siempre se registra aunque sea cero + If Not ErrorMovtosCxP Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", 19, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True + End If + + 'Agrego el RetIVA + If Not ErrorMovtosCxP AndAlso TxtRetIVA.Text.ToDouble > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True + End If + + 'Agrego el RetISR + If Not ErrorMovtosCxP AndAlso TxtRetISR.Text.ToDouble > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True + End If + 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 + 'Siempre: Se agrega IVA aunque sea cero + If TxtIVA.Text.ToDouble <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then + ErrorMovtosIVA = True + End If + End If + + 'Se agregan las Ret IVA + If TxtRetIVA.Text.ToDouble <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then + ErrorMovtosRetIVA = True + End If + End If + + 'Se agregan las Ret ISR + If TxtRetISR.Text.ToDouble > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetISR, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then + ErrorMovtosRetISR = True + End If + End If + + 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 + + 'CvePrePoliza = ObjConta.AddPrePolizas("Banc", 2, ImporteAPagarFE, ImporteAPagarFE, DdlMoneda.SelectedValue.ToEntero, TxtFecha.Text.ToDate, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + If CvePrePoliza > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImportePagar, " ", 29, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CvePersonal:=DdlFuncionarioEmpleado.SelectedValue.ToEntero, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveColectiva:=CveColectiva, CveIE:=CveIE, ImporteMX:=ImportePagar) Then + ErrorMovtosCxP = True + End If + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImportePagar, " ", 17, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CvePersonal:=DdlFuncionarioEmpleado.SelectedValue.ToEntero, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveColectiva:=CveColectiva, CveIE:=CveIE, ImporteMX:=ImportePagar) Then + ErrorMovtosCxP = True + End If + + + Dim PorcentajePago As Decimal = (ImportePagar) / TxtTotal.Text.ToDecimal + + 'IVA por Acreditar . siempre se registra aunque sea cero + If Not ErrorMovtosCxP Then + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", 19, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True + + End If + + If Not ErrorMovtosCxP AndAlso TxtRetIVA.Text.ToDouble > 0 Then + 'Agrego el RetIVA + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True + + End If + + If Not ErrorMovtosCxP AndAlso TxtRetISR.Text.ToDouble > 0 Then + 'Agrego el RetISR + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then ErrorMovtosCxP = True + + End If + + + 'sino alcanzo a cubrir se regitran los ivas por acreditar + If TxtTotal.Text.ToDouble - ImportePagar > 0 Then + PorcentajePago = (TxtTotal.Text.ToDecimal - ImportePagar) / TxtTotal.Text.ToDecimal + 'Movimiento, se omite, porque se esta registrando la totalidad de la deuda + 'If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtTotal.Text.ToDouble - ImporteAnticipo, " ", 5, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle) Then + ' ErrorMovtosCxP = True + 'End If + 'Siempre: Se agrega IVA aunque sea cero + If TxtIVA.Text.ToDouble <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, TxtIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtIVA.Text.ToDecimal * PorcentajePago) Then + ErrorMovtosIVA = True + End If + End If + + 'Se agregan las Ret IVA + If TxtRetIVA.Text.ToDouble <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetIVA.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetIVA, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetIVA.Text.ToDecimal * PorcentajePago) Then + ErrorMovtosRetIVA = True + End If + End If + + 'Se agregan las Ret ISR + If TxtRetISR.Text.ToDouble > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TxtRetISR.Text.ToDecimal * PorcentajePago, " ", CveConceptoRetISR, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorLocal, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=TxtRetISR.Text.ToDecimal * PorcentajePago) Then + ErrorMovtosRetISR = True + End If + End If + + End If + + 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 + 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 + + + If tDTAcarreos.Rows.Count > 0 Then + If TotAcarreos = TxtSubTotal.Text.ToDouble Then + 'ACARREOS + For Each tDTAcar As DataRow In tDTAcarreos.Rows + If Not ObjAcar.UpdatePreEstimacion(CInt(tDTAcar("CvePreEstimacion")), CveCompra) Then + ErrorAddAcarreos = True + Exit For + End If + Next + Else + ErrorAddAcarreos = 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 + + 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, "", 17, "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.
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.
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.
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.
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.
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.
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.
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.
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 + ErrorOC = 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) 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 + ObjContaAC.AjustaPoliza(IdPoliza) + Msg.AppendFormat("

Ver Póliza", IdPoliza) + End If + + If CveMovimientoInventario > 0 Then + Dim TempParametros = Encripta(String.Format("OP=Alm&CveMovimiento={0}", CveMovimientoInventario)) + Msg.AppendFormat("
Ver Movimiento de Almacen", CveMovimientoInventario) + Msg.AppendFormat("
Imprimir Entrada Almacen", TempParametros) + End If + + ObjCompras.UpdateCompraPrePoliza(TxtFecha.Text.ToDate, PolizaFolio.ToString, IdPoliza, CvePrePoliza, CveCompra, 0) + + If EntregaDirecta Then + Msg.AppendFormat($"
Recibir mercancía de entrega directa.") + End If + + 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("

El proveedor tiene evaluaciones pendientes
") + Msg.Append("¿Desea realizar una evaluacion al proveedor?") + Msg.AppendFormat($"
Evaluar Proveedor.") + End If + + Alert(Msg.ToString, TipoMensaje.MsgInformacion, MsgAccionAceptar) + + 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.
Revise sus datos de pago y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia) + ObjCompras.RollBack() + End If + + + Catch ex As Exception + ObjCompras.RollBack() + If ObjContaAC IsNot Nothing Then ObjContaAC.RollBack() + Alert("Ocurrió un error al registrar la compra y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgError) + GuardaLog($"Ocurrió un error al registrar la compra y 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 + + 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 ErrorCompra = False + + If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 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 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() + 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) + + '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 + + '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, CveCuenta As Integer + + Dim PorcentajePago, ImporteMovimiento, sumaAmortizacion, sumaAmortizacionCompleto As Decimal + Dim ConceptoPoliza As String = $"Amortización {NombreProveedor} - {TxtSerie.Text}-{TxtFolio.Text}" + Dim CompraUnificada As Boolean = False + Dim IVACompleto As Boolean = False + Dim IdCtaIVAXAcreditar As Integer = 0 + Dim IdCtaIVAAcreditable As Integer = 0 + 'PorcentajeIVA + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("IVAPorcentaje").ToDouble).Rows.Count > 0 Then + IdCtaIVAXAcreditar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("IVAPorcentaje").ToDouble).Rows(0)("IdCtaIVAXAcreditar").ToString.ToEntero + IdCtaIVAAcreditable = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("IVAPorcentaje").ToDouble).Rows(0)("IdCtaIVAAcreditable").ToString.ToEntero + End If + + Try + Dim CveIE As Integer = -1 + + If EmpresaPrueba Then + Dim CvePlantillaPoliza = 52 + Dim tipoCambio As Decimal + Dim tipoCambioNC As Decimal + Dim alertaContabilizacion As New StringBuilder + Dim idCuentaContabilizacion As Long = 1 + Dim CveCuentaContabilizacion As Long = 1 + Dim CvePrepolizaPadre As Integer = CvePrePoliza + Dim CuentasContablesInvalidas As New StringBuilder + Dim CuentasContablesInvalidasSIG As New StringBuilder + + If DdlMoneda.SelectedValue.ToString.ToEntero = 2 Then + tipoCambio = GlobalTipoCambio(Fecha).ToString.ToDecimal + Else + tipoCambio = 1 + End If + + '[IPP] PARCHE PARA AMORTIZACIÓN NC + Dim TipoCambioCompra = Me.TipoCambio.ToDecimal + + 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 + tipoCambioNC = gvr.DataKey("TCCompra").ToDecimal + sumaAmortizacion = 0 + + If CvePrePolizaNueva > 0 Then + If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPoliza) 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) + ImporteMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 0 + Dim Concepto As String = "" + Dim importeMN As Decimal = 0 + Dim Multiplicador As Integer = If(Row("Multiplicador").ToString.ToEntero = 1, 1, -1) + Dim PorcentajeImpuesto As Decimal = 0 + Dim ConceptoPartida As String = String.Format("{0}-{1}", TxtSerie.Text, TxtFolio.Text) + + + Select Case ConceptoContable + Case 265 'Amortización Anticipos Compras + If gvr.DataKey("TipoDocto").Contiene("Ant") Then + CveIE = -1 + ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal + importeMN = ImporteMovimiento * tipoCambioNC + sumaAmortizacion += ImporteMovimiento + sumaAmortizacionCompleto += ImporteMovimiento + + If DdlMoneda.SelectedValue.ToEntero <> 1 Then + IdCtaContable = CtaProveedorAnticiposExtranjera + CveCuenta = CveCuentaProveedorAnticiposExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, "", ConceptoContable, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then + If UsuarioActual.CveEmpresa.Contiene(119) Then + IdCtaContable = CtaProveedorAnticiposComplementaria + CveCuenta = CveCuentaProveedorAnticiposComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeMN - ImporteMovimiento, "", 266, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN - ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + Exit Select + End If + End If + Else + ErrorMovtosCxP = 1 + Exit Select + End If + Else + IdCtaContable = CtaProveedorAnticipos + CveCuenta = CveCuentaProveedorAnticipos + If ImporteMovimiento <> 0 Then + PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, "", ConceptoContable, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + End If + End If + End If + End If + + ImporteMovimiento = 0 + Case 60 'Nota de Credito + If gvr.DataKey("TipoDocto").Contiene("NC", "DEV") Then + CveIE = -1 + ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal + importeMN = ImporteMovimiento * tipoCambioNC + sumaAmortizacion += ImporteMovimiento + sumaAmortizacionCompleto += ImporteMovimiento + + If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, ConceptoPartida, ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeMN - ImporteMovimiento, ConceptoPartida, 235, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN - ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=tipoCambioNC, CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + Exit Select + End If + Else + ErrorMovtosCxP = 1 + Exit Select + End If + Else + IdCtaContable = CtaProveedor + CveCuenta = CveCuentaProveedor + If ImporteMovimiento <> 0 Then + PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, ConceptoPartida, ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCompraAmortizacion:=CveCompra, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + End If + End If + End If + End If + + ImporteMovimiento = 0 + Case 21 'Anticipo + If gvr.DataKey("TipoDocto") = "Egsc" Then + CveCompraNC = -1 + CveIE = gvr.DataKey("CveIE").ToEntero + ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal + sumaAmortizacion += ImporteMovimiento + sumaAmortizacionCompleto += ImporteMovimiento + IdCtaContable = CtaProveedorAnticipos + CveCuenta = CveCuentaProveedorAnticipos + If ImporteMovimiento <> 0 Then + PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal + + Dim TipoCambioAnt = gvr.DataKey("TCCompra").ToDecimal + Dim usacomplementariaAnticipo As Boolean = False + usacomplementariaAnticipo = If(TipoCambioAnt > 1 AndAlso UsuarioActual.CveEmpresa.Contiene(1, 119), True, False) + + + Dim ImporteAnt As Decimal = ImporteMovimiento + Dim ImporteAntMN As Decimal = ImporteAnt * TipoCambioAnt + If usacomplementariaAnticipo Then + IdCtaContable = CtaProveedorAnticiposComplementaria + CveCuenta = CveCuentaProveedorAnticiposComplementaria + ImporteAntMN = TipoCambioAnt * ImporteAnt - ImporteAnt + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteAnt, "", 266, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CvePersonal:=CvePersonal, ImporteMX:=ImporteAntMN, ImporteME:=ImporteAnt, TipoCambio:=TipoCambioAnt, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + End If + ImporteAntMN = ImporteAnt + End If + + If TipoCambioAnt > 1 Then + IdCtaContable = CtaProveedorAnticiposExtranjera + CveCuenta = CveCuentaProveedorAnticiposExtranjera + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteAnt, "", ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteAntMN, CvePrePolizaOriginal:=CvePrePolizaNueva, ImporteME:=If(tipoCambio = 1, 0, ImporteAnt), CveCompraAmortizacion:=CveCompraNC, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + End If + + If tipoCambio <> TipoCambioAnt Then + Dim importeFluctuacion = (ImporteAnt * tipoCambio) - (ImporteAnt * TipoCambioAnt) + + If importeFluctuacion > 0 Then + ConceptoContable = 64 + TipoMovimiento = True + IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + ElseIf importeFluctuacion < 0 Then + ConceptoContable = 65 + TipoMovimiento = False + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + End If + + importeFluctuacion = importeFluctuacion.Abs.RoundSQL() + If importeFluctuacion <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeFluctuacion, "", ConceptoContable, ConceptoPartida, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeFluctuacion, CvePrePolizaOriginal:=CvePrePolizaNueva, ImporteME:=0, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + End If + End If + End If + + End If + End If + + ImporteMovimiento = 0 + + Case 37 'Deudores Diversos + If gvr.DataKey("TipoDocto") = "DD" Then + CveCompraNC = -1 + CveIE = gvr.DataKey("CveIE").ToEntero + ImporteMovimiento = gvr.FCTextBox("TxtAnticipo").Text.ToDecimal + sumaAmortizacion += ImporteMovimiento + sumaAmortizacionCompleto += ImporteMovimiento + IdCtaContable = CtaProveedorDeudores + CveCuenta = CveCuentaProveedorDeudores + + If ImporteMovimiento <> 0 Then + PorcentajePago = ImporteMovimiento / TxtTotal.Text.ToDecimal + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, "", ConceptoContable, "", Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento * tipoCambio, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCompraAmortizacion:=CveCompraNC, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + End If + End If + End If + + ImporteMovimiento = 0 + + Case 17 'Pago Proveedores + Dim TipoCambio17 = tipoCambio + If gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant", "Egsc") Then + TipoCambio17 = TipoCambioCompra + End If + If gvr.DataKey("TipoDocto").Contiene("NC", "DEV") Then + ConceptoContable = 272 + End If + + ImporteMovimiento = sumaAmortizacion + importeMN = ImporteMovimiento * TipoCambio17 + + If DdlMoneda.SelectedValue.ToEntero <> 1 And UsuarioActual.CveEmpresa.Contiene(119) Then + IdCtaContable = CtaProveedorExtranjera + CveCuenta = CveCuentaProveedorExtranjera + If ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=TipoCambio17, CveCuenta:=CveCuenta) Then + IdCtaContable = CtaProveedorComplementaria + CveCuenta = CveCuentaProveedorComplementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, importeMN - ImporteMovimiento, Concepto, 206, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN - ImporteMovimiento, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=ImporteMovimiento, TipoCambio:=TipoCambio17, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + Exit Select + End If + Else + ErrorMovtosCxP = 1 + Exit Select + End If + Else + IdCtaContable = CtaProveedor + CveCuenta = CveCuentaProveedor + If ImporteMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveCompraAmortizacion:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(TipoCambio17 = 1, 0, ImporteMovimiento), CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + Exit For + End If + End If + End If + + ImporteMovimiento = 0 + Case 14 'Iva X Acreditar + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If UsuarioActual.Empresa.Funcionalidad(521) = "1" Then + If sumaAmortizacion = CompraSaldo Then + ImporteMovimiento = TxtIVA.Text.ToDecimal + IVACompleto = True + Else + ImporteMovimiento = 0 + End If + Else + ImporteMovimiento = Math.Round(PorcentajePago * TxtIVA.Text.ToDecimal, 2) + End If + importeMN = ImporteMovimiento * tipoCambio + PorcentajeImpuesto = TmpDT.MAX("IVAPorcentaje").ToDecimal + IdCtaContable = If(IdCtaIVAXAcreditar > 0, IdCtaIVAXAcreditar, 0) + If 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAxAcreditarSIG").ToString.ToEntero + End If + End If + End If + Case 19 'Iva Acreditado + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If UsuarioActual.Empresa.Funcionalidad(521) = "1" Then + If sumaAmortizacion = CompraSaldo Then + ImporteMovimiento = TxtIVA.Text.ToDecimal + IVACompleto = True + Else + ImporteMovimiento = 0 + End If + Else + ImporteMovimiento = Math.Round(PorcentajePago * TxtIVA.Text.ToDecimal, 2) + End If + importeMN = ImporteMovimiento * tipoCambio + PorcentajeImpuesto = TmpDT.MAX("IVAPorcentaje").ToDecimal + IdCtaContable = If(IdCtaIVAAcreditable > 0, IdCtaIVAAcreditable, 0) + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) And Not IdCtaContable > 0 Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditable").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIVAAcreditableSIG").ToString.ToEntero + End If + End If + End If + Case 15 'RetIVA x Acreditar Honorarios/Serv. Prof. + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(307).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(307).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + Case 22 'RetIVA Acreditable Honorarios/Serv. Prof. + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 1 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(308).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(308).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + + Case 183 'RetIVA x Acreditar Fletes P.F. + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(309).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(309).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + + Case 184 'RetIVA Acreditable Fletes P.F. + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 2 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(310).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(310).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + + Case 185 'RetIVA x Acreditar Fletes P.M. + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(311).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(311).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + + Case 186 'RetIVA Acreditable Fletes P.M. + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 3 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(312).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(312).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + Case 248 'RetIVA x Acreditar Arrendamiento + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(313).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(313).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + + Case 249 'RetIVA Acreditable Arrendamiento + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetIVAConcepto.Items.Count > 0 Then + If DdlRetIVAConcepto.SelectedValue.ToEntero = 4 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetIVA > 0 Then + IdCtaContable = CtaProveedorRetIVA + CveCuenta = CveCuentaProveedorRetIVA + ElseIf UsuarioActual.Empresa.Funcionalidad(314).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(314).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + End If + Case 16 'RetISR x Acreditar + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(315).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(315).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + + Case 23 'RetISR Acreditable + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 1 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(316).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(316).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + Case 243 'RetISR X Acreditar Terceros y Arrendamiento + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(317).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(317).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + Case 244 'RetISR Acreditable Terceros y Arrendamiento + If Not gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then + If DdlRetISRConcepto.Items.Count > 0 AndAlso DdlRetISRConcepto.SelectedValue.ToEntero = 2 Then + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) + importeMN = ImporteMovimiento * tipoCambio + If CtaProveedorRetISR > 0 Then + IdCtaContable = CtaProveedorRetISR + CveCuenta = CveCuentaProveedorRetISR + ElseIf UsuarioActual.Empresa.Funcionalidad(318).ToEntero > 0 Then + IdCtaContable = UsuarioActual.Empresa.Funcionalidad(318).ToEntero + Else + If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + End If + Case 64 'GANANCIA + If gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then 'SOLO SE IMPLEMENTÓ PARA NC + If DdlMoneda.SelectedValue.ToEntero <> 1 Or gvr.DataKey("CveMoneda").ToEntero <> 1 Then + IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + If TipoCambioCompra > tipoCambioNC Then + ImporteMovimiento = (sumaAmortizacion * TipoCambioCompra) - (sumaAmortizacion * tipoCambioNC) + ImporteMovimiento = ImporteMovimiento.RoundSQL() + importeMN = ImporteMovimiento + End If + + If ImporteMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + Exit For + End If + End If + + End If + End If + ImporteMovimiento = 0 + Case 65 'PERDIDA + If gvr.DataKey("TipoDocto").Contiene("NC", "DEV", "Ant") Then 'SOLO SE IMPLEMENTÓ PARA NC + If DdlMoneda.SelectedValue.ToEntero <> 1 Or gvr.DataKey("CveMoneda").ToEntero <> 1 Then + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + If tipoCambioNC > TipoCambioCompra Then + ImporteMovimiento = (sumaAmortizacion * tipoCambioNC) - (sumaAmortizacion * TipoCambioCompra) + ImporteMovimiento = ImporteMovimiento.RoundSQL() + importeMN = ImporteMovimiento + End If + + If ImporteMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=0, CveCuenta:=CveCuenta) Then + ErrorMovtosCxP = 1 + Exit For + End If + End If + + End If + End If + ImporteMovimiento = 0 + End Select + + If ImporteMovimiento <> 0 Then + 'Conta ContPAQ + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + 'Conta SIG + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, TipoMovimiento, ImporteMovimiento, Concepto, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=importeMN, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, ImporteMovimiento), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then + ErrorMovtosCxP = 1 + Exit For + End If + + End If + Next + + End If + + End If + + '[IPP] COMENTADO PORQUE REUNIFICABA AMORTIZACIÓN NC 27/Agosto/2018 + 'If Not CompraUnificada Then + ' 'Unificacion de PrePolizas + ' If UsuarioActual.Empresa.Funcionalidad(219) = "1" Then + ' If Not ObjConta.PrePolizaUnificacion(gvr.DataKey("CvePrePoliza").ToEntero, CvePrepolizaPadre) Then + ' ErrorMovtosCxP = 1 + ' Alert("No se pudo unificar la prepoliza", TipoMensaje.MsgError) + ' End If + ' End If + 'End If + End If + Next + + 'Si el importe total de la amortizacion es igual al saldo de la compra se registra IVA + If IVACompleto = False AndAlso UsuarioActual.Empresa.Funcionalidad(521) = "1" Then + If sumaAmortizacionCompleto = CompraSaldo Then + Dim PorcentajeImpuesto As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, True, TxtIVA.Text.ToDecimal, "", 14, "", Fecha, IdCtaIVAXAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=TxtIVA.Text.ToDecimal * tipoCambio, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, TxtIVA.Text.ToDecimal), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then + ErrorMovtosCxP = 1 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaNueva, False, TxtIVA.Text.ToDecimal, "", 19, "", Fecha, IdCtaIVAAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=TxtIVA.Text.ToDecimal * tipoCambio, CvePrePolizaOriginal:=CvePrePoliza, ImporteME:=If(tipoCambio = 1, 0, TxtIVA.Text.ToDecimal), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then + ErrorMovtosCxP = 1 + End If + End If + End If + + 'Unificacion de PrePolizas + If UsuarioActual.Empresa.Funcionalidad(219) = "1" Then + If Not ObjConta.PrePolizaUnificacion(CvePrepolizaPadre, CvePrePolizaNueva) Then + ErrorMovtosCxP = 1 + 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.PrePolizaSimplificacion(CvePrepolizaPadre, UsuarioActual.CveEmpresa) Then + ErrorMovtosCxP = 1 + Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) + End If + End If + + 'Validacion de prepolizas + If ObjConta.ValidacionPrePolizaCuadre(CvePrePolizaNueva, 4) Then + If ObjConta.ValorPolizaDescuadre > 0 Then + GuardaLogAD($"Compras/Compras-Anticipos | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas") + 'ErrorMovtosCxP = 1 + End If + End If + + 'Conta ContPAQ + If UsuarioActual.Empresa.Funcionalidad(200) = "1" And ErrorMovtosCxP = 0 And UsuarioActual.Empresa.UsaContabilidad Then + If idCuentaContabilizacion > 0 Then + If ObjConta.ContabilizarPrePoliza(CvePrePolizaNueva, UsuarioActual.CveUsuario, UsuarioActual.Empresa) Then + alertaContabilizacion.AppendFormat("{1}<\a>
", ObjConta.ContaIdPoliza, ObjConta.ContaFolio) + Else + ErrorMovtosCxP = 1 + End If + If ErrorMovtosCxP = 0 Then + Alert("Se enviaron correctamente las siguientes pólizas:

" & alertaContabilizacion.ToString, ModExtensiones.TipoMensaje.MsgInformacion) + Else + 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:
{0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia) + End If + End If + + + Else 'Empresa Prueba + + 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 CveConceptoPago As Integer = 17 + Dim TipoMovimientoCompra As Boolean = True + Select Case gvr.DataKey("TipoDocto") + Case "NC", "DEV" + CveConceptoCompra = 60 + CveIE = -1 + CveConceptoPago = 272 + Case "Egsc" + CveConceptoCompra = 21 + 'vinculo la compra actual, y no la compra como si fuera nota de credito + CveCompraNC = -1 + CveIE = gvr.DataKey("CveIE").ToEntero + Case "DD" + CveConceptoCompra = 37 + '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 + + 'Se agrega la nota de credito + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimientoCompra, gvr.FCTextBox("TxtAnticipo").Text.ToDecimal, " ", CveConceptoCompra, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompraNC, CveProveedor:=CveProveedor, CveIE:=CveIE, CveCompraAmortizacion:=CveCompraNC, ImporteMX:=gvr.FCTextBox("TxtAnticipo").Text.ToDecimal) Then + ErrorMovtosCxP = 1 + Exit For + End If + + 'movimiento de pago proveedor + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimientoCompra, gvr.FCTextBox("TxtAnticipo").Text.ToDecimal, " ", CveConceptoPago, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, CveCompraAmortizacion:=CveCompraNC, ImporteMX:=gvr.FCTextBox("TxtAnticipo").Text.ToDecimal) Then + ErrorMovtosCxP = 1 + Exit For + End If + + 'si tiene iva y su proporcion + ImporteMovimiento = Math.Round(PorcentajePago * TxtIVA.Text.ToDecimal, 2) + If ImporteMovimiento > 0 Then + Dim PorcentajeImpuesto As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, " ", 14, " ", TxtFechaPago.Text.ToDate, IdCtaIVAXAcreditar, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, PorcentajeImpuesto:=PorcentajeImpuesto) Then ErrorMovtosCxP = 1 : Exit For + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, " ", 19, " ", TxtFechaPago.Text.ToDate, IdCtaIVAAcreditable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento, PorcentajeImpuesto:=PorcentajeImpuesto) Then ErrorMovtosCxP = 1 : Exit For + + End If + + 'si tiene Ret iva y su proporcion + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetIVA.Text.ToDecimal, 2) + If ImporteMovimiento > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, " ", 15, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, " ", 22, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For + + End If + + 'si tiene Ret ISR y su proporcion + ImporteMovimiento = Math.Round(PorcentajePago * TxtRetISR.Text.ToDecimal, 2) + If ImporteMovimiento > 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, " ", 16, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, " ", 23, " ", TxtFechaPago.Text.ToDate, 0, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, CveIE:=CveIE, ImporteMX:=ImporteMovimiento) Then ErrorMovtosCxP = 1 : Exit For + + End If + + + 'actualizo una tabla de vinculaciones + + 'actualizo la cantidad en amortizaciones + + If gvr.DataKey("TipoDocto").Contiene("NC", "DEV") Then + If Not ObjCompra.AmortizarCompra(CveCompra, CveCompraNC, gvr.FCTextBox("TxtAnticipo").Text.ToDouble, UsuarioActual.CveUsuario) Then + ErrorMovtosCxP = 2 + Exit For + + End If + + End If + + + End If + + End If + + Next + + End If 'Empresa Prueba + + + + Select Case ErrorMovtosCxP + Case 0 + 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
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
Revise su factura y cualquier detalle comuníquese a Soporte Técnico", TipoMensaje.MsgAdvertencia) + ObjCompra.RollBack() + End Select + + Catch ex As Exception + ObjCompra.RollBack() + End Try + 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, .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 Anticipos In ArrAnticipos + ImporteAnticipo += Ant.Importe + Next + End If + + LblAmortizacion.Text = ImporteAnticipo.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 + + '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 + + 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.
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 = New ClsContPAQi(UsuarioActual.Empresa) + + 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 + + 'PORCENTAJE IVA + Dim PorcentajeIVA As Decimal = TmpDT.MAX("IVAPorcentaje").ToDecimal + + 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) 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 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 And 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) + + 'COMENTADO 15/3/2016 + 'cuando hay algo que ingresar a inventarios + 'Dim x As Integer = 0 + 'For Each Dr As DataRow In TmpDT.Rows + ' If GvInv.Rows.Count > 0 Then + ' If GvInv.Rows(x).FCCheckBox("cbInv").Checked Then + ' Dr("CveAlmacen") = GvInv.Rows(x).FCDropDownList("ddlEAlmacen").SelectedValue.ToEntero + ' Else 'limpio el valor para que no truene en linq mas abajo + ' Dr("CveAlmacen") = 0 + ' End If + ' x = x + 1 + ' Else + ' Exit For + ' End If + 'Next + + ''previamente si hay un ingreso a inventarios + 'Dim CtaAlmacen As Integer + 'If ContadorInventario > 0 Then + ' Dim drr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", TmpDT.Rows(0)("CveAlmacen").ToString)) + ' If drr IsNot Nothing Then + ' CtaAlmacen = drr("IdCtaContable").ToString.ToEntero + ' End If + 'End If + + 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) + ' tDiferenciaIVA -= tIVA + ' 'identifico si es el ultimo registro, para ver si es necesario un ajuste + ' If ipresup = GvPS.Rows.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 + tImporte += ttIVA + + 'PU = tImporte / gvr.DataKey("Cantidad").ToDouble + 'If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, gvr.DataKey("Cantidad").ToDouble, gvr.DataKey("CveUM").ToEntero, gvr.DataKey("CvePS").ToEntero, PU, -1) Then + ' ErrorAC = True + ' Exit For + 'End If + 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 + 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 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 = "True" AndAlso EsNoDeducible, True, False)) Then + + Retorno = False + Exit For + End If + + '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 + Dim ObjCompras As New ClsCompras + If Not ObjCompras.DeleteCompraDetalle(item.ToEntero) Then + Retorno = False + End If + Next + + If Retorno Then + If ViewState("IdPoliza").ToString.ToEntero > 0 Then + ObjContaAC = New ClsContPAQi(UsuarioActual.Empresa) + ObjContaAC.IniciaTransacSQL() + + 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.") + 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 + Catch ex As Exception + Alert("Ocurrió un error al actualizar la compra", TipoMensaje.MsgError) + ObjCompra.RollBack() + 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("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.ToDecimal > 0, TipoCambio.ToDecimal, tipoCambioActual) + tipoCambioPago = GlobalTipoCambio(TxtFechaPago.Text.ToDate).ToString.ToDecimal + Else + tipoCambioActual = 1 + tipoCambioPago = 1 + End If + + 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 CveCuenta 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, CveAcreedor As Integer = 0, CveIE As Integer = 0, CveColectiva As Integer = 0, CveCreditoDetalle As Integer = 0 + Dim ConceptoPersonal As String = "", Concepto As String = "" + + If Not ObjConta.GetPrePolizasDetalle(CvePrePoliza) Then + ErrorPrepoliza = True + Else + If ObjConta.DtResultados.FiltraParametros("CveConceptoContable IN (6,68,49,205,176)").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 + CveAcreedor = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveAcreedor").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 + CveColectiva = ObjConta.DtResultados.FiltraParametros("CveConceptoContable = 6 OR CveConceptoContable = 68 OR CveConceptoContable = 49 OR CveConceptoContable = 205 OR CveConceptoContable = 176").Rows(0)("CveColectiva").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 + + 'Removemos los conceptos de la prepoliza + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 6, CveCompra, 1) 'GASTO + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 68, CveCompra, 1) 'ALMACEN + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 49, CveCompra, 1) 'AF + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 205, CveCompra, 1) 'PS YA RECIBIDO + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 230, CveCompra, 1) 'PS YA RECIBIDO + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 231, CveCompra, 1) 'PS YA RECIBIDO + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 176, CveCompra, 1) 'PS NO RECIBIDO + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 228, CveCompra, 1) 'PS NO RECIBIDO + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, 229, CveCompra, 1) '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" And ConceptoContabilizacionAlmacen = 0 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijoSIG").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, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + End If + End If + Next + End If + + 'LIMPIA + importeMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 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 + 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 + 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero + End If + End If + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 68, Concepto, FechaMovimiento, IdCtaContable, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CvePersonal:=CvePersonal, CveMovimientoAlmacen:=CveMovimientoInventario, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + End If + End If + Next + End If + End If + + 'LIMPIA + importeMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 0 + + 'INV [MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA) ] + If UsuarioActual.CveEmpresa.Contiene(119) And 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), CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + End If + End If + + End If + + 'NC CON PRODUCTOS - CUENTA PUENTE + If UsuarioActual.CveEmpresa.Contiene(119) And 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), CveCuenta:=CveCuenta) 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 + 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 + DT.AcceptChanges() + DtAlmacenes.Dispose() + + 'QUITA 1-[MERCANCIA RECIBIDA POR ADELANTADO (OC) | MERCANCIA PENDIENTE POR RECIBIR (COMPRA)] 2-[NC CON PRODUCTOS] + If UsuarioActual.CveEmpresa.Contiene(119) And 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", "CveProyecto", "CveSubProyecto", "CveTipoGasto", "TipoGasto"}) + Else + DTDistinct = DTDistinct.FiltraParametros("ISNULL(TipoAF,0) <> 2 AND ISNULL(CveAlmacen,0) = 0 AND ISNULL(AplicaCostoIndirecto,0) <> 1", "", {"CveClasificacion", "Clasificacion", "SubProyecto", "CveProyecto", "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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero + Else + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero + End If + End If + End If + + 'SEGMENTO DE NEGOCIO + Dim IdSegmentoNegocio As Integer = -1 + Dim drT As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero).FiltroPrimero(String.Format("CveSubProyecto = {0} ", Row2("CveSubProyecto").ToString.ToEntero)) + If drT IsNot Nothing Then + IdSegmentoNegocio = drT("IdSegNeg").ToString.ToEntero + End If + + 'AGREGA MOVIMIENTO + If importeMovimiento <> 0 Then + Concepto = $"{NombreProveedor} {TxtSerie.Text} - {TxtFolio.Text}" + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 6, Concepto, FechaMovimiento, IdCtaContable, IdSegmentoNegocio, CveCompra:=CveCompra, CveProveedor:=CveProveedorConcepto, CveAcreedor:=CveAcreedor, CveIE:=CveIE, CveColectiva:=CveColectiva, CveCreditoDetalle:=CveCreditoDetalle, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMN, ImporteME:=If(tipoCambioActual = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveTipoGasto:=Row2("CveTipoGasto").ToString.ToEntero) Then + ErrorPrepoliza = True + End If + End If + + Next + End If + + 'LIMPIA + importeMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 0 + + End Select + + Next + End If + + If ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 4) Then + If ObjConta.ValorPolizaDescuadre > 0 Then + ErrorPrepoliza = True + 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").ToDouble + + If Version = "3.3" 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 Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) + Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" + Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) + + 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 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") + 'EmisorNombre = ValorXML(node, "nombre") + End If + 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 + + 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("04", "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 + Next + 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" Then + + For Each retencion As XmlNode In nodeRetenciones + If retencion.Attributes("Impuesto").Value = "002" Then + RetencionIVA += retencion.Attributes("Importe").Value.ToDecimal + End If + If retencion.Attributes("Impuesto").Value = "001" Then + RetencionISR += retencion.Attributes("Importe").Value.ToDecimal + End If + ' Do something. + 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 + End If + If retencion.Attributes("impuesto").Value = "ISR" Then + RetencionISR += retencion.Attributes("importe").Value.ToDecimal + End If + ' Do something. + 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" Then + + For Each traslado As XmlNode In nodeTraslados + If traslado.Attributes("Impuesto").Value = "002" Then + TrasladoIVA += traslado.Attributes("Importe").Value.ToDecimal + End If + If traslado.Attributes("Impuesto").Value = "003" Then + TrasladoIEPS += traslado.Attributes("Importe").Value.ToDecimal + End If + If traslado.Attributes("Impuesto").Value = "001" Then + 'TrasladoISR = traslado.Attributes("importe").Value + End If + ' Do something. + Next + + Else + + For Each traslado As XmlNode In nodeTraslados + If traslado.Attributes("impuesto").Value = "IVA" Then + TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal + End If + If traslado.Attributes("impuesto").Value = "IEPS" Then + TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal + End If + 'If traslado.Attributes("impuesto").Value = "ISR" Then + ' TrasladoISR = traslado.Attributes("importe").Value + 'End If + ' Do something. + 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 + OtrosImpuestosRetenciones = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal + + 'If RetencionIVA <= 0 AndAlso ValorXML(node, "TotaldeRetenciones", "0").ToDouble > 0 Then RetencionIVA = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal + + 'For Each retencion As XmlNode In nodeImpLocales + ' If retencion.Attributes("impuesto").Value = "IVA" Then + ' RetencionIVA += retencion.Attributes("importe").Value.ToDouble + ' End If + ' If retencion.Attributes("impuesto").Value = "ISR" Then + ' RetencionISR += retencion.Attributes("importe").Value.ToDouble + ' End If + ' ' Do something. + 'Next + ' SumaTotalRetenciones += RetencionIVA + ' SumaTotalRetenciones += RetencionISR + + 'TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble + + 'Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) + 'For Each traslado As XmlNode In nodeTraslados + ' If traslado.Attributes("impuesto").Value = "IVA" Then + ' TrasladoIVA += traslado.Attributes("importe").Value.ToDouble + ' End If + ' If traslado.Attributes("impuesto").Value = "IEPS" Then + ' TrasladoIEPS += traslado.Attributes("importe").Value.ToDouble + ' End If + ' 'If traslado.Attributes("impuesto").Value = "ISR" Then + ' ' TrasladoISR = traslado.Attributes("importe").Value + ' 'End If + ' ' Do something. + 'Next + 'SumaTotalTraslados += TrasladoIVA + 'SumaTotalTraslados += TrasladoIEPS + End If + + End If + + 'Try + ' _TFDUUID = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces).LastChild.Attributes("UUID").InnerText + 'Catch ex As Exception + ' _TFDUUID = "" + 'End Try + + + 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(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.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 = "" + + 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, If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDouble)))) 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO + e.Row.FCTextBox("TxtAnticipo").Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1},{2});", e.Row.FCCheckBox("Chk").ClientID, e.Row.DBCampo("Saldo"), If(CveCompra > 0, Saldo, If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteConImpuestos"), TxtTotal.Text.ToDouble)))) 'SI ES UNA COMPRA NUEVA SE PONE EL TOTAL, SI NO EL SALDO + + 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 + 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 + e.Row.Cells(0).Width = Unit.Pixel(15) + e.Row.Cells(1).Width = Unit.Pixel(45) + e.Row.Cells(2).Width = Unit.Pixel(70) + e.Row.Cells(3).Width = Unit.Pixel(230) + e.Row.Cells(4).Width = Unit.Pixel(202) + e.Row.Cells(5).Width = Unit.Pixel(155) + e.Row.Cells(6).Width = Unit.Pixel(155) + e.Row.Cells(7).Width = Unit.Pixel(50) + e.Row.Cells(8).Width = Unit.Pixel(80) + e.Row.Cells(9).Width = Unit.Pixel(80) + e.Row.Cells(10).Width = Unit.Pixel(43) + e.Row.Cells(11).Width = Unit.Pixel(43) + + If UsuarioActual.Empresa.UsaAC Then 'AndAlso (CveFactura > 0 Or CveCompra > 0) + e.Row.Cells(12).Width = Unit.Pixel(150) + 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(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("'", "").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 = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToString.ToEntero, -1) + + '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("CveSATUnidadMedida")}','{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("CveSATUnidadMedida")}','{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 + 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 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 + + 'CargaPresupuestosEgresos + If UsuarioActual.Empresa.UsaAC Then + e.Row.Cells(13).Visible = True + 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.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("NOT CodigoCOG like '1%'", 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(13).Enabled = False + e.Row.Cells(14).Enabled = False + e.Row.Cells(15).Enabled = False + e.Row.Cells(16).Enabled = False + e.Row.Cells(17).Enabled = False + End If + Else + + e.Row.Cells(13).Visible = False + e.Row.Cells(14).Visible = False + e.Row.Cells(15).Visible = False + e.Row.Cells(16).Visible = False + e.Row.Cells(17).Visible = False + End If + + 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() + + 'GVAF.DataSource = TmpDT + 'GVAF.DataBind() + ''UpnAF.Update() + + 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}"")", e.Row.FCTextBox("TxtSaldoDeudor").ClientID, total, saldo)) + 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) + Dim ObjPS As New ClsProductosServicios + + If (ObjPS.GetPSSimplificado(-1)) Then + Application("GlobalDTPSSimplificado") = ObjPS.DtResultados.AsEnumerable + End If + + If ObjPS.GetPSEquivalencias(-1, -1) Then + GlobalDTProductosServiciosEquivalencias(-1, -1) = ObjPS.DtResultados + End If + + ObjPS.Dispose() + 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.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)) + End Sub + 'Private Sub AddPS(Cantidad As Double, UM As String, PS As String, PU As Double, IVA As Double, Descuento As Double, Optional Total As Double = 0) + ' Dim Row As DataRow = Nothing + ' Row = DTConceptos.NewRow() + ' Row("Consec") = DTConceptos.Rows.Count + 1 + ' Row("Cantidad") = Cantidad + ' Row("UM") = UM + ' Row("CveClasificacion") = -1 + ' Row("PS") = PS + ' Row("PU") = PU + ' Row("IVA") = IVA + ' Row("Total") = If(Total > 0, Total, Cantidad * PU) + ' Row("Descuento") = Descuento + + ' DTConceptos.Rows.Add(Row) + '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("CveSATUnidadMedida", GetType(Integer)) + TmpDT.Columns.Add("SATClaveUnidadMedida", GetType(String)) + + '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)) + + 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("CveSATUnidadMedida", GetType(Integer)) + TmpDTOriginal.Columns.Add("SATClaveUnidadMedida", GetType(String)) + + '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)) + + + End Sub + 'Private Sub AddDTEnvio(Cantidad As Double, UM As String, CveUM As Integer, CvePS As Integer, PS As String, PU As Double, CveAlmacen As Integer, CveEq As Integer) + + ' Dim dr As DataRow = DtInv.NewRow + + ' dr("Cantidad") = Cantidad + ' dr("UM") = UM + ' dr("CveUM") = CveUM + ' dr("CvePS") = CvePS + ' dr("PS") = PS + ' dr("PU") = PU + ' dr("CveAlmacen") = CveAlmacen + ' dr("CveEq") = CveEq + + ' DtInv.Rows.InsertAt(dr, hdnIndexInv.Value.ToEntero + 1) + + ' GvInv.DataSource = DtInv + ' GvInv.DataBind() + + + '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},
", 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},
", 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() + CargaClasificaciones() + CargaPS(-1) + CargaProyecto() + 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 GVAF_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAF.RowCreated + ' If e.Row.RowType = DataControlRowType.DataRow AndAlso (e.Row.RowState = DataControlRowState.Alternate OrElse e.Row.RowState = DataControlRowState.Normal) Then + ' e.Row.FCDropDownList("DdlTipoActivoFijo").DataSource = TmpDTTiposAF + ' e.Row.FCDropDownList("DdlTipoActivoFijo").DataBind() + + ' e.Row.FCDropDownList("DdlSubTipoActivoFijo").DataSource = Nothing + ' e.Row.FCDropDownList("DdlSubTipoActivoFijo").DataBind() + ' e.Row.FCDropDownList("DdlSubTipoActivoFijo").Items.Insert(0, New ListItem("Seleccione", "-1")) + + + ' e.Row.FCDropDownList("DdlAF").DataSource = Nothing + ' e.Row.FCDropDownList("DdlAF").DataBind() + ' e.Row.FCDropDownList("DdlAF").Items.Insert(0, New ListItem("Seleccione", "-1")) + + ' End If + 'End Sub + + 'Protected Sub GVAF_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAF.RowDataBound + ' If e.Row.RowType = DataControlRowType.DataRow Then + ' If e.Row.RowIndex = 0 Then + ' e.Row.Cells(0).Width = Unit.Pixel(20) + ' e.Row.Cells(1).Width = Unit.Pixel(140) + ' e.Row.Cells(2).Width = Unit.Pixel(250) + ' End If + + ' e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Right + ' e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Left + ' e.Row.Cells(2).HorizontalAlign = HorizontalAlign.Left + ' End If + 'End Sub + + 'Protected Sub DdlTipoActivoFijo_SelectedIndexChanged(sender As Object, e As System.EventArgs) + ' Dim Array() As String = Nothing + ' Dim DdlGVSubTipoAF As DropDownList = Nothing + + ' Array = DirectCast(sender, DropDownList).ClientID.Split("_"c) + ' If Array.Length > 0 Then + ' DdlGVSubTipoAF = DirectCast(GVAF.Rows(Array(3).ToEntero).Controls(4).Controls(1), DropDownList) + ' End If + + ' If DdlGVSubTipoAF IsNot Nothing Then CargaSubTipoAF(DirectCast(sender, DropDownList), DdlGVSubTipoAF) + 'End Sub + + 'Protected Sub GvOCC2_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvOCC2.RowDataBound + ' If e.Row.RowType = DataControlRowType.DataRow Then + + ' e.Row.Cells(0).Text = (e.Row.RowIndex + 1).ToString + + ' End If + 'End Sub + + 'Protected Sub chkFuncionariosEmpleados_CheckedChanged(sender As Object, e As EventArgs) Handles chkFuncionariosEmpleados.CheckedChanged + ' PnlPagoContado.Visible = Not chkFuncionariosEmpleados.Checked + ' PnlFuncionarioEmpleado.Visible = chkFuncionariosEmpleados.Checked + ' UPCondicionesPago.Update() + 'End Sub + 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 + + 'GvOCC.DataSource = TmpDT + 'GvOCC.DataBind() + 'GvOCC2.DataSource = dt + 'GvOCC2.DataBind() + + 'UpnAF.Update() + + 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 = DirectCast(GvInv.Rows(e.RowIndex).FindControl("txtECantidad"), TextBox).Text.ToDouble + Dim CveUnidadMedida As Integer = DirectCast(GvInv.Rows(e.RowIndex).FindControl("ddlEUnidad"), DropDownList).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("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 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 + 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() + 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).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", DdlMoneda.SelectedValue)) + DdlCuenta.DataBind() + DdlCuenta.Items.Insert(0, New ListItem("Seleccione", "-1")) + + DdlCuentaCaja.Items.Clear() + DdlCuentaCaja.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", DdlMoneda.SelectedValue)) + 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() + End Sub + Protected Sub DivirInsumo(sender As Object, e As EventArgs) + Dim index2 As Integer = 0 + + '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.ToDouble + dr1("IVA") = Math.Round(dr1("IVAPorcentaje").ToString.ToDouble * dr1("Total").ToString.ToDouble, 6) + TmpDT.AcceptChanges() + + + dr("CveActivoFijo") = 0 + dr("CodAF") = "" + 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 + 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") + 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") + 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") + 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") + 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 "C O N T R A T O S" + 'Protected Sub ImgBtnBuscarContrato_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnBuscarContrato.Click + ' If CveProveedor <= 0 Then + ' Alert("Debe de Seleccionar un proveedor") + ' Exit Sub + ' End If + + ' RegistraScript(String.Format("AbrirVentana('/Contratos/PopUpBuscarContrato.aspx?V=VCCOMP',730,300,'N');")) + 'End Sub + + 'Protected Sub CargaVContrato(sender As Object, e As EventArgs) + ' CargaVContrato2(HdnVCveContrato.Value) + 'End Sub + + 'Protected Sub CargaVContrato2(CveContrato As String) + ' If TxtContrato.Text <> "" Then + ' Dim ObjContratos As New ClsContratos + ' Dim DTContratosTemp As DataTable = Nothing + + ' GvContratos1.DataSource = TmpDT + ' GvContratos1.DataBind() + ' UPGVContratos1.Update() + + ' Dim ArrayCveContratos As String() = HdnVCveContrato.Value.Split(New Char() {","c}) + ' For i As Integer = 1 To ArrayCveContratos.Count + ' If ObjContratos.GetContratosDetalle(ArrayCveContratos(i - 1).ToEntero) Then + ' If IsNothing(DTContratosTemp) Then + ' DTContratosTemp = ObjContratos.DtResultados.Copy + ' Else + ' DTContratosTemp.Merge(ObjContratos.DtResultados) + ' End If + ' Else + ' Alert("Ocurrio un ERROR al cargar el Contrato") + ' DTContratosTemp.Rows.Clear() + ' Exit For + ' End If + ' Next + + ' GvContratos2.DataSource = DTContratosTemp + ' GvContratos2.DataBind() + ' UPGVContratos2.Update() + + ' ObjContratos.Dispose() + ' End If + '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) + 'Dim TempSubTotal = TxtSubTotal.Text.ToDouble + + If TmpDT.Rows.Count > 0 Then ' si hay movimientos y si esta afectando al total, que se haga el ajuste + 'Dim ImporteAjuste As Decimal = Total - (SubTotal2 + IVA - RetencionIVA - RetencionIVA - RetencionISR + IEPS + OtrosImpuestos) + 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 + + TmpDT.Rows(Indice)("PU") = TmpDT.Rows(Indice)("PU").ToString.ToDouble + tPU + TmpDT.Rows(Indice)("Total") = TmpDT.Rows(Indice)("Total").ToString.ToDouble + ImporteAjuste + TmpDT.AcceptChanges() + End If + + SubTotal = TmpDT.SUM("Total").ToString.ToDecimal + If Not EsCarga Then + Descuentos = TmpDT.SUM("Descuento").ToString.ToDecimal + End If + TxtSubTotal.Text = (SubTotal + Descuentos).FormatoNumero() + TxtSubTotal2.Text = SubTotal.FormatoNumero + TxtDescuento.Text = Descuentos.FormatoNumero() + SubTotalConceptos = SubTotal + GvPS.DataSource = TmpDT : GvPS.DataBind() + + If TxtOtrosImpuestos.Text.ToDouble > 0 Then TxtOtrosImpuestos.Text = "" : TrOtrosImpuestos.Visible = False + + 'EN ESPERA DE ALGUN CASO QUE LO NECESITE - IPP 5 DICIEMBRE 2016 + 'TempSubTotal = TempSubTotal - SubTotal + 'If TempSubTotal > 0 Then + ' TxtTotal.Text = TempSubTotal.ToString.FormatoNumero + 'End If + + 'GVAF.DataSource = TmpDT : GVAF.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 EmpresaPrueba Then + ' dr = DtAcreedores.FiltroPrimero(String.Format("CveProveedor = {0}", DdlAcreedor.SelectedValue)) + 'Else + ' dr = DtAcreedores.FiltroPrimero(String.Format("CveProveedor = {0}", DdlDeudor.SelectedValue)) + 'End If + + + If dr IsNot Nothing Then + Dim tSaldo As Double = dr("Saldo").ToString.ToDouble + 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.ToDouble, 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 + ViewState("CveCuentaProveedorAcreedores") = ObjProveedor.CveCuentaAcreedor + 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).Rows.Count > 0 Then + RowProveedorSucursal.Visible = True + DdlProveedorSucursal.Items.Clear() + DdlProveedorSucursal.DataSource = GlobalDTProveedorSucursales(DdlProveedor.SelectedValue.ToEntero) + 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() + + + + + + + + 'DdlProveedor.Attributes.Add("onclick", "CargaProveedores();") + 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).FiltroPrimero("CveCuenta = " & DdlCuenta.SelectedValue) + + If dr IsNot Nothing Then + CveMoneda = dr("CveMoneda").ToString.ToEntero + IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero + CveCuentaBancaria = dr("IdCtaContableSIG").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).FiltroPrimero("CveCuenta = " & DdlCuentaCaja.SelectedValue) + + If dr IsNot Nothing Then + CveMoneda = dr("CveMoneda").ToString.ToEntero + IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero + CveCuentaBancaria = dr("IdCtaContableSIG").ToString.ToEntero + 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() + + + 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 = False + 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 + 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 + 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 + 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 + Case "2" ' F y E + PnlContadoFyE.Visible = True + CargaFuncionariosEmpleados() + Case "3" ' Creditos + PnlContadoCreditos.Visible = True + CargaCreditos() + Case "4" ' Deudores + PnlContadoDeudores.Visible = True + CargaDeudores() + Case "5" ' ACREEDORES + PnlContadoAcreedores.Visible = True + CargaAcreedores() + Case "6" ' Caja Chica + PnlContadoCajaChica.Visible = True + TxtDocumentoImporteCaja.Text = TxtTotal.Text + End Select + + UpContado.Update() + End Sub + + Protected Sub RblRembolso_SelectedIndexChanged(sender As Object, e As EventArgs) + TrRembolsoCajaChica.Visible = False + TrRembolsoPersonal.Visible = False + DdlRembolsoCajaChica.SelectedValueExist("-1") + DdlRembolsoPersonal.SelectedValueExist("-1") + If RblRembolso.SelectedValue.ToEntero = 1 Then + TrRembolsoPersonal.Visible = True + ElseIf RblRembolso.SelectedValue.ToEntero = 2 Then + TrRembolsoCajaChica.Visible = True + End If + End Sub +#End Region + +#Region "ARMONIZACION CONTABLE - AC - SIMPLIFICADO" + Private Sub CargaPresupuestosEgresos(Optional CargaTodo As Boolean = True) + + 'Seccion Grid + GvPS.Width = 1760 + GvPS.Columns(12).Visible = True + GvPS.Columns(13).Visible = True + GvPS.Columns(14).Visible = True + GvPS.Columns(15).Visible = True + GvPS.Columns(16).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("NOT CodigoCOG like '1%'", DistinctColumns:={"CveClasificacion", "CodigoClasificacion"}, Orderby:="CodigoClasificacion") + 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("
#{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("
#{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) + + 'DtDetalle.Rows(gvr.RowIndex)("CveClasificacionOG") = gvr.FCDropDownList("DdlAC5").SelectedValue.ToEntero + 'DtDetalle.Rows(gvr.RowIndex)("CveProgramaOperativo") = gvr.FCDropDownList("DdlAC1").SelectedValue.ToEntero + 'DtDetalle.Rows(gvr.RowIndex)("CveUnidadAdministrativa") = gvr.FCDropDownList("DdlAC2").SelectedValue.ToEntero + 'DtDetalle.Rows(gvr.RowIndex)("CveFuenteFinanciamiento") = gvr.FCDropDownList("DdlAC3").SelectedValue.ToEntero + 'DtDetalle.Rows(gvr.RowIndex)("CveTipoGasto") = gvr.FCDropDownList("DdlAC4").SelectedValue.ToEntero + + 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("Empresas\{0}\OI", UsuarioActual.CveEmpresa)) + 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 + 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 + End Sub + Protected Sub DdlCajaChica2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCuentaCajaChicaReembolso.SelectedIndexChanged + Dim dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltroPrimero("CveCuenta = " & DdlCuentaCajaChicaReembolso.SelectedValue) + + If dr IsNot Nothing Then + CveMoneda = dr("CveMoneda").ToString.ToEntero + IdCuentaBancaria = dr("IdCtaContable").ToString.ToEntero + CveCuentaBancaria = dr("IdCtaContableSIG").ToString.ToEntero + 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 Double, Fecha As Date) As Boolean + Dim ErrorMovInv As Boolean = False + Dim CveAlmacen As Integer + 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 + CveAlmacen = Dr.DataKey("CveAlmacen").ToString.ToEntero + 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 subtotal > subtotaldevolucion - 1 AndAlso subtotal < subtotaldevolucion + 1 Then + + Dim CveMovimientoEntrada = ObjInventario.AddMovimiento(CveAlmacen, 13, 1, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra, -1, -1, -1) + If CveMovimientoEntrada <= 0 Then + ErrorMovInv = True + Else + For Each Dr As GridViewRow In GVDevolucion.Rows + If Dr.FCTextBox("TxtCantidad").Text.ToDouble > 0 Then + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Dr.FCTextBox("TxtCantidad").Text.ToDouble, Dr.DataKey("CveUM").ToString.ToEntero, Dr.DataKey("CvePS").ToString.ToEntero, Dr.DataKey("PU").ToString.ToDouble, -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 + Return ErrorMovInv + 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 + Dim objcompras As New ClsCompras() + If objcompras.GetCompraDetallealmacen(DDLDevolucion.SelectedValue.ToEntero) Then + GVDevolucion.DataSource = objcompras.DtResultados + GVDevolucion.DataBind() + End If + objcompras.Dispose() + 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) + 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 TxtSubTotal.Text.ToDouble > subtotaldevolucion - 1 AndAlso TxtSubTotal.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 + + End Sub + + Private Sub VinculaDevolucion() + 'Borramos el TmpDT + TmpDT.Clear() + + 'Iteramos el GridView de la OC + For Each gvr As GridViewRow In GVDevolucion.Rows + If gvr.FCTextBox("TxtCantidad").Text.ToDecimal > 0 Then + + 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 CvePS As Integer = gvr.DataKey("CvePS").ToString.ToEntero + 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 = 0 + Dim Descuento As Decimal = 0 + + 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.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 = 119 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 + 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:
{1}", 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: {1}", 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 + ElseIf CveMovimientoAlmacen = 0 Then + BtnCancelarCompra.Visible = True + End If + End If + End Sub + Protected Sub BtnCancelarCompra2_Click(sender As Object, e As EventArgs) + RegistraScript("$('#DivCancelarCompra').modal('hide');") + + Dim ObjAC As ClsContPAQi = Nothing + If UsuarioActual.Empresa.UsaAC 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 TxtFecha.Text.ToDate.Month < TxtFechaCancelacion.Text.ToDate.Month Or TxtFecha.Text.ToDate.Year < TxtFechaCancelacion.Text.ToDate.Year Then + + 'CREA POLIZA NEGATIVA + 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 + + 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 CvePrePoliza > 0 Then + If ObjContabilidad.GetPrePolizasDetalle(CvePrePoliza) 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, + dr("CveMovimientoAlmacen").ToString.ToEntero, dr("CveActivoFijo").ToString.ToEntero, dr("CveAcreedor").ToString.ToEntero, dr("CveColectiva").ToString.ToEntero, dr("CveCreditoDetalle").ToString.ToEntero, CveCuenta:=dr("CveCuenta").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) Then + ErrorCancelar = True + Exit For + End If + Next + Else + ErrorCancelar = True + End If + Else + ErrorCancelar = True + 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) 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) 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("

Ver Póliza de cancelación", 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 Double = dr("PU").ToString.ToDouble + Dim IVA As Double = dr("IVA").ToString.ToDouble + Dim RetIVA As Double = dr("RetIVA").ToString.ToDouble + Dim RetISR As Double = dr("RetISR").ToString.ToDouble + Dim IEPSPS As Double = dr("IEPSPSPorcentaje").ToString.ToDouble + Dim IEPSPSIVA As Double = If(dr("IEPSGrabaIVA").ToString = "True", dr("IEPSPorcentaje").ToString.ToDouble, 0) + Dim Descuento As Double = dr("Descuento").ToString.ToDouble + 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 Double = dr("Cantidad").ToString.ToDouble * (valores(1).ToDouble / 100) + Dim CveSubProyectoContrato As String = valores(0) + Dim CveProyecto As String = valores(0) + Dim Total As Double = 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 += $"
El folio {ArrayCveOC(i).ToEntero} 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:
{TextoErrorOC}

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($"OC #{FolioOC} {Promocion}
") + 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 + If UsuarioActual.CveEmpresa.Contiene(119) Then + If UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 And Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then + DivOCVinculaInv.Visible = True + End If + End If + + + 'TIPO CAMBIO + If CveCompra > 0 Then + DivTipoCambioOC.Visible = False + End If + + DTOCTemp.Columns.Add("PUTC", GetType(Double)) + DTOCTemp.Columns.Add("TotalTC", GetType(Double)) + DTOCTemp.Columns.Add("DescuentoTC", GetType(Double)) + DTOCTemp.Columns.Add("IVATC", GetType(Double)) + DTOCTemp.Columns.Add("IEPSPSTC", GetType(Double)) + DTOCTemp.Columns.Add("IEPSPSIVATC", GetType(Double)) + DTOCTemp.Columns.Add("RetIVATC", GetType(Double)) + DTOCTemp.Columns.Add("RetISRTC", GetType(Double)) + 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") + + '[IPP] - JAMEntregaAdelantado | AJUSTE DE CANITDAD POR RECIBIR EN BASE A SALDOS DE INV-COMPRAS + 'If UsuarioActual.CveUsuario = 100 Then + 'If Dr("CveTipoPS").ToString.ToEntero = 2 And UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then + ' Dr("CantidadDisponible") = If(Dr("CantidadDisponible").ToString.ToDouble > Dr("CantidadPendienteVincular").ToString.ToDouble, Dr("CantidadPendienteVincular"), Dr("CantidadDisponible")) + 'End If + 'End If + 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("CantidadDisponible > 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 And Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then + Select Case DdlOCVinculaInv.SelectedValue.ToEntero + Case 176 + DTOCGV = DTOCGV.FiltraParametros("(EstatusInventario = 3 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.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
Proyecto" + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then + GvOC1.Columns(5).HeaderText = "Proyecto
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("'", "")}', {gvr.DataKey("CantidadDisponible").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("'", "")}', {e.Row.DBCampo("CantidadDisponible").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("CantidadDisponible")}, 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 = "" + e.Row.FCLabel("LbEstatusInv").ForeColor = Drawing.Color.Red + Case 2 + e.Row.FCLabel("LbEstatusInv").Text = "" + e.Row.FCLabel("LbEstatusInv").ForeColor = Drawing.Color.DarkOrange + Case 3 + e.Row.FCLabel("LbEstatusInv").Text = "" + 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" 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 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 + + Dim SubTotalGV = 0.0D + Dim SubTotalCompra = If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteSinImpuestos"), TmpDT.SUM("Total").ToString.ToDecimal) + Dim DiferenciaPermitida = 1 + Dim Cont = 0 + 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 + Next + + If Math.Abs(SubTotalGV - SubTotalCompra) < DiferenciaPermitida Then + 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.Contiene(119) Then + If UsuarioActual.Empresa.UsaInventarios And UsuarioActual.Empresa.Funcionalidad(131).ToEntero > 0 And Not UsuarioActual.Empresa.Funcionalidad(153).ToEntero > 0 Then + If DdlOCVinculaInv.SelectedValue.ToEntero <= 0 Then + Alert("El campo Tipo de recepción almacén es necesario. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + End If + + If (HdnIEPSModificadoOC.Value.ToDecimal <> LbIEPSOC2.Text.ToDecimal) 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 + 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 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), 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 Double = dr("RetIVAPorcentaje").ToString.ToDecimal + Dim RetISR As Double = dr("RetISRPorcentaje").ToString.ToDecimal + Dim IEPSPS As Double = dr("IEPSPSPorcentaje").ToString.ToDecimal + Dim IEPSPSIVA As Double = dr("IEPSPSIVAPorcentaje").ToString.ToDecimal + Dim Descuento As Double = If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TxtDescuento.Text.ToDouble / 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 = -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 + + 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 + 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)("CantidadDisponible") = 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(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, TmpDT.SUMD("ImporteSinImpuestos"), TxtSubTotal2.Text.ToDouble) + TxtOtrosImpuestos.Text.ToDouble).ToDecimal - If(ListaDocumentos IsNot Nothing AndAlso ListaDocumentos.Count > 0 AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 AndAlso TxtTotal.Text.ToDecimal = 0, 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() + + 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.ToDouble, TxtSubTotal2.Text.ToDouble, TxtIVA.Text.ToDouble, TxtRetIVA.Text.ToDouble, TxtRetISR.Text.ToDouble, TxtTotal.Text.ToDouble) + + 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 Double = dr("RetIVAPorcentaje").ToString.ToDecimal + Dim RetISR As Double = dr("RetISRPorcentaje").ToString.ToDecimal + Dim IEPSPS As Double = dr("IEPSPSPorcentaje").ToString.ToDecimal + Dim IEPSPSIVA As Double = dr("IEPSPSIVAPorcentaje").ToString.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 = -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)("CantidadDisponible") = 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.ToDouble + + 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.ToDouble + + dr("Cantidad") = dr("Cantidad").ToString.ToEntero - Cantidad + dr("Total") = dr("Cantidad").ToString.ToEntero * dr("PU").ToString.ToDouble + + 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 /<> b > En caso de vincular la OC de esta manera la cantidad especificada sera considerada como recibida.

De ser correcto Continue o de lo contrario rectifique.", TipoMensaje.MsgAdvertencia) + + + Alert($"El concepto {PS} tiene especificada la cantidad {Cantidad} pero un costo de cero ($0).

En caso de vincular la OC de esta manera la cantidad especificada sera considerada como recibida.

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) + If DdlTipo.SelectedValue.ToEntero = 1 Then + + '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() + + 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 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) + + 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 + + '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 + + '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 + + '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 + 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(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append("") + strBody.Append("

Vinculación de orden de compra a factura

") + strBody.Append("

") + strBody.AppendFormat(" Se ha vinculado la OC # {0} {1}.", row("Folio"), If(row("FolioREQ").ToString.Length > 0, $", relacionada a la(s) requisicion(es) # {row("FolioREQ")}", "")) + strBody.Append("
") + strBody.Append(" Con los siguientes productos:") + strBody.Append("

") + + 'DETALLES + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + + For Each RowM As DataRow In DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows + strBody.AppendFormat(" ") + strBody.AppendFormat(" ", RowM("Cantidad").ToString.FormatoNumero) + strBody.AppendFormat(" ", RowM("UnidadMedida")) + strBody.AppendFormat(" ", RowM("Codigo")) + strBody.AppendFormat(" ", RowM("PS")) + strBody.AppendFormat(" ") + Next + + strBody.Append("
CantidadUMCódigoProducto
{0}{0}{0}{0}
") + strBody.Append("") + strBody.Append("") + + + '' 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(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append("") + strBody.Append("

Notificación de recepción de material

") + strBody.Append("

") + strBody.AppendFormat(" Se confirma recepción de material en almacén {0} vinculado la OC # {1} {2}.", DTMovimientos.FiltroPrimeroValor("Almacen"), row("Folio").ToString, If(row("FolioREQ").ToString.Length > 0, $", relacionada a la(s) requisicion(es) # {row("FolioREQ")}", "")) + strBody.Append("
") + strBody.Append(" Con los siguientes productos:") + strBody.Append("

") + + 'DETALLES + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + + For Each RowM As DataRow In DTMovimientos.FiltraParametros($"CveOrdenCompra = {row("CveOrdenCompra")}").Rows + strBody.AppendFormat(" ") + strBody.AppendFormat(" ", RowM("Cantidad").ToString.FormatoNumero) + strBody.AppendFormat(" ", RowM("UnidadMedida")) + strBody.AppendFormat(" ", RowM("Codigo")) + strBody.AppendFormat(" ", RowM("PS")) + strBody.AppendFormat(" ") + Next + + strBody.Append("
CantidadUMCódigoProducto
{0}{0}{0}{0}
") + strBody.Append("") + strBody.Append("") + + '' 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 {0}-{1} a la siguiente OC", Serie, Folio) + ' strBody.Append(" ") + ' strBody.Append(" ") + ' strBody.Append(" ") + ' strBody.Append(" ") + + ' 'Cargo el detalle + ' strBody.Append("
") + ' strBody.Append("
") + ' strBody.Append(" Ordenes de compra ") + ' strBody.Append(" + ' + ' ") + + ' 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("", RowM("Folio").ToString, RowM("Tipo")) + ' Next + + ' strBody.Append("
FolioTipo
{0}{1}
") + ' strBody.Append("
") + ' strBody.Append("
") + ' strBody.Append("") + + ' 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 {SerieLote} 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() + 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), 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.ToDouble * TipoCambioTemp + Dr("IVA") = Dr("IVA").ToString.ToDouble * TipoCambioTemp + Dr("RetIVA") = Dr("RetIVA").ToString.ToDouble * TipoCambioTemp + Dr("RetISR") = Dr("RetISR").ToString.ToDouble * TipoCambioTemp + Dr("IEPSPS") = Dr("IEPSPS").ToString.ToDouble * TipoCambioTemp + Dr("Descuento") = Dr("Descuento").ToString.ToDouble * TipoCambioTemp + Dr("OtrosGastos") = Dr("OtrosGastos").ToString.ToDouble * TipoCambioTemp + + Dim Total = (Dr("Cantidad").ToString.ToDouble * Dr("PU").ToString.ToDouble) - Dr("Descuento").ToString.ToDouble + Dr("OtrosGastos").ToString.ToDouble + Dr("Total") = Total + Next + + GvPS.DataSource = TmpDT + GvPS.DataBind() + UpPS.Update() + + + TxtSubTotal.Text = (TxtSubTotal.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + TxtSubTotal2.Text = (TxtSubTotal2.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + TxtIVA.Text = (TxtIVA.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + + 'IPP CAMBIADO - 5 DICIEMBRE 2016 + 'TxtTotal.Text = (TxtSubTotal2.Text.ToDouble + TxtIVA.Text.ToDouble).ToString.FormatoNumero.Replace(","c, "") + TxtTotal.Text = (TxtTotal.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + + SubTotalOriginal = TxtSubTotal.Text.ToDouble + SubTotal2Original = TxtSubTotal2.Text.ToDouble + + If TrDescuento.Visible Then TxtDescuento.Text = (TxtDescuento.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + If TrRetIVA.Visible Then TxtRetIVA.Text = (TxtRetIVA.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + If TrRetISR.Visible Then TxtRetISR.Text = (TxtRetISR.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + If TrIEPS.Visible Then TxtIEPS.Text = (TxtIEPS.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + If TrOtrosImpuestos.Visible Then TxtOtrosImpuestos.Text = (TxtOtrosImpuestos.Text.ToDouble * TipoCambioTemp).ToString.FormatoNumero.Replace(","c, "") + 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") + IVA = If(TmpDT.SUM("IVA") > 0, SubTotalIVA + SubTotalIEPSIVA, 0) + '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 = TxtRetIVA.Text.ToDecimal + Retenciones += TxtRetISR.Text.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 + + 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() + + 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 TempPorcentajeRetIVA = LblRetIVA.Text.ToDouble / 100 + 'Dim TempPorcentajeRetISR = LblRetISR.Text.ToDouble / 100 + + TempSubTotal = TxtSubTotal.Text.ToDouble + SubTotalOriginal = TxtSubTotal.Text.ToDouble + SubTotal2Original = TxtSubTotal2.Text.ToDouble + TempDescuentos = TxtDescuento.Text.Trim.ToDouble '+ LblAmortizacion.Text.Trim.ToDouble + 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, 2) + DifTotales = TxtTotal.Text.ToDouble - TempTotal + Dim DiferenciaPermitida = 0.6 + + If Math.Abs(DifTotales) > DiferenciaPermitida 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 + 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")) + 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) + 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")) + End If + + + CargaSubProyecto() + + + 'DdlProyecto.SelectedValueExist(GvRow.DataKey("CveProyecto")) + + DdlSubProyecto.SelectedValueExist(GvRow.DataKey("CveSubProyecto")) + 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").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 + + 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) + 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 + 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) + 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() + + '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 + ViewState("IEPSPS") = If(PS("IEPSPorcentaje").ToString = "-1", ViewState("IEPSPS"), PS("IEPSPorcentaje").ToString).ToString + 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) + TxtIEPSModal.Text = FormatoNumero(ViewState("IEPSPS").ToString().ToDouble * 100, 0) + + UpIVA.Update() + + If DdlClasificacion.SelectedIndex = 0 Then + 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 + + 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 + Private Sub CargaProyecto() + DdlProyecto.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"})) + + 'DdlProyecto.DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) + DdlProyecto.DataBind() + 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() + If CveProyecto > 0 Or UsuarioActual.Empresa.Tipo_CentroCosto.Contiene(1, 2) Then + DdlSubProyecto.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 + 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 {DdlSubProyecto.SelectedItem.Text} con la clasificación {DdlClasificacion.SelectedItem.Text} y el tipo de gasto {DdlTipoGasto.SelectedItem.Text}. Se excede por {Diferencia.FormatoNumero}", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + End If + + ActualizaTotales = True + Select Case Modalidad + Case "A" 'ADD + AddPS(TxtCantidad.Text.Trim.ToDouble, 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.ToDouble, Total, Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2), TxtRetIVAModal.Text.ToDouble / 100, TxtRetISRModal.Text.ToDouble / 100, TxtIEPSModal.Text.ToDouble / 100, 0, TxtDescuentoModal.Text.ToDouble, OtrosGastos:=TxtOtrosGastos.Text.ToDouble, CveTipoGasto:=DdlTipoGasto.SelectedValue.ToEntero, TipoGasto:=DdlTipoGasto.SelectedItem.Text, NoDeducible:=ChkEsNoDeduciblePS.Checked) + + 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() + 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 + UpPS.Update() + CargaGvPersonal() + End Sub + ''' + ''' Regresa el INDEX del row que acaba de agregar en el TMPDT + ''' + ''' + Private Function AddPS(Cantidad As Double, 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 Double, Total As Double, IVA As Double, RetIVA As Double, RetISR As Double, IEPSPS As Double, IEPSPSIVA As Double, Descuento As Double, 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 Double = 0, + Optional CveSATPS As Integer = -1, Optional CargaXml As Boolean = False, Optional CveTipoGasto As Integer = -1, Optional TipoGasto As String = "", Optional PorcentajeIVA As Double = 0, + Optional PorcentajeIEPS As Double = 0, Optional PorcentajeRetIVA As Double = 0, Optional PorcentajeRetISR As Double = 0, Optional NoDeducible As Boolean = False) 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" And CveSATPS > 0 Then + Dim DrPSSAT As DataRow = Nothing + If CargaXml Then + 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 + 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 + End If + End If + + 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" Then + Row("IVA") = Math.Round(IVA, DecimalesPermitidos) + Row("IVAPorcentaje") = PorcentajeIVA + 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) + Row("IVA") = Math.Round(IVA * Total, DecimalesPermitidos) + Row("IVAPorcentaje") = IVA + Row("RetIVA") = Math.Round(RetIVA * Total, DecimalesPermitidos) + Row("RetIVAPorcentaje") = RetIVA + Row("RetISR") = Math.Round(RetISR * Total, DecimalesPermitidos) + Row("RetISRPorcentaje") = RetISR + Row("IEPSPS") = Math.Round(IEPSPS * Total, DecimalesPermitidos) + Row("IEPSPSPorcentaje") = IEPSPS + End If + Row("ImporteConImpuestos") = (Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble) + Row("IVA").ToString.ToDouble + Row("IEPSPS").ToString.ToDouble - (Row("RetIVA").ToString.ToDouble + Row("RetISR").ToString.ToDouble) + Row("ImporteSinImpuestos") = Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble + + 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, "") + + 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 + + + + 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 + + End Sub + Private Sub UpdatePS() + 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 + + '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 + + + 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 + DrPS("CveClasificacion") = PSRow("CveClasificacion").ToString + DrPS("Clasificacion") = PSRow("Clasificacion").ToString + DrPS("CvePS") = DdlPS.SelectedValue + DrPS("PS") = PSRow("PS").ToString + DrPS("CveTipoPS") = PSRow("CveTipoPS").ToString.ToEntero + DrPS("CveSATPS") = PSRow("CveSATPS").ToString.ToEntero + DrPS("SATClaveProductoServicio") = PSRow("SATClaveProductoServicio").ToString + + '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.ToDouble - 1, 2) + Dim RetISR = (TxtRetISRModal.Text.ToDouble / 100) + Dim RetIVA = (TxtRetIVAModal.Text.ToDouble / 100) + Dim IEPSPS = (TxtIEPSModal.Text.ToDouble / 100) + Dim IEPSPSIVA = 0 + + If Not (CveCompra > 0 Or CveFactura > 0 Or OCVinculada) Then + 'If DdlIVA.SelectedValue.ToDouble = 0 Then DrPS("IVA") = 0 Else DrPS("IVA") = IVA * Total + DrPS("IVA") = IVA * Total + DrPS("IVAPorcentaje") = IVA + DrPS("RetIVA") = RetIVA * Total + DrPS("RetIVAPorcentaje") = RetIVA + DrPS("RetISR") = RetISR * Total + DrPS("RetISRPorcentaje") = RetISR + DrPS("IEPSPS") = IEPSPS * Total + DrPS("IEPSPSPorcentaje") = IEPSPS + DrPS("IEPSPSIVA") = IEPSPSIVA * Total + DrPS("IEPSPSIVAPorcentaje") = IEPSPSIVA + 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") + 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 + Alert("No hay partidas para reclasificar el SubProyecto", TipoMensaje.MsgAdvertencia) + Exit Sub + 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 + + 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) + 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.MsgInformacion) + + 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.MsgInformacion) + + 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) + DdlUnidadAlias.DataBind() + HdnPSAliasCveClasificacion.Value = DrPS("CveClasificacion").ToString + HdnPSAliasClasificacion.Value = DrPS("Clasificacion").ToString + End If + End If + UpPSAlias.Update() + End Sub + Protected Sub BtnAddPSAlias_Click(sender As Object, e As EventArgs) Handles BtnAddPSAlias.Click + Dim PS As New ClsProductosServicios + Dim CvePS = -1 + Dim tPS = "" + + CvePS = DdlPSAlias2.SelectedValue.ToEntero + tPS = DdlPSAlias2.SelectedText + + If PS.AddPSAlias(TxtPSAlias.Text.Trim, CvePS) Then + GlobalDTProductosServiciosAlias(-1) = 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 + + '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 + Next + + TmpDT.AcceptChanges() + + GvPS.DataSource = TmpDT + GvPS.DataBind() + UpPS.Update() + + Alert("Registro actualizado con exito.", 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() + End Sub + Private Sub GeneraGlobalEquivalencias() + Dim ObjPS = New ClsProductosServicios + If ObjPS.GetPSEquivalencias(-1, -1) Then + GlobalDTProductosServiciosEquivalencias(-1, -1) = 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).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) + 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).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) + 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() + End Sub + Private Sub GeneraGlobalUM() + Dim ObjPS = New ClsProductosServicios + Dim OjbUM As New ClsUnidadesMedida + + If ObjPS.GetPSEquivalencias(-1, -1) Then + GlobalDTProductosServiciosEquivalencias(-1, -1) = 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("", 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("", 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() + 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 + LBDevolucionAlmacen.Text = " Cancelar Devolución Almacén" + LBDevolucionAlmacen.ToolTip = "¿Está seguro de Cancelar la Devolución de Almacén?" + Else + LBDevolucionAlmacen.Text = " Solicitar Devolución Almacén" + LBDevolucionAlmacen.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) + 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, UsuarioActual.CveEmpresa) 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() + 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() + + Dim SaldoAnticipo = 0.0 + Dim CveCompras As String = "" + If ChkNCInvNC.Checked 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 + 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 + End If + + + If SaldoAnticipo <= 0 Then + Alert("No hay movimientos seleccionados para aplicar", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + LbNCInvSaldo.Text = SaldoAnticipo.FormatoNumero() + + If ChkNCInvNC.Checked Then + Dim ObjInventarios As New ClsInventarios + If ObjInventarios.RecepcionAlmacenGet(-1, -1, UsuarioActual.CveEmpresa, CveProveedor) AndAlso ObjInventarios.DtResultados.FiltraParametros($"CveCompra IN ({CveCompras}) AND CantidadF > 0").Rows.Count > 0 Then + DtPendientesAlmacen = ObjInventarios.DtResultados.FiltraParametros($"CveCompra IN ({CveCompras}) AND 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() + UpNCInv.Update() + RegistraScript("$('#FacturaNC').modal('hide');", "FacturaNC") + End If + RegistraScript("$('#ModalNCInv').modal('show');", "ModalNCInv") + 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() + + 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 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 +#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 + 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("Folio: {1} Fecha: {2} {3} {4}", 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 CuentasContablesInvalidasSIG As New StringBuilder + Dim IdCtaContable As Integer = 0 + Dim CveCuenta 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContActivoFijoSIG").ToString.ToEntero + End If + End If + If ImporteMovimiento <> 0 Then + If IdCtaContable = 0 Then + CuentasContablesInvalidas.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 49))("ConceptoContable").ToString) + End If + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & 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), CveCuenta:=CveCuenta) 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 + CveCuenta = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"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("CveCuenta") = CveCuenta + 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("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) + End If + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 68))("ConceptoContable").ToString) + 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), CveCuenta:=Row("CveCuenta").ToString.ToEntero) Then + TieneError = True + Exit For + End If + End If + Next + End If + End If + + ImporteMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 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 + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaGastoSIG").ToString.ToEntero + Else + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToString.ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", 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("
" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 6))("ConceptoContable").ToString) + End If + If CveCuenta = 0 Then + CuentasContablesInvalidasSIG.Append("
" & 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), CveCuenta:=CveCuenta) 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 + + 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 + Dim Dr As DataRow = Nothing + If ObjInventario.GetFletes(UsuarioActual.CveEmpresa, CveFlete) Then + If ObjInventario.DtResultados.Rows.Count > 0 Then + Dr = ObjInventario.DtResultados.Rows(0) + End If + End If + If Dr IsNot Nothing Then + If Not ObjInventario.UpdateFlete(CveFlete, Dr("Descripcion").ToString, Dr("Fecha").ToString.ToDate, -1, CveCompra, UsuarioActual.CveUsuario) Then + ErrorTrans = True + End If + Else + 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) 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) 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.ToDecimal, 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() + + Dim ObjCompras As New ClsCompras + If ObjCompras.GetImportaciones(-1, -1, -1, "-1", "-1", UsuarioActual.CveEmpresa) Then + DdlImportaciones.DataSource = ObjCompras.DtResultados + DdlImportaciones.Items.Insert(0, New ListItem("Seleccione", "-1")) + End If + ObjCompras.Dispose() + + Dim ObjInv As New ClsInventarios + If ObjInv.GetFletes(UsuarioActual.CveEmpresa) Then + DdlFletes.DataSource = ObjInv.DtResultados + DdlFletes.Items.Insert(0, New ListItem("Seleccione", "-1")) + End If + ObjInv.Dispose() + + DdlImportaciones.DataBind() + DdlFletes.DataBind() + + 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) 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 + + + 'EMPIEZA OBJETOS Y TRANSACCIONES + 'Dim OC As New ClsOC + 'Dim OCBitacora As New ClsOIEventos(OC.IniciaTransacSQL()) + 'Dim ObjInventarios As New ClsInventarios(OC.IniciaTransacSQL()) + 'Dim ObjConta As New ClsContabilidad(OC.IniciaTransacSQL()) + + + + 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("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 'And DtInvOC.Rows.Count > 0 + 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 + + 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("") + DrInvOCDiferencias("TipoCambioAjuste") = drInv("TipoCambioAjuste").ToString.ToDecimal + DrInvOCDiferencias("Diferencia") = ((gvr.FCTextBox("TxtPU").Text.ToDecimal * drInv("TipoCambioAjuste").ToString.ToDecimal) - drInv("PU").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 + 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) 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 = -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 = Now + 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 + PUCompra = DrDiferencias("PUCompra").ToString.ToDecimal + PS = DrDiferencias("PS").ToString + + Fecha = Now + 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}", ProveedorNombre, DrDiferencias("FolioOC")) + + 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 + CveCuentaAlmacen = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {DrDiferencias("CveAlmacen").ToString.ToEntero}").ToEntero + + If DiferenciaInvOC.RoundSQL() <> 0 Then + CvePrePoliza = ObjConta.AddPrePolizas("Compras/OC-(OCAlmacen)", 74, DiferenciaInvOC, DiferenciaInvOC, 1, Fecha, ConceptoPartida, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + If CvePrePoliza > 0 Then + + If CveMoneda = 2 And UsuarioActual.CveEmpresa.Contiene(119) Then + ImporteME = (DiferenciaInvOC / TCInvOC).RoundSQL() + ImporteMEComp = (DiferenciaInvOC - ImporteME).RoundSQL() + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, -DiferenciaInvOC, SerieFolio, 177, ConceptoPartida, Fecha, IdCtaContableRecepcionOCER, -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=-DiferenciaInvOC, CveOCDetalle:=CveOCDetalle) 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 Not 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 + 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, If(ConceptoSalida = 0, IdCtaContableAlmacen, IdCtaContableRecepcionOCER), -1, CveProveedor:=CveProveedor, CveMovimientoAlmacen:=CveMovimientoAlmacen, CveOC:=CveOrdenCompra, ImporteMX:=-DiferenciaInvOC, CveCuenta:=CveCuentaAlmacen, CveOCDetalle:=CveOCDetalle) 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) 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 + 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.") + RecargaGlobalEquivalencias() + End If + ObjPS.Dispose() + + TxtPS.Text = "" + TxtCodigoPS.Text = "" + DdlUnidadMedida.SelectedValueExist(-1) + DdlClasificacionPS.SelectedValueExist(-1) + DdlTipoPS.SelectedValueExist(-1) + + UpAgregarPS.Update() + + RegistraScript("$('#DivAgregarPS').modal('hide');") + RecargaPSGlobal() + End Sub + Private Sub RecargaPSGlobal() + Dim ObjPS As New ClsProductosServicios + + If ObjPS.GetPSSimplificado(-1) Then Application("GlobalDTPSSimplificado") = ObjPS.DtResultados.AsEnumerable() + + ObjPS.Dispose() + End Sub + +#End Region + +#Region "TIPO DE COMPRA" + + Protected Sub DdlTipoCompra_SelectedIndexChanged(sender As Object, e As EventArgs) + + End Sub + +#End Region + + + Protected Sub BtnFacturaNC_Click(sender As Object, e As EventArgs) + If ChkNCInvNC.Checked Then + CargaNCINV() + 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(10).Visible = True + UpEsNoDeduciblePS.Visible = True + Else + EsNoDeducible = False + dvNoDeducible.Visible = False + GvPS.Columns(10).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 End Class \ No newline at end of file diff --git a/General/SaldosIniciales.aspx b/General/SaldosIniciales.aspx index 89ed63393..880cb1253 100644 --- a/General/SaldosIniciales.aspx +++ b/General/SaldosIniciales.aspx @@ -43,11 +43,12 @@ - - - - - + + + + + + diff --git a/General/SaldosIniciales.aspx.vb b/General/SaldosIniciales.aspx.vb index 3fbfc4bca..47e7f074e 100644 --- a/General/SaldosIniciales.aspx.vb +++ b/General/SaldosIniciales.aspx.vb @@ -449,7 +449,26 @@ Partial Class General_SaldosIniciales Alert("El nombre de la diescisieteava columna debe ser 'Clave Unidad'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If + ElseIf RblFormato.SelectedValue = "12" Then + If Not dt.Columns(0).ColumnName = "CodigoPS" Then + Alert("El nombre de la primera columna debe ser 'CodigoPS'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(1).ColumnName = "Almacen" Then + Alert("El nombre de la segunda columna debe ser 'Almacen'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + + If Not dt.Columns(2).ColumnName = "Existencia" Then + Alert("El nombre de la tercera columna debe ser 'Existencia'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + + If Not dt.Columns(3).ColumnName = "Valor" Then + Alert("El nombre de la cuarta columna debe ser 'Valor'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If End If @@ -606,10 +625,10 @@ Partial Class General_SaldosIniciales 'If Not ObjPS.UpdatePS(CveClasificacion, 1, CveUnidadMedida, Codigo, "", CodigoBarras, Descripcion, 0, 1, 1, False, 0, True, True, True, UsuarioActual.CveUsuario, CvePS, -1, -1, CveSATPS, ' CveTipoPS:=CveTipoPS, CveMarca:=CveMarca, CveTamaño:=CveTamaño, CveMedida:=CveMedida) Then ErrorPS = True - Codigo.GuardaLog - Exit For - Else - Contador += 1 + Codigo.GuardaLog + Exit For + Else + Contador += 1 End If Else If ObjPS.AddPS(CveClasificacion, 1, CveUnidadMedida, Codigo, "", "", Descripcion, 0, 0, 0, False, 0, False, True, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 1, 1, @@ -873,7 +892,7 @@ Partial Class General_SaldosIniciales End If Dim ConceptoContablePago As Integer = 17 If TipoDocto = "NC" Then ConceptoContablePago = 60 - + 'PrePólizaDetalle If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Total, Folio, IIf(TipoDocto = "Fac", 5, 18).ToString.ToEntero, String.Format("{0}-{1}", Serie, Folio), Fecha, -1, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=Total, CveSubProyecto:=Sucursal.ToEntero) Then ErrorCompras = True : Exit For If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, SubTotal, Folio, 6, String.Format("{0}-{1}", Serie, Folio), Fecha, -1, -1, CveCompra:=CveCompra, CveProveedor:=CveProveedor, ImporteMX:=SubTotal, CveClasificacion:=CveClasificacion, CveSubProyecto:=Sucursal.ToEntero) Then ErrorCompras = True : Exit For @@ -927,7 +946,7 @@ Partial Class General_SaldosIniciales If Not CvePS > 0 Then Alert(String.Format("No se encontró el Producto Servicio"), TipoMensaje.MsgError) : ErrorVentas = True ' If Not CveSucursal > 0 Then Alert("No se encontró la sucursal.", TipoMensaje.MsgError) : ErrorVentas = True If Not CveUnidadMedida > 0 Then Alert(String.Format("No se encontró la Unidad de Medida."), TipoMensaje.MsgError) : ErrorVentas = True - Dim dtsubp As DataTable = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa) + Dim dtsubp As DataTable = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa) For Each Row As DataRow In dt.FiltraParametros("RFC <> ''").Rows @@ -953,7 +972,7 @@ Partial Class General_SaldosIniciales Dim IEPS As Decimal = Row("IEPS").ToString.ToDecimal Dim CveClienteSucursal As Integer = Row("CveClienteSucursal").ToString.ToEntero - GuardaLog(Sucursal + "-" + Row("Sucursal").ToString) + GuardaLog(Sucursal + "-" + Row("Sucursal").ToString) 'Temporalmente SE BORRARA Dim Transaccion As String = "" ' Row("Transaccion2").ToString Dim Folio2 As String = "" ' Row("Folio2").ToString @@ -1015,7 +1034,7 @@ Partial Class General_SaldosIniciales ConceptoContablePago = 91 End If - + 'PrePólizaDetalle If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, SubTotal, Folio.ToString, 4, String.Format("{0}-{1}", Serie, Folio), Fecha, -1, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveClasificacion:=CveClasificacion, ImporteMX:=SubTotal, CveSubProyecto:=Sucursal.ToEntero) Then ErrorVentas = True : Exit For If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Total, Folio.ToString, ConceptoContable, String.Format("{0}-{1}", Serie, Folio), Fecha, -1, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=Total) Then ErrorVentas = True : Exit For @@ -1501,7 +1520,52 @@ Partial Class General_SaldosIniciales End Try ObjConta.Dispose() + ElseIf RblFormato.SelectedValue = "12" Then + Dim ObjMovimientos As New ClsInventarios + ObjMovimientos.IniciaTransacSQL() + Dim OcurrioError As Boolean = False + Try + For Each almacenSinRepetir As DataRow In dt.FiltraParametros("", DistinctColumns:={"Almacen"}).Rows + Dim almacenActual As String = almacenSinRepetir("Almacen").ToString + Dim CveAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"Almacen = '{almacenActual}'").ToEntero + Dim movimientoCabecera As Integer = ObjMovimientos.AddMovimiento(CveAlmacen, 1, 1, Date.Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1) + If CveAlmacen > 0 Then + For Each nuevaEntrada As DataRow In dt.FiltraParametros($"Almacen = '{almacenActual}'").Rows + Dim CvePS As Integer = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePS", $"Codigo = '{nuevaEntrada("CodigoPS")}'").ToEntero + Dim CveUM As Integer = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveUnidadMedida", $"Codigo = '{nuevaEntrada("CodigoPS")}'").ToEntero + If CvePS > 0 Then + Dim Cantidad As Decimal = nuevaEntrada("Existencia").ToString.ToDecimal + Dim Valor As Decimal = nuevaEntrada("Valor").ToString.ToDecimal + If Not ObjMovimientos.AddMovimientoDetalle(movimientoCabecera, Cantidad, CveUM, CvePS, (Valor / Cantidad), -1, -1) Then + OcurrioError = True + End If + Else + OcurrioError = True + + End If + Next + Else + OcurrioError = True + 'alert amacén no existe + Exit For + End If + + Next + Catch ex As Exception + OcurrioError = True + ObjMovimientos.RollBack() + End Try + + If Not OcurrioError Then + ObjMovimientos.Commit() + Alert("Se cargó correctamente #movimientos") + Else + Alert("Ocurrió un error al cargar las existencias", TipoMensaje.MsgError) + ObjMovimientos.RollBack() + End If + + ObjMovimientos.Dispose() End If End If @@ -1528,6 +1592,8 @@ Partial Class General_SaldosIniciales Directorio = AppDomain.CurrentDomain.BaseDirectory & "Empresas\Grales\SaldosIniciales\FormatoContabilidad.xlsx" ElseIf RblFormato.SelectedValue = "9" Then Directorio = AppDomain.CurrentDomain.BaseDirectory & "Empresas\Grales\SaldosIniciales\FormatoContabilidad.xlsx" + ElseIf RblFormato.SelectedValue = "12" Then + Directorio = AppDomain.CurrentDomain.BaseDirectory & "Empresas\Grales\SaldosIniciales\FormatoAlmacen.xlsx" End If Dim Archivo As New IO.FileInfo(Directorio) diff --git a/Inventarios/RepNotasSinAlmacen.aspx b/Inventarios/RepNotasSinAlmacen.aspx index 2f1be222a..b66f5625e 100644 --- a/Inventarios/RepNotasSinAlmacen.aspx +++ b/Inventarios/RepNotasSinAlmacen.aspx @@ -1,207 +1,215 @@ -<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="RepNotasSinAlmacen.aspx.vb" Inherits="RepNotasSinAlmacen" %> - - -
  • - Exportar a Excel -
  • -
  • - Generar PDF -
  • -
    - - - - - - - Reporte de Compras / Notas Sin Entrada - - - - -
    -
    -
    +<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="RepNotasSinAlmacen.aspx.vb" Inherits="RepNotasSinAlmacen" %> + + +
  • + Exportar a Excel +
  • +
  • + Generar PDF +
  • +
    + + + + + + + Reporte de Compras / Notas Sin Entrada + + + + +
    +
    +
    -
    -
    -
    -
    Cliente:
    -
    - -
    -
    Proveedor:
    -
    - -
    -
    Fecha Inicio:
    -
    -
    - - - - -
    - - -
    -
    Fecha Fin:
    -
    -
    - - - - -
    - - -
    -
    -
    -
    Tipo Documento:
    -
    - - - - - - - -
    -
    Tipo Documento:
    -
    - - - - -
    - <%--
    Sucursal:
    + +
    +
    +
    +
    Cliente:
    +
    + +
    +
    Proveedor:
    +
    + +
    +
    Fecha Inicio:
    +
    +
    + + + + +
    + + +
    +
    Fecha Fin:
    +
    +
    + + + + +
    + + +
    +
    +
    +
    Tipo Documento:
    +
    + + + + + + + +
    +
    Tipo Documento:
    +
    + + + + +
    + <%--
    Sucursal:
    -
    --%> -
    Proyecto:
    -
    - - - -
    -
    -
    -
    -
    - - - - - - - -
    - " style="display: inline-block; margin-right: -20px; width: 150px;" /> - " style="margin-top: -3px;" class="btn btn-circle btn-sm label-info"> -
    - - - - - - - - - - - - - - -
    -
    - - -
    - " style="display: inline-block; margin-right: -20px; width: 150px;" /> - " style="margin-top: -3px;" class="btn btn-circle btn-sm label-info"> -
    - - - - - - - - - - - - - -
    -
    -
    -
    -
    - - - +
    --%> +
    Proyecto:
    +
    + + + +
    +
    +
    +
    + +
    +
    + + + + + +
    + " style="display: inline-block; margin-right: -20px; width: 150px;" /> + " style="margin-top: -3px;" class="btn btn-circle btn-sm label-info"> +
    + + + + + + + + + + + + + + +
    +
    + + +
    + " style="display: inline-block; margin-right: -20px; width: 150px;" /> + " style="margin-top: -3px;" class="btn btn-circle btn-sm label-info"> +
    + + + + + + + + + + + + + + + + + + + + +
    +
    +
    +
    +
    +
    + + <%-- --%> - - + --%> + + diff --git a/Inventarios/RepNotasSinAlmacen.aspx.vb b/Inventarios/RepNotasSinAlmacen.aspx.vb index 247211f30..6973d632c 100644 --- a/Inventarios/RepNotasSinAlmacen.aspx.vb +++ b/Inventarios/RepNotasSinAlmacen.aspx.vb @@ -70,9 +70,11 @@ Partial Class RepNotasSinAlmacen End If End Sub Private Sub CargaPermisos() - Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) + Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) + Dim TienePermisoDesmarcar As Boolean = UsuarioActual.TienePermisoProceso(278) GvVentas.Columns(4).Visible = TienePermisoImportes - GvCompras.Columns(3).Visible = TienePermisoImportes + GvCompras.Columns(3).Visible = TienePermisoImportes + GvCompras.Columns(4).Visible = TienePermisoDesmarcar End Sub Private Sub CargaCombos() TxtFechaF.Text = Date.Now.ToShortDateString @@ -261,12 +263,12 @@ Partial Class RepNotasSinAlmacen ImprimirPDF("Empresas/Grales/Formatos/RepNotasSinAlmacenCompras.rdlc", DtNotasSinAlmacenCompras, params, "RepNotasSinAlmacenCompras", Formato:=Formato) End If - End Sub + End Sub #End Region - + #End Region - - + + Protected Sub GvCompras_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then If Not e.Row.DBCampo("CveCompraDetalle").ToEntero > 0 Then @@ -275,9 +277,40 @@ Partial Class RepNotasSinAlmacen e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Left e.Row.Cells(1).Text = e.Row.DBCampo("Fecha").ToDate.ToShortDateString e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Center - e.Row.Cells(2).Text = "" & e.Row.DBCampo("RazonSocial") & "" + e.Row.Cells(2).Text = "" & e.Row.DBCampo("RazonSocial") & "" + + If GvCompras.Columns(4).Visible Then + e.Row.Cells(4).Text = "" + End If + End If End If - End Sub - + End Sub + + Protected Sub BtnActulizarEstatus_Click(sender As Object, e As EventArgs) + If UsuarioActual.TienePermisoProceso(278) Then + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + + Dim CveCompraDetalle As Integer = GvRow.DataKey("CveCompraDetalle") + Dim CveCompra As Integer = GvRow.DataKey("CveCompra") + Dim CvePS As Integer = GvRow.DataKey("CveCompra") + + Dim PS = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).FiltroPrimeroValor("PSCodigo", $"CvePS = {CvePS}") + + Dim ObjCompras As New ClsCompras + Dim ObjEventos As New ClsOIEventos + If ObjCompras.UpdateEstatusAlmacenDetalle(CveCompraDetalle, 1) Then + If ObjEventos.AddEventoBitacora(String.Format("Se cambio el estatus de almacen del producto/servicio: {0} a 'No Recibir'", PS), "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompra) Then + Alert("El producto se desmarco correctamente.") + End If + End If + ObjCompras.Dispose() + ObjEventos.Dispose() + + CargaDatos() + End If + + + End Sub + End Class diff --git a/OC/OC.aspx b/OC/OC.aspx index 30e93fdef..24f8facb8 100644 --- a/OC/OC.aspx +++ b/OC/OC.aspx @@ -828,8 +828,7 @@ - - + diff --git a/Ventas/RepConciliacionEmitidosSat.aspx b/Ventas/RepConciliacionEmitidosSat.aspx index 9be90a3db..753022003 100644 --- a/Ventas/RepConciliacionEmitidosSat.aspx +++ b/Ventas/RepConciliacionEmitidosSat.aspx @@ -40,14 +40,14 @@
    - Facturas emitidas en el sat sin registrar (<%= GVConciliacionemitidasSAT.Rows.Count %>) + Facturas emitidas en el sat sin registrar de
    -
    - - +
    + +
    @@ -98,14 +98,15 @@ <%-- --%> - + - r + r +
    @@ -153,6 +154,15 @@ diff --git a/Ventas/RepConciliacionEmitidosSat.aspx.cs b/Ventas/RepConciliacionEmitidosSat.aspx.cs index 649c309c0..4e7ae76cd 100644 --- a/Ventas/RepConciliacionEmitidosSat.aspx.cs +++ b/Ventas/RepConciliacionEmitidosSat.aspx.cs @@ -11,6 +11,7 @@ using Extensiones; using System.Data; using System.Text; using ADSistemaLibrary.SatXml; +//using ADS_CFDI_SAT; public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas { @@ -44,7 +45,7 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas DdlPS.setEsWebService(false); DdlPS.ddl.DataSource = get_GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion: CveClasificacion, Estatus: 1, AplicaParaVenta: 1); DdlPS.ddl.DataBind(); - } + } } } protected void CargaConciliacionemitidasSATGet() @@ -52,6 +53,8 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas ClsVentas ObjV = new ClsVentas(); ObjV.ConciliacionemitidasSATGet(UsuarioActual.CveEmpresa); GVConciliacionemitidasSAT.DataSource = ObjV.DtResultados.FiltraParametros("", "CveVenta"); + Ltlsinregistrar.Text = $"{ObjV.DtResultados.COUNT("FolioFiscal","CveVenta IS NULL")}"; + ltlTotal.Text = $"{ObjV.DtResultados.Rows.Count}"; ObjV.Dispose(); GVConciliacionemitidasSAT.DataBind(); UpDatosReporte.Update(); @@ -229,6 +232,39 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas int CvePsReconstruccion = DdlPS.SelectedValue.ToEntero(); int CveSubProyectoReconstruccion = DdlSubProyectoDatos.SelectedValue.ToEntero(); //Modelos.Factura.MMensajeFactura resp; + + string Moneda = objxml.comprobante.Moneda; + if (objxml.comprobante.Version == "3.2") + { + switch (Moneda) + { + case "Peso Mexicano": Moneda = "MXN"; break; + case "Dolar Americano": Moneda = "USD"; break; + } + + } + string formadepago = objxml.comprobante.FormaPago; + string metododepago = objxml.comprobante.MetodoPago; + if (objxml.comprobante.Version == "3.2") + { + switch (objxml.comprobante.MetodoPago)//si es correcto estan invertidos + { + case "TRANSFERENCIA ELECTRONICA": formadepago = "03"; break; + default: formadepago = objxml.comprobante.MetodoPago; break; + } + + } + if (objxml.comprobante.Version == "3.2") + { + switch (objxml.comprobante.FormaPago)//si es correcto estan invertidos + { + case "PAGO EN UNA SOLA EXHIBICION": metododepago = "PUE"; break; + default: metododepago = objxml.comprobante.FormaPago; break; + } + + } + + Modelos.Factura objfact = new Modelos.Factura(UsuarioActual) { TipoMensajeRespuesta = Modelos.TipoMensajeRespuesta.TextoLimpio,//?que es esto @@ -242,8 +278,8 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas TipoCambio = objxml.comprobante.TipoCambio, //ConvertirPesos =false,//?para que sirve MonedaSAT = objxml.comprobante.Moneda, - CveMoneda = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $" AbreviaturaSAT= '{objxml.comprobante.Moneda}' ").ToEntero(), - Moneda = GlobalDTMonedas.FiltroPrimeroValor("Moneda", $" AbreviaturaSAT= '{objxml.comprobante.Moneda}' "), + CveMoneda = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $" AbreviaturaSAT= '{Moneda}' ").ToEntero(), + Moneda = GlobalDTMonedas.FiltroPrimeroValor("Moneda", $" AbreviaturaSAT= '{Moneda}' "), TipoDocto = objxml.comprobante.TipoDeComprobanteSIG, RefDocto = "", CveMesa = -1, @@ -292,11 +328,11 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas } objfact.CveAlmacen = -1; - objfact.CveFormaPago33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("CveFormaPago", $"ClaveFormaPagoSAT = '{objxml.comprobante.FormaPago}'").ToEntero(); + objfact.CveFormaPago33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("CveFormaPago", $"ClaveFormaPagoSAT = '{formadepago}'").ToEntero(); objfact.FormaPagoSAT33 = objxml.comprobante.FormaPago; objfact.FormaPago33 = objxml.comprobante.FormaPagoTexto; - objfact.CveMetodoPago33 = GlobalDTVtaMetodoPago.FiltroPrimeroValor("CveMetodoPago", $" ClaveMetodoPagoSAT = '{objxml.comprobante.MetodoPago}'").ToEntero(); - objfact.CveMetodoPago = GlobalDTVtaMetodoPago.FiltroPrimeroValor("CveMetodoPago", $" ClaveMetodoPagoSAT = '{objxml.comprobante.MetodoPago}'").ToEntero(); + objfact.CveMetodoPago33 = GlobalDTVtaMetodoPago.FiltroPrimeroValor("CveMetodoPago", $" ClaveMetodoPagoSAT = '{metododepago}'").ToEntero(); + objfact.CveMetodoPago = GlobalDTVtaMetodoPago.FiltroPrimeroValor("CveMetodoPago", $" ClaveMetodoPagoSAT = '{metododepago}'").ToEntero(); objfact.ClaveMetodoPagoSAT = objxml.comprobante.MetodoPago; objfact.MetodoPago33 = objxml.comprobante.MetodoPagoTexto; objfact.CveUsoCFDI = get_GlobalDTSATUsosCFDI(-1).FiltroPrimeroValor("CveUsoCFDI", $"UsoCFDI = '{objxml.receptor.UsoCFDI}'").ToEntero(); @@ -304,16 +340,16 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas objfact.ClaveUsoCFDI = objxml.receptor.UsoCFDI; objfact.CveClienteSucursal = -1; - objfact.DtDetalle = CreaDTDetalle(UsuarioActual, objxml.conceptos, objfact.CveSubProyecto, CvePsReconstruccion); - + objfact.DtDetalle = CreaDTDetalle(UsuarioActual, objxml.conceptos, objfact.CveSubProyecto, CvePsReconstruccion, objxml); + objfact.TipoCambioDolares = objxml.comprobante.TipoCambio; objfact.SubTotal = objxml.comprobante.SubTotal; objfact.Descuento = objxml.comprobante.Descuento; objfact.Amortizacion = 0; - objfact.IVA = objxml.Impuestos.Where(x => x.Impuesto == "002" && x.Tipo == "Traslados").Sum(item => item.Importe); - objfact.RetIVA = objxml.Impuestos.Where(x => x.Impuesto == "002" && x.Tipo == "Retenciones").Sum(item => item.Importe); - objfact.RetISR = objxml.Impuestos.Where(x => x.Impuesto == "001" && x.Tipo == "Retenciones").Sum(item => item.Importe); - objfact.IEPS = objxml.Impuestos.Where(x => x.Impuesto == "003").Sum(item => item.Importe); + objfact.IVA = objxml.Impuestos.Where(x => (x.Impuesto == "002" || x.Impuesto == "IVA") && x.Tipo == "Traslados").Sum(item => item.Importe); + objfact.RetIVA = objxml.Impuestos.Where(x => (x.Impuesto == "002" || x.Impuesto == "IVA") && x.Tipo == "Retenciones").Sum(item => item.Importe); + objfact.RetISR = objxml.Impuestos.Where(x => (x.Impuesto == "001" || x.Impuesto == "ISR") && x.Tipo == "Retenciones").Sum(item => item.Importe); + objfact.IEPS = objxml.Impuestos.Where(x => (x.Impuesto == "003" || x.Impuesto == "IEPS")).Sum(item => item.Importe); objfact.Total = objxml.comprobante.Total; objfact.TotalOtrosConceptos = 0; @@ -328,7 +364,7 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas } return objfact; } - private DataTable CreaDTDetalle(Usuario UsuarioActual, List conceptos, int CveSubProyecto, int CvePsReconstruccion) + private DataTable CreaDTDetalle(Usuario UsuarioActual, List conceptos, int CveSubProyecto, int CvePsReconstruccion, XmlSatCFDI objxml) { bool continuar = true; var TmpDT = new DataTable(); @@ -433,14 +469,29 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas } DrSubProyecto = get_GlobalDTSubProyectos(-1, CveSubProyecto, UsuarioActual.CveEmpresa).Rows[0]; + + + if (objxml.comprobante.Version == "3.2") + { + item.ClaveUnidad = item.Unidad; + switch (item.ClaveUnidad) + { + case "TON": item.ClaveUnidad = "A75"; break; + case "No aplica": item.ClaveUnidad = "ACT"; break; + case "LITROS": item.ClaveUnidad = "E32"; break; + case "M3-KM": item.ClaveUnidad = "M73"; break; + } + + } + DrUmSat = GlobalDTPSATUM.FiltroPrimero(string.Format("SATClaveUnidadMedida='{0}'", item.ClaveUnidad)); } - if (continuar && DrUmSat == null ) { continuar = false; strErrores.AppendLine($"No se encontro la unidad de medida en el catalogo del sat '{item.ClaveUnidad}', favor de contactar a soporte tecnico."); } + if (continuar && DrUmSat == null) { continuar = false; strErrores.AppendLine($"No se encontro la unidad de medida en el catalogo del sat '{item.ClaveUnidad}', favor de contactar a soporte tecnico."); } if (continuar) { DrUm = get_GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa).FiltroPrimero(string.Format("CveUnidadMedidaSAT={0}", DrUmSat["CveSATUnidadMedida"])); } - if (continuar && DrUm == null) { continuar = false; strErrores.AppendLine($"No se encontro la unidad de medida relacionada a la clave del sat '{item.ClaveUnidad}', favor de asignarla en el catalogo de unidad de medida."); } + if (continuar && DrUm == null) { continuar = false; strErrores.AppendLine($"No se encontro la unidad de medida relacionada a la clave del sat '{item.ClaveUnidad}', favor de asignarla en el catalogo de unidad de medida."); } if (continuar) { //no se encontro una undidad de medida para @@ -475,24 +526,34 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas Row["CveTipoPS"] = DrPS["CveTipoPS"]; Row["CveTipoInvPS"] = DrPS["Inv_CveMetodoInventario"]; Row["CveTamaño"] = DrPS["CveTamaño"]; - ADSistemaLibrary.SatXml.CFDIConceptoImpuesto impuesto = item.Impuestos.FirstOrDefault(x => x.Impuesto == "002" && x.Tipo == "Traslado"); - decimal sumaimpuesto=0; + CFDIConceptoImpuesto impuesto = item.Impuestos.FirstOrDefault(x => x.Impuesto == "002" && x.Tipo == "Traslado"); + decimal sumaimpuesto = 0; decimal PorcentajeIVA = 0; if (impuesto != null) { decimal decimpuesto = 0; decimal.TryParse(impuesto.TasaOCuota, out decimpuesto); - PorcentajeIVA = decimpuesto/100; - Row["PorcentajeIVA"] = decimpuesto / 100; - Row["ImporteIVA"] = decimpuesto / 100;// impuesto.Importe;//Math.Round(item.Importe * (decimpuesto/100), 2); + PorcentajeIVA = decimpuesto / 100; + Row["PorcentajeIVA"] = PorcentajeIVA; + Row["ImporteIVA"] = impuesto.Importe ;// impuesto.Importe;//Math.Round(item.Importe * (decimpuesto/100), 2); sumaimpuesto += impuesto.Importe; } else { Row["PorcentajeIVA"] = 0; Row["ImporteIVA"] = 0; + if (objxml.comprobante.Version == "3.2") + { + if (item.Importe > 0) + { + PorcentajeIVA = .16M; + Row["PorcentajeIVA"] = PorcentajeIVA; + Row["ImporteIVA"] = item.Importe * PorcentajeIVA;//Math.Round(((item.Importe / (1 + PorcentajeIVA))*.16M),2); + + } + } } - Row["IVA"] = Row["PorcentajeIVA"]; + Row["IVA"] = Row["ImporteIVA"]; impuesto = item.Impuestos.FirstOrDefault(x => x.Impuesto == "003" && x.Tipo == "Traslado"); if (impuesto != null) { @@ -541,7 +602,7 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas Row["TipoDescuento"] = "2"; //Row["Total"] = item.Importe - sumaimpuesto; - Row["Total"] = item.Importe /(1+ PorcentajeIVA); + Row["Total"] = item.Importe / (1 + PorcentajeIVA); Row["TotalImporte"] = item.Importe; Row["SATClaveProdServ"] = item.ClaveProdServ; @@ -579,14 +640,12 @@ public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas } } /* -//SatCFDI namespace ADS_CFDI_SAT { - /// - /// clase para contener los valores de un xml CFDI + /// clase para contener los valores de un xml CFDI cambio norama /// public class XmlSatCFDI { @@ -660,6 +719,7 @@ namespace ADS_CFDI_SAT return lcon; } + public static XmlSatCFDI readXML(string fileUrl) { XmlSatCFDI xmlCFDI = new XmlSatCFDI(); @@ -677,7 +737,11 @@ namespace ADS_CFDI_SAT //(canread = xtr.Read()) para evitar ciclos infinitos, todos los .Read() los guardo en la variable Canread y en los while reviso primero esta variable if (File.Exists(fileUrl)) { - using (XmlTextReader xtr = new XmlTextReader(fileUrl)) + XmlReaderSettings settings = new XmlReaderSettings(); + settings.ConformanceLevel = ConformanceLevel.Fragment; + settings.IgnoreWhitespace = true; + settings.IgnoreComments = true; + using (XmlReader xtr = XmlReader.Create(fileUrl, settings)) { while ((canread = xtr.Read()) && !(xtr.NodeType == XmlNodeType.Element && xtr.Name == keyComprobante)) @@ -686,40 +750,40 @@ namespace ADS_CFDI_SAT } if (xtr.NodeType == XmlNodeType.Element && xtr.Name == keyComprobante) { - xmlCFDI.comprobante.xmlns_cfdi = xtr.GetAttribute("xmlns:cfdi"); - xmlCFDI.comprobante.xmlns_xsi = xtr.GetAttribute("xmlns:xsi"); - xmlCFDI.comprobante.xsi_schemaLocation = xtr.GetAttribute("xsi:schemaLocation"); - xmlCFDI.comprobante.Version = xtr.GetAttribute("Version"); - xmlCFDI.comprobante.Serie = xtr.GetAttribute("Serie"); - xmlCFDI.comprobante.Folio = xtr.GetAttribute("Folio"); - xmlCFDI.comprobante.Fecha = xtr.GetAttribute("Fecha"); - xmlCFDI.comprobante.Moneda = xtr.GetAttribute("Moneda"); - decimal SubTotal = 0; - decimal.TryParse(xtr.GetAttribute("SubTotal"), out SubTotal); - xmlCFDI.comprobante.SubTotal = SubTotal; - - decimal Total = 0; - decimal.TryParse(xtr.GetAttribute("Total"), out Total); - xmlCFDI.comprobante.Total = Total; - - decimal Descuento = 0; - decimal.TryParse(xtr.GetAttribute("Descuento"), out Descuento); - xmlCFDI.comprobante.Descuento = Descuento; - - decimal TipoCambio = 0; - decimal.TryParse(xtr.GetAttribute("TipoCambio"), out TipoCambio); - xmlCFDI.comprobante.TipoCambio = TipoCambio; - - xmlCFDI.comprobante.TipoDeComprobante = xtr.GetAttribute("TipoDeComprobante"); - xmlCFDI.comprobante.FormaPago = xtr.GetAttribute("FormaPago"); - xmlCFDI.comprobante.MetodoPago = xtr.GetAttribute("MetodoPago"); - xmlCFDI.comprobante.CondicionesDePago = xtr.GetAttribute("CondicionesDePago"); - xmlCFDI.comprobante.LugarExpedicion = xtr.GetAttribute("LugarExpedicion"); - xmlCFDI.comprobante.Confirmacion = xtr.GetAttribute("Confirmacion"); - xmlCFDI.comprobante.NoCertificado = xtr.GetAttribute("NoCertificado"); - xmlCFDI.comprobante.Sello = xtr.GetAttribute("Sello"); - xmlCFDI.comprobante.Certificado = xtr.GetAttribute("Certificado"); int Nivel = xtr.Depth; + bool cont = xtr.MoveToFirstAttribute(); + while (cont) + { + + switch (xtr.Name.ToUpper()) + { + case "XMLNS:CFDI": xmlCFDI.comprobante.xmlns_cfdi = xtr.Value; break; + case "XMLNS:XSI": xmlCFDI.comprobante.xmlns_xsi = xtr.Value; break; + case "XSI:SCHEMALOCATION": xmlCFDI.comprobante.xsi_schemaLocation = xtr.Value; break; + case "VERSION": xmlCFDI.comprobante.Version = xtr.Value; break; + case "SERIE": xmlCFDI.comprobante.Serie = xtr.Value; break; + case "FOLIO": xmlCFDI.comprobante.Folio = xtr.Value; break; + case "FECHA": xmlCFDI.comprobante.Fecha = xtr.Value; break; + case "MONEDA": xmlCFDI.comprobante.Moneda = xtr.Value; break; + case "SUBTOTAL": decimal SubTotal = 0; decimal.TryParse(xtr.Value, out SubTotal); xmlCFDI.comprobante.SubTotal = SubTotal; break; + case "TOTAL": decimal Total = 0; decimal.TryParse(xtr.Value, out Total); xmlCFDI.comprobante.Total = Total; break; + case "DESCUENTO": decimal Descuento = 0; decimal.TryParse(xtr.Value, out Descuento); xmlCFDI.comprobante.Descuento = Descuento; break; + case "TIPOCAMBIO": decimal TipoCambio = 0; decimal.TryParse(xtr.Value, out TipoCambio); xmlCFDI.comprobante.TipoCambio = TipoCambio; break; + case "TIPODECOMPROBANTE": xmlCFDI.comprobante.TipoDeComprobante = xtr.Value; break; + case "FORMAPAGO": xmlCFDI.comprobante.FormaPago = xtr.Value; break; + case "FORMADEPAGO": xmlCFDI.comprobante.FormaPago = xtr.Value; break; + case "METODOPAGO": xmlCFDI.comprobante.MetodoPago = xtr.Value; break; + case "METODODEPAGO": xmlCFDI.comprobante.MetodoPago = xtr.Value; break; + case "CONDICIONESDEPAGO": xmlCFDI.comprobante.CondicionesDePago = xtr.Value; break; + case "LUGAREXPEDICION": xmlCFDI.comprobante.LugarExpedicion = xtr.Value; break; + case "CONFIRMACION": xmlCFDI.comprobante.Confirmacion = xtr.Value; break; + case "NOCERTIFICADO": xmlCFDI.comprobante.NoCertificado = xtr.Value; break; + case "SELLO": xmlCFDI.comprobante.Sello = xtr.Value; break; + case "CERTIFICADO": xmlCFDI.comprobante.Certificado = xtr.Value; break; + } + cont = xtr.MoveToNextAttribute(); + } + cont = xtr.MoveToFirstAttribute(); while ((canread = xtr.Read()) && xtr.NodeType != XmlNodeType.Element) { } while (canread && xtr.Depth > Nivel) { @@ -727,8 +791,18 @@ namespace ADS_CFDI_SAT { if (xtr.NodeType == XmlNodeType.Element && xtr.Name == keyCfdiRelacionados) { - string TipoRelacion = xtr.GetAttribute("TipoRelacion"); int cDepth = xtr.Depth; + + string TipoRelacion = null; + cont = xtr.MoveToFirstAttribute(); + while (cont) + { + switch (xtr.Name.ToUpper()) + { + case "TIPORELACION": TipoRelacion = xtr.Value; break; + } + cont = xtr.MoveToNextAttribute(); + } while ((canread = xtr.Read()) && xtr.NodeType != XmlNodeType.Element) { } while (canread && xtr.Depth > cDepth) { @@ -745,22 +819,40 @@ namespace ADS_CFDI_SAT } if (xtr.NodeType == XmlNodeType.Element && xtr.Name == keyEmisor) { - xmlCFDI.emisor.RegimenFiscal = xtr.GetAttribute("RegimenFiscal"); - xmlCFDI.emisor.Nombre = xtr.GetAttribute("Nombre"); - xmlCFDI.emisor.Rfc = xtr.GetAttribute("Rfc"); - while ((canread = xtr.Read()) && xtr.NodeType != XmlNodeType.Element) { } + int curentNivel = xtr.Depth; + cont = xtr.MoveToFirstAttribute(); + while (cont) + { + switch (xtr.Name.ToUpper()) + { + case "REGIMENFISCAL": xmlCFDI.emisor.RegimenFiscal = xtr.Value; break; + case "NOMBRE": xmlCFDI.emisor.Nombre = xtr.Value; break; + case "RFC": xmlCFDI.emisor.Rfc = xtr.Value; break; + } + cont = xtr.MoveToNextAttribute(); + } + while ((canread = xtr.Read()) && !(xtr.NodeType == XmlNodeType.Element && curentNivel >= xtr.Depth)) { }//continua hasta que no tenga nodos y (el nodo sea tipo elemnto y ete en el mismo nivel) } if (xtr.NodeType == XmlNodeType.Element && xtr.Name == keyReceptor) { - xmlCFDI.receptor.Rfc = xtr.GetAttribute("Rfc"); - xmlCFDI.receptor.Nombre = xtr.GetAttribute("Nombre"); - xmlCFDI.receptor.ResidenciaFiscal = xtr.GetAttribute("ResidenciaFiscal"); - xmlCFDI.receptor.NumRegIdTrib = xtr.GetAttribute("NumRegIdTrib"); - xmlCFDI.receptor.UsoCFDI = xtr.GetAttribute("UsoCFDI"); + int curentNivel = xtr.Depth; + cont = xtr.MoveToFirstAttribute(); + while (cont) + { + switch (xtr.Name.ToUpper()) + { + case "RFC": xmlCFDI.receptor.Rfc = xtr.Value; break; + case "NOMBRE": xmlCFDI.receptor.Nombre = xtr.Value; break; + case "RESIDENCIAFISCAL": xmlCFDI.receptor.ResidenciaFiscal = xtr.Value; break; + case "NUMREGIDTRIB": xmlCFDI.receptor.NumRegIdTrib = xtr.Value; break; + case "USOCFDI": xmlCFDI.receptor.UsoCFDI = xtr.Value; break; + } + cont = xtr.MoveToNextAttribute(); + } - while ((canread = xtr.Read()) && xtr.NodeType != XmlNodeType.Element) { } + while ((canread = xtr.Read()) && !(xtr.NodeType == XmlNodeType.Element && curentNivel >= xtr.Depth)) { }//continua hasta que no tenga nodos y (el nodo sea tipo elemnto y ete en el mismo nivel) } if (xtr.NodeType == XmlNodeType.Element && xtr.Name == keyConceptos) { @@ -770,25 +862,27 @@ namespace ADS_CFDI_SAT { if (xtr.Name == "cfdi:Concepto") { - CFDIConcepto concepto = new CFDIConcepto(); - concepto.ClaveProdServ = xtr.GetAttribute("ClaveProdServ"); - concepto.NoIdentificacion = xtr.GetAttribute("NoIdentificacion"); - concepto.Cantidad = xtr.GetAttribute("Cantidad"); - concepto.ClaveUnidad = xtr.GetAttribute("ClaveUnidad"); - concepto.Unidad = xtr.GetAttribute("Unidad"); - decimal ValorUnitario = 0; - decimal.TryParse(xtr.GetAttribute("ValorUnitario"), out ValorUnitario); - concepto.ValorUnitario = ValorUnitario; - decimal Importe = 0; - decimal.TryParse(xtr.GetAttribute("Importe"), out Importe); - concepto.Importe = Importe; - decimal DDescuento = 0; - decimal.TryParse(xtr.GetAttribute("Descuento"), out DDescuento); - concepto.Descuento = DDescuento; - concepto.Descripcion = xtr.GetAttribute("Descripcion"); - int cDepthb = xtr.Depth; + CFDIConcepto concepto = new CFDIConcepto(); + cont = xtr.MoveToFirstAttribute(); + while (cont) + { + switch (xtr.Name.ToUpper()) + { + case "CLAVEPRODSERV": concepto.ClaveProdServ = xtr.Value; break; + case "NOIDENTIFICACION": concepto.NoIdentificacion = xtr.Value; break; + case "CANTIDAD": concepto.Cantidad = xtr.Value; break; + case "CLAVEUNIDAD": concepto.ClaveUnidad = xtr.Value; break; + case "UNIDAD": concepto.Unidad = xtr.Value; break; + case "VALORUNITARIO": decimal ValorUnitario = 0; decimal.TryParse(xtr.Value, out ValorUnitario); concepto.ValorUnitario = ValorUnitario; ; break; + case "IMPORTE": decimal Importe = 0; decimal.TryParse(xtr.Value, out Importe); concepto.Importe = Importe; ; break; + case "DESCUENTO": decimal DDescuento = 0; decimal.TryParse(xtr.Value, out DDescuento); concepto.Descuento = DDescuento; ; break; + case "DESCRIPCION": concepto.Descripcion = xtr.Value; break; + } + cont = xtr.MoveToNextAttribute(); + } + xtr.MoveToFirstAttribute(); while ((canread = xtr.Read()) && xtr.NodeType != XmlNodeType.Element) { } while (canread && xtr.Depth > cDepthb) { @@ -850,14 +944,14 @@ namespace ADS_CFDI_SAT while (canread && xtr.Depth > cDepth) { CFDIImpuesto impuest = new CFDIImpuesto(); - if (xtr.Name == "cfdi:Traslado" || xtr.Name == "cfdi:Retencion") + if (xtr.Name == "cfdi:Traslado" || xtr.Name == "cfdi:Retencion" && xmlCFDI.comprobante.Version != null) { impuest.Tipo = xtr.LocalName == "Traslado" ? "Traslados" : (xtr.LocalName == "Retencion" ? "Retenciones" : ""); - impuest.Impuesto = xtr.GetAttribute("Impuesto"); + impuest.Impuesto = xmlCFDI.comprobante.Version == "3.3" ? xtr.GetAttribute("Impuesto") : xtr.GetAttribute("impuesto"); impuest.TipoFactor = xtr.GetAttribute("TipoFactor"); - impuest.TasaOCuota = xtr.GetAttribute("TasaOCuota"); + impuest.TasaOCuota = xmlCFDI.comprobante.Version == "3.3" ? xtr.GetAttribute("TasaOCuota") : xtr.GetAttribute("tasa"); decimal ImImporte = 0; - decimal.TryParse(xtr.GetAttribute("Importe"), out ImImporte); + decimal.TryParse((xmlCFDI.comprobante.Version == "3.3" ? xtr.GetAttribute("Importe") : xtr.GetAttribute("importe")), out ImImporte); impuest.Importe = ImImporte; xmlCFDI.Impuestos.Add(impuest); } @@ -871,7 +965,7 @@ namespace ADS_CFDI_SAT while ((canread = xtr.Read()) && xtr.NodeType != XmlNodeType.Element) { } while (canread && xtr.Depth > cDepth) { - if (xtr.NodeType == XmlNodeType.Element && xtr.LocalName == "TimbreFiscalDigital") + if (xtr.NodeType == XmlNodeType.Element && xtr.LocalName == "TimbreFiscalDigital" && xmlCFDI.comprobante.Version != null) { xmlCFDI.complemento.xmlns_tfd = xtr.GetAttribute("xmlns:tfd"); xmlCFDI.complemento.xsi_schemaLocation = xtr.GetAttribute("xsi:schemaLocation"); @@ -879,9 +973,9 @@ namespace ADS_CFDI_SAT xmlCFDI.complemento.UUID = xtr.GetAttribute("UUID"); xmlCFDI.complemento.FechaTimbrado = xtr.GetAttribute("FechaTimbrado"); xmlCFDI.complemento.RfcProvCertif = xtr.GetAttribute("RfcProvCertif"); - xmlCFDI.complemento.SelloCFD = xtr.GetAttribute("SelloCFD"); - xmlCFDI.complemento.NoCertificadoSAT = xtr.GetAttribute("NoCertificadoSAT"); - xmlCFDI.complemento.SelloSAT = xtr.GetAttribute("SelloSAT"); + xmlCFDI.complemento.SelloCFD = xmlCFDI.comprobante.Version == "3.3" ? xtr.GetAttribute("SelloCFD") : xtr.GetAttribute("selloCFD"); + xmlCFDI.complemento.NoCertificadoSAT = xmlCFDI.comprobante.Version == "3.3" ? xtr.GetAttribute("NoCertificadoSAT") : xtr.GetAttribute("noCertificadoSAT"); + xmlCFDI.complemento.SelloSAT = xmlCFDI.comprobante.Version == "3.3" ? xtr.GetAttribute("SelloSAT") : xtr.GetAttribute("selloSAT"); } while ((canread = xtr.Read()) && xtr.NodeType != XmlNodeType.Element) { } @@ -897,10 +991,8 @@ namespace ADS_CFDI_SAT } } - - } - if (xmlCFDI.comprobante.Version == "3.3") + if (xmlCFDI.comprobante.Version == "3.3" || xmlCFDI.comprobante.Version == "3.2") { return xmlCFDI; } @@ -914,7 +1006,7 @@ namespace ADS_CFDI_SAT public void ImprimirPDF(string NombreArchivo) { XmlSatCFDI objxml = this; - string rutaReporte = string.Format("{0}{1}", Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName, "\\Empresas\\Grales\\Formatos\\CFDIV3.rdlc"); + string rutaReporte = string.Format("{0}{1}", Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).Parent.FullName, "\\Empresas\\Grales\\Formatos\\CFDIV3.rdlc"); ClbNegBICFDv3_2.ClsNegCBBGenerar QR = new ClbNegBICFDv3_2.ClsNegCBBGenerar(); @@ -1081,44 +1173,6 @@ namespace ADS_CFDI_SAT public decimal Descuento { get; set; } public decimal TipoCambio { get; set; } public string TipoDeComprobante { get; set; } - public string TipoDeComprobanteSIG - { - get - { - string retorno = ""; - - if (Version == "3.3") - { - - - - - switch (TipoDeComprobante) - { - case "I": - retorno = "Ing"; - break; - case "E": - retorno = "Egs"; - break; - case "P": - retorno = "PA"; - break; - //case "T": - // retorno = "Traslado"; - // break; - //case "N": - // retorno = "Nómina"; - // break; - - default: - break; - } - } - else { retorno = TipoDeComprobante; } - return retorno; - } - } public string TipoDeComprobanteTexto { get @@ -1149,6 +1203,89 @@ namespace ADS_CFDI_SAT break; } } + if (Version == "3.2") + { + switch (TipoDeComprobante) + { + case "ingreso": + retorno = "Ing"; + break; + case "egreso": + retorno = "Egs"; + break; + case "P": + retorno = "PA"; + break; + //case "T": + // retorno = "Traslado"; + // break; + //case "N": + // retorno = "Nómina"; + // break; + + default: + retorno = TipoDeComprobante; + break; + } + } + else { retorno = TipoDeComprobante; } + return retorno; + } + } + + public string TipoDeComprobanteSIG + { + get + { + string retorno = ""; + if (Version == "3.3") + { + switch (TipoDeComprobante) + { + case "I": + retorno = "Ing"; + break; + case "E": + retorno = "Egs"; + break; + case "P": + retorno = "PA"; + break; + //case "T": + // retorno = "Traslado"; + // break; + //case "N": + // retorno = "Nómina"; + // break; + + default: + break; + } + } + if (Version == "3.2") + { + switch (TipoDeComprobante) + { + case "ingreso": + retorno = "Ing"; + break; + case "egreso": + retorno = "Egs"; + break; + case "P": + retorno = "PA"; + break; + //case "T": + // retorno = "Traslado"; + // break; + //case "N": + // retorno = "Nómina"; + // break; + + default: + break; + } + } else { retorno = TipoDeComprobante; } return retorno; } @@ -1184,6 +1321,7 @@ namespace ADS_CFDI_SAT case "30": retorno = "Aplicación de anticipos"; break; case "31": retorno = "Intermediario pagos"; break; case "99": retorno = "Por definir"; break; + default: retorno = FormaPago; break; } return retorno; @@ -1200,6 +1338,7 @@ namespace ADS_CFDI_SAT { case "PUE": retorno = "Pago en una sola exhibición"; break; case "PPD": retorno = "Pago en parcialidades o diferido"; break; + default: retorno = MetodoPago; break; } return retorno; } @@ -1487,4 +1626,8 @@ namespace ADS_CFDI_SAT public decimal Impuesto_Importe { get; set; } } -}*/ \ No newline at end of file +} + + + + */ \ No newline at end of file diff --git a/Ventas/Ventas.aspx.vb b/Ventas/Ventas.aspx.vb index 3f0ab4f82..7f4141744 100644 --- a/Ventas/Ventas.aspx.vb +++ b/Ventas/Ventas.aspx.vb @@ -1,5756 +1,5757 @@ -Option Explicit On -Option Strict On - -Imports Extensiones -Imports System.Data -Imports System.IO -Imports System.Xml -Imports Microsoft.Reporting.WebForms -Imports System.Security.Cryptography.X509Certificates -Imports System.Globalization - -Partial Class Ventas +Option Explicit On +Option Strict On + +Imports Extensiones +Imports System.Data +Imports System.IO +Imports System.Xml +Imports Microsoft.Reporting.WebForms +Imports System.Security.Cryptography.X509Certificates +Imports System.Globalization + +Partial Class Ventas Inherits ClsPaginas -#Region "Propiedades" - Private Const NumeroDecimales As Integer = 2 - - Dim ColumnaDescuento As Integer = 10 - Dim ColumnaPredial As Integer = 11 - Dim ColumnaIVA As Integer = 12 - Dim ColumnaIEPS As Integer = 13 - Dim ColumnaRetIVA As Integer = 14 - Dim ColumnaRetISR As Integer = 15 - Dim ColumnaEditar As Integer = 17 - Dim ColumnaEliminar As Integer = 18 - - 'Factura de ventas - Dim DTConceptos As DataTable - Private Property Version As String - Private Property Fecha As String - Private Property SerieXML As String - Private Property FolioXML As String - Private Property SubTotal As Decimal - Private Property Total As Decimal = 0 - Private Property Descuentos 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 OtrosImpuestos 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 NumRow As Integer - Private Property EsSupervisor As Boolean = False - Private Property MandarCorreoSupervisor As Boolean = False - Private ReadOnly Property ExFolioFactura As Boolean - Get - Return CBool(ViewState("ExFolioFactura")) - End Get - End Property - Private Property CveFactura As Integer - Get - Return ViewState("CveFactura").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveFactura") = value - End Set - End Property - - Private Property idCuentaContabilizacion As Integer - Get - Return ViewState("idCuentaContabilizacion").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("idCuentaContabilizacion") = value - End Set - End Property - - Private Property CuentasContablesInvalidas As StringBuilder - Get - Return CType(ViewState("CuentasContablesInvalidas"), StringBuilder) - End Get - Set(value As StringBuilder) - ViewState("CuentasContablesInvalidas") = value - End Set - End Property - - 'Local - Private Property TmpDT As DataTable - Get - Return If(IsNothing(ViewState("TmpDT")), Nothing, CType(ViewState("TmpDT"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDT") = value - End Set - End Property - Private Property TmpDTError As DataTable - Get - Return If(IsNothing(ViewState("TmpDTError")), Nothing, CType(ViewState("TmpDTError"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTError") = value - End Set - End Property - - Private Property TmpDTImpuestos As DataTable - Get - Return If(IsNothing(ViewState("TmpDTImpuestos")), Nothing, CType(ViewState("TmpDTImpuestos"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTImpuestos") = value - End Set - End Property - Private Property TmpDTImpuestosIVAIEPS As DataTable - Get - Return If(IsNothing(ViewState("TmpDTImpuestosIVAIEPS")), Nothing, CType(ViewState("TmpDTImpuestosIVAIEPS"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTImpuestosIVAIEPS") = value - End Set - End Property - Private Property TmpDTDocumentosRelacionados As DataTable - Get - Return If(IsNothing(ViewState("TmpDTDocumentosRelacionados")), Nothing, CType(ViewState("TmpDTDocumentosRelacionados"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTDocumentosRelacionados") = value - End Set - End Property - Private Property TmpDTNCVinculadas As DataTable - Get - Return If(IsNothing(ViewState("TmpDTNCVinculadas")), Nothing, CType(ViewState("TmpDTNCVinculadas"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTNCVinculadas") = value - End Set - End Property - Private Property TmpDTEnvioDireccion As DataTable - Get - Return If(IsNothing(ViewState("TmpDTEnvioDireccion")), Nothing, CType(ViewState("TmpDTEnvioDireccion"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTEnvioDireccion") = value - End Set - 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 CveAlmacenDevolucion As Integer - Get - Return ViewState("CveAlmacenDevolucion").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveAlmacenDevolucion") = value - End Set - End Property - - Private Property EraCotizacion As Integer - Get - Return ViewState("EraCotizacion").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("EraCotizacion") = value - End Set - End Property - Private Property FacturaMateriales As Integer - Get - Return ViewState("FacturaMateriales").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("FacturaMateriales") = value - End Set - End Property - Private Property TmpDTDeducciones As DataTable - Get - Return If(IsNothing(ViewState("TmpDTDeducciones")), Nothing, CType(ViewState("TmpDTDeducciones"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTDeducciones") = value - End Set - End Property - - Private Property TmpDTComplementos As DataTable - Get - Return If(IsNothing(ViewState("TmpDTComplementos")), Nothing, CType(ViewState("TmpDTComplementos"), DataTable)) - End Get - Set(value As DataTable) - ViewState("TmpDTComplementos") = value - End Set - End Property - Private Property DTmpC As DataTable - Get - Return If(IsNothing(ViewState("DTmpC")), Nothing, CType(ViewState("DTmpC"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DTmpC") = value - End Set - End Property - Private Property DTmpF As DataTable - Get - Return If(IsNothing(ViewState("DTmpF")), Nothing, CType(ViewState("DTmpF"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DTmpF") = value - End Set - End Property - Private Property DTSucursal As DataTable - Get - Return If(IsNothing(ViewState("DTSucursal")), Nothing, CType(ViewState("DTSucursal"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DTSucursal") = value - End Set - End Property - Private Property DTOrdenesCompra As DataTable - Get - Return If(IsNothing(ViewState("DTOrdenesCompra")), Nothing, CType(ViewState("DTOrdenesCompra"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DTOrdenesCompra") = value - End Set - End Property - Private Property DTOrdenesCompraPS As DataTable - Get - Return If(IsNothing(ViewState("DTOrdenesCompraPS")), Nothing, CType(ViewState("DTOrdenesCompraPS"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DTOrdenesCompraPS") = value - End Set - End Property - Private Property DtOCTmpDT As DataTable - Get - Return If(IsNothing(ViewState("DtOCTmpDT")), Nothing, CType(ViewState("DtOCTmpDT"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtOCTmpDT") = value - End Set - End Property - Private Property DTRemisiones As DataTable - Get - Return If(IsNothing(ViewState("DTRemisiones")), Nothing, CType(ViewState("DTRemisiones"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DTRemisiones") = value - End Set - End Property - Private Property RemisionesLista As List(Of Integer) - Get - Return If(IsNothing(ViewState("RemisionesLista")), Nothing, CType(ViewState("RemisionesLista"), List(Of Integer))) - End Get - Set(value As List(Of Integer)) - ViewState("RemisionesLista") = value - End Set - End Property - Private Property Pedidos2Lista As List(Of Integer) - Get - Return If(IsNothing(ViewState("Pedidos2Lista")), Nothing, CType(ViewState("Pedidos2Lista"), List(Of Integer))) - End Get - Set(value As List(Of Integer)) - ViewState("Pedidos2Lista") = value - End Set - End Property - Private Property DtRemisionesPS As DataTable - Get - Return If(IsNothing(ViewState("DtRemisionesPS")), Nothing, CType(ViewState("DtRemisionesPS"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtRemisionesPS") = value - End Set - End Property - Private Property DtCotizaciones As DataTable - Get - Return If(IsNothing(ViewState("DtCotizaciones")), Nothing, CType(ViewState("DtCotizaciones"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtCotizaciones") = value - End Set - End Property - Private Property CotizacionesLista As List(Of Integer) - Get - Return If(IsNothing(ViewState("CotizacionesLista")), Nothing, CType(ViewState("CotizacionesLista"), List(Of Integer))) - End Get - Set(value As List(Of Integer)) - ViewState("CotizacionesLista") = value - End Set - End Property - Private Property DtCotizacionesPS As DataTable - Get - Return If(IsNothing(ViewState("DtCotizacionesPS")), Nothing, CType(ViewState("DtCotizacionesPS"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtCotizacionesPS") = value - End Set - End Property - Private Property DtCotizacionTmpDT As DataTable - Get - Return If(IsNothing(ViewState("DtCotizacionTmpDT")), Nothing, CType(ViewState("DtCotizacionTmpDT"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtCotizacionTmpDT") = value - End Set - End Property - Private Property DtRemisionesTmpDT As DataTable - Get - Return If(IsNothing(ViewState("DtRemisionesTmpDT")), Nothing, CType(ViewState("DtRemisionesTmpDT"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtRemisionesTmpDT") = value - End Set - End Property - Private Property DtPedidos2TmpDT As DataTable - Get - Return If(IsNothing(ViewState("DtPedidos2TmpDT")), Nothing, CType(ViewState("DtPedidos2TmpDT"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtPedidos2TmpDT") = value - End Set - End Property - Private Property DtRemConceptosSurtidos As DataTable - Get - Return If(IsNothing(ViewState("DtRemConceptosSurtidos")), Nothing, CType(ViewState("DtRemConceptosSurtidos"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtRemConceptosSurtidos") = value - End Set - End Property - Private Property HuboCambioRemi As Boolean - Get - Return If(IsNothing(ViewState("HuboCambioRemi")), False, CType(ViewState("HuboCambioRemi"), Boolean)) - End Get - Set(value As Boolean) - ViewState("HuboCambioRemi") = value - End Set - End Property - Private Property AplicaGastoContrato As Boolean - Get - Return If(IsNothing(ViewState("AplicaGastoContrato")), False, CType(ViewState("AplicaGastoContrato"), Boolean)) - End Get - Set(value As Boolean) - ViewState("AplicaGastoContrato") = value - End Set - End Property - Private Property EsCreaApartirDe As Boolean - Get - Return If(IsNothing(ViewState("EsCreaApartirDe")), False, CType(ViewState("EsCreaApartirDe"), Boolean)) - End Get - Set(value As Boolean) - ViewState("EsCreaApartirDe") = value - End Set - End Property - Private Property RequiereAlmacenDestino As Boolean - Get - Return If(IsNothing(ViewState("RequiereAlmacenDestino")), False, CType(ViewState("RequiereAlmacenDestino"), Boolean)) - End Get - Set(value As Boolean) - ViewState("RequiereAlmacenDestino") = value - End Set - End Property - Private Property RequiereAlmacenOrigen As Boolean - Get - Return If(IsNothing(ViewState("RequiereAlmacenOrigen")), False, CType(ViewState("RequiereAlmacenOrigen"), Boolean)) - End Get - Set(value As Boolean) - ViewState("RequiereAlmacenOrigen") = value - End Set - End Property - Private Property EmpresaActual As Empresa - Get - Return CType(ViewState("EmpresaActual"), Empresa) - End Get - Set(value As Empresa) - ViewState("EmpresaActual") = value - End Set - End Property - - Property CargaDocumentoOC As Boolean - Get - If ViewState("CargaDocumentoOC") Is Nothing Then - Return False - Else - Return DirectCast(ViewState("CargaDocumentoOC"), Boolean) - End If - End Get - Set(value As Boolean) - ViewState("CargaDocumentoOC") = value - End Set - End Property - Private Property DTFacNC As DataTable - Get - Return If(IsNothing(ViewState("DTFacNC")), Nothing, CType(ViewState("DTFacNC"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DTFacNC") = value - End Set - End Property - Private Property DtPromociones As DataTable - Get - Return If(IsNothing(ViewState("DtPromociones")), Nothing, CType(ViewState("DtPromociones"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtPromociones") = value - End Set - End Property - Private ReadOnly Property CveCliente As Integer - Get - Return ViewState("CveCliente").ToString.ToEntero - End Get - End Property - Private ReadOnly Property CveClienteAnterior As Integer - Get - Return ViewState("CveClienteAnterior").ToString.ToEntero - End Get - End Property - - Private Property CveClienteSucursal As Integer - Get - If ViewState("CveClienteSucursal") Is Nothing Then - Return -1 - Else - Return ViewState("CveClienteSucursal").ToString.ToEntero - End If - End Get - Set(value As Integer) - ViewState("CveClienteSucursal") = value - End Set - End Property - Private Property CveAnticipo As Integer - Get - If ViewState("CveAnticipo") Is Nothing Then - Return -1 - Else - Return ViewState("CveAnticipo").ToString.ToEntero - End If - End Get - Set(value As Integer) - ViewState("CveAnticipo") = value - End Set - End Property - - Private Property CveUsuarioActual As Integer - Get - Return ViewState("CveUsuarioActual").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveUsuarioActual") = value - End Set - End Property - Private ReadOnly Property Mail As String - Get - Return ViewState("Mail").ToString - End Get - End Property - Private ReadOnly Property MailCC As String - Get - Return ViewState("MailCC").ToString - End Get - End Property - Private ReadOnly Property CveVenta As Integer - Get - Return ViewState("CveVenta").ToString.ToEntero - End Get - End Property - Private Property CveVentaPadre As Integer - Get - Return If(IsNothing(ViewState("CveVentaPadre")), -1, ViewState("CveVentaPadre").ToString.ToEntero) - End Get - Set(value As Integer) - ViewState("CveVentaPadre") = value - End Set - End Property - Private Property CveEstatusFacturaPadre As Integer - Get - Return If(IsNothing(ViewState("CveEstatusFacturaPadre")), -1, ViewState("CveEstatusFacturaPadre").ToString.ToEntero) - End Get - Set(value As Integer) - ViewState("CveEstatusFacturaPadre") = value - End Set - End Property - Private Property CveMovimientoDetalle As Integer - Get - Return If(IsNothing(ViewState("CveMovimientoDetalle")), -1, ViewState("CveMovimientoDetalle").ToString.ToEntero) - End Get - Set(value As Integer) - ViewState("CveMovimientoDetalle") = value - End Set - End Property - Private ReadOnly Property CveDevolucion As Integer - Get - Return ViewState("CveDevolucion").ToString.ToEntero - End Get - End Property - - Private Property CveVentaRelacion As Integer - Get - Return If(IsNothing(ViewState("CveVentaRelacion")), -1, ViewState("CveVentaRelacion").ToString.ToEntero) - End Get - Set(value As Integer) - ViewState("CveVentaRelacion") = value - End Set - End Property - - Private Property ImporteRelacion As Double - Get - Return If(IsNothing(ViewState("ImporteRelacion")), 0, ViewState("ImporteRelacion").ToString.ToDouble) - End Get - Set(value As Double) - ViewState("ImporteRelacion") = value - End Set - End Property - - Private Property IsTotalxConcepto As Boolean - Get - Return If(IsNothing(ViewState("IsTotalxConcepto")), False, CBool(ViewState("IsTotalxConcepto").ToString)) - End Get - Set(value As Boolean) - ViewState("IsTotalxConcepto") = value - End Set - End Property - Private ReadOnly Property CveAlmacenTransitorio As Integer - Get - Return ViewState("CveAlmacenTransitorio").ToString.ToEntero - End Get - End Property - Private ReadOnly Property NuevaFactura As Integer - Get - Return ViewState("NuevaFactura").ToString.ToEntero - End Get - End Property - Private ReadOnly Property VentaFolio As String - Get - Return ViewState("VentaFolio").ToString - End Get - End Property - Private ReadOnly Property SelloCancelacion As String - Get - Return ViewState("SelloCancelacion").ToString - End Get - End Property - Private ReadOnly Property FechaCancelacion As DateTime - Get - Return ViewState("FechaCancelacion").ToString.ToDateTime - End Get - End Property - Private ReadOnly Property EstablecioFolio As Boolean - Get - Return CBool(ViewState("EstablecioFolio")) - End Get - End Property - Private ReadOnly Property FolioFiscal As String - Get - Return ViewState("FolioFiscal").ToString - End Get - End Property - Private ReadOnly Property Ruta As String - Get - Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\" & UsuarioActual.CveEmpresa & "\" - End Get - End Property - Private ReadOnly Property RutaPruebas As String - Get - Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\1\" - End Get - End Property - Private ReadOnly Property TipoCambio As Decimal - Get - Return ViewState("TipoCambio").ToString.ToDecimal - End Get - End Property - Private ReadOnly Property ProcesoCorrecto As Boolean - Get - Return CBool(ViewState("ProcesoCorrecto")) - End Get - End Property - - 'FUENTES RECAUDACIÓN - Private Property DTPresupuestoIngresos As DataTable - Get - Return CType(ViewState("DTPresupuestoIngresos"), DataTable) - End Get - Set(value As DataTable) - ViewState("DTPresupuestoIngresos") = value - End Set - End Property - 'Folios - Private ReadOnly Property CveFolio As Integer - Get - Return ViewState("CveFolio").ToString.ToEntero - End Get - End Property - Private ReadOnly Property NumAprobacion As Long - Get - Return CLng(ViewState("NumAprobacion").ToString) - End Get - End Property - Private ReadOnly Property FechaAprobacion As Date - Get - Return ViewState("FechaAprobacion").ToString.ToDate - End Get - End Property - Private ReadOnly Property FolioActual As String - Get - Return ViewState("FolioActual").ToString - End Get - End Property - 'Sucursal - Private ReadOnly Property Serie As String - Get - Return ViewState("Serie").ToString - End Get - End Property - Private ReadOnly Property Folio As Integer - Get - Return ViewState("Folio").ToString.ToEntero - End Get - End Property - Private ReadOnly Property FormatoFactura As String - Get - Return ViewState("FormatoFactura").ToString - End Get - End Property - Private ReadOnly Property TipoFormato As String - Get - Return ViewState("TipoFormato").ToString - End Get - End Property - Private ReadOnly Property IVA As Decimal - Get - Return ViewState("IVA").ToString.ToDecimal - End Get - End Property - 'Private ReadOnly Property SubProyectoPorcentajeIVA As Decimal - ' Get - ' Return ViewState("SubProyectoPorcentajeIVA").ToString.ToDecimal - ' End Get - 'End Property - Private ReadOnly Property ClienteRetIVA As Decimal - Get - Return ViewState("ClienteRetIVA").ToString.ToDecimal - End Get - End Property - Private ReadOnly Property ClienteRetISR As Decimal - Get - Return ViewState("ClienteRetISR").ToString.ToDecimal - End Get - End Property - - Private ReadOnly Property ClienteDesglosaIEPS As Boolean - Get - Return CType(ViewState("ClienteDesglosaIEPS").ToString, Boolean) - End Get - End Property - - 'Cliente - Private ReadOnly Property NombreCliente As String - Get - Return ViewState("NombreCliente").ToString - End Get - End Property - Private ReadOnly Property Vendedor As String - Get - Return ViewState("Vendedor").ToString - End Get - End Property - Private ReadOnly Property CtaContable As String - Get - Return ViewState("CtaContable").ToString - End Get - End Property - Private ReadOnly Property IdCtaContClientes As Integer - Get - Return ViewState("IdCtaContClientes").ToString.ToEntero - End Get - End Property - Private ReadOnly Property CveCuentaClientes As Integer - Get - Return ViewState("CveCuentaClientes").ToString.ToEntero - End Get - End Property - Private ReadOnly Property IdCtaContMonedaExtranjera As Integer - Get - Return ViewState("IdCtaContMonedaExtranjera").ToString.ToEntero - End Get - End Property - Private ReadOnly Property IdCtaContComplementaria As Integer - Get - Return ViewState("IdCtaContComplementaria").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 CveCuentaAnticipos As Integer - Get - Return ViewState("CveCuentaAnticipos").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 CveCuentaRetIVA As Integer - Get - Return ViewState("CveCuentaRetIVA").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 CveCuentaRetISR As Integer - Get - Return ViewState("CveCuentaRetISR").ToString.ToEntero - End Get - End Property - - Private ReadOnly Property CodCliente As String - Get - Return ViewState("CodCliente").ToString - End Get - End Property - Private ReadOnly Property CliNoExt As String - Get - Return ViewState("CliNoExt").ToString - End Get - End Property - Private ReadOnly Property CliNoInt As String - Get - Return ViewState("CliNoInt").ToString - End Get - End Property - Private ReadOnly Property CliLocalidad As String - Get - Return ViewState("CliLocalidad").ToString - End Get - End Property - Private ReadOnly Property CliPais As String - Get - Return ViewState("CliPais").ToString - End Get - End Property - Private ReadOnly Property SucCalle As String - Get - Return ViewState("SucCalle").ToString - End Get - End Property - Private ReadOnly Property CliCorreoCot As String - Get - If ViewState("CliCorreoCot") Is Nothing Then - Return "" - Else - Return ViewState("CliCorreoCot").ToString - End If - End Get - End Property - Private ReadOnly Property SucNoExt As String - Get - Return ViewState("SucNoExt").ToString - End Get - End Property - Private ReadOnly Property SucNoInt As String - Get - Return ViewState("SucNoInt").ToString - End Get - End Property - Private ReadOnly Property SucColonia As String - Get - Return ViewState("SucColonia").ToString - End Get - End Property - Private ReadOnly Property SucLocalidad As String - Get - Return ViewState("SucLocalidad").ToString - End Get - End Property - Private ReadOnly Property SucMunicipio As String - Get - Return ViewState("SucMunicipio").ToString - End Get - End Property - Private ReadOnly Property SucEstado As String - Get - Return ViewState("SucEstado").ToString - End Get - End Property - Private ReadOnly Property SucPais As String - Get - Return ViewState("SucPais").ToString - End Get - End Property - Private ReadOnly Property SucCP As String - Get - Return ViewState("SucCP").ToString - End Get - End Property - Private ReadOnly Property MatCalle As String - Get - Return ViewState("MatCalle").ToString - End Get - End Property - Private ReadOnly Property MatNoExt As String - Get - Return ViewState("MatNoExt").ToString - End Get - End Property - Private ReadOnly Property MatNoInt As String - Get - Return ViewState("MatNoInt").ToString - End Get - End Property - Private ReadOnly Property MatColonia As String - Get - Return ViewState("MatColonia").ToString - End Get - End Property - Private ReadOnly Property MatLocalidad As String - Get - Return ViewState("MatLocalidad").ToString - End Get - End Property - Private ReadOnly Property MatMunicipio As String - Get - Return ViewState("MatMunicipio").ToString - End Get - End Property - Private ReadOnly Property MatEstado As String - Get - Return ViewState("MatEstado").ToString - End Get - End Property - Private ReadOnly Property MatPais As String - Get - Return ViewState("MatPais").ToString - End Get - End Property - Private ReadOnly Property MatCP As String - Get - Return ViewState("MatCP").ToString - End Get - End Property - Private Property ImprimeNombreSucursal As Boolean - Get - Return CBool(ViewState("ImprimeNombreSucursal")) - End Get - Set(value As Boolean) - ViewState("ImprimeNombreSucursal") = value - End Set - End Property - Private ReadOnly Property AplicaFEMSA As Boolean - Get - Return CBool(ViewState("AplicaFEMSA")) - End Get - End Property - Private ReadOnly Property AplicaComercioExterior As Boolean - Get - Return CBool(ViewState("AplicaComercioExterior")) - End Get - End Property - Private ReadOnly Property CveTipoOperacion As Integer - Get - Return CInt(ViewState("CveTipoOperacion")) - End Get - End Property - Private ReadOnly Property CvePedimento As Integer - Get - Return CInt(ViewState("CvePedimento")) - End Get - End Property - Private ReadOnly Property CveIncoterm As Integer - Get - Return CInt(ViewState("CveIncoterm")) - End Get - End Property - Private ReadOnly Property AplicaDetallista As Boolean - Get - Return CBool(ViewState("AplicaDetallista")) - End Get - End Property - Private ReadOnly Property AplicaFord As Boolean - Get - Return CBool(ViewState("AplicaFord")) - End Get - End Property - Private ReadOnly Property CveOS As Integer - Get - Return ViewState("CveOS").ToString.ToEntero - End Get - End Property - Private ReadOnly Property SaldoVenta As Decimal - Get - Return If(IsNothing(ViewState("SaldoVenta")), 0, ViewState("SaldoVenta").ToString.ToDecimal) - End Get - End Property - Private Property CvePSAmortizacion As Integer - Get - Return ViewState("CvePSAmortizacion").ToString.ToEntero - End Get - - Set(value As Integer) - ViewState("CvePSAmortizacion") = 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 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 SeGuardoPrePoliza As Boolean - Get - Return CBool(ViewState("SeGuardoPrePoliza")) - End Get - End Property - Private Property CveVentaFacturada As Integer - Get - Return ViewState("CveVentaFacturada").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveVentaFacturada") = value - End Set - End Property - Private ReadOnly Property AplicarVentaFacturada As Boolean - Get - Return CBool(ViewState("AplicarVentaFacturada")) - End Get - End Property - 'Estimaciones - Private Property CveContrato As Integer - Get - Return ViewState("CveContrato").ToString.ToEntero - End Get - - Set(value As Integer) - ViewState("CveContrato") = value - End Set - End Property - Private Property CvePedido As Integer - Get - Return ViewState("CvePedido").ToString.ToEntero - End Get - - Set(value As Integer) - ViewState("CvePedido") = value - End Set - End Property - Private Property CvePedido2 As Integer - Get - Return ViewState("CvePedido2").ToString.ToEntero - End Get - - Set(value As Integer) - ViewState("CvePedido2") = value - End Set - End Property - Private Property TipoContrato As Integer - Get - Return ViewState("TipoContrato").ToString.ToEntero - End Get - - Set(value As Integer) - ViewState("TipoContrato") = value - End Set - End Property - Private Property Opcion As String - Get - Return ViewState("Opcion").ToString - End Get - - Set(value As String) - ViewState("Opcion") = value - End Set - End Property - Private Property CorreoNotificacionPedDev As String - Get - Return If(IsNothing(ViewState("CorreoNotificacionDevPed")), "", ViewState("CorreoNotificacionDevPed").ToString()) - End Get - - Set(value As String) - ViewState("CorreoNotificacionDevPed") = value - End Set - End Property - - 'Presupuesto - Private Property CvePresupuesto As Integer - Get - Return ViewState("CvePresupuesto").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CvePresupuesto") = value - End Set - End Property - Private Property TotalOtrosConceptos As Decimal - Get - Return ViewState("TotalOtrosConceptos").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("TotalOtrosConceptos") = value - End Set - End Property - Private Property TipoCambioFactura As Decimal - Get - Return ViewState("TipoCambioFactura").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("TipoCambioFactura") = value - End Set - End Property - - Private Property DtPagos As DataTable - Get - Return CType(ViewState("DtPagos"), DataTable) - End Get - Set(value As DataTable) - ViewState("DtPagos") = value - End Set - End Property - Private Property DevolucionAlmacen As Integer - Get - Return ViewState("DevolucionAlmacen").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("DevolucionAlmacen") = value - End Set - End Property - Private ReadOnly Property TipoDoctoDevolucion As String - Get - Return ViewState("TipoDoctoDevolucion").ToString - End Get - End Property - Private Property PlazoCobranza As Integer - Get - Return ViewState("PlazoCobranza").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("PlazoCobranza") = value - End Set - End Property - Private Property PlazoCobranzaRemision As Integer - Get - Return ViewState("PlazoCobranzaRemision").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("PlazoCobranzaRemision") = value - End Set - End Property - - 'CvePAC - Private Property CvePAC As Integer - Get - Return ViewState("CvePAC").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CvePAC") = value - End Set - End Property - - Private Property AplicaDevolucion As Boolean - Get - Return If(IsNothing(ViewState("AplicaDevolucion")), False, CType(ViewState("AplicaDevolucion"), Boolean)) - End Get - Set(value As Boolean) - ViewState("AplicaDevolucion") = value - End Set - End Property - - Private Property CveVentaDevolucion As Integer - Get - Return If(IsNothing(ViewState("CveVentaDevolucion")), 0, CType(ViewState("CveVentaDevolucion"), Integer)) - End Get - Set(value As Integer) - ViewState("CveVentaDevolucion") = value - End Set - End Property - Private Property SaldoVentaDevolucion As Decimal - Get - Return ViewState("SaldoVentaDevolucion").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("SaldoVentaDevolucion") = value - End Set - End Property - Private Property ContratoOC As Boolean - Get - Return If(IsNothing(ViewState("ContratoOC")), False, CType(ViewState("ContratoOC"), Boolean)) - End Get - Set(value As Boolean) - ViewState("ContratoOC") = value - End Set - End Property - - Private Property TieneAlmacen As Boolean - Get - Return If(IsNothing(ViewState("TieneAlmacen")), False, CType(ViewState("TieneAlmacen"), Boolean)) - End Get - Set(value As Boolean) - ViewState("TieneAlmacen") = value - End Set - End Property - Private Property PorcentajeIVA As Decimal - Get - Return ViewState("PorcentajeIVA").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("PorcentajeIVA") = value - End Set - End Property - Private Property CveEstatusRefacturacion As Integer - Get - Return If(IsNothing(ViewState("CveEstatusRefacturacion")), 0, CType(ViewState("CveEstatusRefacturacion"), Integer)) - End Get - Set(value As Integer) - ViewState("CveEstatusRefacturacion") = value - End Set +#Region "Propiedades" + Private Const NumeroDecimales As Integer = 2 + + Dim ColumnaDescuento As Integer = 10 + Dim ColumnaPredial As Integer = 11 + Dim ColumnaIVA As Integer = 12 + Dim ColumnaIEPS As Integer = 13 + Dim ColumnaRetIVA As Integer = 14 + Dim ColumnaRetISR As Integer = 15 + Dim ColumnaEditar As Integer = 17 + Dim ColumnaEliminar As Integer = 18 + + 'Factura de ventas + Dim DTConceptos As DataTable + Private Property Version As String + Private Property Fecha As String + Private Property SerieXML As String + Private Property FolioXML As String + Private Property SubTotal As Decimal + Private Property Total As Decimal = 0 + Private Property Descuentos 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 OtrosImpuestos 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 NumRow As Integer + Private Property EsSupervisor As Boolean = False + Private Property MandarCorreoSupervisor As Boolean = False + Private ReadOnly Property ExFolioFactura As Boolean + Get + Return CBool(ViewState("ExFolioFactura")) + End Get + End Property + Private Property CveFactura As Integer + Get + Return ViewState("CveFactura").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveFactura") = value + End Set End Property -#End Region - -#Region "Propiedades PuntoVenta" - - Private Property CveCorte As Integer - Get - Return ViewState("CveCorte").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveCorte") = value - End Set - End Property - - Private Property Entrega As String - Get - Return ViewState("Entrega").ToString - End Get - Set(value As String) - ViewState("Entrega") = value - End Set - End Property - - Private Property Vigencia As String - Get - Return ViewState("Vigencia").ToString - End Get - Set(value As String) - ViewState("Vigencia") = value - End Set - End Property - - Private Property DineroCaja As Double - Get - Return ViewState("DineroCaja").ToString.ToDouble - End Get - Set(value As Double) - ViewState("DineroCaja") = value - End Set - End Property - - Private ReadOnly Property CveCicloComercial As Integer - Get - Return ViewState("CveCicloComercial").ToString.ToEntero - End Get + Private Property idCuentaContabilizacion As Integer + Get + Return ViewState("idCuentaContabilizacion").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("idCuentaContabilizacion") = value + End Set End Property -#End Region - -#Region "Propiedades Contratos" - Private Property DtContratos As DataTable - Get - Return If(IsNothing(ViewState("DtContratos")), Nothing, CType(ViewState("DtContratos"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtContratos") = value - End Set - End Property - Private Property NumeroContrato As String - Get - Return ViewState("NumeroContrato").ToString - End Get - Set(value As String) - ViewState("NumeroContrato") = value - End Set - End Property - Private Property DescripcionContrato As String - Get - Return ViewState("DescripcionContrato").ToString - End Get - Set(value As String) - ViewState("DescripcionContrato") = value - End Set - End Property - Private Property NumeroLicitacion As String - Get - Return ViewState("NumeroLicitacion").ToString - End Get - Set(value As String) - ViewState("NumeroLicitacion") = value - End Set - End Property - Private Property CveAlmacenExistenciasContrato As Integer - Get - Return ViewState("CveAlmacenExistenciasContrato").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveAlmacenExistenciasContrato") = value - End Set - End Property - Private Property CveAlmacenOrigenContrato As Integer - Get - Return ViewState("CveAlmacenOrigenContrato").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveAlmacenOrigenContrato") = value - End Set - End Property - Private Property DtContratosSerieDetalle As DataTable - Get - Return If(IsNothing(ViewState("DtContratosSerieDetalle")), Nothing, CType(ViewState("DtContratosSerieDetalle"), DataTable)) - End Get - Set(value As DataTable) - ViewState("DtContratosSerieDetalle") = 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 CveConsecSerieLote As Integer - Get - Return CType(ViewState("CveConsecSerieLote"), Integer) - End Get - Set(value As Integer) - ViewState("CveConsecSerieLote") = value - End Set - End Property - Private Property LimitaCantidadSerieLote As Integer - Get - Return CType(ViewState("LimitaCantidadSerieLote"), Integer) - End Get - Set(value As Integer) - ViewState("LimitaCantidadSerieLote") = value - End Set + Private Property CuentasContablesInvalidas As StringBuilder + Get + Return CType(ViewState("CuentasContablesInvalidas"), StringBuilder) + End Get + Set(value As StringBuilder) + ViewState("CuentasContablesInvalidas") = value + End Set End Property -#End Region - -#Region " PROPIEDADES NUEVAS | GUARDAR - IMPRESION " - Private Property ErrorList As List(Of String) - Get - Return CType(ViewState("ErrorList"), List(Of String)) - End Get - Set(value As List(Of String)) - ViewState("ErrorList") = value - End Set - End Property - Private Property MensajeAlert As StringBuilder - Get - Return CType(ViewState("MensajeAlert"), StringBuilder) - End Get - Set(value As StringBuilder) - ViewState("MensajeAlert") = value - End Set - End Property - Private Property ObjFactura As Modelos.Factura - Get - Return CType(ViewState("ObjFactura"), Modelos.Factura) - End Get - Set(value As Modelos.Factura) - ViewState("ObjFactura") = value - End Set - End Property - Private Property ObjFacturaDevolucion As Modelos.Factura - Get - Return CType(ViewState("ObjFacturaDevolucion"), Modelos.Factura) - End Get - Set(value As Modelos.Factura) - ViewState("ObjFacturaDevolucion") = value - End Set + 'Local + Private Property TmpDT As DataTable + Get + Return If(IsNothing(ViewState("TmpDT")), Nothing, CType(ViewState("TmpDT"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDT") = value + End Set + End Property + Private Property TmpDTError As DataTable + Get + Return If(IsNothing(ViewState("TmpDTError")), Nothing, CType(ViewState("TmpDTError"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTError") = value + End Set End Property -#End Region -#Region " PROPIEDADES NUEVAS " - Private Property CveOC As Integer - Get - Return ViewState("CveOC").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveOC") = value - End Set - End Property - Private Property EnviarCorreoCliente As Boolean - Get - Return CBool(ViewState("EnviarCorreoCliente").ToString) - End Get - Set(value As Boolean) - ViewState("EnviarCorreoCliente") = value - End Set - End Property - Private Property EstatusCliente As Boolean - Get - Return CBool(ViewState("EstatusCliente").ToString) - End Get - Set(value As Boolean) - ViewState("EstatusCliente") = value - End Set - End Property - Private Property CveMetodoPagoCliente As Integer - Get - Return ViewState("CveMetodoPagoCliente").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveMetodoPagoCliente") = 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 - 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 TotAnt As Decimal - Get - Return ViewState("TotAnt").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("TotAnt") = value - End Set - End Property - Private Property TotalOriginal As Double - Get - Return ViewState("TotalOriginal").ToString.ToDouble - End Get - Set(value As Double) - ViewState("TotalOriginal") = value - End Set - End Property - - Private Property AplicaCancelarRemision As Boolean - Get - Return CBool(ViewState("AplicaCancelarRemision").ToString) - End Get - Set(value As Boolean) - ViewState("AplicaCancelarRemision") = value - End Set - End Property - Private Property TipoVentaSucursal As Integer - Get - Return ViewState("TipoVentaSucursal").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("TipoVentaSucursal") = value - End Set - End Property - Private Property MensajeCveSAT As StringBuilder - Get - If ViewState("MensajeCveSAT") Is Nothing Then ViewState("MensajeCveSAT") = New StringBuilder - Return CType(ViewState("MensajeCveSAT"), StringBuilder) - End Get - Set(value As StringBuilder) - ViewState("TipoVentaSucursal") = value - End Set - End Property - Private Property EditoRemision As Boolean - Get - Return CBool(ViewState("EditoRemision").ToString) - End Get - Set(value As Boolean) - ViewState("EditoRemision") = value - End Set - End Property - Private Property AplicaNC As Boolean - Get - Return CBool(ViewState("AplicaNC").ToString) - End Get - Set(value As Boolean) - ViewState("AplicaNC") = value - End Set - End Property - Private Property DtVentasNC As DataTable - Get - Return CType(ViewState("DtVentasNC"), DataTable) - End Get - Set(value As DataTable) - ViewState("DtVentasNC") = value - End Set - End Property - Private Property AplicaNCMasiva As Boolean - Get - Return CBool(ViewState("AplicaNCMasiva").ToString) - End Get - Set(value As Boolean) - ViewState("AplicaNCMasiva") = value - End Set - End Property - Private Property RefacturacionGeneroNC As Boolean - Get - Return CBool(ViewState("RefacturacionGeneroNC").ToString) - End Get - Set(value As Boolean) - ViewState("RefacturacionGeneroNC") = value - End Set - End Property - Private Property ModalidadEdicion As Boolean - Get - Return CBool(ViewState("ModalidadEdicion").ToString) - End Get - Set(value As Boolean) - ViewState("ModalidadEdicion") = value - End Set - End Property - Private Property ConversionRemision As String - Get - Return ViewState("ConversionRemision").ToString - End Get - Set(value As String) - ViewState("ConversionRemision") = value - End Set - End Property - Private Property TipoCambioRemision As Decimal - Get - Return ViewState("TipoCambioRemision").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("TipoCambioRemision") = value - End Set - End Property - Private Property TieneContrato As Boolean - Get - Return CBool(ViewState("TieneContrato").ToString) - End Get - Set(value As Boolean) - ViewState("TieneContrato") = value - End Set - End Property - Private Property CveOrdenCompraContrato As Integer - Get - Return ViewState("CveOrdenCompraContrato").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveOrdenCompraContrato") = value - End Set - End Property - Private Property ContratosConOC As StringBuilder - Get - If ViewState("ContratosConOC") Is Nothing Then ViewState("ContratosConOC") = New StringBuilder - Return CType(ViewState("ContratosConOC"), StringBuilder) - End Get - Set(value As StringBuilder) - ViewState("ContratosConOC") = value - End Set - End Property - Private Property RequiereOC As Boolean - Get - Return CBool(ViewState("RequiereOC").ToString) - End Get - Set(value As Boolean) - ViewState("RequiereOC") = value - End Set - End Property - Private Property PorcentajeCredito As Decimal - Get - Return ViewState("PorcentajeCredito").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("PorcentajeCredito") = value - End Set - End Property - Private Property CvePedidoA As Integer - Get - Return ViewState("CvePedidoA").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CvePedidoA") = value - End Set - End Property - - Private Property CveEmpresaCRM As Integer - Get - Return ViewState("CveEmpresaCRM").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveEmpresaCRM") = value - End Set - End Property - - Private Property CveAcercamientoCRM As Integer - Get - Return ViewState("CveAcercamientoCRM").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveAcercamientoCRM") = value - End Set - End Property - - Private Property DtPedidos2 As DataTable - Get - Return CType(ViewState("DtPedidos2"), DataTable) - End Get - Set(value As DataTable) - ViewState("DtPedidos2") = value - End Set - End Property - Private Property DtPedidos2PS As DataTable - Get - Return CType(ViewState("DtPedidos2PS"), DataTable) - End Get - Set(value As DataTable) - ViewState("DtPedidos2PS") = value - End Set - End Property - - Private Property CveEstatus As Integer - Get - Return ViewState("CveEstatus").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("CveEstatus") = value - End Set - End Property - Private Property DiasCredito As Integer - Get - Return ViewState("DiasCredito").ToString.ToEntero - End Get - Set(value As Integer) - ViewState("DiasCredito") = value - End Set - End Property - Private Property EsDiasCreditoFijo As Boolean - Get - Return CBool(ViewState("EsDiasCreditoFijo").ToString) - End Get - Set(value As Boolean) - ViewState("EsDiasCreditoFijo") = value - End Set - End Property - Private Property VentaSaldoAlmacen As Decimal - Get - Return ViewState("VentaSaldoAlmacen").ToString.ToDecimal - End Get - Set(value As Decimal) - ViewState("VentaSaldoAlmacen") = value - End Set - End Property - Private Property SeCancelaRemisionProceso As Boolean - Get - Return CBool(ViewState("SeCancelaRemisionProceso").ToString) - End Get - Set(value As Boolean) - ViewState("SeCancelaRemisionProceso") = value - End Set + Private Property TmpDTImpuestos As DataTable + Get + Return If(IsNothing(ViewState("TmpDTImpuestos")), Nothing, CType(ViewState("TmpDTImpuestos"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTImpuestos") = value + End Set + End Property + Private Property TmpDTImpuestosIVAIEPS As DataTable + Get + Return If(IsNothing(ViewState("TmpDTImpuestosIVAIEPS")), Nothing, CType(ViewState("TmpDTImpuestosIVAIEPS"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTImpuestosIVAIEPS") = value + End Set + End Property + Private Property TmpDTDocumentosRelacionados As DataTable + Get + Return If(IsNothing(ViewState("TmpDTDocumentosRelacionados")), Nothing, CType(ViewState("TmpDTDocumentosRelacionados"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTDocumentosRelacionados") = value + End Set + End Property + Private Property TmpDTNCVinculadas As DataTable + Get + Return If(IsNothing(ViewState("TmpDTNCVinculadas")), Nothing, CType(ViewState("TmpDTNCVinculadas"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTNCVinculadas") = value + End Set + End Property + Private Property TmpDTEnvioDireccion As DataTable + Get + Return If(IsNothing(ViewState("TmpDTEnvioDireccion")), Nothing, CType(ViewState("TmpDTEnvioDireccion"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTEnvioDireccion") = value + End Set + 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 CveAlmacenDevolucion As Integer + Get + Return ViewState("CveAlmacenDevolucion").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveAlmacenDevolucion") = value + End Set + End Property + + Private Property EraCotizacion As Integer + Get + Return ViewState("EraCotizacion").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("EraCotizacion") = value + End Set + End Property + Private Property FacturaMateriales As Integer + Get + Return ViewState("FacturaMateriales").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("FacturaMateriales") = value + End Set + End Property + Private Property TmpDTDeducciones As DataTable + Get + Return If(IsNothing(ViewState("TmpDTDeducciones")), Nothing, CType(ViewState("TmpDTDeducciones"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTDeducciones") = value + End Set + End Property + + Private Property TmpDTComplementos As DataTable + Get + Return If(IsNothing(ViewState("TmpDTComplementos")), Nothing, CType(ViewState("TmpDTComplementos"), DataTable)) + End Get + Set(value As DataTable) + ViewState("TmpDTComplementos") = value + End Set + End Property + Private Property DTmpC As DataTable + Get + Return If(IsNothing(ViewState("DTmpC")), Nothing, CType(ViewState("DTmpC"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DTmpC") = value + End Set + End Property + Private Property DTmpF As DataTable + Get + Return If(IsNothing(ViewState("DTmpF")), Nothing, CType(ViewState("DTmpF"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DTmpF") = value + End Set + End Property + Private Property DTSucursal As DataTable + Get + Return If(IsNothing(ViewState("DTSucursal")), Nothing, CType(ViewState("DTSucursal"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DTSucursal") = value + End Set + End Property + Private Property DTOrdenesCompra As DataTable + Get + Return If(IsNothing(ViewState("DTOrdenesCompra")), Nothing, CType(ViewState("DTOrdenesCompra"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DTOrdenesCompra") = value + End Set + End Property + Private Property DTOrdenesCompraPS As DataTable + Get + Return If(IsNothing(ViewState("DTOrdenesCompraPS")), Nothing, CType(ViewState("DTOrdenesCompraPS"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DTOrdenesCompraPS") = value + End Set + End Property + Private Property DtOCTmpDT As DataTable + Get + Return If(IsNothing(ViewState("DtOCTmpDT")), Nothing, CType(ViewState("DtOCTmpDT"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtOCTmpDT") = value + End Set + End Property + Private Property DTRemisiones As DataTable + Get + Return If(IsNothing(ViewState("DTRemisiones")), Nothing, CType(ViewState("DTRemisiones"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DTRemisiones") = value + End Set + End Property + Private Property RemisionesLista As List(Of Integer) + Get + Return If(IsNothing(ViewState("RemisionesLista")), Nothing, CType(ViewState("RemisionesLista"), List(Of Integer))) + End Get + Set(value As List(Of Integer)) + ViewState("RemisionesLista") = value + End Set + End Property + Private Property Pedidos2Lista As List(Of Integer) + Get + Return If(IsNothing(ViewState("Pedidos2Lista")), Nothing, CType(ViewState("Pedidos2Lista"), List(Of Integer))) + End Get + Set(value As List(Of Integer)) + ViewState("Pedidos2Lista") = value + End Set + End Property + Private Property DtRemisionesPS As DataTable + Get + Return If(IsNothing(ViewState("DtRemisionesPS")), Nothing, CType(ViewState("DtRemisionesPS"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtRemisionesPS") = value + End Set + End Property + Private Property DtCotizaciones As DataTable + Get + Return If(IsNothing(ViewState("DtCotizaciones")), Nothing, CType(ViewState("DtCotizaciones"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtCotizaciones") = value + End Set + End Property + Private Property CotizacionesLista As List(Of Integer) + Get + Return If(IsNothing(ViewState("CotizacionesLista")), Nothing, CType(ViewState("CotizacionesLista"), List(Of Integer))) + End Get + Set(value As List(Of Integer)) + ViewState("CotizacionesLista") = value + End Set + End Property + Private Property DtCotizacionesPS As DataTable + Get + Return If(IsNothing(ViewState("DtCotizacionesPS")), Nothing, CType(ViewState("DtCotizacionesPS"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtCotizacionesPS") = value + End Set + End Property + Private Property DtCotizacionTmpDT As DataTable + Get + Return If(IsNothing(ViewState("DtCotizacionTmpDT")), Nothing, CType(ViewState("DtCotizacionTmpDT"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtCotizacionTmpDT") = value + End Set + End Property + Private Property DtRemisionesTmpDT As DataTable + Get + Return If(IsNothing(ViewState("DtRemisionesTmpDT")), Nothing, CType(ViewState("DtRemisionesTmpDT"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtRemisionesTmpDT") = value + End Set + End Property + Private Property DtPedidos2TmpDT As DataTable + Get + Return If(IsNothing(ViewState("DtPedidos2TmpDT")), Nothing, CType(ViewState("DtPedidos2TmpDT"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtPedidos2TmpDT") = value + End Set + End Property + Private Property DtRemConceptosSurtidos As DataTable + Get + Return If(IsNothing(ViewState("DtRemConceptosSurtidos")), Nothing, CType(ViewState("DtRemConceptosSurtidos"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtRemConceptosSurtidos") = value + End Set + End Property + Private Property HuboCambioRemi As Boolean + Get + Return If(IsNothing(ViewState("HuboCambioRemi")), False, CType(ViewState("HuboCambioRemi"), Boolean)) + End Get + Set(value As Boolean) + ViewState("HuboCambioRemi") = value + End Set + End Property + Private Property AplicaGastoContrato As Boolean + Get + Return If(IsNothing(ViewState("AplicaGastoContrato")), False, CType(ViewState("AplicaGastoContrato"), Boolean)) + End Get + Set(value As Boolean) + ViewState("AplicaGastoContrato") = value + End Set + End Property + Private Property EsCreaApartirDe As Boolean + Get + Return If(IsNothing(ViewState("EsCreaApartirDe")), False, CType(ViewState("EsCreaApartirDe"), Boolean)) + End Get + Set(value As Boolean) + ViewState("EsCreaApartirDe") = value + End Set + End Property + Private Property RequiereAlmacenDestino As Boolean + Get + Return If(IsNothing(ViewState("RequiereAlmacenDestino")), False, CType(ViewState("RequiereAlmacenDestino"), Boolean)) + End Get + Set(value As Boolean) + ViewState("RequiereAlmacenDestino") = value + End Set + End Property + Private Property RequiereAlmacenOrigen As Boolean + Get + Return If(IsNothing(ViewState("RequiereAlmacenOrigen")), False, CType(ViewState("RequiereAlmacenOrigen"), Boolean)) + End Get + Set(value As Boolean) + ViewState("RequiereAlmacenOrigen") = value + End Set + End Property + Private Property EmpresaActual As Empresa + Get + Return CType(ViewState("EmpresaActual"), Empresa) + End Get + Set(value As Empresa) + ViewState("EmpresaActual") = value + End Set + End Property + + Property CargaDocumentoOC As Boolean + Get + If ViewState("CargaDocumentoOC") Is Nothing Then + Return False + Else + Return DirectCast(ViewState("CargaDocumentoOC"), Boolean) + End If + End Get + Set(value As Boolean) + ViewState("CargaDocumentoOC") = value + End Set + End Property + Private Property DTFacNC As DataTable + Get + Return If(IsNothing(ViewState("DTFacNC")), Nothing, CType(ViewState("DTFacNC"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DTFacNC") = value + End Set + End Property + Private Property DtPromociones As DataTable + Get + Return If(IsNothing(ViewState("DtPromociones")), Nothing, CType(ViewState("DtPromociones"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtPromociones") = value + End Set + End Property + Private ReadOnly Property CveCliente As Integer + Get + Return ViewState("CveCliente").ToString.ToEntero + End Get + End Property + Private ReadOnly Property CveClienteAnterior As Integer + Get + Return ViewState("CveClienteAnterior").ToString.ToEntero + End Get + End Property + + Private Property CveClienteSucursal As Integer + Get + If ViewState("CveClienteSucursal") Is Nothing Then + Return -1 + Else + Return ViewState("CveClienteSucursal").ToString.ToEntero + End If + End Get + Set(value As Integer) + ViewState("CveClienteSucursal") = value + End Set + End Property + Private Property CveAnticipo As Integer + Get + If ViewState("CveAnticipo") Is Nothing Then + Return -1 + Else + Return ViewState("CveAnticipo").ToString.ToEntero + End If + End Get + Set(value As Integer) + ViewState("CveAnticipo") = value + End Set + End Property + + Private Property CveUsuarioActual As Integer + Get + Return ViewState("CveUsuarioActual").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveUsuarioActual") = value + End Set + End Property + Private ReadOnly Property Mail As String + Get + Return ViewState("Mail").ToString + End Get + End Property + Private ReadOnly Property MailCC As String + Get + Return ViewState("MailCC").ToString + End Get + End Property + Private ReadOnly Property CveVenta As Integer + Get + Return ViewState("CveVenta").ToString.ToEntero + End Get + End Property + Private Property CveVentaPadre As Integer + Get + Return If(IsNothing(ViewState("CveVentaPadre")), -1, ViewState("CveVentaPadre").ToString.ToEntero) + End Get + Set(value As Integer) + ViewState("CveVentaPadre") = value + End Set + End Property + Private Property CveEstatusFacturaPadre As Integer + Get + Return If(IsNothing(ViewState("CveEstatusFacturaPadre")), -1, ViewState("CveEstatusFacturaPadre").ToString.ToEntero) + End Get + Set(value As Integer) + ViewState("CveEstatusFacturaPadre") = value + End Set + End Property + Private Property CveMovimientoDetalle As Integer + Get + Return If(IsNothing(ViewState("CveMovimientoDetalle")), -1, ViewState("CveMovimientoDetalle").ToString.ToEntero) + End Get + Set(value As Integer) + ViewState("CveMovimientoDetalle") = value + End Set + End Property + Private ReadOnly Property CveDevolucion As Integer + Get + Return ViewState("CveDevolucion").ToString.ToEntero + End Get + End Property + + Private Property CveVentaRelacion As Integer + Get + Return If(IsNothing(ViewState("CveVentaRelacion")), -1, ViewState("CveVentaRelacion").ToString.ToEntero) + End Get + Set(value As Integer) + ViewState("CveVentaRelacion") = value + End Set + End Property + + Private Property ImporteRelacion As Double + Get + Return If(IsNothing(ViewState("ImporteRelacion")), 0, ViewState("ImporteRelacion").ToString.ToDouble) + End Get + Set(value As Double) + ViewState("ImporteRelacion") = value + End Set + End Property + + Private Property IsTotalxConcepto As Boolean + Get + Return If(IsNothing(ViewState("IsTotalxConcepto")), False, CBool(ViewState("IsTotalxConcepto").ToString)) + End Get + Set(value As Boolean) + ViewState("IsTotalxConcepto") = value + End Set + End Property + Private ReadOnly Property CveAlmacenTransitorio As Integer + Get + Return ViewState("CveAlmacenTransitorio").ToString.ToEntero + End Get + End Property + Private ReadOnly Property NuevaFactura As Integer + Get + Return ViewState("NuevaFactura").ToString.ToEntero + End Get + End Property + Private ReadOnly Property VentaFolio As String + Get + Return ViewState("VentaFolio").ToString + End Get + End Property + Private ReadOnly Property SelloCancelacion As String + Get + Return ViewState("SelloCancelacion").ToString + End Get + End Property + Private ReadOnly Property FechaCancelacion As DateTime + Get + Return ViewState("FechaCancelacion").ToString.ToDateTime + End Get + End Property + Private ReadOnly Property EstablecioFolio As Boolean + Get + Return CBool(ViewState("EstablecioFolio")) + End Get + End Property + Private ReadOnly Property FolioFiscal As String + Get + Return ViewState("FolioFiscal").ToString + End Get + End Property + Private ReadOnly Property Ruta As String + Get + Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\" & UsuarioActual.CveEmpresa & "\" + End Get + End Property + Private ReadOnly Property RutaPruebas As String + Get + Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\1\" + End Get + End Property + Private ReadOnly Property TipoCambio As Decimal + Get + Return ViewState("TipoCambio").ToString.ToDecimal + End Get + End Property + Private ReadOnly Property ProcesoCorrecto As Boolean + Get + Return CBool(ViewState("ProcesoCorrecto")) + End Get + End Property + + 'FUENTES RECAUDACIÓN + Private Property DTPresupuestoIngresos As DataTable + Get + Return CType(ViewState("DTPresupuestoIngresos"), DataTable) + End Get + Set(value As DataTable) + ViewState("DTPresupuestoIngresos") = value + End Set + End Property + 'Folios + Private ReadOnly Property CveFolio As Integer + Get + Return ViewState("CveFolio").ToString.ToEntero + End Get + End Property + Private ReadOnly Property NumAprobacion As Long + Get + Return CLng(ViewState("NumAprobacion").ToString) + End Get + End Property + Private ReadOnly Property FechaAprobacion As Date + Get + Return ViewState("FechaAprobacion").ToString.ToDate + End Get + End Property + Private ReadOnly Property FolioActual As String + Get + Return ViewState("FolioActual").ToString + End Get + End Property + 'Sucursal + Private ReadOnly Property Serie As String + Get + Return ViewState("Serie").ToString + End Get + End Property + Private ReadOnly Property Folio As Integer + Get + Return ViewState("Folio").ToString.ToEntero + End Get + End Property + Private ReadOnly Property FormatoFactura As String + Get + Return ViewState("FormatoFactura").ToString + End Get + End Property + Private ReadOnly Property TipoFormato As String + Get + Return ViewState("TipoFormato").ToString + End Get + End Property + Private ReadOnly Property IVA As Decimal + Get + Return ViewState("IVA").ToString.ToDecimal + End Get + End Property + 'Private ReadOnly Property SubProyectoPorcentajeIVA As Decimal + ' Get + ' Return ViewState("SubProyectoPorcentajeIVA").ToString.ToDecimal + ' End Get + 'End Property + Private ReadOnly Property ClienteRetIVA As Decimal + Get + Return ViewState("ClienteRetIVA").ToString.ToDecimal + End Get + End Property + Private ReadOnly Property ClienteRetISR As Decimal + Get + Return ViewState("ClienteRetISR").ToString.ToDecimal + End Get + End Property + + Private ReadOnly Property ClienteDesglosaIEPS As Boolean + Get + Return CType(ViewState("ClienteDesglosaIEPS").ToString, Boolean) + End Get + End Property + + 'Cliente + Private ReadOnly Property NombreCliente As String + Get + Return ViewState("NombreCliente").ToString + End Get + End Property + Private ReadOnly Property Vendedor As String + Get + Return ViewState("Vendedor").ToString + End Get + End Property + Private ReadOnly Property CtaContable As String + Get + Return ViewState("CtaContable").ToString + End Get + End Property + Private ReadOnly Property IdCtaContClientes As Integer + Get + Return ViewState("IdCtaContClientes").ToString.ToEntero + End Get + End Property + Private ReadOnly Property CveCuentaClientes As Integer + Get + Return ViewState("CveCuentaClientes").ToString.ToEntero + End Get + End Property + Private ReadOnly Property IdCtaContMonedaExtranjera As Integer + Get + Return ViewState("IdCtaContMonedaExtranjera").ToString.ToEntero + End Get + End Property + Private ReadOnly Property IdCtaContComplementaria As Integer + Get + Return ViewState("IdCtaContComplementaria").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 CveCuentaAnticipos As Integer + Get + Return ViewState("CveCuentaAnticipos").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 CveCuentaRetIVA As Integer + Get + Return ViewState("CveCuentaRetIVA").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 CveCuentaRetISR As Integer + Get + Return ViewState("CveCuentaRetISR").ToString.ToEntero + End Get + End Property + + Private ReadOnly Property CodCliente As String + Get + Return ViewState("CodCliente").ToString + End Get + End Property + Private ReadOnly Property CliNoExt As String + Get + Return ViewState("CliNoExt").ToString + End Get + End Property + Private ReadOnly Property CliNoInt As String + Get + Return ViewState("CliNoInt").ToString + End Get + End Property + Private ReadOnly Property CliLocalidad As String + Get + Return ViewState("CliLocalidad").ToString + End Get + End Property + Private ReadOnly Property CliPais As String + Get + Return ViewState("CliPais").ToString + End Get + End Property + Private ReadOnly Property SucCalle As String + Get + Return ViewState("SucCalle").ToString + End Get + End Property + Private ReadOnly Property CliCorreoCot As String + Get + If ViewState("CliCorreoCot") Is Nothing Then + Return "" + Else + Return ViewState("CliCorreoCot").ToString + End If + End Get + End Property + Private ReadOnly Property SucNoExt As String + Get + Return ViewState("SucNoExt").ToString + End Get + End Property + Private ReadOnly Property SucNoInt As String + Get + Return ViewState("SucNoInt").ToString + End Get + End Property + Private ReadOnly Property SucColonia As String + Get + Return ViewState("SucColonia").ToString + End Get + End Property + Private ReadOnly Property SucLocalidad As String + Get + Return ViewState("SucLocalidad").ToString + End Get + End Property + Private ReadOnly Property SucMunicipio As String + Get + Return ViewState("SucMunicipio").ToString + End Get + End Property + Private ReadOnly Property SucEstado As String + Get + Return ViewState("SucEstado").ToString + End Get + End Property + Private ReadOnly Property SucPais As String + Get + Return ViewState("SucPais").ToString + End Get + End Property + Private ReadOnly Property SucCP As String + Get + Return ViewState("SucCP").ToString + End Get + End Property + Private ReadOnly Property MatCalle As String + Get + Return ViewState("MatCalle").ToString + End Get + End Property + Private ReadOnly Property MatNoExt As String + Get + Return ViewState("MatNoExt").ToString + End Get + End Property + Private ReadOnly Property MatNoInt As String + Get + Return ViewState("MatNoInt").ToString + End Get + End Property + Private ReadOnly Property MatColonia As String + Get + Return ViewState("MatColonia").ToString + End Get + End Property + Private ReadOnly Property MatLocalidad As String + Get + Return ViewState("MatLocalidad").ToString + End Get + End Property + Private ReadOnly Property MatMunicipio As String + Get + Return ViewState("MatMunicipio").ToString + End Get + End Property + Private ReadOnly Property MatEstado As String + Get + Return ViewState("MatEstado").ToString + End Get + End Property + Private ReadOnly Property MatPais As String + Get + Return ViewState("MatPais").ToString + End Get + End Property + Private ReadOnly Property MatCP As String + Get + Return ViewState("MatCP").ToString + End Get + End Property + Private Property ImprimeNombreSucursal As Boolean + Get + Return CBool(ViewState("ImprimeNombreSucursal")) + End Get + Set(value As Boolean) + ViewState("ImprimeNombreSucursal") = value + End Set + End Property + Private ReadOnly Property AplicaFEMSA As Boolean + Get + Return CBool(ViewState("AplicaFEMSA")) + End Get + End Property + Private ReadOnly Property AplicaComercioExterior As Boolean + Get + Return CBool(ViewState("AplicaComercioExterior")) + End Get + End Property + Private ReadOnly Property CveTipoOperacion As Integer + Get + Return CInt(ViewState("CveTipoOperacion")) + End Get + End Property + Private ReadOnly Property CvePedimento As Integer + Get + Return CInt(ViewState("CvePedimento")) + End Get + End Property + Private ReadOnly Property CveIncoterm As Integer + Get + Return CInt(ViewState("CveIncoterm")) + End Get + End Property + Private ReadOnly Property AplicaDetallista As Boolean + Get + Return CBool(ViewState("AplicaDetallista")) + End Get + End Property + Private ReadOnly Property AplicaFord As Boolean + Get + Return CBool(ViewState("AplicaFord")) + End Get + End Property + Private ReadOnly Property CveOS As Integer + Get + Return ViewState("CveOS").ToString.ToEntero + End Get + End Property + Private ReadOnly Property SaldoVenta As Decimal + Get + Return If(IsNothing(ViewState("SaldoVenta")), 0, ViewState("SaldoVenta").ToString.ToDecimal) + End Get + End Property + Private Property CvePSAmortizacion As Integer + Get + Return ViewState("CvePSAmortizacion").ToString.ToEntero + End Get + + Set(value As Integer) + ViewState("CvePSAmortizacion") = 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 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 SeGuardoPrePoliza As Boolean + Get + Return CBool(ViewState("SeGuardoPrePoliza")) + End Get + End Property + Private Property CveVentaFacturada As Integer + Get + Return ViewState("CveVentaFacturada").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveVentaFacturada") = value + End Set + End Property + Private ReadOnly Property AplicarVentaFacturada As Boolean + Get + Return CBool(ViewState("AplicarVentaFacturada")) + End Get + End Property + 'Estimaciones + Private Property CveContrato As Integer + Get + Return ViewState("CveContrato").ToString.ToEntero + End Get + + Set(value As Integer) + ViewState("CveContrato") = value + End Set + End Property + Private Property CvePedido As Integer + Get + Return ViewState("CvePedido").ToString.ToEntero + End Get + + Set(value As Integer) + ViewState("CvePedido") = value + End Set + End Property + Private Property CvePedido2 As Integer + Get + Return ViewState("CvePedido2").ToString.ToEntero + End Get + + Set(value As Integer) + ViewState("CvePedido2") = value + End Set + End Property + Private Property TipoContrato As Integer + Get + Return ViewState("TipoContrato").ToString.ToEntero + End Get + + Set(value As Integer) + ViewState("TipoContrato") = value + End Set + End Property + Private Property Opcion As String + Get + Return ViewState("Opcion").ToString + End Get + + Set(value As String) + ViewState("Opcion") = value + End Set + End Property + Private Property CorreoNotificacionPedDev As String + Get + Return If(IsNothing(ViewState("CorreoNotificacionDevPed")), "", ViewState("CorreoNotificacionDevPed").ToString()) + End Get + + Set(value As String) + ViewState("CorreoNotificacionDevPed") = value + End Set + End Property + + 'Presupuesto + Private Property CvePresupuesto As Integer + Get + Return ViewState("CvePresupuesto").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CvePresupuesto") = value + End Set + End Property + Private Property TotalOtrosConceptos As Decimal + Get + Return ViewState("TotalOtrosConceptos").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("TotalOtrosConceptos") = value + End Set + End Property + Private Property TipoCambioFactura As Decimal + Get + Return ViewState("TipoCambioFactura").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("TipoCambioFactura") = value + End Set + End Property + + Private Property DtPagos As DataTable + Get + Return CType(ViewState("DtPagos"), DataTable) + End Get + Set(value As DataTable) + ViewState("DtPagos") = value + End Set + End Property + Private Property DevolucionAlmacen As Integer + Get + Return ViewState("DevolucionAlmacen").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("DevolucionAlmacen") = value + End Set + End Property + Private ReadOnly Property TipoDoctoDevolucion As String + Get + Return ViewState("TipoDoctoDevolucion").ToString + End Get + End Property + Private Property PlazoCobranza As Integer + Get + Return ViewState("PlazoCobranza").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("PlazoCobranza") = value + End Set + End Property + Private Property PlazoCobranzaRemision As Integer + Get + Return ViewState("PlazoCobranzaRemision").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("PlazoCobranzaRemision") = value + End Set + End Property + + 'CvePAC + Private Property CvePAC As Integer + Get + Return ViewState("CvePAC").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CvePAC") = value + End Set + End Property + + Private Property AplicaDevolucion As Boolean + Get + Return If(IsNothing(ViewState("AplicaDevolucion")), False, CType(ViewState("AplicaDevolucion"), Boolean)) + End Get + Set(value As Boolean) + ViewState("AplicaDevolucion") = value + End Set + End Property + + Private Property CveVentaDevolucion As Integer + Get + Return If(IsNothing(ViewState("CveVentaDevolucion")), 0, CType(ViewState("CveVentaDevolucion"), Integer)) + End Get + Set(value As Integer) + ViewState("CveVentaDevolucion") = value + End Set + End Property + Private Property SaldoVentaDevolucion As Decimal + Get + Return ViewState("SaldoVentaDevolucion").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("SaldoVentaDevolucion") = value + End Set + End Property + Private Property ContratoOC As Boolean + Get + Return If(IsNothing(ViewState("ContratoOC")), False, CType(ViewState("ContratoOC"), Boolean)) + End Get + Set(value As Boolean) + ViewState("ContratoOC") = value + End Set + End Property + + Private Property TieneAlmacen As Boolean + Get + Return If(IsNothing(ViewState("TieneAlmacen")), False, CType(ViewState("TieneAlmacen"), Boolean)) + End Get + Set(value As Boolean) + ViewState("TieneAlmacen") = value + End Set + End Property + Private Property PorcentajeIVA As Decimal + Get + Return ViewState("PorcentajeIVA").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("PorcentajeIVA") = value + End Set + End Property + Private Property CveEstatusRefacturacion As Integer + Get + Return If(IsNothing(ViewState("CveEstatusRefacturacion")), 0, CType(ViewState("CveEstatusRefacturacion"), Integer)) + End Get + Set(value As Integer) + ViewState("CveEstatusRefacturacion") = value + End Set + End Property + +#End Region + +#Region "Propiedades PuntoVenta" + + Private Property CveCorte As Integer + Get + Return ViewState("CveCorte").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveCorte") = value + End Set + End Property + + Private Property Entrega As String + Get + Return ViewState("Entrega").ToString + End Get + Set(value As String) + ViewState("Entrega") = value + End Set + End Property + + Private Property Vigencia As String + Get + Return ViewState("Vigencia").ToString + End Get + Set(value As String) + ViewState("Vigencia") = value + End Set + End Property + + Private Property DineroCaja As Double + Get + Return ViewState("DineroCaja").ToString.ToDouble + End Get + Set(value As Double) + ViewState("DineroCaja") = value + End Set + End Property + + Private ReadOnly Property CveCicloComercial As Integer + Get + Return ViewState("CveCicloComercial").ToString.ToEntero + End Get + End Property + +#End Region + +#Region "Propiedades Contratos" + Private Property DtContratos As DataTable + Get + Return If(IsNothing(ViewState("DtContratos")), Nothing, CType(ViewState("DtContratos"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtContratos") = value + End Set + End Property + Private Property NumeroContrato As String + Get + Return ViewState("NumeroContrato").ToString + End Get + Set(value As String) + ViewState("NumeroContrato") = value + End Set + End Property + Private Property DescripcionContrato As String + Get + Return ViewState("DescripcionContrato").ToString + End Get + Set(value As String) + ViewState("DescripcionContrato") = value + End Set + End Property + Private Property NumeroLicitacion As String + Get + Return ViewState("NumeroLicitacion").ToString + End Get + Set(value As String) + ViewState("NumeroLicitacion") = value + End Set + End Property + Private Property CveAlmacenExistenciasContrato As Integer + Get + Return ViewState("CveAlmacenExistenciasContrato").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveAlmacenExistenciasContrato") = value + End Set + End Property + Private Property CveAlmacenOrigenContrato As Integer + Get + Return ViewState("CveAlmacenOrigenContrato").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveAlmacenOrigenContrato") = value + End Set + End Property + Private Property DtContratosSerieDetalle As DataTable + Get + Return If(IsNothing(ViewState("DtContratosSerieDetalle")), Nothing, CType(ViewState("DtContratosSerieDetalle"), DataTable)) + End Get + Set(value As DataTable) + ViewState("DtContratosSerieDetalle") = 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 CveConsecSerieLote As Integer + Get + Return CType(ViewState("CveConsecSerieLote"), Integer) + End Get + Set(value As Integer) + ViewState("CveConsecSerieLote") = value + End Set + End Property + Private Property LimitaCantidadSerieLote As Integer + Get + Return CType(ViewState("LimitaCantidadSerieLote"), Integer) + End Get + Set(value As Integer) + ViewState("LimitaCantidadSerieLote") = value + End Set + End Property + +#End Region + +#Region " PROPIEDADES NUEVAS | GUARDAR - IMPRESION " + Private Property ErrorList As List(Of String) + Get + Return CType(ViewState("ErrorList"), List(Of String)) + End Get + Set(value As List(Of String)) + ViewState("ErrorList") = value + End Set + End Property + Private Property MensajeAlert As StringBuilder + Get + Return CType(ViewState("MensajeAlert"), StringBuilder) + End Get + Set(value As StringBuilder) + ViewState("MensajeAlert") = value + End Set + End Property + Private Property ObjFactura As Modelos.Factura + Get + Return CType(ViewState("ObjFactura"), Modelos.Factura) + End Get + Set(value As Modelos.Factura) + ViewState("ObjFactura") = value + End Set + End Property + Private Property ObjFacturaDevolucion As Modelos.Factura + Get + Return CType(ViewState("ObjFacturaDevolucion"), Modelos.Factura) + End Get + Set(value As Modelos.Factura) + ViewState("ObjFacturaDevolucion") = value + End Set + End Property +#End Region + +#Region " PROPIEDADES NUEVAS " + Private Property CveOC As Integer + Get + Return ViewState("CveOC").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveOC") = value + End Set + End Property + Private Property EnviarCorreoCliente As Boolean + Get + Return CBool(ViewState("EnviarCorreoCliente").ToString) + End Get + Set(value As Boolean) + ViewState("EnviarCorreoCliente") = value + End Set + End Property + Private Property EstatusCliente As Boolean + Get + Return CBool(ViewState("EstatusCliente").ToString) + End Get + Set(value As Boolean) + ViewState("EstatusCliente") = value + End Set + End Property + Private Property CveMetodoPagoCliente As Integer + Get + Return ViewState("CveMetodoPagoCliente").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveMetodoPagoCliente") = 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 + 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 TotAnt As Decimal + Get + Return ViewState("TotAnt").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("TotAnt") = value + End Set + End Property + Private Property TotalOriginal As Double + Get + Return ViewState("TotalOriginal").ToString.ToDouble + End Get + Set(value As Double) + ViewState("TotalOriginal") = value + End Set + End Property + + Private Property AplicaCancelarRemision As Boolean + Get + Return CBool(ViewState("AplicaCancelarRemision").ToString) + End Get + Set(value As Boolean) + ViewState("AplicaCancelarRemision") = value + End Set + End Property + Private Property TipoVentaSucursal As Integer + Get + Return ViewState("TipoVentaSucursal").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("TipoVentaSucursal") = value + End Set + End Property + Private Property MensajeCveSAT As StringBuilder + Get + If ViewState("MensajeCveSAT") Is Nothing Then ViewState("MensajeCveSAT") = New StringBuilder + Return CType(ViewState("MensajeCveSAT"), StringBuilder) + End Get + Set(value As StringBuilder) + ViewState("TipoVentaSucursal") = value + End Set + End Property + Private Property EditoRemision As Boolean + Get + Return CBool(ViewState("EditoRemision").ToString) + End Get + Set(value As Boolean) + ViewState("EditoRemision") = value + End Set + End Property + Private Property AplicaNC As Boolean + Get + Return CBool(ViewState("AplicaNC").ToString) + End Get + Set(value As Boolean) + ViewState("AplicaNC") = value + End Set + End Property + Private Property DtVentasNC As DataTable + Get + Return CType(ViewState("DtVentasNC"), DataTable) + End Get + Set(value As DataTable) + ViewState("DtVentasNC") = value + End Set + End Property + Private Property AplicaNCMasiva As Boolean + Get + Return CBool(ViewState("AplicaNCMasiva").ToString) + End Get + Set(value As Boolean) + ViewState("AplicaNCMasiva") = value + End Set + End Property + Private Property RefacturacionGeneroNC As Boolean + Get + Return CBool(ViewState("RefacturacionGeneroNC").ToString) + End Get + Set(value As Boolean) + ViewState("RefacturacionGeneroNC") = value + End Set + End Property + Private Property ModalidadEdicion As Boolean + Get + Return CBool(ViewState("ModalidadEdicion").ToString) + End Get + Set(value As Boolean) + ViewState("ModalidadEdicion") = value + End Set + End Property + Private Property ConversionRemision As String + Get + Return ViewState("ConversionRemision").ToString + End Get + Set(value As String) + ViewState("ConversionRemision") = value + End Set + End Property + Private Property TipoCambioRemision As Decimal + Get + Return ViewState("TipoCambioRemision").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("TipoCambioRemision") = value + End Set + End Property + Private Property TieneContrato As Boolean + Get + Return CBool(ViewState("TieneContrato").ToString) + End Get + Set(value As Boolean) + ViewState("TieneContrato") = value + End Set + End Property + Private Property CveOrdenCompraContrato As Integer + Get + Return ViewState("CveOrdenCompraContrato").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveOrdenCompraContrato") = value + End Set + End Property + Private Property ContratosConOC As StringBuilder + Get + If ViewState("ContratosConOC") Is Nothing Then ViewState("ContratosConOC") = New StringBuilder + Return CType(ViewState("ContratosConOC"), StringBuilder) + End Get + Set(value As StringBuilder) + ViewState("ContratosConOC") = value + End Set + End Property + Private Property RequiereOC As Boolean + Get + Return CBool(ViewState("RequiereOC").ToString) + End Get + Set(value As Boolean) + ViewState("RequiereOC") = value + End Set + End Property + Private Property PorcentajeCredito As Decimal + Get + Return ViewState("PorcentajeCredito").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("PorcentajeCredito") = value + End Set + End Property + Private Property CvePedidoA As Integer + Get + Return ViewState("CvePedidoA").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CvePedidoA") = value + End Set + End Property + + Private Property CveEmpresaCRM As Integer + Get + Return ViewState("CveEmpresaCRM").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveEmpresaCRM") = value + End Set + End Property + + Private Property CveAcercamientoCRM As Integer + Get + Return ViewState("CveAcercamientoCRM").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveAcercamientoCRM") = value + End Set + End Property + + Private Property DtPedidos2 As DataTable + Get + Return CType(ViewState("DtPedidos2"), DataTable) + End Get + Set(value As DataTable) + ViewState("DtPedidos2") = value + End Set + End Property + Private Property DtPedidos2PS As DataTable + Get + Return CType(ViewState("DtPedidos2PS"), DataTable) + End Get + Set(value As DataTable) + ViewState("DtPedidos2PS") = value + End Set + End Property + + Private Property CveEstatus As Integer + Get + Return ViewState("CveEstatus").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("CveEstatus") = value + End Set + End Property + Private Property DiasCredito As Integer + Get + Return ViewState("DiasCredito").ToString.ToEntero + End Get + Set(value As Integer) + ViewState("DiasCredito") = value + End Set + End Property + Private Property EsDiasCreditoFijo As Boolean + Get + Return CBool(ViewState("EsDiasCreditoFijo").ToString) + End Get + Set(value As Boolean) + ViewState("EsDiasCreditoFijo") = value + End Set + End Property + Private Property VentaSaldoAlmacen As Decimal + Get + Return ViewState("VentaSaldoAlmacen").ToString.ToDecimal + End Get + Set(value As Decimal) + ViewState("VentaSaldoAlmacen") = value + End Set + End Property + Private Property SeCancelaRemisionProceso As Boolean + Get + Return CBool(ViewState("SeCancelaRemisionProceso").ToString) + End Get + Set(value As Boolean) + ViewState("SeCancelaRemisionProceso") = value + End Set End Property -#End Region +#End Region -#Region " A C U M U L A D O R E S" +#Region " A C U M U L A D O R E S" - Private Property ClienteEsDistribuidor As Boolean - Get - If ViewState("ClienteEsDistribuidor") Is Nothing Then - Return False - Else - Return Boolean.Parse(ViewState("ClienteEsDistribuidor").ToString) - End If - End Get - Set(value As Boolean) - ViewState("ClienteEsDistribuidor") = value - End Set + Private Property ClienteEsDistribuidor As Boolean + Get + If ViewState("ClienteEsDistribuidor") Is Nothing Then + Return False + Else + Return Boolean.Parse(ViewState("ClienteEsDistribuidor").ToString) + End If + End Get + Set(value As Boolean) + ViewState("ClienteEsDistribuidor") = value + End Set End Property -#End Region +#End Region - Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load - If Not IsPostBack Then - Modalidad = "" - Opcion = "" - Index = 0 - TotAnt = 0 - 'CargoComercioExterior = False - DdlBPPS.setEsWebService(True) - DdlBPPS.ddlWS.Attributes.Add("data-clear", "1") - ViewState("ProcesoCorrecto") = True - ViewState("NuevaFactura") = -1 - ViewState("CveDevolucion") = -1 - ViewState("CvePedido") = -1 - ViewState("CvePedido2") = -1 - ViewState("TipoContrato") = -1 - ViewState("CveVenta") = -1 - ViewState("CveCliente") = -1 - ViewState("CveClienteAnterior") = -1 - ViewState("CveOS") = -1 - ViewState("CveOC") = -1 - ViewState("CveAnticipo") = -1 - ViewState("CveFactura") = -1 - ViewState("CveCicloComercial") = -1 - ViewState("Entrega") = "" - ViewState("Vigencia") = "" - ViewState("AplicarVentaFacturada") = False - ViewState("SeGuardoPrePoliza") = False - ViewState("TipoDoctoDevolucion") = "" - ViewState("EditoRemision") = False - ViewState("RequiereOC") = False - ViewState("ClienteDesglosaIEPS") = False - ViewState("ClienteRetIVA") = 0 - ViewState("ClienteRetISR") = 0 - idCuentaContabilizacion = 1 - CveEmpresaCRM = 0 - CveAcercamientoCRM = 0 - EstatusCliente = False - RemisionesLista = New List(Of Integer) - Pedidos2Lista = New List(Of Integer) - CotizacionesLista = New List(Of Integer) - CuentasContablesInvalidas = New StringBuilder - CvePrePoliza = 0 - TotalOtrosConceptos = 0 - CveUsuarioActual = UsuarioActual.CveUsuario - EmpresaActual = UsuarioActual.Empresa - IdPoliza = 0 - CveCorte = -1 - CveContrato = -1 - DevolucionAlmacen = 0 - CvePSAmortizacion = 0 - EraCotizacion = 0 - FacturaMateriales = 0 - CvePedidoA = 0 - EsCreaApartirDe = False - RequiereAlmacenDestino = False - RequiereAlmacenOrigen = False - TmpDTComplementos = New DataTable - DtRemConceptosSurtidos = Nothing - TipoVentaSucursal = 0 - PlazoCobranza = 0 - PlazoCobranzaRemision = 0 - TipoCambioFactura = 1 - NumeroContrato = "" - DescripcionContrato = "" - NumeroLicitacion = "" - ImprimeNombreSucursal = False - RegistraScript("SetDisabledTxtTotal(true);") - TrVistaPrevia.Visible = False - CveMetodoPagoCliente = 1 - CveAlmacenExistenciasContrato = -1 - UpFacturar.Update() - 'CargaTiposDocumentos() - TrEmitir.Visible = False - ViewState("EstablecioFolio") = False - 'ViewState("SubProyectoPorcentajeIVA") = 0 - RefacturacionGeneroNC = False - ModalidadEdicion = False - ConversionRemision = "" - TipoCambioRemision = 1 - CveOrdenCompraContrato = -1 - TieneContrato = False - AplicaNC = False - TieneAlmacen = False - CveEstatus = -1 - PorcentajeIVA = 0 - EsDiasCreditoFijo = False - DiasCredito = 0 - AplicaCancelarRemision = False - SeCancelaRemisionProceso = False - TotalOriginal = 0 - CveAlmacenDevolucion = 0 - - txtFechaICot.Text = Now.AddMonths(-3).ToShortDateString - TxtFechaIRem.Text = Now.AddMonths(-3).ToShortDateString - TxtFechaIPed.Text = Now.AddMonths(-3).ToShortDateString - TxtFechaIOC.Text = Now.AddMonths(-3).ToShortDateString - - txtFechaFCot.Text = Now.ToShortDateString - TxtFechaFRem.Text = Now.ToShortDateString - TxtFechaFPedido.Text = Now.ToShortDateString - TxtFechaFOC.Text = Now.ToShortDateString - - If UsuarioActual.TienePermisoProceso(177) Then - DdlTipoComprobante.Items.Insert(4, New ListItem("Pedido de Contrato", "Ped")) - End If - - TrSinExistencia.Visible = UsuarioActual.TienePermisoProceso(276) - - If UsuarioActual.CveEmpresa.Contiene(119, 1) Then - ImgDescPU.Visible = False - ImgDescConcepto.Visible = False - DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Autorización", "PA")) - End If - - DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Pedido", "Pd2")) - - If UsuarioActual.Empresa.Funcionalidad(528) = "1" Then 'FUNCIONALIDAD. DE REGISTRO DE CUENTA PREDIAL. - GvPS.Columns(ColumnaPredial).Visible = True - thPredial1.Visible = True - thPredial2.Visible = True - End If - - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then ' PARA BUSCAR FOLIO DE OC, YA FACTURADA EN EL CAMPO ORDEN DE COMPRA - TxtOrdenCompra.Attributes.Add("onblur", "BuscarOCRegistrada();") - End If - - If UsuarioActual.Empresa.Funcionalidad(561).ToString = "1" Then - thPoliza.Visible = True - thPoliza2.Visible = True - End If - - - DdlSATPS.setEsWebService(True) : DdlSATPS.Attributes.Add("data-metodo", "getpssat") - DivPSSAT.Visible = True - - SetValues() - CvePresupuesto = 0 - - 'MODALIDADES - If Request("Op") IsNot Nothing AndAlso Request("Op").ToString <> "" Then - Opcion = Request("Op").ToString - LblTitulo.Text = "Registro de Cotizaciones" - TrTipo.Visible = False - TabAlmacen.Visible = False - TabDetalleVentas.Visible = False - TabVentaAF.Visible = False - TabE.Visible = False - TabComplementos.Visible = False - divcondicionespago.Visible = UsuarioActual.Empresa.CvePlataforma = 1 'SI ES PLATAFORMA ERP SIEMPRE VSIBLE ESTE PORLET - ImgAntiPend.Visible = False - TrObsAlmacen.Visible = False - TrTxtObsAlmacen.Visible = False - TrPedido.Visible = False - TrOC.Visible = False - DdlTipoComprobante.SelectedValue = "Op" - Else - Opcion = "Ing" - DdlTipoComprobante.SelectedValue = "Ing" - End If - - - - 'DdlTipoComprobante.Attributes.Add("onChange", "ActivaReferencia(this)") - TxtFecha.Text = Now.ToShortDateString() - TxtFechaEjecucion.Text = Now.ToShortDateString - LblUsuario.Text = UsuarioActual.Usuario - LblFechaRegistro.Text = Now.ToShortDateString() - - TxtPrecioPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();") - TxtCantidadPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();") - ImgDescPU.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '0'; $get('LblPrecio1').style.display = ''; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") - ImgDescConcepto.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '1'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = ''; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") - ImgDescTotal.Visible = False - - ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") - ImgAntiPend.Attributes.Add("onclick", "$get('HdnTipoDescuento').value = '3'; MuestraAnticipos();") - ImgOtrosConceptos.Attributes.Add("onclick", "javascript:$('#ModalOtrosConceptos').modal();") - LkbAgregarComplementos.Attributes.Add("onclick", "javascript:$('#ModalComplementos').modal();") - 'ImgCerrar.Attributes.Add("OnClick", "$('#DivAnticipos').hide();") - 'LkbEstadodeCaja.Attributes.Add("OnClick", "MuestraEstadoCaja();") - 'LkbIngreso.Attributes.Add("OnClick", "MuestraIngresoEgreso(1);") - 'LkbRetiro.Attributes.Add("OnClick", "MuestraIngresoEgreso(0);") - TxtImporteEfectivo.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") - TxtImporteCredito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") - TxtImporteDebito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") - TxtImporteCheque.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") - TxtImporteTransferencia.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") - TxtEfectivoEnCaja.Attributes.Add("onKeyUp", "CalculaDiferencia();") - 'ImgCerrarTerminoCorte.Attributes.Add("OnClick", "$('#DivTerminarCorte').hide();") - 'ImgCerrarIE.Attributes.Add("OnClick", "$('#DivIngresoEgreso').hide();")DdlTipoComprobante - 'ImgCerrarEstadoCaja.Attributes.Add("OnClick", "$('#DivEstadoCaja').hide();") - TabAlmacen.Enabled = UsuarioActual.Empresa.UsaInventarios - TxtPorDescP.Attributes.Add("onKeyUp", "CalculaDescuento();") - TxtDescP.Attributes.Add("onKeyUp", "CalculaDescuento();") - TxtCantidadPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')") - TxtObsPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')") - TxtPrecioPyME.Attributes.Add("onkeypress", "CallServerMethod(event)") - - CreaDTmpC() - CreaDTmpF() - CreaDTDocumentosRelacionados() - CargaDdlSubProyectos() - CargaProyecto() - CargaSucursales() - - CargaClasificaciones() - CargaPS(-1, DdlPS) - CargaPSPyME(-1, DdlPSPyME) - - CreaDTVentas() - CargaMetodosPago() - 'CargaFormaPago(-1) - CargaUsoCFDI() - CargaTiposRelacion() - CargaMonedas() - CargaVendedores() - CargarAlmacenes() - CargaFormaEntrega() - CargaCuentasTerminal() - CargaDdlNCPS() - - - - 'SI USUARIO USA AMORTIZACIÓN CONTABLE, se carga las tablas para usarlas mas adelante - If UsuarioActual.Empresa.UsaAC Then - - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) - DdlTipoComprobante.Items.Add(New ListItem("Compromisos", "Com")) - DdlTipoComprobante.Items.Add(New ListItem("Orden Pago", "OP")) - - Dim AC As New ClsAC - If AC.GetPresupuestoIngresos(-1, Now.Year, True, UsuarioActual.CveEmpresa) Then - DdlFuenteRecaudacion.DataSource = AC.DtResultados() - DTPresupuestoIngresos = AC.DtResultados() - ViewState("DTFuenteRecaudacion") = AC.DtResultados() - 'GenerarPolizasAC() - End If - AC.Dispose() - 'columna de Fuente de recaudacion - GvPS.Columns(21).Visible = True - nomostrar.Visible = True - nomostrar2.Visible = True - 'GvPS.Width = 1250 - DdlFuenteRecaudacion.DataBind() - Else - TFuenteRecaudacion.Visible = False - End If - - 'Carga cliente - If Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 AndAlso Request("CveFactura") Is Nothing Then - ViewState("CveCliente") = Request("CveCliente") - HdnCveCliente.Value = Request("CveCliente") - CargaCliente(CveCliente) - VerificarContrato(True) - ElseIf Request("CveFactura") IsNot Nothing AndAlso IsNumeric(Request("CveFactura")) AndAlso Request("CveFactura").ToEntero > 0 AndAlso Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 Then - ViewState("CveCliente") = Request("CveCliente") - ViewState("CveFactura") = Request("CveFactura").ToEntero - Dim RFC As String = CargaFactura(CveFactura) - CargaCliente(CveCliente) - Else - ViewState("CveCliente") = -1 - HdnCveCliente.Value = "-1" - End If - - 'Carga empresa CRM - If Request("CveEmpresaCRM") IsNot Nothing AndAlso IsNumeric(Request("CveEmpresaCRM")) AndAlso Request("CveEmpresaCRM").ToEntero > 0 Then - ViewState("CveEmpresaCRM") = Request("CveEmpresaCRM") - CargaEmpresaCRM(CveEmpresaCRM) - Else - ViewState("CveEmpresaCRM") = -1 - End If - - If Request("CveAcercamientoCRM") IsNot Nothing AndAlso IsNumeric(Request("CveAcercamientoCRM")) AndAlso Request("CveAcercamientoCRM").ToEntero > 0 Then - ViewState("CveAcercamientoCRM") = Request("CveAcercamientoCRM") - Else - ViewState("CveAcercamientoCRM") = -1 - End If - - 'mensaje de confirmación al guardar - BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)},{If(HdnTieneAnticipos.Value = "1", 1, 0)});" - BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") - BtnEmitirImprimir.Attributes.Add("data-popout", "true") - BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") - BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") - BtnEmitirImprimir.Attributes.Add("data-html", "true") - - If UsuarioActual.CveEmpresa.Contiene(126) Then ' cuando la empresa se relaciona a ua orden de producción, Citrus Game - TrOP.Visible = True - CargaOrdenProduccion() - End If - - 'Carga Venta - If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero > 0 Then - ViewState("CveVenta") = Request("CveVenta") - If CargaVenta() Then - - 'DdlSucursal.Enabled = False - DdlSubProyectoDatos.Enabled = False - BtnEmitirImprimir.Visible = False - BtnCrearApartirDe.Visible = True - 'DdlEstatus.Enabled = True - - DivFechaAnticipoCliente.Visible = True - TxtFechaAnticipoCliente.Text = Now.ToShortDateString - - - ImgAddObs.Visible = True - CargaEventoBitacora() - - ConfiguraTipoDocto() - - TrFolioFiscal.Visible = True - - ' Si esta cancelado el compromiso/Pedido no se puede editar el estatus - 'If DdlEstatus.SelectedValue.Contiene({"9", "14", "17"}) Then - ' DdlEstatus.Enabled = False - 'End If - - 'CargaDetalle de Almacen - If Not LblAlertRefacInv.Visible Then - If CveVentaPadre > 0 Then - InventarioMov(CveVentaPadre) - Else - InventarioMov() - End If - End If - - - - - 'PERMISO PARA CANCELAR PEDIDO - If GvInv.Rows.Count = 0 Then - If DdlTipoComprobante.SelectedValue.Contiene("Ped") And Not CveEstatus = 14 Then - If UsuarioActual.TienePermisoProceso(186) Then - LBCancelarPedido.Visible = True - End If - End If - End If - - 'CARGA GV DE COMERCIO EXTERIOR SI NO ESTA TIMBRADA - If LblSeTimbro.Text = "No" Then - CargaGvComercioExterior() - End If - - 'HABILITA IMPRESION DE FORMATO CICOVISA - If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then - LnkImprimirFormatoCicovisa.Visible = True - End If - - If UsuarioActual.TienePermisoProceso(269) AndAlso Not DevolucionAlmacen = 2 Then - DivDevAlm.Visible = True - End If - - End If - Else - If Request("CveOS") IsNot Nothing AndAlso IsNumeric(Request("CveOS")) AndAlso Request("CveOS").ToEntero > 0 Then - ViewState("CveOS") = Request("CveOS") - CargaOS(CveOS) - Else - 'Modalidad Devoluciones y Refacturacion - If Request("CveDevolucion") IsNot Nothing AndAlso IsNumeric(Request("CveDevolucion")) AndAlso Request("CveDevolucion").ToEntero > 0 Then - ViewState("CveDevolucion") = Request("CveDevolucion") - ViewState("CveVenta") = Request("CveDevolucion") - ViewState("NuevaFactura") = Request("NuevaFactura") - - trNCFactura.Visible = True - DdlNCFactura.DataSource = Nothing - DdlNCFactura.DataBind() - CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString.ToEntero) - DdlNCFactura.SelectedValueExist(CveDevolucion) - - If NuevaFactura = 0 Then - LbAgregar.Visible = False - If DdlTipoComprobante.SelectedValue = "Ing" Then - DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) - DdlTipoComprobante.SelectedValue = "Dev" - ElseIf DdlTipoComprobante.SelectedValue = "Ant" Then - DdlTipoComprobante.SelectedValueExist("Egs") - End If - DdlTipoComprobante.Enabled = False - CargaFolios() - - DdlUsoCFDI.Enabled = True - DdlUsoCFDI.SelectedValueExist("2") - DdlMetodoPago33.Enabled = True - DdlMetodoPago33.SelectedValueExist("1") - DdlFormaPago33.Enabled = True - DdlFormaPago33.SelectedValueExist("20") - - End If - - If NuevaFactura = 1 Then - TrTipoRelacion.Visible = True - DdlTiposRelacion.SelectedValueExist("4") - - Dim ObjInv As New ClsInventarios - If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjInv.DtResultados.Rows.Count > 0 Then - TieneAlmacen = True - End If - End If - ObjInv.Dispose() - - End If - - CargaNuevaFactura(Nothing) - - - 'NOTA DE CREDITO - If NuevaFactura = 2 Then - DdlTipoComprobante.Items.Insert(0, New ListItem("Nota de Crédito", "Egs")) - DdlTipoComprobante.SelectedValue = "Egs" - DdlTipoComprobante.Enabled = False - CargaFolios() - - DdlUsoCFDI.Enabled = True - DdlUsoCFDI.SelectedValueExist("2") - DdlMetodoPago33.Enabled = True - DdlMetodoPago33.SelectedValueExist("1") - DdlFormaPago33.Enabled = True - DdlFormaPago33.SelectedValueExist("20") - TrTipoRelacion.Visible = True - DdlTiposRelacion.SelectedValueExist("1") - End If - - End If - - 'ENTREGA POR ADELANTADO - If DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ped", "PeC") Then - If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then - RequiereAlmacenDestino = True - - If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then - TrAlmacenAsignado.Visible = True - End If - - Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero - If CveAlmacenDestino > 0 Then - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)") - DdlAlmacenAsignado.DataBind() - DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString)) - DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString - Else - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (10)") - DdlAlmacenAsignado.DataBind() - End If - UpParametros.Update() - Else - RequiereAlmacenDestino = False - TrAlmacenAsignado.Visible = False - End If - - 'ENVIO DE FACTURA - If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then - ChkEnviarFactura.Checked = EnviarCorreoCliente - ChkEnviarFactura.Visible = True - LblEnviarMail.Visible = True - End If - End If - - 'Modalidad Contrato - If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").Contiene("0", "1") Then - TrAlmacenOrigen.Visible = False - If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then - TrAlmacenAsignado.Visible = True - - End If - UPCondicionesPago.Visible = False - RequiereAlmacenDestino = True - CveContrato = Request("CveContrato").ToEntero - TipoContrato = Request("Tipo").ToEntero - - 'DESACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto disabled") - TxtCodigo.ReadOnly = True - - CargarContratoUrl() - UpParametros.Update() - End If - - 'Modalidad CveCicloComercial - If Request("CveCicloComercial") IsNot Nothing AndAlso IsNumeric(Request("CveCicloComercial")) AndAlso Request("CveCicloComercial").ToEntero > 0 Then - ViewState("CveCicloComercial") = Request("CveCicloComercial").ToEntero - CargaCicloComercialURL() - UpParametros.Update() - End If - - 'Modalidad Devolucion Pedido **REVISAR SI SE USA - If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero > 0 AndAlso Request("CvePedido") IsNot Nothing AndAlso IsNumeric(Request("CvePedido")) AndAlso Request("CvePedido").ToEntero > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").ToEntero = 2 Then - CveContrato = Request("CveContrato").ToEntero - CvePedido = Request("CvePedido").ToEntero - TipoContrato = Request("Tipo").ToEntero - - ''REQUIERE DEVOLUCION - 'DdlDevolucionAlmacen.SelectedValue = "1" - 'DdlDevolucionAlmacen.Enabled = False - 'UpInvDev.Update() - - CargarPedidoUrl() - End If - - 'MODALIDAD DEVOLUCION PEDIDO NUEVO - If Request("DevPed") IsNot Nothing AndAlso IsNumeric(Request("DevPed")) AndAlso Request("DevPed").ToEntero > 0 AndAlso Request("MovInv") IsNot Nothing AndAlso IsNumeric(Request("MovInv")) AndAlso Request("MovInv").ToEntero > 0 Then - ViewState("CveVenta") = Request("DevPed") - ViewState("MovInv") = Request("MovInv") - ViewState("CveMovimientoDetalle") = IfNull(Request("CveMovimientoDetalle"), "-1").ToString.ToEntero - DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe")) - DdlTipoComprobante.SelectedValue = "DPe" - DdlTipoComprobante.Enabled = False - CargaFacturaDevolucionPedido() - CargaFolios() - If CveContrato > 0 Then - CargaNotificacionContrato() - End If - End If - - 'Modalidad Cotizacion - If Opcion = "Cot" Then - DdlTipoComprobante.SelectedValueExist(Opcion) - DdlTipoComprobante.Enabled = False - - DdlTipoComprobante_SelectedIndexChanged(sender, Nothing) - 'Carga CvePresupuesto - If Request("CvePresupuesto") IsNot Nothing AndAlso IsNumeric(Request("CvePresupuesto")) AndAlso Request("CvePresupuesto").ToEntero > 0 Then - CvePresupuesto = Request("CvePresupuesto").ToEntero - 'DdlEstatus.Enabled = False - End If - - End If - CargaEstatusFactura(Opcion) - - If Opcion = "Ing" Then - ObtenerFechaVencimientoCER() - 'DdlEstatus.Enabled = False - If UsuarioActual.Empresa.TipoFacturacion = "CBB" Then - 'DdlEstatus.SelectedValue = "3" - CveEstatus = 3 - ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then - 'DdlEstatus.SelectedValue = "2" - CveEstatus = 2 - End If - End If - - End If - End If - - 'CARGA PARA FACTURAR - ViewState("CveRemision") = IfNull(Request("CveRemision").ToEntero, 0) - ViewState("CveCotizacion") = IfNull(Request("CveCotizacion").ToEntero, 0) - - If ViewState("CveCotizacion").ToString.ToEntero > 0 Then - EsCreaApartirDe = True - End If - - If ViewState("CveRemision").ToString.ToEntero > 0 Or ViewState("CveCotizacion").ToString.ToEntero > 0 Then - 'ViewState("CveRemision") = Request("CveRemision") - 'Dim CveRemision As Integer = ViewState("CveRemision").ToString.ToEntero - - CargaVenta() - - 'DdlSucursal.Enabled = False - BtnCrearApartirDe.Visible = True - 'DdlEstatus.Enabled = True - - ImgAddObs.Visible = True - CargaEventoBitacora() - - DdlTipoComprobante.Enabled = False - DdlTipoComprobante.SelectedValue = "Ing" - - CargaEstatusFactura() - 'DdlEstatus.SelectedValueExist("2") - - ConfiguraTipoDocto() - CargaFolios() - - BtnEmitirImprimir.Text = "Facturar" - BtnEmitirImprimir.Visible = True - - UpnTools.Update() - - TxtFecha.Text = Now.ToShortDateString - - '' Si esta cancelado el compromiso no se puede editar el estatus - 'If DdlEstatus.SelectedValue = "9" Then - ' DdlEstatus.Enabled = False - 'End If - - 'CargaDetalle de Almacen - InventarioMov() - End If - - If Not ExFolioFactura Then SetPermisos() - - 'SELECCIONA VENDEDOR DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE - If UsuarioActual.CveVendedor > 0 Then - If CveVenta = -1 AndAlso Not DdlVendedor.SelectedValue.ToEntero > 0 Then DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) - If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then - DdlVendedor.Enabled = False - End If - 'multiples vendedores visible - If UsuarioActual.TienePermisoProceso(153) Then - DdlVendedor.Enabled = True - End If - End If - - If UsuarioActual.Empresa.Funcionalidad(301).ToEntero > 0 Then - TxtFecha.Enabled = False - ImgFecha.Visible = False - End If - - CargarCodigo() - InicializaImprimirNew() - - 'RegistraScript("FnSuma()") - TxtSubTotal.Attributes.Add("onKeyUp", "FnSuma()") - TxtIVA.Attributes.Add("onKeyUp", "FnSuma()") - TxtIEPS.Attributes.Add("onKeyUp", "FnSuma()") - TxtRetIVA.Attributes.Add("onKeyUp", "FnSuma()") - TxtRetISR.Attributes.Add("onKeyUp", "FnSuma()") - - 'Permitir Edicion de Iva - If UsuarioActual.Empresa.Funcionalidad(509) = "1" Then - TxtIVA.Enabled = True - 'TxtTotal.Enabled = True - RegistraScript("SetDisabledTxtTotal(false);") - TxtSubTotal.Enabled = True - TxtSubTotal2.Enabled = True - End If - - 'Cortes de Caja - If UsuarioActual.TienePermisoProceso(160) Then - CargaCorteCaja() - End If - '********************************** - - 'Complementos de Timbrado - Dim ObjVenta As New ClsVentas - If ObjVenta.GetVentaComplementos() Then - RblComplementos.DataSource = ObjVenta.DtResultados - RblComplementos.DataBind() - UpComplementos.Update() - End If - ObjVenta.Dispose() - - CargaFormatoSucursal() - - InicializaDevolucionAlmacen() - CargaOtrosConceptos() - CargaFacturaOC() - - 'SELECCIONA SUCURSAL DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE - If Not (CveCliente > 0 Or CveVenta > 0) Then - DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto) - DdlSubProyectoEjecucion.SelectedValueExist(UsuarioActual.CveSubProyecto) - DdlSubProyectoCobranza.SelectedValueExist(UsuarioActual.CveSubProyecto) - If UsuarioActual.TienePermisoProceso(152) Then - DdlSubProyectoDatos.Enabled = False - End If - CambiaSucursal() - UpParametros.Update() - UpDetalle.Update() - End If - - 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE - EnviarCorreoCliente = True - If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then - ChkEnviarFactura.Checked = False - ChkEnviarFactura.Visible = False - LblEnviarMail.Visible = False - Else - ChkEnviarFactura.Checked = EnviarCorreoCliente - ChkEnviarFactura.Visible = True - LblEnviarMail.Visible = True - End If - - CargaFletes() - - If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then - DdlProyecto.Visible = False - BrSubProyecto.Visible = False - DdlProyectoPyME.Visible = False - LblProyectoHeader.Text = "Sucursal" - LblSubProyecto.Text = "" - divProyectoPyME.Visible = False - LblSubProyectoPyME.InnerText = "Sucursal" - - DdlSubProyecto.Items.Clear() - DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) - DdlSubProyecto.DataBind() - DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - DdlSubProyectoPyME.Items.Clear() - DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - 'DdlSubProyectoPyME.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) - DdlSubProyectoPyME.DataBind() - DdlSubProyectoPyME.Items.Insert(0, New ListItem("Seleccione", "-1")) - - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then - DdlProyecto.Visible = False - BrSubProyecto.Visible = False - DdlProyectoPyME.Visible = False - LblProyectoHeader.Text = "Proyecto" - LblSubProyecto.Text = "" - divProyectoPyME.Visible = False - LblSubProyectoPyME.InnerText = "Proyecto" - - DdlSubProyecto.Items.Clear() - DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) - DdlSubProyecto.DataBind() - DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - - DdlSubProyectoPyME.Items.Clear() - DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - 'DdlSubProyectoPyME.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) - DdlSubProyectoPyME.DataBind() - DdlSubProyectoPyME.Items.Insert(0, New ListItem("Seleccione", "-1")) - - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then - LblProyectoHeader.Text = "Sucursal" - LblSubProyecto.Text = "Proyecto" - - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then - LblProyectoHeader.Text = "Proyecto" - LblSubProyecto.Text = "Sucursal" - - End If - - If UsuarioActual.Empresa.CvePlataforma = 2 Then - ImgOtrosConceptos.Visible = False - TrFormaEntrega.Visible = False - TabDetalleVentas.Visible = False - TabE.Visible = False - LnkOCs.Visible = False - GvPS.Columns(8).Visible = False - TrEdit.Visible = False - ThProyecto.Visible = False - For Each Gvr As GridViewRow In GvPS.Rows - Gvr.FCLinkButton("imgE").Visible = False - Gvr.FCLinkButton("imgEPyME").Visible = True - Next - LnkAddVenta.Visible = True - divproyectos.Visible = False - End If - - TabVentaAF.Visible = False - - 'CARGA VALORES INICIALES PARA AGREGAR PS DESDE MODAL - CargaMetodosPSModal() - - 'CARGA VALORES DE ORDEN DE PRODUCCION - Dim CveOrdenProduccion = IfNull(Request("CveOrdenProduccion"), "-1").ToString.ToEntero - If CveOrdenProduccion > 0 And Not CveVenta > 0 Then - DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion) - If DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then - DdlTipoComprobante.SelectedValue = "Rem" - DdlMoneda.SelectedValue = "2" - Dim ObjCGame As New ClsCGame - If ObjCGame.GetAvance(DdlOrdenProduccion.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then - For Each dt As DataRow In ObjCGame.DtResultados.Rows - If dt("Avance").ToString.ToEntero > 0 Then - AgregarProductoServicio(dt("Avance").ToString.ToDecimal, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString, dt("PU").ToString.ToDecimal, 0, - DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text) - 'AddPS(dt("Avance").ToString.ToDouble, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString, dt("PU").ToString.ToDouble, 0, 0, 0, 1, 0, True, - ' "", DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, 2, HdnTipoInv.Value.ToEntero) - End If - Next - GvPS.DataSource = TmpDT - End If - If ObjCGame.GetFlete(UsuarioActual.CveEmpresa) Then - TxtObsFact.Text = String.Format("Chofer: {0}; Remolque: {1}; Scat: {2};", ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Chofer"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("CodigoDescripcionRemolque"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Scat")) - End If - ObjCGame.Dispose() - GvPS.DataBind() - UPObservaciones.Update() - UpPS.Update() - CargaFolios() - End If - End If - - - If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero = -1 AndAlso UsuarioActual.CveTipoDocumento.Length = 3 Then - CargaDdlSubProyectos() - UpParametros.Update() - DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento) - CambiaTipoDocto() - LimpiaEscondeContado() - End If - - InicializaAplicarNC() - - If CveCliente > 0 Then - CargaRestriccionesCreditoCliente() - End If - - If Not CveVenta > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(403).ToString = "1" Then - If (DdlTipoComprobante.Items.FindByValue("Ing") IsNot Nothing) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) - End If - End If - - End If - - ''EN REALIDAD SE OCUPAN ESTAS COSAS DENTRO DEL POSTABCK ??? - If Not CveVenta > 0 Then - 'LbDescargarExcel.Visible = True - HlAgregarExcel.Visible = True - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then - ' IPP 15 Julio 2017 - ERA FALSE - ImgAntiPend.Visible = False - UpPS.Update() - End If - - If UsuarioActual.Empresa.Funcionalidad(517) <> "" Then - TxtFolio.Enabled = False - TxtFecha.Enabled = False - If LblSeTimbro.Text = "No" And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev", "Ant") Then - TxtFecha.Text = Now.ToShortDateString - End If - ImgFecha.Visible = False - End If - - 'condición temporal por implementación JAM. usuario FernandaRomo - If UsuarioActual.CveUsuario.Contiene(11703, 1719) Then - TxtFecha.Enabled = True - ImgFecha.Visible = True - End If - End Sub - - Private Sub ConfiguraEmpresa() - Select Case UsuarioActual.CveEmpresa - Case 119 - TxtObsPS.Attributes.Add("onkeypress", "setFocus(event,'TxtPrecio');") - End Select + Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load + If Not IsPostBack Then + Modalidad = "" + Opcion = "" + Index = 0 + TotAnt = 0 + 'CargoComercioExterior = False + DdlBPPS.setEsWebService(True) + DdlBPPS.ddlWS.Attributes.Add("data-clear", "1") + ViewState("ProcesoCorrecto") = True + ViewState("NuevaFactura") = -1 + ViewState("CveDevolucion") = -1 + ViewState("CvePedido") = -1 + ViewState("CvePedido2") = -1 + ViewState("TipoContrato") = -1 + ViewState("CveVenta") = -1 + ViewState("CveCliente") = -1 + ViewState("CveClienteAnterior") = -1 + ViewState("CveOS") = -1 + ViewState("CveOC") = -1 + ViewState("CveAnticipo") = -1 + ViewState("CveFactura") = -1 + ViewState("CveCicloComercial") = -1 + ViewState("Entrega") = "" + ViewState("Vigencia") = "" + ViewState("AplicarVentaFacturada") = False + ViewState("SeGuardoPrePoliza") = False + ViewState("TipoDoctoDevolucion") = "" + ViewState("EditoRemision") = False + ViewState("RequiereOC") = False + ViewState("ClienteDesglosaIEPS") = False + ViewState("ClienteRetIVA") = 0 + ViewState("ClienteRetISR") = 0 + idCuentaContabilizacion = 1 + CveEmpresaCRM = 0 + CveAcercamientoCRM = 0 + EstatusCliente = False + RemisionesLista = New List(Of Integer) + Pedidos2Lista = New List(Of Integer) + CotizacionesLista = New List(Of Integer) + CuentasContablesInvalidas = New StringBuilder + CvePrePoliza = 0 + TotalOtrosConceptos = 0 + CveUsuarioActual = UsuarioActual.CveUsuario + EmpresaActual = UsuarioActual.Empresa + IdPoliza = 0 + CveCorte = -1 + CveContrato = -1 + DevolucionAlmacen = 0 + CvePSAmortizacion = 0 + EraCotizacion = 0 + FacturaMateriales = 0 + CvePedidoA = 0 + EsCreaApartirDe = False + RequiereAlmacenDestino = False + RequiereAlmacenOrigen = False + TmpDTComplementos = New DataTable + DtRemConceptosSurtidos = Nothing + TipoVentaSucursal = 0 + PlazoCobranza = 0 + PlazoCobranzaRemision = 0 + TipoCambioFactura = 1 + NumeroContrato = "" + DescripcionContrato = "" + NumeroLicitacion = "" + ImprimeNombreSucursal = False + RegistraScript("SetDisabledTxtTotal(true);") + TrVistaPrevia.Visible = False + CveMetodoPagoCliente = 1 + CveAlmacenExistenciasContrato = -1 + UpFacturar.Update() + 'CargaTiposDocumentos() + TrEmitir.Visible = False + ViewState("EstablecioFolio") = False + 'ViewState("SubProyectoPorcentajeIVA") = 0 + RefacturacionGeneroNC = False + ModalidadEdicion = False + ConversionRemision = "" + TipoCambioRemision = 1 + CveOrdenCompraContrato = -1 + TieneContrato = False + AplicaNC = False + TieneAlmacen = False + CveEstatus = -1 + PorcentajeIVA = 0 + EsDiasCreditoFijo = False + DiasCredito = 0 + AplicaCancelarRemision = False + SeCancelaRemisionProceso = False + TotalOriginal = 0 + CveAlmacenDevolucion = 0 + + txtFechaICot.Text = Now.AddMonths(-3).ToShortDateString + TxtFechaIRem.Text = Now.AddMonths(-3).ToShortDateString + TxtFechaIPed.Text = Now.AddMonths(-3).ToShortDateString + TxtFechaIOC.Text = Now.AddMonths(-3).ToShortDateString + + txtFechaFCot.Text = Now.ToShortDateString + TxtFechaFRem.Text = Now.ToShortDateString + TxtFechaFPedido.Text = Now.ToShortDateString + TxtFechaFOC.Text = Now.ToShortDateString + + If UsuarioActual.TienePermisoProceso(177) Then + DdlTipoComprobante.Items.Insert(4, New ListItem("Pedido de Contrato", "Ped")) + End If + + TrSinExistencia.Visible = UsuarioActual.TienePermisoProceso(276) + + If UsuarioActual.CveEmpresa.Contiene(119, 1) Then + ImgDescPU.Visible = False + ImgDescConcepto.Visible = False + DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Autorización", "PA")) + End If + + DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Pedido", "Pd2")) + + If UsuarioActual.Empresa.Funcionalidad(528) = "1" Then 'FUNCIONALIDAD. DE REGISTRO DE CUENTA PREDIAL. + GvPS.Columns(ColumnaPredial).Visible = True + thPredial1.Visible = True + thPredial2.Visible = True + End If + + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then ' PARA BUSCAR FOLIO DE OC, YA FACTURADA EN EL CAMPO ORDEN DE COMPRA + TxtOrdenCompra.Attributes.Add("onblur", "BuscarOCRegistrada();") + End If + + If UsuarioActual.Empresa.Funcionalidad(561).ToString = "1" Then + thPoliza.Visible = True + thPoliza2.Visible = True + End If + + + DdlSATPS.setEsWebService(True) : DdlSATPS.Attributes.Add("data-metodo", "getpssat") + DivPSSAT.Visible = True + + SetValues() + CvePresupuesto = 0 + + 'MODALIDADES + If Request("Op") IsNot Nothing AndAlso Request("Op").ToString <> "" Then + Opcion = Request("Op").ToString + LblTitulo.Text = "Registro de Cotizaciones" + TrTipo.Visible = False + TabAlmacen.Visible = False + TabDetalleVentas.Visible = False + TabVentaAF.Visible = False + TabE.Visible = False + TabComplementos.Visible = False + divcondicionespago.Visible = UsuarioActual.Empresa.CvePlataforma = 1 'SI ES PLATAFORMA ERP SIEMPRE VSIBLE ESTE PORLET + ImgAntiPend.Visible = False + TrObsAlmacen.Visible = False + TrTxtObsAlmacen.Visible = False + TrPedido.Visible = False + TrOC.Visible = False + DdlTipoComprobante.SelectedValue = "Op" + Else + Opcion = "Ing" + DdlTipoComprobante.SelectedValue = "Ing" + End If + + + + 'DdlTipoComprobante.Attributes.Add("onChange", "ActivaReferencia(this)") + TxtFecha.Text = Now.ToShortDateString() + TxtFechaEjecucion.Text = Now.ToShortDateString + LblUsuario.Text = UsuarioActual.Usuario + LblFechaRegistro.Text = Now.ToShortDateString() + + TxtPrecioPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();") + TxtCantidadPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();") + ImgDescPU.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '0'; $get('LblPrecio1').style.display = ''; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") + ImgDescConcepto.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '1'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = ''; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") + ImgDescTotal.Visible = False + + ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") + ImgAntiPend.Attributes.Add("onclick", "$get('HdnTipoDescuento').value = '3'; MuestraAnticipos();") + ImgOtrosConceptos.Attributes.Add("onclick", "javascript:$('#ModalOtrosConceptos').modal();") + LkbAgregarComplementos.Attributes.Add("onclick", "javascript:$('#ModalComplementos').modal();") + 'ImgCerrar.Attributes.Add("OnClick", "$('#DivAnticipos').hide();") + 'LkbEstadodeCaja.Attributes.Add("OnClick", "MuestraEstadoCaja();") + 'LkbIngreso.Attributes.Add("OnClick", "MuestraIngresoEgreso(1);") + 'LkbRetiro.Attributes.Add("OnClick", "MuestraIngresoEgreso(0);") + TxtImporteEfectivo.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") + TxtImporteCredito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") + TxtImporteDebito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") + TxtImporteCheque.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") + TxtImporteTransferencia.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") + TxtEfectivoEnCaja.Attributes.Add("onKeyUp", "CalculaDiferencia();") + 'ImgCerrarTerminoCorte.Attributes.Add("OnClick", "$('#DivTerminarCorte').hide();") + 'ImgCerrarIE.Attributes.Add("OnClick", "$('#DivIngresoEgreso').hide();")DdlTipoComprobante + 'ImgCerrarEstadoCaja.Attributes.Add("OnClick", "$('#DivEstadoCaja').hide();") + TabAlmacen.Enabled = UsuarioActual.Empresa.UsaInventarios + TxtPorDescP.Attributes.Add("onKeyUp", "CalculaDescuento();") + TxtDescP.Attributes.Add("onKeyUp", "CalculaDescuento();") + TxtCantidadPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')") + TxtObsPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')") + TxtPrecioPyME.Attributes.Add("onkeypress", "CallServerMethod(event)") + + CreaDTmpC() + CreaDTmpF() + CreaDTDocumentosRelacionados() + CargaDdlSubProyectos() + CargaProyecto() + CargaSucursales() + + CargaClasificaciones() + CargaPS(-1, DdlPS) + CargaPSPyME(-1, DdlPSPyME) + + CreaDTVentas() + CargaMetodosPago() + 'CargaFormaPago(-1) + CargaUsoCFDI() + CargaTiposRelacion() + CargaMonedas() + CargaVendedores() + CargarAlmacenes() + CargaFormaEntrega() + CargaCuentasTerminal() + CargaDdlNCPS() + + + + 'SI USUARIO USA AMORTIZACIÓN CONTABLE, se carga las tablas para usarlas mas adelante + If UsuarioActual.Empresa.UsaAC Then + + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) + DdlTipoComprobante.Items.Add(New ListItem("Compromisos", "Com")) + DdlTipoComprobante.Items.Add(New ListItem("Orden Pago", "OP")) + + Dim AC As New ClsAC + If AC.GetPresupuestoIngresos(-1, Now.Year, True, UsuarioActual.CveEmpresa) Then + DdlFuenteRecaudacion.DataSource = AC.DtResultados() + DTPresupuestoIngresos = AC.DtResultados() + ViewState("DTFuenteRecaudacion") = AC.DtResultados() + 'GenerarPolizasAC() + End If + AC.Dispose() + 'columna de Fuente de recaudacion + GvPS.Columns(21).Visible = True + nomostrar.Visible = True + nomostrar2.Visible = True + 'GvPS.Width = 1250 + DdlFuenteRecaudacion.DataBind() + Else + TFuenteRecaudacion.Visible = False + End If + + 'Carga cliente + If Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 AndAlso Request("CveFactura") Is Nothing Then + ViewState("CveCliente") = Request("CveCliente") + HdnCveCliente.Value = Request("CveCliente") + CargaCliente(CveCliente) + VerificarContrato(True) + ElseIf Request("CveFactura") IsNot Nothing AndAlso IsNumeric(Request("CveFactura")) AndAlso Request("CveFactura").ToEntero > 0 AndAlso Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 Then + ViewState("CveCliente") = Request("CveCliente") + ViewState("CveFactura") = Request("CveFactura").ToEntero + Dim RFC As String = CargaFactura(CveFactura) + CargaCliente(CveCliente) + Else + ViewState("CveCliente") = -1 + HdnCveCliente.Value = "-1" + End If + + 'Carga empresa CRM + If Request("CveEmpresaCRM") IsNot Nothing AndAlso IsNumeric(Request("CveEmpresaCRM")) AndAlso Request("CveEmpresaCRM").ToEntero > 0 Then + ViewState("CveEmpresaCRM") = Request("CveEmpresaCRM") + CargaEmpresaCRM(CveEmpresaCRM) + Else + ViewState("CveEmpresaCRM") = -1 + End If + + If Request("CveAcercamientoCRM") IsNot Nothing AndAlso IsNumeric(Request("CveAcercamientoCRM")) AndAlso Request("CveAcercamientoCRM").ToEntero > 0 Then + ViewState("CveAcercamientoCRM") = Request("CveAcercamientoCRM") + Else + ViewState("CveAcercamientoCRM") = -1 + End If + + 'mensaje de confirmación al guardar + BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)},{If(HdnTieneAnticipos.Value = "1", 1, 0)});" + BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") + BtnEmitirImprimir.Attributes.Add("data-popout", "true") + BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") + BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") + BtnEmitirImprimir.Attributes.Add("data-html", "true") + + If UsuarioActual.CveEmpresa.Contiene(126) Then ' cuando la empresa se relaciona a ua orden de producción, Citrus Game + TrOP.Visible = True + CargaOrdenProduccion() + End If + + 'Carga Venta + If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero > 0 Then + ViewState("CveVenta") = Request("CveVenta") + If CargaVenta() Then + + 'DdlSucursal.Enabled = False + DdlSubProyectoDatos.Enabled = False + BtnEmitirImprimir.Visible = False + BtnCrearApartirDe.Visible = True + 'DdlEstatus.Enabled = True + + DivFechaAnticipoCliente.Visible = True + TxtFechaAnticipoCliente.Text = Now.ToShortDateString + + + ImgAddObs.Visible = True + CargaEventoBitacora() + + ConfiguraTipoDocto() + + TrFolioFiscal.Visible = True + + ' Si esta cancelado el compromiso/Pedido no se puede editar el estatus + 'If DdlEstatus.SelectedValue.Contiene({"9", "14", "17"}) Then + ' DdlEstatus.Enabled = False + 'End If + + 'CargaDetalle de Almacen + If Not LblAlertRefacInv.Visible Then + If CveVentaPadre > 0 Then + InventarioMov(CveVentaPadre) + Else + InventarioMov() + End If + End If + + + + + 'PERMISO PARA CANCELAR PEDIDO + If GvInv.Rows.Count = 0 Then + If DdlTipoComprobante.SelectedValue.Contiene("Ped") And Not CveEstatus = 14 Then + If UsuarioActual.TienePermisoProceso(186) Then + LBCancelarPedido.Visible = True + End If + End If + End If + + 'CARGA GV DE COMERCIO EXTERIOR SI NO ESTA TIMBRADA + If LblSeTimbro.Text = "No" Then + CargaGvComercioExterior() + End If + + 'HABILITA IMPRESION DE FORMATO CICOVISA + If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then + LnkImprimirFormatoCicovisa.Visible = True + End If + + If UsuarioActual.TienePermisoProceso(269) AndAlso Not DevolucionAlmacen = 2 Then + DivDevAlm.Visible = True + End If + + End If + Else + If Request("CveOS") IsNot Nothing AndAlso IsNumeric(Request("CveOS")) AndAlso Request("CveOS").ToEntero > 0 Then + ViewState("CveOS") = Request("CveOS") + CargaOS(CveOS) + Else + 'Modalidad Devoluciones y Refacturacion + If Request("CveDevolucion") IsNot Nothing AndAlso IsNumeric(Request("CveDevolucion")) AndAlso Request("CveDevolucion").ToEntero > 0 Then + ViewState("CveDevolucion") = Request("CveDevolucion") + ViewState("CveVenta") = Request("CveDevolucion") + ViewState("NuevaFactura") = Request("NuevaFactura") + + trNCFactura.Visible = True + DdlNCFactura.DataSource = Nothing + DdlNCFactura.DataBind() + CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString.ToEntero) + DdlNCFactura.SelectedValueExist(CveDevolucion) + + If NuevaFactura = 0 Then + LbAgregar.Visible = False + If DdlTipoComprobante.SelectedValue = "Ing" Then + DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) + DdlTipoComprobante.SelectedValue = "Dev" + ElseIf DdlTipoComprobante.SelectedValue = "Ant" Then + DdlTipoComprobante.SelectedValueExist("Egs") + End If + DdlTipoComprobante.Enabled = False + CargaFolios() + + DdlUsoCFDI.Enabled = True + DdlUsoCFDI.SelectedValueExist("2") + DdlMetodoPago33.Enabled = True + DdlMetodoPago33.SelectedValueExist("1") + DdlFormaPago33.Enabled = True + DdlFormaPago33.SelectedValueExist("20") + + End If + + If NuevaFactura = 1 Then + TrTipoRelacion.Visible = True + DdlTiposRelacion.SelectedValueExist("4") + + Dim ObjInv As New ClsInventarios + If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjInv.DtResultados.Rows.Count > 0 Then + TieneAlmacen = True + End If + End If + ObjInv.Dispose() + + End If + + CargaNuevaFactura(Nothing) + + + 'NOTA DE CREDITO + If NuevaFactura = 2 Then + DdlTipoComprobante.Items.Insert(0, New ListItem("Nota de Crédito", "Egs")) + DdlTipoComprobante.SelectedValue = "Egs" + DdlTipoComprobante.Enabled = False + CargaFolios() + + DdlUsoCFDI.Enabled = True + DdlUsoCFDI.SelectedValueExist("2") + DdlMetodoPago33.Enabled = True + DdlMetodoPago33.SelectedValueExist("1") + DdlFormaPago33.Enabled = True + DdlFormaPago33.SelectedValueExist("20") + TrTipoRelacion.Visible = True + DdlTiposRelacion.SelectedValueExist("1") + End If + + End If + + 'ENTREGA POR ADELANTADO + If DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ped", "PeC") Then + If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then + RequiereAlmacenDestino = True + + If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then + TrAlmacenAsignado.Visible = True + End If + + Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero + If CveAlmacenDestino > 0 Then + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)") + DdlAlmacenAsignado.DataBind() + DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString)) + DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString + Else + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (10)") + DdlAlmacenAsignado.DataBind() + End If + UpParametros.Update() + Else + RequiereAlmacenDestino = False + TrAlmacenAsignado.Visible = False + End If + + 'ENVIO DE FACTURA + If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then + ChkEnviarFactura.Checked = EnviarCorreoCliente + ChkEnviarFactura.Visible = True + LblEnviarMail.Visible = True + End If + End If + + 'Modalidad Contrato + If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").Contiene("0", "1") Then + TrAlmacenOrigen.Visible = False + If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then + TrAlmacenAsignado.Visible = True + + End If + UPCondicionesPago.Visible = False + RequiereAlmacenDestino = True + CveContrato = Request("CveContrato").ToEntero + TipoContrato = Request("Tipo").ToEntero + + 'DESACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto disabled") + TxtCodigo.ReadOnly = True + + CargarContratoUrl() + UpParametros.Update() + End If + + 'Modalidad CveCicloComercial + If Request("CveCicloComercial") IsNot Nothing AndAlso IsNumeric(Request("CveCicloComercial")) AndAlso Request("CveCicloComercial").ToEntero > 0 Then + ViewState("CveCicloComercial") = Request("CveCicloComercial").ToEntero + CargaCicloComercialURL() + UpParametros.Update() + End If + + 'Modalidad Devolucion Pedido **REVISAR SI SE USA + If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero > 0 AndAlso Request("CvePedido") IsNot Nothing AndAlso IsNumeric(Request("CvePedido")) AndAlso Request("CvePedido").ToEntero > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").ToEntero = 2 Then + CveContrato = Request("CveContrato").ToEntero + CvePedido = Request("CvePedido").ToEntero + TipoContrato = Request("Tipo").ToEntero + + ''REQUIERE DEVOLUCION + 'DdlDevolucionAlmacen.SelectedValue = "1" + 'DdlDevolucionAlmacen.Enabled = False + 'UpInvDev.Update() + + CargarPedidoUrl() + End If + + 'MODALIDAD DEVOLUCION PEDIDO NUEVO + If Request("DevPed") IsNot Nothing AndAlso IsNumeric(Request("DevPed")) AndAlso Request("DevPed").ToEntero > 0 AndAlso Request("MovInv") IsNot Nothing AndAlso IsNumeric(Request("MovInv")) AndAlso Request("MovInv").ToEntero > 0 Then + ViewState("CveVenta") = Request("DevPed") + ViewState("MovInv") = Request("MovInv") + ViewState("CveMovimientoDetalle") = IfNull(Request("CveMovimientoDetalle"), "-1").ToString.ToEntero + DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe")) + DdlTipoComprobante.SelectedValue = "DPe" + DdlTipoComprobante.Enabled = False + CargaFacturaDevolucionPedido() + CargaFolios() + If CveContrato > 0 Then + CargaNotificacionContrato() + End If + End If + + 'Modalidad Cotizacion + If Opcion = "Cot" Then + DdlTipoComprobante.SelectedValueExist(Opcion) + DdlTipoComprobante.Enabled = False + + DdlTipoComprobante_SelectedIndexChanged(sender, Nothing) + 'Carga CvePresupuesto + If Request("CvePresupuesto") IsNot Nothing AndAlso IsNumeric(Request("CvePresupuesto")) AndAlso Request("CvePresupuesto").ToEntero > 0 Then + CvePresupuesto = Request("CvePresupuesto").ToEntero + 'DdlEstatus.Enabled = False + End If + + End If + CargaEstatusFactura(Opcion) + + If Opcion = "Ing" Then + ObtenerFechaVencimientoCER() + 'DdlEstatus.Enabled = False + If UsuarioActual.Empresa.TipoFacturacion = "CBB" Then + 'DdlEstatus.SelectedValue = "3" + CveEstatus = 3 + ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then + 'DdlEstatus.SelectedValue = "2" + CveEstatus = 2 + End If + End If + + End If + End If + + 'CARGA PARA FACTURAR + ViewState("CveRemision") = IfNull(Request("CveRemision").ToEntero, 0) + ViewState("CveCotizacion") = IfNull(Request("CveCotizacion").ToEntero, 0) + + If ViewState("CveCotizacion").ToString.ToEntero > 0 Then + EsCreaApartirDe = True + End If + + If ViewState("CveRemision").ToString.ToEntero > 0 Or ViewState("CveCotizacion").ToString.ToEntero > 0 Then + 'ViewState("CveRemision") = Request("CveRemision") + 'Dim CveRemision As Integer = ViewState("CveRemision").ToString.ToEntero + + CargaVenta() + + 'DdlSucursal.Enabled = False + BtnCrearApartirDe.Visible = True + 'DdlEstatus.Enabled = True + + ImgAddObs.Visible = True + CargaEventoBitacora() + + DdlTipoComprobante.Enabled = False + DdlTipoComprobante.SelectedValue = "Ing" + + CargaEstatusFactura() + 'DdlEstatus.SelectedValueExist("2") + + ConfiguraTipoDocto() + CargaFolios() + + BtnEmitirImprimir.Text = "Facturar" + BtnEmitirImprimir.Visible = True + + UpnTools.Update() + + TxtFecha.Text = Now.ToShortDateString + + '' Si esta cancelado el compromiso no se puede editar el estatus + 'If DdlEstatus.SelectedValue = "9" Then + ' DdlEstatus.Enabled = False + 'End If + + 'CargaDetalle de Almacen + InventarioMov() + End If + + If Not ExFolioFactura Then SetPermisos() + + 'SELECCIONA VENDEDOR DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE + If UsuarioActual.CveVendedor > 0 Then + If CveVenta = -1 AndAlso Not DdlVendedor.SelectedValue.ToEntero > 0 Then DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) + If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then + DdlVendedor.Enabled = False + End If + 'multiples vendedores visible + If UsuarioActual.TienePermisoProceso(153) Then + DdlVendedor.Enabled = True + End If + End If + + If UsuarioActual.Empresa.Funcionalidad(301).ToEntero > 0 Then + TxtFecha.Enabled = False + ImgFecha.Visible = False + End If + + CargarCodigo() + InicializaImprimirNew() + + 'RegistraScript("FnSuma()") + TxtSubTotal.Attributes.Add("onKeyUp", "FnSuma()") + TxtIVA.Attributes.Add("onKeyUp", "FnSuma()") + TxtIEPS.Attributes.Add("onKeyUp", "FnSuma()") + TxtRetIVA.Attributes.Add("onKeyUp", "FnSuma()") + TxtRetISR.Attributes.Add("onKeyUp", "FnSuma()") + + 'Permitir Edicion de Iva + If UsuarioActual.Empresa.Funcionalidad(509) = "1" Then + TxtIVA.Enabled = True + 'TxtTotal.Enabled = True + RegistraScript("SetDisabledTxtTotal(false);") + TxtSubTotal.Enabled = True + TxtSubTotal2.Enabled = True + End If + + 'Cortes de Caja + If UsuarioActual.TienePermisoProceso(160) Then + CargaCorteCaja() + End If + '********************************** + + 'Complementos de Timbrado + Dim ObjVenta As New ClsVentas + If ObjVenta.GetVentaComplementos() Then + RblComplementos.DataSource = ObjVenta.DtResultados + RblComplementos.DataBind() + UpComplementos.Update() + End If + ObjVenta.Dispose() + + CargaFormatoSucursal() + + InicializaDevolucionAlmacen() + CargaOtrosConceptos() + CargaFacturaOC() + + 'SELECCIONA SUCURSAL DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE + If Not (CveCliente > 0 Or CveVenta > 0) Then + DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto) + DdlSubProyectoEjecucion.SelectedValueExist(UsuarioActual.CveSubProyecto) + DdlSubProyectoCobranza.SelectedValueExist(UsuarioActual.CveSubProyecto) + If UsuarioActual.TienePermisoProceso(152) Then + DdlSubProyectoDatos.Enabled = False + End If + CambiaSucursal() + UpParametros.Update() + UpDetalle.Update() + End If + + 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE + EnviarCorreoCliente = True + If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then + ChkEnviarFactura.Checked = False + ChkEnviarFactura.Visible = False + LblEnviarMail.Visible = False + Else + ChkEnviarFactura.Checked = EnviarCorreoCliente + ChkEnviarFactura.Visible = True + LblEnviarMail.Visible = True + End If + + CargaFletes() + + If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then + DdlProyecto.Visible = False + BrSubProyecto.Visible = False + DdlProyectoPyME.Visible = False + LblProyectoHeader.Text = "Sucursal" + LblSubProyecto.Text = "" + divProyectoPyME.Visible = False + LblSubProyectoPyME.InnerText = "Sucursal" + + DdlSubProyecto.Items.Clear() + DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) + DdlSubProyecto.DataBind() + DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + DdlSubProyectoPyME.Items.Clear() + DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + 'DdlSubProyectoPyME.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) + DdlSubProyectoPyME.DataBind() + DdlSubProyectoPyME.Items.Insert(0, New ListItem("Seleccione", "-1")) + + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then + DdlProyecto.Visible = False + BrSubProyecto.Visible = False + DdlProyectoPyME.Visible = False + LblProyectoHeader.Text = "Proyecto" + LblSubProyecto.Text = "" + divProyectoPyME.Visible = False + LblSubProyectoPyME.InnerText = "Proyecto" + + DdlSubProyecto.Items.Clear() + DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) + DdlSubProyecto.DataBind() + DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + + DdlSubProyectoPyME.Items.Clear() + DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + 'DdlSubProyectoPyME.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) + DdlSubProyectoPyME.DataBind() + DdlSubProyectoPyME.Items.Insert(0, New ListItem("Seleccione", "-1")) + + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then + LblProyectoHeader.Text = "Sucursal" + LblSubProyecto.Text = "Proyecto" + + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then + LblProyectoHeader.Text = "Proyecto" + LblSubProyecto.Text = "Sucursal" + + End If + + If UsuarioActual.Empresa.CvePlataforma = 2 Then + ImgOtrosConceptos.Visible = False + TrFormaEntrega.Visible = False + TabDetalleVentas.Visible = False + TabE.Visible = False + LnkOCs.Visible = False + GvPS.Columns(8).Visible = False + TrEdit.Visible = False + ThProyecto.Visible = False + For Each Gvr As GridViewRow In GvPS.Rows + Gvr.FCLinkButton("imgE").Visible = False + Gvr.FCLinkButton("imgEPyME").Visible = True + Next + LnkAddVenta.Visible = True + divproyectos.Visible = False + End If + + TabVentaAF.Visible = False + + 'CARGA VALORES INICIALES PARA AGREGAR PS DESDE MODAL + CargaMetodosPSModal() + + 'CARGA VALORES DE ORDEN DE PRODUCCION + Dim CveOrdenProduccion = IfNull(Request("CveOrdenProduccion"), "-1").ToString.ToEntero + If CveOrdenProduccion > 0 And Not CveVenta > 0 Then + DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion) + If DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then + DdlTipoComprobante.SelectedValue = "Rem" + DdlMoneda.SelectedValue = "2" + Dim ObjCGame As New ClsCGame + If ObjCGame.GetAvance(DdlOrdenProduccion.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then + For Each dt As DataRow In ObjCGame.DtResultados.Rows + If dt("Avance").ToString.ToEntero > 0 Then + AgregarProductoServicio(dt("Avance").ToString.ToDecimal, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString, dt("PU").ToString.ToDecimal, 0, + DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text) + 'AddPS(dt("Avance").ToString.ToDouble, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString, dt("PU").ToString.ToDouble, 0, 0, 0, 1, 0, True, + ' "", DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, 2, HdnTipoInv.Value.ToEntero) + End If + Next + GvPS.DataSource = TmpDT + End If + If ObjCGame.GetFlete(UsuarioActual.CveEmpresa) Then + TxtObsFact.Text = String.Format("Chofer: {0}; Remolque: {1}; Scat: {2};", ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Chofer"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("CodigoDescripcionRemolque"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Scat")) + End If + ObjCGame.Dispose() + GvPS.DataBind() + UPObservaciones.Update() + UpPS.Update() + CargaFolios() + End If + End If + + + If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero = -1 AndAlso UsuarioActual.CveTipoDocumento.Length = 3 Then + CargaDdlSubProyectos() + UpParametros.Update() + DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento) + CambiaTipoDocto() + LimpiaEscondeContado() + End If + + InicializaAplicarNC() + + If CveCliente > 0 Then + CargaRestriccionesCreditoCliente() + End If + + If Not CveVenta > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(403).ToString = "1" Then + If (DdlTipoComprobante.Items.FindByValue("Ing") IsNot Nothing) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) + End If + End If + + End If + + ''EN REALIDAD SE OCUPAN ESTAS COSAS DENTRO DEL POSTABCK ??? + If Not CveVenta > 0 Then + 'LbDescargarExcel.Visible = True + HlAgregarExcel.Visible = True + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then + ' IPP 15 Julio 2017 - ERA FALSE + ImgAntiPend.Visible = False + UpPS.Update() + End If + + If UsuarioActual.Empresa.Funcionalidad(517) <> "" Then + TxtFolio.Enabled = False + TxtFecha.Enabled = False + If LblSeTimbro.Text = "No" And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev", "Ant") Then + TxtFecha.Text = Now.ToShortDateString + End If + ImgFecha.Visible = False + End If + + 'condición temporal por implementación JAM. usuario FernandaRomo + If UsuarioActual.CveUsuario.Contiene(11703, 1719) Then + TxtFecha.Enabled = True + ImgFecha.Visible = True + End If End Sub -#Region "Punto Venta" - Private Sub CargaCorteCaja() - 'Checar si hay un Turno Abierto - Dim ObjPVenta As New ClsPuntoVenta - - If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then - - If ObjPVenta.DtResultados.Rows.Count > 0 Then - CveCorte = ObjPVenta.CveCorte - LblEstatusCaja.Text = ObjPVenta.FechaInicial.ToShortDateString - TrEstatusCaja.Visible = True - BtnIniciarTurno.Visible = False - LkbEstadodeCaja.Visible = True - LkbIngreso.Visible = True - LkbRetiro.Visible = True - Else - 'Ingresar un nuevo Turno - RegistraScript("window.onload = function MuestraCorteCaja() { document.getElementById(""C_btnShow"").click(); }") - End If - End If - ObjPVenta.Dispose() - End Sub - Private Sub BtnIniciarTurno_Click(sender As Object, e As EventArgs) Handles BtnIniciarTurno.Click - Dim ObjPVenta As New ClsPuntoVenta - - ObjPVenta.AddVtaCortes(Now, TxtDineroCaja.Text.ToDecimal, UsuarioActual.CveUsuario, TxtDescripcionCaja.Text, UsuarioActual.CveEmpresa) - CveCorte = ObjPVenta.CveCorte - LblEstatusCaja.Text = Now.ToShortDateString - TrEstatusCaja.Visible = True - LkbEstadodeCaja.Visible = True - LkbIngreso.Visible = True - LkbRetiro.Visible = True - BtnIniciarTurno.Visible = False - - ObjPVenta.Dispose() - - RegistraScript("$('#DivCorteDeCaja').hide();") - End Sub - Private Sub LkbEstadodeCaja_Click(sender As Object, e As EventArgs) Handles LkbEstadodeCaja.Click - CargaDatosCorte() - CargaVentasPago() - CargaEntradasSalidas() - RegistraScript("$('#DivEstadoCaja').modal()") - End Sub - Private Sub CargaDatosCorte() - Dim ObjPVenta As New ClsPuntoVenta - Dim Total As Double - - If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then - If ObjPVenta.DtResultados.Rows.Count > 0 Then - - Total = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble + ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble + ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble + ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble - ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble - DineroCaja = Total - LblEfectivoEsperado.Text = Total.FormatoNumero(2) - - Dim Dt As New DataTable - - Dt.Columns.Add("Descripcion", GetType(String)) - Dt.Columns.Add("Importe", GetType(Decimal)) - - Dim Dr1 = Dt.NewRow - Dr1("Descripcion") = "Fondo de Caja" - Dr1("Importe") = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble - Dt.Rows.Add(Dr1) - - Dim Dr2 = Dt.NewRow - Dr2("Descripcion") = "Ventas en Efectivo" - Dr2("Importe") = ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble - Dt.Rows.Add(Dr2) - - Dim Dr3 = Dt.NewRow - Dr3("Descripcion") = "Propinas" - Dr3("Importe") = ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble - Dt.Rows.Add(Dr3) - - Dim Dr4 = Dt.NewRow - Dr4("Descripcion") = "Entradas" - Dr4("Importe") = ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble - Dt.Rows.Add(Dr4) - - Dim Dr5 = Dt.NewRow - Dr5("Descripcion") = "Salidas" - Dr5("Importe") = ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble - Dt.Rows.Add(Dr5) - - Dim Dr6 = Dt.NewRow - Dr6("Descripcion") = "Total" - Dr6("Importe") = Total - Dt.Rows.Add(Dr6) - - GvDineroCaja.DataSource = Dt - GvDineroCaja.DataBind() - UpDineroCaja.Update() - UpTerminarCorte.Update() - - End If - End If - - ObjPVenta.Dispose() - - End Sub - Private Sub CargaVentasPago() - Dim ObjPVenta As New ClsPuntoVenta - - If ObjPVenta.GetVta_MetodosPago(CveCorte) Then - If ObjPVenta.DtResultados.Rows.Count > 0 Then - GvMetodosPago.DataSource = ObjPVenta.DtResultados - GvMetodosPago.DataBind() - UpMetodosPago.Update() - End If - End If - - ObjPVenta.Dispose() - End Sub - Private Sub CargaEntradasSalidas() - Dim ObjPVenta As New ClsPuntoVenta - - 'Salida - If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 0) Then - If ObjPVenta.DtResultados.Rows.Count > 0 Then - GvEgresos.DataSource = ObjPVenta.DtResultados - GvEgresos.DataBind() - UpEgresos.Update() - End If - End If - - 'Entrada - If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 1) Then - If ObjPVenta.DtResultados.Rows.Count > 0 Then - GvIngresos.DataSource = ObjPVenta.DtResultados - GvIngresos.DataBind() - UpIngresos.Update() - End If - End If - - ObjPVenta.Dispose() - End Sub - Private Sub BtnAceptarIE_Click(sender As Object, e As EventArgs) Handles BtnAceptarIE.Click - Dim ObjPVenta As New ClsPuntoVenta - If TxtCantidadIE.Text.ToEntero > 0 Then - If ObjPVenta.AddVta_MovimientosCajas(CveCorte, UsuarioActual.CveUsuario, TxtCantidadIE.Text.ToDouble, TxtDescripcionIE.Text, HdnTipoMovimiento.Value.ToEntero, Now) Then - TxtCantidadIE.Text = "" - TxtDescripcionIE.Text = "" - RegistraScript("$('#DivIngresoEgreso').modal('hide')", "divingresoegreso") - Alert("El movimiento se realizó correctamente") - UpIngresoEgreso.Update() - End If - End If - ObjPVenta.Dispose() - End Sub - Private Sub BtnCerrarTurno_Click(sender As Object, e As EventArgs) Handles BtnCerrarTurno.Click - Dim ObjPVenta As New ClsPuntoVenta - If TxtEfectivoEnCaja.Text.Trim <> "" Then - If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoEnCaja.Text.ToDouble, LblDiferenciaCaja.Text.ToDouble, Now, UsuarioActual.CveEmpresa) Then - RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=CORT&CVECORTE={0}&FORMATO={1}", CveCorte, "PDF"))}'", "Imprimir") - Dim Liga = "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";" - Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga) - End If - End If - ObjPVenta.Dispose() - End Sub - Private Sub BtnCancelar_Click(sender As Object, e As EventArgs) Handles BtnCancelar.Click - Response.Redirect("~/Inicio.aspx") - End Sub - - Protected Sub BtnCerrarCaja_Click(sender As Object, e As EventArgs) - RegistraScript("$('#DivEstadoCaja').modal('hide')") - RegistraScript("$('#DivTerminarCorte').modal()", "divterminarcorte") - End Sub - Protected Sub LkbIngreso_Click(sender As Object, e As EventArgs) - CargaIngresoEgreso(1) - End Sub - Public Sub CargaIngresoEgreso(Opcion As Integer) - RegistraScript("$('#DivIngresoEgreso').modal()") - If Opcion = 1 Then - LblTituloIE.Text = "Ingreso de Efectivo: " - HdnTipoMovimiento.Value = "1" - ElseIf Opcion = 0 Then - LblTituloIE.Text = "Retiro de Efectivo: " - HdnTipoMovimiento.Value = "0" - End If - UpIngresoEgreso.Update() - End Sub - Protected Sub LkbRetiro_Click(sender As Object, e As EventArgs) - CargaIngresoEgreso(0) + Private Sub ConfiguraEmpresa() + Select Case UsuarioActual.CveEmpresa + Case 119 + TxtObsPS.Attributes.Add("onkeypress", "setFocus(event,'TxtPrecio');") + End Select End Sub -#End Region -#Region "Contratos" - Private Sub PresionarBotonModal(Boton As String) - Try - Dim script As String = $"document.getElementById(""{Boton}"").click();" - Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.Handler, Page) - ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), Boton, script, True) - Pag = Nothing - Catch ex As Exception - End Try - End Sub - Private Sub VerificarContrato(Optional AfterPageLoad As Boolean = False) - Dim ObjContratos As New ClsContratos - - If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then - If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then - - DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'") - - If AfterPageLoad Then - RegistraScript("window.onload = function MuestraContratos() { document.getElementById(""C_BtnMostrarContrato"").click(); }") - Else - PresionarBotonModal("C_BtnMostrarContrato") - End If - - End If - End If - - ObjContratos.Dispose() - End Sub - Private Sub BtnIniciarContrato_Click(sender As Object, e As EventArgs) Handles BtnIniciarContrato.Click - DdlContratosModal.Items.Clear() - - If RblOpcionContrato.SelectedValue = "2" Then - ContratoDetalles.Visible = True - DivEstimaciones.Visible = False - - DdlContratosModal.DataSource = DtContratos - DdlContratosModal.DataBind() - DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) - - DdlContratosOC.Items.Clear() - DdlContratosOC.DataSource = DtContratos - DdlContratosOC.DataBind() - 'DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) - UPEstimaciones.Update() - - Tab.ActiveTab = TabE - TabGenerales.Enabled = False - Updatetabs.Update() - - 'ESCONDE ACCIONES - LnkRemisiones.Visible = False - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - HlAgregarExcel.Visible = False - - 'VINCULARA LAS OC QUE TENGAN CONTRATO SOLAMENTE - TieneContrato = True - LnkOCs.Visible = True - UpnTools.Update() - Else - DdlContratosOC.Items.Clear() - DdlContratosOC.DataSource = DtContratos - DdlContratosOC.DataBind() - DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) - - GvContratoDetalles.DataSource = Nothing - GvContratoDetalles.DataBind() - UpContratos.Update() - - DivEstimaciones.Visible = True - ContratoDetalles.Visible = False - UPEstimaciones.Update() - - Tab.ActiveTab = TabGenerales - TabGenerales.Enabled = True - Updatetabs.Update() - TieneContrato = False - - End If - - PresionarBotonModal("C_BtnCerrarContrato") - End Sub - Private Sub BtnCancelarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCancelarContratoDetalles.Click - DtContratos = Nothing - PresionarBotonModal("C_BtnCerrarContrato") - End Sub - Private Sub DdlContratosModal_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosModal.SelectedIndexChanged - DdlContratoModalSelectIndex() - End Sub - Protected Sub RBLTipoContrato_SelectedIndexChanged(sender As Object, e As EventArgs) - CargaContratos() - End Sub - Private Sub CargaContratos() - - Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}") - If DrContrato Is Nothing Then - Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError) - Exit Sub - End If - - LbContratoImporteTotal.Text = DrContrato("ImporteTotal").ToString.FormatoNumero - LbContratoImporteMinimo.Text = DrContrato("ImporteMin").ToString.FormatoNumero - LbContratoImporteMaximo.Text = DrContrato("ImporteMax").ToString.FormatoNumero - LtContratoImporteSaldo.Text = DrContrato("ImporteSaldo").ToString.FormatoNumero - - - Dim ObjContrato As New ClsContratos - Dim NoId As Integer = 0 - - If ObjContrato.GetContratosDetalle(DdlContratosModal.SelectedValue.ToEntero) Then - - 'SI ES CONTRATO DE CONSIGNACION DE VENTA AGARRA LAS EXISTENCIAS DEL ALMACEN - CreaConsignacionSerieDetalle() - CveAlmacenExistenciasContrato = -1 - CveAlmacenOrigenContrato = -1 - GvContratoDetalles.Columns(8).Visible = False - - If DrContrato("CveContratoTipo").ToString.Contiene("27") Then - CveAlmacenExistenciasContrato = If(DrContrato("CveAlmacenDestino").ToString.ToEntero > 0, DrContrato("CveAlmacenDestino").ToString.ToEntero, -1) - CveAlmacenOrigenContrato = If(DrContrato("CveAlmacenOrigen").ToString.ToEntero > 0, DrContrato("CveAlmacenOrigen").ToString.ToEntero, -1) - End If - - NoId = ObjContrato.DtResultados.FiltraParametros("NoIdentificacion <> ''").Rows.Count 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA - - Dim DtDetalle As DataTable = ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}") - - GvContratoDetalles.DataSource = DtDetalle 'ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}") - GvContratoDetalles.DataBind() - UpContratos.Update() - - NumeroContrato = DrContrato("NumeroContrato").ToString - DescripcionContrato = DrContrato("DescripcionContrato").ToString - NumeroLicitacion = DrContrato("NumeroLicitacion").ToString.Trim - DdlVendedor.SelectedValueExist(DrContrato("CveVendedor")) - - If DrContrato("CveSucursalCliente").ToString.ToEntero > 0 Then - DdlSucursalCliente.SelectedValueExist(DrContrato("CveSucursalCliente")) - End If - - Dim CveAlmacenDestino As Integer = DrContrato("CveAlmacenDestino").ToString.ToEntero - - If CveAlmacenDestino > 0 Then - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen IN (4, 10)") - DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlAlmacenAsignado.Items.Insert(1, New ListItem(DrContrato("Almacen").ToString, CveAlmacenDestino.ToString)) - DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString) - DdlAlmacenAsignado.DataBind() - Else - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)") - DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString) - DdlAlmacenAsignado.DataBind() - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}") - DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString) - DdlAlmacenAsignado.DataBind() - End If - - UpParametros.Update() - End If - - If NoId > 0 Then 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA - GvContratoDetalles.Columns(3).Visible = True 'NoIdentificacion - End If - - ObjContrato.Dispose() - - If CveOC > 0 Then - BtnCargarContratoDetalles.Enabled = True - For Each gvr As GridViewRow In GvContratoDetalles.Rows - gvr.FCTextBox("TxtCant").Enabled = False - Next - Dim EsValido = True - For Each Dr As DataRow In TmpDT.Rows - Dim CantidadActual = Dr("Cantidad").ToString.ToDouble - Dim CantidadDispo = 0.0 - Dim CantidadAsignada = 0.0 - For Each gvr As GridViewRow In GvContratoDetalles.Rows - If gvr.DataKey("CvePS").ToEntero = Dr("CvePS").ToString.ToEntero Then - CantidadDispo = gvr.DataKey("Cantidad").ToString.ToDouble - gvr.FCTextBox("TxtCant").Text.ToDouble - If CantidadDispo = 0 Then Continue For - CantidadAsignada = If(CantidadDispo > CantidadActual, CantidadActual, CantidadDispo) - gvr.FCTextBox("TxtCant").Text = (gvr.FCTextBox("TxtCant").Text.ToDouble + CantidadAsignada).ToString - CantidadActual = CantidadActual - CantidadAsignada - - If CantidadActual = 0 Then - Exit For - End If - - End If - Next - If CantidadActual > 0 Then - EsValido = False - Alert("No se cumple con la totalidad de la Orden de Compra. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - BtnCargarContratoDetalles.Enabled = False - Exit For - End If - Next - - If EsValido Then - BtnCargarContratoDetalles_Click(BtnCargarContratoDetalles, EventArgs.Empty) - End If - - End If - - 'LIMPIA TIPOS DOCTO - If (DdlTipoComprobante.Items.FindByValue("Ped") IsNot Nothing) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ped")) - End If - - If (DdlTipoComprobante.Items.FindByValue("PeC") IsNot Nothing) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PeC")) - End If - - If (DdlTipoComprobante.Items.FindByValue("Cot") IsNot Nothing) Then 'NO PUEDEN HACER COTIZACIÓN DE UN CONTRATO - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) - End If - - Select Case RBLTipoContrato.SelectedValue.ToEntero - Case 1 - DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) - DdlTipoComprobante.SelectedValue = "Ped" - DdlTipoComprobante.Enabled = False - Case 2 - DdlTipoComprobante.Enabled = True - DdlTipoComprobante.SelectedValueExist("Ing") - Case 3 - DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido de Consignación", "PeC")) - DdlTipoComprobante.SelectedValue = "PeC" - DdlTipoComprobante.Enabled = False - End Select - - ChkPSOC.Checked = False - CambiaTipoDocto() - UpParametros.Update() - UPEstimaciones.Update() - UPOCFactura.Update() - End Sub - Private Sub BtnCargarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCargarContratoDetalles.Click - - ''SI LA VENTA ES TIPO VENTA DE CONTRATO Y EL CONTRATO TIENE LICITACION EL CLIENTE DEBE TENER IMPUESTOS LOCALES - 'If RBLTipoContrato.SelectedValue = "2" Then - ' Dim ObjClientes As New ClsClientes - ' If NumeroLicitacion <> "" Then - ' If ObjClientes.GetClienteImpuestosLocales(CveCliente) Then - ' If Not ObjClientes.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then - ' Alert("El contrato con licitación al que se hace referencia requiere impuestos locales.", TipoMensaje.MsgAdvertencia) - ' ObjClientes.Dispose() - ' Exit Sub - ' End If - ' End If - ' End If - ' ObjClientes.Dispose() - 'End If - - - Dim DrContrato As DataRow = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue.ToEntero}") - Dim ps As New ClsInventarios - - CveContrato = DdlContratosModal.SelectedValue.ToEntero - AplicaGastoContrato = If(DrContrato("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento - - 'VALIDA IMPORTE DEL CONTRATO - Dim SeleccionadoContrato = 0.0 '(From row As GridViewRow In GvContratoDetalles.Rows.Cast(Of GridViewRow)() Select row.FCLabel("LtlTotal").Text.ToDecimal).Sum - - TmpDT.Clear() - TxtSubTotal.Text = "0" - LblDescuentos.Text = "0" - TxtIVA.Text = "0" - TxtRetIVA.Text = "0" - - For Each Row As GridViewRow In GvContratoDetalles.Rows - If Row.FCTextBox("TxtCant").Text.ToEntero > 0 Then - - 'VALIDA EXISTENCIAS DE ALMACÉN - 'Dim DrPS = GlobalDTProductosServicios(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero).FiltroPrimero("") - Dim DrPS = GlobalDTPS(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero).FiltroPrimero("") - - If DrPS IsNot Nothing Then - Dim CveTipoPS As Integer = DrPS("CveTipoPS").ToString.ToEntero - Dim CveTipoInv As Integer = DrPS("Inv_CveMetodoInventario").ToString.ToEntero - Dim existencia As Decimal = ps.GetExistenciasPS(Row.DataKey("CvePS").ToEntero, Row.DataKey("CveUM").ToEntero, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) - If (existencia < Row.FCTextBox("TxtCant").Text.ToEntero AndAlso CveTipoPS <> 1) AndAlso UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ped") Then ' And DdlContratosModal.SelectedValue.ToEntero <> 196 Then - Alert("No cuenta con la cantidad suficiente en inventario para el producto:
    " + Row.FCLiteral("LtlPS").Text + ".", TipoMensaje.MsgAdvertencia) - TmpDT.Clear() - GvPS.DataSource = Nothing - GvPS.DataBind() - UpPS.Update() - Exit Sub - Else - SeleccionadoContrato += Row.FCTextBox("TxtCant").Text.ToEntero * Row.FCLiteral("LtlPU").Text.ToDouble - AgregarProductoServicio(Row.FCTextBox("TxtCant").Text.ToEntero, Row.DataKey("CveUM").ToEntero, Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero, - Row.DataKey("Clasificacion"), Row.DataKey("CvePS").ToEntero, Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, Row.DataKey("Observaciones"), $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDecimal, 0, - DrContrato("CveProyecto").ToString.ToEntero, DrContrato("ProyectoContrato").ToString, DrContrato("CveSubProyecto").ToString.ToEntero, DrContrato("SubProyectoContrato").ToString, CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero) - 'AddPS(Row.FCTextBox("TxtCant").Text.ToEntero, Row.DataKey("CveUM").ToEntero, Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero, Row.DataKey("Clasificacion"), - ' Row.DataKey("CvePS").ToEntero, Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, Row.DataKey("Observaciones"), $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDouble, If(Row.DataKey("IVA").ToDouble = -1, ViewState("IVA").ToString.ToDouble, Row.DataKey("IVA").ToDouble), 0, 0, 1, 0, True, "", - ' DrContrato("CveProyecto").ToString.ToEntero, DrContrato("ProyectoContrato").ToString, DrContrato("CveSubProyecto").ToString.ToEntero, DrContrato("SubProyectoContrato").ToString, CveTipoPS, CveTipoInv, CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero, CodigoPS:=Row.FCLiteral("LtlPS").Text) - End If - Else - Alert("El producto presenta una inconsistencia en su información", TipoMensaje.MsgError) - TmpDT.Clear() - GvPS.DataSource = Nothing - GvPS.DataBind() - UpPS.Update() - Exit Sub - End If - - - End If - Next - - 'SI EL CONTRATO TIENE IMPUESTOS LOCALES SE CARGAN LOS DEL CONTRATO AHUEVO - If RBLTipoContrato.SelectedValue = "2" Then - Dim ObjContratos As New ClsContratos - If ObjContratos.GetContratoImpuestosLocales(CveContrato, UsuarioActual.CveEmpresa) Then - If ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then - - Dim DtContratoImpuesto As DataTable = ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") - - If DtContratoImpuesto IsNot Nothing AndAlso DtContratoImpuesto.Rows.Count > 0 Then - - ' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear() - TmpDTImpuestos = DtContratoImpuesto - - GvImpuestosLocales2.DataSource = TmpDTImpuestos - GvImpuestosLocales2.DataBind() - - If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then - TrOtros.Visible = True - GvImpuestosLocales2.Visible = True - TrOtros.Style.Add("display", "") - Else - TrOtros.Visible = False - GvImpuestosLocales2.Visible = False - End If - DtContratoImpuesto.Dispose() - End If - UpImpuestos.Update() - End If - End If - ObjContratos.Dispose() - End If - - If Not CveCicloComercial > 0 Then - 'SI EL IMPORTE MAX O EL IMPORTE FIJO DEL CONTRATO FLEXIBLE ES CERO, NO HAY LIMITE - If Not (DrContrato("Importe").ToString.ToDouble = 0 And DrContrato("ImporteMax").ToString.ToDouble = 0) Then - If DdlTipoComprobante.SelectedValue = "Ing" And (DrContrato("ModalidadDetalle").ToString = "1" Or DrContrato("ImporteMax").ToString.ToDouble > 0) AndAlso (DrContrato("ImporteTotal").ToString.ToDouble - DrContrato("Avance").ToString.ToDouble) < (SeleccionadoContrato) Then - Alert("Se excede el importe límite del contrato. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - TmpDT.Clear() - GvPS.DataSource = Nothing - GvPS.DataBind() - UpPS.Update() - Exit Sub - End If - End If - End If - - CalculaTotalesVenta() - LbAgregar.Visible = False - UpPS.Update() - - 'restricciones para evitar cambios una vez seleccionado el contrato - If BtnEmitirImprimir.Visible = False Then BtnEmitirImprimir.Visible = True : TrVistaPrevia.Visible = True - - 'DESACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto disabled") - TxtCodigo.ReadOnly = True - - Tab.ActiveTab = TabGenerales - TabGenerales.Enabled = True - Updatetabs.Update() - - PresionarBotonModal("C_BtnCerrarContrato") - - ps.Dispose() - UpFacturar.Update() - End Sub - Private Sub CargarContratoUrl() - Dim ObjContratos As New ClsContratos - - If ObjContratos.GetContratos(CveContrato, UsuarioActual.CveEmpresa, -1, -1, 1) Then - If ObjContratos.DtResultados.Rows.Count > 0 Then - - 'Cargamos los datos del Cliente - DtContratos = ObjContratos.DtResultados - ViewState("CveCliente") = ObjContratos.DtResultados(0)("CveCliente").ToString.ToEntero - CorreoNotificacionPedDev = ObjContratos.DtResultados(0)("CorreoNotificacionPedDev").ToString - HdnCveCliente.Value = ObjContratos.DtResultados(0)("CveCliente").ToString - CargaCliente(CveCliente) - DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) - DdlTipoComprobante.SelectedValue = "Ped" - DdlTipoComprobante.Enabled = False - DdlAlmacenAsignado.Enabled = False - DdlSubProyectoDatos.SelectedValueExist(ObjContratos.DtResultados(0)("CveSubProyecto")) - - AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento - - If TipoContrato = 1 Then - 'Cargamos los datos del Contrato - RblOpcionContrato.SelectedValue = "2" - BtnIniciarContrato_Click(Nothing, Nothing) - DdlContratosModal.SelectedValue = CveContrato.ToString - DdlContratosModal_SelectedIndexChanged(Nothing, Nothing) - ElseIf TipoContrato = 0 Then - 'Mostramos los almacenes - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} {If(DdlTipoComprobante.SelectedValue = "Ped", "", "AND CveTipoAlmacen IN (4,10)")}") - DdlAlmacenAsignado.DataBind() - DdlAlmacenAsignado.Enabled = True - TrAlmacenAsignado.Visible = True - TrTipoPedido.Visible = True - TrObs.InnerText = "No. Serie" - SpObs.InnerText = "Contrato" - TrObsGenerales.InnerText = "Número de Contrato " - UpParametros.Update() - End If - - If ObjContratos.CveAlmacen > 0 Then - If (DdlAlmacenAsignado.Items.FindByValue(ObjContratos.CveAlmacen.ToString) Is Nothing) Then - Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacen.ToString)) - If dr IsNot Nothing Then - DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString)) - End If - End If - DdlAlmacenAsignado.SelectedValue = ObjContratos.CveAlmacen.ToString - DdlAlmacenAsignado.Enabled = False - Else - If (DdlAlmacenAsignado.Items.FindByValue("89") Is Nothing) Then - Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", "89")) - If dr IsNot Nothing Then - DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString)) ' lo genera Obj.SelectedValue = Valor.ToString - DdlAlmacenAsignado.Enabled = False - End If - End If - DdlAlmacenAsignado.SelectedValue = "89" - End If - - If ObjContratos.CveAlmacenOrigen > 0 AndAlso TipoContrato = 0 Then - DdlAlmacenOrigen.Visible = True - RequiereAlmacenOrigen = True - If (DdlAlmacenOrigen.Items.FindByValue(ObjContratos.CveAlmacenOrigen.ToString) Is Nothing) Then - Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacenOrigen.ToString)) - If dr IsNot Nothing Then - DdlAlmacenOrigen.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString)) - End If - End If - DdlAlmacenOrigen.SelectedValue = ObjContratos.CveAlmacenOrigen.ToString - DdlAlmacenOrigen.Enabled = False - End If - - Else - Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) - End If - Else - Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) - End If - - ObjContratos.Dispose() - End Sub - Private Sub CargarPedidoUrl() - - CargaVenta() - CargaFolios() - - TrAlmacenOrigen.Visible = True - TrAlmacenAsignado.Visible = True - RequiereAlmacenDestino = True - - BtnEmitirImprimir.Text = "Devolver Pedido" - BtnEmitirImprimir.Visible = True - - DdlAlmacenAsignado.DataBind() - DdlAlmacenAsignado.Items.Insert(0, New ListItem("Productos Financieros Como Dato", "89")) - DdlAlmacenAsignado.Enabled = False - - UpParametros.Update() - UpFacturar.Update() - - End Sub - Private Sub GuardarContratoAvanceEstimaciones(ObjContrato As ClsContratos, factura As Modelos.Factura, ErrorList As List(Of String), Multiplicador As Integer, Optional CrearAvance As Boolean = False) - - If (factura.CveContrato > 0 AndAlso ((DdlContratosModal.Items.Count > 0 AndAlso factura.CveContrato = DdlContratosModal.SelectedValue.ToEntero) OrElse DdlFiltroContrato.SelectedValue.ToEntero > 0 OrElse CrearAvance)) Or ContratoOC Then - - Dim CveEstimacion As Integer = -1 - - If ObjContrato.AddEstimaciones(factura.CveContrato, factura.Fecha, -1, factura.CveVenta, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then - CveEstimacion = ObjContrato.DtResultados(0)("CveEstimacion").ToString.ToEntero - - For Each row As DataRow In TmpDT.Rows - If row("CveContratoDetalle").ToString.ToEntero > 0 Then - If Not ObjContrato.AddContratosAvance(row("CveContratoDetalle").ToString.ToEntero, row("Cantidad").ToString.ToEntero * Multiplicador, factura.Fecha, UsuarioActual.CveUsuario, CveEstimacion:=CveEstimacion) Then - ErrorList.Add("Ocurrió un error al agregar los avances") - End If - End If - Next - - Else - ErrorList.Add("Ocurrió un error al agregar las estimaciones") - End If - End If - - End Sub - Private Sub GvContratoDetalles_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvContratoDetalles.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow Then - - Dim CantidadDisponible = If(e.Row.DBCampo("Cantidad").ToDouble < 0, "0", e.Row.DBCampo("Cantidad")) - e.Row.FCLiteral("LtlCantDisp").Text = CantidadDisponible - - If CveCicloComercial > 0 Then 'Si es un Ciclo Comercial quitamos el límite de CantidadDisponible - e.Row.Cells(1).Style.Add("display", "none") - CantidadDisponible = "10000000" - e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadContratada") - End If - - 'Si es contrato flexible le damos una cantidad alta de lo contrario lo maximo es lo estipulado en el contrato - If e.Row.DataKey("LimitarCantidad").ToString() = "True" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or e.Row.DataKey("ModalidadDetalle").ToString() = "1" Then - e.Row.FCRangeValidator("RVCant").MaximumValue = CantidadDisponible - LimitaCantidadSerieLote = 1 - Else - e.Row.FCRangeValidator("RVCant").MaximumValue = "10000000" - LimitaCantidadSerieLote = 0 - End If - - 'CONSIGNACION DE VENTA - If CveAlmacenExistenciasContrato > 0 And e.Row.DBCampo("Inv_CveMetodoInventario").ToString.ToEntero = 5 Then - GvContratoDetalles.Columns(8).Visible = True - e.Row.FCButton("BtnSerieConsignacion").Visible = True - e.Row.FCButton("BtnSerieConsignacion").CommandArgument = $"{e.Row.DBCampo("CveContratoDetalle")}°{e.Row.DBCampo("CvePS")}°{e.Row.DBCampo("CveUM")}°{e.Row.DBCampo("CodigoPS")}°{e.Row.DBCampo("Cantidad")}°{LimitaCantidadSerieLote}" - e.Row.FCTextBox("TxtCant").Enabled = False - End If - - ''Si viene de una OC Sin Facturar y tiene contrato - 'If TieneContrato AndAlso ContratosConOC IsNot Nothing AndAlso ContratosConOC.ToString.Length > 0 Then - ' e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadOC").ToString - 'End If - - End If - End Sub - Private Sub BtnCalcularTotalesContrato_Click(sender As Object, e As EventArgs) Handles BtnCalcularTotalesContrato.Click - For Each row As GridViewRow In GvContratoDetalles.Rows - row.FCLiteral("LtlTotal").Text = (row.FCLiteral("LtlCantDisp").Text.ToEntero * row.FCTextBox("TxtCant").Text.ToDouble).FormatoNumero(2) - Next - - UpContratos.Update() - End Sub - Private Sub DdlContratoModalSelectIndex() - If Not DdlContratosModal.SelectedValue.ToEntero > 0 Then - GvContratoDetalles.DataBind() - UpContratos.Update() - Exit Sub - End If - - Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}") - If DrContrato Is Nothing Then - Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError) - Exit Sub - End If - - CargaContratos() - - DdlContratosOC.SelectedValue = DdlContratosModal.SelectedValue - UPOCFactura.Update() +#Region "Punto Venta" + Private Sub CargaCorteCaja() + 'Checar si hay un Turno Abierto + Dim ObjPVenta As New ClsPuntoVenta + + If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then + + If ObjPVenta.DtResultados.Rows.Count > 0 Then + CveCorte = ObjPVenta.CveCorte + LblEstatusCaja.Text = ObjPVenta.FechaInicial.ToShortDateString + TrEstatusCaja.Visible = True + BtnIniciarTurno.Visible = False + LkbEstadodeCaja.Visible = True + LkbIngreso.Visible = True + LkbRetiro.Visible = True + Else + 'Ingresar un nuevo Turno + RegistraScript("window.onload = function MuestraCorteCaja() { document.getElementById(""C_btnShow"").click(); }") + End If + End If + ObjPVenta.Dispose() End Sub -#End Region + Private Sub BtnIniciarTurno_Click(sender As Object, e As EventArgs) Handles BtnIniciarTurno.Click + Dim ObjPVenta As New ClsPuntoVenta -#Region "C A R G A S" - Private Sub ClasificacionModal() - DdlClasificacionModal.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion") - DdlClasificacionModal.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlClasificacionModal.DataBind() - UpModal.Update() - End Sub - Private Sub CargaOrdenProduccion(Optional Opcion As Integer = 1, Optional CveVenta As Integer = -1) - DdlOrdenProduccion.Items.Clear() - Dim CveOrdenProduccion As String = "-1" - Dim ObjCGame As New ClsCGame - If ObjCGame.GetOrdenProduccion(-1, UsuarioActual.CveEmpresa, -1, "-1", MinFecha, MaxFecha, -1) Then - If Opcion = 1 Then - DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros(String.Format("CveVenta IS NULL ")) - ElseIf Opcion = 2 Then - LnkActualizarOrdenProduccion.Visible = True - DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta} OR CveVenta IS NULL") - If ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows.Count > 0 Then - CveOrdenProduccion = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows(0)("CveOrdenProduccion").ToString - End If - End If - DdlOrdenProduccion.Items.Insert(0, New ListItem("Seleccione", "-1")) - End If - ObjCGame.Dispose() - DdlOrdenProduccion.DataBind() - DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion) - End Sub - Private Sub CargaEstatusFactura(Optional TipoDocto As String = "Ing") - - Dim FiltroCompromiso = If(TipoDocto = "Com", "And CveEstatusFactura In (2, 9)", "And CveEstatusFactura Not In (9)") - If TipoDocto.ToUpper.Contiene("EGS", "COM", "ANT") Then TipoDocto = "Ing" - - - 'DdlEstatus.Items.Clear() - 'DdlEstatus.Items.Insert(0, New ListItem("Seleccione", "-1")) - 'DdlEstatus.SelectedValue = "-1" - 'DdlEstatus.DataSource = GlobalDTEstatusFactura.FiltraParametros(String.Format("TipoDocto = '{0}' {1}", TipoDocto, FiltroCompromiso)) - 'DdlEstatus.DataBind() - ''If DdlEstatus.Items.Count > 1 Then - '' DdlEstatus.SelectedIndex = 1 - ''End If - - ''permiso para poder cambiar estatus - 'If CveVenta > 0 Then DdlEstatus.Enabled = UsuarioActual.TienePermisoProceso(116) - - End Sub - Private Sub CargaOS(CveOS As Integer) - Dim OS As New ClsOS - Dim DtDetalle As DataTable = Nothing - Dim DtDetalleMateriales As DataTable = Nothing - - If OS.GetOrdenesServicios(CveOS, -1, -1, -1, -1, UsuarioActual.CveEmpresa) Then - - HdnCveCliente.Value = OS.CveCliente.ToString - ViewState("CveCliente") = OS.CveCliente - CargaCliente(CveCliente) - - If OS.GetOrdenesServiciosDetalleAFacturar(CveOS) Then - Dim Cons As Integer = 1 - For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows - - AgregarProductoServicio(dr("Cantidad").ToString.ToDecimal, dr("CveUM").ToString.ToEntero, dr("UM").ToString, -1, "", dr("CvePS").ToString.ToEntero, "", dr("Obs").ToString, 0, 0, -1, "", - dr("CveSubProyecto").ToString.ToEntero, dr("SubProyecto").ToString) - 'Dim drt As DataRow = TmpDT.NewRow - - 'drt("Consec") = Cons - 'drt("CvePS") = dr("CvePS") - 'drt("CveClasificacion") = dr("CveClasificacion") - 'drt("Clasificacion") = dr("Clasificacion") - 'drt("PS") = dr("PS") - 'drt("CveOSDetalle") = dr("CveOSDetalle") - 'drt("CodigoPS") = dr("CodigoPS") - 'drt("Cantidad") = dr("Cantidad") - 'drt("CveSubProyecto") = dr("CveSubProyecto") - 'drt("SubProyecto") = dr("SubProyecto") - 'drt("Obs") = dr("Obs") - 'TmpDT.Rows.Add(drt) - 'Cons = Cons + 1 - Next - TmpDT.AcceptChanges() - DtDetalle = OS.DtResultados.FiltraParametros("SeFacturara = 1 ") - End If - - For Each Row As DataRow In DtDetalle.Rows - If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString.ToEntero, CveOS) Then - If OS.DtResultados.FiltraParametros("SeFacturara = 1").Rows.Count > 0 Then - Alert("Hay materiales en la Orden de Servicio, ¿Desea facturar los materiales?", TipoMensaje.MsgConfirmacion, "BtnMateriales()") - End If - End If - Next - - OS.Dispose() - - TxtTotal.Text = TmpDT.SUM("Total").FormatoNumero() - - GvPS.DataSource = TmpDT - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - GvPS.DataBind() - - 'JJMQ 20160506: Se agrego para la validacion de pago de contado. - CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") - - UpContado.Update() - UpPS.Update() - End If - End Sub - - Private Function CargaVenta() As Boolean - - Dim Retorno As Boolean = False - - 'CARGA PARA FACTURACION - Dim CveRemision As Integer = IfNull(ViewState("CveRemision"), 0).ToString.ToEntero - Dim CveCotizacion As Integer = IfNull(ViewState("CveCotizacion"), 0).ToString.ToEntero - Dim CveVenta As Integer = Me.CveVenta - CveVenta = If(CveRemision > 0, CveRemision, CveVenta) - CveVenta = If(CveCotizacion > 0, CveCotizacion, CveVenta) - CveVenta = If(CvePedido > 0, CvePedido, CveVenta) - - Dim ObjVentas As New ClsVentas() - - Dim SerieFolioPadre As String - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - - If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0) - Dim CveCliente As Integer = DbRowVenta("CveCliente").ToString.ToEntero - HdnCveVenta.Value = CveVenta.ToString - - Me.CveEstatusFacturaPadre = DbRowVenta("CveEstatusFacturaPadre").ToString.ToEntero - 'CargaEncabezado - If Not (CveRemision > 0 Or CveCotizacion > 0) Then - DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString - - If UsuarioActual.TienePermisoProceso(274) Then - TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant" - End If - - If TrAntEspecial.Visible Then - ChkAntEspecial.Enabled = False - ChkAntEspecial.Checked = If(DbRowVenta("AnticipoEspecial").ToString = "True", True, False) - End If - CargaEstatusFactura(DdlTipoComprobante.SelectedValue) - CveEstatus = DbRowVenta("CveEstatusFactura").ToString.ToEntero - LbEstatus.Text = DbRowVenta("EstatusFactura").ToString - ViewState("SaldoVenta") = DbRowVenta("Saldo").ToString - AplicaCancelarRemision = CBool(DbRowVenta("AplicaCancelarRemision").ToString) - If AplicaCancelarRemision AndAlso CveEstatus.Contiene(2, 3) AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then DivCanRem.Visible = True - VentaSaldoAlmacen = DbRowVenta("SaldoAlmacen").ToString.ToDecimal - - If CveEstatus = 5 Then LbCancelarDocumento.Enabled = False - 'If CveEstatus = 20 Then - ' LbCancelarDocumentoManual.Visible = True - 'End If - - If Not CveEstatus.Contiene(4, 5, 12, 13, 20) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Ant") AndAlso UsuarioActual.TienePermisoProceso(159) Then - Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) - If TienePermiso <> "" Then - LkRefacturacion.Visible = True - End If - End If - - If DbRowVenta("CveVentaRelacionada").ToString.ToEntero > 0 Then - TrRefacturadaa.Visible = True - HplRefacturadaEn.NavigateUrl = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", DbRowVenta("CveVentaRelacionada")) - HplRefacturadaEn.Text = DbRowVenta("SerieFolioRelacionada").ToString - LblAlertRefacInv.Visible = True - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Ing", "Ant", "Dev", "Rem", "DPe") AndAlso Not CveEstatus.Contiene(4, 5, 12, 13, 20) Then - If UsuarioActual.TienePermisoProceso(159) Then - Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) - If TienePermiso <> "" Then - LbCancelarDocumento.Visible = True - 'If UsuarioActual.CveEmpresa = 119 And Not UsuarioActual.CveUsuario.Contiene(100, 1703) Then '[IPP] AD y Jesus de JAM - ' 'si es del mes anterior no permita cancelar - ' If Not DdlTipoComprobante.SelectedValue.Contiene("Rem") Then - ' If DbRowVenta("Fecha").ToString.ToDate <= Now.AddMonths(-1).LastDayOfMonth Then - ' LbCancelarDocumento.Visible = False - ' End If - ' End If - 'End If - End If - If LblFolioFiscal.Text.Trim = "" Then HplFolioFiscalModal.Visible = True - End If - End If - - - Select Case DbRowVenta("TipoDocto").ToString - Case "Ing" - Trsaldo.Visible = True - HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then - HLPagar.Visible = True - HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675" - HlCuentaTerminal.Visible = True - End If - - Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) - If TienePermiso <> "" Then ' si tiene acceso en el subproyecto - 'LkNotaCredito.Visible = UsuarioActual.TienePermisoProceso(175) - If UsuarioActual.TienePermisoProceso(264) Then - LkDevolucion.Visible = True - InicializaAplicaDevolucion() - End If - End If - - - HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) - Case "Egs" - HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) - HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString - Trsaldo.Visible = True - HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - Case "Rem" - 'IPP 15 Julio 2017 - Trsaldo.Visible = True - HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then - HLPagar.Visible = True - HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675" - HlCuentaTerminal.Visible = True - End If - - If UsuarioActual.CveEmpresa = 80 Then - LtlImprimir.Text = String.Format("
  • Imprimir
  • ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta))) - End If - DiasCredito = DbRowVenta("DiasCredito").ToString.ToEntero - EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString) - Case "OP" - TdOrdenPago.Visible = True - DdlOrdenPago.SelectedValue = DbRowVenta("Num3").ToString - DdlOrdenPago.Enabled = False - Case "Cot" - TxtAtencionA.Text = DbRowVenta("AtencionA").ToString - TxtFechaVencimientoCotizacion.Text = DbRowVenta("Vigencia").ToString - PnlImprimir.Visible = True - HLOrdendeCompra.Visible = True - HLOrdendeCompra.NavigateUrl = String.Format("/OC/OC.aspx?Tipo=Req&CveCotizacion={0}", CveVenta) - - Dim ObjOS As New ClsOS() - If ObjOS.GetCotizacionOS(CveVenta) Then - If ObjOS.DtResultados.Rows.Count > 0 Then - Dim DbRowOS As DataRow = ObjOS.DtResultados.Rows(0) - ViewState("CveOS") = DbRowOS("CveOS").ToString.ToEntero - CargaOS(CveOS) - End If - - Else - HLOrdenServicio.Visible = True - HLOrdenServicio.NavigateUrl = String.Format("/OS/OrdenesServicios.aspx?CveCotizacion={0}", CveVenta) - End If - ObjOS.Dispose() - - If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 145) Then PnlImprimir.Visible = True : LnkImprimir.OnClientClick = "javascript:ImprimirCotizacion();return false;" - 'Deshabilitar impresión cuando no esté supervisada - If DbRowVenta("TipoEstatus").ToString.ToEntero = 2 Or UsuarioActual.Empresa.Funcionalidad(113) = "1" Then - PnlImprimir.Visible = True - Else - HplDownPDF.Visible = False - PnlImprimir.Visible = False - End If - - - 'Verifico si tiene la funcionalidad (135) - If UsuarioActual.Empresa.Funcionalidad(135) = "1" Then - 'Reviso cuales son los supervisores - Dim Objeto As New ClsVtaVendedores - - If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then - Dim DTVendedores As New DataTable - DTVendedores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString)).FiltraParametros(String.Format("CveSupervisor = {0}", UsuarioActual.CveVendedor)) - 'Verifico si es su supervisor asignado - If DTVendedores.Rows.Count > 0 Then - LkCotizacionAutorizar.Visible = True - End If - DTVendedores.Dispose() - End If - Objeto.Dispose() - End If - - String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString) - - - Case "Ant" - Trsaldo.Visible = True - HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - 'LkNotaCredito.Visible = True - HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) - Case "Dev" - DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) - HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) - HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString - ViewState("CveDevolucion") = DbRowVenta("CveVentaPadre").ToString.ToEntero - Trsaldo.Visible = True - HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) - Case "Ped" - DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) - Case "DPe" - DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe")) - Case "PeC" - DdlTipoComprobante.Items.Insert(5, New ListItem("Pedido de Consignación", "PeC")) - Case "PA" - BtnGenerarRemision.Visible = If(CveEstatus = 16, True, False) - CvePedidoA = CveVenta - DiasCredito = DbRowVenta("DiasCredito").ToString.ToEntero - EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString) - Case "Pd2" - CvePedido2 = CveVenta - BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False) - BtnGenerarRemision.Visible = If(CveEstatus <> 21, True, False) - End Select - - DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString - - End If - - 'contado 0, credito 1, terminal 2 - If ObjVentas.DtResultados(0)("CondicionesPago").ToString.ToEntero = 1 Then - RBLPago.SelectedValue = "1" - RBLPago_SelectedIndexChanged(Nothing, Nothing) - UPCondicionesPago.Update() - ElseIf ObjVentas.DtResultados(0)("CondicionesPago").ToString.ToEntero = 0 Then - RBLPago.SelectedValue = "2" - RBLPago.Items(0).Enabled = False - RBLPago_SelectedIndexChanged(Nothing, Nothing) - UPCondicionesPago.Update() - Else - DdlCuentasTerminal.SelectedValue = DbRowVenta("CveCuentaTerminal").ToString - RBLPago.SelectedValue = "3" - RBLPago.Items(0).Enabled = False - RBLPago_SelectedIndexChanged(Nothing, Nothing) - UPCondicionesPago.Update() - End If - - 'CargaDetalle - If ObjVentas.GetVentaDetalle(CveVenta) Then - TmpDT = ObjVentas.DtResultados - TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) - TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) - GvPS.DataSource = ObjVentas.DtResultados - GvPS.DataBind() - - 'IEPS A NIVEL DETALLE - 'TxtIEPS.Text = If(TmpDT.SUM("IEPS") > 0, TmpDT.SUM("IEPS").FormatoNumero, TxtIEPS.Text) - End If - - 'ESCONDE ACCIONES - LnkRemisiones.Visible = False - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - LnkOCs.Visible = False - UpnTools.Update() - - DivEstatusFac.Visible = True - HdnCveCliente.Value = CveCliente.ToString - ViewState("CveCliente") = CveCliente - ViewState("CveEmpresaCRM") = DbRowVenta("CveEmpresaCRM").ToString.ToEntero - ViewState("CveAcercamientoCRM") = DbRowVenta("CveAcercamientoCRM").ToString.ToEntero - Entrega = DbRowVenta("Entrega").ToString - Vigencia = DbRowVenta("Vigencia").ToString.ToDate.ToShortDateString - HplSaldoAuxiliar.Text = DbRowVenta("Saldo").ToString.FormatoNumero(2) - If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then - HplSaldoAuxiliar.Visible = False - HplPagado.Visible = True - - If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString.ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then - ImgAntiPend.Visible = True - Else - ImgAntiPend.Visible = False - End If - - End If - HdnPagado.Value = DbRowVenta("Pagado").ToString - TxtTotal.Text = DbRowVenta("Total").ToString.FormatoNumero(2) - HdnVentaSaldo.Value = (SaldoVenta).ToString - CvePrePoliza = DbRowVenta("CvePrePoliza").ToString.ToEntero - CveVentaFacturada = DbRowVenta("CveVentaFacturada").ToString.ToEntero - - CveVentaRelacion = DbRowVenta("CveVentaRelacion").ToString.ToEntero - ImporteRelacion = DbRowVenta("ImporteRelacion").ToString.ToDouble - - DdlMoneda.SelectedValue = DbRowVenta("CveMoneda").ToString - CambiaMoneda() - - If DbRowVenta("TipoDocto").ToString = "Pd2" Then - 'CANTIDAD FACTURADA - If TmpDT.SUM("CantidadFacturadaPed2") > 0 Then - GvPS.Columns(7).Visible = True - ThCantidadFacturada.Visible = True - ThCantidadFacturada2.Visible = True - Else - GvPS.Columns(7).Visible = False - ThCantidadFacturada.Visible = False - ThCantidadFacturada2.Visible = False - End If - - ''ACTIVA EDITAR - ''SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA - 'If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString.ToEntero Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") - ' BtnPermisoEditarCotizacion.Visible = True - 'End If - - 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR - 'If TmpDT.SUM("CantidadFacturadaPed2") < TmpDT.SUM("Cantidad") Then - ' BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) - ' BtnsFacturar.Visible = True - 'End If - End If - - - If CveEmpresaCRM > 0 And Not CveCliente > 0 Then - CargaEmpresaCRM(CveEmpresaCRM) - Else - CveEmpresaCRM = IIf(CveEmpresaCRM > 0, CveEmpresaCRM, 0).ToString().ToEntero() - CargaCliente(CveCliente, -1) 'Estatus activo, se requiere para cargar una factura en la que el cliente a sido eliminado - End If - - ViewState("CveAlmacenTransitorio") = DbRowVenta("CveAlmacenTraspasoDestino").ToString.ToEntero - DevolucionAlmacen = DbRowVenta("EsDevolucionVenta").ToString.ToEntero - - 'sino esta cargada la información del metodo de pago que le corresponde, la recarga para que se le pueda asignar - If DdlMetodoPago33.SelectedValue <> DbRowVenta("CveMetodoPago33").ToString Then - CargaFormaPago(DbRowVenta("CveMetodoPago33").ToString.ToEntero) - End If - DdlMetodoPago33.SelectedValueExist(DbRowVenta("CveMetodoPago33").ToString) - DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString.ToEntero) - - If DdlFormaPago33.SelectedValue <> DbRowVenta("CveFormaPago33").ToString And DbRowVenta("CveFormaPago33").ToString <> "" Then - 'sino está seleccionada la asginada la debe de cargar - Dim Nombre As String = GlobalDTVtaFormaPago().FiltroPrimeroValor("FormaPagoSAT", String.Format("CveFormaPago={0}", DbRowVenta("CveFormaPago33"))) - DdlFormaPago33.Items.Add(New ListItem(Nombre, DbRowVenta("CveFormaPago33").ToString)) - DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString.ToEntero) - End If - - DdlUsoCFDI.SelectedValueExist(DbRowVenta("CveUsoCFDI").ToString) - - If UsuarioActual.CveEmpresa = 126 Then CargaOrdenProduccion(2, CveVenta) - - If DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then - TrTipoRelacion.Visible = True - DdlTiposRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion").ToString.ToEntero) - HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString - End If - - If DbRowVenta("Saldo").ToString.ToDouble < 0.01 Then - If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString.ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then - ImgAntiPend.Visible = True - Else - ImgAntiPend.Visible = False - End If - ElseIf Opcion <> "Op" Then - ImgAntiPend.Visible = True - End If - If UsuarioActual.CveRol.Contiene(1, 1155) Then LiLnkGuias.Visible = True - - LiComplementoPago.Visible = True - - - ViewState("FolioFiscal") = DbRowVenta("FolioFiscal").ToString - LblSerie.Text = DbRowVenta("Serie").ToString - ViewState("Serie") = DbRowVenta("Serie").ToString - ViewState("Folio") = DbRowVenta("Folio").ToString.ToEntero - TxtFolio.Text = DbRowVenta("Folio").ToString - 'TxtDocto.Text = DbRowVenta("Ref").ToString - 'TxtNumCtaPago.Text = DbRowVenta("NumeroCuenta").ToString - LblFolioFiscal.Text = DbRowVenta("FolioFiscal").ToString - TxtFecha.Text = DbRowVenta("Fecha").ToString - TxtSubTotal.Text = DbRowVenta("SubTotal").ToString.FormatoNumero(2) - LblDescuentos.Text = DbRowVenta("Descuento").ToString.FormatoNumero(2) - LblAmortizacion.Text = DbRowVenta("Amortizacion").ToString.FormatoNumero(2) - TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) - TxtIVA.Text = DbRowVenta("IVA").ToString.FormatoNumero(2) - TxtRetIVA.Text = DbRowVenta("RetIVA").ToString.FormatoNumero(2) - TxtRetISR.Text = DbRowVenta("RetISR").ToString.FormatoNumero(2) - TxtIEPS.Text = DbRowVenta("IEPS").ToString.FormatoNumero(2) - TrIEPS.Visible = TxtIEPS.Text.ToDouble > 0 - TxtTotal.Text = DbRowVenta("Total").ToString.FormatoNumero(2) - HdnTotalVenta.Value = DbRowVenta("Total").ToString.FormatoNumero(2) - TxtMotivoDescuento.Text = DbRowVenta("MotivoDescuento").ToString - TxtObsFact.Text = DbRowVenta("Observaciones").ToString - LblUsuario.Text = DbRowVenta("Nombre").ToString - LblFechaRegistro.Text = DbRowVenta("FechaIng").ToString.ToDate.ToShortDateString - LblSeTimbro.Text = DbRowVenta("SeTimbro").ToString - LblMail.Text = DbRowVenta("EnvioMail").ToString - TxtFechaPago.Text = DbRowVenta("FechaVencimiento").ToString - TxtFechaVencimientoCotizacion.Text = Vigencia - TxtDet_OrdenCompra.Text = DbRowVenta("Det_OrdenCompra").ToString - TxtDet_FechaOrdenCompra.Text = DbRowVenta("Det_FechaOrdenCompra").ToString - HdnIVAOriginal.Value = TxtIVA.Text - TxtPedidoContrato.Text = DbRowVenta("PedidoContrato").ToString - TxtPedidoContrato.Enabled = False - - - HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString - HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) - 'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString - 'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString = "True" - DdlTipoAmortizacionAnticipo.SelectedValueExist(DbRowVenta("CveTipoAmortizacionAnticipo")) - DdlTipoRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion")) - - 'HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString - 'HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) - 'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString - 'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString = "True" - - - If DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then - TrTipoRelacion2.Visible = True - LblTipoRelacion.Text = DbRowVenta("TipoRelacion").ToString - HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString - End If - - - TxtOrdenCompra.Text = DbRowVenta("OrdenCompra").ToString - TxtOrdenCompra.Enabled = False - - TxtObsAlmacen.Text = DbRowVenta("ObservacionesAlmacen").ToString - CvePAC = DbRowVenta("CvePAC").ToString.ToEntero - - If DbRowVenta("Saldo").ToString.ToDecimal > 0 AndAlso UsuarioActual.TienePermisoProceso(204) AndAlso Not UsuarioActual.CveEmpresa.Contiene(119) Then - TxtFechaSaldarVenta.Text = TxtFecha.Text - CEFechaSaldarVenta.StartDate = TxtFecha.Text.ToDate - HLSaldarVenta.Visible = True - End If - - - If (UsuarioActual.TienePermisoProceso(166) Or UsuarioActual.CveRol = 1) AndAlso (LblFolioFiscal.Text = "" Or LblFolioFiscal.Text = "test") Then - LkEliminarFactura.Visible = True - End If - - 'Envio Direccion - If DbRowVenta("CveDireccionEnvio").ToString.ToEntero > 0 AndAlso DbRowVenta("CveDireccionEnvio").ToString IsNot Nothing Then - ChkDireccionEnvio.Checked = True - DdlDireccionEnvio.SelectedValueExist(DbRowVenta("CveDireccionEnvio").ToString.ToEntero) - DdlDireccionEnvio.Enabled = False - ChkDireccionEnvio.Enabled = False - DdlDireccionEnvio.Visible = True - trDireccionEnvio.Visible = True - End If - - 'ESTATUS FACTURA - If Not (CveRemision > 0 Or CveCotizacion > 0) Then - CveEstatus = DbRowVenta("CveEstatusFactura").ToString.ToEntero - - End If - - TxtTipoCambio.Text = DbRowVenta("TipoCambio").ToString - If DbRowVenta("TipoCambio").ToString.ToDecimal <> DbRowVenta("TipoCambioValuacion").ToString.ToDecimal Then - LblTCValuacion.Text = String.Format("Ult. Val:{0}", DbRowVenta("UltimasFluctuaciones").ToString) - LblTCValuacion.Visible = True - End If - - ViewState("SelloCancelacion") = DbRowVenta("SelloCancelacion").ToString - ViewState("FechaCancelacion") = DbRowVenta("FechaCancelacion").ToString.ToDateTime - TxtAtencionA.Text = DbRowVenta("AtencionA").ToString - TxtTelefonoGenerico.Text = DbRowVenta("TelefonoGenerico").ToString - CveVentaPadre = DbRowVenta("CveVentaPadre").ToString.ToEntero - SerieFolioPadre = DbRowVenta("SerieFolioPadre").ToString - - If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then - DdlVendedor.Enabled = False - End If - - If CveVentaPadre > 0 Then - If IsNothing(Request("CveDevolucion")) AndAlso IsNumeric(Request("CveDevolucion")) Then - DdlNCFactura.Visible = True - Else - DdlNCFactura.Visible = False - End If - trNCFactura.Visible = True - LblSerieFolioPadre.Visible = True - LblSerieFolioPadre.Text = String.Format("{1}", CveVentaPadre, SerieFolioPadre) - - End If - - TxtFechaEjecucion.Text = DbRowVenta("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy") - 'DdlSucursalEjecucion.SelectedValueExist(DbRowVenta("CveSucursalEjecucion").ToString) - 'DdlSucursalCobranza.SelectedValueExist(DbRowVenta("CveSucursalCobranza").ToString) - DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").ToString) - 'DdlSucursal.SelectedValueExist(DbRowVenta("CveSucursal").ToString) - 'DdlSubProyectoDatos.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString) - - If DdlSubProyectoDatos.Items.Count = 0 Then - DdlSubProyectoDatos.Items.Insert(0, New ListItem("Seleccione", "-1")) - End If - DdlSubProyectoDatos.SelectedValueExistInsert(DbRowVenta("CveSubProyecto").ToString, DbRowVenta("SubProyecto").ToString) - - If DdlSubProyectoCobranza.Items.Count = 0 Then - DdlSubProyectoCobranza.Items.Insert(0, New ListItem("Seleccione", "-1")) - End If - DdlSubProyectoCobranza.SelectedValueExistInsert(DbRowVenta("CveSubProyectoCobranza").ToString, GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoCobranza").ToString.ToEntero).FiltroPrimeroValor("SubProyecto").ToString) - - If DdlSubProyectoEjecucion.Items.Count = 0 Then - DdlSubProyectoEjecucion.Items.Insert(0, New ListItem("Seleccione", "-1")) - End If - DdlSubProyectoEjecucion.SelectedValueExistInsert(DbRowVenta("CveSubProyectoEjecucion").ToString, GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoEjecucion").ToString.ToEntero).FiltroPrimeroValor("SubProyecto").ToString) - - CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString.ToEntero) - - If DbRowVenta("CveContrato").ToString.ToEntero > 0 Then - CveContrato = DbRowVenta("CveContrato").ToString.ToEntero - NumeroContrato = DbRowVenta("NumeroContrato").ToString - DescripcionContrato = DbRowVenta("DescripcionContrato").ToString - DdlContrato.Visible = False - HLContrato.Text = $"{DbRowVenta("NumeroContrato")} - {DbRowVenta("DescripcionContrato")}" - HLContrato.NavigateUrl = $"/Contratos/Contrato.aspx?CveContrato={CveContrato}" - 'trPresupuesto.Visible = True - 'HplPresupuesto.NavigateUrl = String.Format(" / Presupuestos / Presupuesto.aspx?CvePresupuesto={0}", DbRowVenta("CveContrato").ToString) - Else - NumeroContrato = "" - DescripcionContrato = "" - End If - - 'DdlEstatus.Items.Remove(DdlEstatus.Items.FindByText("Cotización")) - - If DbRowVenta("SeTimbro").ToString <> "No" Then - HplDownXML.Visible = True - 'If HLImprimir.Visible = False Then - HplDownPDF.Visible = True - 'End If - ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" OrElse DdlTipoComprobante.SelectedValue = "Cot" Then - 'If drv("TipoEstatus").ToString.ToEntero = 2 AndAlso drv("TipoDocto").ToString = "Cot" Then - ' ImgDownPDF.Visible = True - 'Else - HplDownPDF.Visible = False - 'End If - ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso DbRowVenta("SeTimbro").ToString = "No" AndAlso DbRowVenta("CveEstatusFactura").ToString = "2" AndAlso DbRowVenta("TipoDocto").ToString.Contiene("Ing", "Egs", "Dev", "Ant") Then - TrEmitir.Visible = True - If TxtFecha.Text.ToDate < Now.AddDays(-3) Then - TxtFecha.Enabled = True - End If - End If - - If DbRowVenta("SeTimbro").ToString = "Si" Then - TrEmitir.Visible = False - End If - - 'CargaAcuseCancelacion - If DbRowVenta("CveEstatusFactura").ToString = "5" Then - ImgDownCancelacion.Visible = True - ImgDownCancelacion.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CAN&CVEVTA={0}", CveVenta))) - End If - IdPoliza = DbRowVenta("IdPoliza").ToString.ToEntero - - 'Carga si es Contabilizada - If IdPoliza > 0 Then - HLContabilizada.Text = "Si" - HLContabilizada.NavigateUrl = $"/Contabilidad/RegPoliza.aspx?IdPoliza={DbRowVenta("IdPoliza")}" - trContabilizada.Visible = True - If UsuarioActual.TienePermisoProceso(107) Then BtnDescontabilizar.Visible = True - - Else - 'cuando no este contabilizada y usa AC, habilita el boton para generar la poliza - If UsuarioActual.Empresa.UsaAC AndAlso UsuarioActual.CveRol = 1 Then - BtnGenerarPoliza.Visible = True - End If - If UsuarioActual.Empresa.Funcionalidad(200) = "1" Then - BtnContabilizar.Visible = True - End If - End If - - If DbRowVenta("IdPolizaCancelacion").ToString.ToEntero > 0 Then - HPLContaCancelacion.Text = "Cancelación" - HPLContaCancelacion.NavigateUrl = String.Format("/Contabilidad/RegPoliza.aspx?IdPoliza={0}", DbRowVenta("IdPolizaCancelacion")) - trContabilizada.Visible = True - End If - - - If UsuarioActual.Empresa.UsaOS AndAlso DbRowVenta("CveOS").ToString.ToEntero = 0 Then - BtnGenerarOS.Visible = True - BtnGenerarOS.OnClientClick = String.Format("javascriptwindow.location.href = '/OS/OrdenesServicios.aspx?CveVenta={0}'; return false;", CveVenta) - ' BtnGenerarOS.OnClientClick = String.Format("/OS/OrdenesServicios.aspx?CveVenta={0}", CveVenta) - End If - - - '[IPP] COMENTADO 12/MARZO/2018 -SABRA QUE SE QUERIA ESCONDER - 'If DbRowVenta("TipoDocto").ToString = "Rem" Then - ' GvPS.Columns(11).Visible = False - ' GvPS.Columns(12).Visible = False - 'End If - - - 'Ocultamos los botones Clonar y Ordenar - GvPS.Columns(19).Visible = False - GvPS.Columns(20).Visible = False - - 'CargaFirmas - If ObjVentas.GetVentasFirmas(CveVenta) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - DTmpF = ObjVentas.DtResultados - GvFirmas.DataSource = ObjVentas.DtResultados - GvFirmas.DataBind() - Else - GvFirmas.DataSource = Nothing - End If - End If - - 'CARGA IMPUESTOS LOCALES - If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - TrOtros.Visible = True - TmpDTImpuestos = ObjVentas.DtResultados - GvImpuestosLocales2.DataSource = ObjVentas.DtResultados - GvImpuestosLocales2.DataBind() - - GvImpuestosLocales2.Enabled = False - GvImpuestosLocales2.Visible = True - End If - End If - - DdlVendedor.SelectedValue = DbRowVenta("CveVendedor").ToString - DdlTipoComprobante.Enabled = False - 'TxtDocto.Enabled = False - - 'PORLET CLIENTE - 'DESACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto disabled") - TxtCodigo.ReadOnly = True - ChkEnviarFactura.Enabled = False - ChkDireccionEnvio.Enabled = False - TxtAtencionA.Enabled = False - TxtFechaVencimientoCotizacion.Enabled = False - - TxtCantidad.Enabled = False - DdlClasificacion.Enabled = False - - DdlPS.Enabled = False - TxtObsPS.Enabled = False - DdlProyecto.Enabled = False - DdlSubProyecto.Enabled = False - TxtPrecio.Enabled = False - ImgDescPU.Attributes.Clear() - ImgDescTotal.Attributes.Clear() - ImgDescConcepto.Attributes.Clear() - LbAgregar.Enabled = False - LnkAgregarPyME.Enabled = False - DdlCuentasTerminal.Enabled = False - - For Each Row As GridViewRow In GvPS.Rows - Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString() - Next - GvPS.Columns(ColumnaEditar).HeaderText = "" - GvPS.Columns(ColumnaEliminar).HeaderText = "" - 'GvPS.Columns(ColumnaEliminar).Visible = False - - TxtObsFact.Enabled = False - TxtObsAlmacen.Enabled = False - TxtMotivoDescuento.Enabled = False - 'GvLeyendasFiscales.Enabled = False - TxtSubTotal.ReadOnly = True - TxtIVA.ReadOnly = True - TxtRetIVA.ReadOnly = True - TxtRetISR.ReadOnly = True - TxtIEPS.ReadOnly = True - TxtTotal.ReadOnly = True - - 'Sección Detalle - DdlMoneda.Enabled = False - TxtFechaEjecucion.ReadOnly = True - ImgCalendarFechaEje.Enabled = False - 'DdlSucursalEjecucion.Enabled = False - 'DdlSucursalCobranza.Enabled = False - DdlVendedor.Enabled = False - DdlSucursalCliente.Enabled = False - TxtTiempoEntrega.Enabled = False - TxtAlfa1.ReadOnly = True - TxtAlfa2.ReadOnly = True - TxtAlfa3.ReadOnly = True - TxtNum1.ReadOnly = True - TxtNum2.ReadOnly = True - TxtNum3.ReadOnly = True - TxtFech1.ReadOnly = True : ImgFech1.Enabled = False - TxtFech2.ReadOnly = True : ImgFech2.Enabled = False - TxtFech3.ReadOnly = True : ImgFech3.Enabled = False - ChkConvertirDoctoPesos.Enabled = False - ChkConvertirDolares.Enabled = False - TxtTipoCambio.Enabled = False - TxtTipoCambioDlls.Enabled = False - - 'Condiciones de Pago - RBLPago.Enabled = False - DdlFormaPago33.Enabled = False - DdlUsoCFDI.Enabled = False - DdlMetodoPago33.Enabled = False - 'TxtNumCtaPago.Enabled = False - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then - TxtFechaPago.ReadOnly = Not UsuarioActual.TienePermisoProceso(260) - LnkUpdateFechaVencimiento.Visible = UsuarioActual.TienePermisoProceso(260) - Else - TxtFechaPago.ReadOnly = False - End If - - imgCalendario.Enabled = False - DdlFuenteRecaudacion.Enabled = False - - TrVistaPrevia.Visible = False - BtnEmitirImprimir.Visible = False - 'CargaLeyendasFiscales - ViewState("VentaFolio") = If(LblSerie.Text.Trim.Length = 0, TxtFolio.Text.Trim, LblSerie.Text.Trim & "-" & TxtFolio.Text.Trim) - - CalculaTotalesVenta(False) - - 'JJMQ 20160506: Se agrego para la validacion de pago de contado. - CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") - - 'CARGA ANTICIPOS - If Not (CveRemision > 0 Or CveCotizacion > 0) Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then - 'carga as notas de credito vinculadas - If ObjVentas.GetVentasAntNC(CveVenta, -1) Then - GvAntNC.DataSource = ObjVentas.DtResultados - TmpDTDocumentosRelacionados = ObjVentas.DtResultados - GvAntNC.Caption = "
    (Anticipos/NC/IxC) Vinculados
    " - GvAntNC.DataBind() - End If - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev", "Ant") Then - If ObjVentas.GetVentasAntNC(-1, CveVenta) Then - GvNC.DataSource = ObjVentas.DtResultados - TmpDTNCVinculadas = ObjVentas.DtResultados - GvNC.Caption = "
    Ventas Aplicadas
    " - GvNC.DataBind() - InicializaDTVentasNC() - For Each Dr As DataRow In ObjVentas.DtResultados.Rows - If Dr("CveConceptoContable").ToString.ToEntero = 91 Then - CargaNCDT(Dr("CveVenta").ToString.ToEntero, Dr("Importe").ToString.ToDecimal, Dr("FolioFiscal").ToString, TC:=Dr("TipoCambio").ToString.ToDecimal) - End If - Next - End If - End If - End If - - If GvNC.Rows.Count > 0 Then - ImgAntiPend.Visible = False - End If - - 'CARGA REMISIONES - If ObjVentas.GetRemisionesRelacionadas(CveVenta, DdlTipoComprobante.SelectedValue) Then - GvRemisiones.Caption = "
    Remisiones/Facturas
    " - GvRemisiones.DataSource = ObjVentas.DtResultados - GvCancelarRemisiones.DataSource = ObjVentas.DtResultados - - GvRemisiones.DataBind() - GvCancelarRemisiones.DataBind() - - '[IPP] SI ES REMISION PARA CANCELARLA NO DEBE TENER NINGUNA FACTURADA RELACIONADA - 24Abril2018 - If DdlTipoComprobante.SelectedValue.Contiene("Rem") And GvRemisiones.Rows.Count > 0 Then - LbCancelarDocumento.Visible = False - End If - End If - - tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") - tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") - - - If DbRowVenta("TipoDocto").ToString = "Rem" Then - 'CANTIDAD FACTURADA - If TmpDT.SUM("CantidadFacturadaRem") > 0 Then - GvPS.Columns(6).Visible = True - ThCantidadFacturadaRem.Visible = True - ThCantidadFacturadaRem2.Visible = True - Else - GvPS.Columns(6).Visible = False - ThCantidadFacturadaRem.Visible = False - ThCantidadFacturadaRem2.Visible = False - End If - - 'ACTIVA EDITAR - 'SOLO LA PUEDE EDITAR CON PROCESO | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR - If UsuarioActual.TienePermisoProceso(202) And TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then - BtnPermisoEditarRemision.Visible = True - End If - - 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR - If TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then - BtnsFacturar.Visible = True - - 'ACTIVA CONVERSION DE MONEDA - If DdlMoneda.SelectedValue.ToEntero = 1 Then - TrConversionDolares.Visible = True - ChkConvertirDolares.Enabled = True - TxtTipoCambioDlls.Enabled = True - Else - TrConversionTipoCambio.Visible = True - ChkConvertirDoctoPesos.Enabled = True - TxtTipoCambio.Enabled = True - End If - End If - - End If - - - If DbRowVenta("TipoDocto").ToString.Contiene("Cot", "Pd2") Then - 'CANTIDAD FACTURADA - If TmpDT.SUM("CantidadFacturadaCot") > 0 Then - GvPS.Columns(7).Visible = True - ThCantidadFacturada.Visible = True - ThCantidadFacturada2.Visible = True - Else - GvPS.Columns(7).Visible = False - ThCantidadFacturada.Visible = False - ThCantidadFacturada2.Visible = False - End If - - 'ACTIVA EDITAR - 'SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA - If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString.ToEntero Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") - BtnPermisoEditarCotizacion.Visible = True - End If - - 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR - If TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") AndAlso DdlTipoComprobante.SelectedValue.Contiene("Cot") Then - BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) - BtnsFacturar.Visible = True - End If - End If - - UpPS.Update() - UpContado.Update() - UpEstatus.Update() - Retorno = True - - Else - CveVenta = -1 - Alert("El documento solicitado no existe, favor de revisar su búsqueda.", TipoMensaje.MsgAdvertencia) - End If - End If - ObjVentas.Dispose() - Return Retorno - End Function - Private Sub CargaTiposDocumentos() - DdlTipoComprobante.DataSource = GlobalDTTiposDocumentos() - DdlTipoComprobante.DataBind() - End Sub - Private Sub CargaNuevaFactura(OVenta As ClsVentas) - Dim ObjVentas As ClsVentas - - If OVenta IsNot Nothing Then - ObjVentas = OVenta - Else - ObjVentas = New ClsVentas() - End If - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) - - 'CargaCliente - Dim CveCliente As Integer = drv("CveCliente").ToString.ToEntero - - HdnCveCliente.Value = CveCliente.ToString - ViewState("CveCliente") = CveCliente - CargaCliente(CveCliente) - - 'Carga Detalle Sucursal - TxtFechaEjecucion.Text = drv("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy") - TxtFechaPago.Text = drv("FechaVencimiento").ToString.ToDateTime.ToString("dd/MM/yyyy") - 'DdlSucursalEjecucion.SelectedValueExist(drv("CveSucursalEjecucion").ToString) - 'DdlSucursalCobranza.SelectedValueExist(drv("CveSucursalCobranza").ToString) - DdlSucursalCliente.SelectedValueExist(drv("CveClienteSucursal").ToString) - 'DdlSucursal.SelectedValueExist(drv("CveSucursal").ToString) - DdlSubProyectoDatos.SelectedValueExist(drv("CveSubProyecto").ToString) - DdlSubProyectoEjecucion.SelectedValueExist(drv("CveSubProyectoEjecucion").ToString) - DdlSubProyectoCobranza.SelectedValueExist(drv("CveSubProyectoCobranza").ToString) - - If CveDevolucion > 0 Then - CambiaSucursalGeneral() - End If - CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero) - - 'CargaDetalle - If ObjVentas.GetVentaDetalle(CveVenta) Then - TmpDT = ObjVentas.DtResultados - TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) - TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) - 'TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) - GvPS.DataSource = ObjVentas.DtResultados - GvPS.DataBind() - End If - - 'CARGA IMPUESTOS LOCALES - If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - TrOtros.Visible = True - TmpDTImpuestos = ObjVentas.DtResultados - GvImpuestosLocales2.DataSource = ObjVentas.DtResultados - GvImpuestosLocales2.DataBind() - - GvImpuestosLocales2.Enabled = False - GvImpuestosLocales2.Visible = True - End If - End If - - 'Carga Totales - ViewState("TipoDoctoDevolucion") = drv("TipoDocto").ToString - TxtSubTotal.Text = drv("SubTotal").ToString.FormatoNumero(2) - LblDescuentos.Text = drv("Descuento").ToString.FormatoNumero(2) - LblAmortizacion.Text = drv("Amortizacion").ToString.FormatoNumero(2) - TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) - TxtIVA.Text = drv("IVA").ToString.FormatoNumero(2) - TxtRetIVA.Text = drv("RetIVA").ToString.FormatoNumero(2) - TxtRetISR.Text = drv("RetISR").ToString.FormatoNumero(2) - TxtTotal.Text = drv("Total").ToString.FormatoNumero(2) - TotalOriginal = Math.Round(drv("Total").ToString.ToDouble, 2) - HdnVentaSaldo.Value = drv("Total").ToString - TxtMotivoDescuento.Text = drv("MotivoDescuento").ToString - TxtObsFact.Text = drv("Observaciones").ToString - DdlMoneda.SelectedValue = drv("CveMoneda").ToString - CambiaMoneda() - TxtTipoCambio.Text = drv("TipoCambio").ToString - DdlVendedor.SelectedValue = drv("CveVendedor").ToString - CvePAC = drv("CvePAC").ToString.ToEntero - - DdlUsoCFDI.SelectedValueExist(drv("CveUsoCFDI").ToString) - DdlMetodoPago33.SelectedValueExist(drv("CveMetodoPago33").ToString) - CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) - DdlFormaPago33.SelectedValueExist(drv("CveFormaPago33").ToString) - - DdlTipoComprobante.SelectedValueExist(drv("TipoDocto").ToString) - DdlTipoComprobante.Enabled = False - - HdnIVAOriginal.Value = TxtIVA.Text - HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString - HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) - - 'JJMQ 20160506: Se agrego para la validacion de pago de contado. - CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") - - If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then - DdlVendedor.Enabled = False - End If - CveContrato = drv("CveContrato").ToString.ToEntero - TabAlmacen.Enabled = False - TabDetalleVentas.Enabled = False - TabComplementos.Enabled = False - 'HplDownPDF.Visible = True - 'HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}", CveVenta))) - Updatetabs.Update() - UpPS.Update() - UpContado.Update() - - If CveDevolucion > 0 Then - HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString - 'CALCULA IMPUESTOS LOCALES CON LOS DATOS DEL CLIENTE AL MOMENTO DE LA NUEVA FACTURA NO LA VIEJA - 'CalculaTotalesImpuestosLocales() - 'CalculaTotales(CBool(ViewState("RetIVAFletes"))) - CalculaTotalesVenta() ' al hacer una refacturación que regenere los importes, sino vienen correctos - ''CARGA IMPUESTOS LOCALES DE LA VENTA ANTERIOR - 'If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then - ' If ObjVentas.DtResultados.Rows.Count > 0 Then - - ' GvImpuestosLocales2.DataSource = ObjVentas.DtResultados - ' GvImpuestosLocales2.DataBind() - - ' GvImpuestosLocales2.Enabled = False - ' GvImpuestosLocales2.Visible = True - ' End If - 'End If - - 'cuando es refacturacion, la fecha de pago debe de ser la misma - If UsuarioActual.Empresa.Funcionalidad(526) = "1" Then - ' Dim ObjVenta As New ClsVentas - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - TxtFechaPago.Text = ObjVentas.DtResultados(0)("FechaVencimiento").ToString.ToDate.ToShortDateString - End If - End If - 'ObjVenta.Dispose() - Else - TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString - End If - - CreaObjetosVentaDevolucion() - End If - TabComplementos.Enabled = True - End If - End If - - If OVenta Is Nothing Then - ObjVentas.Dispose() - End If - End Sub - Private Sub CargaSucursales() - If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.Enabled = False : DdlSubProyectoEjecucion.Enabled = False : DdlSubProyectoCobranza.Enabled = False - End Sub - - Private Sub CargaMetodosPago() - - 'FACTURACION 3.3 - - DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago - DdlMetodoPago33.DataBind() - DdlMetodoPago33.SelectedValue = "3" - - CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) - - 'End If - - End Sub - Private Sub CargaFormaPago(CveMetodoPago As Integer) - 'FACTURACION 3.3 - - Dim dtt As DataTable = Nothing - If CveMetodoPago > 0 Then - dtt = GlobalDTVtaFormaPago.FiltraParametros(If(CveMetodoPago = 1, " CveFormaPago <> 20 ", "CveFormaPago = 20")) - Else - dtt = GlobalDTVtaFormaPago - End If - DdlFormaPago33.Items.Clear() - 'DdlFormaPago33.ClearSelection() - 'DdlFormaPago33.DataBind() - DdlFormaPago33.DataSource = dtt - DdlFormaPago33.SelectedValue = dtt.FiltroPrimeroValor("CveFormaPago", "") - DdlFormaPago33.DataBind() - 'End If - End Sub - Private Sub CargaUsoCFDI() - DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica) - DdlUsoCFDI.DataBind() - End Sub - Private Sub CargaTiposRelacion() - DdlTiposRelacion.DataSource = GlobalDTVtaTiposRelacion - DdlTiposRelacion.DataBind() - DdlTiposRelacion.Items.Insert(0, New ListItem("-", "-1")) - End Sub - Private Sub CargaFormaEntrega() - TrFormaEntrega.Visible = True - DdlFormaEntrega.DataSource = GlobalDTVtaCondicionesEntrega(UsuarioActual.CveEmpresa) - DdlFormaEntrega.DataBind() - DdlFormaEntrega.Items.Insert(0, New ListItem("Seleccione", "-1")) - End Sub - Private Sub CargaMonedas() - DdlMoneda.DataSource = GlobalDTMonedas - DdlMoneda.DataBind() - - End Sub - Private Sub CargaProyecto() - Dim CveSubProyecto As Integer = 0 - Dim dtt As DataTable = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) - - DdlProyecto.DataSource = dtt - DdlProyecto.DataBind() - - DdlProyectoPyME.DataSource = dtt - DdlProyectoPyME.DataBind() - - CveSubProyecto = GetSubProyectoSucursal() - - CargaSubProyecto(CveSubProyecto) - - End Sub - Private Function GetSubProyectoSucursal() As Integer - Dim Retorno As Integer = 0 - - Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") - 'Dim dr As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") - - 'si hay un proyecto relacionado con el subproyecto - If dr IsNot Nothing AndAlso dr("CveSubProyecto").ToString.ToEntero > 0 Then - DdlProyecto.SelectedValueExist(dr("CveProyecto")) - Retorno = dr("CveSubProyecto").ToString.ToEntero - End If - - Return Retorno - - End Function - Private Sub CargarAlmacenes() - - If CveVenta > 0 Then - DivAlmacen.Visible = False - Else - ddlAlmacen.Items.Clear() - ddlAlmacen.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}") - ddlAlmacen.Items.Insert(0, New ListItem(" Seleccione ", "-1")) - ddlAlmacen.SelectedValue = "-1" - ddlAlmacen.DataBind() - If GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").Rows.Count > 0 Then - ddlAlmacen.SelectedValueExist(UsuarioActual.CveAlmacen) - End If - End If - - 'SI TIENE CONTRATO NO SE MUEVE - If Not CveContrato > 0 Then - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (4,10)") - DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1")) - DdlAlmacenAsignado.SelectedValue = "-1" - DdlAlmacenAsignado.DataBind() - DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").ToString.ToEntero) - End If - - If CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}") - DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1")) - DdlAlmacenAsignado.SelectedValue = "-1" - DdlAlmacenAsignado.DataBind() - DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString.ToEntero) - End If - - UpINV.Update() - End Sub - Private Sub CargaSubProyecto(Optional CveSubProyecto As Integer = -1) - DdlSubProyecto.Items.Clear() - DdlSubProyecto.SelectedValue = Nothing - If DdlProyecto.SelectedValue.ToEntero > 0 Then - DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) - End If - DdlSubProyecto.DataBind() - DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) - If CveSubProyecto > 0 Then DdlSubProyecto.SelectedValueExist(CveSubProyecto) - End Sub - - Private Sub CargaEmpresaCRM(CveEmpresaCRM As Integer) - Dim ObjCRM As New ClsCRM - If ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa, CveEmpresaCRM) Then - If ObjCRM.DtResultados.Rows.Count > 0 Then - ViewState("CveCliente") = IIf(ObjCRM.DtResultados.Rows(0)("CveCliente").ToString().ToEntero() > 0, ObjCRM.DtResultados.Rows(0)("CveCliente"), -1) - HdnCveCliente.Value = CveCliente.ToString() - If (CveCliente > 0) Then - CargaCliente(CveCliente) - VerificarContrato(True) - - 'DESACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto disabled") - TxtCodigo.ReadOnly = True - - UpCliente.Visible = True - UpEmpresaCRM.Visible = False - Else - LblEmpresaCRM.Text = ObjCRM.DtResultados.Rows(0)("Empresa").ToString - LblRFCCRM.Text = ObjCRM.DtResultados.Rows(0)("RFC").ToString - LblMedioCaptacionCRM.Text = ObjCRM.DtResultados.Rows(0)("MedioCaptacion").ToString - ChkEnviarFactura.Checked = False - ChkEnviarFactura.Visible = False - LblEnviarMail.Visible = False - - UPCondicionesPago.Visible = True - UpCliente.Visible = False - UpEmpresaCRM.Visible = True - End If - - DdlVendedor.SelectedValueExist(ObjCRM.DtResultados.Rows(0)("CveVendedorAsignado").ToString) - DdlVendedor.Enabled = False - LbAgregar.Enabled = True - End If - End If - ObjCRM.Dispose() - End Sub - Private Sub CargaCliente(CveCliente As Integer, Optional Estatus As Integer = -1) - - - - RBLPago.Items(0).Enabled = True - - Dim ObjCliente As New ClsClientes() - - If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus, TipoCliente:=-1) Then - If ObjCliente.DtResultados.Rows.Count > 0 Then - TxtCodigo.Text = ObjCliente.Codigo - DdlFormaEntrega.SelectedValueExist(ObjCliente.DtResultados(0)("CveCondicionEntrega").ToString) - LblCliente.Text = String.Format("{1}", CveCliente, ObjCliente.Nombre) - ViewState("NombreCliente") = ObjCliente.Nombre - LtlCliente.Text = ObjCliente.Nombre - ViewState("RequiereOC") = ObjCliente.RequiereOC - EnviarCorreoCliente = ObjCliente.EnviarFactura - EstatusCliente = ObjCliente.Estatus - - ClienteEsDistribuidor = Boolean.Parse(ObjCliente.DtResultados.Rows(0)("EsDistribuidor").ToString) - - If EstatusCliente = False And Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") And (CveVenta <= 0 Or EsCreaApartirDe) Then - Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) - End If - - 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE - If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then - ChkEnviarFactura.Checked = False - ChkEnviarFactura.Visible = False - LblEnviarMail.Visible = False - Else - ChkEnviarFactura.Visible = True - ChkEnviarFactura.Checked = EnviarCorreoCliente - LblEnviarMail.Visible = True - End If - - ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail) - ViewState("MailCC") = ObjCliente.NotificarA - LblDireccion.Text = ObjCliente.Direccion - LblColonia.Text = ObjCliente.Colonia - LblCiudad.Text = ObjCliente.Ciudad - LblEstado.Text = ObjCliente.Estado - LblCP.Text = ObjCliente.CP - LblRFC.Text = ObjCliente.RFC - LblTelefono.Text = ObjCliente.Telefono - LblRetIVA.Text = ObjCliente.RetIVA.ToString.FormatoNumero(5) - LblRetISR.Text = ObjCliente.RetISR.ToString.FormatoNumero(5) - ViewState("ClienteRetIVA") = ObjCliente.RetIVA / 100 - ViewState("ClienteRetISR") = ObjCliente.RetISR / 100 - - ViewState("RetIVAFletes") = ObjCliente.RetieneIVAFletes - If ObjCliente.RetieneIVAFletes Then - TrRetIVA.Style.Add("display", "") - UsuarioActual.Empresa.MostrarRetIVA = True - End If - - - - - ViewState("Vendedor") = ObjCliente.Vendedor - ViewState("CtaContable") = ObjCliente.CuentaContable - ViewState("IdCtaContClientes") = ObjCliente.IdCtaContClientes - ViewState("CveCuentaClientes") = ObjCliente.CveCuentaClientes - ViewState("IdCtaContMonedaExtranjera") = ObjCliente.IdCtaContMonedaExtranjera - ViewState("IdCtaContComplementaria") = ObjCliente.IdCtaContComplementaria - ViewState("IdCtaContAnticipos") = ObjCliente.IdCtaContAnticipos - ViewState("CveCuentaAnticipos") = ObjCliente.CveCuentaAnticipos - ViewState("IdCtaContRetIVA") = ObjCliente.IdCtaContRetIVA - ViewState("CveCuentaRetIVA") = ObjCliente.CveCuentaRetIVA - ViewState("IdCtaContRetISR") = ObjCliente.IdCtaContRetISR - ViewState("CveCuentaRetISR") = ObjCliente.CveCuentaRetISR - ViewState("CodCliente") = ObjCliente.Codigo - - ViewState("CliNoExt") = ObjCliente.NoExt - ViewState("CliNoInt") = ObjCliente.NoInt - ViewState("CliLocalidad") = If(ObjCliente.Localidad.Trim.Length = 0, ObjCliente.Ciudad.Trim, ObjCliente.Localidad.Trim) - ViewState("CliPais") = ObjCliente.Pais - ImprimeNombreSucursal = ObjCliente.ImprimeNombreSucursal - 'ViewState("NumCtaPago") = ObjCliente.NumCtaPago - ViewState("ClienteDesglosaIEPS") = ObjCliente.DesglosaIEPS - If Not ClienteDesglosaIEPS Then - DivClienteMsg.Visible = True - LtlClienteMsg.Text = "Cálculo sin desglose de IEPS" - End If - - Dim dr As DataRow = Nothing - dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal = 1 And Estatus = 'Activo' AND CveEmpresa = " & UsuarioActual.CveEmpresa) - If dr IsNot Nothing Then - ViewState("MatCalle") = dr("Calle") - ViewState("MatNoExt") = dr("NoExt") - ViewState("MatNoInt") = dr("NoInt") - ViewState("MatColonia") = dr("Colonia") - ViewState("MatLocalidad") = dr("Localidad") - ViewState("MatMunicipio") = dr("Municipio") - ViewState("MatEstado") = dr("Estado") - ViewState("MatPais") = dr("Pais") - ViewState("MatCP") = dr("CP") - End If - - 'HABILITA LA OPCION DE DIRECCION DE ENVIO - If UsuarioActual.CveEmpresa.Contiene(1, 72, 119) Then - trDireccionEnvio.Visible = True - CargaDireccionesEnvio() - End If - - If CveCliente = 239903 AndAlso UsuarioActual.CveEmpresa = 119 Then - DdlMetodoPago33.Enabled = False - ObjCliente.CveMetodoPago = 1 ' PUE, y que no se pueda modificar - Else - DdlMetodoPago33.Enabled = True - End If - - If CveVenta <= 0 Or EsCreaApartirDe Or NuevaFactura = 1 Then - CveMetodoPagoCliente = ObjCliente.CveMetodoPago - - - DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33) - CambiaMetodoPago33() - DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) - DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI) - End If - - PlazoCobranza = ObjCliente.PlazoCobranza - PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision - - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then - TxtFechaPago.ReadOnly = True - Calendario.Enabled = False - imgCalendario.Visible = False - End If - - 'funcionalidad EnviarSMSTimbrado - If CveVenta <= 0 And UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue = "Ing" Then - If ObjCliente.CobranzaTelefono <> "" Then - LblMensaje.Text = $"Se enviará mensaje SMS a {ObjCliente.CobranzaTelefono}" - Else - LblMensaje.Text = $"El Cliente no tiene teléfono para envío SMS " - End If - LblMensaje.Visible = True - End If - - 'If Not ObjCliente.RFC = "XAXX010101000" Then - ' TxtNumCtaPago.Text = ObjCliente.NumCtaPago - 'End If - - 'Complementos - - - 'COMERCIO EXTERIOR - ViewState("AplicaComercioExterior") = ObjCliente.AplicaComercioExterior - ViewState("CveTipoOperacion") = ObjCliente.CveTipoOperacion - ViewState("CvePedimento") = ObjCliente.CvePedimento - ViewState("CveIncoterm") = ObjCliente.CveIncoterm - - LblTipoOperacion.Text = ObjCliente.ClaveSATTipoOperacionDescripcion - LblClavePedimento.Text = ObjCliente.ClaveSATPedimentoDescripcion - - If ObjCliente.AplicaComercioExterior Then - DdlSATMotivoTraslado.DataSource = GlobalDTSATMotivoTraslado - DdlSATMotivoTraslado.DataBind() - DdlSATMotivoTraslado.SelectedValueExist(ObjCliente.CveMotivoTraslado) - DdlIncoterm.Items.Clear() - DdlIncoterm.DataSource = GlobalDTIncoterm() - DdlIncoterm.DataBind() - DdlIncoterm.SelectedValueExist(ObjCliente.CveIncoterm) - CargaPais() - DdlComExtPais.SelectedValueExist(ObjCliente.CvePais) - CargaEstado() - DdlComExtEstado.SelectedValueExist(ObjCliente.CveEstado) - If ObjCliente.ClaveSATPais = "MEX" Then - CargaMunicipio() - CargaColonia() - Else - If ObjCliente.ClaveSATPais.Contiene("USA", "CAN") Then - DdlComExtEstado.Visible = True - Else - TxtComExtEstado.Visible = True : DdlComExtEstado.Visible = False - End If - TxtComExtMunicipio.Text = ObjCliente.ComExtMunicipio - TxtComExtColonia.Text = ObjCliente.ComExtColonia - TxtComExtMunicipio.Visible = True : TxtComExtColonia.Visible = True - - End If - TxtNumRegIdTrib.Text = ObjCliente.NumRegIdTrib - TxtDestinatarioNombre.Text = ObjCliente.Nombre - TxtComExtCalle.Text = ObjCliente.Direccion - TxtComExtNumero.Text = ObjCliente.NoExt - TxtComExtCP.Text = ObjCliente.CP - - End If - - 'FEMSA - ViewState("AplicaFEMSA") = ObjCliente.AplicaFEMSA - TxtFEMSA_NumSociedad.Text = ObjCliente.FEMSA_NumSociedad - TxtFEMSA_NumProveedor.Text = ObjCliente.FEMSA_NumProveedor - TxtFEMSA_Mail.Text = ObjCliente.FEMSA_Mail - 'DETALLISTA - ViewState("AplicaDetallista") = ObjCliente.AplicaDetallista - TxtDet_GLNComprador.Text = ObjCliente.Detallista_GLNComprador - TxtDet_Departamento.Text = ObjCliente.Detallista_Departamento - TxtDet_GLNVendedor.Text = ObjCliente.Detallista_GLNVendedor - TxtDet_NumProv.Text = ObjCliente.Detallista_NumProveedor - - Txt7ElevenNumProveedor.Text = ObjCliente.SevenEleven_NumProveedor.Trim - - ViewState("AplicaFord") = ObjCliente.AplicaFord - TxtFordGSDB.Text = ObjCliente.Ford_GSDB - - 'SELECIONAMOS VENDEDOR - SI ESTA EN MODO EDICIÓN SE QUEDA EL VENDEDOR ORIGINAL - If Not ModalidadEdicion Then - If ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero > 0 Then - DdlVendedor.SelectedValueExist(ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero) - End If - - 'SI EL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO - If Not DdlVendedor.SelectedValue.ToEntero > 0 Then - DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) - End If - End If - - If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then - DdlVendedor.Enabled = False - End If - - UpFacturar.Update() - - 'SI LA VENTA YA ESTA REGISTRADA NO DEBE HABILITAR ACCIONES - If CveVenta <= 0 Then - LnkRemisiones.Visible = If(UsuarioActual.TienePermisoProceso(199), True, False) : LnkOCs.Visible = True : LnkCotizaciones.Visible = True : LnkPedido2SinFacturar.Visible = True : InicializaAplicarNCMasiva() - End If - - If UsuarioActual.Empresa.CvePlataforma = 2 Then LnkOCs.Visible = False - If UsuarioActual.Empresa.UsaInventarios Then - RblTipo.Items.Remove(RblTipo.Items.FindByValue("1")) - RblTipo.Items.Remove(RblTipo.Items.FindByValue("2")) - End If - UpnTools.Update() - 'UpRemisionesFacturas.Update() - - If Not CveVenta > 0 Then - If ObjCliente.DtResultados.Rows.Count > 0 Then - If UsuarioActual.TienePermisoProceso(152) Then - DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto) - DdlSubProyectoDatos.Enabled = False - Else - DdlSubProyectoDatos.SelectedValueExist(ObjCliente.CveSubProyecto) - End If - 'RECARGA LOS VALORES DE LA SUCURSAL - CambiaSucursal() - UpParametros.Update() - End If - End If - - DdlSucursalCliente.Items.Clear() - If ObjCliente.GetSucursales(CveCliente) Then - DdlSucursalCliente.DataSource = ObjCliente.DtResultados - If ObjCliente.DtResultados.Rows.Count > 0 Then - trsucursalciente.Visible = True - Else - trsucursalciente.Visible = False - End If - Else - trsucursalciente.Visible = False - DdlSucursalCliente.DataSource = Nothing - End If - DdlSucursalCliente.Items.Insert(0, New ListItem("Matriz", "-1")) - DdlSucursalCliente.DataBind() - - 'CargaFolios() - - CargaDatosEstimaciones(CveCliente) - - If ObjCliente.GetClienteImpuestosLocales(CveCliente) Then - 'se cargan impuestos locales - Dim DtClienteImpuesto As DataTable = ObjCliente.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") - - If DtClienteImpuesto IsNot Nothing AndAlso DtClienteImpuesto.Rows.Count > 0 Then - - ' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear() - TmpDTImpuestos = DtClienteImpuesto - - GvImpuestosLocales2.DataSource = TmpDTImpuestos - GvImpuestosLocales2.DataBind() - - - If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then - TrOtros.Visible = True - GvImpuestosLocales2.Visible = True - TrOtros.Style.Add("display", "") - Else - TrOtros.Visible = False - GvImpuestosLocales2.Visible = False - End If - DtClienteImpuesto.Dispose() - - End If - UpImpuestos.Update() - - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Cot") Then - TrAtencionA.Visible = True - TrDireccion.Visible = False - TrCiudad.Visible = False - TrRFC.Visible = False - tdTelefonoGen.Visible = False - tdTxtTelefonoGen.Visible = False - ElseIf ObjCliente.RFC = "XAXX010101000" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ret") Then - TrAtencionA.Visible = True - TrDireccion.Visible = False - TrCiudad.Visible = False - TrRFC.Visible = False - tdTelefonoGen.Visible = True - tdTxtTelefonoGen.Visible = True - Else - 'TrAtencionA.Visible = False - TrDireccion.Visible = True - TrCiudad.Visible = True - TrRFC.Visible = True - tdTelefonoGen.Visible = False - tdTxtTelefonoGen.Visible = False - TxtAtencionA.Text = "" - TxtTelefonoGenerico.Text = "" - End If - - TrAtencionA.Visible = True - tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") - tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") - - - LbAgregar.Enabled = True - LnkAgregarPyME.Enabled = True - - CargarAlmacenes() - - CargaDocumentacionCliente() - - If UsuarioActual.CveEmpresa.Contiene(72, 80, 1, 119) Then - BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)});" - BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") - BtnEmitirImprimir.Attributes.Add("data-popout", "true") - BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") - BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") - BtnEmitirImprimir.Attributes.Add("data-html", "true") - End If - - 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO - If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO - BtnEmitirImprimir.Visible = True - TrVistaPrevia.Visible = True - 'Else - ' BtnEmitirImprimir.Visible = EstatusCliente - ' TrVistaPrevia.Visible = EstatusCliente - End If - - TrVistaPrevia.Visible = True - - If Not (ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem") Then - CargaRestriccionesCreditoCliente(True) - End If - - - UpFacturar.Update() - UpEstatus.Update() - UpPS.Update() - UpParametros.Update() - UPCondicionesPago.Update() - UpDetalle.Update() - UpComplementos.Update() - UpCliente.Update() - UpAplicarNC.Update() - UpINV.Update() - UPPVentas.Update() - UPComplementosSAT.Update() - UpnTools.Update() - Else - Alert("Ocurrió un error al cargar los datos del cliente. Por favor vuelva a intentar.", TipoMensaje.MsgError) - End If - End If - ObjCliente.Dispose() - - If CveCliente > 0 Then CargaAnticipos(CveCliente) : UpAnticipos.Update() - - - If RequiereOC Then - Dim Documentacion As String = "" - 'RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });", "ModalArchivos") - Dim Count = 0 - For Each GvRow As GridViewRow In GvDocumentosCliente.Rows - If GvRow.DataKey("Orden").ToEntero = 1 Then - IndexDocumentoCliente = Count - Documentacion = GvRow.DataKey("Documentacion").ToString - AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString - Exit For - End If - Count = +1 - Next - LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion - BtnModalClienteDocumentoCancelar.Visible = False - - If CveVenta <= 0 Then - LnkUploadDocumentacionCliente.Visible = True - End If - - UpModalTitleUploadDocumentoCliente.Update() - UpModalButtonUploadDocumentoCliente.Update() - UPObservaciones.Update() - ' RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});", "modalOC") - End If - - End Sub - - Private Sub CargaRestriccionesCreditoCliente(Optional Alertas As Boolean = False) - Dim ObjCliente As New ClsClientes() - If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa) Then - If ObjCliente.DtResultados.Rows.Count > 0 Then - If UsuarioActual.CveEmpresa.Contiene(72, 119) AndAlso ObjCliente.DtResultados.Rows(0)("PermiteCredito").ToString = "False" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") AndAlso CveVenta < 1 Then - RBLPago.SelectedValue = "2" - RBLPago.Items(0).Enabled = False - RBLPago_SelectedIndexChanged(Nothing, Nothing) - If UsuarioActual.CveEmpresa.Contiene(119) AndAlso Not UsuarioActual.TienePermisoProceso(268) Then - DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") - DdlTipoComprobante.SelectedValue = "PA" - TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString - 'si llegó por la opción de cotización no debe de restringuir - If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot" - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - End If - UPCondicionesPago.Update() - ElseIf UsuarioActual.CveEmpresa.Contiene(72, 119) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "Cot", "PA") AndAlso CveVenta < 1 Then - RBLPago.SelectedValue = "1" - RBLPago_SelectedIndexChanged(Nothing, Nothing) - UPCondicionesPago.Update() - Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero) - - If CreditoDispo > 0 Then - TrCreditoDisponible.Visible = True - LblCreditoDisponible.Text = CreditoDispo.FormatoNumero - If PorcentajeCredito > 80 Then TrPorcentajeCredito.Visible = True : LblPorcentajeCredito.Text = $"{PorcentajeCredito.FormatoNumero}%" - If UsuarioActual.CveEmpresa = 119 AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "PA") Then - If LblRFC.Text.Trim <> "XAXX010101000" Then - Dim Vta As New ClsVentas - Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) - Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

    {0}", Vta.SerieVenta) - Vta.Dispose() - If Opcion > 0 Then - 'si la cotización no debe de existir este canddado - If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) - 'RBLPago.SelectedValue = "2" - 'RBLPago.Items(0).Enabled = False - RBLPago_SelectedIndexChanged(Nothing, Nothing) - UPCondicionesPago.Update() - DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") - DdlTipoComprobante.SelectedValue = "PA" - TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString - 'si llegó por la opción de cotización no debe de restringuir - If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot" - 'quito remisión y factura - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) - If Opcion = 1 Then - BtnEmitirImprimir.Visible = False - BtnsFacturar.Visible = False - BtnGenerarRemision.Visible = False - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - LnkOCs.Visible = False - End If - Else - ' el cliente tiene crédito disponible, no tiene bloqueo - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PA")) - - If UsuarioActual.TienePermisoProceso(60) Then DdlTipoComprobante.SelectedValueExistInsert("Ing", "Ingresos") 'puede facturar - If UsuarioActual.TienePermisoProceso(199) Then DdlTipoComprobante.SelectedValueExistInsert("Rem", "Remisión") ' puede remisionar - DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento) - - TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString - End If - Else - 'que no de crédito, solo contado - RBLPago.SelectedValue = "2" - RBLPago.Items(0).Enabled = False - End If - End If - Else - - If UsuarioActual.CveEmpresa = 119 AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ant", "PA") Then - Dim Vta As New ClsVentas - Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) - Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

    {0}", Vta.SerieVenta) - Vta.Dispose() - If Opcion > 0 Then - If Opcion = 1 Then - BtnEmitirImprimir.Visible = False - End If - If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) - Else - If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia) - End If - - 'RBLPago.SelectedValue = "2" - 'RBLPago.Items(0).Enabled = False - RBLPago_SelectedIndexChanged(Nothing, Nothing) - UPCondicionesPago.Update() - DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") - DdlTipoComprobante.SelectedValue = "PA" - TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString - 'si llegó por la opción de cotización no debe de restringuir - If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot" - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) - BtnsFacturar.Visible = False - BtnGenerarRemision.Visible = False - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - LnkOCs.Visible = False - End If - End If - UPPCreditoDisponible.Update() - ElseIf UsuarioActual.CveEmpresa.Contiene(119, 1) AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso CveVenta > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Pd2", "Cot") Or (DdlTipoComprobante.SelectedValue = "Rem" And ModalidadEdicion And ViewState("CveClienteAnterior").ToString.ToEntero > 0 And LblRFC.Text.Trim <> "XAXX010101000")) Then - Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero) - If CreditoDispo > 0 Then - Dim Vta As New ClsVentas - Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) - Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

    {0}", Vta.SerieVenta) - Vta.Dispose() - If Opcion > 0 Then - If ModalidadEdicion AndAlso ViewState("CveCliente").ToString.ToEntero <> ViewState("CveClienteAnterior").ToString.ToEntero And DdlTipoComprobante.SelectedValue = "Rem" And ViewState("CveClienteAnterior").ToString.ToEntero > 0 And LblRFC.Text.Trim <> "XAXX010101000" Then - ViewState("CveCliente") = ViewState("CveClienteAnterior").ToString.ToEntero - ObjCliente.Dispose() - CargaCliente(ViewState("CveCliente").ToString.ToEntero) - If Opcion > 0 Then - If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) - Else - If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia) - End If - BtnEmitirImprimir.Visible = False - BtnVistaPrevia.Visible = False - UpFacturar.Update() - Exit Sub - ElseIf DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso EsCreaApartirDe Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) - BtnGenerarRemision.Visible = False - BtnGenerarOS.Visible = False - BtnEmitirImprimir.Visible = True - BtnsFacturar.Visible = False - Else - - If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then - BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False) - End If - BtnGenerarRemision.Visible = False - BtnGenerarOS.Visible = False - BtnEmitirImprimir.Visible = False - BtnsFacturar.Visible = False - If ViewState("CveCliente").ToString.ToEntero <> ViewState("CveClienteAnterior").ToString.ToEntero Then - If Opcion > 0 Then - If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) - Else - If Alertas Then Alert("El cliente tiene límite de crédito agotado.", TipoMensaje.MsgAdvertencia) - End If - End If - End If - Else - BtnGeneraAutorizacion.Visible = False - If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then - BtnGenerarRemision.Visible = If(CveEstatus <> 21, True, False) - End If - End If - Else - BtnGenerarRemision.Visible = False - If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then - BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False) - End If - End If - End If - End If - End If - ObjCliente.Dispose() - End Sub - - - Private Sub CargaClienteSucursal(CveClienteSuc As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing) - Dim ObjCliente As New ClsClientes - If CveClienteSuc > 0 Then - If ObjCliente.GetSucursales(CveCliente, CveClienteSuc) Then - If ObjCliente.DtResultados.Rows.Count > 0 Then - Dim Correo = ObjCliente.DtResultados.Rows(0)("Correo").ToString - If Correo.Trim.Length > 0 Then - ViewState("Mail") = Correo - End If - LblDireccion.Text = ObjCliente.DtResultados.Rows(0)("Direccion").ToString - LblColonia.Text = ObjCliente.DtResultados.Rows(0)("Colonia").ToString - LblCiudad.Text = ObjCliente.DtResultados.Rows(0)("Ciudad").ToString - LblEstado.Text = ObjCliente.DtResultados.Rows(0)("Estado").ToString - 'TxtNumCtaPago.Text = ObjCliente.DtResultados.Rows(0)("NumCtaPago").ToString - LblTelefono.Text = ObjCliente.DtResultados.Rows(0)("Telefono").ToString - LblCP.Text = ObjCliente.DtResultados.Rows(0)("CP").ToString - ViewState("CliLocalidad") = ObjCliente.DtResultados.Rows(0)("Localidad").ToString - ViewState("CliPais") = ObjCliente.DtResultados.Rows(0)("Pais").ToString - ViewState("CliNoExt") = ObjCliente.DtResultados.Rows(0)("NoExt").ToString - ViewState("CliNoInt") = ObjCliente.DtResultados.Rows(0)("NoInt").ToString - DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString) - ViewState("CveClienteSucursal") = ObjCliente.DtResultados(0)("CveClienteSucursal").ToString - ViewState("CliCorreoCot") = ObjCliente.DtResultados.Rows(0)("CorreoCotizacion").ToString - - If ObjCliente.DtResultados.Rows(0)("Estatus").ToString <> "Activo" Then - RBLPago.Items(0).Enabled = False - Alert("La Sucursal/Departamento del cliente se encuentra inactivo", TipoMensaje.MsgAdvertencia) - Else - RBLPago.Items(0).Enabled = True - Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero, ObjVentas) - - TrCreditoDisponible.Visible = True - LblCreditoDisponible.Text = CreditoDispo.FormatoNumero - UPPCreditoDisponible.Update() - UpParametros.Update() - End If - - If CveVenta <= 0 Then + ObjPVenta.AddVtaCortes(Now, TxtDineroCaja.Text.ToDecimal, UsuarioActual.CveUsuario, TxtDescripcionCaja.Text, UsuarioActual.CveEmpresa) + CveCorte = ObjPVenta.CveCorte + LblEstatusCaja.Text = Now.ToShortDateString + TrEstatusCaja.Visible = True + LkbEstadodeCaja.Visible = True + LkbIngreso.Visible = True + LkbRetiro.Visible = True + BtnIniciarTurno.Visible = False + + ObjPVenta.Dispose() + + RegistraScript("$('#DivCorteDeCaja').hide();") + End Sub + Private Sub LkbEstadodeCaja_Click(sender As Object, e As EventArgs) Handles LkbEstadodeCaja.Click + CargaDatosCorte() + CargaVentasPago() + CargaEntradasSalidas() + RegistraScript("$('#DivEstadoCaja').modal()") + End Sub + Private Sub CargaDatosCorte() + Dim ObjPVenta As New ClsPuntoVenta + Dim Total As Double + + If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then + If ObjPVenta.DtResultados.Rows.Count > 0 Then + + Total = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble + ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble + ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble + ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble - ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble + DineroCaja = Total + LblEfectivoEsperado.Text = Total.FormatoNumero(2) + + Dim Dt As New DataTable + + Dt.Columns.Add("Descripcion", GetType(String)) + Dt.Columns.Add("Importe", GetType(Decimal)) + + Dim Dr1 = Dt.NewRow + Dr1("Descripcion") = "Fondo de Caja" + Dr1("Importe") = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble + Dt.Rows.Add(Dr1) + + Dim Dr2 = Dt.NewRow + Dr2("Descripcion") = "Ventas en Efectivo" + Dr2("Importe") = ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble + Dt.Rows.Add(Dr2) + + Dim Dr3 = Dt.NewRow + Dr3("Descripcion") = "Propinas" + Dr3("Importe") = ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble + Dt.Rows.Add(Dr3) + + Dim Dr4 = Dt.NewRow + Dr4("Descripcion") = "Entradas" + Dr4("Importe") = ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble + Dt.Rows.Add(Dr4) + + Dim Dr5 = Dt.NewRow + Dr5("Descripcion") = "Salidas" + Dr5("Importe") = ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble + Dt.Rows.Add(Dr5) + + Dim Dr6 = Dt.NewRow + Dr6("Descripcion") = "Total" + Dr6("Importe") = Total + Dt.Rows.Add(Dr6) + + GvDineroCaja.DataSource = Dt + GvDineroCaja.DataBind() + UpDineroCaja.Update() + UpTerminarCorte.Update() + + End If + End If + + ObjPVenta.Dispose() + + End Sub + Private Sub CargaVentasPago() + Dim ObjPVenta As New ClsPuntoVenta + + If ObjPVenta.GetVta_MetodosPago(CveCorte) Then + If ObjPVenta.DtResultados.Rows.Count > 0 Then + GvMetodosPago.DataSource = ObjPVenta.DtResultados + GvMetodosPago.DataBind() + UpMetodosPago.Update() + End If + End If + + ObjPVenta.Dispose() + End Sub + Private Sub CargaEntradasSalidas() + Dim ObjPVenta As New ClsPuntoVenta + + 'Salida + If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 0) Then + If ObjPVenta.DtResultados.Rows.Count > 0 Then + GvEgresos.DataSource = ObjPVenta.DtResultados + GvEgresos.DataBind() + UpEgresos.Update() + End If + End If + + 'Entrada + If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 1) Then + If ObjPVenta.DtResultados.Rows.Count > 0 Then + GvIngresos.DataSource = ObjPVenta.DtResultados + GvIngresos.DataBind() + UpIngresos.Update() + End If + End If + + ObjPVenta.Dispose() + End Sub + Private Sub BtnAceptarIE_Click(sender As Object, e As EventArgs) Handles BtnAceptarIE.Click + Dim ObjPVenta As New ClsPuntoVenta + If TxtCantidadIE.Text.ToEntero > 0 Then + If ObjPVenta.AddVta_MovimientosCajas(CveCorte, UsuarioActual.CveUsuario, TxtCantidadIE.Text.ToDouble, TxtDescripcionIE.Text, HdnTipoMovimiento.Value.ToEntero, Now) Then + TxtCantidadIE.Text = "" + TxtDescripcionIE.Text = "" + RegistraScript("$('#DivIngresoEgreso').modal('hide')", "divingresoegreso") + Alert("El movimiento se realizó correctamente") + UpIngresoEgreso.Update() + End If + End If + ObjPVenta.Dispose() + End Sub + Private Sub BtnCerrarTurno_Click(sender As Object, e As EventArgs) Handles BtnCerrarTurno.Click + Dim ObjPVenta As New ClsPuntoVenta + If TxtEfectivoEnCaja.Text.Trim <> "" Then + If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoEnCaja.Text.ToDouble, LblDiferenciaCaja.Text.ToDouble, Now, UsuarioActual.CveEmpresa) Then + RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=CORT&CVECORTE={0}&FORMATO={1}", CveCorte, "PDF"))}'", "Imprimir") + Dim Liga = "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";" + Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga) + End If + End If + ObjPVenta.Dispose() + End Sub + Private Sub BtnCancelar_Click(sender As Object, e As EventArgs) Handles BtnCancelar.Click + Response.Redirect("~/Inicio.aspx") + End Sub + + Protected Sub BtnCerrarCaja_Click(sender As Object, e As EventArgs) + RegistraScript("$('#DivEstadoCaja').modal('hide')") + RegistraScript("$('#DivTerminarCorte').modal()", "divterminarcorte") + End Sub + Protected Sub LkbIngreso_Click(sender As Object, e As EventArgs) + CargaIngresoEgreso(1) + End Sub + Public Sub CargaIngresoEgreso(Opcion As Integer) + RegistraScript("$('#DivIngresoEgreso').modal()") + If Opcion = 1 Then + LblTituloIE.Text = "Ingreso de Efectivo: " + HdnTipoMovimiento.Value = "1" + ElseIf Opcion = 0 Then + LblTituloIE.Text = "Retiro de Efectivo: " + HdnTipoMovimiento.Value = "0" + End If + UpIngresoEgreso.Update() + End Sub + Protected Sub LkbRetiro_Click(sender As Object, e As EventArgs) + CargaIngresoEgreso(0) + End Sub +#End Region + +#Region "Contratos" + Private Sub PresionarBotonModal(Boton As String) + Try + Dim script As String = $"document.getElementById(""{Boton}"").click();" + Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.Handler, Page) + ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), Boton, script, True) + Pag = Nothing + Catch ex As Exception + End Try + End Sub + Private Sub VerificarContrato(Optional AfterPageLoad As Boolean = False) + Dim ObjContratos As New ClsContratos + + If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then + If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then + + DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'") + + If AfterPageLoad Then + RegistraScript("window.onload = function MuestraContratos() { document.getElementById(""C_BtnMostrarContrato"").click(); }") + Else + PresionarBotonModal("C_BtnMostrarContrato") + End If + + End If + End If + + ObjContratos.Dispose() + End Sub + Private Sub BtnIniciarContrato_Click(sender As Object, e As EventArgs) Handles BtnIniciarContrato.Click + DdlContratosModal.Items.Clear() + + If RblOpcionContrato.SelectedValue = "2" Then + ContratoDetalles.Visible = True + DivEstimaciones.Visible = False + + DdlContratosModal.DataSource = DtContratos + DdlContratosModal.DataBind() + DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) + + DdlContratosOC.Items.Clear() + DdlContratosOC.DataSource = DtContratos + DdlContratosOC.DataBind() + 'DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) + UPEstimaciones.Update() + + Tab.ActiveTab = TabE + TabGenerales.Enabled = False + Updatetabs.Update() + + 'ESCONDE ACCIONES + LnkRemisiones.Visible = False + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + HlAgregarExcel.Visible = False + + 'VINCULARA LAS OC QUE TENGAN CONTRATO SOLAMENTE + TieneContrato = True + LnkOCs.Visible = True + UpnTools.Update() + Else + DdlContratosOC.Items.Clear() + DdlContratosOC.DataSource = DtContratos + DdlContratosOC.DataBind() + DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) + + GvContratoDetalles.DataSource = Nothing + GvContratoDetalles.DataBind() + UpContratos.Update() + + DivEstimaciones.Visible = True + ContratoDetalles.Visible = False + UPEstimaciones.Update() + + Tab.ActiveTab = TabGenerales + TabGenerales.Enabled = True + Updatetabs.Update() + TieneContrato = False + + End If + + PresionarBotonModal("C_BtnCerrarContrato") + End Sub + Private Sub BtnCancelarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCancelarContratoDetalles.Click + DtContratos = Nothing + PresionarBotonModal("C_BtnCerrarContrato") + End Sub + Private Sub DdlContratosModal_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosModal.SelectedIndexChanged + DdlContratoModalSelectIndex() + End Sub + Protected Sub RBLTipoContrato_SelectedIndexChanged(sender As Object, e As EventArgs) + CargaContratos() + End Sub + Private Sub CargaContratos() + + Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}") + If DrContrato Is Nothing Then + Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError) + Exit Sub + End If + + LbContratoImporteTotal.Text = DrContrato("ImporteTotal").ToString.FormatoNumero + LbContratoImporteMinimo.Text = DrContrato("ImporteMin").ToString.FormatoNumero + LbContratoImporteMaximo.Text = DrContrato("ImporteMax").ToString.FormatoNumero + LtContratoImporteSaldo.Text = DrContrato("ImporteSaldo").ToString.FormatoNumero + + + Dim ObjContrato As New ClsContratos + Dim NoId As Integer = 0 + + If ObjContrato.GetContratosDetalle(DdlContratosModal.SelectedValue.ToEntero) Then + + 'SI ES CONTRATO DE CONSIGNACION DE VENTA AGARRA LAS EXISTENCIAS DEL ALMACEN + CreaConsignacionSerieDetalle() + CveAlmacenExistenciasContrato = -1 + CveAlmacenOrigenContrato = -1 + GvContratoDetalles.Columns(8).Visible = False + + If DrContrato("CveContratoTipo").ToString.Contiene("27") Then + CveAlmacenExistenciasContrato = If(DrContrato("CveAlmacenDestino").ToString.ToEntero > 0, DrContrato("CveAlmacenDestino").ToString.ToEntero, -1) + CveAlmacenOrigenContrato = If(DrContrato("CveAlmacenOrigen").ToString.ToEntero > 0, DrContrato("CveAlmacenOrigen").ToString.ToEntero, -1) + End If + + NoId = ObjContrato.DtResultados.FiltraParametros("NoIdentificacion <> ''").Rows.Count 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA + + Dim DtDetalle As DataTable = ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}") + + GvContratoDetalles.DataSource = DtDetalle 'ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}") + GvContratoDetalles.DataBind() + UpContratos.Update() + + NumeroContrato = DrContrato("NumeroContrato").ToString + DescripcionContrato = DrContrato("DescripcionContrato").ToString + NumeroLicitacion = DrContrato("NumeroLicitacion").ToString.Trim + DdlVendedor.SelectedValueExist(DrContrato("CveVendedor")) + + If DrContrato("CveSucursalCliente").ToString.ToEntero > 0 Then + DdlSucursalCliente.SelectedValueExist(DrContrato("CveSucursalCliente")) + End If + + Dim CveAlmacenDestino As Integer = DrContrato("CveAlmacenDestino").ToString.ToEntero + + If CveAlmacenDestino > 0 Then + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen IN (4, 10)") + DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlAlmacenAsignado.Items.Insert(1, New ListItem(DrContrato("Almacen").ToString, CveAlmacenDestino.ToString)) + DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString) + DdlAlmacenAsignado.DataBind() + Else + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)") + DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString) + DdlAlmacenAsignado.DataBind() + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}") + DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString) + DdlAlmacenAsignado.DataBind() + End If + + UpParametros.Update() + End If + + If NoId > 0 Then 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA + GvContratoDetalles.Columns(3).Visible = True 'NoIdentificacion + End If + + ObjContrato.Dispose() + + If CveOC > 0 Then + BtnCargarContratoDetalles.Enabled = True + For Each gvr As GridViewRow In GvContratoDetalles.Rows + gvr.FCTextBox("TxtCant").Enabled = False + Next + Dim EsValido = True + For Each Dr As DataRow In TmpDT.Rows + Dim CantidadActual = Dr("Cantidad").ToString.ToDouble + Dim CantidadDispo = 0.0 + Dim CantidadAsignada = 0.0 + For Each gvr As GridViewRow In GvContratoDetalles.Rows + If gvr.DataKey("CvePS").ToEntero = Dr("CvePS").ToString.ToEntero Then + CantidadDispo = gvr.DataKey("Cantidad").ToString.ToDouble - gvr.FCTextBox("TxtCant").Text.ToDouble + If CantidadDispo = 0 Then Continue For + CantidadAsignada = If(CantidadDispo > CantidadActual, CantidadActual, CantidadDispo) + gvr.FCTextBox("TxtCant").Text = (gvr.FCTextBox("TxtCant").Text.ToDouble + CantidadAsignada).ToString + CantidadActual = CantidadActual - CantidadAsignada + + If CantidadActual = 0 Then + Exit For + End If + + End If + Next + If CantidadActual > 0 Then + EsValido = False + Alert("No se cumple con la totalidad de la Orden de Compra. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + BtnCargarContratoDetalles.Enabled = False + Exit For + End If + Next + + If EsValido Then + BtnCargarContratoDetalles_Click(BtnCargarContratoDetalles, EventArgs.Empty) + End If + + End If + + 'LIMPIA TIPOS DOCTO + If (DdlTipoComprobante.Items.FindByValue("Ped") IsNot Nothing) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ped")) + End If + + If (DdlTipoComprobante.Items.FindByValue("PeC") IsNot Nothing) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PeC")) + End If + + If (DdlTipoComprobante.Items.FindByValue("Cot") IsNot Nothing) Then 'NO PUEDEN HACER COTIZACIÓN DE UN CONTRATO + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) + End If + + Select Case RBLTipoContrato.SelectedValue.ToEntero + Case 1 + DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) + DdlTipoComprobante.SelectedValue = "Ped" + DdlTipoComprobante.Enabled = False + Case 2 + DdlTipoComprobante.Enabled = True + DdlTipoComprobante.SelectedValueExist("Ing") + Case 3 + DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido de Consignación", "PeC")) + DdlTipoComprobante.SelectedValue = "PeC" + DdlTipoComprobante.Enabled = False + End Select + + ChkPSOC.Checked = False + CambiaTipoDocto() + UpParametros.Update() + UPEstimaciones.Update() + UPOCFactura.Update() + End Sub + Private Sub BtnCargarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCargarContratoDetalles.Click + + ''SI LA VENTA ES TIPO VENTA DE CONTRATO Y EL CONTRATO TIENE LICITACION EL CLIENTE DEBE TENER IMPUESTOS LOCALES + 'If RBLTipoContrato.SelectedValue = "2" Then + ' Dim ObjClientes As New ClsClientes + ' If NumeroLicitacion <> "" Then + ' If ObjClientes.GetClienteImpuestosLocales(CveCliente) Then + ' If Not ObjClientes.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then + ' Alert("El contrato con licitación al que se hace referencia requiere impuestos locales.", TipoMensaje.MsgAdvertencia) + ' ObjClientes.Dispose() + ' Exit Sub + ' End If + ' End If + ' End If + ' ObjClientes.Dispose() + 'End If + + + Dim DrContrato As DataRow = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue.ToEntero}") + Dim ps As New ClsInventarios + + CveContrato = DdlContratosModal.SelectedValue.ToEntero + AplicaGastoContrato = If(DrContrato("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento + + 'VALIDA IMPORTE DEL CONTRATO + Dim SeleccionadoContrato = 0.0 '(From row As GridViewRow In GvContratoDetalles.Rows.Cast(Of GridViewRow)() Select row.FCLabel("LtlTotal").Text.ToDecimal).Sum + + TmpDT.Clear() + TxtSubTotal.Text = "0" + LblDescuentos.Text = "0" + TxtIVA.Text = "0" + TxtRetIVA.Text = "0" + + For Each Row As GridViewRow In GvContratoDetalles.Rows + If Row.FCTextBox("TxtCant").Text.ToEntero > 0 Then + + 'VALIDA EXISTENCIAS DE ALMACÉN + 'Dim DrPS = GlobalDTProductosServicios(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero).FiltroPrimero("") + Dim DrPS = GlobalDTPS(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero).FiltroPrimero("") + + If DrPS IsNot Nothing Then + Dim CveTipoPS As Integer = DrPS("CveTipoPS").ToString.ToEntero + Dim CveTipoInv As Integer = DrPS("Inv_CveMetodoInventario").ToString.ToEntero + Dim existencia As Decimal = ps.GetExistenciasPS(Row.DataKey("CvePS").ToEntero, Row.DataKey("CveUM").ToEntero, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) + If (existencia < Row.FCTextBox("TxtCant").Text.ToEntero AndAlso CveTipoPS <> 1) AndAlso UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ped") Then ' And DdlContratosModal.SelectedValue.ToEntero <> 196 Then + Alert("No cuenta con la cantidad suficiente en inventario para el producto:
    " + Row.FCLiteral("LtlPS").Text + ".", TipoMensaje.MsgAdvertencia) + TmpDT.Clear() + GvPS.DataSource = Nothing + GvPS.DataBind() + UpPS.Update() + Exit Sub + Else + SeleccionadoContrato += Row.FCTextBox("TxtCant").Text.ToEntero * Row.FCLiteral("LtlPU").Text.ToDouble + AgregarProductoServicio(Row.FCTextBox("TxtCant").Text.ToEntero, Row.DataKey("CveUM").ToEntero, Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero, + Row.DataKey("Clasificacion"), Row.DataKey("CvePS").ToEntero, Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, Row.DataKey("Observaciones"), $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDecimal, 0, + DrContrato("CveProyecto").ToString.ToEntero, DrContrato("ProyectoContrato").ToString, DrContrato("CveSubProyecto").ToString.ToEntero, DrContrato("SubProyectoContrato").ToString, CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero) + 'AddPS(Row.FCTextBox("TxtCant").Text.ToEntero, Row.DataKey("CveUM").ToEntero, Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero, Row.DataKey("Clasificacion"), + ' Row.DataKey("CvePS").ToEntero, Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, Row.DataKey("Observaciones"), $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDouble, If(Row.DataKey("IVA").ToDouble = -1, ViewState("IVA").ToString.ToDouble, Row.DataKey("IVA").ToDouble), 0, 0, 1, 0, True, "", + ' DrContrato("CveProyecto").ToString.ToEntero, DrContrato("ProyectoContrato").ToString, DrContrato("CveSubProyecto").ToString.ToEntero, DrContrato("SubProyectoContrato").ToString, CveTipoPS, CveTipoInv, CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero, CodigoPS:=Row.FCLiteral("LtlPS").Text) + End If + Else + Alert("El producto presenta una inconsistencia en su información", TipoMensaje.MsgError) + TmpDT.Clear() + GvPS.DataSource = Nothing + GvPS.DataBind() + UpPS.Update() + Exit Sub + End If + + + End If + Next + + 'SI EL CONTRATO TIENE IMPUESTOS LOCALES SE CARGAN LOS DEL CONTRATO AHUEVO + If RBLTipoContrato.SelectedValue = "2" Then + Dim ObjContratos As New ClsContratos + If ObjContratos.GetContratoImpuestosLocales(CveContrato, UsuarioActual.CveEmpresa) Then + If ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then + + Dim DtContratoImpuesto As DataTable = ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") + + If DtContratoImpuesto IsNot Nothing AndAlso DtContratoImpuesto.Rows.Count > 0 Then + + ' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear() + TmpDTImpuestos = DtContratoImpuesto + + GvImpuestosLocales2.DataSource = TmpDTImpuestos + GvImpuestosLocales2.DataBind() + + If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then + TrOtros.Visible = True + GvImpuestosLocales2.Visible = True + TrOtros.Style.Add("display", "") + Else + TrOtros.Visible = False + GvImpuestosLocales2.Visible = False + End If + DtContratoImpuesto.Dispose() + End If + UpImpuestos.Update() + End If + End If + ObjContratos.Dispose() + End If + + If Not CveCicloComercial > 0 Then + 'SI EL IMPORTE MAX O EL IMPORTE FIJO DEL CONTRATO FLEXIBLE ES CERO, NO HAY LIMITE + If Not (DrContrato("Importe").ToString.ToDouble = 0 And DrContrato("ImporteMax").ToString.ToDouble = 0) Then + If DdlTipoComprobante.SelectedValue = "Ing" And (DrContrato("ModalidadDetalle").ToString = "1" Or DrContrato("ImporteMax").ToString.ToDouble > 0) AndAlso (DrContrato("ImporteTotal").ToString.ToDouble - DrContrato("Avance").ToString.ToDouble) < (SeleccionadoContrato) Then + Alert("Se excede el importe límite del contrato. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + TmpDT.Clear() + GvPS.DataSource = Nothing + GvPS.DataBind() + UpPS.Update() + Exit Sub + End If + End If + End If + + CalculaTotalesVenta() + LbAgregar.Visible = False + UpPS.Update() + + 'restricciones para evitar cambios una vez seleccionado el contrato + If BtnEmitirImprimir.Visible = False Then BtnEmitirImprimir.Visible = True : TrVistaPrevia.Visible = True + + 'DESACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto disabled") + TxtCodigo.ReadOnly = True + + Tab.ActiveTab = TabGenerales + TabGenerales.Enabled = True + Updatetabs.Update() + + PresionarBotonModal("C_BtnCerrarContrato") + + ps.Dispose() + UpFacturar.Update() + End Sub + Private Sub CargarContratoUrl() + Dim ObjContratos As New ClsContratos + + If ObjContratos.GetContratos(CveContrato, UsuarioActual.CveEmpresa, -1, -1, 1) Then + If ObjContratos.DtResultados.Rows.Count > 0 Then + + 'Cargamos los datos del Cliente + DtContratos = ObjContratos.DtResultados + ViewState("CveCliente") = ObjContratos.DtResultados(0)("CveCliente").ToString.ToEntero + CorreoNotificacionPedDev = ObjContratos.DtResultados(0)("CorreoNotificacionPedDev").ToString + HdnCveCliente.Value = ObjContratos.DtResultados(0)("CveCliente").ToString + CargaCliente(CveCliente) + DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) + DdlTipoComprobante.SelectedValue = "Ped" + DdlTipoComprobante.Enabled = False + DdlAlmacenAsignado.Enabled = False + DdlSubProyectoDatos.SelectedValueExist(ObjContratos.DtResultados(0)("CveSubProyecto")) + + AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento + + If TipoContrato = 1 Then + 'Cargamos los datos del Contrato + RblOpcionContrato.SelectedValue = "2" + BtnIniciarContrato_Click(Nothing, Nothing) + DdlContratosModal.SelectedValue = CveContrato.ToString + DdlContratosModal_SelectedIndexChanged(Nothing, Nothing) + ElseIf TipoContrato = 0 Then + 'Mostramos los almacenes + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} {If(DdlTipoComprobante.SelectedValue = "Ped", "", "AND CveTipoAlmacen IN (4,10)")}") + DdlAlmacenAsignado.DataBind() + DdlAlmacenAsignado.Enabled = True + TrAlmacenAsignado.Visible = True + TrTipoPedido.Visible = True + TrObs.InnerText = "No. Serie" + SpObs.InnerText = "Contrato" + TrObsGenerales.InnerText = "Número de Contrato " + UpParametros.Update() + End If + + If ObjContratos.CveAlmacen > 0 Then + If (DdlAlmacenAsignado.Items.FindByValue(ObjContratos.CveAlmacen.ToString) Is Nothing) Then + Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacen.ToString)) + If dr IsNot Nothing Then + DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString)) + End If + End If + DdlAlmacenAsignado.SelectedValue = ObjContratos.CveAlmacen.ToString + DdlAlmacenAsignado.Enabled = False + Else + If (DdlAlmacenAsignado.Items.FindByValue("89") Is Nothing) Then + Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", "89")) + If dr IsNot Nothing Then + DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString)) ' lo genera Obj.SelectedValue = Valor.ToString + DdlAlmacenAsignado.Enabled = False + End If + End If + DdlAlmacenAsignado.SelectedValue = "89" + End If + + If ObjContratos.CveAlmacenOrigen > 0 AndAlso TipoContrato = 0 Then + DdlAlmacenOrigen.Visible = True + RequiereAlmacenOrigen = True + If (DdlAlmacenOrigen.Items.FindByValue(ObjContratos.CveAlmacenOrigen.ToString) Is Nothing) Then + Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacenOrigen.ToString)) + If dr IsNot Nothing Then + DdlAlmacenOrigen.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString)) + End If + End If + DdlAlmacenOrigen.SelectedValue = ObjContratos.CveAlmacenOrigen.ToString + DdlAlmacenOrigen.Enabled = False + End If + + Else + Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) + End If + Else + Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) + End If + + ObjContratos.Dispose() + End Sub + Private Sub CargarPedidoUrl() + + CargaVenta() + CargaFolios() + + TrAlmacenOrigen.Visible = True + TrAlmacenAsignado.Visible = True + RequiereAlmacenDestino = True + + BtnEmitirImprimir.Text = "Devolver Pedido" + BtnEmitirImprimir.Visible = True + + DdlAlmacenAsignado.DataBind() + DdlAlmacenAsignado.Items.Insert(0, New ListItem("Productos Financieros Como Dato", "89")) + DdlAlmacenAsignado.Enabled = False + + UpParametros.Update() + UpFacturar.Update() + + End Sub + Private Sub GuardarContratoAvanceEstimaciones(ObjContrato As ClsContratos, factura As Modelos.Factura, ErrorList As List(Of String), Multiplicador As Integer, Optional CrearAvance As Boolean = False) + + If (factura.CveContrato > 0 AndAlso ((DdlContratosModal.Items.Count > 0 AndAlso factura.CveContrato = DdlContratosModal.SelectedValue.ToEntero) OrElse DdlFiltroContrato.SelectedValue.ToEntero > 0 OrElse CrearAvance)) Or ContratoOC Then + + Dim CveEstimacion As Integer = -1 + + If ObjContrato.AddEstimaciones(factura.CveContrato, factura.Fecha, -1, factura.CveVenta, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then + CveEstimacion = ObjContrato.DtResultados(0)("CveEstimacion").ToString.ToEntero + + For Each row As DataRow In TmpDT.Rows + If row("CveContratoDetalle").ToString.ToEntero > 0 Then + If Not ObjContrato.AddContratosAvance(row("CveContratoDetalle").ToString.ToEntero, row("Cantidad").ToString.ToEntero * Multiplicador, factura.Fecha, UsuarioActual.CveUsuario, CveEstimacion:=CveEstimacion) Then + ErrorList.Add("Ocurrió un error al agregar los avances") + End If + End If + Next + + Else + ErrorList.Add("Ocurrió un error al agregar las estimaciones") + End If + End If + + End Sub + Private Sub GvContratoDetalles_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvContratoDetalles.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + + Dim CantidadDisponible = If(e.Row.DBCampo("Cantidad").ToDouble < 0, "0", e.Row.DBCampo("Cantidad")) + e.Row.FCLiteral("LtlCantDisp").Text = CantidadDisponible + + If CveCicloComercial > 0 Then 'Si es un Ciclo Comercial quitamos el límite de CantidadDisponible + e.Row.Cells(1).Style.Add("display", "none") + CantidadDisponible = "10000000" + e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadContratada") + End If + + 'Si es contrato flexible le damos una cantidad alta de lo contrario lo maximo es lo estipulado en el contrato + If e.Row.DataKey("LimitarCantidad").ToString() = "True" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or e.Row.DataKey("ModalidadDetalle").ToString() = "1" Then + e.Row.FCRangeValidator("RVCant").MaximumValue = CantidadDisponible + LimitaCantidadSerieLote = 1 + Else + e.Row.FCRangeValidator("RVCant").MaximumValue = "10000000" + LimitaCantidadSerieLote = 0 + End If + + 'CONSIGNACION DE VENTA + If CveAlmacenExistenciasContrato > 0 And e.Row.DBCampo("Inv_CveMetodoInventario").ToString.ToEntero = 5 Then + GvContratoDetalles.Columns(8).Visible = True + e.Row.FCButton("BtnSerieConsignacion").Visible = True + e.Row.FCButton("BtnSerieConsignacion").CommandArgument = $"{e.Row.DBCampo("CveContratoDetalle")}°{e.Row.DBCampo("CvePS")}°{e.Row.DBCampo("CveUM")}°{e.Row.DBCampo("CodigoPS")}°{e.Row.DBCampo("Cantidad")}°{LimitaCantidadSerieLote}" + e.Row.FCTextBox("TxtCant").Enabled = False + End If + + ''Si viene de una OC Sin Facturar y tiene contrato + 'If TieneContrato AndAlso ContratosConOC IsNot Nothing AndAlso ContratosConOC.ToString.Length > 0 Then + ' e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadOC").ToString + 'End If + + End If + End Sub + Private Sub BtnCalcularTotalesContrato_Click(sender As Object, e As EventArgs) Handles BtnCalcularTotalesContrato.Click + For Each row As GridViewRow In GvContratoDetalles.Rows + row.FCLiteral("LtlTotal").Text = (row.FCLiteral("LtlCantDisp").Text.ToEntero * row.FCTextBox("TxtCant").Text.ToDouble).FormatoNumero(2) + Next + + UpContratos.Update() + End Sub + Private Sub DdlContratoModalSelectIndex() + If Not DdlContratosModal.SelectedValue.ToEntero > 0 Then + GvContratoDetalles.DataBind() + UpContratos.Update() + Exit Sub + End If + + Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}") + If DrContrato Is Nothing Then + Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError) + Exit Sub + End If + + CargaContratos() + + DdlContratosOC.SelectedValue = DdlContratosModal.SelectedValue + UPOCFactura.Update() + End Sub +#End Region + +#Region "C A R G A S" + Private Sub ClasificacionModal() + DdlClasificacionModal.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion") + DdlClasificacionModal.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlClasificacionModal.DataBind() + UpModal.Update() + End Sub + Private Sub CargaOrdenProduccion(Optional Opcion As Integer = 1, Optional CveVenta As Integer = -1) + DdlOrdenProduccion.Items.Clear() + Dim CveOrdenProduccion As String = "-1" + Dim ObjCGame As New ClsCGame + If ObjCGame.GetOrdenProduccion(-1, UsuarioActual.CveEmpresa, -1, "-1", MinFecha, MaxFecha, -1) Then + If Opcion = 1 Then + DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros(String.Format("CveVenta IS NULL ")) + ElseIf Opcion = 2 Then + LnkActualizarOrdenProduccion.Visible = True + DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta} OR CveVenta IS NULL") + If ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows.Count > 0 Then + CveOrdenProduccion = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows(0)("CveOrdenProduccion").ToString + End If + End If + DdlOrdenProduccion.Items.Insert(0, New ListItem("Seleccione", "-1")) + End If + ObjCGame.Dispose() + DdlOrdenProduccion.DataBind() + DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion) + End Sub + Private Sub CargaEstatusFactura(Optional TipoDocto As String = "Ing") + + Dim FiltroCompromiso = If(TipoDocto = "Com", "And CveEstatusFactura In (2, 9)", "And CveEstatusFactura Not In (9)") + If TipoDocto.ToUpper.Contiene("EGS", "COM", "ANT") Then TipoDocto = "Ing" + + + 'DdlEstatus.Items.Clear() + 'DdlEstatus.Items.Insert(0, New ListItem("Seleccione", "-1")) + 'DdlEstatus.SelectedValue = "-1" + 'DdlEstatus.DataSource = GlobalDTEstatusFactura.FiltraParametros(String.Format("TipoDocto = '{0}' {1}", TipoDocto, FiltroCompromiso)) + 'DdlEstatus.DataBind() + ''If DdlEstatus.Items.Count > 1 Then + '' DdlEstatus.SelectedIndex = 1 + ''End If + + ''permiso para poder cambiar estatus + 'If CveVenta > 0 Then DdlEstatus.Enabled = UsuarioActual.TienePermisoProceso(116) + + End Sub + Private Sub CargaOS(CveOS As Integer) + Dim OS As New ClsOS + Dim DtDetalle As DataTable = Nothing + Dim DtDetalleMateriales As DataTable = Nothing + + If OS.GetOrdenesServicios(CveOS, -1, -1, -1, -1, UsuarioActual.CveEmpresa) Then + + HdnCveCliente.Value = OS.CveCliente.ToString + ViewState("CveCliente") = OS.CveCliente + CargaCliente(CveCliente) + + If OS.GetOrdenesServiciosDetalleAFacturar(CveOS) Then + Dim Cons As Integer = 1 + For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows + + AgregarProductoServicio(dr("Cantidad").ToString.ToDecimal, dr("CveUM").ToString.ToEntero, dr("UM").ToString, -1, "", dr("CvePS").ToString.ToEntero, "", dr("Obs").ToString, 0, 0, -1, "", + dr("CveSubProyecto").ToString.ToEntero, dr("SubProyecto").ToString) + 'Dim drt As DataRow = TmpDT.NewRow + + 'drt("Consec") = Cons + 'drt("CvePS") = dr("CvePS") + 'drt("CveClasificacion") = dr("CveClasificacion") + 'drt("Clasificacion") = dr("Clasificacion") + 'drt("PS") = dr("PS") + 'drt("CveOSDetalle") = dr("CveOSDetalle") + 'drt("CodigoPS") = dr("CodigoPS") + 'drt("Cantidad") = dr("Cantidad") + 'drt("CveSubProyecto") = dr("CveSubProyecto") + 'drt("SubProyecto") = dr("SubProyecto") + 'drt("Obs") = dr("Obs") + 'TmpDT.Rows.Add(drt) + 'Cons = Cons + 1 + Next + TmpDT.AcceptChanges() + DtDetalle = OS.DtResultados.FiltraParametros("SeFacturara = 1 ") + End If + + For Each Row As DataRow In DtDetalle.Rows + If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString.ToEntero, CveOS) Then + If OS.DtResultados.FiltraParametros("SeFacturara = 1").Rows.Count > 0 Then + Alert("Hay materiales en la Orden de Servicio, ¿Desea facturar los materiales?", TipoMensaje.MsgConfirmacion, "BtnMateriales()") + End If + End If + Next + + OS.Dispose() + + TxtTotal.Text = TmpDT.SUM("Total").FormatoNumero() + + GvPS.DataSource = TmpDT + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + GvPS.DataBind() + + 'JJMQ 20160506: Se agrego para la validacion de pago de contado. + CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") + + UpContado.Update() + UpPS.Update() + End If + End Sub + + Private Function CargaVenta() As Boolean + + Dim Retorno As Boolean = False + + 'CARGA PARA FACTURACION + Dim CveRemision As Integer = IfNull(ViewState("CveRemision"), 0).ToString.ToEntero + Dim CveCotizacion As Integer = IfNull(ViewState("CveCotizacion"), 0).ToString.ToEntero + Dim CveVenta As Integer = Me.CveVenta + CveVenta = If(CveRemision > 0, CveRemision, CveVenta) + CveVenta = If(CveCotizacion > 0, CveCotizacion, CveVenta) + CveVenta = If(CvePedido > 0, CvePedido, CveVenta) + + Dim ObjVentas As New ClsVentas() + + Dim SerieFolioPadre As String + + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + + If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then + Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0) + Dim CveCliente As Integer = DbRowVenta("CveCliente").ToString.ToEntero + HdnCveVenta.Value = CveVenta.ToString + + Me.CveEstatusFacturaPadre = DbRowVenta("CveEstatusFacturaPadre").ToString.ToEntero + 'CargaEncabezado + If Not (CveRemision > 0 Or CveCotizacion > 0) Then + DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString + + If UsuarioActual.TienePermisoProceso(274) Then + TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant" + End If + + If TrAntEspecial.Visible Then + ChkAntEspecial.Enabled = False + ChkAntEspecial.Checked = If(DbRowVenta("AnticipoEspecial").ToString = "True", True, False) + End If + CargaEstatusFactura(DdlTipoComprobante.SelectedValue) + CveEstatus = DbRowVenta("CveEstatusFactura").ToString.ToEntero + LbEstatus.Text = DbRowVenta("EstatusFactura").ToString + ViewState("SaldoVenta") = DbRowVenta("Saldo").ToString + AplicaCancelarRemision = CBool(DbRowVenta("AplicaCancelarRemision").ToString) + If AplicaCancelarRemision AndAlso CveEstatus.Contiene(2, 3) AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then DivCanRem.Visible = True + VentaSaldoAlmacen = DbRowVenta("SaldoAlmacen").ToString.ToDecimal + + If CveEstatus = 5 Then LbCancelarDocumento.Enabled = False + 'If CveEstatus = 20 Then + ' LbCancelarDocumentoManual.Visible = True + 'End If + + If Not CveEstatus.Contiene(4, 5, 12, 13, 20) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Ant") AndAlso UsuarioActual.TienePermisoProceso(159) Then + Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) + If TienePermiso <> "" Then + LkRefacturacion.Visible = True + End If + End If + + If DbRowVenta("CveVentaRelacionada").ToString.ToEntero > 0 Then + TrRefacturadaa.Visible = True + HplRefacturadaEn.NavigateUrl = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", DbRowVenta("CveVentaRelacionada")) + HplRefacturadaEn.Text = DbRowVenta("SerieFolioRelacionada").ToString + LblAlertRefacInv.Visible = True + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Ing", "Ant", "Dev", "Rem", "DPe") AndAlso Not CveEstatus.Contiene(4, 5, 12, 13, 20) Then + If UsuarioActual.TienePermisoProceso(159) Then + Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) + If TienePermiso <> "" Then + LbCancelarDocumento.Visible = True + 'If UsuarioActual.CveEmpresa = 119 And Not UsuarioActual.CveUsuario.Contiene(100, 1703) Then '[IPP] AD y Jesus de JAM + ' 'si es del mes anterior no permita cancelar + ' If Not DdlTipoComprobante.SelectedValue.Contiene("Rem") Then + ' If DbRowVenta("Fecha").ToString.ToDate <= Now.AddMonths(-1).LastDayOfMonth Then + ' LbCancelarDocumento.Visible = False + ' End If + ' End If + 'End If + End If + + End If + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Ing", "Ant", "Dev") AndAlso LblFolioFiscal.Text.Trim = "" Then HplFolioFiscalModal.Visible = True + + Select Case DbRowVenta("TipoDocto").ToString + Case "Ing" + Trsaldo.Visible = True + HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then + HLPagar.Visible = True + HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675" + HlCuentaTerminal.Visible = True + End If + + Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) + If TienePermiso <> "" Then ' si tiene acceso en el subproyecto + 'LkNotaCredito.Visible = UsuarioActual.TienePermisoProceso(175) + If UsuarioActual.TienePermisoProceso(264) Then + LkDevolucion.Visible = True + InicializaAplicaDevolucion() + End If + End If + + + HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) + Case "Egs" + HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) + HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString + Trsaldo.Visible = True + HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + Case "Rem" + 'IPP 15 Julio 2017 + Trsaldo.Visible = True + HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then + HLPagar.Visible = True + HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675" + HlCuentaTerminal.Visible = True + End If + + If UsuarioActual.CveEmpresa = 80 Then + LtlImprimir.Text = String.Format("
  • Imprimir
  • ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta))) + End If + DiasCredito = DbRowVenta("DiasCredito").ToString.ToEntero + EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString) + Case "OP" + TdOrdenPago.Visible = True + DdlOrdenPago.SelectedValue = DbRowVenta("Num3").ToString + DdlOrdenPago.Enabled = False + Case "Cot" + TxtAtencionA.Text = DbRowVenta("AtencionA").ToString + TxtFechaVencimientoCotizacion.Text = DbRowVenta("Vigencia").ToString + PnlImprimir.Visible = True + HLOrdendeCompra.Visible = True + HLOrdendeCompra.NavigateUrl = String.Format("/OC/OC.aspx?Tipo=Req&CveCotizacion={0}", CveVenta) + + Dim ObjOS As New ClsOS() + If ObjOS.GetCotizacionOS(CveVenta) Then + If ObjOS.DtResultados.Rows.Count > 0 Then + Dim DbRowOS As DataRow = ObjOS.DtResultados.Rows(0) + ViewState("CveOS") = DbRowOS("CveOS").ToString.ToEntero + CargaOS(CveOS) + End If + + Else + HLOrdenServicio.Visible = True + HLOrdenServicio.NavigateUrl = String.Format("/OS/OrdenesServicios.aspx?CveCotizacion={0}", CveVenta) + End If + ObjOS.Dispose() + + If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 145) Then PnlImprimir.Visible = True : LnkImprimir.OnClientClick = "javascript:ImprimirCotizacion();return false;" + 'Deshabilitar impresión cuando no esté supervisada + If DbRowVenta("TipoEstatus").ToString.ToEntero = 2 Or UsuarioActual.Empresa.Funcionalidad(113) = "1" Then + PnlImprimir.Visible = True + Else + HplDownPDF.Visible = False + PnlImprimir.Visible = False + End If + + + 'Verifico si tiene la funcionalidad (135) + If UsuarioActual.Empresa.Funcionalidad(135) = "1" Then + 'Reviso cuales son los supervisores + Dim Objeto As New ClsVtaVendedores + + If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then + Dim DTVendedores As New DataTable + DTVendedores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString)).FiltraParametros(String.Format("CveSupervisor = {0}", UsuarioActual.CveVendedor)) + 'Verifico si es su supervisor asignado + If DTVendedores.Rows.Count > 0 Then + LkCotizacionAutorizar.Visible = True + End If + DTVendedores.Dispose() + End If + Objeto.Dispose() + End If + + String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString) + + + Case "Ant" + Trsaldo.Visible = True + HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + 'LkNotaCredito.Visible = True + HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) + Case "Dev" + DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) + HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) + HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString + ViewState("CveDevolucion") = DbRowVenta("CveVentaPadre").ToString.ToEntero + Trsaldo.Visible = True + HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) + Case "Ped" + DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) + Case "DPe" + DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe")) + Case "PeC" + DdlTipoComprobante.Items.Insert(5, New ListItem("Pedido de Consignación", "PeC")) + Case "PA" + BtnGenerarRemision.Visible = If(CveEstatus = 16, True, False) + CvePedidoA = CveVenta + DiasCredito = DbRowVenta("DiasCredito").ToString.ToEntero + EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString) + Case "Pd2" + CvePedido2 = CveVenta + BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False) + BtnGenerarRemision.Visible = If(CveEstatus <> 21, True, False) + End Select + + DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString + + End If + + 'contado 0, credito 1, terminal 2 + If ObjVentas.DtResultados(0)("CondicionesPago").ToString.ToEntero = 1 Then + RBLPago.SelectedValue = "1" + RBLPago_SelectedIndexChanged(Nothing, Nothing) + UPCondicionesPago.Update() + ElseIf ObjVentas.DtResultados(0)("CondicionesPago").ToString.ToEntero = 0 Then + RBLPago.SelectedValue = "2" + RBLPago.Items(0).Enabled = False + RBLPago_SelectedIndexChanged(Nothing, Nothing) + UPCondicionesPago.Update() + Else + DdlCuentasTerminal.SelectedValue = DbRowVenta("CveCuentaTerminal").ToString + RBLPago.SelectedValue = "3" + RBLPago.Items(0).Enabled = False + RBLPago_SelectedIndexChanged(Nothing, Nothing) + UPCondicionesPago.Update() + End If + + 'CargaDetalle + If ObjVentas.GetVentaDetalle(CveVenta) Then + TmpDT = ObjVentas.DtResultados + TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) + TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) + GvPS.DataSource = ObjVentas.DtResultados + GvPS.DataBind() + + 'IEPS A NIVEL DETALLE + 'TxtIEPS.Text = If(TmpDT.SUM("IEPS") > 0, TmpDT.SUM("IEPS").FormatoNumero, TxtIEPS.Text) + End If + + 'ESCONDE ACCIONES + LnkRemisiones.Visible = False + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + LnkOCs.Visible = False + UpnTools.Update() + + DivEstatusFac.Visible = True + HdnCveCliente.Value = CveCliente.ToString + ViewState("CveCliente") = CveCliente + ViewState("CveEmpresaCRM") = DbRowVenta("CveEmpresaCRM").ToString.ToEntero + ViewState("CveAcercamientoCRM") = DbRowVenta("CveAcercamientoCRM").ToString.ToEntero + Entrega = DbRowVenta("Entrega").ToString + Vigencia = DbRowVenta("Vigencia").ToString.ToDate.ToShortDateString + HplSaldoAuxiliar.Text = DbRowVenta("Saldo").ToString.FormatoNumero(2) + If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then + HplSaldoAuxiliar.Visible = False + HplPagado.Visible = True + + If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString.ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then + ImgAntiPend.Visible = True + Else + ImgAntiPend.Visible = False + End If + + End If + HdnPagado.Value = DbRowVenta("Pagado").ToString + TxtTotal.Text = DbRowVenta("Total").ToString.FormatoNumero(2) + HdnVentaSaldo.Value = (SaldoVenta).ToString + CvePrePoliza = DbRowVenta("CvePrePoliza").ToString.ToEntero + CveVentaFacturada = DbRowVenta("CveVentaFacturada").ToString.ToEntero + + CveVentaRelacion = DbRowVenta("CveVentaRelacion").ToString.ToEntero + ImporteRelacion = DbRowVenta("ImporteRelacion").ToString.ToDouble + + DdlMoneda.SelectedValue = DbRowVenta("CveMoneda").ToString + CambiaMoneda() + + If DbRowVenta("TipoDocto").ToString = "Pd2" Then + 'CANTIDAD FACTURADA + If TmpDT.SUM("CantidadFacturadaPed2") > 0 Then + GvPS.Columns(7).Visible = True + ThCantidadFacturada.Visible = True + ThCantidadFacturada2.Visible = True + Else + GvPS.Columns(7).Visible = False + ThCantidadFacturada.Visible = False + ThCantidadFacturada2.Visible = False + End If + + ''ACTIVA EDITAR + ''SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA + 'If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString.ToEntero Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") + ' BtnPermisoEditarCotizacion.Visible = True + 'End If + + 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR + 'If TmpDT.SUM("CantidadFacturadaPed2") < TmpDT.SUM("Cantidad") Then + ' BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) + ' BtnsFacturar.Visible = True + 'End If + End If + + + If CveEmpresaCRM > 0 And Not CveCliente > 0 Then + CargaEmpresaCRM(CveEmpresaCRM) + Else + CveEmpresaCRM = IIf(CveEmpresaCRM > 0, CveEmpresaCRM, 0).ToString().ToEntero() + CargaCliente(CveCliente, -1) 'Estatus activo, se requiere para cargar una factura en la que el cliente a sido eliminado + End If + + ViewState("CveAlmacenTransitorio") = DbRowVenta("CveAlmacenTraspasoDestino").ToString.ToEntero + DevolucionAlmacen = DbRowVenta("EsDevolucionVenta").ToString.ToEntero + + 'sino esta cargada la información del metodo de pago que le corresponde, la recarga para que se le pueda asignar + If DdlMetodoPago33.SelectedValue <> DbRowVenta("CveMetodoPago33").ToString Then + CargaFormaPago(DbRowVenta("CveMetodoPago33").ToString.ToEntero) + End If + DdlMetodoPago33.SelectedValueExist(DbRowVenta("CveMetodoPago33").ToString) + DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString.ToEntero) + + If DdlFormaPago33.SelectedValue <> DbRowVenta("CveFormaPago33").ToString And DbRowVenta("CveFormaPago33").ToString <> "" Then + 'sino está seleccionada la asginada la debe de cargar + Dim Nombre As String = GlobalDTVtaFormaPago().FiltroPrimeroValor("FormaPagoSAT", String.Format("CveFormaPago={0}", DbRowVenta("CveFormaPago33"))) + DdlFormaPago33.Items.Add(New ListItem(Nombre, DbRowVenta("CveFormaPago33").ToString)) + DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString.ToEntero) + End If + + DdlUsoCFDI.SelectedValueExist(DbRowVenta("CveUsoCFDI").ToString) + + If UsuarioActual.CveEmpresa = 126 Then CargaOrdenProduccion(2, CveVenta) + + If DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then + TrTipoRelacion.Visible = True + DdlTiposRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion").ToString.ToEntero) + HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString + End If + + If DbRowVenta("Saldo").ToString.ToDouble < 0.01 Then + If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString.ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then + ImgAntiPend.Visible = True + Else + ImgAntiPend.Visible = False + End If + ElseIf Opcion <> "Op" Then + ImgAntiPend.Visible = True + End If + If UsuarioActual.CveRol.Contiene(1, 1155) Then LiLnkGuias.Visible = True + + LiComplementoPago.Visible = True + + + ViewState("FolioFiscal") = DbRowVenta("FolioFiscal").ToString + LblSerie.Text = DbRowVenta("Serie").ToString + ViewState("Serie") = DbRowVenta("Serie").ToString + ViewState("Folio") = DbRowVenta("Folio").ToString.ToEntero + TxtFolio.Text = DbRowVenta("Folio").ToString + 'TxtDocto.Text = DbRowVenta("Ref").ToString + 'TxtNumCtaPago.Text = DbRowVenta("NumeroCuenta").ToString + LblFolioFiscal.Text = DbRowVenta("FolioFiscal").ToString + TxtFecha.Text = DbRowVenta("Fecha").ToString + TxtSubTotal.Text = DbRowVenta("SubTotal").ToString.FormatoNumero(2) + LblDescuentos.Text = DbRowVenta("Descuento").ToString.FormatoNumero(2) + LblAmortizacion.Text = DbRowVenta("Amortizacion").ToString.FormatoNumero(2) + TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) + TxtIVA.Text = DbRowVenta("IVA").ToString.FormatoNumero(2) + TxtRetIVA.Text = DbRowVenta("RetIVA").ToString.FormatoNumero(2) + TxtRetISR.Text = DbRowVenta("RetISR").ToString.FormatoNumero(2) + TxtIEPS.Text = DbRowVenta("IEPS").ToString.FormatoNumero(2) + TrIEPS.Visible = TxtIEPS.Text.ToDouble > 0 + TxtTotal.Text = DbRowVenta("Total").ToString.FormatoNumero(2) + HdnTotalVenta.Value = DbRowVenta("Total").ToString.FormatoNumero(2) + TxtMotivoDescuento.Text = DbRowVenta("MotivoDescuento").ToString + TxtObsFact.Text = DbRowVenta("Observaciones").ToString + LblUsuario.Text = DbRowVenta("Nombre").ToString + LblFechaRegistro.Text = DbRowVenta("FechaIng").ToString.ToDate.ToShortDateString + LblSeTimbro.Text = DbRowVenta("SeTimbro").ToString + LblMail.Text = DbRowVenta("EnvioMail").ToString + TxtFechaPago.Text = DbRowVenta("FechaVencimiento").ToString + TxtFechaVencimientoCotizacion.Text = Vigencia + TxtDet_OrdenCompra.Text = DbRowVenta("Det_OrdenCompra").ToString + TxtDet_FechaOrdenCompra.Text = DbRowVenta("Det_FechaOrdenCompra").ToString + HdnIVAOriginal.Value = TxtIVA.Text + TxtPedidoContrato.Text = DbRowVenta("PedidoContrato").ToString + TxtPedidoContrato.Enabled = False + + + HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString + HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) + 'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString + 'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString = "True" + DdlTipoAmortizacionAnticipo.SelectedValueExist(DbRowVenta("CveTipoAmortizacionAnticipo")) + DdlTipoRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion")) + + 'HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString + 'HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) + 'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString + 'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString = "True" + + + If DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then + TrTipoRelacion2.Visible = True + LblTipoRelacion.Text = DbRowVenta("TipoRelacion").ToString + HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString + End If + + + TxtOrdenCompra.Text = DbRowVenta("OrdenCompra").ToString + TxtOrdenCompra.Enabled = False + + TxtObsAlmacen.Text = DbRowVenta("ObservacionesAlmacen").ToString + CvePAC = DbRowVenta("CvePAC").ToString.ToEntero + + If DbRowVenta("Saldo").ToString.ToDecimal > 0 AndAlso UsuarioActual.TienePermisoProceso(204) AndAlso Not UsuarioActual.CveEmpresa.Contiene(119) Then + TxtFechaSaldarVenta.Text = TxtFecha.Text + CEFechaSaldarVenta.StartDate = TxtFecha.Text.ToDate + HLSaldarVenta.Visible = True + End If + + + If (UsuarioActual.TienePermisoProceso(166) Or UsuarioActual.CveRol = 1) AndAlso (LblFolioFiscal.Text = "" Or LblFolioFiscal.Text = "test") Then + LkEliminarFactura.Visible = True + End If + + 'Envio Direccion + If DbRowVenta("CveDireccionEnvio").ToString.ToEntero > 0 AndAlso DbRowVenta("CveDireccionEnvio").ToString IsNot Nothing Then + ChkDireccionEnvio.Checked = True + DdlDireccionEnvio.SelectedValueExist(DbRowVenta("CveDireccionEnvio").ToString.ToEntero) + DdlDireccionEnvio.Enabled = False + ChkDireccionEnvio.Enabled = False + DdlDireccionEnvio.Visible = True + trDireccionEnvio.Visible = True + End If + + 'ESTATUS FACTURA + If Not (CveRemision > 0 Or CveCotizacion > 0) Then + CveEstatus = DbRowVenta("CveEstatusFactura").ToString.ToEntero + + End If + + TxtTipoCambio.Text = DbRowVenta("TipoCambio").ToString + If DbRowVenta("TipoCambio").ToString.ToDecimal <> DbRowVenta("TipoCambioValuacion").ToString.ToDecimal Then + LblTCValuacion.Text = String.Format("Ult. Val:{0}", DbRowVenta("UltimasFluctuaciones").ToString) + LblTCValuacion.Visible = True + End If + + ViewState("SelloCancelacion") = DbRowVenta("SelloCancelacion").ToString + ViewState("FechaCancelacion") = DbRowVenta("FechaCancelacion").ToString.ToDateTime + TxtAtencionA.Text = DbRowVenta("AtencionA").ToString + TxtTelefonoGenerico.Text = DbRowVenta("TelefonoGenerico").ToString + CveVentaPadre = DbRowVenta("CveVentaPadre").ToString.ToEntero + SerieFolioPadre = DbRowVenta("SerieFolioPadre").ToString + + If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then + DdlVendedor.Enabled = False + End If + + If CveVentaPadre > 0 Then + If IsNothing(Request("CveDevolucion")) AndAlso IsNumeric(Request("CveDevolucion")) Then + DdlNCFactura.Visible = True + Else + DdlNCFactura.Visible = False + End If + trNCFactura.Visible = True + LblSerieFolioPadre.Visible = True + LblSerieFolioPadre.Text = String.Format("{1}", CveVentaPadre, SerieFolioPadre) + + End If + + TxtFechaEjecucion.Text = DbRowVenta("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy") + 'DdlSucursalEjecucion.SelectedValueExist(DbRowVenta("CveSucursalEjecucion").ToString) + 'DdlSucursalCobranza.SelectedValueExist(DbRowVenta("CveSucursalCobranza").ToString) + DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").ToString) + 'DdlSucursal.SelectedValueExist(DbRowVenta("CveSucursal").ToString) + 'DdlSubProyectoDatos.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString) + + If DdlSubProyectoDatos.Items.Count = 0 Then + DdlSubProyectoDatos.Items.Insert(0, New ListItem("Seleccione", "-1")) + End If + DdlSubProyectoDatos.SelectedValueExistInsert(DbRowVenta("CveSubProyecto").ToString, DbRowVenta("SubProyecto").ToString) + + If DdlSubProyectoCobranza.Items.Count = 0 Then + DdlSubProyectoCobranza.Items.Insert(0, New ListItem("Seleccione", "-1")) + End If + DdlSubProyectoCobranza.SelectedValueExistInsert(DbRowVenta("CveSubProyectoCobranza").ToString, GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoCobranza").ToString.ToEntero).FiltroPrimeroValor("SubProyecto").ToString) + + If DdlSubProyectoEjecucion.Items.Count = 0 Then + DdlSubProyectoEjecucion.Items.Insert(0, New ListItem("Seleccione", "-1")) + End If + DdlSubProyectoEjecucion.SelectedValueExistInsert(DbRowVenta("CveSubProyectoEjecucion").ToString, GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoEjecucion").ToString.ToEntero).FiltroPrimeroValor("SubProyecto").ToString) + + CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString.ToEntero) + + If DbRowVenta("CveContrato").ToString.ToEntero > 0 Then + CveContrato = DbRowVenta("CveContrato").ToString.ToEntero + NumeroContrato = DbRowVenta("NumeroContrato").ToString + DescripcionContrato = DbRowVenta("DescripcionContrato").ToString + DdlContrato.Visible = False + HLContrato.Text = $"{DbRowVenta("NumeroContrato")} - {DbRowVenta("DescripcionContrato")}" + HLContrato.NavigateUrl = $"/Contratos/Contrato.aspx?CveContrato={CveContrato}" + 'trPresupuesto.Visible = True + 'HplPresupuesto.NavigateUrl = String.Format(" / Presupuestos / Presupuesto.aspx?CvePresupuesto={0}", DbRowVenta("CveContrato").ToString) + Else + NumeroContrato = "" + DescripcionContrato = "" + End If + + 'DdlEstatus.Items.Remove(DdlEstatus.Items.FindByText("Cotización")) + + If DbRowVenta("SeTimbro").ToString <> "No" Then + HplDownXML.Visible = True + 'If HLImprimir.Visible = False Then + HplDownPDF.Visible = True + 'End If + ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" OrElse DdlTipoComprobante.SelectedValue = "Cot" Then + 'If drv("TipoEstatus").ToString.ToEntero = 2 AndAlso drv("TipoDocto").ToString = "Cot" Then + ' ImgDownPDF.Visible = True + 'Else + HplDownPDF.Visible = False + 'End If + ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso DbRowVenta("SeTimbro").ToString = "No" AndAlso DbRowVenta("CveEstatusFactura").ToString = "2" AndAlso DbRowVenta("TipoDocto").ToString.Contiene("Ing", "Egs", "Dev", "Ant") Then + TrEmitir.Visible = True + If TxtFecha.Text.ToDate < Now.AddDays(-3) Then + TxtFecha.Enabled = True + End If + End If + + If DbRowVenta("SeTimbro").ToString = "Si" Then + TrEmitir.Visible = False + End If + + 'CargaAcuseCancelacion + If DbRowVenta("CveEstatusFactura").ToString = "5" Then + ImgDownCancelacion.Visible = True + ImgDownCancelacion.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CAN&CVEVTA={0}", CveVenta))) + End If + IdPoliza = DbRowVenta("IdPoliza").ToString.ToEntero + + 'Carga si es Contabilizada + If IdPoliza > 0 Then + HLContabilizada.Text = "Si" + HLContabilizada.NavigateUrl = $"/Contabilidad/RegPoliza.aspx?IdPoliza={DbRowVenta("IdPoliza")}" + trContabilizada.Visible = True + If UsuarioActual.TienePermisoProceso(107) Then BtnDescontabilizar.Visible = True + + Else + 'cuando no este contabilizada y usa AC, habilita el boton para generar la poliza + If UsuarioActual.Empresa.UsaAC AndAlso UsuarioActual.CveRol = 1 Then + BtnGenerarPoliza.Visible = True + End If + If UsuarioActual.Empresa.Funcionalidad(200) = "1" Then + BtnContabilizar.Visible = True + End If + End If + + If DbRowVenta("IdPolizaCancelacion").ToString.ToEntero > 0 Then + HPLContaCancelacion.Text = "Cancelación" + HPLContaCancelacion.NavigateUrl = String.Format("/Contabilidad/RegPoliza.aspx?IdPoliza={0}", DbRowVenta("IdPolizaCancelacion")) + trContabilizada.Visible = True + End If + + + If UsuarioActual.Empresa.UsaOS AndAlso DbRowVenta("CveOS").ToString.ToEntero = 0 Then + BtnGenerarOS.Visible = True + BtnGenerarOS.OnClientClick = String.Format("javascriptwindow.location.href = '/OS/OrdenesServicios.aspx?CveVenta={0}'; return false;", CveVenta) + ' BtnGenerarOS.OnClientClick = String.Format("/OS/OrdenesServicios.aspx?CveVenta={0}", CveVenta) + End If + + + '[IPP] COMENTADO 12/MARZO/2018 -SABRA QUE SE QUERIA ESCONDER + 'If DbRowVenta("TipoDocto").ToString = "Rem" Then + ' GvPS.Columns(11).Visible = False + ' GvPS.Columns(12).Visible = False + 'End If + + + 'Ocultamos los botones Clonar y Ordenar + GvPS.Columns(19).Visible = False + GvPS.Columns(20).Visible = False + + 'CargaFirmas + If ObjVentas.GetVentasFirmas(CveVenta) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + DTmpF = ObjVentas.DtResultados + GvFirmas.DataSource = ObjVentas.DtResultados + GvFirmas.DataBind() + Else + GvFirmas.DataSource = Nothing + End If + End If + + 'CARGA IMPUESTOS LOCALES + If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + TrOtros.Visible = True + TmpDTImpuestos = ObjVentas.DtResultados + GvImpuestosLocales2.DataSource = ObjVentas.DtResultados + GvImpuestosLocales2.DataBind() + + GvImpuestosLocales2.Enabled = False + GvImpuestosLocales2.Visible = True + End If + End If + + DdlVendedor.SelectedValue = DbRowVenta("CveVendedor").ToString + DdlTipoComprobante.Enabled = False + 'TxtDocto.Enabled = False + + 'PORLET CLIENTE + 'DESACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto disabled") + TxtCodigo.ReadOnly = True + ChkEnviarFactura.Enabled = False + ChkDireccionEnvio.Enabled = False + TxtAtencionA.Enabled = False + TxtFechaVencimientoCotizacion.Enabled = False + + TxtCantidad.Enabled = False + DdlClasificacion.Enabled = False + + DdlPS.Enabled = False + TxtObsPS.Enabled = False + DdlProyecto.Enabled = False + DdlSubProyecto.Enabled = False + TxtPrecio.Enabled = False + ImgDescPU.Attributes.Clear() + ImgDescTotal.Attributes.Clear() + ImgDescConcepto.Attributes.Clear() + LbAgregar.Enabled = False + LnkAgregarPyME.Enabled = False + DdlCuentasTerminal.Enabled = False + + For Each Row As GridViewRow In GvPS.Rows + Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString() + Next + GvPS.Columns(ColumnaEditar).HeaderText = "" + GvPS.Columns(ColumnaEliminar).HeaderText = "" + 'GvPS.Columns(ColumnaEliminar).Visible = False + + TxtObsFact.Enabled = False + TxtObsAlmacen.Enabled = False + TxtMotivoDescuento.Enabled = False + 'GvLeyendasFiscales.Enabled = False + TxtSubTotal.ReadOnly = True + TxtIVA.ReadOnly = True + TxtRetIVA.ReadOnly = True + TxtRetISR.ReadOnly = True + TxtIEPS.ReadOnly = True + TxtTotal.ReadOnly = True + + 'Sección Detalle + DdlMoneda.Enabled = False + TxtFechaEjecucion.ReadOnly = True + ImgCalendarFechaEje.Enabled = False + 'DdlSucursalEjecucion.Enabled = False + 'DdlSucursalCobranza.Enabled = False + DdlVendedor.Enabled = False + DdlSucursalCliente.Enabled = False + TxtTiempoEntrega.Enabled = False + TxtAlfa1.ReadOnly = True + TxtAlfa2.ReadOnly = True + TxtAlfa3.ReadOnly = True + TxtNum1.ReadOnly = True + TxtNum2.ReadOnly = True + TxtNum3.ReadOnly = True + TxtFech1.ReadOnly = True : ImgFech1.Enabled = False + TxtFech2.ReadOnly = True : ImgFech2.Enabled = False + TxtFech3.ReadOnly = True : ImgFech3.Enabled = False + ChkConvertirDoctoPesos.Enabled = False + ChkConvertirDolares.Enabled = False + TxtTipoCambio.Enabled = False + TxtTipoCambioDlls.Enabled = False + + 'Condiciones de Pago + RBLPago.Enabled = False + DdlFormaPago33.Enabled = False + DdlUsoCFDI.Enabled = False + DdlMetodoPago33.Enabled = False + 'TxtNumCtaPago.Enabled = False + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then + TxtFechaPago.ReadOnly = Not UsuarioActual.TienePermisoProceso(260) + LnkUpdateFechaVencimiento.Visible = UsuarioActual.TienePermisoProceso(260) + Else + TxtFechaPago.ReadOnly = False + End If + + imgCalendario.Enabled = False + DdlFuenteRecaudacion.Enabled = False + + TrVistaPrevia.Visible = False + BtnEmitirImprimir.Visible = False + 'CargaLeyendasFiscales + ViewState("VentaFolio") = If(LblSerie.Text.Trim.Length = 0, TxtFolio.Text.Trim, LblSerie.Text.Trim & "-" & TxtFolio.Text.Trim) + + CalculaTotalesVenta(False) + + 'JJMQ 20160506: Se agrego para la validacion de pago de contado. + CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") + + 'CARGA ANTICIPOS + If Not (CveRemision > 0 Or CveCotizacion > 0) Then + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then + 'carga as notas de credito vinculadas + If ObjVentas.GetVentasAntNC(CveVenta, -1) Then + GvAntNC.DataSource = ObjVentas.DtResultados + TmpDTDocumentosRelacionados = ObjVentas.DtResultados + GvAntNC.Caption = "
    (Anticipos/NC/IxC) Vinculados
    " + GvAntNC.DataBind() + End If + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev", "Ant") Then + If ObjVentas.GetVentasAntNC(-1, CveVenta) Then + GvNC.DataSource = ObjVentas.DtResultados + TmpDTNCVinculadas = ObjVentas.DtResultados + GvNC.Caption = "
    Ventas Aplicadas
    " + GvNC.DataBind() + InicializaDTVentasNC() + For Each Dr As DataRow In ObjVentas.DtResultados.Rows + If Dr("CveConceptoContable").ToString.ToEntero = 91 Then + CargaNCDT(Dr("CveVenta").ToString.ToEntero, Dr("Importe").ToString.ToDecimal, Dr("FolioFiscal").ToString, TC:=Dr("TipoCambio").ToString.ToDecimal) + End If + Next + End If + End If + End If + + If GvNC.Rows.Count > 0 Then + ImgAntiPend.Visible = False + End If + + 'CARGA REMISIONES + If ObjVentas.GetRemisionesRelacionadas(CveVenta, DdlTipoComprobante.SelectedValue) Then + GvRemisiones.Caption = "
    Remisiones/Facturas
    " + GvRemisiones.DataSource = ObjVentas.DtResultados + GvCancelarRemisiones.DataSource = ObjVentas.DtResultados + + GvRemisiones.DataBind() + GvCancelarRemisiones.DataBind() + + '[IPP] SI ES REMISION PARA CANCELARLA NO DEBE TENER NINGUNA FACTURADA RELACIONADA - 24Abril2018 + If DdlTipoComprobante.SelectedValue.Contiene("Rem") And GvRemisiones.Rows.Count > 0 Then + LbCancelarDocumento.Visible = False + End If + End If + + tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") + tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") + + + If DbRowVenta("TipoDocto").ToString = "Rem" Then + 'CANTIDAD FACTURADA + If TmpDT.SUM("CantidadFacturadaRem") > 0 Then + GvPS.Columns(6).Visible = True + ThCantidadFacturadaRem.Visible = True + ThCantidadFacturadaRem2.Visible = True + Else + GvPS.Columns(6).Visible = False + ThCantidadFacturadaRem.Visible = False + ThCantidadFacturadaRem2.Visible = False + End If + + 'ACTIVA EDITAR + 'SOLO LA PUEDE EDITAR CON PROCESO | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR + If UsuarioActual.TienePermisoProceso(202) And TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then + BtnPermisoEditarRemision.Visible = True + End If + + 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR + If TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then + BtnsFacturar.Visible = True + + 'ACTIVA CONVERSION DE MONEDA + If DdlMoneda.SelectedValue.ToEntero = 1 Then + TrConversionDolares.Visible = True + ChkConvertirDolares.Enabled = True + TxtTipoCambioDlls.Enabled = True + Else + TrConversionTipoCambio.Visible = True + ChkConvertirDoctoPesos.Enabled = True + TxtTipoCambio.Enabled = True + End If + End If + + End If + + + If DbRowVenta("TipoDocto").ToString.Contiene("Cot", "Pd2") Then + 'CANTIDAD FACTURADA + If TmpDT.SUM("CantidadFacturadaCot") > 0 Then + GvPS.Columns(7).Visible = True + ThCantidadFacturada.Visible = True + ThCantidadFacturada2.Visible = True + Else + GvPS.Columns(7).Visible = False + ThCantidadFacturada.Visible = False + ThCantidadFacturada2.Visible = False + End If + + 'ACTIVA EDITAR + 'SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA + If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString.ToEntero Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") + BtnPermisoEditarCotizacion.Visible = True + End If + + 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR + If TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") AndAlso DdlTipoComprobante.SelectedValue.Contiene("Cot") Then + BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) + BtnsFacturar.Visible = True + End If + End If + + UpPS.Update() + UpContado.Update() + UpEstatus.Update() + Retorno = True + + Else + CveVenta = -1 + Alert("El documento solicitado no existe, favor de revisar su búsqueda.", TipoMensaje.MsgAdvertencia) + End If + End If + ObjVentas.Dispose() + Return Retorno + End Function + Private Sub CargaTiposDocumentos() + DdlTipoComprobante.DataSource = GlobalDTTiposDocumentos() + DdlTipoComprobante.DataBind() + End Sub + Private Sub CargaNuevaFactura(OVenta As ClsVentas) + Dim ObjVentas As ClsVentas + + If OVenta IsNot Nothing Then + ObjVentas = OVenta + Else + ObjVentas = New ClsVentas() + End If + + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then + Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) + + 'CargaCliente + Dim CveCliente As Integer = drv("CveCliente").ToString.ToEntero + + HdnCveCliente.Value = CveCliente.ToString + ViewState("CveCliente") = CveCliente + CargaCliente(CveCliente) + + 'Carga Detalle Sucursal + TxtFechaEjecucion.Text = drv("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy") + TxtFechaPago.Text = drv("FechaVencimiento").ToString.ToDateTime.ToString("dd/MM/yyyy") + 'DdlSucursalEjecucion.SelectedValueExist(drv("CveSucursalEjecucion").ToString) + 'DdlSucursalCobranza.SelectedValueExist(drv("CveSucursalCobranza").ToString) + DdlSucursalCliente.SelectedValueExist(drv("CveClienteSucursal").ToString) + 'DdlSucursal.SelectedValueExist(drv("CveSucursal").ToString) + DdlSubProyectoDatos.SelectedValueExist(drv("CveSubProyecto").ToString) + DdlSubProyectoEjecucion.SelectedValueExist(drv("CveSubProyectoEjecucion").ToString) + DdlSubProyectoCobranza.SelectedValueExist(drv("CveSubProyectoCobranza").ToString) + + If CveDevolucion > 0 Then + CambiaSucursalGeneral() + End If + CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero) + + 'CargaDetalle + If ObjVentas.GetVentaDetalle(CveVenta) Then + TmpDT = ObjVentas.DtResultados + TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) + TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) + 'TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) + GvPS.DataSource = ObjVentas.DtResultados + GvPS.DataBind() + End If + + 'CARGA IMPUESTOS LOCALES + If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + TrOtros.Visible = True + TmpDTImpuestos = ObjVentas.DtResultados + GvImpuestosLocales2.DataSource = ObjVentas.DtResultados + GvImpuestosLocales2.DataBind() + + GvImpuestosLocales2.Enabled = False + GvImpuestosLocales2.Visible = True + End If + End If + + 'Carga Totales + ViewState("TipoDoctoDevolucion") = drv("TipoDocto").ToString + TxtSubTotal.Text = drv("SubTotal").ToString.FormatoNumero(2) + LblDescuentos.Text = drv("Descuento").ToString.FormatoNumero(2) + LblAmortizacion.Text = drv("Amortizacion").ToString.FormatoNumero(2) + TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) + TxtIVA.Text = drv("IVA").ToString.FormatoNumero(2) + TxtRetIVA.Text = drv("RetIVA").ToString.FormatoNumero(2) + TxtRetISR.Text = drv("RetISR").ToString.FormatoNumero(2) + TxtTotal.Text = drv("Total").ToString.FormatoNumero(2) + TotalOriginal = Math.Round(drv("Total").ToString.ToDouble, 2) + HdnVentaSaldo.Value = drv("Total").ToString + TxtMotivoDescuento.Text = drv("MotivoDescuento").ToString + TxtObsFact.Text = drv("Observaciones").ToString + DdlMoneda.SelectedValue = drv("CveMoneda").ToString + CambiaMoneda() + TxtTipoCambio.Text = drv("TipoCambio").ToString + DdlVendedor.SelectedValue = drv("CveVendedor").ToString + CvePAC = drv("CvePAC").ToString.ToEntero + + DdlUsoCFDI.SelectedValueExist(drv("CveUsoCFDI").ToString) + DdlMetodoPago33.SelectedValueExist(drv("CveMetodoPago33").ToString) + CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) + DdlFormaPago33.SelectedValueExist(drv("CveFormaPago33").ToString) + + DdlTipoComprobante.SelectedValueExist(drv("TipoDocto").ToString) + DdlTipoComprobante.Enabled = False + + HdnIVAOriginal.Value = TxtIVA.Text + HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString + HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) + + 'JJMQ 20160506: Se agrego para la validacion de pago de contado. + CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") + + If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then + DdlVendedor.Enabled = False + End If + CveContrato = drv("CveContrato").ToString.ToEntero + TabAlmacen.Enabled = False + TabDetalleVentas.Enabled = False + TabComplementos.Enabled = False + 'HplDownPDF.Visible = True + 'HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}", CveVenta))) + Updatetabs.Update() + UpPS.Update() + UpContado.Update() + + If CveDevolucion > 0 Then + HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString + 'CALCULA IMPUESTOS LOCALES CON LOS DATOS DEL CLIENTE AL MOMENTO DE LA NUEVA FACTURA NO LA VIEJA + 'CalculaTotalesImpuestosLocales() + 'CalculaTotales(CBool(ViewState("RetIVAFletes"))) + CalculaTotalesVenta() ' al hacer una refacturación que regenere los importes, sino vienen correctos + ''CARGA IMPUESTOS LOCALES DE LA VENTA ANTERIOR + 'If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then + ' If ObjVentas.DtResultados.Rows.Count > 0 Then + + ' GvImpuestosLocales2.DataSource = ObjVentas.DtResultados + ' GvImpuestosLocales2.DataBind() + + ' GvImpuestosLocales2.Enabled = False + ' GvImpuestosLocales2.Visible = True + ' End If + 'End If + + 'cuando es refacturacion, la fecha de pago debe de ser la misma + If UsuarioActual.Empresa.Funcionalidad(526) = "1" Then + ' Dim ObjVenta As New ClsVentas + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + TxtFechaPago.Text = ObjVentas.DtResultados(0)("FechaVencimiento").ToString.ToDate.ToShortDateString + End If + End If + 'ObjVenta.Dispose() + Else + TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString + End If + + CreaObjetosVentaDevolucion() + End If + TabComplementos.Enabled = True + End If + End If + + If OVenta Is Nothing Then + ObjVentas.Dispose() + End If + End Sub + Private Sub CargaSucursales() + If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.Enabled = False : DdlSubProyectoEjecucion.Enabled = False : DdlSubProyectoCobranza.Enabled = False + End Sub + + Private Sub CargaMetodosPago() + + 'FACTURACION 3.3 + + DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago + DdlMetodoPago33.DataBind() + DdlMetodoPago33.SelectedValue = "3" + + CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) + + 'End If + + End Sub + Private Sub CargaFormaPago(CveMetodoPago As Integer) + 'FACTURACION 3.3 + + Dim dtt As DataTable = Nothing + If CveMetodoPago > 0 Then + dtt = GlobalDTVtaFormaPago.FiltraParametros(If(CveMetodoPago = 1, " CveFormaPago <> 20 ", "CveFormaPago = 20")) + Else + dtt = GlobalDTVtaFormaPago + End If + DdlFormaPago33.Items.Clear() + 'DdlFormaPago33.ClearSelection() + 'DdlFormaPago33.DataBind() + DdlFormaPago33.DataSource = dtt + DdlFormaPago33.SelectedValue = dtt.FiltroPrimeroValor("CveFormaPago", "") + DdlFormaPago33.DataBind() + 'End If + End Sub + Private Sub CargaUsoCFDI() + DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica) + DdlUsoCFDI.DataBind() + End Sub + Private Sub CargaTiposRelacion() + DdlTiposRelacion.DataSource = GlobalDTVtaTiposRelacion + DdlTiposRelacion.DataBind() + DdlTiposRelacion.Items.Insert(0, New ListItem("-", "-1")) + End Sub + Private Sub CargaFormaEntrega() + TrFormaEntrega.Visible = True + DdlFormaEntrega.DataSource = GlobalDTVtaCondicionesEntrega(UsuarioActual.CveEmpresa) + DdlFormaEntrega.DataBind() + DdlFormaEntrega.Items.Insert(0, New ListItem("Seleccione", "-1")) + End Sub + Private Sub CargaMonedas() + DdlMoneda.DataSource = GlobalDTMonedas + DdlMoneda.DataBind() + + End Sub + Private Sub CargaProyecto() + Dim CveSubProyecto As Integer = 0 + Dim dtt As DataTable = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) + + DdlProyecto.DataSource = dtt + DdlProyecto.DataBind() + + DdlProyectoPyME.DataSource = dtt + DdlProyectoPyME.DataBind() + + CveSubProyecto = GetSubProyectoSucursal() + + CargaSubProyecto(CveSubProyecto) + + End Sub + Private Function GetSubProyectoSucursal() As Integer + Dim Retorno As Integer = 0 + + Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") + 'Dim dr As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") + + 'si hay un proyecto relacionado con el subproyecto + If dr IsNot Nothing AndAlso dr("CveSubProyecto").ToString.ToEntero > 0 Then + DdlProyecto.SelectedValueExist(dr("CveProyecto")) + Retorno = dr("CveSubProyecto").ToString.ToEntero + End If + + Return Retorno + + End Function + Private Sub CargarAlmacenes() + + If CveVenta > 0 Then + DivAlmacen.Visible = False + Else + ddlAlmacen.Items.Clear() + ddlAlmacen.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}") + ddlAlmacen.Items.Insert(0, New ListItem(" Seleccione ", "-1")) + ddlAlmacen.SelectedValue = "-1" + ddlAlmacen.DataBind() + If GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").Rows.Count > 0 Then + ddlAlmacen.SelectedValueExist(UsuarioActual.CveAlmacen) + End If + End If + + 'SI TIENE CONTRATO NO SE MUEVE + If Not CveContrato > 0 Then + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (4,10)") + DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1")) + DdlAlmacenAsignado.SelectedValue = "-1" + DdlAlmacenAsignado.DataBind() + DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").ToString.ToEntero) + End If + + If CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}") + DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1")) + DdlAlmacenAsignado.SelectedValue = "-1" + DdlAlmacenAsignado.DataBind() + DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString.ToEntero) + End If + + UpINV.Update() + End Sub + Private Sub CargaSubProyecto(Optional CveSubProyecto As Integer = -1) + DdlSubProyecto.Items.Clear() + DdlSubProyecto.SelectedValue = Nothing + If DdlProyecto.SelectedValue.ToEntero > 0 Then + DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) + End If + DdlSubProyecto.DataBind() + DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) + If CveSubProyecto > 0 Then DdlSubProyecto.SelectedValueExist(CveSubProyecto) + End Sub + + Private Sub CargaEmpresaCRM(CveEmpresaCRM As Integer) + Dim ObjCRM As New ClsCRM + If ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa, CveEmpresaCRM) Then + If ObjCRM.DtResultados.Rows.Count > 0 Then + ViewState("CveCliente") = IIf(ObjCRM.DtResultados.Rows(0)("CveCliente").ToString().ToEntero() > 0, ObjCRM.DtResultados.Rows(0)("CveCliente"), -1) + HdnCveCliente.Value = CveCliente.ToString() + If (CveCliente > 0) Then + CargaCliente(CveCliente) + VerificarContrato(True) + + 'DESACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto disabled") + TxtCodigo.ReadOnly = True + + UpCliente.Visible = True + UpEmpresaCRM.Visible = False + Else + LblEmpresaCRM.Text = ObjCRM.DtResultados.Rows(0)("Empresa").ToString + LblRFCCRM.Text = ObjCRM.DtResultados.Rows(0)("RFC").ToString + LblMedioCaptacionCRM.Text = ObjCRM.DtResultados.Rows(0)("MedioCaptacion").ToString + ChkEnviarFactura.Checked = False + ChkEnviarFactura.Visible = False + LblEnviarMail.Visible = False + + UPCondicionesPago.Visible = True + UpCliente.Visible = False + UpEmpresaCRM.Visible = True + End If + + DdlVendedor.SelectedValueExist(ObjCRM.DtResultados.Rows(0)("CveVendedorAsignado").ToString) + DdlVendedor.Enabled = False + LbAgregar.Enabled = True + End If + End If + ObjCRM.Dispose() + End Sub + Private Sub CargaCliente(CveCliente As Integer, Optional Estatus As Integer = -1) + + + + RBLPago.Items(0).Enabled = True + + Dim ObjCliente As New ClsClientes() + + If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus, TipoCliente:=-1) Then + If ObjCliente.DtResultados.Rows.Count > 0 Then + TxtCodigo.Text = ObjCliente.Codigo + DdlFormaEntrega.SelectedValueExist(ObjCliente.DtResultados(0)("CveCondicionEntrega").ToString) + LblCliente.Text = String.Format("{1}", CveCliente, ObjCliente.Nombre) + ViewState("NombreCliente") = ObjCliente.Nombre + LtlCliente.Text = ObjCliente.Nombre + ViewState("RequiereOC") = ObjCliente.RequiereOC + EnviarCorreoCliente = ObjCliente.EnviarFactura + EstatusCliente = ObjCliente.Estatus + + ClienteEsDistribuidor = Boolean.Parse(ObjCliente.DtResultados.Rows(0)("EsDistribuidor").ToString) + + If EstatusCliente = False And Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") And (CveVenta <= 0 Or EsCreaApartirDe) Then + Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) + End If + + 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE + If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then + ChkEnviarFactura.Checked = False + ChkEnviarFactura.Visible = False + LblEnviarMail.Visible = False + Else + ChkEnviarFactura.Visible = True + ChkEnviarFactura.Checked = EnviarCorreoCliente + LblEnviarMail.Visible = True + End If + + ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail) + ViewState("MailCC") = ObjCliente.NotificarA + LblDireccion.Text = ObjCliente.Direccion + LblColonia.Text = ObjCliente.Colonia + LblCiudad.Text = ObjCliente.Ciudad + LblEstado.Text = ObjCliente.Estado + LblCP.Text = ObjCliente.CP + LblRFC.Text = ObjCliente.RFC + LblTelefono.Text = ObjCliente.Telefono + LblRetIVA.Text = ObjCliente.RetIVA.ToString.FormatoNumero(5) + LblRetISR.Text = ObjCliente.RetISR.ToString.FormatoNumero(5) + ViewState("ClienteRetIVA") = ObjCliente.RetIVA / 100 + ViewState("ClienteRetISR") = ObjCliente.RetISR / 100 + + ViewState("RetIVAFletes") = ObjCliente.RetieneIVAFletes + If ObjCliente.RetieneIVAFletes Then + TrRetIVA.Style.Add("display", "") + UsuarioActual.Empresa.MostrarRetIVA = True + End If + + + + + ViewState("Vendedor") = ObjCliente.Vendedor + ViewState("CtaContable") = ObjCliente.CuentaContable + ViewState("IdCtaContClientes") = ObjCliente.IdCtaContClientes + ViewState("CveCuentaClientes") = ObjCliente.CveCuentaClientes + ViewState("IdCtaContMonedaExtranjera") = ObjCliente.IdCtaContMonedaExtranjera + ViewState("IdCtaContComplementaria") = ObjCliente.IdCtaContComplementaria + ViewState("IdCtaContAnticipos") = ObjCliente.IdCtaContAnticipos + ViewState("CveCuentaAnticipos") = ObjCliente.CveCuentaAnticipos + ViewState("IdCtaContRetIVA") = ObjCliente.IdCtaContRetIVA + ViewState("CveCuentaRetIVA") = ObjCliente.CveCuentaRetIVA + ViewState("IdCtaContRetISR") = ObjCliente.IdCtaContRetISR + ViewState("CveCuentaRetISR") = ObjCliente.CveCuentaRetISR + ViewState("CodCliente") = ObjCliente.Codigo + + ViewState("CliNoExt") = ObjCliente.NoExt + ViewState("CliNoInt") = ObjCliente.NoInt + ViewState("CliLocalidad") = If(ObjCliente.Localidad.Trim.Length = 0, ObjCliente.Ciudad.Trim, ObjCliente.Localidad.Trim) + ViewState("CliPais") = ObjCliente.Pais + ImprimeNombreSucursal = ObjCliente.ImprimeNombreSucursal + 'ViewState("NumCtaPago") = ObjCliente.NumCtaPago + ViewState("ClienteDesglosaIEPS") = ObjCliente.DesglosaIEPS + If Not ClienteDesglosaIEPS Then + DivClienteMsg.Visible = True + LtlClienteMsg.Text = "Cálculo sin desglose de IEPS" + End If + + Dim dr As DataRow = Nothing + dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal = 1 And Estatus = 'Activo' AND CveEmpresa = " & UsuarioActual.CveEmpresa) + If dr IsNot Nothing Then + ViewState("MatCalle") = dr("Calle") + ViewState("MatNoExt") = dr("NoExt") + ViewState("MatNoInt") = dr("NoInt") + ViewState("MatColonia") = dr("Colonia") + ViewState("MatLocalidad") = dr("Localidad") + ViewState("MatMunicipio") = dr("Municipio") + ViewState("MatEstado") = dr("Estado") + ViewState("MatPais") = dr("Pais") + ViewState("MatCP") = dr("CP") + End If + + 'HABILITA LA OPCION DE DIRECCION DE ENVIO + If UsuarioActual.CveEmpresa.Contiene(1, 72, 119) Then + trDireccionEnvio.Visible = True + CargaDireccionesEnvio() + End If + + If CveCliente = 239903 AndAlso UsuarioActual.CveEmpresa = 119 Then + DdlMetodoPago33.Enabled = False + ObjCliente.CveMetodoPago = 1 ' PUE, y que no se pueda modificar + Else + DdlMetodoPago33.Enabled = True + End If + + If CveVenta <= 0 Or EsCreaApartirDe Or NuevaFactura = 1 Then + CveMetodoPagoCliente = ObjCliente.CveMetodoPago + + + DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33) + CambiaMetodoPago33() + DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) + DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI) + End If + + PlazoCobranza = ObjCliente.PlazoCobranza + PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision + + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then + TxtFechaPago.ReadOnly = True + Calendario.Enabled = False + imgCalendario.Visible = False + End If + + 'funcionalidad EnviarSMSTimbrado + If CveVenta <= 0 And UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue = "Ing" Then + If ObjCliente.CobranzaTelefono <> "" Then + LblMensaje.Text = $"Se enviará mensaje SMS a {ObjCliente.CobranzaTelefono}" + Else + LblMensaje.Text = $"El Cliente no tiene teléfono para envío SMS " + End If + LblMensaje.Visible = True + End If + + 'If Not ObjCliente.RFC = "XAXX010101000" Then + ' TxtNumCtaPago.Text = ObjCliente.NumCtaPago + 'End If + + 'Complementos + + + 'COMERCIO EXTERIOR + ViewState("AplicaComercioExterior") = ObjCliente.AplicaComercioExterior + ViewState("CveTipoOperacion") = ObjCliente.CveTipoOperacion + ViewState("CvePedimento") = ObjCliente.CvePedimento + ViewState("CveIncoterm") = ObjCliente.CveIncoterm + + LblTipoOperacion.Text = ObjCliente.ClaveSATTipoOperacionDescripcion + LblClavePedimento.Text = ObjCliente.ClaveSATPedimentoDescripcion + + If ObjCliente.AplicaComercioExterior Then + DdlSATMotivoTraslado.DataSource = GlobalDTSATMotivoTraslado + DdlSATMotivoTraslado.DataBind() + DdlSATMotivoTraslado.SelectedValueExist(ObjCliente.CveMotivoTraslado) + DdlIncoterm.Items.Clear() + DdlIncoterm.DataSource = GlobalDTIncoterm() + DdlIncoterm.DataBind() + DdlIncoterm.SelectedValueExist(ObjCliente.CveIncoterm) + CargaPais() + DdlComExtPais.SelectedValueExist(ObjCliente.CvePais) + CargaEstado() + DdlComExtEstado.SelectedValueExist(ObjCliente.CveEstado) + If ObjCliente.ClaveSATPais = "MEX" Then + CargaMunicipio() + CargaColonia() + Else + If ObjCliente.ClaveSATPais.Contiene("USA", "CAN") Then + DdlComExtEstado.Visible = True + Else + TxtComExtEstado.Visible = True : DdlComExtEstado.Visible = False + End If + TxtComExtMunicipio.Text = ObjCliente.ComExtMunicipio + TxtComExtColonia.Text = ObjCliente.ComExtColonia + TxtComExtMunicipio.Visible = True : TxtComExtColonia.Visible = True + + End If + TxtNumRegIdTrib.Text = ObjCliente.NumRegIdTrib + TxtDestinatarioNombre.Text = ObjCliente.Nombre + TxtComExtCalle.Text = ObjCliente.Direccion + TxtComExtNumero.Text = ObjCliente.NoExt + TxtComExtCP.Text = ObjCliente.CP + + End If + + 'FEMSA + ViewState("AplicaFEMSA") = ObjCliente.AplicaFEMSA + TxtFEMSA_NumSociedad.Text = ObjCliente.FEMSA_NumSociedad + TxtFEMSA_NumProveedor.Text = ObjCliente.FEMSA_NumProveedor + TxtFEMSA_Mail.Text = ObjCliente.FEMSA_Mail + 'DETALLISTA + ViewState("AplicaDetallista") = ObjCliente.AplicaDetallista + TxtDet_GLNComprador.Text = ObjCliente.Detallista_GLNComprador + TxtDet_Departamento.Text = ObjCliente.Detallista_Departamento + TxtDet_GLNVendedor.Text = ObjCliente.Detallista_GLNVendedor + TxtDet_NumProv.Text = ObjCliente.Detallista_NumProveedor + + Txt7ElevenNumProveedor.Text = ObjCliente.SevenEleven_NumProveedor.Trim + + ViewState("AplicaFord") = ObjCliente.AplicaFord + TxtFordGSDB.Text = ObjCliente.Ford_GSDB + + 'SELECIONAMOS VENDEDOR - SI ESTA EN MODO EDICIÓN SE QUEDA EL VENDEDOR ORIGINAL + If Not ModalidadEdicion Then + If ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero > 0 Then + DdlVendedor.SelectedValueExist(ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero) + End If + + 'SI EL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO + If Not DdlVendedor.SelectedValue.ToEntero > 0 Then + DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) + End If + End If + + If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then + DdlVendedor.Enabled = False + End If + + UpFacturar.Update() + + 'SI LA VENTA YA ESTA REGISTRADA NO DEBE HABILITAR ACCIONES + If CveVenta <= 0 Then + LnkRemisiones.Visible = If(UsuarioActual.TienePermisoProceso(199), True, False) : LnkOCs.Visible = True : LnkCotizaciones.Visible = True : LnkPedido2SinFacturar.Visible = True : InicializaAplicarNCMasiva() + End If + + If UsuarioActual.Empresa.CvePlataforma = 2 Then LnkOCs.Visible = False + If UsuarioActual.Empresa.UsaInventarios Then + RblTipo.Items.Remove(RblTipo.Items.FindByValue("1")) + RblTipo.Items.Remove(RblTipo.Items.FindByValue("2")) + End If + UpnTools.Update() + 'UpRemisionesFacturas.Update() + + If Not CveVenta > 0 Then + If ObjCliente.DtResultados.Rows.Count > 0 Then + If UsuarioActual.TienePermisoProceso(152) Then + DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto) + DdlSubProyectoDatos.Enabled = False + Else + DdlSubProyectoDatos.SelectedValueExist(ObjCliente.CveSubProyecto) + End If + 'RECARGA LOS VALORES DE LA SUCURSAL + CambiaSucursal() + UpParametros.Update() + End If + End If + + DdlSucursalCliente.Items.Clear() + If ObjCliente.GetSucursales(CveCliente) Then + DdlSucursalCliente.DataSource = ObjCliente.DtResultados + If ObjCliente.DtResultados.Rows.Count > 0 Then + trsucursalciente.Visible = True + Else + trsucursalciente.Visible = False + End If + Else + trsucursalciente.Visible = False + DdlSucursalCliente.DataSource = Nothing + End If + DdlSucursalCliente.Items.Insert(0, New ListItem("Matriz", "-1")) + DdlSucursalCliente.DataBind() + + 'CargaFolios() + + CargaDatosEstimaciones(CveCliente) + + If ObjCliente.GetClienteImpuestosLocales(CveCliente) Then + 'se cargan impuestos locales + Dim DtClienteImpuesto As DataTable = ObjCliente.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") + + If DtClienteImpuesto IsNot Nothing AndAlso DtClienteImpuesto.Rows.Count > 0 Then + + ' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear() + TmpDTImpuestos = DtClienteImpuesto + + GvImpuestosLocales2.DataSource = TmpDTImpuestos + GvImpuestosLocales2.DataBind() + + + If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then + TrOtros.Visible = True + GvImpuestosLocales2.Visible = True + TrOtros.Style.Add("display", "") + Else + TrOtros.Visible = False + GvImpuestosLocales2.Visible = False + End If + DtClienteImpuesto.Dispose() + + End If + UpImpuestos.Update() + + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Cot") Then + TrAtencionA.Visible = True + TrDireccion.Visible = False + TrCiudad.Visible = False + TrRFC.Visible = False + tdTelefonoGen.Visible = False + tdTxtTelefonoGen.Visible = False + ElseIf ObjCliente.RFC = "XAXX010101000" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ret") Then + TrAtencionA.Visible = True + TrDireccion.Visible = False + TrCiudad.Visible = False + TrRFC.Visible = False + tdTelefonoGen.Visible = True + tdTxtTelefonoGen.Visible = True + Else + 'TrAtencionA.Visible = False + TrDireccion.Visible = True + TrCiudad.Visible = True + TrRFC.Visible = True + tdTelefonoGen.Visible = False + tdTxtTelefonoGen.Visible = False + TxtAtencionA.Text = "" + TxtTelefonoGenerico.Text = "" + End If + + TrAtencionA.Visible = True + tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") + tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") + + + LbAgregar.Enabled = True + LnkAgregarPyME.Enabled = True + + CargarAlmacenes() + + CargaDocumentacionCliente() + + If UsuarioActual.CveEmpresa.Contiene(72, 80, 1, 119) Then + BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)});" + BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") + BtnEmitirImprimir.Attributes.Add("data-popout", "true") + BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") + BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") + BtnEmitirImprimir.Attributes.Add("data-html", "true") + End If + + 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO + If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO + BtnEmitirImprimir.Visible = True + TrVistaPrevia.Visible = True + 'Else + ' BtnEmitirImprimir.Visible = EstatusCliente + ' TrVistaPrevia.Visible = EstatusCliente + End If + + TrVistaPrevia.Visible = True + + If Not (ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem") Then + CargaRestriccionesCreditoCliente(True) + End If + + + UpFacturar.Update() + UpEstatus.Update() + UpPS.Update() + UpParametros.Update() + UPCondicionesPago.Update() + UpDetalle.Update() + UpComplementos.Update() + UpCliente.Update() + UpAplicarNC.Update() + UpINV.Update() + UPPVentas.Update() + UPComplementosSAT.Update() + UpnTools.Update() + Else + Alert("Ocurrió un error al cargar los datos del cliente. Por favor vuelva a intentar.", TipoMensaje.MsgError) + End If + End If + ObjCliente.Dispose() + + If CveCliente > 0 Then CargaAnticipos(CveCliente) : UpAnticipos.Update() + + + If RequiereOC Then + Dim Documentacion As String = "" + 'RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });", "ModalArchivos") + Dim Count = 0 + For Each GvRow As GridViewRow In GvDocumentosCliente.Rows + If GvRow.DataKey("Orden").ToEntero = 1 Then + IndexDocumentoCliente = Count + Documentacion = GvRow.DataKey("Documentacion").ToString + AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString + Exit For + End If + Count = +1 + Next + LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion + BtnModalClienteDocumentoCancelar.Visible = False + + If CveVenta <= 0 Then + LnkUploadDocumentacionCliente.Visible = True + End If + + UpModalTitleUploadDocumentoCliente.Update() + UpModalButtonUploadDocumentoCliente.Update() + UPObservaciones.Update() + ' RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});", "modalOC") + End If + + End Sub + + Private Sub CargaRestriccionesCreditoCliente(Optional Alertas As Boolean = False) + Dim ObjCliente As New ClsClientes() + If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa) Then + If ObjCliente.DtResultados.Rows.Count > 0 Then + If UsuarioActual.CveEmpresa.Contiene(72, 119) AndAlso ObjCliente.DtResultados.Rows(0)("PermiteCredito").ToString = "False" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") AndAlso CveVenta < 1 Then + RBLPago.SelectedValue = "2" + RBLPago.Items(0).Enabled = False + RBLPago_SelectedIndexChanged(Nothing, Nothing) + If UsuarioActual.CveEmpresa.Contiene(119) AndAlso Not UsuarioActual.TienePermisoProceso(268) Then + DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") + DdlTipoComprobante.SelectedValue = "PA" + TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString + 'si llegó por la opción de cotización no debe de restringuir + If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot" + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + End If + UPCondicionesPago.Update() + ElseIf UsuarioActual.CveEmpresa.Contiene(72, 119) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "Cot", "PA") AndAlso CveVenta < 1 Then + RBLPago.SelectedValue = "1" + RBLPago_SelectedIndexChanged(Nothing, Nothing) + UPCondicionesPago.Update() + Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero) + + If CreditoDispo > 0 Then + TrCreditoDisponible.Visible = True + LblCreditoDisponible.Text = CreditoDispo.FormatoNumero + If PorcentajeCredito > 80 Then TrPorcentajeCredito.Visible = True : LblPorcentajeCredito.Text = $"{PorcentajeCredito.FormatoNumero}%" + If UsuarioActual.CveEmpresa = 119 AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "PA") Then + If LblRFC.Text.Trim <> "XAXX010101000" Then + Dim Vta As New ClsVentas + Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) + Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

    {0}", Vta.SerieVenta) + Vta.Dispose() + If Opcion > 0 Then + 'si la cotización no debe de existir este canddado + If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) + 'RBLPago.SelectedValue = "2" + 'RBLPago.Items(0).Enabled = False + RBLPago_SelectedIndexChanged(Nothing, Nothing) + UPCondicionesPago.Update() + DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") + DdlTipoComprobante.SelectedValue = "PA" + TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString + 'si llegó por la opción de cotización no debe de restringuir + If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot" + 'quito remisión y factura + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) + If Opcion = 1 Then + BtnEmitirImprimir.Visible = False + BtnsFacturar.Visible = False + BtnGenerarRemision.Visible = False + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + LnkOCs.Visible = False + End If + Else + ' el cliente tiene crédito disponible, no tiene bloqueo + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PA")) + + If UsuarioActual.TienePermisoProceso(60) Then DdlTipoComprobante.SelectedValueExistInsert("Ing", "Ingresos") 'puede facturar + If UsuarioActual.TienePermisoProceso(199) Then DdlTipoComprobante.SelectedValueExistInsert("Rem", "Remisión") ' puede remisionar + DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento) + + TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString + End If + Else + 'que no de crédito, solo contado + RBLPago.SelectedValue = "2" + RBLPago.Items(0).Enabled = False + End If + End If + Else + + If UsuarioActual.CveEmpresa = 119 AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ant", "PA") Then + Dim Vta As New ClsVentas + Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) + Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

    {0}", Vta.SerieVenta) + Vta.Dispose() + If Opcion > 0 Then + If Opcion = 1 Then + BtnEmitirImprimir.Visible = False + End If + If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) + Else + If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia) + End If + + 'RBLPago.SelectedValue = "2" + 'RBLPago.Items(0).Enabled = False + RBLPago_SelectedIndexChanged(Nothing, Nothing) + UPCondicionesPago.Update() + DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") + DdlTipoComprobante.SelectedValue = "PA" + TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString + 'si llegó por la opción de cotización no debe de restringuir + If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot" + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) + BtnsFacturar.Visible = False + BtnGenerarRemision.Visible = False + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + LnkOCs.Visible = False + End If + End If + UPPCreditoDisponible.Update() + ElseIf UsuarioActual.CveEmpresa.Contiene(119, 1) AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso CveVenta > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Pd2", "Cot") Or (DdlTipoComprobante.SelectedValue = "Rem" And ModalidadEdicion And ViewState("CveClienteAnterior").ToString.ToEntero > 0 And LblRFC.Text.Trim <> "XAXX010101000")) Then + Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero) + If CreditoDispo > 0 Then + Dim Vta As New ClsVentas + Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) + Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

    {0}", Vta.SerieVenta) + Vta.Dispose() + If Opcion > 0 Then + If ModalidadEdicion AndAlso ViewState("CveCliente").ToString.ToEntero <> ViewState("CveClienteAnterior").ToString.ToEntero And DdlTipoComprobante.SelectedValue = "Rem" And ViewState("CveClienteAnterior").ToString.ToEntero > 0 And LblRFC.Text.Trim <> "XAXX010101000" Then + ViewState("CveCliente") = ViewState("CveClienteAnterior").ToString.ToEntero + ObjCliente.Dispose() + CargaCliente(ViewState("CveCliente").ToString.ToEntero) + If Opcion > 0 Then + If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) + Else + If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia) + End If + BtnEmitirImprimir.Visible = False + BtnVistaPrevia.Visible = False + UpFacturar.Update() + Exit Sub + ElseIf DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso EsCreaApartirDe Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) + BtnGenerarRemision.Visible = False + BtnGenerarOS.Visible = False + BtnEmitirImprimir.Visible = True + BtnsFacturar.Visible = False + Else + + If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then + BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False) + End If + BtnGenerarRemision.Visible = False + BtnGenerarOS.Visible = False + BtnEmitirImprimir.Visible = False + BtnsFacturar.Visible = False + If ViewState("CveCliente").ToString.ToEntero <> ViewState("CveClienteAnterior").ToString.ToEntero Then + If Opcion > 0 Then + If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) + Else + If Alertas Then Alert("El cliente tiene límite de crédito agotado.", TipoMensaje.MsgAdvertencia) + End If + End If + End If + Else + BtnGeneraAutorizacion.Visible = False + If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then + BtnGenerarRemision.Visible = If(CveEstatus <> 21, True, False) + End If + End If + Else + BtnGenerarRemision.Visible = False + If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then + BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False) + End If + End If + End If + End If + End If + ObjCliente.Dispose() + End Sub + + + Private Sub CargaClienteSucursal(CveClienteSuc As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing) + Dim ObjCliente As New ClsClientes + If CveClienteSuc > 0 Then + If ObjCliente.GetSucursales(CveCliente, CveClienteSuc) Then + If ObjCliente.DtResultados.Rows.Count > 0 Then + Dim Correo = ObjCliente.DtResultados.Rows(0)("Correo").ToString + If Correo.Trim.Length > 0 Then + ViewState("Mail") = Correo + End If + LblDireccion.Text = ObjCliente.DtResultados.Rows(0)("Direccion").ToString + LblColonia.Text = ObjCliente.DtResultados.Rows(0)("Colonia").ToString + LblCiudad.Text = ObjCliente.DtResultados.Rows(0)("Ciudad").ToString + LblEstado.Text = ObjCliente.DtResultados.Rows(0)("Estado").ToString + 'TxtNumCtaPago.Text = ObjCliente.DtResultados.Rows(0)("NumCtaPago").ToString + LblTelefono.Text = ObjCliente.DtResultados.Rows(0)("Telefono").ToString + LblCP.Text = ObjCliente.DtResultados.Rows(0)("CP").ToString + ViewState("CliLocalidad") = ObjCliente.DtResultados.Rows(0)("Localidad").ToString + ViewState("CliPais") = ObjCliente.DtResultados.Rows(0)("Pais").ToString + ViewState("CliNoExt") = ObjCliente.DtResultados.Rows(0)("NoExt").ToString + ViewState("CliNoInt") = ObjCliente.DtResultados.Rows(0)("NoInt").ToString + DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString) + ViewState("CveClienteSucursal") = ObjCliente.DtResultados(0)("CveClienteSucursal").ToString + ViewState("CliCorreoCot") = ObjCliente.DtResultados.Rows(0)("CorreoCotizacion").ToString + + If ObjCliente.DtResultados.Rows(0)("Estatus").ToString <> "Activo" Then + RBLPago.Items(0).Enabled = False + Alert("La Sucursal/Departamento del cliente se encuentra inactivo", TipoMensaje.MsgAdvertencia) + Else + RBLPago.Items(0).Enabled = True + Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero, ObjVentas) + + TrCreditoDisponible.Visible = True + LblCreditoDisponible.Text = CreditoDispo.FormatoNumero + UPPCreditoDisponible.Update() + UpParametros.Update() + End If + + If CveVenta <= 0 Then CveMetodoPagoCliente = ObjCliente.DtResultados.Rows(0)("CveMetodoPago").ToString.ToEntero DdlMetodoPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago33").ToString) - DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty) - - DdlFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString) - DdlUsoCFDI.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveUsoCFDI").ToString) - End If - - If CveVenta < 0 Then TxtAtencionA.Text = ObjCliente.DtResultados.Rows(0)("Contacto").ToString - End If - Else - Alert("No se pudieron cargar los datos de la sucursal", TipoMensaje.MsgAdvertencia) - End If - Else - If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then - If ObjCliente.DtResultados.Rows.Count > 0 Then - ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail) - LblDireccion.Text = ObjCliente.Direccion - LblColonia.Text = ObjCliente.Colonia - LblCiudad.Text = ObjCliente.Ciudad - LblEstado.Text = ObjCliente.Estado - LblCP.Text = ObjCliente.CP - LblTelefono.Text = ObjCliente.Telefono - DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString) - ViewState("CliNoExt") = ObjCliente.NoExt - ViewState("CliNoInt") = ObjCliente.NoInt - PlazoCobranza = ObjCliente.PlazoCobranza - - If CveVenta <= 0 Then + DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty) + + DdlFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString) + DdlUsoCFDI.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveUsoCFDI").ToString) + End If + + If CveVenta < 0 Then TxtAtencionA.Text = ObjCliente.DtResultados.Rows(0)("Contacto").ToString + End If + Else + Alert("No se pudieron cargar los datos de la sucursal", TipoMensaje.MsgAdvertencia) + End If + Else + If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then + If ObjCliente.DtResultados.Rows.Count > 0 Then + ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail) + LblDireccion.Text = ObjCliente.Direccion + LblColonia.Text = ObjCliente.Colonia + LblCiudad.Text = ObjCliente.Ciudad + LblEstado.Text = ObjCliente.Estado + LblCP.Text = ObjCliente.CP + LblTelefono.Text = ObjCliente.Telefono + DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString) + ViewState("CliNoExt") = ObjCliente.NoExt + ViewState("CliNoInt") = ObjCliente.NoInt + PlazoCobranza = ObjCliente.PlazoCobranza + + If CveVenta <= 0 Then CveMetodoPagoCliente = ObjCliente.CveMetodoPago DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33) - DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty) - - DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) - DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI) - End If - - End If - End If - End If - - 'SI LA SUCURSAL DEL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO - If Not DdlVendedor.SelectedValue.ToEntero > 0 Then - DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) - End If - - UPPVentas.Update() - UpEstatus.Update() - UPCondicionesPago.Update() - ObjCliente.Dispose() - End Sub - Private Function CargaCreditoDisponible(tCveCliente As Integer, tCveSucursalCliente As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing) As Decimal - Dim Retorno As Decimal = 0 - If UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then - - Dim ObjVentasAplciar As ClsVentas = Nothing - If ObjVentas IsNot Nothing Then - ObjVentasAplciar = ObjVentas - Else - ObjVentasAplciar = New ClsVentas - End If - - If ObjVentasAplciar.ObtenerCreditoRestante(tCveCliente, tCveSucursalCliente) Then - If ObjVentasAplciar.DtResultados.Rows.Count > 0 Then - - If tCveSucursalCliente > 0 Then - Retorno = ObjVentasAplciar.DtResultados(0)("LimiteRestanteSucursal").ToString.ToDecimal - PorcentajeCredito = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoSucursal").ToString.ToDecimal - Else - Retorno = ObjVentasAplciar.DtResultados(0)("LimiteRestanteCliente").ToString.ToDecimal - PorcentajeCredito = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoCliente").ToString.ToDecimal - End If - End If - End If - - If ObjVentas Is Nothing Then - ObjVentasAplciar.Dispose() - End If - - End If - Return Retorno - End Function - Private Sub CargaDdlSubProyectos() - DdlSubProyectoDatos.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ") - DdlSubProyectoDatos.DataBind() - DdlSubProyectoCobranza.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ") - DdlSubProyectoCobranza.DataBind() - DdlSubProyectoEjecucion.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ") - DdlSubProyectoEjecucion.DataBind() - DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) - DdlSubProyectoPyME.DataBind() - End Sub - Private Sub CargaClasificaciones() - If UsuarioActual.Empresa.UsaAC Then - DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") - DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") - Else - DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("Estado = 1", Orderby:="Clasificacion") - DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion") - End If - 'DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa) - DdlClasificacion.DataBind() - DdlClasificacionPyME.DataBind() - End Sub - Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost) - - Objeto.setEsWebService(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1") - - If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then - Objeto.ddl.Items.Clear() - 'Objeto.ddl.DataSource = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) - Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, Estatus:=1, AplicaParaVenta:=1) - Objeto.ddl.DataBind() - Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2")) - Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1")) - Else - Objeto.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) - Objeto.ddlWS.Attributes.Add("data-cveclasificacion", CveClasificacion.ToString) - Objeto.ddlWS.Attributes.Add("data-pagina", "ventas/ventas") - Objeto.ddlWS.Attributes.Add("data-Estatus", "1") - End If - - End Sub - Private Sub CargaNC(pCveVenta As Integer) - If pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then - - If IsNothing(Request("CveDevolucion")) AndAlso IsNumeric(Request("CveDevolucion")) Then - trNCFactura.Visible = True - End If - - If DdlNCFactura.Items.Count = 0 Then - Dim ObjClientes As New ClsVentas() - - If ObjClientes.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then - DTFacNC = ObjClientes.DtResultados - Dim drvv As DataRow = DTFacNC.FiltroPrimero("") - DTFacNC.Columns.Add("Factura", GetType(String), " Folio + ' - ' + Fecha + ' $' + Total") - HdnFolioFiscalNC.Value = drvv("FolioFiscal").ToString - - If DTFacNC IsNot Nothing AndAlso DTFacNC.Rows.Count > 0 Then - Me.CveEstatusRefacturacion = DTFacNC.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero() - HdnRFCVenta.Value = DTFacNC.Rows(0)("ClienteRFC").ToString() - End If - Else - DTFacNC = Nothing - End If - ObjClientes.Dispose() - - DdlNCFactura.DataSource = DTFacNC - DdlNCFactura.DataBind() - - DdlNCFactura.SelectedValueExist(pCveVenta) - DdlNCFactura.Enabled = False - End If - - Else - trNCFactura.Visible = False - End If - End Sub - Private Sub CargaCuentasTerminal() - DdlCuentasTerminal.Items.Clear() - DdlCuentaTerminalModal.Items.Clear() - - DdlCuentasTerminal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"}) - DdlCuentaTerminalModal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"}) - - DdlCuentasTerminal.DataBind() - DdlCuentaTerminalModal.DataBind() - - DdlCuentasTerminal.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlCuentaTerminalModal.Items.Insert(0, New ListItem("Seleccione", "-1")) - - UPTarjetaTermminal.Update() - UpCuentaTerminal.Update() - - End Sub - Public Sub CargaDdlNCPS() - - Dim CveSATNC = "84111506" - DdlNCPS.DataSource = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC - DdlNCPS.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlNCPS.DataBind() - - DdlNCPSAnt.DataSource = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC - DdlNCPSAnt.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlNCPSAnt.DataBind() + DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty) + + DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) + DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI) + End If + + End If + End If + End If + + 'SI LA SUCURSAL DEL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO + If Not DdlVendedor.SelectedValue.ToEntero > 0 Then + DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) + End If + + UPPVentas.Update() + UpEstatus.Update() + UPCondicionesPago.Update() + ObjCliente.Dispose() End Sub -#End Region + Private Function CargaCreditoDisponible(tCveCliente As Integer, tCveSucursalCliente As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing) As Decimal + Dim Retorno As Decimal = 0 + If UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then -#Region "G R I D V I E W S" + Dim ObjVentasAplciar As ClsVentas = Nothing + If ObjVentas IsNot Nothing Then + ObjVentasAplciar = ObjVentas + Else + ObjVentasAplciar = New ClsVentas + End If -#Region "GvPS" - Protected Sub GvPS_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvPS.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow Then - e.Row.Attributes("id") = e.Row.RowIndex.ToString - If e.Row.RowIndex = 0 Then - End If - - - If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then - 'MODO EDICION - - e.Row.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToEntero, -1) - e.Row.FCDropDownList("DdlUnidadMedida").DataBind() - e.Row.FCDropDownList("DdlUnidadMedida").SelectedValueExist(e.Row.DBCampo("CveUM")) - - e.Row.FCDropDownList("DdlClasificacion").DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1) - e.Row.FCDropDownList("DdlClasificacion").DataBind() - e.Row.FCDropDownList("DdlClasificacion").SelectedValue = e.Row.DBCampo("CveClasificacion") - CargaPS(e.Row.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero, e.Row.FCDropDownLost("DdlPS")) - e.Row.FCDropDownLost("DdlPS").SelectedText = e.Row.DBCampo("PS") - e.Row.FCDropDownLost("DdlPS").SelectedValue = e.Row.DBCampo("CvePS") - - - If e.Row.DBCampo("CveSubProyecto") = "-1" Then - 'cargo todos las opciones para - e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) - e.Row.FCDropDownList("DdlProyecto").DataBind() - e.Row.FCDropDownList("DdlProyecto").Items.Insert(0, New ListItem("Sin Proyecto Asignado", "-1")) - - e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, -1, 1) - 'e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectos.FiltraParametros("CveEmpresa = " & UsuarioActual.CveEmpresa & " AND CveProyecto = '" & DdlProyecto.SelectedValue & "'") - e.Row.FCDropDownList("DdlSubProyecto").DataBind() - 'e.Row.FCDropDownList("DdlSubProyectoEdit").SelectedValue = e.Row.DBCampo("CveSubProyecto") - e.Row.FCDropDownList("DdlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) - Else - Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, e.Row.DBCampo("CveSubProyecto").ToEntero, 1).FiltroPrimero("") - - If dr IsNot Nothing Then - e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) - e.Row.FCDropDownList("DdlProyecto").DataBind() - e.Row.FCDropDownList("DdlProyecto").SelectedValue = dr("CveProyecto").ToString - - e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, dr("CveProyecto").ToString.ToEntero, UsuarioActual.CveEmpresa, -1, 1) - e.Row.FCDropDownList("DdlSubProyecto").DataBind() - e.Row.FCDropDownList("DdlSubProyecto").SelectedValue = e.Row.DBCampo("CveSubProyecto") - - End If - - End If - - 'Si es una devolucion - If NuevaFactura = 0 Then - e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False - e.Row.FCDropDownList("DdlClasificacion").Enabled = False - e.Row.FCDropDownLost("DdlPS").Enabled = False - e.Row.FCDropDownList("DdlProyecto").Enabled = False - e.Row.FCDropDownList("DdlSubProyecto").Enabled = False - e.Row.FCTextBox("TxtPrecio").Enabled = False - ElseIf NuevaFactura = 1 Or CveContrato > 0 Then - e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False - e.Row.FCDropDownList("DdlClasificacion").Enabled = False - e.Row.FCDropDownLost("DdlPS").Enabled = False - e.Row.FCTextBox("TxtCantidad").Enabled = False - e.Row.FCTextBox("TxtPrecio").Enabled = False - e.Row.FCTextBox("TxtDescuento").Enabled = False - - If TieneAlmacen Then e.Row.FCLinkButton("imgD").Visible = False - - If UsuarioActual.TienePermisoProceso(222) Then - e.Row.FCDropDownList("DdlUnidadMedida").Enabled = True - e.Row.FCDropDownList("DdlClasificacion").Enabled = True - e.Row.FCDropDownLost("DdlPS").Enabled = True - e.Row.FCTextBox("TxtCantidad").Enabled = True - e.Row.FCTextBox("TxtPrecio").Enabled = True - e.Row.FCTextBox("TxtDescuento").Enabled = True - End If - - End If - - 'Si es facturacion de OC o Contrato - If CveContrato > 0 AndAlso Not CveVenta > 0 AndAlso Not CveCicloComercial > 0 Then - e.Row.FCLinkButton("imgClone").Visible = False - e.Row.FCTextBox("TxtOrden").Visible = True - e.Row.FCTextBox("TxtCantidad").Enabled = False - e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False - e.Row.FCDropDownList("DdlClasificacion").Enabled = False - e.Row.FCDropDownLost("DdlPS").Enabled = False - e.Row.FCDropDownList("DdlProyecto").Enabled = False - e.Row.FCDropDownList("DdlSubProyecto").Enabled = False - e.Row.FCTextBox("TxtPrecio").Enabled = False - End If - - If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then - e.Row.FCLinkButton("imgClone").Visible = False - e.Row.FCTextBox("TxtOrden").Visible = True - e.Row.FCTextBox("TxtCantidad").Enabled = False - e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False - e.Row.FCDropDownList("DdlClasificacion").Enabled = False - e.Row.FCDropDownList("DdlProyecto").Enabled = False - e.Row.FCDropDownList("DdlSubProyecto").Enabled = False - e.Row.FCLiteral("LtlPSEdit").Visible = True - e.Row.FCDropDownLost("DdlPS").Visible = False - e.Row.FCDropDownLost("DdlPS").Enabled = False - e.Row.FCTextBox("TxtPrecio").Enabled = True - End If - - If CveCicloComercial > 0 Then - e.Row.FCTextBox("TxtPrecio").Enabled = True - End If - - 'CUANDO SE QUIERE FACTURAR UNA REMISIÓN NO PERMITE EDITAR SU PRECIO - If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso (e.Row.DBCampo("CveVentaDetalle").ToEntero > 0 Or e.Row.DBCampo("CveVentaDetalleRemision").ToEntero > 0) Then - e.Row.FCTextBox("TxtPrecio").Enabled = False - End If - - 'PERMISO EDITAR REM - If e.Row.DBCampo("TipoDocto") = "Rem" And ModalidadEdicion Then - 'LO PERMITIDO MODIFICAR - e.Row.FCTextBox("TxtPrecio").Enabled = True - e.Row.FCTextBox("TxtObsPS").Enabled = True - e.Row.FCTextBox("TxtCantidad").Attributes.Add("onblur", $"ValidarCantidadMenor(this,{e.Row.DBCampo("CantidadInventario").ToDouble})") - - 'LO NO PERMITIDO MODIFICAR - e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False - 'e.Row.FCDropDownList("DdlClasificacion").Enabled = False - 'e.Row.FCDropDownLost("DdlPS").Enabled = False - - e.Row.FCTextBox("TxtTiempoEntrega").Enabled = False - e.Row.FCDropDownList("DdlProyecto").Enabled = False - e.Row.FCDropDownList("DdlSubProyecto").Enabled = False - - e.Row.FCLinkButton("imgD").Visible = False - End If - - 'If UsuarioActual.CveEmpresa = 119 Then - ' e.Row.FCTextBox("TxtDescuento").Enabled = False - 'End If - - Else - 'MODO NORMAL - - If UsuarioActual.Empresa.UsaAC Then - e.Row.FCDropDownList("DdlFR").DataSource = DTPresupuestoIngresos - e.Row.FCDropDownList("DdlFR").DataBind() - e.Row.FCDropDownList("DdlFR").SelectedValue = e.Row.DBCampo("CvePresupuestoIngreso") - 'e.Row.FCDropDownList("DdlFR").Enabled = False - End If - - If e.Row.DataKey("IEPS").ToDouble > 0 Then : TrIEPS.Visible = True : End If - - If NuevaFactura = 1 Then - If Not UsuarioActual.TienePermisoProceso(222) Then - e.Row.FCLinkButton("imgD").Visible = False - e.Row.FCLinkButton("imgE").Visible = False - End If - If TieneAlmacen Then - e.Row.FCLinkButton("imgD").Visible = False - End If - End If - - If (CveContrato > 0 AndAlso Not CveVenta > 0) Then - e.Row.FCLinkButton("imgD").Visible = False - End If - - If DdlContratosModal.DataSource IsNot Nothing AndAlso CveCicloComercial <= 0 Then - e.Row.FCLinkButton("imgE").Visible = False - End If - - 'Si es Cotizacíon - If e.Row.DBCampo("TipoDocto") = "Cot" Then - ThTiempoEntrega.Visible = True - ThTiempoEntrega2.Visible = True - GvPS.Columns(5).Visible = True - End If - - 'Si es facturacion de OC - If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then - e.Row.FCLinkButton("imgClone").Visible = False - e.Row.FCTextBox("TxtOrden").Visible = True - End If - - If UsuarioActual.Empresa.CvePlataforma = 2 Then - e.Row.FCLinkButton("imgE").Visible = False - e.Row.FCLinkButton("imgEPyME").Visible = True - End If - - If UsuarioActual.Empresa.Tipo_CentroCosto = 2 Or UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then - e.Row.FCLabel("LblProyecto").Visible = False - End If - - If CveVenta > 0 Then 'And e.Row.DBCampo("TipoDocto") = "Rem" - If ModalidadEdicion Then - e.Row.FCLinkButton("imgE").Visible = Not e.Row.DBCampo("CantidadFacturadaRem").ToDouble > 0 - e.Row.FCLinkButton("imgD").Visible = Not e.Row.DBCampo("CantidadInventario").ToDouble > 0 - ElseIf Not CveDevolucion > 0 Then - e.Row.FCLinkButton("imgE").Visible = False - e.Row.FCLinkButton("imgD").Visible = False - End If - End If - - 'CANTIDAD FACTURADA - Select Case e.Row.DBCampo("TipoDocto") - Case "Cot" - e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaCot").ToDecimal.ToString("#,##0.##") - Case "Pd2" - e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaPed2").ToDecimal.ToString("#,##0.##") - End Select - - 'If GvInv.Rows.Count > 0 AndAlso ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem" AndAlso e.Row.DataKey("CveVentaDetalle").ToString.ToEntero > 0 Then - ' e.Row.FCLinkButton("imgE").Enabled = False - ' e.Row.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen." - 'End If - - End If - End If - End Sub - Protected Sub GvPS_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvPS.RowEditing - GvPS.EditIndex = e.NewEditIndex - GvPS.DataSource = TmpDT - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - GvPS.DataBind() - End Sub - Protected Sub GvPS_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvPS.RowCancelingEdit - GvPS.EditIndex = -1 - GvPS.DataSource = TmpDT - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - GvPS.DataBind() - End Sub - Protected Sub GvPS_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvPS.RowUpdating - 'Dim TipoDescuento As Integer - Dim Cantidad, PU, Descuento As Decimal - Dim CuentaPredial As String - - Cantidad = GvPS.Rows(e.RowIndex).FCTextBox("TxtCantidad").Text.ToDecimal - PU = Math.Round(GvPS.Rows(e.RowIndex).FCTextBox("TxtPrecio").Text.ToDecimal, 6) - Descuento = Math.Round(GvPS.Rows(e.RowIndex).FCTextBox("TxtDescuento").Text.ToDecimal, NumeroDecimales) - CuentaPredial = GvPS.Rows(e.RowIndex).FCTextBox("TxtPredial").Text.Trim - - Dim DatarowPS As DataRow = Nothing - DatarowPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero).FiltroPrimero("") ' Estado = -1 - - 'verifica si tiene ventaminima - If Cantidad > 0 AndAlso DatarowPS("VentaMinima").ToString.ToDecimal > 0 AndAlso (DdlTipoComprobante.SelectedValue = "Rem" Or DdlTipoComprobante.SelectedValue = "Ing") Then - 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... - If Cantidad Mod DatarowPS("VentaMinima").ToString.ToDecimal <> 0 Then - Alert(String.Format("El producto se vende solo en cantidades de {0}", DatarowPS("VentaMinima").ToString)) - Exit Sub - End If - End If - - If TmpDT.Rows(e.RowIndex)("CvePS").ToString <> GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue Then - 'eliminar y cargar el ps *** - Dim DdlUM As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida") - Dim DdlCla As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlClasificacion") - - TmpDT.Rows.Remove(TmpDT.Rows(e.RowIndex)) - CalculaUsados() - AgregarProductoServicio(Cantidad, DdlUM.SelectedValue.ToEntero, DdlUM.SelectedItem.Text, DdlCla.SelectedValue.ToEntero, DdlCla.SelectedItem.Text, - GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedText, - GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.Trim, PU, Descuento, - GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text, - GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text, - CuentaPredial:=CuentaPredial, CveVentaDetalle:=GvPS.Rows(e.RowIndex).DataKey("CveVentaDetalle").ToString.ToEntero, SeActualiza:=True) - - ' TmpDT.Rows(e.RowIndex)("CveUM") = Ddl.SelectedValue - ' TmpDT.Rows(e.RowIndex)("UM") = Ddl.SelectedItem.Text - - If UsuarioActual.Empresa.Funcionalidad(533).ToEntero > 0 Then - - GvPS.EditIndex = -1 - GvPS.DataSource = TmpDT - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - GvPS.DataBind() - CargaGVInv(DtInv) - CalculaUsados() - End If - - Else - If Not ClienteDesglosaIEPS Then - Dim DrPS As DataRow = Nothing - - 'DrPS = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero, Estatus:=-1).FiltroPrimero("") - - DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero).FiltroPrimero("") - - PU = PU * (1 + DrPS("IEPSPorcentaje").ToString.ToDecimal) - - TmpDT.Rows(e.RowIndex)("PorcentajeIEPS") = 0 - End If - - Dim TotalCalculableImpuestos As Decimal = ((Cantidad * PU) - (Descuento)) - - - TmpDT.Rows(e.RowIndex)("CveUM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedValue.ToEntero - TmpDT.Rows(e.RowIndex)("UM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedItem.Text - TmpDT.Rows(e.RowIndex)("Cantidad") = Cantidad - TmpDT.Rows(e.RowIndex)("Obs") = GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.Trim - TmpDT.Rows(e.RowIndex)("TiempoEntrega") = GvPS.Rows(e.RowIndex).FCTextBox("TxtTiempoEntrega").Text.Trim - TmpDT.Rows(e.RowIndex)("PU") = PU - TmpDT.Rows(e.RowIndex)("Descuento") = Descuento - TmpDT.Rows(e.RowIndex)("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) - TmpDT.Rows(e.RowIndex)("ImporteIVA") = Math.Round(TmpDT.Rows(e.RowIndex)("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - TmpDT.Rows(e.RowIndex)("ImporteIEPS") = Math.Round(TmpDT.Rows(e.RowIndex)("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - TmpDT.Rows(e.RowIndex)("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) - TmpDT.Rows(e.RowIndex)("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) - TmpDT.Rows(e.RowIndex)("PorcentajeRetIVA") = ClienteRetIVA - TmpDT.Rows(e.RowIndex)("PorcentajeRetISR") = ClienteRetISR - TmpDT.Rows(e.RowIndex)("CuentaPredial") = CuentaPredial - - If GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").Items.Count = 0 Then - TmpDT.Rows(e.RowIndex)("Proyecto") = "Sin Proyecto Asignado" - TmpDT.Rows(e.RowIndex)("CveSubProyecto") = -1 - Else - TmpDT.Rows(e.RowIndex)("Proyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text - End If - - - If GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").Items.Count = 0 Then - TmpDT.Rows(e.RowIndex)("SubProyecto") = "Sin SubProyecto Asignado" - Else - TmpDT.Rows(e.RowIndex)("SubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text - TmpDT.Rows(e.RowIndex)("CveSubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue - End If - - GvPS.EditIndex = -1 - GvPS.DataSource = TmpDT - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - GvPS.DataBind() - CargaGVInv(DtInv) - CalculaUsados() - End If - - CalculaTotalesVenta() - - 'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW - If AplicaComercioExterior Then - CargaGvComercioExterior() - End If - - - 'JJMQ 20160506: Se agrego para la validacion de pago de contado. - CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") - - UpPS.Update() - UpContado.Update() - - - 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) - TmpDT.Rows.Remove(DbRow) - - CalculaUsados() - - GvPS.DataSource = TmpDT - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - GvPS.DataBind() - CargaGVInv(DtInv) - CalculaTotalesVenta() - - Alert("Eliminado Correctamente.", TipoMensaje.MsgInformacion) - 'JJMQ 20160506: Se agrego para la validacion de pago de contado. - CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") - - UpContado.Update() + If ObjVentasAplciar.ObtenerCreditoRestante(tCveCliente, tCveSucursalCliente) Then + If ObjVentasAplciar.DtResultados.Rows.Count > 0 Then + + If tCveSucursalCliente > 0 Then + Retorno = ObjVentasAplciar.DtResultados(0)("LimiteRestanteSucursal").ToString.ToDecimal + PorcentajeCredito = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoSucursal").ToString.ToDecimal + Else + Retorno = ObjVentasAplciar.DtResultados(0)("LimiteRestanteCliente").ToString.ToDecimal + PorcentajeCredito = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoCliente").ToString.ToDecimal + End If + End If + End If + + If ObjVentas Is Nothing Then + ObjVentasAplciar.Dispose() + End If + + End If + Return Retorno + End Function + Private Sub CargaDdlSubProyectos() + DdlSubProyectoDatos.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ") + DdlSubProyectoDatos.DataBind() + DdlSubProyectoCobranza.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ") + DdlSubProyectoCobranza.DataBind() + DdlSubProyectoEjecucion.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ") + DdlSubProyectoEjecucion.DataBind() + DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) + DdlSubProyectoPyME.DataBind() End Sub -#End Region + Private Sub CargaClasificaciones() + If UsuarioActual.Empresa.UsaAC Then + DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") + DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") + Else + DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("Estado = 1", Orderby:="Clasificacion") + DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion") + End If + 'DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa) + DdlClasificacion.DataBind() + DdlClasificacionPyME.DataBind() + End Sub + Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost) -#Region "GvINV" + Objeto.setEsWebService(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1") - Private Sub GvInv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvInv.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow Then - - 'SERIE ALMACEN - If e.Row.DBCampo("CveTipoInvPS").ToEntero = 5 Then - If CveVenta > 0 Then - e.Row.FCLiteral("LtlSerie").Visible = True - Else - e.Row.FCTextBox("TxtSerie").Visible = True - e.Row.FCTextBox("TxtSerie").Attributes.Remove("onkeypress") - e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeypress", String.Format("SeriePS(event,{0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID)) - e.Row.FCTextBox("TxtSerie").Attributes.Remove("onblur") - e.Row.FCTextBox("TxtSerie").Attributes.Add("onblur", String.Format("SeriePSBlur({0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID)) - End If - - - 'e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) - - 'e.Row.FCTextBox("LblCodigo").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) - 'e.Row.FCTextBox("LblCodigo").Attributes.Add("onblur", String.Format("LimpiaAF(1, '{0}'); AFBlurEdit(this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) - End If - - If e.Row.DBCampo("CvePS") = "" Then - e.Row.FCLiteral("LtlPS").Text = String.Format("Folio: {1} Fecha: {2} -- {3} -- {4}", 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) - - e.Row.FCCheckBox("cbInv").Visible = False - e.Row.FCCheckBox("cbInv").Enabled = False - - If e.Row.DataKey("Origen").ToEntero > 0 Then - e.Row.BackColor = Drawing.Color.FromArgb(224, 130, 131) - e.Row.ForeColor = Drawing.Color.White - e.Row.Font.Bold = True - Else - e.Row.CssClass = "SubTotales" - End If - Else - - e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left - e.Row.FCCheckBox("cbInv").Visible = True - e.Row.FCCheckBox("cbInv").Enabled = True - - 'SI ES REMISION O VENTA DEBE SALIR DE ALMACEN - If UsuarioActual.TienePermisoProceso(157) AndAlso e.Row.DBCampo("CvePS").ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") AndAlso UsuarioActual.CveEmpresa <> 72 Then - e.Row.FCCheckBox("cbInv").Checked = True - e.Row.FCCheckBox("cbInv").Enabled = False - End If - - End If - - If CveVenta > 0 Then - If e.Row.DBCampo("CveConcepto").ToEntero = 3 Then CveAlmacenDevolucion = e.Row.DBCampo("CveAlmacen").ToEntero - e.Row.FCCheckBox("cbInv").Visible = False - End If - - - End If - End Sub - - Protected Sub GVINV_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvInv.RowEditing - GvInv.EditIndex = e.NewEditIndex - CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2")) - End Sub - - Protected Sub GVINV_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvInv.RowCancelingEdit - GvInv.EditIndex = -1 - CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2")) - End Sub - - Protected Sub GVINV_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvInv.RowUpdating - Dim Cantidad As Double = DirectCast(GvInv.Rows(e.RowIndex).FindControl("txtECantidad"), TextBox).Text.ToDouble - DtInv.Rows.Item(e.RowIndex)("Cantidad") = Cantidad - GvInv.DataSource = DtInv.FiltraParametros("CveTipoPS=2") + If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then + Objeto.ddl.Items.Clear() + 'Objeto.ddl.DataSource = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) + Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, Estatus:=1, AplicaParaVenta:=1) + Objeto.ddl.DataBind() + Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2")) + Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1")) + Else + Objeto.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) + Objeto.ddlWS.Attributes.Add("data-cveclasificacion", CveClasificacion.ToString) + Objeto.ddlWS.Attributes.Add("data-pagina", "ventas/ventas") + Objeto.ddlWS.Attributes.Add("data-Estatus", "1") + End If + + End Sub + Private Sub CargaNC(pCveVenta As Integer) + If pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then + + If IsNothing(Request("CveDevolucion")) AndAlso IsNumeric(Request("CveDevolucion")) Then + trNCFactura.Visible = True + End If + + If DdlNCFactura.Items.Count = 0 Then + Dim ObjClientes As New ClsVentas() + + If ObjClientes.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then + DTFacNC = ObjClientes.DtResultados + Dim drvv As DataRow = DTFacNC.FiltroPrimero("") + DTFacNC.Columns.Add("Factura", GetType(String), " Folio + ' - ' + Fecha + ' $' + Total") + HdnFolioFiscalNC.Value = drvv("FolioFiscal").ToString + + If DTFacNC IsNot Nothing AndAlso DTFacNC.Rows.Count > 0 Then + Me.CveEstatusRefacturacion = DTFacNC.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero() + HdnRFCVenta.Value = DTFacNC.Rows(0)("ClienteRFC").ToString() + End If + Else + DTFacNC = Nothing + End If + ObjClientes.Dispose() + + DdlNCFactura.DataSource = DTFacNC + DdlNCFactura.DataBind() + + DdlNCFactura.SelectedValueExist(pCveVenta) + DdlNCFactura.Enabled = False + End If + + Else + trNCFactura.Visible = False + End If + End Sub + Private Sub CargaCuentasTerminal() + DdlCuentasTerminal.Items.Clear() + DdlCuentaTerminalModal.Items.Clear() + + DdlCuentasTerminal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"}) + DdlCuentaTerminalModal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"}) + + DdlCuentasTerminal.DataBind() + DdlCuentaTerminalModal.DataBind() + + DdlCuentasTerminal.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlCuentaTerminalModal.Items.Insert(0, New ListItem("Seleccione", "-1")) + + UPTarjetaTermminal.Update() + UpCuentaTerminal.Update() + + End Sub + Public Sub CargaDdlNCPS() + + Dim CveSATNC = "84111506" + DdlNCPS.DataSource = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC + DdlNCPS.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlNCPS.DataBind() + + DdlNCPSAnt.DataSource = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC + DdlNCPSAnt.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlNCPSAnt.DataBind() + End Sub +#End Region + +#Region "G R I D V I E W S" + +#Region "GvPS" + Protected Sub GvPS_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvPS.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + e.Row.Attributes("id") = e.Row.RowIndex.ToString + If e.Row.RowIndex = 0 Then + End If + + + If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then + 'MODO EDICION + + e.Row.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToEntero, -1) + e.Row.FCDropDownList("DdlUnidadMedida").DataBind() + e.Row.FCDropDownList("DdlUnidadMedida").SelectedValueExist(e.Row.DBCampo("CveUM")) + + e.Row.FCDropDownList("DdlClasificacion").DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1) + e.Row.FCDropDownList("DdlClasificacion").DataBind() + e.Row.FCDropDownList("DdlClasificacion").SelectedValue = e.Row.DBCampo("CveClasificacion") + CargaPS(e.Row.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero, e.Row.FCDropDownLost("DdlPS")) + e.Row.FCDropDownLost("DdlPS").SelectedText = e.Row.DBCampo("PS") + e.Row.FCDropDownLost("DdlPS").SelectedValue = e.Row.DBCampo("CvePS") + + + If e.Row.DBCampo("CveSubProyecto") = "-1" Then + 'cargo todos las opciones para + e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) + e.Row.FCDropDownList("DdlProyecto").DataBind() + e.Row.FCDropDownList("DdlProyecto").Items.Insert(0, New ListItem("Sin Proyecto Asignado", "-1")) + + e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, -1, 1) + 'e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectos.FiltraParametros("CveEmpresa = " & UsuarioActual.CveEmpresa & " AND CveProyecto = '" & DdlProyecto.SelectedValue & "'") + e.Row.FCDropDownList("DdlSubProyecto").DataBind() + 'e.Row.FCDropDownList("DdlSubProyectoEdit").SelectedValue = e.Row.DBCampo("CveSubProyecto") + e.Row.FCDropDownList("DdlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) + Else + Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, e.Row.DBCampo("CveSubProyecto").ToEntero, 1).FiltroPrimero("") + + If dr IsNot Nothing Then + e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) + e.Row.FCDropDownList("DdlProyecto").DataBind() + e.Row.FCDropDownList("DdlProyecto").SelectedValue = dr("CveProyecto").ToString + + e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, dr("CveProyecto").ToString.ToEntero, UsuarioActual.CveEmpresa, -1, 1) + e.Row.FCDropDownList("DdlSubProyecto").DataBind() + e.Row.FCDropDownList("DdlSubProyecto").SelectedValue = e.Row.DBCampo("CveSubProyecto") + + End If + + End If + + 'Si es una devolucion + If NuevaFactura = 0 Then + e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False + e.Row.FCDropDownList("DdlClasificacion").Enabled = False + e.Row.FCDropDownLost("DdlPS").Enabled = False + e.Row.FCDropDownList("DdlProyecto").Enabled = False + e.Row.FCDropDownList("DdlSubProyecto").Enabled = False + e.Row.FCTextBox("TxtPrecio").Enabled = False + ElseIf NuevaFactura = 1 Or CveContrato > 0 Then + e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False + e.Row.FCDropDownList("DdlClasificacion").Enabled = False + e.Row.FCDropDownLost("DdlPS").Enabled = False + e.Row.FCTextBox("TxtCantidad").Enabled = False + e.Row.FCTextBox("TxtPrecio").Enabled = False + e.Row.FCTextBox("TxtDescuento").Enabled = False + + If TieneAlmacen Then e.Row.FCLinkButton("imgD").Visible = False + + If UsuarioActual.TienePermisoProceso(222) Then + e.Row.FCDropDownList("DdlUnidadMedida").Enabled = True + e.Row.FCDropDownList("DdlClasificacion").Enabled = True + e.Row.FCDropDownLost("DdlPS").Enabled = True + e.Row.FCTextBox("TxtCantidad").Enabled = True + e.Row.FCTextBox("TxtPrecio").Enabled = True + e.Row.FCTextBox("TxtDescuento").Enabled = True + End If + + End If + + 'Si es facturacion de OC o Contrato + If CveContrato > 0 AndAlso Not CveVenta > 0 AndAlso Not CveCicloComercial > 0 Then + e.Row.FCLinkButton("imgClone").Visible = False + e.Row.FCTextBox("TxtOrden").Visible = True + e.Row.FCTextBox("TxtCantidad").Enabled = False + e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False + e.Row.FCDropDownList("DdlClasificacion").Enabled = False + e.Row.FCDropDownLost("DdlPS").Enabled = False + e.Row.FCDropDownList("DdlProyecto").Enabled = False + e.Row.FCDropDownList("DdlSubProyecto").Enabled = False + e.Row.FCTextBox("TxtPrecio").Enabled = False + End If + + If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then + e.Row.FCLinkButton("imgClone").Visible = False + e.Row.FCTextBox("TxtOrden").Visible = True + e.Row.FCTextBox("TxtCantidad").Enabled = False + e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False + e.Row.FCDropDownList("DdlClasificacion").Enabled = False + e.Row.FCDropDownList("DdlProyecto").Enabled = False + e.Row.FCDropDownList("DdlSubProyecto").Enabled = False + e.Row.FCLiteral("LtlPSEdit").Visible = True + e.Row.FCDropDownLost("DdlPS").Visible = False + e.Row.FCDropDownLost("DdlPS").Enabled = False + e.Row.FCTextBox("TxtPrecio").Enabled = True + End If + + If CveCicloComercial > 0 Then + e.Row.FCTextBox("TxtPrecio").Enabled = True + End If + + 'CUANDO SE QUIERE FACTURAR UNA REMISIÓN NO PERMITE EDITAR SU PRECIO + If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso (e.Row.DBCampo("CveVentaDetalle").ToEntero > 0 Or e.Row.DBCampo("CveVentaDetalleRemision").ToEntero > 0) Then + e.Row.FCTextBox("TxtPrecio").Enabled = False + End If + + 'PERMISO EDITAR REM + If e.Row.DBCampo("TipoDocto") = "Rem" And ModalidadEdicion Then + 'LO PERMITIDO MODIFICAR + e.Row.FCTextBox("TxtPrecio").Enabled = True + e.Row.FCTextBox("TxtObsPS").Enabled = True + e.Row.FCTextBox("TxtCantidad").Attributes.Add("onblur", $"ValidarCantidadMenor(this,{e.Row.DBCampo("CantidadInventario").ToDouble})") + + 'LO NO PERMITIDO MODIFICAR + e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False + 'e.Row.FCDropDownList("DdlClasificacion").Enabled = False + 'e.Row.FCDropDownLost("DdlPS").Enabled = False + + e.Row.FCTextBox("TxtTiempoEntrega").Enabled = False + e.Row.FCDropDownList("DdlProyecto").Enabled = False + e.Row.FCDropDownList("DdlSubProyecto").Enabled = False + + e.Row.FCLinkButton("imgD").Visible = False + End If + + 'If UsuarioActual.CveEmpresa = 119 Then + ' e.Row.FCTextBox("TxtDescuento").Enabled = False + 'End If + + Else + 'MODO NORMAL + + If UsuarioActual.Empresa.UsaAC Then + e.Row.FCDropDownList("DdlFR").DataSource = DTPresupuestoIngresos + e.Row.FCDropDownList("DdlFR").DataBind() + e.Row.FCDropDownList("DdlFR").SelectedValue = e.Row.DBCampo("CvePresupuestoIngreso") + 'e.Row.FCDropDownList("DdlFR").Enabled = False + End If + + If e.Row.DataKey("IEPS").ToDouble > 0 Then : TrIEPS.Visible = True : End If + + If NuevaFactura = 1 Then + If Not UsuarioActual.TienePermisoProceso(222) Then + e.Row.FCLinkButton("imgD").Visible = False + e.Row.FCLinkButton("imgE").Visible = False + End If + If TieneAlmacen Then + e.Row.FCLinkButton("imgD").Visible = False + End If + End If + + If (CveContrato > 0 AndAlso Not CveVenta > 0) Then + e.Row.FCLinkButton("imgD").Visible = False + End If + + If DdlContratosModal.DataSource IsNot Nothing AndAlso CveCicloComercial <= 0 Then + e.Row.FCLinkButton("imgE").Visible = False + End If + + 'Si es Cotizacíon + If e.Row.DBCampo("TipoDocto") = "Cot" Then + ThTiempoEntrega.Visible = True + ThTiempoEntrega2.Visible = True + GvPS.Columns(5).Visible = True + End If + + 'Si es facturacion de OC + If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then + e.Row.FCLinkButton("imgClone").Visible = False + e.Row.FCTextBox("TxtOrden").Visible = True + End If + + If UsuarioActual.Empresa.CvePlataforma = 2 Then + e.Row.FCLinkButton("imgE").Visible = False + e.Row.FCLinkButton("imgEPyME").Visible = True + End If + + If UsuarioActual.Empresa.Tipo_CentroCosto = 2 Or UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then + e.Row.FCLabel("LblProyecto").Visible = False + End If + + If CveVenta > 0 Then 'And e.Row.DBCampo("TipoDocto") = "Rem" + If ModalidadEdicion Then + e.Row.FCLinkButton("imgE").Visible = Not e.Row.DBCampo("CantidadFacturadaRem").ToDouble > 0 + e.Row.FCLinkButton("imgD").Visible = Not e.Row.DBCampo("CantidadInventario").ToDouble > 0 + ElseIf Not CveDevolucion > 0 Then + e.Row.FCLinkButton("imgE").Visible = False + e.Row.FCLinkButton("imgD").Visible = False + End If + End If + + 'CANTIDAD FACTURADA + Select Case e.Row.DBCampo("TipoDocto") + Case "Cot" + e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaCot").ToDecimal.ToString("#,##0.##") + Case "Pd2" + e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaPed2").ToDecimal.ToString("#,##0.##") + End Select + + 'If GvInv.Rows.Count > 0 AndAlso ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem" AndAlso e.Row.DataKey("CveVentaDetalle").ToString.ToEntero > 0 Then + ' e.Row.FCLinkButton("imgE").Enabled = False + ' e.Row.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen." + 'End If + + End If + End If + End Sub + Protected Sub GvPS_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvPS.RowEditing + GvPS.EditIndex = e.NewEditIndex + GvPS.DataSource = TmpDT + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + GvPS.DataBind() + End Sub + Protected Sub GvPS_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvPS.RowCancelingEdit + GvPS.EditIndex = -1 + GvPS.DataSource = TmpDT + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + GvPS.DataBind() + End Sub + Protected Sub GvPS_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvPS.RowUpdating + 'Dim TipoDescuento As Integer + Dim Cantidad, PU, Descuento As Decimal + Dim CuentaPredial As String + + Cantidad = GvPS.Rows(e.RowIndex).FCTextBox("TxtCantidad").Text.ToDecimal + PU = Math.Round(GvPS.Rows(e.RowIndex).FCTextBox("TxtPrecio").Text.ToDecimal, 6) + Descuento = Math.Round(GvPS.Rows(e.RowIndex).FCTextBox("TxtDescuento").Text.ToDecimal, NumeroDecimales) + CuentaPredial = GvPS.Rows(e.RowIndex).FCTextBox("TxtPredial").Text.Trim + + Dim DatarowPS As DataRow = Nothing + DatarowPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero).FiltroPrimero("") ' Estado = -1 + + 'verifica si tiene ventaminima + If Cantidad > 0 AndAlso DatarowPS("VentaMinima").ToString.ToDecimal > 0 AndAlso (DdlTipoComprobante.SelectedValue = "Rem" Or DdlTipoComprobante.SelectedValue = "Ing") Then + 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... + If Cantidad Mod DatarowPS("VentaMinima").ToString.ToDecimal <> 0 Then + Alert(String.Format("El producto se vende solo en cantidades de {0}", DatarowPS("VentaMinima").ToString)) + Exit Sub + End If + End If + + If TmpDT.Rows(e.RowIndex)("CvePS").ToString <> GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue Then + 'eliminar y cargar el ps *** + Dim DdlUM As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida") + Dim DdlCla As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlClasificacion") + + TmpDT.Rows.Remove(TmpDT.Rows(e.RowIndex)) + CalculaUsados() + AgregarProductoServicio(Cantidad, DdlUM.SelectedValue.ToEntero, DdlUM.SelectedItem.Text, DdlCla.SelectedValue.ToEntero, DdlCla.SelectedItem.Text, + GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedText, + GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.Trim, PU, Descuento, + GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text, + GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text, + CuentaPredial:=CuentaPredial, CveVentaDetalle:=GvPS.Rows(e.RowIndex).DataKey("CveVentaDetalle").ToString.ToEntero, SeActualiza:=True) + + ' TmpDT.Rows(e.RowIndex)("CveUM") = Ddl.SelectedValue + ' TmpDT.Rows(e.RowIndex)("UM") = Ddl.SelectedItem.Text + + If UsuarioActual.Empresa.Funcionalidad(533).ToEntero > 0 Then + + GvPS.EditIndex = -1 + GvPS.DataSource = TmpDT + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + GvPS.DataBind() + CargaGVInv(DtInv) + CalculaUsados() + End If + + Else + If Not ClienteDesglosaIEPS Then + Dim DrPS As DataRow = Nothing + + 'DrPS = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero, Estatus:=-1).FiltroPrimero("") + + DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero).FiltroPrimero("") + + PU = PU * (1 + DrPS("IEPSPorcentaje").ToString.ToDecimal) + + TmpDT.Rows(e.RowIndex)("PorcentajeIEPS") = 0 + End If + + Dim TotalCalculableImpuestos As Decimal = ((Cantidad * PU) - (Descuento)) + + + TmpDT.Rows(e.RowIndex)("CveUM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedValue.ToEntero + TmpDT.Rows(e.RowIndex)("UM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedItem.Text + TmpDT.Rows(e.RowIndex)("Cantidad") = Cantidad + TmpDT.Rows(e.RowIndex)("Obs") = GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.Trim + TmpDT.Rows(e.RowIndex)("TiempoEntrega") = GvPS.Rows(e.RowIndex).FCTextBox("TxtTiempoEntrega").Text.Trim + TmpDT.Rows(e.RowIndex)("PU") = PU + TmpDT.Rows(e.RowIndex)("Descuento") = Descuento + TmpDT.Rows(e.RowIndex)("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) + TmpDT.Rows(e.RowIndex)("ImporteIVA") = Math.Round(TmpDT.Rows(e.RowIndex)("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + TmpDT.Rows(e.RowIndex)("ImporteIEPS") = Math.Round(TmpDT.Rows(e.RowIndex)("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + TmpDT.Rows(e.RowIndex)("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) + TmpDT.Rows(e.RowIndex)("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) + TmpDT.Rows(e.RowIndex)("PorcentajeRetIVA") = ClienteRetIVA + TmpDT.Rows(e.RowIndex)("PorcentajeRetISR") = ClienteRetISR + TmpDT.Rows(e.RowIndex)("CuentaPredial") = CuentaPredial + + If GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").Items.Count = 0 Then + TmpDT.Rows(e.RowIndex)("Proyecto") = "Sin Proyecto Asignado" + TmpDT.Rows(e.RowIndex)("CveSubProyecto") = -1 + Else + TmpDT.Rows(e.RowIndex)("Proyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text + End If + + + If GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").Items.Count = 0 Then + TmpDT.Rows(e.RowIndex)("SubProyecto") = "Sin SubProyecto Asignado" + Else + TmpDT.Rows(e.RowIndex)("SubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text + TmpDT.Rows(e.RowIndex)("CveSubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue + End If + + GvPS.EditIndex = -1 + GvPS.DataSource = TmpDT + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + GvPS.DataBind() + CargaGVInv(DtInv) + CalculaUsados() + End If + + CalculaTotalesVenta() + + 'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW + If AplicaComercioExterior Then + CargaGvComercioExterior() + End If + + + 'JJMQ 20160506: Se agrego para la validacion de pago de contado. + CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") + + UpPS.Update() + UpContado.Update() + + + 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) + TmpDT.Rows.Remove(DbRow) + + CalculaUsados() + + GvPS.DataSource = TmpDT + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + GvPS.DataBind() + CargaGVInv(DtInv) + CalculaTotalesVenta() + + Alert("Eliminado Correctamente.", TipoMensaje.MsgInformacion) + 'JJMQ 20160506: Se agrego para la validacion de pago de contado. + CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") + + UpContado.Update() + End Sub +#End Region + +#Region "GvINV" + + Private Sub GvInv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvInv.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + + 'SERIE ALMACEN + If e.Row.DBCampo("CveTipoInvPS").ToEntero = 5 Then + If CveVenta > 0 Then + e.Row.FCLiteral("LtlSerie").Visible = True + Else + e.Row.FCTextBox("TxtSerie").Visible = True + e.Row.FCTextBox("TxtSerie").Attributes.Remove("onkeypress") + e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeypress", String.Format("SeriePS(event,{0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID)) + e.Row.FCTextBox("TxtSerie").Attributes.Remove("onblur") + e.Row.FCTextBox("TxtSerie").Attributes.Add("onblur", String.Format("SeriePSBlur({0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID)) + End If + + + 'e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) + + 'e.Row.FCTextBox("LblCodigo").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) + 'e.Row.FCTextBox("LblCodigo").Attributes.Add("onblur", String.Format("LimpiaAF(1, '{0}'); AFBlurEdit(this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) + End If + + If e.Row.DBCampo("CvePS") = "" Then + e.Row.FCLiteral("LtlPS").Text = String.Format("Folio: {1} Fecha: {2} -- {3} -- {4}", 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) + + e.Row.FCCheckBox("cbInv").Visible = False + e.Row.FCCheckBox("cbInv").Enabled = False + + If e.Row.DataKey("Origen").ToEntero > 0 Then + e.Row.BackColor = Drawing.Color.FromArgb(224, 130, 131) + e.Row.ForeColor = Drawing.Color.White + e.Row.Font.Bold = True + Else + e.Row.CssClass = "SubTotales" + End If + Else + + e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left + e.Row.FCCheckBox("cbInv").Visible = True + e.Row.FCCheckBox("cbInv").Enabled = True + + 'SI ES REMISION O VENTA DEBE SALIR DE ALMACEN + If UsuarioActual.TienePermisoProceso(157) AndAlso e.Row.DBCampo("CvePS").ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") AndAlso UsuarioActual.CveEmpresa <> 72 Then + e.Row.FCCheckBox("cbInv").Checked = True + e.Row.FCCheckBox("cbInv").Enabled = False + End If + + End If + + If CveVenta > 0 Then + If e.Row.DBCampo("CveConcepto").ToEntero = 3 Then CveAlmacenDevolucion = e.Row.DBCampo("CveAlmacen").ToEntero + e.Row.FCCheckBox("cbInv").Visible = False + End If + + + End If + End Sub + + Protected Sub GVINV_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvInv.RowEditing + GvInv.EditIndex = e.NewEditIndex + CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2")) + End Sub + + Protected Sub GVINV_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvInv.RowCancelingEdit + GvInv.EditIndex = -1 + CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2")) + End Sub + + Protected Sub GVINV_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvInv.RowUpdating + Dim Cantidad As Double = DirectCast(GvInv.Rows(e.RowIndex).FindControl("txtECantidad"), TextBox).Text.ToDouble + DtInv.Rows.Item(e.RowIndex)("Cantidad") = Cantidad + GvInv.DataSource = DtInv.FiltraParametros("CveTipoPS=2") End Sub -#End Region +#End Region -#Region "GvInvNC" - Protected Sub GvInvNCCheckClick(sender As Object, e As EventArgs) - Dim chk As CheckBox = DirectCast(sender, CheckBox) - Dim gvr As GridViewRow = DirectCast(chk.NamingContainer, GridViewRow) - gvr.FCTextBox("Txtcantidad").Visible = chk.Checked - UpINVNC.Update() +#Region "GvInvNC" + Protected Sub GvInvNCCheckClick(sender As Object, e As EventArgs) + Dim chk As CheckBox = DirectCast(sender, CheckBox) + Dim gvr As GridViewRow = DirectCast(chk.NamingContainer, GridViewRow) + gvr.FCTextBox("Txtcantidad").Visible = chk.Checked + UpINVNC.Update() End Sub 'Private Function SubTotalFacturaVinNC() As Decimal *** ESTABA TRONANDO EN COMPU 11/01/17 *** @@ -5775,4476 +5776,4476 @@ Partial Class Ventas ' Return retorno 'End Function -#End Region +#End Region -#Region "GvConceptos" - Protected Sub GvConceptos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvConceptos.RowDeleting - DTmpC.Rows.RemoveAt(e.RowIndex) - GvConceptos.DataSource = DTmpC - GvConceptos.DataBind() - UPCD.Update() - UPCD.Update() - End Sub - Protected Sub GvConceptos_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvConceptos.RowEditing - - GvConceptos.DataSource = DTmpC - GvConceptos.EditIndex = e.NewEditIndex - GvConceptos.DataBind() - - - End Sub - Protected Sub GvConceptos_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvConceptos.RowCancelingEdit - GvConceptos.EditIndex = -1 - GvConceptos.DataSource = DTmpC - GvConceptos.DataBind() - - End Sub - Protected Sub GvConceptos_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvConceptos.RowUpdating - - DTmpC.Rows(e.RowIndex)("Descripcion") = GvConceptos.Rows(e.RowIndex).FCTextBox("tbDescCE").Text - GvConceptos.EditIndex = -1 - GvConceptos.DataSource = DTmpC - GvConceptos.DataBind() - +#Region "GvConceptos" + Protected Sub GvConceptos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvConceptos.RowDeleting + DTmpC.Rows.RemoveAt(e.RowIndex) + GvConceptos.DataSource = DTmpC + GvConceptos.DataBind() + UPCD.Update() + UPCD.Update() End Sub -#End Region + Protected Sub GvConceptos_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvConceptos.RowEditing + + GvConceptos.DataSource = DTmpC + GvConceptos.EditIndex = e.NewEditIndex + GvConceptos.DataBind() + -#Region "GvFirma" - Protected Sub GvFirmas_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvFirmas.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow And Not e.Row.RowState = DataControlRowState.Edit Then - If e.Row.DBCampo("Lado") = "0" Then - e.Row.FCLabel("lbPosF").Text = "Der." - ElseIf e.Row.DBCampo("Lado") = "1" Then - e.Row.FCLabel("lbPosF").Text = "Izq." - End If - End If - End Sub - Protected Sub GvFirmas_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvFirmas.RowDeleting - DTmpF.Rows.RemoveAt(e.RowIndex) - GvFirmas.DataSource = DTmpF - GvFirmas.DataBind() - UPCD.Update() - UPFirmas.Update() - - End Sub - Protected Sub GvFirmas_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvFirmas.RowEditing - - GvFirmas.DataSource = DTmpF - GvFirmas.EditIndex = e.NewEditIndex - GvFirmas.DataBind() - - - End Sub - Protected Sub GvFirmas_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvFirmas.RowCancelingEdit - GvFirmas.EditIndex = -1 - GvFirmas.DataSource = DTmpF - GvFirmas.DataBind() - - End Sub - Protected Sub GvFirmas_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvFirmas.RowUpdating - - DTmpF.Rows(e.RowIndex)("Titulo") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbTituloFE").Text - DTmpF.Rows(e.RowIndex)("Nombre") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbNmbFE").Text - DTmpF.Rows(e.RowIndex)("Puesto") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbPuestFE").Text - DTmpF.Rows(e.RowIndex)("Lado") = GvFirmas.Rows(e.RowIndex).FCDropDownList("ddlPosE").SelectedValue - GvFirmas.EditIndex = -1 - GvFirmas.DataSource = DTmpF - GvFirmas.DataBind() - End Sub -#End Region + Protected Sub GvConceptos_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvConceptos.RowCancelingEdit + GvConceptos.EditIndex = -1 + GvConceptos.DataSource = DTmpC + GvConceptos.DataBind() -#Region "GvIEPS" + End Sub + Protected Sub GvConceptos_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvConceptos.RowUpdating + + DTmpC.Rows(e.RowIndex)("Descripcion") = GvConceptos.Rows(e.RowIndex).FCTextBox("tbDescCE").Text + GvConceptos.EditIndex = -1 + GvConceptos.DataSource = DTmpC + GvConceptos.DataBind() + + End Sub +#End Region + +#Region "GvFirma" + Protected Sub GvFirmas_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvFirmas.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow And Not e.Row.RowState = DataControlRowState.Edit Then + If e.Row.DBCampo("Lado") = "0" Then + e.Row.FCLabel("lbPosF").Text = "Der." + ElseIf e.Row.DBCampo("Lado") = "1" Then + e.Row.FCLabel("lbPosF").Text = "Izq." + End If + End If + End Sub + Protected Sub GvFirmas_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvFirmas.RowDeleting + DTmpF.Rows.RemoveAt(e.RowIndex) + GvFirmas.DataSource = DTmpF + GvFirmas.DataBind() + UPCD.Update() + UPFirmas.Update() + + End Sub + Protected Sub GvFirmas_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvFirmas.RowEditing + + GvFirmas.DataSource = DTmpF + GvFirmas.EditIndex = e.NewEditIndex + GvFirmas.DataBind() + + + End Sub + Protected Sub GvFirmas_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvFirmas.RowCancelingEdit + GvFirmas.EditIndex = -1 + GvFirmas.DataSource = DTmpF + GvFirmas.DataBind() + + End Sub + Protected Sub GvFirmas_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvFirmas.RowUpdating + + DTmpF.Rows(e.RowIndex)("Titulo") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbTituloFE").Text + DTmpF.Rows(e.RowIndex)("Nombre") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbNmbFE").Text + DTmpF.Rows(e.RowIndex)("Puesto") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbPuestFE").Text + DTmpF.Rows(e.RowIndex)("Lado") = GvFirmas.Rows(e.RowIndex).FCDropDownList("ddlPosE").SelectedValue + GvFirmas.EditIndex = -1 + GvFirmas.DataSource = DTmpF + GvFirmas.DataBind() + + End Sub +#End Region + +#Region "GvIEPS" 'Protected Sub GvIEPS_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvIEPS.RowDataBound ' If e.Row.RowType = DataControlRowType.DataRow Then ' e.Row.FCLiteral("LtlIEPS").Text = String.Format("IEPS ({0}):", If(e.Row.DBCampo("PorcentajeIEPS").ToDecimal = 0.03, "3%", If(e.Row.DBCampo("PorcentajeIEPS").ToDecimal = 0.06, "6%", If(e.Row.DBCampo("PorcentajeIEPS").ToDecimal = 0.07, "7%", "9%")))) ' End If 'End Sub -#End Region +#End Region -#End Region +#End Region -#Region " EMITIR IMPRIMIR - GUARDAR " +#Region " EMITIR IMPRIMIR - GUARDAR " + + Protected Sub BtnEmitirImprimir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitirImprimir.Click + EmitirImprimir() + End Sub + + Private Sub EmitirImprimir() + DtRemisionesTmpDT = TmpDT.Copy + DtPedidos2TmpDT = TmpDT.Copy + DtCotizacionTmpDT = TmpDT.Copy + DtOCTmpDT = TmpDT.Copy + TmpDTError = TmpDT.Copy + + 'CUANDO ES PEDIDO SE DEBE ESPECIFICAR EL NUMERO DE CONTRATO + If TrTipoPedido.Visible AndAlso DdlTipoPedido.SelectedIndex = 2 Then + If String.IsNullOrEmpty(TxtObsFact.Text.Trim()) Then + Alert("Se debe especificar el Número de contrato.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + + 'CUANDO ES COTIZACION Y SE VA A FACTURAR SE HACE INGRESO + If DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar" Then + DdlTipoComprobante.SelectedValue = "Ing" + + EraCotizacion = 1 + TxtFecha.Text = Now.ToString + TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranza), Now.AddDays(PlazoCobranza)).ToShortDateString + TxtFechaEjecucion.Text = Now.ToString + + 'debo de regenerar los folios, para facturar + CargaFolios() + End If + + 'VALIDACIONES + If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then + Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + If TmpDT Is Nothing OrElse TmpDT.Rows.Count = 0 Then + Alert("Es necesario tener al menos un concepto registrado.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'Subproyecto Obligatorio + If UsuarioActual.Empresa.Funcionalidad(120) = "1" AndAlso TmpDT.FiltraParametros("ISNULL(CveSubProyecto,0) <= 0").Rows.Count > 0 Then + Alert("El Subproyecto de los conceptos es obligatorio, Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'SI TIENE ANTICIPOS Y ESTA AMORTIZADO AL 100% EL DOCUMENTO (SALDO = 0) | NO VALIDA PU DEL CONCEPTO + If Not (LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0) Then + If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then + If TmpDT.FiltraParametros($"TotalImporte = 0").Rows.Count > 0 Then + Alert("El importe de cada concepto debe ser mayor a cero. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + End If + End If + + Dim CveContratoTipo As Integer = 0 + If CveContrato > 0 Then + Dim ObjContrato As New ClsContratos + If ObjContrato.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then + If ObjContrato.DtResultados.Rows.Count > 0 Then + CveContratoTipo = ObjContrato.DtResultados.Rows(0)("CveContratoTipo").ToString.ToEntero + End If + End If + ObjContrato.Dispose() + End If + + 'No exceder el limite de credito, Si no tiene contrato limita el credito, si tiene no hace nada. Si no tiene remisiones tampoco hace nada. + If (Not CveContrato > 0 Or CveContratoTipo.Contiene(28)) AndAlso (Not NuevaFactura = 1) AndAlso RBLPago.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso RemisionesLista.Count <= 0 AndAlso TxtTotal.Text.ToDecimal > 0 AndAlso Not CvePedidoA > 0 Then + If UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then + Dim ObjVentas As New ClsVentas + + If ObjVentas.ObtenerCreditoRestante(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + + If DdlSucursalCliente.SelectedValue.ToEntero > 0 Then + If ObjVentas.DtResultados(0)("LimiteRestanteSucursal").ToString.ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then + ObjVentas.Dispose() + Alert("Se está excediendo el límite de credito permitido de la Sucursal del Cliente.", TipoMensaje.MsgInformacion) + Exit Sub + End If + Else + If ObjVentas.DtResultados(0)("LimiteRestanteCliente").ToString.ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then + ObjVentas.Dispose() + Alert("Se está excediendo el límite de credito permitido del Cliente.", TipoMensaje.MsgInformacion) + Exit Sub + End If + End If + + Else + ObjVentas.Dispose() + Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError) + Exit Sub + End If + Else + ObjVentas.Dispose() + Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError) + Exit Sub + End If + ObjVentas.Dispose() + End If + End If + + + 'VALIDA PRECIO AL AGREGAR A ALMACEN + If Not UsuarioActual.TienePermisoProceso(169) Then + If (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") AndAlso NuevaFactura <> 1) Or (DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119)) Then + Dim MensajeCosto As New StringBuilder + Dim CostoMenor = 0.0D + Dim CostoMayor = 0.0D + Dim Costo = 0.0D + Dim EsValido = False 'BANDERA + Dim EsValidoMayor = False + Dim EsValidoPU = True 'SOLO SE VALIDA CUANDO EL TXTPU = 0 Y LO INVALIDA ALGUNA PROMOCION + + + 'VALIDA PROMOCIONES Y EXISTENCIAS + Dim ObjVentas As New ClsVentas + If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero, CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then + DtPromociones = ObjVentas.DtResultados + End If + ObjVentas.Dispose() + + + Dim ObjInventarios As New ClsInventarios + Dim PU = 0.0D + Dim Cantidad As Double + Dim CveUnidad As Integer + Dim CveProducto As Integer + Dim Existencia As Double + Dim CveAlmacen = ddlAlmacen.SelectedValue.ToEntero + For Each dr As DataRow In TmpDT.Rows + + 'SI ES SERVICIO NO VALIDA + 'GlobalDTProductosServicios + If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=dr("CvePS").ToString.ToEntero).FiltroPrimeroValor("CveTipoPS").ToString.ToEntero = 1 Then + Continue For + End If + + If DdlTipoComprobante.SelectedValue <> "Cot" And ChkSinExistencia.Checked = False Then + 'VALIDA EXISTENCIA + CveProducto = dr("CvePS").ToString.ToEntero + CveUnidad = dr("CveUM").ToString.ToEntero + Cantidad = TmpDT.SUM("Cantidad", $"CvePS = {CveProducto}") 'VALIDA CONTRA LA SUMA DEL MISMO PS + If UsuarioActual.CveEmpresa.Contiene({72, 80, 119}) AndAlso RemisionesLista.Count < 1 AndAlso dr("EntregaDirecta").ToString.ToEntero < 1 Then + Existencia = ObjInventarios.GetExistenciasPS(CveProducto, CveUnidad, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) + If Existencia < Cantidad Then + MensajeCosto.AppendFormat("
    El Producto {0}. No cuenta con la cantidad suficiente en inventario. Cuenta con {1}.", dr("CodigoPS").ToString, Existencia.FormatoNumero(2)) + Continue For + End If + End If + End If + + EsValido = False + EsValidoMayor = False + EsValidoPU = True + PU = dr("PU").ToString.ToDecimal * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) + Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString.ToEntero, dr("Cantidad").ToString.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) + + Dim PrecioMinimo As Decimal = 0 + 'RMF. condicion temporal, para reubicación, precio mínimo + If UsuarioActual.CveEmpresa = 119 Then + 'Dim CvePrecioLista As Integer = 38 + Dim objPS As New ClsProductosServicios + If objPS.GetPSSucursalesALL(dr("CvePS").ToString.ToEntero, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then + PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal + If PrecioMinimo > 0 Then + Costo = PrecioMinimo + End If + End If + objPS.Dispose() + + End If + + 'COSTO ALMACEN + If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then + CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) + 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA + If PrecioMinimo > 0 Then CostoMenor = PrecioMinimo + If Math.Round(PU, 4) >= Math.Round(CostoMenor, 4) Then + EsValido = True + End If + Else + EsValido = True + End If + + If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then + CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo) + 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA + If PU <= CostoMayor Then + EsValidoMayor = True + End If + Else + EsValidoMayor = True + End If + + 'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR + If Not EsValido Or PU = 0 Then + If DtPromociones.FiltraParametros($"CvePS = {dr("CvePS").ToString.ToEntero}").Rows.Count > 0 Then + If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {dr("CvePS").ToString.ToEntero}").ToDecimal Then + EsValido = True + Else + EsValidoPU = False ' SI NO ENTRA DENTRO DE LA PROMOCION NO SE PUEDE VENDER A 0 + End If + Else + EsValidoPU = False ' SI NO TIENE PROMOCION NO SE PUEDE VENDER A 0 + End If + End If + + 'NO DEJA REGISTRAR CON VALIDACION DE COSTO ALMACEN O PROMOCION + Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) + If Not EsValido Then + + MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio menor de su Costo ni a un precio mayor de su rango aceptado
    ", dr("PS").ToString) + If TienePermisoImportes Then + MensajeCosto.AppendFormat("El costo del producto es: {0}$
    ", Costo) + MensajeCosto.AppendFormat("El rango menor aceptado es: {0} {1}$
    ", UsuarioActual.Empresa.Funcionalidad(129).ToEntero, CostoMenor) + MensajeCosto.AppendFormat("El precio indicado es: {0}$ ({1}% de ganancia)
    ", PU.FormatoNumero, If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)) + End If + End If + + If Not EsValidoMayor Then + MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio mayor de su rango aceptado
    ", dr("PS").ToString) + If TienePermisoImportes Then + MensajeCosto.AppendFormat("El costo del producto es: {0}$
    ", Costo) + MensajeCosto.AppendFormat("El rango mayor aceptado es: {0} {1}$
    ", UsuarioActual.Empresa.Funcionalidad(133).ToEntero, CostoMayor) + MensajeCosto.AppendFormat("El precio indicado es: {0}$ ({1}% de ganancia)
    ", PU.FormatoNumero, If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)) + End If + End If + + ' SOLO SI TIENE LA FUNCIONALIDAD DE RESTRICCION VALIDA EL IMPORTE CERO + If UsuarioActual.Empresa.Funcionalidad(139).ToString.ToEntero > 0 Then + If Not EsValidoPU Then + MensajeCosto.AppendFormat($"El producto {dr("PS").ToString}. No se puede vender a un importe de cero ($0)", TipoMensaje.MsgAdvertencia) + End If + End If + + Next + ObjInventarios.Dispose() + + If MensajeCosto.ToString.Length > 1 Then + Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + End If + End If + + If UsuarioActual.Empresa.Funcionalidad(135) = "1" And DdlTipoComprobante.SelectedValue = "Cot" Then + Alert("Se mando autorización al supervisor.", TipoMensaje.MsgInformacion) + MandarCorreoSupervisor = True + Dim CorreoSupervisor As String = "" + Dim Objeto As New ClsVtaVendedores + Dim DTSupervisores As New DataTable + If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then + DTSupervisores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DdlVendedor.SelectedValue.ToEntero)) + 'Verifico si el supervisor tiene correo para proceder + If DTSupervisores.Rows.Count > 0 Then + CorreoSupervisor = DTSupervisores.Rows(0)("CorreoSupervisor").ToString + End If + End If + DTSupervisores.Dispose() + Objeto.Dispose() + If MandarCorreoSupervisor = True And CorreoSupervisor <> "" Then + ViewState("Mail") = CorreoSupervisor + End If + MandarCorreoSupervisor = False + End If + + If RequiereOC AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Ing") AndAlso Not CveDevolucion > 0 Then + If Not CargaDocumentoOC Then + Alert("Tiene que cargar un archivo de orden de compra", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + If TxtOrdenCompra.Text.Trim = "" Then + Alert("Tiene que especificar un folio de orden de compra", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If - Protected Sub BtnEmitirImprimir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitirImprimir.Click - EmitirImprimir() - End Sub - - Private Sub EmitirImprimir() - DtRemisionesTmpDT = TmpDT.Copy - DtPedidos2TmpDT = TmpDT.Copy - DtCotizacionTmpDT = TmpDT.Copy - DtOCTmpDT = TmpDT.Copy - TmpDTError = TmpDT.Copy - - 'CUANDO ES PEDIDO SE DEBE ESPECIFICAR EL NUMERO DE CONTRATO - If TrTipoPedido.Visible AndAlso DdlTipoPedido.SelectedIndex = 2 Then - If String.IsNullOrEmpty(TxtObsFact.Text.Trim()) Then - Alert("Se debe especificar el Número de contrato.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - - 'CUANDO ES COTIZACION Y SE VA A FACTURAR SE HACE INGRESO - If DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar" Then - DdlTipoComprobante.SelectedValue = "Ing" - - EraCotizacion = 1 - TxtFecha.Text = Now.ToString - TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranza), Now.AddDays(PlazoCobranza)).ToShortDateString - TxtFechaEjecucion.Text = Now.ToString - - 'debo de regenerar los folios, para facturar - CargaFolios() - End If - - 'VALIDACIONES - If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then - Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - If TmpDT Is Nothing OrElse TmpDT.Rows.Count = 0 Then - Alert("Es necesario tener al menos un concepto registrado.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'Subproyecto Obligatorio - If UsuarioActual.Empresa.Funcionalidad(120) = "1" AndAlso TmpDT.FiltraParametros("ISNULL(CveSubProyecto,0) <= 0").Rows.Count > 0 Then - Alert("El Subproyecto de los conceptos es obligatorio, Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'SI TIENE ANTICIPOS Y ESTA AMORTIZADO AL 100% EL DOCUMENTO (SALDO = 0) | NO VALIDA PU DEL CONCEPTO - If Not (LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0) Then - If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then - If TmpDT.FiltraParametros($"TotalImporte = 0").Rows.Count > 0 Then - Alert("El importe de cada concepto debe ser mayor a cero. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - End If - End If - - Dim CveContratoTipo As Integer = 0 - If CveContrato > 0 Then - Dim ObjContrato As New ClsContratos - If ObjContrato.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then - If ObjContrato.DtResultados.Rows.Count > 0 Then - CveContratoTipo = ObjContrato.DtResultados.Rows(0)("CveContratoTipo").ToString.ToEntero - End If - End If - ObjContrato.Dispose() - End If - - 'No exceder el limite de credito, Si no tiene contrato limita el credito, si tiene no hace nada. Si no tiene remisiones tampoco hace nada. - If (Not CveContrato > 0 Or CveContratoTipo.Contiene(28)) AndAlso (Not NuevaFactura = 1) AndAlso RBLPago.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso RemisionesLista.Count <= 0 AndAlso TxtTotal.Text.ToDecimal > 0 AndAlso Not CvePedidoA > 0 Then - If UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then - Dim ObjVentas As New ClsVentas - - If ObjVentas.ObtenerCreditoRestante(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - - If DdlSucursalCliente.SelectedValue.ToEntero > 0 Then - If ObjVentas.DtResultados(0)("LimiteRestanteSucursal").ToString.ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then - ObjVentas.Dispose() - Alert("Se está excediendo el límite de credito permitido de la Sucursal del Cliente.", TipoMensaje.MsgInformacion) - Exit Sub - End If - Else - If ObjVentas.DtResultados(0)("LimiteRestanteCliente").ToString.ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then - ObjVentas.Dispose() - Alert("Se está excediendo el límite de credito permitido del Cliente.", TipoMensaje.MsgInformacion) - Exit Sub - End If - End If - - Else - ObjVentas.Dispose() - Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError) - Exit Sub - End If - Else - ObjVentas.Dispose() - Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError) - Exit Sub - End If - ObjVentas.Dispose() - End If - End If - - - 'VALIDA PRECIO AL AGREGAR A ALMACEN - If Not UsuarioActual.TienePermisoProceso(169) Then - If (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") AndAlso NuevaFactura <> 1) Or (DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119)) Then - Dim MensajeCosto As New StringBuilder - Dim CostoMenor = 0.0D - Dim CostoMayor = 0.0D - Dim Costo = 0.0D - Dim EsValido = False 'BANDERA - Dim EsValidoMayor = False - Dim EsValidoPU = True 'SOLO SE VALIDA CUANDO EL TXTPU = 0 Y LO INVALIDA ALGUNA PROMOCION - - - 'VALIDA PROMOCIONES Y EXISTENCIAS - Dim ObjVentas As New ClsVentas - If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero, CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then - DtPromociones = ObjVentas.DtResultados - End If - ObjVentas.Dispose() - - - Dim ObjInventarios As New ClsInventarios - Dim PU = 0.0D - Dim Cantidad As Double - Dim CveUnidad As Integer - Dim CveProducto As Integer - Dim Existencia As Double - Dim CveAlmacen = ddlAlmacen.SelectedValue.ToEntero - For Each dr As DataRow In TmpDT.Rows - - 'SI ES SERVICIO NO VALIDA - 'GlobalDTProductosServicios - If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=dr("CvePS").ToString.ToEntero).FiltroPrimeroValor("CveTipoPS").ToString.ToEntero = 1 Then - Continue For - End If - - If DdlTipoComprobante.SelectedValue <> "Cot" And ChkSinExistencia.Checked = False Then - 'VALIDA EXISTENCIA - CveProducto = dr("CvePS").ToString.ToEntero - CveUnidad = dr("CveUM").ToString.ToEntero - Cantidad = TmpDT.SUM("Cantidad", $"CvePS = {CveProducto}") 'VALIDA CONTRA LA SUMA DEL MISMO PS - If UsuarioActual.CveEmpresa.Contiene({72, 80, 119}) AndAlso RemisionesLista.Count < 1 AndAlso dr("EntregaDirecta").ToString.ToEntero < 1 Then - Existencia = ObjInventarios.GetExistenciasPS(CveProducto, CveUnidad, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) - If Existencia < Cantidad Then - MensajeCosto.AppendFormat("
    El Producto {0}. No cuenta con la cantidad suficiente en inventario. Cuenta con {1}.", dr("CodigoPS").ToString, Existencia.FormatoNumero(2)) - Continue For - End If - End If - End If - - EsValido = False - EsValidoMayor = False - EsValidoPU = True - PU = dr("PU").ToString.ToDecimal * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) - Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString.ToEntero, dr("Cantidad").ToString.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) - - Dim PrecioMinimo As Decimal = 0 - 'RMF. condicion temporal, para reubicación, precio mínimo - If UsuarioActual.CveEmpresa = 119 Then - 'Dim CvePrecioLista As Integer = 38 - Dim objPS As New ClsProductosServicios - If objPS.GetPSSucursalesALL(dr("CvePS").ToString.ToEntero, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then - PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal - If PrecioMinimo > 0 Then - Costo = PrecioMinimo - End If - End If - objPS.Dispose() - - End If - - 'COSTO ALMACEN - If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then - CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) - 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA - If PrecioMinimo > 0 Then CostoMenor = PrecioMinimo - If Math.Round(PU, 4) >= Math.Round(CostoMenor, 4) Then - EsValido = True - End If - Else - EsValido = True - End If - - If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then - CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo) - 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA - If PU <= CostoMayor Then - EsValidoMayor = True - End If - Else - EsValidoMayor = True - End If - - 'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR - If Not EsValido Or PU = 0 Then - If DtPromociones.FiltraParametros($"CvePS = {dr("CvePS").ToString.ToEntero}").Rows.Count > 0 Then - If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {dr("CvePS").ToString.ToEntero}").ToDecimal Then - EsValido = True - Else - EsValidoPU = False ' SI NO ENTRA DENTRO DE LA PROMOCION NO SE PUEDE VENDER A 0 - End If - Else - EsValidoPU = False ' SI NO TIENE PROMOCION NO SE PUEDE VENDER A 0 - End If - End If - - 'NO DEJA REGISTRAR CON VALIDACION DE COSTO ALMACEN O PROMOCION - Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) - If Not EsValido Then - - MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio menor de su Costo ni a un precio mayor de su rango aceptado
    ", dr("PS").ToString) - If TienePermisoImportes Then - MensajeCosto.AppendFormat("El costo del producto es: {0}$
    ", Costo) - MensajeCosto.AppendFormat("El rango menor aceptado es: {0} {1}$
    ", UsuarioActual.Empresa.Funcionalidad(129).ToEntero, CostoMenor) - MensajeCosto.AppendFormat("El precio indicado es: {0}$ ({1}% de ganancia)
    ", PU.FormatoNumero, If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)) - End If - End If - - If Not EsValidoMayor Then - MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio mayor de su rango aceptado
    ", dr("PS").ToString) - If TienePermisoImportes Then - MensajeCosto.AppendFormat("El costo del producto es: {0}$
    ", Costo) - MensajeCosto.AppendFormat("El rango mayor aceptado es: {0} {1}$
    ", UsuarioActual.Empresa.Funcionalidad(133).ToEntero, CostoMayor) - MensajeCosto.AppendFormat("El precio indicado es: {0}$ ({1}% de ganancia)
    ", PU.FormatoNumero, If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)) - End If - End If - - ' SOLO SI TIENE LA FUNCIONALIDAD DE RESTRICCION VALIDA EL IMPORTE CERO - If UsuarioActual.Empresa.Funcionalidad(139).ToString.ToEntero > 0 Then - If Not EsValidoPU Then - MensajeCosto.AppendFormat($"El producto {dr("PS").ToString}. No se puede vender a un importe de cero ($0)", TipoMensaje.MsgAdvertencia) - End If - End If - - Next - ObjInventarios.Dispose() - - If MensajeCosto.ToString.Length > 1 Then - Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - End If - End If - - If UsuarioActual.Empresa.Funcionalidad(135) = "1" And DdlTipoComprobante.SelectedValue = "Cot" Then - Alert("Se mando autorización al supervisor.", TipoMensaje.MsgInformacion) - MandarCorreoSupervisor = True - Dim CorreoSupervisor As String = "" - Dim Objeto As New ClsVtaVendedores - Dim DTSupervisores As New DataTable - If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then - DTSupervisores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DdlVendedor.SelectedValue.ToEntero)) - 'Verifico si el supervisor tiene correo para proceder - If DTSupervisores.Rows.Count > 0 Then - CorreoSupervisor = DTSupervisores.Rows(0)("CorreoSupervisor").ToString - End If - End If - DTSupervisores.Dispose() - Objeto.Dispose() - If MandarCorreoSupervisor = True And CorreoSupervisor <> "" Then - ViewState("Mail") = CorreoSupervisor - End If - MandarCorreoSupervisor = False - End If - - If RequiereOC AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Ing") AndAlso Not CveDevolucion > 0 Then - If Not CargaDocumentoOC Then - Alert("Tiene que cargar un archivo de orden de compra", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - If TxtOrdenCompra.Text.Trim = "" Then - Alert("Tiene que especificar un folio de orden de compra", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - If GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked) > 0 AndAlso ddlAlmacen.SelectedValue.ToEntero() <= 0 Then Alert("Tiene que seleccionar un almacen", TipoMensaje.MsgAdvertencia) Exit Sub - End If - - EmitirImprimirNew() - End Sub -#End Region + End If -#Region " NNNNEEEEEEEWWWWWW " - Private Sub InicializaImprimirNew() - Dim Archivo As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) - Dim Archivo2 As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) - - LnkImprimir.Visible = False - - 'If (UsuarioActual.CveEmpresa.Contiene(1, 4, 5, 7, 11, 12, 72, 80, 81, 83) And UsuarioActual.CveUsuario = 100) Or UsuarioActual.CveEmpresa.Contiene(80, 83) Or UsuarioActual.CveUsuario = 100 Then - If (Archivo.Exists Or Archivo2.Exists) And IfNull(CveVenta, 0).ToString.ToEntero > 0 Then - HplDownPDF.Visible = True - HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))) - End If - - UpnTools.Update() - End Sub - - Protected Sub EmitirImprimirNew() - - - If ValidaPagosContado() Then - Exit Sub - End If - - CreaObjetosVenta() - - 'Verifica versión 3.3.() - If ObjFactura.Version = "3.3" AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then - Dim dttsat As DataTable = TmpDT.FiltraParametros("ISNULL(SATClaveProdServ,'') = '' OR ISNULL(SATClaveUM,'') = '' ") - If dttsat IsNot Nothing AndAlso dttsat.Rows.Count > 0 Then - Dim str As New StringBuilder - str.Append("Los siguientes productos no tiene asignado la clave Producto SAT o Unidad Medida SAT

    ") - For Each drt As DataRow In dttsat.Rows - str.AppendFormat("{0}
    ", drt("CodigoPS")) - Next - Alert(str.ToString, TipoMensaje.MsgAdvertencia) - dttsat.Dispose() - Exit Sub - End If - dttsat.Dispose() - End If - - If ObjFactura Is Nothing Or (ObjFactura.Cliente Is Nothing And Not CveEmpresaCRM > 0) Then - Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError) - ObjFactura = Nothing - Exit Sub - End If - - 'If Not CveEmpresaCRM > 0 Then - ' If ObjFactura.Cliente.AplicaComercioExterior Then - ' If Not ValidaComercioExterior() Then - ' ObjFactura = Nothing - ' Exit Sub - ' End If - ' End If - 'End If - - - 'VALIDA TOTAL DE LA NOTA DE CREDITO Y LA FACTURA VINCULADA *** ESTABA TRONANDO EN COMPU 11/01/17 *** - 'If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - ' If SubTotalFacturaVinNC() > 0 Then 'pendiente - ' If GvInvNC.Rows.Count > 0 Then 'pendiente - ' If Not (SubTotalFacturaVinNC() = TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio)) Then - ' Alert(String.Format("El sub-total debe ser igual a '{0}'", SubTotalFacturaVinNC().FormatoNumero)) - ' Exit Sub - ' End If - ' Else - ' If SubTotalFacturaVinNC() < TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio) Then 'pendiente - ' Alert(String.Format("El sub-total no puede exceder a : {0}", SubTotalFacturaVinNC().FormatoNumero)) - ' Exit Sub - ' End If - ' End If - ' End If - 'End If - - If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then - If ObjFactura.SubTotal <= 0 Then - Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - End If - - 'VALIDA CUENTAS CONTABLES DE AC - If UsuarioActual.Empresa.UsaAC Then - If ObjFactura.Cliente.IdCtaContClientes <= 0 Then - Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError) - Exit Sub - End If - 'If ViewState("IdCtaContClientes").ToString.ToEntero <= 0 Then 'GetClientes ObjCliente.IdCtaContClientes - ' Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError) - ' Exit Sub - 'End If - - If ObjFactura.SubTotal <= 0 Then - Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'If TxtSubTotal.Text.ToDouble <= 0 Then - ' Alert("Especifique importe en conceptos", TipoMensaje.MsgError) - ' Exit Sub - 'End If - End If - - 'cuando es contado debe de tener especificado la forma de pago - 'If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso ObjFactura.Total > 0 AndAlso RBLPago.SelectedValue = "2" AndAlso ObjFactura.Total - If(DtPagos Is Nothing, 0, DtPagos.SUM("Importe")) > 0 Then ' AndAlso ObjFactura.CveCorte > 0 - ' Alert("No se han especificado las formas de pago. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) - ' Exit Sub - 'End If - - - If ObjFactura.CveCliente > 0 Or CveEmpresaCRM > 0 Then - If TmpDT.Rows.Count > 0 Then - - Dim ObjVentas As New ClsVentas() - Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) - Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) - Dim ObjContr As New ClsContratos(ObjVentas.IniciaTransacSQL()) - Dim ObjOS As New ClsOS(ObjVentas.IniciaTransacSQL()) - Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) - Dim ObjClientes As New ClsClientes(ObjVentas.IniciaTransacSQL()) - Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) - Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) - Dim ObjDocCliente As New ClsEdocumentacion(ObjVentas.IniciaTransacSQL()) - Dim ObjContPaq As ClsContPAQi = Nothing - 'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) - ErrorList = New List(Of String) - MensajeAlert = New StringBuilder - - - 'CONTABILIDAD AUTOMATICA Y AC - If UsuarioActual.Empresa.UsaAC OrElse UsuarioActual.Empresa.Funcionalidad(200) = "1" Then - ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) - End If - - 'VERIFICA QUE EL FOLIO NO SEA IGUAL AL DE LA FACTURA ANTERIOR - 'If ObjFactura.Folio = TxtFolio.Text.ToEntero Then - ' If ObjFolios.GetFolios(ObjFactura.TipoDocto, UsuarioActual.CveEmpresa) Then - ' Dim DtFolios As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSucursal = {0} And Estado = 'Activo'", ObjFactura.CveSucursal)) - ' If DtFolios.Rows.Count > 0 Then - ' 'ViewState("CveFolio") = DtFolios.Rows(0)("CveFolio").ToString.ToEntero - ' 'ViewState("NumAprobacion") = CLng(DtFolios.Rows(0)("Aprobacion").ToString) - ' 'ViewState("FechaAprobacion") = DtFolios.Rows(0)("FechaAprobacion").ToString.ToDate - ' 'ViewState("FolioActual") = DtFolios.Rows(0)("FActual").ToString - ' 'LblSerie.Text = DtFolios.Rows(0)("Serie").ToString - - ' If UsuarioActual.CveEmpresa <> 72 Then - ' ObjFactura.Folio = DtFolios.Rows(0)("FActual").ToString.ToEntero - ' End If - ' End If - ' End If - 'End If - - 'GUARDA VENTA - - Dim TieneAnticipo As Boolean = False - Dim CveAnticipoPadre As Integer = 0 ' vinculación con anticipo - Dim FolioFiscalRelacionado As String = "" - If GVAnticipos.Rows.Count > 0 Then - Dim actualindex As Integer = 0 - For Each row2 As GridViewRow In GVAnticipos.Rows - - If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then - - TieneAnticipo = True - CveAnticipoPadre = row2.DataKey("CveVenta").ToEntero - ObjFactura.CveVentaRelacion = CveAnticipoPadre 'relaciona al anticipo - CveAnticipo = CveAnticipoPadre - - ObjFactura.ImporteRelacion = row2.FCTextBox($"TxtAnticipo{actualindex}").Text.ToDecimal - FolioFiscalRelacionado = row2.DataKey("FolioFiscal") - ObjFactura.CveVentaPadre = row2.DataKey("CveVenta").ToEntero - - End If - actualindex = actualindex + 1 - Next - End If - - GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjFactura, TmpDT, ObjFactura.CveNCaVincular, ObjContPaq, ObjBancos, ObjOS, ObjEventos, ObjCGame, ObjClientes) - - 'SI ES REFACTURACION - Dim ObjNC As List(Of Object) = Nothing - If ErrorList.Count = 0 Then - If NuevaFactura = 1 Then - 'Si directamente como cancelada sin aceptación, debe de generar la cancelacion aquí - If Me.CveEstatusRefacturacion = 0 Then ' cuando es refacturación sin aceptación debe de cancelar y reducir saldo - ObjNC = generaNC(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, ObjEventos) - If ObjNC Is Nothing Then - ErrorList.Add("No se pudo Cancelar la Factura") - End If - End If - 'Esquema viejo, evitamos que aparezca por surtir - If ErrorList.Count = 0 Then - If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then - ErrorList.Add("No se pudo Cancelar el movimiento de almacen de la Factura") - End If - End If - - End If - End If - - ''[IPP] - ''DATATABLES A USAR - 'Dim DtSites As New DataTable - 'Dim DtExcel As New DataTable - - ''CARGAS EXCEL EN DATATABLE - 'DtExcel = TmpDT - - ''CARGAS LOS SITES REGISTRADOS - 'If ObjBancos.GetBancos() Then - ' DtSites = ObjBancos.DtResultados - 'End If - - ''PROCESAS EXCEL - 'Dim CveSiteActual = -1 - 'For Each Row As DataRow In TmpDT.Rows - - ' 'VALIDA QUE EXISTA EL SITE - ' If DtExcel.Select($"Site = {Row("SITE")}").Count = 0 Then 'SI NO EXISTE AGREGA EL SITE - ' CveSiteActual = ObjBancos.AddComplementoPago(-1, -1, "", -1, -1, -1) - - ' 'VALIDAS QUE SE HALLA AGREGADO - ' If CveSiteActual > 0 Then - ' 'AGREGA NUEVO SITE AL DATATABLE TEMPORAL DE SITES - ' Dim DrNuevoSite = DtExcel.NewRow - ' DrNuevoSite("CVE") = CveSiteActual - ' DrNuevoSite("SITE") = Row("SITE") - ' Else - ' Alert("ERROR AL AGREGAR EL SITE") - ' Exit For - ' End If - - ' ElseIf DtExcel.Select($"Site = {Row("SITE")}").Count = 1 Then 'SI EXISTE OBTIENES CVE - ' CveSiteActual = DtExcel.Select($"Site = {Row("SITE")}")(0)("Cve").ToString.ToEntero - ' Else - ' Alert("ERROR SOLO DEBE DAR RESULTADO 0 ó 1") - ' Exit For - ' End If - - ' 'AGREGA A TABLA CON LA DE MAS INFORMACION - ' If Not ObjBancos.AddBancos_EstatusIE(CveSiteActual, Row("CAMPOS").ToString, Row("CAMPOS_EXTRA").ToString.ToEntero) Then - ' Alert("ERROR AL GUARDAR") - ' Exit For - ' End If - - 'Next - - - - 'SI ES amortizacion 3.3 - Dim Obj2 As New List(Of Object) - - If ErrorList.Count = 0 Then - ' cambiar la condicion para saber si hay seleccionado - If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then - - If TieneAnticipo Then - CreaObjetosVentaAmortizacion(ObjVentas, FolioFiscalRelacionado, CveAnticipoPadre) - - Try - If RegistrarNCAmortizacion(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, Nothing, Nothing) Then - - Obj2.Add(ObjFacturaDevolucion) - - End If - Catch ex As Exception - ErrorList.Add("No se pudo generarse la nota de crédito de amortización") - End Try - - - End If - - If Obj2 Is Nothing AndAlso Obj2.Count = 0 Then - ErrorList.Add("No se pudo generarse la nota de crédito de amortización") - End If - End If - End If - - 'MARCA PARA NO SURTIR VENTA DE COTNRATO DE CONSIGNACION DE VENTA | [IPP] : PARCHE - If ErrorList.Count = 0 Then - If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then - If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then - ErrorList.Add("No se pudo cancelar el movimiento de almacen de la Factura de consignación") - End If - End If - End If - - If ErrorList.Count = 0 Then - If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then - If Not RegistraAlmacenConsignacionVenta(ObjInventario, ObjFactura) Then - ErrorList.Add("Ocurrió un error al registrar los movimientos de almacén del contrato de consignación") - End If - End If - End If - - If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 Then - - 'ACTUALIZA VENTA COTIZACIÓN - If EraCotizacion = 1 And BtnEmitirImprimir.Text = "Facturar" Then - If Not ObjVentas.UpdateVentaCotizacion(ObjFactura.CveVenta, Request("CveVenta").ToEntero) Then - ErrorList.Add("Ocurrió un error al actualizar la cotización") - End If - End If - - 'ACTUALIZA VENTAPADRE PEDIDO - If Request("DevPed").ToEntero > 0 AndAlso ErrorList.Count = 0 Then - If Not ObjVentas.UpdateVentaCotizacion(Request("DevPed").ToEntero, ObjFactura.CveVenta) Then - ErrorList.Add("Ocurrió un error al actualizar la devolución de pedido") - End If - End If - - 'ACTUALIZA LA COLUMNA CveVentaFacturada - If (Request("CveRemision") IsNot Nothing AndAlso ViewState("CveRemision").ToString.ToEntero > 0) AndAlso (Request("Op") IsNot Nothing AndAlso Request("Op") = "Rem") AndAlso ErrorList.Count = 0 Then - If Not ObjVentas.UpdateVentaRemision(ViewState("CveRemision").ToString.ToEntero, ObjFactura.CveVenta) Then - ErrorList.Add("Ocurrió un error al actualizar la remision") - End If - End If - - 'Agregamos las OCs a la tabla - If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then - Dim CveVentaDetalle As Integer = 0 - Dim CveOrdenCompraDetalle As Integer = 0 - Dim Cantidad As Decimal = 0 - - - For Each row As DataRow In TmpDT.Rows - Cantidad = row("Cantidad").ToString.ToDecimal - CveVentaDetalle = row("CveVentaDetalle").ToString.ToEntero - CveOrdenCompraDetalle = row("CveOrdenCompraDetalle").ToString.ToEntero - If Not ObjVentas.AgregarVentaOCDetalle(CveVentaDetalle, CveOrdenCompraDetalle, Cantidad) Then - ErrorList.Add("Ocurrió un Error al agregar el detalle de la Remision") - End If - Next - - End If - - 'Agregamos las Cotizaciones a la tabla - If DtCotizacionesPS IsNot Nothing AndAlso DtCotizacionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then - Dim CveVentaDetalle As Integer = 0 - Dim CveVentaDetallePadre As Integer = 0 - Dim Cantidad As Decimal = 0 - Dim CvePS As Integer = 0 - Dim PU As Decimal = 0 - - For Each row As DataRow In DtCotizacionesPS.Rows - Cantidad = DtCotizacionTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal - CvePS = DtCotizacionTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero - PU = DtCotizacionTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal - CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero - CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero - - If Not ObjVentas.AgregaCotizacionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then - ErrorList.Add("Ocurrió un Error al agregar el detalle de la Cotización.") - End If - Next - End If - - - - 'Marcamos las ventas anteriores a febrero como surtidas - Ajuste Compu - If ErrorList.Count = 0 Then - If Not ObjVentas.MarcarRemisionesSinSurtir(ObjVentas.CveVenta) Then - ErrorList.Add("Ocurrió un Error al marcar la factura") - End If - End If - - If CveOS > 0 And FacturaMateriales = 1 AndAlso ErrorList.Count = 0 Then - If SalidaAlmacenMateriales(ObjInventario, CveOS, ObjConta, True, 3) Then - ErrorList.Add("Ocurrió un Error al dar salida de materiales de almacen") - End If - End If - - If CveFactura > 0 AndAlso ErrorList.Count = 0 Then - If Not ObjVentas.UpdateVentaFacturas(CveFactura, ObjVentas.CveVenta, UsuarioActual.CveEmpresa) Then - ErrorList.Add("No se pudo actualizar la Factura") - End If - End If - - If CveCicloComercial > 0 AndAlso ErrorList.Count = 0 Then - If Not ObjContr.CicloComercialUpdate(CveCicloComercial, True, UsuarioActual.CveEmpresa) Then - ErrorList.Add("No se pudo actualizar ") - End If - End If - - If ErrorList.Count = 0 AndAlso ObjFactura.CveVenta > 0 AndAlso DtDocumentacionCliente IsNot Nothing Then - ' si se cargó algun documento - If DtDocumentacionCliente.FiltraParametros("RutaArchivo <> ''").Rows.Count > 0 Then - GuardaVentaDocumentosCliente(ObjFactura.CveVenta, ObjDocCliente) - End If - End If - - - - If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 AndAlso (SeGuardoPrePoliza Or ObjFactura.TipoDocto.Contiene("Ped", "Cot", "DPe", "PeC", "PA", "Pd2")) Then - ObjVentas.Commit() - - 'ContPAQ El movimiento 1 es el de Venta - Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" - - If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Rem", "Cot", "Ped", "Pd2", "PA", "NC") Then - AutoConta = False - End If - - If AutoConta And UsuarioActual.Empresa.UsaContabilidad = True Then - If idCuentaContabilizacion > 0 Then - If ObjConta.ContabilizarPrePoliza(ObjFactura.CvePrePoliza, ObjFactura.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then - - Else - Alert("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico", TipoMensaje.MsgError) - - End If - Else - Alert(String.Format("Falta asignación de las siguientes cuentas contables: {0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia) - - End If - End If - - If ObjContPaq IsNot Nothing Then ObjContPaq.Commit() - 'If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() - - 'RMF, cuando es pedido, se manda autorización. - If ObjFactura.TipoDocto.Contiene("PA") Then - - Dim Titulo As String = "Solicitud de autorización" 'usuarios de crédito y cobranza - Dim Msg As String = String.Format("{0} - Folio {1} ", DdlSubProyectoDatos.SelectedItem.Text, TxtFolio.Text) - If UsuarioActual.CveEmpresa = 119 Then - ClsSisNotificaciones.SendNotificacionERP(1715, Titulo, Msg, 1) - ClsSisNotificaciones.SendNotificacionERP(1815, Titulo, Msg, 1) - ClsSisNotificaciones.SendNotificacionERP(1830, Titulo, Msg, 1) - End If - - End If - - ViewState("CveVenta") = ObjFactura.CveVenta - - GVAnticipos.DataBind() - - - Try - Dim DirectoriArchivoXML As String = System.IO.Path.Combine(Server.MapPath("/"), "Empresas", UsuarioActual.CveEmpresa.ToString, ObjFactura.TipoDocto) - If Not Directory.Exists(DirectoriArchivoXML) Then - Directory.CreateDirectory(DirectoriArchivoXML) - End If - Catch ex As Exception - - End Try - - - - Dim SeTimbro As Boolean = False - Dim SeTimbroNC As Boolean = False - Dim EstatusSMS = 0 - - 'TIMBRADO Y CASO ESPECIAL NOTA DE CREDITO - If (TipoDoctoDevolucion = "" OrElse Not TipoDoctoDevolucion.Contiene("Rem", "Cot", "Ped", "DPe", "PA", "Pd2")) Then - - Dim DebeTimbrar As Boolean = True - If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then - 'si tiene anticipos seleccionados y el total es cero, que no se timbre(previo empresa72) - If LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0 Then - DebeTimbrar = False - End If - End If - - If ObjFactura.TipoDocto.Contiene("Ing", "Egs", "Ant", "Dev") Then - If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then - - 'FACTURA INGRESO/EGRESO - Dim ObjTimbrado As New Timbrado - Dim FM As New Modelos.FemsaFactura - Dim TmpDT7Eleven As New DataTable - Dim TmpDTComplementosTimbrado As New DataTable - - PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) - 'DOCUMENTO ACTUAL - If DebeTimbrar Then - SeTimbro = ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) - - 'NOTA DE CREDITO - REFACTURADA - CASO ESPECIAL, TIMBRADO E IMPRESION - If Not IsNothing(Obj2) AndAlso Obj2.Count > 0 AndAlso SeTimbro Then - Dim ofa As Modelos.Factura = CType(Obj2(0), Modelos.Factura) - 'asigna el foliofiscal del ingreso que se acaba de timbrar, cuando es amortización de anticipo con NC - If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then - ofa.Timbre.CFDIRelacionados.UUID.Clear() - ofa.Timbre.CFDIRelacionados.UUID.Add(ObjTimbrado.UUID) - End If - - ObjTimbrado.TimbrarFactura(UsuarioActual, ofa) - GeneraPDFFactura(ChkEnviarFactura.Checked) - End If - - If SeTimbro AndAlso ObjFactura.TipoDocto.Contiene("Ing") Then - EstatusSMS = EnviarSMSTimbrado(ObjEventos) - End If - If Not SeTimbro Then - Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgError) - End If - - End If - - 'NOTA DE CREDITO DE REFACTURACION - If RefacturacionGeneroNC Then - If Not IsNothing(ObjNC) AndAlso ObjNC.Count > 0 Then - Dim ofa As Modelos.Factura = CType(ObjNC(0), Modelos.Factura) + EmitirImprimirNew() + End Sub +#End Region + +#Region " NNNNEEEEEEEWWWWWW " + Private Sub InicializaImprimirNew() + Dim Archivo As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) + Dim Archivo2 As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) + + LnkImprimir.Visible = False + + 'If (UsuarioActual.CveEmpresa.Contiene(1, 4, 5, 7, 11, 12, 72, 80, 81, 83) And UsuarioActual.CveUsuario = 100) Or UsuarioActual.CveEmpresa.Contiene(80, 83) Or UsuarioActual.CveUsuario = 100 Then + If (Archivo.Exists Or Archivo2.Exists) And IfNull(CveVenta, 0).ToString.ToEntero > 0 Then + HplDownPDF.Visible = True + HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))) + End If + + UpnTools.Update() + End Sub + + Protected Sub EmitirImprimirNew() + + + If ValidaPagosContado() Then + Exit Sub + End If + + CreaObjetosVenta() + + 'Verifica versión 3.3.() + If ObjFactura.Version = "3.3" AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then + Dim dttsat As DataTable = TmpDT.FiltraParametros("ISNULL(SATClaveProdServ,'') = '' OR ISNULL(SATClaveUM,'') = '' ") + If dttsat IsNot Nothing AndAlso dttsat.Rows.Count > 0 Then + Dim str As New StringBuilder + str.Append("Los siguientes productos no tiene asignado la clave Producto SAT o Unidad Medida SAT

    ") + For Each drt As DataRow In dttsat.Rows + str.AppendFormat("{0}
    ", drt("CodigoPS")) + Next + Alert(str.ToString, TipoMensaje.MsgAdvertencia) + dttsat.Dispose() + Exit Sub + End If + dttsat.Dispose() + End If + + If ObjFactura Is Nothing Or (ObjFactura.Cliente Is Nothing And Not CveEmpresaCRM > 0) Then + Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError) + ObjFactura = Nothing + Exit Sub + End If + + 'If Not CveEmpresaCRM > 0 Then + ' If ObjFactura.Cliente.AplicaComercioExterior Then + ' If Not ValidaComercioExterior() Then + ' ObjFactura = Nothing + ' Exit Sub + ' End If + ' End If + 'End If + + + 'VALIDA TOTAL DE LA NOTA DE CREDITO Y LA FACTURA VINCULADA *** ESTABA TRONANDO EN COMPU 11/01/17 *** + 'If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + ' If SubTotalFacturaVinNC() > 0 Then 'pendiente + ' If GvInvNC.Rows.Count > 0 Then 'pendiente + ' If Not (SubTotalFacturaVinNC() = TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio)) Then + ' Alert(String.Format("El sub-total debe ser igual a '{0}'", SubTotalFacturaVinNC().FormatoNumero)) + ' Exit Sub + ' End If + ' Else + ' If SubTotalFacturaVinNC() < TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio) Then 'pendiente + ' Alert(String.Format("El sub-total no puede exceder a : {0}", SubTotalFacturaVinNC().FormatoNumero)) + ' Exit Sub + ' End If + ' End If + ' End If + 'End If + + If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then + If ObjFactura.SubTotal <= 0 Then + Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + End If + + 'VALIDA CUENTAS CONTABLES DE AC + If UsuarioActual.Empresa.UsaAC Then + If ObjFactura.Cliente.IdCtaContClientes <= 0 Then + Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError) + Exit Sub + End If + 'If ViewState("IdCtaContClientes").ToString.ToEntero <= 0 Then 'GetClientes ObjCliente.IdCtaContClientes + ' Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError) + ' Exit Sub + 'End If + + If ObjFactura.SubTotal <= 0 Then + Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'If TxtSubTotal.Text.ToDouble <= 0 Then + ' Alert("Especifique importe en conceptos", TipoMensaje.MsgError) + ' Exit Sub + 'End If + End If + + 'cuando es contado debe de tener especificado la forma de pago + 'If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso ObjFactura.Total > 0 AndAlso RBLPago.SelectedValue = "2" AndAlso ObjFactura.Total - If(DtPagos Is Nothing, 0, DtPagos.SUM("Importe")) > 0 Then ' AndAlso ObjFactura.CveCorte > 0 + ' Alert("No se han especificado las formas de pago. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) + ' Exit Sub + 'End If + + + If ObjFactura.CveCliente > 0 Or CveEmpresaCRM > 0 Then + If TmpDT.Rows.Count > 0 Then + + Dim ObjVentas As New ClsVentas() + Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) + Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) + Dim ObjContr As New ClsContratos(ObjVentas.IniciaTransacSQL()) + Dim ObjOS As New ClsOS(ObjVentas.IniciaTransacSQL()) + Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) + Dim ObjClientes As New ClsClientes(ObjVentas.IniciaTransacSQL()) + Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) + Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) + Dim ObjDocCliente As New ClsEdocumentacion(ObjVentas.IniciaTransacSQL()) + Dim ObjContPaq As ClsContPAQi = Nothing + 'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) + ErrorList = New List(Of String) + MensajeAlert = New StringBuilder + + + 'CONTABILIDAD AUTOMATICA Y AC + If UsuarioActual.Empresa.UsaAC OrElse UsuarioActual.Empresa.Funcionalidad(200) = "1" Then + ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) + End If + + 'VERIFICA QUE EL FOLIO NO SEA IGUAL AL DE LA FACTURA ANTERIOR + 'If ObjFactura.Folio = TxtFolio.Text.ToEntero Then + ' If ObjFolios.GetFolios(ObjFactura.TipoDocto, UsuarioActual.CveEmpresa) Then + ' Dim DtFolios As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSucursal = {0} And Estado = 'Activo'", ObjFactura.CveSucursal)) + ' If DtFolios.Rows.Count > 0 Then + ' 'ViewState("CveFolio") = DtFolios.Rows(0)("CveFolio").ToString.ToEntero + ' 'ViewState("NumAprobacion") = CLng(DtFolios.Rows(0)("Aprobacion").ToString) + ' 'ViewState("FechaAprobacion") = DtFolios.Rows(0)("FechaAprobacion").ToString.ToDate + ' 'ViewState("FolioActual") = DtFolios.Rows(0)("FActual").ToString + ' 'LblSerie.Text = DtFolios.Rows(0)("Serie").ToString + + ' If UsuarioActual.CveEmpresa <> 72 Then + ' ObjFactura.Folio = DtFolios.Rows(0)("FActual").ToString.ToEntero + ' End If + ' End If + ' End If + 'End If + + 'GUARDA VENTA + + Dim TieneAnticipo As Boolean = False + Dim CveAnticipoPadre As Integer = 0 ' vinculación con anticipo + Dim FolioFiscalRelacionado As String = "" + If GVAnticipos.Rows.Count > 0 Then + Dim actualindex As Integer = 0 + For Each row2 As GridViewRow In GVAnticipos.Rows + + If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then + + TieneAnticipo = True + CveAnticipoPadre = row2.DataKey("CveVenta").ToEntero + ObjFactura.CveVentaRelacion = CveAnticipoPadre 'relaciona al anticipo + CveAnticipo = CveAnticipoPadre + + ObjFactura.ImporteRelacion = row2.FCTextBox($"TxtAnticipo{actualindex}").Text.ToDecimal + FolioFiscalRelacionado = row2.DataKey("FolioFiscal") + ObjFactura.CveVentaPadre = row2.DataKey("CveVenta").ToEntero + + End If + actualindex = actualindex + 1 + Next + End If + + GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjFactura, TmpDT, ObjFactura.CveNCaVincular, ObjContPaq, ObjBancos, ObjOS, ObjEventos, ObjCGame, ObjClientes) + + 'SI ES REFACTURACION + Dim ObjNC As List(Of Object) = Nothing + If ErrorList.Count = 0 Then + If NuevaFactura = 1 Then + 'Si directamente como cancelada sin aceptación, debe de generar la cancelacion aquí + If Me.CveEstatusRefacturacion = 0 Then ' cuando es refacturación sin aceptación debe de cancelar y reducir saldo + ObjNC = generaNC(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, ObjEventos) + If ObjNC Is Nothing Then + ErrorList.Add("No se pudo Cancelar la Factura") + End If + End If + 'Esquema viejo, evitamos que aparezca por surtir + If ErrorList.Count = 0 Then + If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then + ErrorList.Add("No se pudo Cancelar el movimiento de almacen de la Factura") + End If + End If + + End If + End If + + ''[IPP] + ''DATATABLES A USAR + 'Dim DtSites As New DataTable + 'Dim DtExcel As New DataTable + + ''CARGAS EXCEL EN DATATABLE + 'DtExcel = TmpDT + + ''CARGAS LOS SITES REGISTRADOS + 'If ObjBancos.GetBancos() Then + ' DtSites = ObjBancos.DtResultados + 'End If + + ''PROCESAS EXCEL + 'Dim CveSiteActual = -1 + 'For Each Row As DataRow In TmpDT.Rows + + ' 'VALIDA QUE EXISTA EL SITE + ' If DtExcel.Select($"Site = {Row("SITE")}").Count = 0 Then 'SI NO EXISTE AGREGA EL SITE + ' CveSiteActual = ObjBancos.AddComplementoPago(-1, -1, "", -1, -1, -1) + + ' 'VALIDAS QUE SE HALLA AGREGADO + ' If CveSiteActual > 0 Then + ' 'AGREGA NUEVO SITE AL DATATABLE TEMPORAL DE SITES + ' Dim DrNuevoSite = DtExcel.NewRow + ' DrNuevoSite("CVE") = CveSiteActual + ' DrNuevoSite("SITE") = Row("SITE") + ' Else + ' Alert("ERROR AL AGREGAR EL SITE") + ' Exit For + ' End If + + ' ElseIf DtExcel.Select($"Site = {Row("SITE")}").Count = 1 Then 'SI EXISTE OBTIENES CVE + ' CveSiteActual = DtExcel.Select($"Site = {Row("SITE")}")(0)("Cve").ToString.ToEntero + ' Else + ' Alert("ERROR SOLO DEBE DAR RESULTADO 0 ó 1") + ' Exit For + ' End If + + ' 'AGREGA A TABLA CON LA DE MAS INFORMACION + ' If Not ObjBancos.AddBancos_EstatusIE(CveSiteActual, Row("CAMPOS").ToString, Row("CAMPOS_EXTRA").ToString.ToEntero) Then + ' Alert("ERROR AL GUARDAR") + ' Exit For + ' End If + + 'Next + + + + 'SI ES amortizacion 3.3 + Dim Obj2 As New List(Of Object) + + If ErrorList.Count = 0 Then + ' cambiar la condicion para saber si hay seleccionado + If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then + + If TieneAnticipo Then + CreaObjetosVentaAmortizacion(ObjVentas, FolioFiscalRelacionado, CveAnticipoPadre) + + Try + If RegistrarNCAmortizacion(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, Nothing, Nothing) Then + + Obj2.Add(ObjFacturaDevolucion) + + End If + Catch ex As Exception + ErrorList.Add("No se pudo generarse la nota de crédito de amortización") + End Try + + + End If + + If Obj2 Is Nothing AndAlso Obj2.Count = 0 Then + ErrorList.Add("No se pudo generarse la nota de crédito de amortización") + End If + End If + End If + + 'MARCA PARA NO SURTIR VENTA DE COTNRATO DE CONSIGNACION DE VENTA | [IPP] : PARCHE + If ErrorList.Count = 0 Then + If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then + If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then + ErrorList.Add("No se pudo cancelar el movimiento de almacen de la Factura de consignación") + End If + End If + End If + + If ErrorList.Count = 0 Then + If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then + If Not RegistraAlmacenConsignacionVenta(ObjInventario, ObjFactura) Then + ErrorList.Add("Ocurrió un error al registrar los movimientos de almacén del contrato de consignación") + End If + End If + End If + + If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 Then + + 'ACTUALIZA VENTA COTIZACIÓN + If EraCotizacion = 1 And BtnEmitirImprimir.Text = "Facturar" Then + If Not ObjVentas.UpdateVentaCotizacion(ObjFactura.CveVenta, Request("CveVenta").ToEntero) Then + ErrorList.Add("Ocurrió un error al actualizar la cotización") + End If + End If + + 'ACTUALIZA VENTAPADRE PEDIDO + If Request("DevPed").ToEntero > 0 AndAlso ErrorList.Count = 0 Then + If Not ObjVentas.UpdateVentaCotizacion(Request("DevPed").ToEntero, ObjFactura.CveVenta) Then + ErrorList.Add("Ocurrió un error al actualizar la devolución de pedido") + End If + End If + + 'ACTUALIZA LA COLUMNA CveVentaFacturada + If (Request("CveRemision") IsNot Nothing AndAlso ViewState("CveRemision").ToString.ToEntero > 0) AndAlso (Request("Op") IsNot Nothing AndAlso Request("Op") = "Rem") AndAlso ErrorList.Count = 0 Then + If Not ObjVentas.UpdateVentaRemision(ViewState("CveRemision").ToString.ToEntero, ObjFactura.CveVenta) Then + ErrorList.Add("Ocurrió un error al actualizar la remision") + End If + End If + + 'Agregamos las OCs a la tabla + If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then + Dim CveVentaDetalle As Integer = 0 + Dim CveOrdenCompraDetalle As Integer = 0 + Dim Cantidad As Decimal = 0 + + + For Each row As DataRow In TmpDT.Rows + Cantidad = row("Cantidad").ToString.ToDecimal + CveVentaDetalle = row("CveVentaDetalle").ToString.ToEntero + CveOrdenCompraDetalle = row("CveOrdenCompraDetalle").ToString.ToEntero + If Not ObjVentas.AgregarVentaOCDetalle(CveVentaDetalle, CveOrdenCompraDetalle, Cantidad) Then + ErrorList.Add("Ocurrió un Error al agregar el detalle de la Remision") + End If + Next + + End If + + 'Agregamos las Cotizaciones a la tabla + If DtCotizacionesPS IsNot Nothing AndAlso DtCotizacionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then + Dim CveVentaDetalle As Integer = 0 + Dim CveVentaDetallePadre As Integer = 0 + Dim Cantidad As Decimal = 0 + Dim CvePS As Integer = 0 + Dim PU As Decimal = 0 + + For Each row As DataRow In DtCotizacionesPS.Rows + Cantidad = DtCotizacionTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal + CvePS = DtCotizacionTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero + PU = DtCotizacionTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal + CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero + CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero + + If Not ObjVentas.AgregaCotizacionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then + ErrorList.Add("Ocurrió un Error al agregar el detalle de la Cotización.") + End If + Next + End If + + + + 'Marcamos las ventas anteriores a febrero como surtidas - Ajuste Compu + If ErrorList.Count = 0 Then + If Not ObjVentas.MarcarRemisionesSinSurtir(ObjVentas.CveVenta) Then + ErrorList.Add("Ocurrió un Error al marcar la factura") + End If + End If + + If CveOS > 0 And FacturaMateriales = 1 AndAlso ErrorList.Count = 0 Then + If SalidaAlmacenMateriales(ObjInventario, CveOS, ObjConta, True, 3) Then + ErrorList.Add("Ocurrió un Error al dar salida de materiales de almacen") + End If + End If + + If CveFactura > 0 AndAlso ErrorList.Count = 0 Then + If Not ObjVentas.UpdateVentaFacturas(CveFactura, ObjVentas.CveVenta, UsuarioActual.CveEmpresa) Then + ErrorList.Add("No se pudo actualizar la Factura") + End If + End If + + If CveCicloComercial > 0 AndAlso ErrorList.Count = 0 Then + If Not ObjContr.CicloComercialUpdate(CveCicloComercial, True, UsuarioActual.CveEmpresa) Then + ErrorList.Add("No se pudo actualizar ") + End If + End If + + If ErrorList.Count = 0 AndAlso ObjFactura.CveVenta > 0 AndAlso DtDocumentacionCliente IsNot Nothing Then + ' si se cargó algun documento + If DtDocumentacionCliente.FiltraParametros("RutaArchivo <> ''").Rows.Count > 0 Then + GuardaVentaDocumentosCliente(ObjFactura.CveVenta, ObjDocCliente) + End If + End If + + + + If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 AndAlso (SeGuardoPrePoliza Or ObjFactura.TipoDocto.Contiene("Ped", "Cot", "DPe", "PeC", "PA", "Pd2")) Then + ObjVentas.Commit() + + 'ContPAQ El movimiento 1 es el de Venta + Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" + + If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Rem", "Cot", "Ped", "Pd2", "PA", "NC") Then + AutoConta = False + End If + + If AutoConta And UsuarioActual.Empresa.UsaContabilidad = True Then + If idCuentaContabilizacion > 0 Then + If ObjConta.ContabilizarPrePoliza(ObjFactura.CvePrePoliza, ObjFactura.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then + + Else + Alert("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico", TipoMensaje.MsgError) + + End If + Else + Alert(String.Format("Falta asignación de las siguientes cuentas contables: {0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia) + + End If + End If + + If ObjContPaq IsNot Nothing Then ObjContPaq.Commit() + 'If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() + + 'RMF, cuando es pedido, se manda autorización. + If ObjFactura.TipoDocto.Contiene("PA") Then + + Dim Titulo As String = "Solicitud de autorización" 'usuarios de crédito y cobranza + Dim Msg As String = String.Format("{0} - Folio {1} ", DdlSubProyectoDatos.SelectedItem.Text, TxtFolio.Text) + If UsuarioActual.CveEmpresa = 119 Then + ClsSisNotificaciones.SendNotificacionERP(1715, Titulo, Msg, 1) + ClsSisNotificaciones.SendNotificacionERP(1815, Titulo, Msg, 1) + ClsSisNotificaciones.SendNotificacionERP(1830, Titulo, Msg, 1) + End If + + End If + + ViewState("CveVenta") = ObjFactura.CveVenta + + GVAnticipos.DataBind() + + + Try + Dim DirectoriArchivoXML As String = System.IO.Path.Combine(Server.MapPath("/"), "Empresas", UsuarioActual.CveEmpresa.ToString, ObjFactura.TipoDocto) + If Not Directory.Exists(DirectoriArchivoXML) Then + Directory.CreateDirectory(DirectoriArchivoXML) + End If + Catch ex As Exception + + End Try + + + + Dim SeTimbro As Boolean = False + Dim SeTimbroNC As Boolean = False + Dim EstatusSMS = 0 + + 'TIMBRADO Y CASO ESPECIAL NOTA DE CREDITO + If (TipoDoctoDevolucion = "" OrElse Not TipoDoctoDevolucion.Contiene("Rem", "Cot", "Ped", "DPe", "PA", "Pd2")) Then + + Dim DebeTimbrar As Boolean = True + If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then + 'si tiene anticipos seleccionados y el total es cero, que no se timbre(previo empresa72) + If LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0 Then + DebeTimbrar = False + End If + End If + + If ObjFactura.TipoDocto.Contiene("Ing", "Egs", "Ant", "Dev") Then + If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then + + 'FACTURA INGRESO/EGRESO + Dim ObjTimbrado As New Timbrado + Dim FM As New Modelos.FemsaFactura + Dim TmpDT7Eleven As New DataTable + Dim TmpDTComplementosTimbrado As New DataTable + + PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) + 'DOCUMENTO ACTUAL + If DebeTimbrar Then + SeTimbro = ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) + + 'NOTA DE CREDITO - REFACTURADA - CASO ESPECIAL, TIMBRADO E IMPRESION + If Not IsNothing(Obj2) AndAlso Obj2.Count > 0 AndAlso SeTimbro Then + Dim ofa As Modelos.Factura = CType(Obj2(0), Modelos.Factura) + 'asigna el foliofiscal del ingreso que se acaba de timbrar, cuando es amortización de anticipo con NC + If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then + ofa.Timbre.CFDIRelacionados.UUID.Clear() + ofa.Timbre.CFDIRelacionados.UUID.Add(ObjTimbrado.UUID) + End If + + ObjTimbrado.TimbrarFactura(UsuarioActual, ofa) + GeneraPDFFactura(ChkEnviarFactura.Checked) + End If + + If SeTimbro AndAlso ObjFactura.TipoDocto.Contiene("Ing") Then + EstatusSMS = EnviarSMSTimbrado(ObjEventos) + End If + If Not SeTimbro Then + Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgError) + End If + + End If + + 'NOTA DE CREDITO DE REFACTURACION + If RefacturacionGeneroNC Then + If Not IsNothing(ObjNC) AndAlso ObjNC.Count > 0 Then + Dim ofa As Modelos.Factura = CType(ObjNC(0), Modelos.Factura) SeTimbroNC = ObjTimbrado.TimbrarFactura(UsuarioActual, ofa) - End If - End If - - ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then - GeneraPDFCBB(ObjFactura.Fecha, Nothing, ObjFactura.SerieFolio, False) - End If - End If - - End If - - 'VERIFICAR 100% AVANCE A IMPORTE Y CANTIDAD - If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso CveContrato > 0 Then - If ObjContr.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then - - If ObjContr.DtResultados.Rows.Count > 0 Then - ' si es flexible que notifique el monto maximo, si no lo es que notifique el porcentaje alcanzado... flexible = 2, no flexible = 1 - Dim PorcentajeAvance As Double = ObjContr.DtResultados.Rows(0)("ContratoAvance").ToString.ToDouble - - If ObjContr.DtResultados.Rows(0)("ModalidadDetalle").ToString() = "1" Then - - If PorcentajeAvance >= 100 Then - EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString()) - End If - Else - Dim MontoMaximo As Double = ObjContr.DtResultados.Rows(0)("ImporteMax").ToString.ToDouble - - If PorcentajeAvance >= 100 And MontoMaximo > 0 Then - EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString(), MontoMaximo) - End If - End If - - End If - End If - End If - - 'MENSAJE PRINCIPAL - MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} se generó correctamente.

    ", ObjFactura.TipoDocumento, ObjFactura.SerieFolio)) - - - ' DESCARGA XML - SI SE TIMBRA MANDA CORREO CON FACTURA - If SeTimbro Then - Dim ArchivoXML = String.Format("{0}/XML/{1}/{2}.xml", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) - If File.Exists(ArchivoXML) Then - MensajeAlert.AppendFormat("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", ObjFactura.SerieFolio, ObjFactura.TipoDocto))) - End If - GeneraPDFFactura(ChkEnviarFactura.Checked) 'MANDA CORREO - - End If - - 'DESCARGA PDF - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant", "Egs", "Dev", "Pd2") Then - 'If Not ImprimeAlert Then - - Dim ArchivoIngPyMe As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.mrt", UsuarioActual.Empresa.Ruta)) - Dim ArchivoIng As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) - Dim ArchivoRem As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) - Dim ArchivoEgs As New System.IO.FileInfo(String.Format("{0}Formatos/NotaCredito.rdlc", UsuarioActual.Empresa.Ruta)) - - If ArchivoIng.Exists Or ArchivoRem.Exists Or ArchivoIngPyMe.Exists Or ArchivoEgs.Exists Then - MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))) - Else - MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") - End If - End If - - 'ERROR DE NO TIMBRADO - If Not SeTimbro And (DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue = "Ant") Then - MensajeAlert.AppendFormat("La factura no se pudo timbrar. Por favor intentelo de nuevo a traves del boton Emitir.") - End If - - 'ERROR DE NO TIMBRADO NC - If Not IsNothing(ObjNC) AndAlso ObjNC.Count > 0 AndAlso Not SeTimbroNC Then - MensajeAlert.AppendFormat("
    La NC #{0} no se pudo timbrar. Por favor intentelo de nuevo a traves del boton Emitir.", CType(ObjNC(0), Modelos.Factura).SerieFolio) - End If - - 'NOTIFICACION DE SMS - Select Case EstatusSMS - Case 1 - MensajeAlert.AppendFormat("
    Notificación SMS: enviado con éxito al cliente al celular: {0}", ObjFactura.Cliente.CobranzaTelefono) - Case 2 - MensajeAlert.AppendFormat("
    Notificación SMS: sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.") - Case 3 - MensajeAlert.AppendFormat("
    Notificación SMS: sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.") - End Select - - - 'AUTO DESCARGAR PDF - If UsuarioActual.CveEmpresa.Contiene(72, 1) Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") Then - RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))}'", "Imprimir") - End If - End If - - 'DESCARGAR PDF DE CICOVISA - 'If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 Then - ' If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then - ' MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=CIC&CVEVENTA={0}", CveVenta))) - ' End If - 'End If - - If DdlTipoComprobante.SelectedValue = "Cot" Then - If Not CveEmpresaCRM > 0 Then - If CveVenta > 0 Then MensajeAlert = New StringBuilder - Dim ArchivoCotizacion As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.rdlc", UsuarioActual.Empresa.Ruta)) - - If ArchivoCotizacion.Exists Then - MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta))) - Else - MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") - End If - - GeneraPDFCotizacion(ChkEnviarFactura.Checked) ' MANDA CORREO - End If - ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then - If UsuarioActual.CveEmpresa.Contiene(81, 109) Then - EnviaPDFRemision(ChkEnviarFactura.Checked) - End If - End If - - 'ENVIA CORREO CON DETALLE DEL CONTRATO - If DdlTipoComprobante.SelectedValue.Contiene("DPe", "Ped") Then - If Not String.IsNullOrEmpty(CorreoNotificacionPedDev) Then - EnviarCorreoDevPed() - End If - End If - - 'MOVIMIENTO DE ALMACEN - If ObjFactura.Inv_CveMovimiento > 0 Then - MensajeAlert.AppendFormat("

    Movimiento de Almacén
    ", ObjFactura.Inv_CveMovimiento) - End If - - If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then - MensajeAlert.AppendFormat("

    Se generó una Nota de crédito Folio: {0} amortizando el anticipo
    ", ObjFacturaDevolucion.Folio) - End If - - 'MUESTA ALERT OK - ' si es elrol 1165-Ventas,EMp:80, o la empresa 119, recarga ventas, para seguir registrando-. - Dim Liga = If(UsuarioActual.CveRol = 1165 Or UsuarioActual.CveEmpresa = 119, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", If(CveEmpresaCRM > 0, $"document.location.href=""/CRM/EmpresaCRM.aspx?CveEmpresaCRM={CveEmpresaCRM}"";", $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}&Opt=3"";")) - Alert(MensajeAlert.ToString, TipoMensaje.MsgInformacion, Liga) - - - 'LIMPIA CONDICIONES DE PAGO - CONTADO - RBLPago.SelectedValue = "1" - LimpiaEscondeContado() - BtnEmitirImprimir.Visible = False - ObjFactura = Nothing - - Else - ObjVentas.RollBack() - If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() - - For Each ErrorItem In ErrorList - Alert(ErrorItem, TipoMensaje.MsgAdvertencia) - Next - - 'MUESTA ALERT ERROR - Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) - End If - - ObjVentas.Dispose() - ObjConta.Dispose() - ObjInventario.Dispose() - ObjCGame.Dispose() - ObjContr.Dispose() - ObjDocCliente.Dispose() - 'ObjFolios.Dispose() - ErrorList = Nothing - MensajeAlert = Nothing - If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() - TmpDT = TmpDTError.Copy - - Else - ObjVentas.RollBack() - If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() - - For Each ErrorItem In ErrorList - Alert(ErrorItem, TipoMensaje.MsgAdvertencia) - Next - - 'MUESTA ALERT ERROR - Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) - ObjVentas.Dispose() - ObjConta.Dispose() - ObjInventario.Dispose() - ObjCGame.Dispose() - ObjContr.Dispose() - ObjDocCliente.Dispose() - 'ObjFolios.Dispose() - ErrorList = Nothing - MensajeAlert = Nothing - If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() - TmpDT = TmpDTError.Copy - - End If - End If - End If - End Sub - - - Private Sub CreaObjetosVentaAmortizacion(ObjVentas As ClsVentas, FolioFiscalRelacionado As String, CveAnticipoPadre As Integer, Optional CveVentasPadre As Integer = -1) - ObjFacturaDevolucion = New Modelos.Factura - - ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario - ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero - - If CveVentasPadre > 0 Then - ObjFacturaDevolucion.CveVentaPadre = CveVentasPadre - ObjFacturaDevolucion.CveVentaRelacion = CveVentasPadre - Else - ObjFacturaDevolucion.CveVentaPadre = ObjVentas.CveVenta - ObjFacturaDevolucion.CveVentaRelacion = ObjVentas.CveVenta - End If - - - ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa - ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) - ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked - ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero - ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text - ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") - 'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim - 'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1) - ObjFacturaDevolucion.Serie = LblSerie.Text - ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) - ObjFacturaDevolucion.CvePrePoliza = -1 - ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero - ObjFacturaDevolucion.MetodoPago = "" - ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") - ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim - ' ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1) - ' ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") - 'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim - 'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim - ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito - ObjFacturaDevolucion.FormaPago = 0 - - ObjFacturaDevolucion.TipoDocto = "Egs" - ObjFacturaDevolucion.Fecha = Now - - ObjFacturaDevolucion.Version = "3.3" - ObjFacturaDevolucion.CveMetodoPago33 = 1 - ObjFacturaDevolucion.MetodoPago33 = "Pago en una sola exhibición" - ObjFacturaDevolucion.ClaveMetodoPagoSAT = "PUE" - - ObjFacturaDevolucion.CveFormaPago33 = 21 - ObjFacturaDevolucion.FormaPago33 = "Aplicación de anticipos" - ObjFacturaDevolucion.FormaPagoSAT33 = "30" - - ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero - ObjFacturaDevolucion.UsoCFDI = DdlUsoCFDI.SelectedItem.Text - ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") - - ObjFacturaDevolucion.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero - ObjFacturaDevolucion.TipoRelacion = "07" - Dim Fol As New List(Of String) - Fol.Add(FolioFiscalRelacionado) - ObjFacturaDevolucion.UUIDRelacionados = Fol - - Select Case ObjFacturaDevolucion.TipoDocto - Case "Ing" - ObjFacturaDevolucion.TipoDocumento = "Factura" - Case "REM" - ObjFacturaDevolucion.TipoDocumento = "Remision" - Case "Cot" - ObjFacturaDevolucion.TipoDocumento = "Cotizacion" - Case "Egs" - ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito" - Case "Dev" - ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución" - Case Else - ObjFacturaDevolucion.TipoDocumento = "" - End Select - - If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then - ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto - End If - - ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate - ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate - ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate - ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim - ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim - ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim - ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble - ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble - ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) - ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate - - ObjFacturaDevolucion.CveCorte = CveCorte - ObjFacturaDevolucion.CveMesa = -1 - ObjFacturaDevolucion.NumeroPersonas = 0 - ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) - ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "") - ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero - ObjFacturaDevolucion.Entrega = Entrega - ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate - - ObjFacturaDevolucion.CveVentaPadre = CveAnticipoPadre - ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero - If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then - DdlVendedor.Enabled = False - End If - - ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate - ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero - ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero - - ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") - ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim - ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim - ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim - ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim - ObjFacturaDevolucion.MonedaAbreviatura = "" - - 'Totales, Y se llena TmpDTImpuestos - ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal - ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal - ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal - ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal - ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal - ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal - ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal - ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal - - 'ObjFactura.BZDescripcion = TxtBZDescripcion.Text.Trim - 'ObjFactura.BZNombreCorto = TxtBZNombreCorto.Text.Trim - 'ObjFactura.BZTotalLetra = TxtBZTotalLetra.Text.Trim - - If TmpDTImpuestos Is Nothing Then - CreaDTImpuestos() - Else - TmpDTImpuestos.Clear() - End If - - Dim DR As DataRow = TmpDTImpuestos.NewRow() - - If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - - If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - - - 'If DdlFormatoImpresion.SelectedValue.ToEntero = 3 Or DdlFormatoImpresion.SelectedValue.ToEntero = 4 Then - ' DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (TxtSubTotal.Text.ToDecimal + TxtIVA.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal) : DR("Orden") = 55 : TmpDTImpuestos.Rows.Add(DR) - - ' DR = TmpDTImpuestos.NewRow() - 'End If - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - Dim Orden As Integer = 80 - If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then - DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - Orden = Orden + 1 - End If - End If - Next - - - If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) - - ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC") - - - 'otros - ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim - ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim - - - ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero - - If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then - ObjFacturaDevolucion.TipoCambio = 1 - ObjFacturaDevolucion.CveMoneda = 1 - End If - - 'DETALLES - ObjFacturaDevolucion.DtDetalle = TmpDT - ObjFacturaDevolucion.DtFirmas = DTmpF - - 'CLIENTE - ObjFacturaDevolucion.CveCliente = CveCliente - ObjFacturaDevolucion.SetCliente() - - ''SUCURSAL - 'ObjFacturaDevolucion.CveSucursal = DdlSucursal.SelectedValue.ToEntero - 'ObjFacturaDevolucion.SetSucursalMatriz(Me) - 'ObjFacturaDevolucion.SetSucursal(Me) - - ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel - ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt - ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt - ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad - ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text - ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text - ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text - ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text - ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text - ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais - ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString - ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text - ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "") - - - - ObjFacturaDevolucion.SetSubProyectoMatriz(Me) - ObjFacturaDevolucion.SetSubProyecto(Me) - - 'ENVIO DIRECCION - ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel - If ChkDireccionEnvio.Checked Then - If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then - For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows - ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero - ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString - ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString - ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString - ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString - ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString - Next - End If - End If - - If DtVentasNC Is Nothing Then InicializaDTVentasNC() - Dim Drt = DtVentasNC.NewRow - Drt("CveVenta") = ObjFactura.CveVenta - Drt("Importe") = 0 - Drt("FolioFiscal") = ObjFactura.FolioFiscal - DtVentasNC.Rows.Add(Drt) - DtVentasNC.AcceptChanges() - - End Sub - - - Private Function RegistrarNCAmortizacion(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean - Dim ProcesoCorrecto As Boolean = True - - 'Generamos el nuevo folio - Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) - - If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then - Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue.ToEntero)) - If DT.Rows.Count > 0 Then - factura.Folio = DT.Rows(0)("FActual").ToString.ToEntero - Else - ProcesoCorrecto = False - End If - DT.Dispose() - End If - - '** genero los datos de la NC - Dim tmpcon As DataTable = TmpDT.Clone - tmpcon.Clear() - - Dim drpss As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlNCPSAnt.SelectedValue.ToEntero).FiltroPrimero("") - - If drpss IsNot Nothing Then - Dim ii As Integer = 1 - Dim CveVentaP As Integer = 0 - For Each gvrt As GridViewRow In GVAnticipos.Rows - If gvrt.FCCheckBox(String.Format("Chk{0}", gvrt.RowIndex)).Checked Then - Dim CveSub As Integer = TmpDT.FiltroPrimeroValor("CveSubProyecto").ToEntero - Dim dr As DataRow = tmpcon.NewRow - Dim Cantidad As Decimal = 1 - Dim PU As Decimal = gvrt.FCTextBox(String.Format("TxtAnticipo{0}", gvrt.RowIndex)).Text.ToDecimal - Dim TotalCalculableImpuestos As Decimal = (Cantidad * (PU)) - dr("CvePS") = drpss("CvePS") - dr("PS") = drpss("PS") - dr("OBS") = drpss("PS") - dr("PU") = PU - dr("Cantidad") = Cantidad - dr("CveUM") = drpss("CveUnidadMedida") - dr("SATClaveProdServ") = "84111506" - dr("SATClaveUM") = "ACT" - dr("Consec") = ii - - If drpss("IVA").ToString = "-1" Then - dr("PorcentajeIVA") = PorcentajeIVA ' GlobalDTSubProyectos(-1,cves DrPS("IVA") - Else - dr("PorcentajeIVA") = drpss("IVA") - End If - - dr("IVA") = dr("PorcentajeIVA") - dr("ImporteIVA") = Math.Round(dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) - dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) - dr("PorcentajeRetIVA") = ClienteRetIVA - dr("PorcentajeRetISR") = ClienteRetISR - If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then - dr("PorcentajeIEPS") = drpss("IEPSPorcentaje") - dr("ImporteIEPS") = Math.Round(drpss("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - Else - dr("PorcentajeIEPS") = 0 ' DrPS("IEPSPorcentaje") - dr("ImporteIEPS") = 0 'Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - End If - - dr("IEPS") = dr("ImporteIEPS") - dr("Descuento") = Math.Round(0, NumeroDecimales) - dr("TipoDescuento") = HdnTipoDescuento.Value - dr("Total") = (Cantidad * PU) - dr("CveClasificacion") = drpss("CveClasificacion") - dr("CveSubProyecto") = CveSub - dr("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) - CveVentaP = gvrt.DataKey("CveVenta").ToEntero - tmpcon.Rows.Add(dr) - ii += 1 - End If - - Next - - '**** impuestos locales - - factura.DtDetalle = tmpcon - Dim TotalSubTotal As Decimal = tmpcon.SUM("TotalImporte").ToDecimal - Dim TotalDescuentos As Decimal = tmpcon.SUM("Descuento").ToDecimal - - Dim TotalIVA As Decimal = tmpcon.SUM("ImporteIVA").ToDecimal - Dim TotalIEPS As Decimal = tmpcon.SUM("ImporteIEPS").ToDecimal - Dim TotalRetIVA As Decimal = tmpcon.SUM("ImporteRetIVA").ToDecimal - Dim TotalRetISR As Decimal = tmpcon.SUM("ImporteRetISR").ToDecimal - Dim Total As Decimal = 0 - Dim TotalImpuestosLocales As Decimal = 0 - Total = (TotalSubTotal - TotalDescuentos + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) - - factura.SubTotal = TotalSubTotal - factura.Descuento = 0 - factura.IVA = TotalIVA - factura.IEPS = TotalIEPS - factura.RetIVA = TotalRetIVA - factura.RetISR = TotalRetISR - factura.Total = Total - factura.CveVentaPadre = CveVentaP - - If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then - DtVentasNC.Rows(0)("Importe") = Total - End If - - ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) - - 'Registramos la venta - GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, tmpcon, -1, ObjContPaq, ObjBancos) - - ''Timbramos - 'If factura.TipoDocto.Contiene("Ing", "Egs", "Ant") Then - ' If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then - - ' Dim sw As New Diagnostics.Stopwatch - ' sw.Start() - - ' ''factura INGRESO / EGRESO - ' Dim ObjTimbrado As New Modelos.Timbrado - ' Dim FM As New Modelos.FemsaFactura - ' Dim TmpDT7Eleven As New DataTable - ' Dim TmpDTComplementosTimbrado As New DataTable - - ' 'PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) - ' '** - ' ObjTimbrado.TimbrarFactura(UsuarioActual, factura, FM, TmpDT, TmpDTImpuestos, TmpDT7Eleven, TmpDTComplementosTimbrado, Ruta, LstFordASN, TxtFordGSDB.Text) - - ' sw.Stop() - ' 'GuardaLogTimbrado(sw.ElapsedMilliseconds.ToString, UsuarioActual.Empresa.CvePAC) - - - ' End If - 'End If - - Else - ErrorList.Add("No se encontró un producto para generar la nota de crédito") - End If - - - Return ProcesoCorrecto - End Function - - - Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False) - ObjFactura = New Modelos.Factura - - ObjFactura.Version = "3.3" - ObjFactura.CveUsuario = UsuarioActual.CveUsuario - ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa - ObjFactura.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) - ObjFactura.TipoCambioDolares = TxtTipoCambioDlls.Text.Trim.ToDecimal - ObjFactura.ConvertirPesos = ChkConvertirDoctoPesos.Checked - ObjFactura.ConvertirDolares = ChkConvertirDolares.Checked - ObjFactura.CveMoneda = DdlMoneda.SelectedValue.ToEntero - ObjFactura.Moneda = DdlMoneda.SelectedItem.Text - ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") - ObjFactura.TipoDocto = If(IfNull(ViewState("CveRemision"), 0).ToString.ToEntero > 0, "Ing", DdlTipoComprobante.SelectedValue) - 'ObjFactura.RefDocto = TxtDocto.Text.Trim - ObjFactura.Folio = If(EstablecioFolio Or VistaPrevia Or (CveVenta > 0 And (NuevaFactura.Contiene(0, 2))), TxtFolio.Text.Trim.ToEntero, -1) - 'ObjFactura.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1) - ObjFactura.Serie = If(VistaPrevia, "VistaPrevia", LblSerie.Text) - ObjFactura.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) - ObjFactura.CvePrePoliza = -1 - ObjFactura.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero - ObjFactura.MetodoPago = "" ' DdlMetodoPago.SelectedItem.Text - ObjFactura.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") - ObjFactura.FechaVencimiento = TxtFechaPago.Text.ToDate - - ' If ObjFactura.TipoDocto = "Cot" Then - - ObjFactura.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero - ObjFactura.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero > 0, DdlMetodoPago33.SelectedItem.Text, "") - ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") - - ObjFactura.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero - ObjFactura.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero > 0, DdlFormaPago33.SelectedItem.Text, "") - ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}") - - ObjFactura.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero - ObjFactura.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero > 0, DdlUsoCFDI.SelectedItem.Text, "") - ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") - ' End If - - ObjFactura.UsuarioCreo = LblUsuario.Text.Trim - ObjFactura.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1) - ObjFactura.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") - 'ObjFactura.NumeroCuenta = TxtNumCtaPago.Text.Trim - 'ObjFactura.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim - ObjFactura.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, If(RBLPago.SelectedValue = "1", 1, 2)) ' 0 - Contado, 1 - Credito, 2 - termianl - ObjFactura.FormaPago = 0 'DdlFormaPago.SelectedValue.ToEntero - - - 'ObjFactura.AnticipoPosicion = DdlAmortizacionConceptos.SelectedValue.ToEntero - 'ObjFactura.AnticipoEnSubTotal = If(ChkAnticipoEnSubTotal.Checked, True, False) - 'ObjFactura.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero - 'ObjFactura.CveTipoAmortizacionAnticipo = DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero - - - 'ObjFactura.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text) - 'ObjFactura.PedidoContrato = TxtPedidoContrato.Text.Trim - ObjFactura.AtnA = TxtAtencionA.Text - ObjFactura.FordGSDB = "" - - ObjFactura.NumeroContrato = NumeroContrato - ObjFactura.DescripcionContrato = DescripcionContrato - ObjFactura.NumeroDescripcionContrato = If($"{NumeroContrato} - {NumeroLicitacion}" = " - ", "", $"{NumeroContrato} {If(NumeroLicitacion = "", "", $" - Licitación: {NumeroLicitacion}")}") - ObjFactura.PedidoContrato = If(TxtPedidoContrato.Text.Trim = "", ObjFactura.NumeroDescripcionContrato, $"{TxtPedidoContrato.Text.Trim} {If(ObjFactura.NumeroDescripcionContrato = "", "", $" / {ObjFactura.NumeroDescripcionContrato}") }") - ObjFactura.OrdenCompra = TxtOrdenCompra.Text.Trim - - Select Case ObjFactura.TipoDocto - Case "Ing" - ObjFactura.TipoDocumento = "Factura" - Case "Rem" - ObjFactura.TipoDocumento = "Remision" - Case "Cot" - ObjFactura.TipoDocumento = "Cotizacion" - Case "Egs" - ObjFactura.TipoDocumento = "Nota de Crédito" - Case "Dev" - ObjFactura.TipoDocumento = "Nota de Devolución" - Case "DPe" - ObjFactura.TipoDocumento = "Devolución de pedido" - Case "PeC" - ObjFactura.TipoDocumento = "Consignación de Pedido" - Case Else - ObjFactura.TipoDocumento = "" - End Select - - ObjFactura.Fech1 = TxtFech1.Text.Trim.ToDate - ObjFactura.Fech2 = TxtFech2.Text.Trim.ToDate - ObjFactura.Fech3 = TxtFech3.Text.Trim.ToDate - ObjFactura.Alfa1 = TxtAlfa1.Text.Trim - ObjFactura.Alfa2 = TxtAlfa2.Text.Trim - ObjFactura.Alfa3 = TxtAlfa3.Text.Trim - ObjFactura.Num1 = TxtNum1.Text.Trim.ToDouble - ObjFactura.Num2 = TxtNum2.Text.Trim.ToDouble - ObjFactura.Num3 = If(ObjFactura.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) - - If divcondicionespago.Visible Then - ObjFactura.FechaPago = TxtFechaPago.Text.ToDate - Else - ObjFactura.FechaPago = Now - End If - - ObjFactura.DiasCredito = DiasCredito - ObjFactura.EsDiasCreditoFijo = EsDiasCreditoFijo - - ObjFactura.CveCorte = CveCorte - ObjFactura.CveMesa = -1 - ObjFactura.NumeroPersonas = 0 - ObjFactura.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) - - ObjFactura.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero - ObjFactura.Entrega = Entrega - ObjFactura.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate - - ObjFactura.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, If(CvePedido2 > 0, CvePedido2, CvePedido)) - If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then - ObjFactura.CveVentaPadre = DtVentasNC.Rows(0)("CveVenta").ToString.ToEntero - ObjFactura.SerieFolioPadre = DtVentasNC.Rows(0)("FolioFiscal").ToString - End If - ObjFactura.CveVendedor = DdlVendedor.SelectedValue.ToEntero - If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then - DdlVendedor.Enabled = False - End If - - ObjFactura.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate - ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero - ObjFactura.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero - ObjFactura.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero - ObjFactura.AtencionA = If(ObjFactura.TipoDocto = "Cot" Or (ObjFactura.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") - ObjFactura.MotivoDescuento = TxtMotivoDescuento.Text.Trim - ObjFactura.Observaciones = TxtObsFact.Text.Trim - ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim - ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim - ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim - ObjFactura.MonedaAbreviatura = "" - - 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS - If (ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble * ObjFactura.TipoCambio, 6) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Next - - Dim ImpuestosLocales As Double = 0 - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio).FormatoNumero - If gvr.DataKey("TipoImpuesto").ToString = "5" Then - ImpuestosLocales -= Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Else - ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - End If - - End If - Next - - ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal - ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal - ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) - ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal - ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal - ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal - ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal - ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal - - TipoCambioRemision = ObjFactura.TipoCambio - ObjFactura.TipoCambio = 1 - ObjFactura.ConvertirPesos = False - ConversionRemision = "/" - - 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES - ElseIf (ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then - - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble / ObjFactura.TipoCambioDolares, 6) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Next - - Dim ImpuestosLocales As Double = 0 - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero - ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - End If - Next - - ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal - ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal - ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) - ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal - ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal - ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal - ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal - ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal - - TipoCambioRemision = ObjFactura.TipoCambioDolares - ObjFactura.TipoCambioDolares = 1 - ObjFactura.ConvertirDolares = False - ConversionRemision = "*" - - 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS REGISTRO DIRECTO SIN VENTA - ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True) Then - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble * ObjFactura.TipoCambio, 6) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - Next - - Dim ImpuestosLocales As Double = 0 - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio).FormatoNumero - ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) - End If - Next - - ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal - ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal - ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) - ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal - ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal - ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal - ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal - ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal - - TipoCambioRemision = ObjFactura.TipoCambio - ObjFactura.TipoCambio = 1 - ObjFactura.ConvertirPesos = False - ConversionRemision = "/" - - 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES REGISTRO DIRECTO SIN VENTA - ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True) Then - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble / ObjFactura.TipoCambioDolares, 6) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - Next - - Dim ImpuestosLocales As Double = 0 - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero - ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) - End If - Next - - ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal - ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal - ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) - ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal - ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal - ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal - ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal - ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal - - TipoCambioRemision = ObjFactura.TipoCambioDolares - ObjFactura.TipoCambioDolares = 1 - ObjFactura.ConvertirDolares = False - ConversionRemision = "*" - - Else - 'Totales, Y se llena TmpDTImpuestos - ObjFactura.SubTotal = TxtSubTotal.Text.ToDecimal - ObjFactura.Descuento = LblDescuentos.Text.Trim.ToDecimal - ObjFactura.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal - ObjFactura.IVA = TxtIVA.Text.ToDecimal - ObjFactura.RetIVA = TxtRetIVA.Text.ToDecimal - ObjFactura.RetISR = TxtRetISR.Text.ToDecimal - ObjFactura.IEPS = TxtIEPS.Text.ToDecimal - ObjFactura.Total = TxtTotal.Text.ToDecimal - End If - - Dim TmpSubtotal As Decimal = TxtSubTotal.Text.ToDecimal - ObjFactura.Descuento - - Dim TmpAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal - - ObjFactura.DtDetalle = TmpDT - - If AplicaFord Then - ObjFactura.FordGSDB = TxtFordGSDB.Text - - Dim SB As New StringBuilder - For Each li As ListItem In LstFordASN.Items - SB.AppendFormat("{0}, ", li.Text) - Next - ObjFactura.FordASN = SB.ToString - End If - - If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() - - Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone() - - Dim DR As DataRow = TmpDTImpuestosVista.NewRow() - - If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = ObjFactura.SubTotal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = ObjFactura.Descuento : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = ObjFactura.Amortizacion : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - - 'If TxtIVA.Text.ToDecimal <> 0 Then - DR("ImpuestoLocal") = "IVA" : DR("Importe") = ObjFactura.IVA : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - - If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = ObjFactura.RetIVA : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = ObjFactura.RetISR : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If TxtIEPS.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IEPS" : DR("Importe") = ObjFactura.IEPS : DR("Orden") = 80 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - Dim Orden As Integer = 80 - If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then - DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - Orden = Orden + 1 - End If - End If - Next - - If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = ObjFactura.Total : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - - ObjFactura.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC") - - 'TmpDT DESGLOSE DE IMPUESTOS 3.3 - If UsuarioActual.CveEmpresa.Contiene(119) Then - If TmpDTDocumentosRelacionados IsNot Nothing Then - ObjFactura.DtDocumentosRelacionados = TmpDTDocumentosRelacionados - End If - - If TmpDTNCVinculadas IsNot Nothing Then - ObjFactura.DtNCVinculadas = TmpDTNCVinculadas - End If - End If - - CreaDTImpuestosIVAIEPS() - - For Each DrImpuestos33 As DataRow In TmpDT.Rows - Dim DrIVA As DataRow = Nothing - Dim DrIEPS As DataRow = Nothing - - Try - DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0) - Catch ex As Exception - DrIVA = Nothing - End Try - - If DrIVA IsNot Nothing Then - DrIVA("Importe") = DrIVA("Importe").ToString.ToDouble + DrImpuestos33("ImporteIVA").ToString.ToDouble - TmpDTImpuestosIVAIEPS.AcceptChanges() - Else - Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() - If DrImpuestos33("PorcentajeIVA").ToString.ToDecimal > 0 Then - DR2("Impuesto") = "IVA" : DR2("tasa") = DdlIVA.SelectedItem.ToString : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString.ToDecimal : DR2("Orden") = "1" - TmpDTImpuestosIVAIEPS.Rows.Add(DR2) - TmpDTImpuestosIVAIEPS.AcceptChanges() - End If - End If - - Try - DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString.ToDecimal * 100} %'")(0) - Catch ex As Exception - DrIEPS = Nothing - End Try - - If DrIEPS IsNot Nothing Then - DrIEPS("Importe") = DrIEPS("Importe").ToString.ToDouble + DrImpuestos33("ImporteIEPS").ToString.ToDouble - TmpDTImpuestosIVAIEPS.AcceptChanges() - Else - Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() - If DrImpuestos33("PorcentajeIEPS").ToString.ToDouble > 0 Then - DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString.ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.09", "5", "0")))) - TmpDTImpuestosIVAIEPS.Rows.Add(DR2) - TmpDTImpuestosIVAIEPS.AcceptChanges() - End If - End If - - Next - - ObjFactura.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC") - - 'otros - ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim - ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim - ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim - - ObjFactura.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero - - If ObjFactura.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then - ObjFactura.TipoCambio = 1 - ObjFactura.CveMoneda = 1 - - ObjFactura.Moneda = "Pesos" - ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") - End If - - If ObjFactura.CveMoneda <> 2 AndAlso ChkConvertirDolares.Checked Then - ObjFactura.TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal - ObjFactura.CveMoneda = 2 - - ObjFactura.Moneda = "Dólares" - ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") - End If - - 'Se agrega CveVenta -1 - For Each Row As DataRow In TmpDT.Rows - Row("CveVenta") = ObjFactura.CveVenta - Next - - 'DETALLES - ObjFactura.DtDetalle = TmpDT.Copy - ObjFactura.DtFirmas = DTmpF.Copy - - 'CLIENTE - ObjFactura.CveCliente = CveCliente - ObjFactura.SetCliente() - - 'SUCURSAL - 'ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero - ObjFactura.SetSubProyectoMatriz(Me) - ObjFactura.SetSubProyecto(Me) - ObjFactura.ClienteSucursal = New Modelos.SucursalModel - If Not CveEmpresaCRM > 0 Then - ObjFactura.ClienteSucursal.NoExt = CliNoExt - ObjFactura.ClienteSucursal.NoInt = CliNoInt - ObjFactura.ClienteSucursal.Localidad = CliLocalidad - ObjFactura.ClienteSucursal.Direccion = LblDireccion.Text - ObjFactura.ClienteSucursal.Colonia = LblColonia.Text - ObjFactura.ClienteSucursal.Municipio = LblCiudad.Text - ObjFactura.ClienteSucursal.Estado = LblEstado.Text - ObjFactura.ClienteSucursal.CP = LblCP.Text - ObjFactura.ClienteSucursal.Pais = CliPais - ObjFactura.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString - ObjFactura.ClienteSucursal.TelefonoSucursal = LblTelefono.Text - ObjFactura.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "") - ObjFactura.ClienteSucursal.ImprimeNombreSucursal = ImprimeNombreSucursal.ToString - End If - - - 'ENVIO DIRECCION - ObjFactura.EnviarA = New Modelos.EnviarAModel - If ChkDireccionEnvio.Checked Then - If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then - For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows - ObjFactura.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero - ObjFactura.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString - ObjFactura.EnviarA.EnvioNoExt = Row("EnvioNoExt").ToString - ObjFactura.EnviarA.EnvioNoInt = Row("EnvioNoInt").ToString - ObjFactura.EnviarA.EnvioColonia = Row("EnvioColonia").ToString - ObjFactura.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString - ObjFactura.EnviarA.EnvioEstado = Row("EnvioEstado").ToString - ObjFactura.EnviarA.EnvioCP = Row("EnvioCP").ToString - ObjFactura.EnviarA.EnvioTel = Row("EnvioTel").ToString - ObjFactura.EnviarA.EnvioContacto = Row("EnvioContacto").ToString - ObjFactura.EnviarA.EnvioDepartamento = Row("EnvioDepartamento").ToString - 'ObjFactura.EnviarA.EnvioPedidoContrato = Row("EnvioPedidoContrato").ToString - Next - End If - End If - - 'Amortizacion - ObjFactura.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero - If ObjFactura.CveTipoRelacion > 0 Then - Select Case ObjFactura.CveTipoRelacion - Case 7 - ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" - ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" - ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) - End Select - - End If - ObjFactura.AplicaDevolucion = Me.AplicaDevolucion - - ObjFactura.CveTipoAmortizacionAnticipo = DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero - - If ObjFactura.Timbre.Comprobante.TipoComprobante = "E" Then - If ObjFactura.TipoDocumento.Contiene("Nota de Crédito") Then - ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "01" - ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso" - End If - If ObjFactura.TipoDocumento.Contiene("Nota de Devolución") Then - ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "03" - ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso" - End If - ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) - End If - ' cuando es refacturacoin es cfdirelacionado, con relacion 04 - If ObjFactura.Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then - ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "04" - ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso" - ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) - End If - - - If ObjFactura.TipoDocto = "Egs" Then - ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero - End If - If ObjFactura.TipoDocto = "Dev" Then - ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero - End If - If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso NuevaFactura = 1 Then ' refacturación - ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero - End If - - If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso DdlTiposRelacion.SelectedValue.ToEntero > 0 Then ' refacturación - ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero - If GVAnticipos.Rows.Count > 0 Then - For Each gvr As GridViewRow In GVAnticipos.Rows - If gvr.FCCheckBox(String.Format("Chk{0}", gvr.RowIndex)).Checked AndAlso gvr.DataKey("CveConceptoContable") = "12" Then ' solo notas de crédito - If DtVentasNC Is Nothing Then InicializaDTVentasNC() - Dim Drt = DtVentasNC.NewRow - Drt("CveVenta") = gvr.DataKey("CveVenta") - Drt("Importe") = gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text - Drt("FolioFiscal") = gvr.DataKey("FolioFiscal") - DtVentasNC.Rows.Add(Drt) - End If - Next - End If - - End If - - If Not CveEmpresaCRM > 0 Then ObjFactura.Timbre = PreParaTimbre(ObjFactura) - - 'RMF. faltan impuestos locales - If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 1").Rows.Count > 0 Then - - For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 1").Rows - If DrImpuestosLocales("Importe").ToString.ToDecimal > 0 Then - Dim ret As New CFDIRetencionesLocales With {.TasaRetencion = DrImpuestosLocales("Porcentaje").ToString.ToDecimal, .ImpuestoLocalRetenido = DrImpuestosLocales("ImpuestoLocal").ToString, .Importe = DrImpuestosLocales("Importe").ToString.ToDecimal(If(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1))} - ObjFactura.Timbre.RetencionesLocales.Add(ret) - End If - Next - End If - - If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows.Count > 0 Then - - For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows - If DrImpuestosLocales("Importe").ToString.ToDecimal > 0 Then - Dim ret As New CFDITrasladosLocales With {.TasaTraslado = DrImpuestosLocales("Porcentaje").ToString.ToDecimal, .ImpuestoLocalTraslado = DrImpuestosLocales("ImpuestoLocal").ToString, .Importe = DrImpuestosLocales("Importe").ToString.ToDecimal(If(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1))} - ObjFactura.Timbre.TrasladosLocales.Add(ret) - End If - Next - End If - - 'INE COMPLEMENTO - If RblComplementos.SelectedValue.ToEntero > 0 Then - ObjFactura.CveComplementoTimbrado = RblComplementos.SelectedValue.ToEntero - Dim INE As New Modelos.ComplementoINE - Select Case RblComplementos.SelectedValue.ToEntero - Case 5 - INE.INEIdContabilidad = TxtIdConta.Text.ToEntero - INE.INETipoProceso = "Ordinario" - INE.INETipoComite = "Directivo Estatal" - INE.INEEntidad = DdlINEEntidad.SelectedValue - Case 6 - INE.INEIdContabilidad = TxtIdConta.Text.ToEntero - INE.INETipoProceso = "Ordinario" - INE.INETipoComite = "Ejecutivo Estatal" - INE.INEEntidad = DdlINEEntidad.SelectedValue - Case 7 - INE.INEIdContabilidad = TxtIdConta.Text.ToEntero - INE.INETipoProceso = "Ordinario" - INE.INETipoComite = "Ejecutivo Nacional" - Case 8 - INE.INEIdContabilidad = TxtIdConta.Text.ToEntero - INE.INETipoProceso = DdlTipoCampaña.SelectedValue - INE.INETipoComite = DdlAmbitoComplemento.SelectedValue - INE.INEEntidad = DdlINEEntidad.SelectedValue - Case Else - INE.INEIdContabilidad = 0 - INE.INETipoProceso = "" - INE.INETipoComite = "" - INE.INEEntidad = "" - End Select - ObjFactura.ComplementoINE = INE - End If - End Sub - - Private Sub CreaObjetosVentaDevolucion() - ObjFacturaDevolucion = New Modelos.Factura - - ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario - ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa - ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) - ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked - ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero - ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text - ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") - 'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim - 'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1) - ObjFacturaDevolucion.Serie = LblSerie.Text - ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) - ObjFacturaDevolucion.CvePrePoliza = -1 - ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero - ObjFacturaDevolucion.MetodoPago = "" 'DdlMetodoPago.SelectedItem.Text - ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") - ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim - ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1) - ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") - 'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim - 'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim - ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito - ObjFacturaDevolucion.FormaPago = 0 - 'ObjFacturaDevolucion.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text) - ObjFacturaDevolucion.TipoDocto = "Egs" - ObjFacturaDevolucion.Fecha = Now - - - 'VALORES DEFAULT DE NC-DEV - Dim CveUsoCFDIOld = DdlUsoCFDI.SelectedValue - Dim MetodoPago33Old = DdlMetodoPago33.SelectedValue - Dim FormaPago33Old = DdlFormaPago33.SelectedValue - - DdlUsoCFDI.SelectedValueExist("2") - DdlMetodoPago33.SelectedValueExist("1") - DdlFormaPago33.SelectedValueExist("20") - - ObjFacturaDevolucion.SerieFolioPadre = HdnFolioFiscalNC.Value.ToString - - ObjFacturaDevolucion.Version = "3.3" - ObjFacturaDevolucion.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero - ObjFacturaDevolucion.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero > 0, DdlMetodoPago33.SelectedItem.Text, "") - ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") - - ObjFacturaDevolucion.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero - ObjFacturaDevolucion.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero > 0, DdlFormaPago33.SelectedItem.Text, "") - ObjFacturaDevolucion.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}") - - ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero - ObjFacturaDevolucion.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero > 0, DdlUsoCFDI.SelectedItem.Text, "") - ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") - - DdlUsoCFDI.SelectedValueExist(CveUsoCFDIOld) - DdlMetodoPago33.SelectedValueExist(MetodoPago33Old) - DdlFormaPago33.SelectedValueExist(FormaPago33Old) - - - Select Case ObjFacturaDevolucion.TipoDocto - Case "Ing" - ObjFacturaDevolucion.TipoDocumento = "Factura" - Case "Rem" - ObjFacturaDevolucion.TipoDocumento = "Remision" - Case "Cot" - ObjFacturaDevolucion.TipoDocumento = "Cotizacion" - Case "Egs" - ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito" - Case "Dev" - ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución" - Case Else - ObjFacturaDevolucion.TipoDocumento = "" - End Select - - If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then - ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto - End If - - ObjFacturaDevolucion.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero - ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate - ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate - ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate - ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim - ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim - ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim - ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble - ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble - ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) - ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate - - ObjFacturaDevolucion.CveCorte = CveCorte - ObjFacturaDevolucion.CveMesa = -1 - ObjFacturaDevolucion.NumeroPersonas = 0 - ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) - ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "") - ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero - ObjFacturaDevolucion.Entrega = Entrega - ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate - - ObjFacturaDevolucion.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, CvePedido) - ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero - If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then - DdlVendedor.Enabled = False - End If - - ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate - 'ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero - 'ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero - ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero - ObjFacturaDevolucion.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero - ObjFacturaDevolucion.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero - ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") - ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim - ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim - ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim - ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim - ObjFacturaDevolucion.MonedaAbreviatura = "" - - 'Totales, Y se llena TmpDTImpuestos - ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal - ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal - ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal - ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal - ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal - ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal - ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal - ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal - - If TmpDTImpuestos Is Nothing Then - CreaDTImpuestos() - End If - Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone() - - Dim DR As DataRow = TmpDTImpuestosVista.NewRow() - - If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - Dim Orden As Integer = 80 - If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then - DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestosVista.Rows.Add(DR) - DR = TmpDTImpuestosVista.NewRow() - Orden = Orden + 1 - End If - End If - Next - - - If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) - - ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC") - - - CreaDTImpuestosIVAIEPS() - - For Each DrImpuestos33 As DataRow In TmpDT.Rows - Dim DrIVA As DataRow = Nothing - Dim DrIEPS As DataRow = Nothing - - Try - DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0) - Catch ex As Exception - DrIVA = Nothing - End Try - - If DrIVA IsNot Nothing Then - DrIVA("Importe") = DrIVA("Importe").ToString.ToDouble + DrImpuestos33("ImporteIVA").ToString.ToDouble - TmpDTImpuestosIVAIEPS.AcceptChanges() - Else - Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() - If DrImpuestos33("PorcentajeIVA").ToString.ToDouble >= 0 Then - DR2("Impuesto") = "IVA" : DR2("tasa") = "16 %" : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString.ToDouble : DR2("Orden") = "1" - TmpDTImpuestosIVAIEPS.Rows.Add(DR2) - TmpDTImpuestosIVAIEPS.AcceptChanges() - End If - End If - - Try - DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100} %'")(0) - Catch ex As Exception - DrIEPS = Nothing - End Try - - If DrIEPS IsNot Nothing Then - DrIEPS("Importe") = DrIEPS("Importe").ToString.ToDouble + DrImpuestos33("ImporteIEPS").ToString.ToDouble - TmpDTImpuestosIVAIEPS.AcceptChanges() - Else - Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() - If DrImpuestos33("PorcentajeIEPS").ToString.ToDouble > 0 Then - DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString.ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.09", "5", "")))) - TmpDTImpuestosIVAIEPS.Rows.Add(DR2) - TmpDTImpuestosIVAIEPS.AcceptChanges() - End If - End If - - Next - - ObjFacturaDevolucion.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC") - - 'otros - ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim - ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim - - ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero - - If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then - ObjFacturaDevolucion.TipoCambio = 1 - ObjFacturaDevolucion.CveMoneda = 1 - End If - - 'DETALLES - ObjFacturaDevolucion.DtDetalle = TmpDT - ObjFacturaDevolucion.DtFirmas = DTmpF - - 'CLIENTE - ObjFacturaDevolucion.CveCliente = CveCliente - ObjFacturaDevolucion.SetCliente() - - 'SUCURSAL - ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero - ObjFacturaDevolucion.SetSubProyectoMatriz(Me) - ObjFacturaDevolucion.SetSubProyecto(Me) - ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel - ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt - ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt - ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad - ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text - ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text - ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text - ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text - ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text - ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais - ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString - ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text - ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "") - - 'ENVIO DIRECCION - ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel - If ChkDireccionEnvio.Checked Then - If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then - For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows - ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero - ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString - ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString - ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString - ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString - ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString - Next - End If - End If - - ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) - End Sub - - Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre - Dim Timbre As New CFDITimbre - Timbre.Comprobante.TipoComprobante = If(Obj.TipoDocto.Contiene("Ing", "Ant"), "I", If(Obj.TipoDocto.Contiene("Egs", "Dev"), "E", "")) - Timbre.Comprobante.Folio = Obj.Folio.ToString - Timbre.Comprobante.Serie = Obj.Serie - Timbre.Comprobante.Fecha = Obj.Fecha - Timbre.Comprobante.FormadePago = Obj.FormaPagoSAT33 - Timbre.Comprobante.CondicionesdePago = Obj.FormaPago33 - Timbre.Comprobante.MetodoPago = Obj.ClaveMetodoPagoSAT - Timbre.Comprobante.Subtotal = Obj.SubTotal - Timbre.Comprobante.Descuentos = Obj.Descuento - Timbre.Comprobante.Moneda = Obj.MonedaSAT - Timbre.Comprobante.TipoCambio = If(Obj.CveMoneda = 1, "1", Obj.TipoCambio.ToString) - Timbre.Comprobante.Total = Obj.Total - - Try - Obj.SetSubProyecto(Me) - Timbre.Comprobante.LugarExpedicion = Obj.SubProyecto.CP - Catch ex As Exception - - End Try - - Timbre.Comprobante.Confirmacion = "" - - Timbre.Receptor.RFC = Obj.Cliente.RFC - Timbre.Receptor.Nombre = Obj.Cliente.Nombre - Timbre.Receptor.ResidenciaFiscal = "" - Timbre.Receptor.NumeroRegistroTributario = "" - Timbre.Receptor.UsoCFDI = Obj.ClaveUsoCFDI - - - If HdnTipoDescuento.Value = "3" And DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero > 0 Then - - Timbre.CFDIRelacionados.TipoRelacion = "07" - Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" - - 'If Timbre.Comprobante.TipoComprobante = "E" Then - ' If Obj.TipoDocumento.Contiene("Nota de Crédito") Then - ' Timbre.CFDIRelacionados.TipoRelacion = "01" - ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso" - ' End If - ' If Obj.TipoDocumento.Contiene("Nota de Devolución") Then - ' Timbre.CFDIRelacionados.TipoRelacion = "03" - ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso" - ' End If - ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) - 'End If - '' cuando es refacturacoin es cfdirelacionado, con relacion 04 - 'If Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then - ' Timbre.CFDIRelacionados.TipoRelacion = "04" - ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso" - ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) - 'End If - - Else - 'SI LA FACTURA VIENE DE SER CANCELADA SISTEMA CUANDO SE REFACTURO NO HAY QUE RELACIONAR - If (CveEstatusFacturaPadre > 0 AndAlso CveEstatusFacturaPadre <> 4) OrElse (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Then - If Obj.CveTipoRelacion > 0 Then - - Select Case Obj.CveTipoRelacion - Case 1 - Timbre.CFDIRelacionados.TipoRelacion = "01" - Timbre.CFDIRelacionados.TipoRelacionTexto = "01-Nota de Crédito aplicada a Ingreso" - Case 2 - Timbre.CFDIRelacionados.TipoRelacion = "02" - Timbre.CFDIRelacionados.TipoRelacionTexto = "02-Nota de débito de los documentos relacionados" - Case 3 - Timbre.CFDIRelacionados.TipoRelacion = "03" - Timbre.CFDIRelacionados.TipoRelacionTexto = "03-Devolución aplicada a Ingreso" - Case 4 - Timbre.CFDIRelacionados.TipoRelacion = "04" - Timbre.CFDIRelacionados.TipoRelacionTexto = "04-Refacturación de Ingreso" - Case 7 - Timbre.CFDIRelacionados.TipoRelacion = "07" - Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" - Case 8 - Timbre.CFDIRelacionados.TipoRelacion = "08" - Timbre.CFDIRelacionados.TipoRelacionTexto = "08-Factura generada por pagos en parcialidades " - Case 9 - Timbre.CFDIRelacionados.TipoRelacion = "09" - Timbre.CFDIRelacionados.TipoRelacionTexto = "09-Factura generada por pagos diferidos" - End Select - - If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then - For Each Dr As DataRow In DtVentasNC.Rows - Timbre.CFDIRelacionados.UUID.Add(Dr("FolioFiscal").ToString) - Next - Else - If Not String.IsNullOrEmpty(HdnFolioFiscalNC.Value.Trim()) Then - Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) - End If - End If - - End If - End If - - End If - - - - - Dim totSubTotal As Decimal = Obj.SubTotal - Dim totIVA As Decimal = Obj.IVA - Dim totRetIVA As Decimal = Obj.RetIVA - Dim totRetISR As Decimal = Obj.RetISR - Dim TasaRetIVA As Decimal = LblRetIVA.Text.ToDecimal / 100 - Dim TasaRetISR As Decimal = LblRetISR.Text.ToDecimal / 100 - Dim i As Integer = 1 - - 'detalles - Dim tPS As String = "" - - For Each drr As DataRow In Obj.DtDetalle.Rows - If drr("PS").ToString.Length = 1 Then - tPS = drr("Obs").ToString - Else - If drr("PS").ToString.Length = 0 Then - tPS = "" - Else - tPS = String.Format("{0} {1}", drr("PS"), drr("Obs")) - End If - End If - 'condicionante, especial - If UsuarioActual.CveEmpresa = 15 Then drr("UM") = "" ' les comentan que no debe de ir la etiqueta de "unidad" en el producto - - Dim concepto As New CFDIConceptos With {.Cantidad = drr("Cantidad").ToString.ToDecimal, - .Descripcion = tPS, - .ValorUnitario = drr("PU").ToString.ToDecimal, - .Importe = drr("TotalImporte").ToString.ToDecimal, - .Descuento = drr("Descuento").ToString.ToDecimal, - .Unidad = drr("UM").ToString, - .ClaveUnidad = drr("SATClaveUM").ToString, - .ClaveProdServ = drr("SATClaveProdServ").ToString, - .Noidentificacion = drr("Noidentificacion").ToString, - .CuentaPredial = drr("CuentaPredial").ToString} - 'verifica suma subtotales - If i = Obj.DtDetalle.Rows.Count AndAlso totSubTotal <> concepto.Importe Then 'proceso de ajusta de decimales - concepto.Importe = totSubTotal - End If - totSubTotal = totSubTotal - concepto.Importe - - 'siempre estaremos agregando el iva, auqnue sea en importe cero o tasa cero, para que se emita la factura - ' If drr("ImporteIVA").ToString.ToDouble > 0 Then - - 'si es ingreso amortizado por la totalidad, y arroja el valor total de cero, no debe de impuestos - If Timbre.Comprobante.Total > 0 Then - concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteIVA").ToString.ToDecimal}) - End If - - If drr("ImporteIEPS").ToString.ToDouble > 0 Then - concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIEPS").ToString.ToDecimal, .Impuesto = "003", .Importe = drr("ImporteIEPS").ToString.ToDecimal}) - End If - - If drr("ImporteRetIVA").ToString.ToDouble > 0 Then 'si hay retenciones - concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetIVA, .Impuesto = "002", .Importe = drr("ImporteRetIVA").ToString.ToDecimal}) - End If - - If drr("ImporteRetISR").ToString.ToDouble > 0 Then 'retención de ISR - concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetISR, .Impuesto = "001", .Importe = drr("ImporteRetISR").ToString.ToDecimal}) - End If - - Timbre.Conceptos.Add(concepto) - i += 1 - Next - - Dim AplicaComercioExteriorSubProyecto As Boolean = If(GlobalDTSubProyectos(-1, Obj.CveSubProyecto)(0)("AplicaComercioExterior").ToString = "True", True, False) - Timbre.Complementos.ComercioExterior11.AplicaComercioExteriorSubProyecto = AplicaComercioExteriorSubProyecto - If Obj.Cliente.AplicaComercioExterior And AplicaComercioExteriorSubProyecto Then - 'DATOS GENERALES - Timbre.Complementos.ComercioExterior11.TipoOperacion = GlobalDTTipoOperacion().FiltraParametros($"CveTipoOperacion={CveTipoOperacion}")(0)("ClaveSATTipoOperacion").ToString - Timbre.Complementos.ComercioExterior11.ClavedePedimento = GlobalDTClavePedimento().FiltraParametros($"CvePedimento={CvePedimento}")(0)("ClaveSATPedimento").ToString - Timbre.Complementos.ComercioExterior11.CertificadoOrigen = "0" - Timbre.Complementos.ComercioExterior11.Incoterm = GlobalDTIncoterm.FiltroPrimeroValor("ClaveSATIncoterm", $"CveIncoterm={DdlIncoterm.SelectedValue}") - Timbre.Complementos.ComercioExterior11.Subdivision = "0" - Timbre.Complementos.ComercioExterior11.TipoCambioUSD = If(Obj.CveMoneda = 1, 1, Obj.TipoCambio.ToString.ToDecimal) - Timbre.Complementos.ComercioExterior11.MotivoTraslado = GlobalDTSATMotivoTraslado.FiltroPrimeroValor("ClaveSATMotivoTraslado", $"CveMotivoTraslado={DdlSATMotivoTraslado.SelectedValue}") - - - 'EMISOR - Dim Dr As DataRow - Dr = Nothing - If GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero).Rows.Count > 0 Then - Dr = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero)(0) - End If - Timbre.Complementos.ComercioExterior11.Emisor.CURP = UsuarioActual.Empresa.CURP - Timbre.Complementos.ComercioExterior11.Emisor.Calle = Dr("Calle").ToString - Timbre.Complementos.ComercioExterior11.Emisor.NumeroExterior = Dr("NoExt").ToString - Timbre.Complementos.ComercioExterior11.Emisor.NumeroInterior = Dr("NoInt").ToString - Timbre.Complementos.ComercioExterior11.Emisor.Colonia = Dr("ClaveSATColonia").ToString - Timbre.Complementos.ComercioExterior11.Emisor.Localidad = "" - Timbre.Complementos.ComercioExterior11.Emisor.Municipio = Dr("ClaveSATMunicipio").ToString - Timbre.Complementos.ComercioExterior11.Emisor.Estado = Dr("ClaveSATEstado").ToString - Timbre.Complementos.ComercioExterior11.Emisor.Pais = Dr("ClaveSATPais").ToString - Timbre.Complementos.ComercioExterior11.Emisor.CP = Dr("ClaveSATCP").ToString - - 'RECEPTOR - Timbre.Complementos.ComercioExterior11.Receptor.NumRegIdTrib = "" ' EN LA VERSION 3.3 NO DEBE DE REGISTRARSE ESTE VALOR - Timbre.Complementos.ComercioExterior11.Receptor.Calle = Obj.Cliente.Direccion - Timbre.Complementos.ComercioExterior11.Receptor.NumeroExterior = Obj.Cliente.NoExt - Timbre.Complementos.ComercioExterior11.Receptor.NumeroInterior = Obj.Cliente.NoInt - Timbre.Complementos.ComercioExterior11.Receptor.Colonia = Obj.Cliente.ClaveSATColonia - Timbre.Complementos.ComercioExterior11.Receptor.Localidad = "" - Timbre.Complementos.ComercioExterior11.Receptor.Referencia = Obj.Cliente.ReferenciaFiscal - Timbre.Complementos.ComercioExterior11.Receptor.Municipio = Obj.Cliente.Ciudad - Timbre.Complementos.ComercioExterior11.Receptor.CP = Obj.Cliente.CP - Timbre.Complementos.ComercioExterior11.Receptor.Estado = Obj.Cliente.ClaveSATEstado - Timbre.Complementos.ComercioExterior11.Receptor.Pais = Obj.Cliente.ClaveSATPais - Timbre.Receptor.ResidenciaFiscal = Obj.Cliente.ClaveSATPais - Timbre.Receptor.NumeroRegistroTributario = Obj.Cliente.NumRegIdTrib - - Dim ComExtPais, ComExtEstado, ComExtMunicipio, ComExtColonia, ComExtCalle, ComExtNumero, ComExtCP As String - ComExtColonia = "" : ComExtMunicipio = "" - ComExtPais = GlobalDTPais.FiltroPrimeroValor("ClaveSATPais", $"CvePais={DdlComExtPais.SelectedValue}") - ComExtCalle = TxtComExtCalle.Text.Trim - ComExtNumero = TxtComExtNumero.Text.Trim - ComExtCP = TxtComExtCP.Text.Trim - - If ComExtPais = "MEX" Then - ComExtEstado = GlobalDTEstado(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}") - ComExtMunicipio = GlobalDTMunicipio(ComExtEstado).FiltroPrimeroValor("ClaveSATMunicipio", $"CveMunicipio={DdlComExtMunicipio.SelectedValue}") - ComExtColonia = GlobalDTColonia(ComExtMunicipio).FiltroPrimeroValor("ClaveSATColonia", $"CveColonia={DdlComExtColonia.SelectedValue}") - Else - If ComExtPais.Contiene("USA", "CAN") Then - ComExtEstado = GlobalDTEstado(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}") - Else - ComExtEstado = TxtComExtEstado.Text.Trim - End If - ComExtMunicipio = TxtComExtMunicipio.Text.Trim - ComExtColonia = TxtComExtColonia.Text.Trim - End If - - 'DESTINATARIO - Timbre.Complementos.ComercioExterior11.Destinatario.Nombre = TxtDestinatarioNombre.Text.Trim - Timbre.Complementos.ComercioExterior11.Destinatario.Calle = ComExtCalle - Timbre.Complementos.ComercioExterior11.Destinatario.NumeroExterior = ComExtNumero - Timbre.Complementos.ComercioExterior11.Destinatario.NumeroInterior = "" - Timbre.Complementos.ComercioExterior11.Destinatario.Colonia = ComExtColonia - Timbre.Complementos.ComercioExterior11.Destinatario.Localidad = "" - Timbre.Complementos.ComercioExterior11.Destinatario.Referencia = Obj.Cliente.ReferenciaFiscal - Timbre.Complementos.ComercioExterior11.Destinatario.Municipio = ComExtMunicipio - Timbre.Complementos.ComercioExterior11.Destinatario.CP = ComExtCP - Timbre.Complementos.ComercioExterior11.Destinatario.Estado = ComExtEstado - Timbre.Complementos.ComercioExterior11.Destinatario.Pais = ComExtPais - Timbre.Complementos.ComercioExterior11.Destinatario.NumRegIdTrib = TxtNumRegIdTrib.Text.Trim - - - 'MERCANCIAS - For Each Gvr As GridViewRow In GvComercioExterior.Rows - Dim mercancia As New CFDIComercioExterior11Mercancias With {.CantidadAduana = Gvr.FCTextBox("TxtCantidad").Text.ToDecimal, - .FraccionArancelaria = Gvr.DataKey("ClaveSATFraccionArancelaria").ToString, - .UnidadAduana = Gvr.DataKey("ClaveSATUnidadAduana").ToString, - .ValorDolares = Math.Round(Gvr.FCTextBox("TxtCantidad").Text.ToDecimal * Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, 2), - .ValorUnitarioAduana = Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, - .NoIdentificacion = Gvr.DataKey("Codigo")} - If Gvr.FCTextBox("TxtMarca").Text <> "" Then - mercancia.DescripcionesEspecificas.Marca = Gvr.FCTextBox("TxtMarca").Text - End If - - Timbre.Complementos.ComercioExterior11.Mercancias.Add(mercancia) - i += 1 - Next - End If - - Return Timbre - End Function - - Private Sub PrepararTimbrado(ByRef FM As Modelos.FemsaFactura, ByRef TmpDT7Eleven As DataTable, ByRef TmpDTComplementosTimbrado As DataTable) - FM.AplicaFEMSA = AplicaFEMSA - FM.FEMSA_NumSociedad = TxtFEMSA_NumSociedad.Text.Trim - FM.FEMSA_NumProveedor = TxtFEMSA_NumProveedor.Text.Trim - FM.FEMSA_Mail = TxtFEMSA_Mail.Text.Trim - FM.FEMSA_Version = TxtFEMSA_Version.Text.ToEntero - FM.FEMSA_NumPedido = TxtFEMSA_NumPedido.Text.Trim.ToLong - FM.FEMSA_NumEntrada = TxtFEMSA_NumEntrada.Text.Trim - FM.FEMSA_NumRemision = TxtFEMSA_NumRemision.Text.Trim - FM.FEMSA_NumSocio = TxtFEMSA_NumSocio.Text.Trim - FM.FEMSA_CentroCosto = TxtFEMSA_CentroCosto.Text.Trim - FM.FEMSA_IPeriodoLiquidacion = TxtFEMSA_IPeriodoLiquidacion.Text.Trim - FM.FEMSA_FPeriodoLiquidacion = TxtFEMSA_FPeriodoLiquidacion.Text.Trim - FM.FEMSA_CodRetencion1 = TxtFEMSA_CodRetencion1.Text.Trim - FM.FEMSA_CodRetencion2 = TxtFEMSA_CodRetencion2.Text.Trim - - TmpDT7Eleven.Columns.Add("sevenElevenNumProveedor") - TmpDT7Eleven.Columns.Add("sevenElevenFolio") - TmpDT7Eleven.Columns.Add("sevenElevenTienda") - TmpDT7Eleven.Columns.Add("sevenElevenFecha") - - Dim Row As DataRow = TmpDT7Eleven.NewRow - Row("sevenElevenNumProveedor") = Txt7ElevenNumProveedor.Text.Trim() - Row("sevenElevenFolio") = Txt7ElevenFolio.Text.Trim() - Row("sevenElevenTienda") = Txt7ElevenTienda.Text.Trim() - Row("sevenElevenFecha") = Txt7ElevenFecha.Text.Trim() - - TmpDT7Eleven.Rows.Add(Row) - - TmpDTComplementosTimbrado.Columns.Add("CveComplemento") - TmpDTComplementosTimbrado.Columns.Add("IdContabilidad") - TmpDTComplementosTimbrado.Columns.Add("TipoProceso") - TmpDTComplementosTimbrado.Columns.Add("TipoAmbito") - TmpDTComplementosTimbrado.Columns.Add("Entidad") - - Dim Row2 As DataRow = TmpDTComplementosTimbrado.NewRow - If RblComplementos.SelectedValue.ToEntero > 0 Then - - Select Case RblComplementos.SelectedValue.ToEntero - Case 5 - Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero - Row2("IdContabilidad") = TxtIdConta.Text.ToEntero - Row2("TipoProceso") = "Ordinario" - Row2("TipoAmbito") = "Directivo Estatal" - Row2("Entidad") = DdlINEEntidad.SelectedValue - Case 6 - Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero - Row2("IdContabilidad") = TxtIdConta.Text.ToEntero - Row2("TipoProceso") = "Ordinario" - Row2("TipoAmbito") = "Ejecutivo Estatal" - Row2("Entidad") = DdlINEEntidad.SelectedValue - Case 7 - Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero - Row2("IdContabilidad") = TxtIdConta.Text.ToEntero - Row2("TipoProceso") = "Ordinario" - Row2("TipoAmbito") = "Ejecutivo Nacional" - Row2("Entidad") = "" - Case 8 - Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero - Row2("IdContabilidad") = TxtIdConta.Text.ToEntero - Row2("TipoProceso") = DdlTipoCampaña.SelectedValue - Row2("TipoAmbito") = DdlAmbitoComplemento.SelectedValue - Row2("Entidad") = DdlINEEntidad.SelectedValue - End Select - Else - Row2("CveComplemento") = "" - Row2("IdContabilidad") = "" - Row2("TipoProceso") = "" - Row2("TipoAmbito") = "" - Row2("Entidad") = "" - End If - - - TmpDTComplementosTimbrado.Rows.Add(Row2) + End If + End If + + ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then + GeneraPDFCBB(ObjFactura.Fecha, Nothing, ObjFactura.SerieFolio, False) + End If + End If + + End If + + 'VERIFICAR 100% AVANCE A IMPORTE Y CANTIDAD + If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso CveContrato > 0 Then + If ObjContr.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then + + If ObjContr.DtResultados.Rows.Count > 0 Then + ' si es flexible que notifique el monto maximo, si no lo es que notifique el porcentaje alcanzado... flexible = 2, no flexible = 1 + Dim PorcentajeAvance As Double = ObjContr.DtResultados.Rows(0)("ContratoAvance").ToString.ToDouble + + If ObjContr.DtResultados.Rows(0)("ModalidadDetalle").ToString() = "1" Then + + If PorcentajeAvance >= 100 Then + EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString()) + End If + Else + Dim MontoMaximo As Double = ObjContr.DtResultados.Rows(0)("ImporteMax").ToString.ToDouble + + If PorcentajeAvance >= 100 And MontoMaximo > 0 Then + EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString(), MontoMaximo) + End If + End If + + End If + End If + End If + + 'MENSAJE PRINCIPAL + MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} se generó correctamente.

    ", ObjFactura.TipoDocumento, ObjFactura.SerieFolio)) + + + ' DESCARGA XML - SI SE TIMBRA MANDA CORREO CON FACTURA + If SeTimbro Then + Dim ArchivoXML = String.Format("{0}/XML/{1}/{2}.xml", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) + If File.Exists(ArchivoXML) Then + MensajeAlert.AppendFormat("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", ObjFactura.SerieFolio, ObjFactura.TipoDocto))) + End If + GeneraPDFFactura(ChkEnviarFactura.Checked) 'MANDA CORREO + + End If + + 'DESCARGA PDF + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant", "Egs", "Dev", "Pd2") Then + 'If Not ImprimeAlert Then + + Dim ArchivoIngPyMe As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.mrt", UsuarioActual.Empresa.Ruta)) + Dim ArchivoIng As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) + Dim ArchivoRem As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) + Dim ArchivoEgs As New System.IO.FileInfo(String.Format("{0}Formatos/NotaCredito.rdlc", UsuarioActual.Empresa.Ruta)) + + If ArchivoIng.Exists Or ArchivoRem.Exists Or ArchivoIngPyMe.Exists Or ArchivoEgs.Exists Then + MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))) + Else + MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") + End If + End If + + 'ERROR DE NO TIMBRADO + If Not SeTimbro And (DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue = "Ant") Then + MensajeAlert.AppendFormat("La factura no se pudo timbrar. Por favor intentelo de nuevo a traves del boton Emitir.") + End If + + 'ERROR DE NO TIMBRADO NC + If Not IsNothing(ObjNC) AndAlso ObjNC.Count > 0 AndAlso Not SeTimbroNC Then + MensajeAlert.AppendFormat("
    La NC #{0} no se pudo timbrar. Por favor intentelo de nuevo a traves del boton Emitir.", CType(ObjNC(0), Modelos.Factura).SerieFolio) + End If + + 'NOTIFICACION DE SMS + Select Case EstatusSMS + Case 1 + MensajeAlert.AppendFormat("
    Notificación SMS: enviado con éxito al cliente al celular: {0}", ObjFactura.Cliente.CobranzaTelefono) + Case 2 + MensajeAlert.AppendFormat("
    Notificación SMS: sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.") + Case 3 + MensajeAlert.AppendFormat("
    Notificación SMS: sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.") + End Select + + + 'AUTO DESCARGAR PDF + If UsuarioActual.CveEmpresa.Contiene(72, 1) Then + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") Then + RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))}'", "Imprimir") + End If + End If + + 'DESCARGAR PDF DE CICOVISA + 'If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 Then + ' If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then + ' MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=CIC&CVEVENTA={0}", CveVenta))) + ' End If + 'End If + + If DdlTipoComprobante.SelectedValue = "Cot" Then + If Not CveEmpresaCRM > 0 Then + If CveVenta > 0 Then MensajeAlert = New StringBuilder + Dim ArchivoCotizacion As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.rdlc", UsuarioActual.Empresa.Ruta)) + + If ArchivoCotizacion.Exists Then + MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta))) + Else + MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") + End If + + GeneraPDFCotizacion(ChkEnviarFactura.Checked) ' MANDA CORREO + End If + ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then + If UsuarioActual.CveEmpresa.Contiene(81, 109) Then + EnviaPDFRemision(ChkEnviarFactura.Checked) + End If + End If + + 'ENVIA CORREO CON DETALLE DEL CONTRATO + If DdlTipoComprobante.SelectedValue.Contiene("DPe", "Ped") Then + If Not String.IsNullOrEmpty(CorreoNotificacionPedDev) Then + EnviarCorreoDevPed() + End If + End If + + 'MOVIMIENTO DE ALMACEN + If ObjFactura.Inv_CveMovimiento > 0 Then + MensajeAlert.AppendFormat("

    Movimiento de Almacén
    ", ObjFactura.Inv_CveMovimiento) + End If + + If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then + MensajeAlert.AppendFormat("

    Se generó una Nota de crédito Folio: {0} amortizando el anticipo
    ", ObjFacturaDevolucion.Folio) + End If + + 'MUESTA ALERT OK + ' si es elrol 1165-Ventas,EMp:80, o la empresa 119, recarga ventas, para seguir registrando-. + Dim Liga = If(UsuarioActual.CveRol = 1165 Or UsuarioActual.CveEmpresa = 119, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", If(CveEmpresaCRM > 0, $"document.location.href=""/CRM/EmpresaCRM.aspx?CveEmpresaCRM={CveEmpresaCRM}"";", $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}&Opt=3"";")) + Alert(MensajeAlert.ToString, TipoMensaje.MsgInformacion, Liga) + + + 'LIMPIA CONDICIONES DE PAGO - CONTADO + RBLPago.SelectedValue = "1" + LimpiaEscondeContado() + BtnEmitirImprimir.Visible = False + ObjFactura = Nothing + + Else + ObjVentas.RollBack() + If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() + + For Each ErrorItem In ErrorList + Alert(ErrorItem, TipoMensaje.MsgAdvertencia) + Next + + 'MUESTA ALERT ERROR + Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) + End If + + ObjVentas.Dispose() + ObjConta.Dispose() + ObjInventario.Dispose() + ObjCGame.Dispose() + ObjContr.Dispose() + ObjDocCliente.Dispose() + 'ObjFolios.Dispose() + ErrorList = Nothing + MensajeAlert = Nothing + If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() + TmpDT = TmpDTError.Copy + + Else + ObjVentas.RollBack() + If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() + + For Each ErrorItem In ErrorList + Alert(ErrorItem, TipoMensaje.MsgAdvertencia) + Next + + 'MUESTA ALERT ERROR + Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) + ObjVentas.Dispose() + ObjConta.Dispose() + ObjInventario.Dispose() + ObjCGame.Dispose() + ObjContr.Dispose() + ObjDocCliente.Dispose() + 'ObjFolios.Dispose() + ErrorList = Nothing + MensajeAlert = Nothing + If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() + TmpDT = TmpDTError.Copy + + End If + End If + End If End Sub -#End Region -#Region "Ordenes de Compra Sin Facurar" - Private Sub CargaOCs() - Dim ObjVentas As New ClsVentas - - If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 1) Then - If DdlContratosOC.SelectedValue.ToEntero > 0 Then - DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"CveContratoVinculado = '{DdlContratosOC.SelectedValue}'") - Else - DTOrdenesCompra = ObjVentas.DtResultados - End If - GVOC.DataSource = DTOrdenesCompra - End If - - If DTOrdenesCompra IsNot Nothing AndAlso Not DTOrdenesCompra.Columns.Contains("Aplicado") Then - DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean")) - End If - - ObjVentas.Dispose() - GVOC.DataBind() - UPOCFactura.Update() - End Sub - Private Sub CargaOCsxProducto() - Dim ObjVentas As New ClsVentas - - If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 2) Then - If DdlContratosOC.SelectedValue.ToEntero > 0 Then - DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0 AND CveContratoVinculado = '{DdlContratosOC.SelectedValue}'") - Else - DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0") - End If - GvOCPS.DataSource = DTOrdenesCompra - End If - - If Not DTOrdenesCompra.Columns.Contains("Aplicado") Then - DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean")) - End If - - ObjVentas.Dispose() - GvOCPS.DataBind() - UPOCFactura.Update() - End Sub - Private Sub ChkOCProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkPSOC.CheckedChanged - CargaOCSinFacturar() - End Sub - Private Sub VerificaOrdenesCompra(ByRef dt As DataTable) - If ChkPSOC.Checked Then - For Each Gvr As GridViewRow In GvOCPS.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - If Gvr.FCCheckBox("Chk").Checked Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveOrdenCompraDetalle As Integer = Gvr.DataKey("CveOrdenCompraDetalle").ToEntero - Dim Drs As DataRow() = dt.Select($"CveOrdenCompraDetalle = {CveOrdenCompraDetalle}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - End If - Next - - Else - For Each Gvr As GridViewRow In GVOC.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - If Gvr.FCCheckBox("Chk").Checked Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveOrdenCompra As Integer = Gvr.DataKey("CveOrdenCompra").ToEntero - Dim Drs As DataRow() = dt.Select($"CveOrdenCompra = {CveOrdenCompra}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - End If - Next - End If - End Sub - Protected Sub BtnCargarOC_Click(sender As Object, e As EventArgs) Handles BtnCargarOC.Click - If GVOC.Rows.Count > 0 Or GvOCPS.Rows.Count > 0 Then - 'Checa las facturas selecionadas - VerificaOrdenesCompra(DTOrdenesCompra) - - Dim dtSeleccionadas As DataTable = DTOrdenesCompra.FiltraParametros("Aplicado = True") - If GvPS.Rows.Count > 0 Then - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = TxtIVA.Text - End If - - If dtSeleccionadas.Rows.Count > 0 Then - - If TieneContrato Then - ContratoDetalles.Visible = True - DivEstimaciones.Visible = False - - DdlContratosModal.DataSource = DtContratos - DdlContratosModal.DataBind() - DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) - - DdlContratosModal.SelectedValue = DdlContratosOC.SelectedValue - DdlContrato.SelectedValue = DdlContratosOC.SelectedValue - UPEstimaciones.Update() - End If - - IsTotalxConcepto = True - Dim ObjClientes As New ClsClientes - Dim sb As New StringBuilder - If ChkPSOC.Checked Then - For Each row As DataRow In dtSeleccionadas.Rows - sb.Append($"{row("CveOrdenCompraDetalle").ToString},") - Next - Else - For Each row As DataRow In dtSeleccionadas.Rows - sb.Append($"{row("CveOrdenCompra").ToString},") - Next - End If - - sb.Remove(sb.Length - 1, 1) - If ObjClientes.GetVentasOCTotales(CveCliente, sb.ToString, If(ChkPSOC.Checked, 2, 1)) Then - DTOrdenesCompraPS = ObjClientes.DtResultados - - Dim tCantidad As Decimal = 0 - For Each Dr As DataRow In DTOrdenesCompraPS.Select() - tCantidad = If(ChkPSOC.Checked, GvOCPS.Rows(IndiceGVDataKey(GvOCPS, "CveOrdenCompraDetalle", $"{Dr("CveOrdenCompraDetalle")}")).FCTextBox("TxtCantidadOC").Text, Dr("Cantidad")).ToString.ToDecimal - AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, - Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PUCon").ToString.ToDecimal, 0, - Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, - CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, - EntregaDirecta:=1) - Next - - - CveContrato = DTOrdenesCompraPS.FiltroPrimeroValor("CveContrato").ToString.ToEntero - If CveContrato > 0 Then ContratoOC = True - - CalculaTotalesVenta() - GvPS.DataSource = TmpDT - GvPS.DataBind() - End If - - ObjClientes.Dispose() - BtnEmitirImprimir.Text = "Facturar" - DdlTipoComprobante.SelectedValue = "Ing" - DdlTipoComprobante.Enabled = False - - Tab.ActiveTab = TabGenerales - TabGenerales.Enabled = True - Updatetabs.Update() - - - 'Else - ' If TieneContrato Then - ' GvContratoDetalles.DataSource = Nothing - ' GvContratoDetalles.DataBind() - ' UPEstimaciones.Update() - ' End If - End If - - End If - - ChkPSOC.Checked = False - UPOCFactura.Update() - UpFacturar.Update() - UpPS.Update() - UpParametros.Update() - RegistraScript("$('#DivOrdenesCompra').modal('hide');") - End Sub - Private Sub DdlContratosOC_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosOC.SelectedIndexChanged - CargaOCSinFacturar() - End Sub - Private Sub CargaOCSinFacturar() - If ChkPSOC.Checked Then - GvOCPS.Visible = True - GVOC.Visible = False - DivFiltroOCPS.Visible = True - GVOC.DataSource = Nothing - GVOC.DataBind() - CargaOCsxProducto() - Else - GvOCPS.Visible = False - GVOC.Visible = True - DivFiltroOCPS.Visible = False - GvOCPS.DataSource = Nothing - GvOCPS.DataBind() - CargaOCs() - End If - End Sub - Private Sub LnkOCs_Click(sender As Object, e As EventArgs) Handles LnkOCs.Click - Dim ObjContratos As New ClsContratos - - If Not TieneContrato Then - If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then - If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then - DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'") - DdlContratosOC.DataSource = DtContratos - DdlContratosOC.DataBind() - - If Not TieneContrato Then - DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) - End If - End If - End If - - GvContratoDetalles.DataSource = Nothing - GvContratoDetalles.DataBind() - UpContratos.Update() - - DivEstimaciones.Visible = True - ContratoDetalles.Visible = False - UPEstimaciones.Update() - - Tab.ActiveTab = TabGenerales - TabGenerales.Enabled = True - Updatetabs.Update() - End If - - ObjContratos.Dispose() - - ChkPSOC.Checked = False - UPOCFactura.Update() - - CargaOCSinFacturar() - RegistraScript("$('#DivOrdenesCompra').modal('show');") - End Sub - Private Sub BtnConsultarOC_Click(sender As Object, e As EventArgs) Handles BtnConsultarOC.Click - CargaOCSinFacturar() + + Private Sub CreaObjetosVentaAmortizacion(ObjVentas As ClsVentas, FolioFiscalRelacionado As String, CveAnticipoPadre As Integer, Optional CveVentasPadre As Integer = -1) + ObjFacturaDevolucion = New Modelos.Factura + + ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario + ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero + + If CveVentasPadre > 0 Then + ObjFacturaDevolucion.CveVentaPadre = CveVentasPadre + ObjFacturaDevolucion.CveVentaRelacion = CveVentasPadre + Else + ObjFacturaDevolucion.CveVentaPadre = ObjVentas.CveVenta + ObjFacturaDevolucion.CveVentaRelacion = ObjVentas.CveVenta + End If + + + ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa + ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) + ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked + ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero + ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text + ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") + 'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim + 'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1) + ObjFacturaDevolucion.Serie = LblSerie.Text + ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) + ObjFacturaDevolucion.CvePrePoliza = -1 + ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero + ObjFacturaDevolucion.MetodoPago = "" + ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") + ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim + ' ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1) + ' ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") + 'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim + 'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim + ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito + ObjFacturaDevolucion.FormaPago = 0 + + ObjFacturaDevolucion.TipoDocto = "Egs" + ObjFacturaDevolucion.Fecha = Now + + ObjFacturaDevolucion.Version = "3.3" + ObjFacturaDevolucion.CveMetodoPago33 = 1 + ObjFacturaDevolucion.MetodoPago33 = "Pago en una sola exhibición" + ObjFacturaDevolucion.ClaveMetodoPagoSAT = "PUE" + + ObjFacturaDevolucion.CveFormaPago33 = 21 + ObjFacturaDevolucion.FormaPago33 = "Aplicación de anticipos" + ObjFacturaDevolucion.FormaPagoSAT33 = "30" + + ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero + ObjFacturaDevolucion.UsoCFDI = DdlUsoCFDI.SelectedItem.Text + ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") + + ObjFacturaDevolucion.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero + ObjFacturaDevolucion.TipoRelacion = "07" + Dim Fol As New List(Of String) + Fol.Add(FolioFiscalRelacionado) + ObjFacturaDevolucion.UUIDRelacionados = Fol + + Select Case ObjFacturaDevolucion.TipoDocto + Case "Ing" + ObjFacturaDevolucion.TipoDocumento = "Factura" + Case "REM" + ObjFacturaDevolucion.TipoDocumento = "Remision" + Case "Cot" + ObjFacturaDevolucion.TipoDocumento = "Cotizacion" + Case "Egs" + ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito" + Case "Dev" + ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución" + Case Else + ObjFacturaDevolucion.TipoDocumento = "" + End Select + + If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then + ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto + End If + + ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate + ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate + ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate + ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim + ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim + ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim + ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble + ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble + ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) + ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate + + ObjFacturaDevolucion.CveCorte = CveCorte + ObjFacturaDevolucion.CveMesa = -1 + ObjFacturaDevolucion.NumeroPersonas = 0 + ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) + ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "") + ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero + ObjFacturaDevolucion.Entrega = Entrega + ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate + + ObjFacturaDevolucion.CveVentaPadre = CveAnticipoPadre + ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero + If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then + DdlVendedor.Enabled = False + End If + + ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate + ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero + ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero + + ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") + ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim + ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim + ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim + ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim + ObjFacturaDevolucion.MonedaAbreviatura = "" + + 'Totales, Y se llena TmpDTImpuestos + ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal + ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal + ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal + ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal + ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal + ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal + ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal + ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal + + 'ObjFactura.BZDescripcion = TxtBZDescripcion.Text.Trim + 'ObjFactura.BZNombreCorto = TxtBZNombreCorto.Text.Trim + 'ObjFactura.BZTotalLetra = TxtBZTotalLetra.Text.Trim + + If TmpDTImpuestos Is Nothing Then + CreaDTImpuestos() + Else + TmpDTImpuestos.Clear() + End If + + Dim DR As DataRow = TmpDTImpuestos.NewRow() + + If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + + If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + + + 'If DdlFormatoImpresion.SelectedValue.ToEntero = 3 Or DdlFormatoImpresion.SelectedValue.ToEntero = 4 Then + ' DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (TxtSubTotal.Text.ToDecimal + TxtIVA.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal) : DR("Orden") = 55 : TmpDTImpuestos.Rows.Add(DR) + + ' DR = TmpDTImpuestos.NewRow() + 'End If + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + Dim Orden As Integer = 80 + If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then + DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestos.Rows.Add(DR) + DR = TmpDTImpuestos.NewRow() + Orden = Orden + 1 + End If + End If + Next + + + If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) + + ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC") + + + 'otros + ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim + ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim + + + ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero + + If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then + ObjFacturaDevolucion.TipoCambio = 1 + ObjFacturaDevolucion.CveMoneda = 1 + End If + + 'DETALLES + ObjFacturaDevolucion.DtDetalle = TmpDT + ObjFacturaDevolucion.DtFirmas = DTmpF + + 'CLIENTE + ObjFacturaDevolucion.CveCliente = CveCliente + ObjFacturaDevolucion.SetCliente() + + ''SUCURSAL + 'ObjFacturaDevolucion.CveSucursal = DdlSucursal.SelectedValue.ToEntero + 'ObjFacturaDevolucion.SetSucursalMatriz(Me) + 'ObjFacturaDevolucion.SetSucursal(Me) + + ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel + ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt + ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt + ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad + ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text + ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text + ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text + ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text + ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text + ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais + ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString + ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text + ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "") + + + + ObjFacturaDevolucion.SetSubProyectoMatriz(Me) + ObjFacturaDevolucion.SetSubProyecto(Me) + + 'ENVIO DIRECCION + ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel + If ChkDireccionEnvio.Checked Then + If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then + For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows + ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero + ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString + ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString + ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString + ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString + ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString + Next + End If + End If + + If DtVentasNC Is Nothing Then InicializaDTVentasNC() + Dim Drt = DtVentasNC.NewRow + Drt("CveVenta") = ObjFactura.CveVenta + Drt("Importe") = 0 + Drt("FolioFiscal") = ObjFactura.FolioFiscal + DtVentasNC.Rows.Add(Drt) + DtVentasNC.AcceptChanges() + End Sub -#End Region + + + Private Function RegistrarNCAmortizacion(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean + Dim ProcesoCorrecto As Boolean = True + + 'Generamos el nuevo folio + Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) + + If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then + Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue.ToEntero)) + If DT.Rows.Count > 0 Then + factura.Folio = DT.Rows(0)("FActual").ToString.ToEntero + Else + ProcesoCorrecto = False + End If + DT.Dispose() + End If + + '** genero los datos de la NC + Dim tmpcon As DataTable = TmpDT.Clone + tmpcon.Clear() + + Dim drpss As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlNCPSAnt.SelectedValue.ToEntero).FiltroPrimero("") + + If drpss IsNot Nothing Then + Dim ii As Integer = 1 + Dim CveVentaP As Integer = 0 + For Each gvrt As GridViewRow In GVAnticipos.Rows + If gvrt.FCCheckBox(String.Format("Chk{0}", gvrt.RowIndex)).Checked Then + Dim CveSub As Integer = TmpDT.FiltroPrimeroValor("CveSubProyecto").ToEntero + Dim dr As DataRow = tmpcon.NewRow + Dim Cantidad As Decimal = 1 + Dim PU As Decimal = gvrt.FCTextBox(String.Format("TxtAnticipo{0}", gvrt.RowIndex)).Text.ToDecimal + Dim TotalCalculableImpuestos As Decimal = (Cantidad * (PU)) + dr("CvePS") = drpss("CvePS") + dr("PS") = drpss("PS") + dr("OBS") = drpss("PS") + dr("PU") = PU + dr("Cantidad") = Cantidad + dr("CveUM") = drpss("CveUnidadMedida") + dr("SATClaveProdServ") = "84111506" + dr("SATClaveUM") = "ACT" + dr("Consec") = ii + + If drpss("IVA").ToString = "-1" Then + dr("PorcentajeIVA") = PorcentajeIVA ' GlobalDTSubProyectos(-1,cves DrPS("IVA") + Else + dr("PorcentajeIVA") = drpss("IVA") + End If + + dr("IVA") = dr("PorcentajeIVA") + dr("ImporteIVA") = Math.Round(dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) + dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) + dr("PorcentajeRetIVA") = ClienteRetIVA + dr("PorcentajeRetISR") = ClienteRetISR + If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then + dr("PorcentajeIEPS") = drpss("IEPSPorcentaje") + dr("ImporteIEPS") = Math.Round(drpss("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + Else + dr("PorcentajeIEPS") = 0 ' DrPS("IEPSPorcentaje") + dr("ImporteIEPS") = 0 'Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + End If + + dr("IEPS") = dr("ImporteIEPS") + dr("Descuento") = Math.Round(0, NumeroDecimales) + dr("TipoDescuento") = HdnTipoDescuento.Value + dr("Total") = (Cantidad * PU) + dr("CveClasificacion") = drpss("CveClasificacion") + dr("CveSubProyecto") = CveSub + dr("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) + CveVentaP = gvrt.DataKey("CveVenta").ToEntero + tmpcon.Rows.Add(dr) + ii += 1 + End If + + Next + + '**** impuestos locales + + factura.DtDetalle = tmpcon + Dim TotalSubTotal As Decimal = tmpcon.SUM("TotalImporte").ToDecimal + Dim TotalDescuentos As Decimal = tmpcon.SUM("Descuento").ToDecimal + + Dim TotalIVA As Decimal = tmpcon.SUM("ImporteIVA").ToDecimal + Dim TotalIEPS As Decimal = tmpcon.SUM("ImporteIEPS").ToDecimal + Dim TotalRetIVA As Decimal = tmpcon.SUM("ImporteRetIVA").ToDecimal + Dim TotalRetISR As Decimal = tmpcon.SUM("ImporteRetISR").ToDecimal + Dim Total As Decimal = 0 + Dim TotalImpuestosLocales As Decimal = 0 + Total = (TotalSubTotal - TotalDescuentos + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) + + factura.SubTotal = TotalSubTotal + factura.Descuento = 0 + factura.IVA = TotalIVA + factura.IEPS = TotalIEPS + factura.RetIVA = TotalRetIVA + factura.RetISR = TotalRetISR + factura.Total = Total + factura.CveVentaPadre = CveVentaP + + If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then + DtVentasNC.Rows(0)("Importe") = Total + End If + + ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) + + 'Registramos la venta + GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, tmpcon, -1, ObjContPaq, ObjBancos) + + ''Timbramos + 'If factura.TipoDocto.Contiene("Ing", "Egs", "Ant") Then + ' If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then + + ' Dim sw As New Diagnostics.Stopwatch + ' sw.Start() + + ' ''factura INGRESO / EGRESO + ' Dim ObjTimbrado As New Modelos.Timbrado + ' Dim FM As New Modelos.FemsaFactura + ' Dim TmpDT7Eleven As New DataTable + ' Dim TmpDTComplementosTimbrado As New DataTable + + ' 'PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) + ' '** + ' ObjTimbrado.TimbrarFactura(UsuarioActual, factura, FM, TmpDT, TmpDTImpuestos, TmpDT7Eleven, TmpDTComplementosTimbrado, Ruta, LstFordASN, TxtFordGSDB.Text) + + ' sw.Stop() + ' 'GuardaLogTimbrado(sw.ElapsedMilliseconds.ToString, UsuarioActual.Empresa.CvePAC) + + + ' End If + 'End If + + Else + ErrorList.Add("No se encontró un producto para generar la nota de crédito") + End If + + + Return ProcesoCorrecto + End Function + + + Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False) + ObjFactura = New Modelos.Factura + + ObjFactura.Version = "3.3" + ObjFactura.CveUsuario = UsuarioActual.CveUsuario + ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa + ObjFactura.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) + ObjFactura.TipoCambioDolares = TxtTipoCambioDlls.Text.Trim.ToDecimal + ObjFactura.ConvertirPesos = ChkConvertirDoctoPesos.Checked + ObjFactura.ConvertirDolares = ChkConvertirDolares.Checked + ObjFactura.CveMoneda = DdlMoneda.SelectedValue.ToEntero + ObjFactura.Moneda = DdlMoneda.SelectedItem.Text + ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") + ObjFactura.TipoDocto = If(IfNull(ViewState("CveRemision"), 0).ToString.ToEntero > 0, "Ing", DdlTipoComprobante.SelectedValue) + 'ObjFactura.RefDocto = TxtDocto.Text.Trim + ObjFactura.Folio = If(EstablecioFolio Or VistaPrevia Or (CveVenta > 0 And (NuevaFactura.Contiene(0, 2))), TxtFolio.Text.Trim.ToEntero, -1) + 'ObjFactura.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1) + ObjFactura.Serie = If(VistaPrevia, "VistaPrevia", LblSerie.Text) + ObjFactura.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) + ObjFactura.CvePrePoliza = -1 + ObjFactura.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero + ObjFactura.MetodoPago = "" ' DdlMetodoPago.SelectedItem.Text + ObjFactura.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") + ObjFactura.FechaVencimiento = TxtFechaPago.Text.ToDate + + ' If ObjFactura.TipoDocto = "Cot" Then + + ObjFactura.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero + ObjFactura.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero > 0, DdlMetodoPago33.SelectedItem.Text, "") + ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") + + ObjFactura.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero + ObjFactura.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero > 0, DdlFormaPago33.SelectedItem.Text, "") + ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}") + + ObjFactura.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero + ObjFactura.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero > 0, DdlUsoCFDI.SelectedItem.Text, "") + ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") + ' End If + + ObjFactura.UsuarioCreo = LblUsuario.Text.Trim + ObjFactura.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1) + ObjFactura.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") + 'ObjFactura.NumeroCuenta = TxtNumCtaPago.Text.Trim + 'ObjFactura.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim + ObjFactura.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, If(RBLPago.SelectedValue = "1", 1, 2)) ' 0 - Contado, 1 - Credito, 2 - termianl + ObjFactura.FormaPago = 0 'DdlFormaPago.SelectedValue.ToEntero + + + 'ObjFactura.AnticipoPosicion = DdlAmortizacionConceptos.SelectedValue.ToEntero + 'ObjFactura.AnticipoEnSubTotal = If(ChkAnticipoEnSubTotal.Checked, True, False) + 'ObjFactura.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero + 'ObjFactura.CveTipoAmortizacionAnticipo = DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero + + + 'ObjFactura.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text) + 'ObjFactura.PedidoContrato = TxtPedidoContrato.Text.Trim + ObjFactura.AtnA = TxtAtencionA.Text + ObjFactura.FordGSDB = "" + + ObjFactura.NumeroContrato = NumeroContrato + ObjFactura.DescripcionContrato = DescripcionContrato + ObjFactura.NumeroDescripcionContrato = If($"{NumeroContrato} - {NumeroLicitacion}" = " - ", "", $"{NumeroContrato} {If(NumeroLicitacion = "", "", $" - Licitación: {NumeroLicitacion}")}") + ObjFactura.PedidoContrato = If(TxtPedidoContrato.Text.Trim = "", ObjFactura.NumeroDescripcionContrato, $"{TxtPedidoContrato.Text.Trim} {If(ObjFactura.NumeroDescripcionContrato = "", "", $" / {ObjFactura.NumeroDescripcionContrato}") }") + ObjFactura.OrdenCompra = TxtOrdenCompra.Text.Trim + + Select Case ObjFactura.TipoDocto + Case "Ing" + ObjFactura.TipoDocumento = "Factura" + Case "Rem" + ObjFactura.TipoDocumento = "Remision" + Case "Cot" + ObjFactura.TipoDocumento = "Cotizacion" + Case "Egs" + ObjFactura.TipoDocumento = "Nota de Crédito" + Case "Dev" + ObjFactura.TipoDocumento = "Nota de Devolución" + Case "DPe" + ObjFactura.TipoDocumento = "Devolución de pedido" + Case "PeC" + ObjFactura.TipoDocumento = "Consignación de Pedido" + Case Else + ObjFactura.TipoDocumento = "" + End Select + + ObjFactura.Fech1 = TxtFech1.Text.Trim.ToDate + ObjFactura.Fech2 = TxtFech2.Text.Trim.ToDate + ObjFactura.Fech3 = TxtFech3.Text.Trim.ToDate + ObjFactura.Alfa1 = TxtAlfa1.Text.Trim + ObjFactura.Alfa2 = TxtAlfa2.Text.Trim + ObjFactura.Alfa3 = TxtAlfa3.Text.Trim + ObjFactura.Num1 = TxtNum1.Text.Trim.ToDouble + ObjFactura.Num2 = TxtNum2.Text.Trim.ToDouble + ObjFactura.Num3 = If(ObjFactura.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) + + If divcondicionespago.Visible Then + ObjFactura.FechaPago = TxtFechaPago.Text.ToDate + Else + ObjFactura.FechaPago = Now + End If + + ObjFactura.DiasCredito = DiasCredito + ObjFactura.EsDiasCreditoFijo = EsDiasCreditoFijo + + ObjFactura.CveCorte = CveCorte + ObjFactura.CveMesa = -1 + ObjFactura.NumeroPersonas = 0 + ObjFactura.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) + + ObjFactura.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero + ObjFactura.Entrega = Entrega + ObjFactura.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate + + ObjFactura.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, If(CvePedido2 > 0, CvePedido2, CvePedido)) + If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then + ObjFactura.CveVentaPadre = DtVentasNC.Rows(0)("CveVenta").ToString.ToEntero + ObjFactura.SerieFolioPadre = DtVentasNC.Rows(0)("FolioFiscal").ToString + End If + ObjFactura.CveVendedor = DdlVendedor.SelectedValue.ToEntero + If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then + DdlVendedor.Enabled = False + End If + + ObjFactura.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate + ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero + ObjFactura.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero + ObjFactura.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero + ObjFactura.AtencionA = If(ObjFactura.TipoDocto = "Cot" Or (ObjFactura.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") + ObjFactura.MotivoDescuento = TxtMotivoDescuento.Text.Trim + ObjFactura.Observaciones = TxtObsFact.Text.Trim + ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim + ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim + ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim + ObjFactura.MonedaAbreviatura = "" + + 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS + If (ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble * ObjFactura.TipoCambio, 6) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Next + + Dim ImpuestosLocales As Double = 0 + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio).FormatoNumero + If gvr.DataKey("TipoImpuesto").ToString = "5" Then + ImpuestosLocales -= Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Else + ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + End If + + End If + Next + + ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal + ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal + ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) + ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal + ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal + ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal + ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal + ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal + + TipoCambioRemision = ObjFactura.TipoCambio + ObjFactura.TipoCambio = 1 + ObjFactura.ConvertirPesos = False + ConversionRemision = "/" + + 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES + ElseIf (ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then + + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble / ObjFactura.TipoCambioDolares, 6) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Next + + Dim ImpuestosLocales As Double = 0 + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero + ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + End If + Next + + ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal + ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal + ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) + ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal + ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal + ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal + ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal + ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal + + TipoCambioRemision = ObjFactura.TipoCambioDolares + ObjFactura.TipoCambioDolares = 1 + ObjFactura.ConvertirDolares = False + ConversionRemision = "*" + + 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS REGISTRO DIRECTO SIN VENTA + ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True) Then + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble * ObjFactura.TipoCambio, 6) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + Next + + Dim ImpuestosLocales As Double = 0 + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio).FormatoNumero + ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) + End If + Next + + ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal + ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal + ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) + ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal + ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal + ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal + ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal + ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal + + TipoCambioRemision = ObjFactura.TipoCambio + ObjFactura.TipoCambio = 1 + ObjFactura.ConvertirPesos = False + ConversionRemision = "/" + + 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES REGISTRO DIRECTO SIN VENTA + ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True) Then + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble / ObjFactura.TipoCambioDolares, 6) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + Next + + Dim ImpuestosLocales As Double = 0 + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero + ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) + End If + Next + + ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal + ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal + ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) + ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal + ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal + ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal + ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal + ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal + + TipoCambioRemision = ObjFactura.TipoCambioDolares + ObjFactura.TipoCambioDolares = 1 + ObjFactura.ConvertirDolares = False + ConversionRemision = "*" + + Else + 'Totales, Y se llena TmpDTImpuestos + ObjFactura.SubTotal = TxtSubTotal.Text.ToDecimal + ObjFactura.Descuento = LblDescuentos.Text.Trim.ToDecimal + ObjFactura.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal + ObjFactura.IVA = TxtIVA.Text.ToDecimal + ObjFactura.RetIVA = TxtRetIVA.Text.ToDecimal + ObjFactura.RetISR = TxtRetISR.Text.ToDecimal + ObjFactura.IEPS = TxtIEPS.Text.ToDecimal + ObjFactura.Total = TxtTotal.Text.ToDecimal + End If + + Dim TmpSubtotal As Decimal = TxtSubTotal.Text.ToDecimal - ObjFactura.Descuento + + Dim TmpAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal + + ObjFactura.DtDetalle = TmpDT + + If AplicaFord Then + ObjFactura.FordGSDB = TxtFordGSDB.Text + + Dim SB As New StringBuilder + For Each li As ListItem In LstFordASN.Items + SB.AppendFormat("{0}, ", li.Text) + Next + ObjFactura.FordASN = SB.ToString + End If + + If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() + + Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone() + + Dim DR As DataRow = TmpDTImpuestosVista.NewRow() + + If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = ObjFactura.SubTotal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = ObjFactura.Descuento : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = ObjFactura.Amortizacion : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + + 'If TxtIVA.Text.ToDecimal <> 0 Then + DR("ImpuestoLocal") = "IVA" : DR("Importe") = ObjFactura.IVA : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + + If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = ObjFactura.RetIVA : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = ObjFactura.RetISR : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If TxtIEPS.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IEPS" : DR("Importe") = ObjFactura.IEPS : DR("Orden") = 80 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + Dim Orden As Integer = 80 + If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then + DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + Orden = Orden + 1 + End If + End If + Next + + If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = ObjFactura.Total : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + + ObjFactura.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC") + + 'TmpDT DESGLOSE DE IMPUESTOS 3.3 + If UsuarioActual.CveEmpresa.Contiene(119) Then + If TmpDTDocumentosRelacionados IsNot Nothing Then + ObjFactura.DtDocumentosRelacionados = TmpDTDocumentosRelacionados + End If + + If TmpDTNCVinculadas IsNot Nothing Then + ObjFactura.DtNCVinculadas = TmpDTNCVinculadas + End If + End If + + CreaDTImpuestosIVAIEPS() + + For Each DrImpuestos33 As DataRow In TmpDT.Rows + Dim DrIVA As DataRow = Nothing + Dim DrIEPS As DataRow = Nothing + + Try + DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0) + Catch ex As Exception + DrIVA = Nothing + End Try + + If DrIVA IsNot Nothing Then + DrIVA("Importe") = DrIVA("Importe").ToString.ToDouble + DrImpuestos33("ImporteIVA").ToString.ToDouble + TmpDTImpuestosIVAIEPS.AcceptChanges() + Else + Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() + If DrImpuestos33("PorcentajeIVA").ToString.ToDecimal > 0 Then + DR2("Impuesto") = "IVA" : DR2("tasa") = DdlIVA.SelectedItem.ToString : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString.ToDecimal : DR2("Orden") = "1" + TmpDTImpuestosIVAIEPS.Rows.Add(DR2) + TmpDTImpuestosIVAIEPS.AcceptChanges() + End If + End If + + Try + DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString.ToDecimal * 100} %'")(0) + Catch ex As Exception + DrIEPS = Nothing + End Try + + If DrIEPS IsNot Nothing Then + DrIEPS("Importe") = DrIEPS("Importe").ToString.ToDouble + DrImpuestos33("ImporteIEPS").ToString.ToDouble + TmpDTImpuestosIVAIEPS.AcceptChanges() + Else + Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() + If DrImpuestos33("PorcentajeIEPS").ToString.ToDouble > 0 Then + DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString.ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.09", "5", "0")))) + TmpDTImpuestosIVAIEPS.Rows.Add(DR2) + TmpDTImpuestosIVAIEPS.AcceptChanges() + End If + End If + + Next + + ObjFactura.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC") + + 'otros + ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim + ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim + ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim + + ObjFactura.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero + + If ObjFactura.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then + ObjFactura.TipoCambio = 1 + ObjFactura.CveMoneda = 1 + + ObjFactura.Moneda = "Pesos" + ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") + End If + + If ObjFactura.CveMoneda <> 2 AndAlso ChkConvertirDolares.Checked Then + ObjFactura.TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal + ObjFactura.CveMoneda = 2 + + ObjFactura.Moneda = "Dólares" + ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") + End If + + 'Se agrega CveVenta -1 + For Each Row As DataRow In TmpDT.Rows + Row("CveVenta") = ObjFactura.CveVenta + Next + + 'DETALLES + ObjFactura.DtDetalle = TmpDT.Copy + ObjFactura.DtFirmas = DTmpF.Copy + + 'CLIENTE + ObjFactura.CveCliente = CveCliente + ObjFactura.SetCliente() + + 'SUCURSAL + 'ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero + ObjFactura.SetSubProyectoMatriz(Me) + ObjFactura.SetSubProyecto(Me) + ObjFactura.ClienteSucursal = New Modelos.SucursalModel + If Not CveEmpresaCRM > 0 Then + ObjFactura.ClienteSucursal.NoExt = CliNoExt + ObjFactura.ClienteSucursal.NoInt = CliNoInt + ObjFactura.ClienteSucursal.Localidad = CliLocalidad + ObjFactura.ClienteSucursal.Direccion = LblDireccion.Text + ObjFactura.ClienteSucursal.Colonia = LblColonia.Text + ObjFactura.ClienteSucursal.Municipio = LblCiudad.Text + ObjFactura.ClienteSucursal.Estado = LblEstado.Text + ObjFactura.ClienteSucursal.CP = LblCP.Text + ObjFactura.ClienteSucursal.Pais = CliPais + ObjFactura.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString + ObjFactura.ClienteSucursal.TelefonoSucursal = LblTelefono.Text + ObjFactura.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "") + ObjFactura.ClienteSucursal.ImprimeNombreSucursal = ImprimeNombreSucursal.ToString + End If + + + 'ENVIO DIRECCION + ObjFactura.EnviarA = New Modelos.EnviarAModel + If ChkDireccionEnvio.Checked Then + If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then + For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows + ObjFactura.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero + ObjFactura.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString + ObjFactura.EnviarA.EnvioNoExt = Row("EnvioNoExt").ToString + ObjFactura.EnviarA.EnvioNoInt = Row("EnvioNoInt").ToString + ObjFactura.EnviarA.EnvioColonia = Row("EnvioColonia").ToString + ObjFactura.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString + ObjFactura.EnviarA.EnvioEstado = Row("EnvioEstado").ToString + ObjFactura.EnviarA.EnvioCP = Row("EnvioCP").ToString + ObjFactura.EnviarA.EnvioTel = Row("EnvioTel").ToString + ObjFactura.EnviarA.EnvioContacto = Row("EnvioContacto").ToString + ObjFactura.EnviarA.EnvioDepartamento = Row("EnvioDepartamento").ToString + 'ObjFactura.EnviarA.EnvioPedidoContrato = Row("EnvioPedidoContrato").ToString + Next + End If + End If + + 'Amortizacion + ObjFactura.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero + If ObjFactura.CveTipoRelacion > 0 Then + Select Case ObjFactura.CveTipoRelacion + Case 7 + ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" + ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" + ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) + End Select + + End If + ObjFactura.AplicaDevolucion = Me.AplicaDevolucion + + ObjFactura.CveTipoAmortizacionAnticipo = DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero + + If ObjFactura.Timbre.Comprobante.TipoComprobante = "E" Then + If ObjFactura.TipoDocumento.Contiene("Nota de Crédito") Then + ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "01" + ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso" + End If + If ObjFactura.TipoDocumento.Contiene("Nota de Devolución") Then + ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "03" + ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso" + End If + ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) + End If + ' cuando es refacturacoin es cfdirelacionado, con relacion 04 + If ObjFactura.Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then + ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "04" + ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso" + ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) + End If + + + If ObjFactura.TipoDocto = "Egs" Then + ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero + End If + If ObjFactura.TipoDocto = "Dev" Then + ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero + End If + If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso NuevaFactura = 1 Then ' refacturación + ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero + End If + + If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso DdlTiposRelacion.SelectedValue.ToEntero > 0 Then ' refacturación + ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero + If GVAnticipos.Rows.Count > 0 Then + For Each gvr As GridViewRow In GVAnticipos.Rows + If gvr.FCCheckBox(String.Format("Chk{0}", gvr.RowIndex)).Checked AndAlso gvr.DataKey("CveConceptoContable") = "12" Then ' solo notas de crédito + If DtVentasNC Is Nothing Then InicializaDTVentasNC() + Dim Drt = DtVentasNC.NewRow + Drt("CveVenta") = gvr.DataKey("CveVenta") + Drt("Importe") = gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text + Drt("FolioFiscal") = gvr.DataKey("FolioFiscal") + DtVentasNC.Rows.Add(Drt) + End If + Next + End If + + End If + + If Not CveEmpresaCRM > 0 Then ObjFactura.Timbre = PreParaTimbre(ObjFactura) + + 'RMF. faltan impuestos locales + If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 1").Rows.Count > 0 Then + + For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 1").Rows + If DrImpuestosLocales("Importe").ToString.ToDecimal > 0 Then + Dim ret As New CFDIRetencionesLocales With {.TasaRetencion = DrImpuestosLocales("Porcentaje").ToString.ToDecimal, .ImpuestoLocalRetenido = DrImpuestosLocales("ImpuestoLocal").ToString, .Importe = DrImpuestosLocales("Importe").ToString.ToDecimal(If(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1))} + ObjFactura.Timbre.RetencionesLocales.Add(ret) + End If + Next + End If + + If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows.Count > 0 Then + + For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows + If DrImpuestosLocales("Importe").ToString.ToDecimal > 0 Then + Dim ret As New CFDITrasladosLocales With {.TasaTraslado = DrImpuestosLocales("Porcentaje").ToString.ToDecimal, .ImpuestoLocalTraslado = DrImpuestosLocales("ImpuestoLocal").ToString, .Importe = DrImpuestosLocales("Importe").ToString.ToDecimal(If(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1))} + ObjFactura.Timbre.TrasladosLocales.Add(ret) + End If + Next + End If + + 'INE COMPLEMENTO + If RblComplementos.SelectedValue.ToEntero > 0 Then + ObjFactura.CveComplementoTimbrado = RblComplementos.SelectedValue.ToEntero + Dim INE As New Modelos.ComplementoINE + Select Case RblComplementos.SelectedValue.ToEntero + Case 5 + INE.INEIdContabilidad = TxtIdConta.Text.ToEntero + INE.INETipoProceso = "Ordinario" + INE.INETipoComite = "Directivo Estatal" + INE.INEEntidad = DdlINEEntidad.SelectedValue + Case 6 + INE.INEIdContabilidad = TxtIdConta.Text.ToEntero + INE.INETipoProceso = "Ordinario" + INE.INETipoComite = "Ejecutivo Estatal" + INE.INEEntidad = DdlINEEntidad.SelectedValue + Case 7 + INE.INEIdContabilidad = TxtIdConta.Text.ToEntero + INE.INETipoProceso = "Ordinario" + INE.INETipoComite = "Ejecutivo Nacional" + Case 8 + INE.INEIdContabilidad = TxtIdConta.Text.ToEntero + INE.INETipoProceso = DdlTipoCampaña.SelectedValue + INE.INETipoComite = DdlAmbitoComplemento.SelectedValue + INE.INEEntidad = DdlINEEntidad.SelectedValue + Case Else + INE.INEIdContabilidad = 0 + INE.INETipoProceso = "" + INE.INETipoComite = "" + INE.INEEntidad = "" + End Select + ObjFactura.ComplementoINE = INE + End If + End Sub + + Private Sub CreaObjetosVentaDevolucion() + ObjFacturaDevolucion = New Modelos.Factura + + ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario + ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa + ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) + ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked + ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero + ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text + ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") + 'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim + 'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1) + ObjFacturaDevolucion.Serie = LblSerie.Text + ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) + ObjFacturaDevolucion.CvePrePoliza = -1 + ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero + ObjFacturaDevolucion.MetodoPago = "" 'DdlMetodoPago.SelectedItem.Text + ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") + ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim + ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1) + ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") + 'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim + 'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim + ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito + ObjFacturaDevolucion.FormaPago = 0 + 'ObjFacturaDevolucion.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text) + ObjFacturaDevolucion.TipoDocto = "Egs" + ObjFacturaDevolucion.Fecha = Now + + + 'VALORES DEFAULT DE NC-DEV + Dim CveUsoCFDIOld = DdlUsoCFDI.SelectedValue + Dim MetodoPago33Old = DdlMetodoPago33.SelectedValue + Dim FormaPago33Old = DdlFormaPago33.SelectedValue + + DdlUsoCFDI.SelectedValueExist("2") + DdlMetodoPago33.SelectedValueExist("1") + DdlFormaPago33.SelectedValueExist("20") + + ObjFacturaDevolucion.SerieFolioPadre = HdnFolioFiscalNC.Value.ToString + + ObjFacturaDevolucion.Version = "3.3" + ObjFacturaDevolucion.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero + ObjFacturaDevolucion.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero > 0, DdlMetodoPago33.SelectedItem.Text, "") + ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") + + ObjFacturaDevolucion.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero + ObjFacturaDevolucion.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero > 0, DdlFormaPago33.SelectedItem.Text, "") + ObjFacturaDevolucion.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}") + + ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero + ObjFacturaDevolucion.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero > 0, DdlUsoCFDI.SelectedItem.Text, "") + ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") + + DdlUsoCFDI.SelectedValueExist(CveUsoCFDIOld) + DdlMetodoPago33.SelectedValueExist(MetodoPago33Old) + DdlFormaPago33.SelectedValueExist(FormaPago33Old) + + + Select Case ObjFacturaDevolucion.TipoDocto + Case "Ing" + ObjFacturaDevolucion.TipoDocumento = "Factura" + Case "Rem" + ObjFacturaDevolucion.TipoDocumento = "Remision" + Case "Cot" + ObjFacturaDevolucion.TipoDocumento = "Cotizacion" + Case "Egs" + ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito" + Case "Dev" + ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución" + Case Else + ObjFacturaDevolucion.TipoDocumento = "" + End Select + + If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then + ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto + End If + + ObjFacturaDevolucion.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero + ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate + ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate + ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate + ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim + ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim + ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim + ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble + ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble + ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) + ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate + + ObjFacturaDevolucion.CveCorte = CveCorte + ObjFacturaDevolucion.CveMesa = -1 + ObjFacturaDevolucion.NumeroPersonas = 0 + ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) + ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "") + ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero + ObjFacturaDevolucion.Entrega = Entrega + ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate + + ObjFacturaDevolucion.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, CvePedido) + ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero + If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then + DdlVendedor.Enabled = False + End If + + ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate + 'ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero + 'ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero + ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero + ObjFacturaDevolucion.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero + ObjFacturaDevolucion.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero + ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") + ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim + ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim + ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim + ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim + ObjFacturaDevolucion.MonedaAbreviatura = "" + + 'Totales, Y se llena TmpDTImpuestos + ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal + ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal + ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal + ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal + ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal + ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal + ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal + ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal + + If TmpDTImpuestos Is Nothing Then + CreaDTImpuestos() + End If + Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone() + + Dim DR As DataRow = TmpDTImpuestosVista.NewRow() + + If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + Dim Orden As Integer = 80 + If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then + DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestosVista.Rows.Add(DR) + DR = TmpDTImpuestosVista.NewRow() + Orden = Orden + 1 + End If + End If + Next + + + If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) + + ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC") + + + CreaDTImpuestosIVAIEPS() + + For Each DrImpuestos33 As DataRow In TmpDT.Rows + Dim DrIVA As DataRow = Nothing + Dim DrIEPS As DataRow = Nothing + + Try + DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0) + Catch ex As Exception + DrIVA = Nothing + End Try + + If DrIVA IsNot Nothing Then + DrIVA("Importe") = DrIVA("Importe").ToString.ToDouble + DrImpuestos33("ImporteIVA").ToString.ToDouble + TmpDTImpuestosIVAIEPS.AcceptChanges() + Else + Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() + If DrImpuestos33("PorcentajeIVA").ToString.ToDouble >= 0 Then + DR2("Impuesto") = "IVA" : DR2("tasa") = "16 %" : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString.ToDouble : DR2("Orden") = "1" + TmpDTImpuestosIVAIEPS.Rows.Add(DR2) + TmpDTImpuestosIVAIEPS.AcceptChanges() + End If + End If + + Try + DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100} %'")(0) + Catch ex As Exception + DrIEPS = Nothing + End Try + + If DrIEPS IsNot Nothing Then + DrIEPS("Importe") = DrIEPS("Importe").ToString.ToDouble + DrImpuestos33("ImporteIEPS").ToString.ToDouble + TmpDTImpuestosIVAIEPS.AcceptChanges() + Else + Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() + If DrImpuestos33("PorcentajeIEPS").ToString.ToDouble > 0 Then + DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString.ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.09", "5", "")))) + TmpDTImpuestosIVAIEPS.Rows.Add(DR2) + TmpDTImpuestosIVAIEPS.AcceptChanges() + End If + End If + + Next + + ObjFacturaDevolucion.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC") + + 'otros + ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim + ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim + + ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero + + If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then + ObjFacturaDevolucion.TipoCambio = 1 + ObjFacturaDevolucion.CveMoneda = 1 + End If + + 'DETALLES + ObjFacturaDevolucion.DtDetalle = TmpDT + ObjFacturaDevolucion.DtFirmas = DTmpF + + 'CLIENTE + ObjFacturaDevolucion.CveCliente = CveCliente + ObjFacturaDevolucion.SetCliente() + + 'SUCURSAL + ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero + ObjFacturaDevolucion.SetSubProyectoMatriz(Me) + ObjFacturaDevolucion.SetSubProyecto(Me) + ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel + ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt + ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt + ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad + ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text + ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text + ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text + ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text + ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text + ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais + ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString + ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text + ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "") + + 'ENVIO DIRECCION + ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel + If ChkDireccionEnvio.Checked Then + If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then + For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows + ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero + ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString + ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString + ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString + ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString + ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString + Next + End If + End If + + ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) + End Sub + + Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre + Dim Timbre As New CFDITimbre + Timbre.Comprobante.TipoComprobante = If(Obj.TipoDocto.Contiene("Ing", "Ant"), "I", If(Obj.TipoDocto.Contiene("Egs", "Dev"), "E", "")) + Timbre.Comprobante.Folio = Obj.Folio.ToString + Timbre.Comprobante.Serie = Obj.Serie + Timbre.Comprobante.Fecha = Obj.Fecha + Timbre.Comprobante.FormadePago = Obj.FormaPagoSAT33 + Timbre.Comprobante.CondicionesdePago = Obj.FormaPago33 + Timbre.Comprobante.MetodoPago = Obj.ClaveMetodoPagoSAT + Timbre.Comprobante.Subtotal = Obj.SubTotal + Timbre.Comprobante.Descuentos = Obj.Descuento + Timbre.Comprobante.Moneda = Obj.MonedaSAT + Timbre.Comprobante.TipoCambio = If(Obj.CveMoneda = 1, "1", Obj.TipoCambio.ToString) + Timbre.Comprobante.Total = Obj.Total + + Try + Obj.SetSubProyecto(Me) + Timbre.Comprobante.LugarExpedicion = Obj.SubProyecto.CP + Catch ex As Exception + + End Try + + Timbre.Comprobante.Confirmacion = "" + + Timbre.Receptor.RFC = Obj.Cliente.RFC + Timbre.Receptor.Nombre = Obj.Cliente.Nombre + Timbre.Receptor.ResidenciaFiscal = "" + Timbre.Receptor.NumeroRegistroTributario = "" + Timbre.Receptor.UsoCFDI = Obj.ClaveUsoCFDI + + + If HdnTipoDescuento.Value = "3" And DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero > 0 Then + + Timbre.CFDIRelacionados.TipoRelacion = "07" + Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" + + 'If Timbre.Comprobante.TipoComprobante = "E" Then + ' If Obj.TipoDocumento.Contiene("Nota de Crédito") Then + ' Timbre.CFDIRelacionados.TipoRelacion = "01" + ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso" + ' End If + ' If Obj.TipoDocumento.Contiene("Nota de Devolución") Then + ' Timbre.CFDIRelacionados.TipoRelacion = "03" + ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso" + ' End If + ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) + 'End If + '' cuando es refacturacoin es cfdirelacionado, con relacion 04 + 'If Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then + ' Timbre.CFDIRelacionados.TipoRelacion = "04" + ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso" + ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) + 'End If + + Else + 'SI LA FACTURA VIENE DE SER CANCELADA SISTEMA CUANDO SE REFACTURO NO HAY QUE RELACIONAR + If (CveEstatusFacturaPadre > 0 AndAlso CveEstatusFacturaPadre <> 4) OrElse (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Then + If Obj.CveTipoRelacion > 0 Then + + Select Case Obj.CveTipoRelacion + Case 1 + Timbre.CFDIRelacionados.TipoRelacion = "01" + Timbre.CFDIRelacionados.TipoRelacionTexto = "01-Nota de Crédito aplicada a Ingreso" + Case 2 + Timbre.CFDIRelacionados.TipoRelacion = "02" + Timbre.CFDIRelacionados.TipoRelacionTexto = "02-Nota de débito de los documentos relacionados" + Case 3 + Timbre.CFDIRelacionados.TipoRelacion = "03" + Timbre.CFDIRelacionados.TipoRelacionTexto = "03-Devolución aplicada a Ingreso" + Case 4 + Timbre.CFDIRelacionados.TipoRelacion = "04" + Timbre.CFDIRelacionados.TipoRelacionTexto = "04-Refacturación de Ingreso" + Case 7 + Timbre.CFDIRelacionados.TipoRelacion = "07" + Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" + Case 8 + Timbre.CFDIRelacionados.TipoRelacion = "08" + Timbre.CFDIRelacionados.TipoRelacionTexto = "08-Factura generada por pagos en parcialidades " + Case 9 + Timbre.CFDIRelacionados.TipoRelacion = "09" + Timbre.CFDIRelacionados.TipoRelacionTexto = "09-Factura generada por pagos diferidos" + End Select + + If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then + For Each Dr As DataRow In DtVentasNC.Rows + Timbre.CFDIRelacionados.UUID.Add(Dr("FolioFiscal").ToString) + Next + Else + If Not String.IsNullOrEmpty(HdnFolioFiscalNC.Value.Trim()) Then + Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) + End If + End If + + End If + End If + + End If + + + + + Dim totSubTotal As Decimal = Obj.SubTotal + Dim totIVA As Decimal = Obj.IVA + Dim totRetIVA As Decimal = Obj.RetIVA + Dim totRetISR As Decimal = Obj.RetISR + Dim TasaRetIVA As Decimal = LblRetIVA.Text.ToDecimal / 100 + Dim TasaRetISR As Decimal = LblRetISR.Text.ToDecimal / 100 + Dim i As Integer = 1 + + 'detalles + Dim tPS As String = "" + + For Each drr As DataRow In Obj.DtDetalle.Rows + If drr("PS").ToString.Length = 1 Then + tPS = drr("Obs").ToString + Else + If drr("PS").ToString.Length = 0 Then + tPS = "" + Else + tPS = String.Format("{0} {1}", drr("PS"), drr("Obs")) + End If + End If + 'condicionante, especial + If UsuarioActual.CveEmpresa = 15 Then drr("UM") = "" ' les comentan que no debe de ir la etiqueta de "unidad" en el producto + + Dim concepto As New CFDIConceptos With {.Cantidad = drr("Cantidad").ToString.ToDecimal, + .Descripcion = tPS, + .ValorUnitario = drr("PU").ToString.ToDecimal, + .Importe = drr("TotalImporte").ToString.ToDecimal, + .Descuento = drr("Descuento").ToString.ToDecimal, + .Unidad = drr("UM").ToString, + .ClaveUnidad = drr("SATClaveUM").ToString, + .ClaveProdServ = drr("SATClaveProdServ").ToString, + .Noidentificacion = drr("Noidentificacion").ToString, + .CuentaPredial = drr("CuentaPredial").ToString} + 'verifica suma subtotales + If i = Obj.DtDetalle.Rows.Count AndAlso totSubTotal <> concepto.Importe Then 'proceso de ajusta de decimales + concepto.Importe = totSubTotal + End If + totSubTotal = totSubTotal - concepto.Importe + + 'siempre estaremos agregando el iva, auqnue sea en importe cero o tasa cero, para que se emita la factura + ' If drr("ImporteIVA").ToString.ToDouble > 0 Then + + 'si es ingreso amortizado por la totalidad, y arroja el valor total de cero, no debe de impuestos + If Timbre.Comprobante.Total > 0 Then + concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteIVA").ToString.ToDecimal}) + End If + + If drr("ImporteIEPS").ToString.ToDouble > 0 Then + concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIEPS").ToString.ToDecimal, .Impuesto = "003", .Importe = drr("ImporteIEPS").ToString.ToDecimal}) + End If + + If drr("ImporteRetIVA").ToString.ToDouble > 0 Then 'si hay retenciones + concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetIVA, .Impuesto = "002", .Importe = drr("ImporteRetIVA").ToString.ToDecimal}) + End If + + If drr("ImporteRetISR").ToString.ToDouble > 0 Then 'retención de ISR + concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetISR, .Impuesto = "001", .Importe = drr("ImporteRetISR").ToString.ToDecimal}) + End If + + Timbre.Conceptos.Add(concepto) + i += 1 + Next + + Dim AplicaComercioExteriorSubProyecto As Boolean = If(GlobalDTSubProyectos(-1, Obj.CveSubProyecto)(0)("AplicaComercioExterior").ToString = "True", True, False) + Timbre.Complementos.ComercioExterior11.AplicaComercioExteriorSubProyecto = AplicaComercioExteriorSubProyecto + If Obj.Cliente.AplicaComercioExterior And AplicaComercioExteriorSubProyecto Then + 'DATOS GENERALES + Timbre.Complementos.ComercioExterior11.TipoOperacion = GlobalDTTipoOperacion().FiltraParametros($"CveTipoOperacion={CveTipoOperacion}")(0)("ClaveSATTipoOperacion").ToString + Timbre.Complementos.ComercioExterior11.ClavedePedimento = GlobalDTClavePedimento().FiltraParametros($"CvePedimento={CvePedimento}")(0)("ClaveSATPedimento").ToString + Timbre.Complementos.ComercioExterior11.CertificadoOrigen = "0" + Timbre.Complementos.ComercioExterior11.Incoterm = GlobalDTIncoterm.FiltroPrimeroValor("ClaveSATIncoterm", $"CveIncoterm={DdlIncoterm.SelectedValue}") + Timbre.Complementos.ComercioExterior11.Subdivision = "0" + Timbre.Complementos.ComercioExterior11.TipoCambioUSD = If(Obj.CveMoneda = 1, 1, Obj.TipoCambio.ToString.ToDecimal) + Timbre.Complementos.ComercioExterior11.MotivoTraslado = GlobalDTSATMotivoTraslado.FiltroPrimeroValor("ClaveSATMotivoTraslado", $"CveMotivoTraslado={DdlSATMotivoTraslado.SelectedValue}") + + + 'EMISOR + Dim Dr As DataRow + Dr = Nothing + If GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero).Rows.Count > 0 Then + Dr = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero)(0) + End If + Timbre.Complementos.ComercioExterior11.Emisor.CURP = UsuarioActual.Empresa.CURP + Timbre.Complementos.ComercioExterior11.Emisor.Calle = Dr("Calle").ToString + Timbre.Complementos.ComercioExterior11.Emisor.NumeroExterior = Dr("NoExt").ToString + Timbre.Complementos.ComercioExterior11.Emisor.NumeroInterior = Dr("NoInt").ToString + Timbre.Complementos.ComercioExterior11.Emisor.Colonia = Dr("ClaveSATColonia").ToString + Timbre.Complementos.ComercioExterior11.Emisor.Localidad = "" + Timbre.Complementos.ComercioExterior11.Emisor.Municipio = Dr("ClaveSATMunicipio").ToString + Timbre.Complementos.ComercioExterior11.Emisor.Estado = Dr("ClaveSATEstado").ToString + Timbre.Complementos.ComercioExterior11.Emisor.Pais = Dr("ClaveSATPais").ToString + Timbre.Complementos.ComercioExterior11.Emisor.CP = Dr("ClaveSATCP").ToString + + 'RECEPTOR + Timbre.Complementos.ComercioExterior11.Receptor.NumRegIdTrib = "" ' EN LA VERSION 3.3 NO DEBE DE REGISTRARSE ESTE VALOR + Timbre.Complementos.ComercioExterior11.Receptor.Calle = Obj.Cliente.Direccion + Timbre.Complementos.ComercioExterior11.Receptor.NumeroExterior = Obj.Cliente.NoExt + Timbre.Complementos.ComercioExterior11.Receptor.NumeroInterior = Obj.Cliente.NoInt + Timbre.Complementos.ComercioExterior11.Receptor.Colonia = Obj.Cliente.ClaveSATColonia + Timbre.Complementos.ComercioExterior11.Receptor.Localidad = "" + Timbre.Complementos.ComercioExterior11.Receptor.Referencia = Obj.Cliente.ReferenciaFiscal + Timbre.Complementos.ComercioExterior11.Receptor.Municipio = Obj.Cliente.Ciudad + Timbre.Complementos.ComercioExterior11.Receptor.CP = Obj.Cliente.CP + Timbre.Complementos.ComercioExterior11.Receptor.Estado = Obj.Cliente.ClaveSATEstado + Timbre.Complementos.ComercioExterior11.Receptor.Pais = Obj.Cliente.ClaveSATPais + Timbre.Receptor.ResidenciaFiscal = Obj.Cliente.ClaveSATPais + Timbre.Receptor.NumeroRegistroTributario = Obj.Cliente.NumRegIdTrib + + Dim ComExtPais, ComExtEstado, ComExtMunicipio, ComExtColonia, ComExtCalle, ComExtNumero, ComExtCP As String + ComExtColonia = "" : ComExtMunicipio = "" + ComExtPais = GlobalDTPais.FiltroPrimeroValor("ClaveSATPais", $"CvePais={DdlComExtPais.SelectedValue}") + ComExtCalle = TxtComExtCalle.Text.Trim + ComExtNumero = TxtComExtNumero.Text.Trim + ComExtCP = TxtComExtCP.Text.Trim + + If ComExtPais = "MEX" Then + ComExtEstado = GlobalDTEstado(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}") + ComExtMunicipio = GlobalDTMunicipio(ComExtEstado).FiltroPrimeroValor("ClaveSATMunicipio", $"CveMunicipio={DdlComExtMunicipio.SelectedValue}") + ComExtColonia = GlobalDTColonia(ComExtMunicipio).FiltroPrimeroValor("ClaveSATColonia", $"CveColonia={DdlComExtColonia.SelectedValue}") + Else + If ComExtPais.Contiene("USA", "CAN") Then + ComExtEstado = GlobalDTEstado(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}") + Else + ComExtEstado = TxtComExtEstado.Text.Trim + End If + ComExtMunicipio = TxtComExtMunicipio.Text.Trim + ComExtColonia = TxtComExtColonia.Text.Trim + End If + + 'DESTINATARIO + Timbre.Complementos.ComercioExterior11.Destinatario.Nombre = TxtDestinatarioNombre.Text.Trim + Timbre.Complementos.ComercioExterior11.Destinatario.Calle = ComExtCalle + Timbre.Complementos.ComercioExterior11.Destinatario.NumeroExterior = ComExtNumero + Timbre.Complementos.ComercioExterior11.Destinatario.NumeroInterior = "" + Timbre.Complementos.ComercioExterior11.Destinatario.Colonia = ComExtColonia + Timbre.Complementos.ComercioExterior11.Destinatario.Localidad = "" + Timbre.Complementos.ComercioExterior11.Destinatario.Referencia = Obj.Cliente.ReferenciaFiscal + Timbre.Complementos.ComercioExterior11.Destinatario.Municipio = ComExtMunicipio + Timbre.Complementos.ComercioExterior11.Destinatario.CP = ComExtCP + Timbre.Complementos.ComercioExterior11.Destinatario.Estado = ComExtEstado + Timbre.Complementos.ComercioExterior11.Destinatario.Pais = ComExtPais + Timbre.Complementos.ComercioExterior11.Destinatario.NumRegIdTrib = TxtNumRegIdTrib.Text.Trim + + + 'MERCANCIAS + For Each Gvr As GridViewRow In GvComercioExterior.Rows + Dim mercancia As New CFDIComercioExterior11Mercancias With {.CantidadAduana = Gvr.FCTextBox("TxtCantidad").Text.ToDecimal, + .FraccionArancelaria = Gvr.DataKey("ClaveSATFraccionArancelaria").ToString, + .UnidadAduana = Gvr.DataKey("ClaveSATUnidadAduana").ToString, + .ValorDolares = Math.Round(Gvr.FCTextBox("TxtCantidad").Text.ToDecimal * Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, 2), + .ValorUnitarioAduana = Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, + .NoIdentificacion = Gvr.DataKey("Codigo")} + If Gvr.FCTextBox("TxtMarca").Text <> "" Then + mercancia.DescripcionesEspecificas.Marca = Gvr.FCTextBox("TxtMarca").Text + End If + + Timbre.Complementos.ComercioExterior11.Mercancias.Add(mercancia) + i += 1 + Next + End If + + Return Timbre + End Function + + Private Sub PrepararTimbrado(ByRef FM As Modelos.FemsaFactura, ByRef TmpDT7Eleven As DataTable, ByRef TmpDTComplementosTimbrado As DataTable) + FM.AplicaFEMSA = AplicaFEMSA + FM.FEMSA_NumSociedad = TxtFEMSA_NumSociedad.Text.Trim + FM.FEMSA_NumProveedor = TxtFEMSA_NumProveedor.Text.Trim + FM.FEMSA_Mail = TxtFEMSA_Mail.Text.Trim + FM.FEMSA_Version = TxtFEMSA_Version.Text.ToEntero + FM.FEMSA_NumPedido = TxtFEMSA_NumPedido.Text.Trim.ToLong + FM.FEMSA_NumEntrada = TxtFEMSA_NumEntrada.Text.Trim + FM.FEMSA_NumRemision = TxtFEMSA_NumRemision.Text.Trim + FM.FEMSA_NumSocio = TxtFEMSA_NumSocio.Text.Trim + FM.FEMSA_CentroCosto = TxtFEMSA_CentroCosto.Text.Trim + FM.FEMSA_IPeriodoLiquidacion = TxtFEMSA_IPeriodoLiquidacion.Text.Trim + FM.FEMSA_FPeriodoLiquidacion = TxtFEMSA_FPeriodoLiquidacion.Text.Trim + FM.FEMSA_CodRetencion1 = TxtFEMSA_CodRetencion1.Text.Trim + FM.FEMSA_CodRetencion2 = TxtFEMSA_CodRetencion2.Text.Trim + + TmpDT7Eleven.Columns.Add("sevenElevenNumProveedor") + TmpDT7Eleven.Columns.Add("sevenElevenFolio") + TmpDT7Eleven.Columns.Add("sevenElevenTienda") + TmpDT7Eleven.Columns.Add("sevenElevenFecha") + + Dim Row As DataRow = TmpDT7Eleven.NewRow + Row("sevenElevenNumProveedor") = Txt7ElevenNumProveedor.Text.Trim() + Row("sevenElevenFolio") = Txt7ElevenFolio.Text.Trim() + Row("sevenElevenTienda") = Txt7ElevenTienda.Text.Trim() + Row("sevenElevenFecha") = Txt7ElevenFecha.Text.Trim() + + TmpDT7Eleven.Rows.Add(Row) + + TmpDTComplementosTimbrado.Columns.Add("CveComplemento") + TmpDTComplementosTimbrado.Columns.Add("IdContabilidad") + TmpDTComplementosTimbrado.Columns.Add("TipoProceso") + TmpDTComplementosTimbrado.Columns.Add("TipoAmbito") + TmpDTComplementosTimbrado.Columns.Add("Entidad") + + Dim Row2 As DataRow = TmpDTComplementosTimbrado.NewRow + If RblComplementos.SelectedValue.ToEntero > 0 Then + + Select Case RblComplementos.SelectedValue.ToEntero + Case 5 + Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero + Row2("IdContabilidad") = TxtIdConta.Text.ToEntero + Row2("TipoProceso") = "Ordinario" + Row2("TipoAmbito") = "Directivo Estatal" + Row2("Entidad") = DdlINEEntidad.SelectedValue + Case 6 + Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero + Row2("IdContabilidad") = TxtIdConta.Text.ToEntero + Row2("TipoProceso") = "Ordinario" + Row2("TipoAmbito") = "Ejecutivo Estatal" + Row2("Entidad") = DdlINEEntidad.SelectedValue + Case 7 + Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero + Row2("IdContabilidad") = TxtIdConta.Text.ToEntero + Row2("TipoProceso") = "Ordinario" + Row2("TipoAmbito") = "Ejecutivo Nacional" + Row2("Entidad") = "" + Case 8 + Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero + Row2("IdContabilidad") = TxtIdConta.Text.ToEntero + Row2("TipoProceso") = DdlTipoCampaña.SelectedValue + Row2("TipoAmbito") = DdlAmbitoComplemento.SelectedValue + Row2("Entidad") = DdlINEEntidad.SelectedValue + End Select + Else + Row2("CveComplemento") = "" + Row2("IdContabilidad") = "" + Row2("TipoProceso") = "" + Row2("TipoAmbito") = "" + Row2("Entidad") = "" + End If + + + TmpDTComplementosTimbrado.Rows.Add(Row2) + End Sub +#End Region + +#Region "Ordenes de Compra Sin Facurar" + Private Sub CargaOCs() + Dim ObjVentas As New ClsVentas + + If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 1) Then + If DdlContratosOC.SelectedValue.ToEntero > 0 Then + DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"CveContratoVinculado = '{DdlContratosOC.SelectedValue}'") + Else + DTOrdenesCompra = ObjVentas.DtResultados + End If + GVOC.DataSource = DTOrdenesCompra + End If + + If DTOrdenesCompra IsNot Nothing AndAlso Not DTOrdenesCompra.Columns.Contains("Aplicado") Then + DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean")) + End If + + ObjVentas.Dispose() + GVOC.DataBind() + UPOCFactura.Update() + End Sub + Private Sub CargaOCsxProducto() + Dim ObjVentas As New ClsVentas + + If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 2) Then + If DdlContratosOC.SelectedValue.ToEntero > 0 Then + DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0 AND CveContratoVinculado = '{DdlContratosOC.SelectedValue}'") + Else + DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0") + End If + GvOCPS.DataSource = DTOrdenesCompra + End If + + If Not DTOrdenesCompra.Columns.Contains("Aplicado") Then + DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean")) + End If + + ObjVentas.Dispose() + GvOCPS.DataBind() + UPOCFactura.Update() + End Sub + Private Sub ChkOCProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkPSOC.CheckedChanged + CargaOCSinFacturar() + End Sub + Private Sub VerificaOrdenesCompra(ByRef dt As DataTable) + If ChkPSOC.Checked Then + For Each Gvr As GridViewRow In GvOCPS.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + If Gvr.FCCheckBox("Chk").Checked Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveOrdenCompraDetalle As Integer = Gvr.DataKey("CveOrdenCompraDetalle").ToEntero + Dim Drs As DataRow() = dt.Select($"CveOrdenCompraDetalle = {CveOrdenCompraDetalle}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + End If + Next + + Else + For Each Gvr As GridViewRow In GVOC.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + If Gvr.FCCheckBox("Chk").Checked Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveOrdenCompra As Integer = Gvr.DataKey("CveOrdenCompra").ToEntero + Dim Drs As DataRow() = dt.Select($"CveOrdenCompra = {CveOrdenCompra}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + End If + Next + End If + End Sub + Protected Sub BtnCargarOC_Click(sender As Object, e As EventArgs) Handles BtnCargarOC.Click + If GVOC.Rows.Count > 0 Or GvOCPS.Rows.Count > 0 Then + 'Checa las facturas selecionadas + VerificaOrdenesCompra(DTOrdenesCompra) + + Dim dtSeleccionadas As DataTable = DTOrdenesCompra.FiltraParametros("Aplicado = True") + If GvPS.Rows.Count > 0 Then + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = TxtIVA.Text + End If + + If dtSeleccionadas.Rows.Count > 0 Then + + If TieneContrato Then + ContratoDetalles.Visible = True + DivEstimaciones.Visible = False + + DdlContratosModal.DataSource = DtContratos + DdlContratosModal.DataBind() + DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) + + DdlContratosModal.SelectedValue = DdlContratosOC.SelectedValue + DdlContrato.SelectedValue = DdlContratosOC.SelectedValue + UPEstimaciones.Update() + End If + + IsTotalxConcepto = True + Dim ObjClientes As New ClsClientes + Dim sb As New StringBuilder + If ChkPSOC.Checked Then + For Each row As DataRow In dtSeleccionadas.Rows + sb.Append($"{row("CveOrdenCompraDetalle").ToString},") + Next + Else + For Each row As DataRow In dtSeleccionadas.Rows + sb.Append($"{row("CveOrdenCompra").ToString},") + Next + End If + + sb.Remove(sb.Length - 1, 1) + If ObjClientes.GetVentasOCTotales(CveCliente, sb.ToString, If(ChkPSOC.Checked, 2, 1)) Then + DTOrdenesCompraPS = ObjClientes.DtResultados + + Dim tCantidad As Decimal = 0 + For Each Dr As DataRow In DTOrdenesCompraPS.Select() + tCantidad = If(ChkPSOC.Checked, GvOCPS.Rows(IndiceGVDataKey(GvOCPS, "CveOrdenCompraDetalle", $"{Dr("CveOrdenCompraDetalle")}")).FCTextBox("TxtCantidadOC").Text, Dr("Cantidad")).ToString.ToDecimal + AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, + Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PUCon").ToString.ToDecimal, 0, + Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, + CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero, + EntregaDirecta:=1) + Next + + + CveContrato = DTOrdenesCompraPS.FiltroPrimeroValor("CveContrato").ToString.ToEntero + If CveContrato > 0 Then ContratoOC = True + + CalculaTotalesVenta() + GvPS.DataSource = TmpDT + GvPS.DataBind() + End If + + ObjClientes.Dispose() + BtnEmitirImprimir.Text = "Facturar" + DdlTipoComprobante.SelectedValue = "Ing" + DdlTipoComprobante.Enabled = False + + Tab.ActiveTab = TabGenerales + TabGenerales.Enabled = True + Updatetabs.Update() + + + 'Else + ' If TieneContrato Then + ' GvContratoDetalles.DataSource = Nothing + ' GvContratoDetalles.DataBind() + ' UPEstimaciones.Update() + ' End If + End If + + End If + + ChkPSOC.Checked = False + UPOCFactura.Update() + UpFacturar.Update() + UpPS.Update() + UpParametros.Update() + RegistraScript("$('#DivOrdenesCompra').modal('hide');") + End Sub + Private Sub DdlContratosOC_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosOC.SelectedIndexChanged + CargaOCSinFacturar() + End Sub + Private Sub CargaOCSinFacturar() + If ChkPSOC.Checked Then + GvOCPS.Visible = True + GVOC.Visible = False + DivFiltroOCPS.Visible = True + GVOC.DataSource = Nothing + GVOC.DataBind() + CargaOCsxProducto() + Else + GvOCPS.Visible = False + GVOC.Visible = True + DivFiltroOCPS.Visible = False + GvOCPS.DataSource = Nothing + GvOCPS.DataBind() + CargaOCs() + End If + End Sub + Private Sub LnkOCs_Click(sender As Object, e As EventArgs) Handles LnkOCs.Click + Dim ObjContratos As New ClsContratos + + If Not TieneContrato Then + If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then + If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then + DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'") + DdlContratosOC.DataSource = DtContratos + DdlContratosOC.DataBind() + + If Not TieneContrato Then + DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) + End If + End If + End If + + GvContratoDetalles.DataSource = Nothing + GvContratoDetalles.DataBind() + UpContratos.Update() + + DivEstimaciones.Visible = True + ContratoDetalles.Visible = False + UPEstimaciones.Update() + + Tab.ActiveTab = TabGenerales + TabGenerales.Enabled = True + Updatetabs.Update() + End If + + ObjContratos.Dispose() + + ChkPSOC.Checked = False + UPOCFactura.Update() + + CargaOCSinFacturar() + RegistraScript("$('#DivOrdenesCompra').modal('show');") + End Sub + Private Sub BtnConsultarOC_Click(sender As Object, e As EventArgs) Handles BtnConsultarOC.Click + CargaOCSinFacturar() + End Sub +#End Region -#Region " GUARDAR - VENTA, PREPOLIZAS, INV, ESTIMACIONES, AC, NOTA DE CRÉDITO " - Private Sub GuardarVenta(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, factura As Modelos.Factura, TmpDTDetalle As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, Optional ByRef ObjOS As ClsOS = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, ByRef Optional ObjCGame As ClsCGame = Nothing, ByRef Optional ObjCliente As ClsClientes = Nothing) - - Dim Msgok As New StringBuilder - Dim CveAlmacenTraspasoOrigen As Integer = -1 - Dim CveAlmacenTraspasoDestino As Integer = -1 - Dim EsDevolucionVenta = -1 - Dim EsInterno As Integer = -1 - - If DdlAlmacenAsignado.Visible Or RequiereAlmacenDestino Then - CveAlmacenTraspasoDestino = DdlAlmacenAsignado.SelectedValue.ToEntero - End If - - If DdlAlmacenOrigen.Visible Or RequiereAlmacenOrigen Then - CveAlmacenTraspasoOrigen = DdlAlmacenOrigen.SelectedValue.ToEntero - End If - - If TrTipoPedido.Visible Then - EsInterno = DdlTipoPedido.SelectedValue.ToEntero() - End If - - 'Si es devolucion revertimos los almacenes - If CvePedido > 0 And TipoContrato = 2 Then - EsDevolucionVenta = 1 - CveAlmacenTraspasoOrigen = DdlAlmacenAsignado.SelectedValue.ToEntero - CveAlmacenTraspasoDestino = DdlAlmacenOrigen.SelectedValue.ToEntero - End If - - 'VALIDA ENTREGA POR ADELANTADO - If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then - 'INCRUSTAMOS ALMACEN ENTREGA POR ADELANTADO CUANDO SEA REMISION Y NO TRAIGA ASIGNADO POR EL USUARIO - If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then - CveAlmacenTraspasoDestino = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString.ToEntero - End If - - 'SI LA SUCURSAL NO TIENE ENTREGA POR ADELANTADO - If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then - ErrorList.Add("Ocurrió un error al seleccionar el almacen de entrega por adelantado de la sucursal.") - End If - End If - Dim TotalImpuestoLocal As Double = 0 - If GvImpuestosLocales2.Rows.Count > 0 Then - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then - If gvr.DataKey("TipoImpuesto") = "5" Then ' cuando es traslado local - TotalImpuestoLocal -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble - Else ' cuando es retención - TotalImpuestoLocal += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble - End If - - End If - End If - Next - End If - - - factura.CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardarVenta", factura.CvePlantillaPoliza, factura.Total, factura.Total, factura.CveMoneda, factura.Fecha, If(CveEmpresaCRM > 0, LblEmpresaCRM.Text, factura.Cliente.Nombre), factura.CveUsuario, factura.CveEmpresa) - If Not ObjVentas.AddVenta(factura.TipoDocto, factura.Folio, factura.CveCliente, factura.CveClienteSucursal, factura.SubTotalTC, factura.DescuentoTC, - factura.AmortizacionTC, factura.IVATC, factura.RetIVATC, factura.RetISRTC, - factura.TotalTC, factura.CveMoneda, factura.TipoCambio, factura.CveMetodoPago, factura.CondicionesPago, factura.FormaPago, factura.FechaPago, factura.Fecha, factura.MotivoDescuento, - factura.Observaciones, factura.FechaEjecucion, factura.CveVendedor, - factura.Alfa1, factura.Alfa2, factura.Alfa3, factura.Num1, factura.Num2, factura.Num3, - factura.Fech1, factura.Fech2, factura.Fech3, factura.CveCorte, factura.CveMesa, factura.NumeroPersonas, factura.CvePrePoliza, factura.CveUsuario, factura.CveEmpresa, - AtencionA:=factura.AtencionA, TelefonoGenerico:=TxtTelefonoGenerico.Text.Trim, CveContrato:=factura.CveContrato, CveVentaPadre:=If(AplicaDevolucion, CveVentaDevolucion, factura.CveVentaPadre), Det_FechaOrdenCompra:=factura.Det_FechaOrdenCompra, Det_OrdenCompra:=factura.Det_OrdenCompra, otros:=factura.Otros, - Entrega:=TxtEntrega.Text, Vigencia:=If(DdlTipoComprobante.SelectedValue = "Cot", TxtFechaVencimientoCotizacion.Text.ToDate, MinFecha), - CveAlmacenTraspasoDestino:=CveAlmacenTraspasoDestino, CveAlmacenTraspasoOrigen:=CveAlmacenTraspasoOrigen, CveDireccionEnvio:=If(DdlDireccionEnvio.Visible, DdlDireccionEnvio.SelectedValue.ToEntero, -1), CveOC:=CveOC, IEPS:=factura.IEPSTC, Serie:=factura.Serie, CveCondicionEntrega:=DdlFormaEntrega.SelectedValue.ToEntero, - PedidoContrato:=TxtPedidoContrato.Text, ObservacionesAlmacen:=TxtObsAlmacen.Text, CveSubProyecto:=factura.CveSubProyecto, CveSubProyectoCobranza:=factura.CveSubProyectoCobranza, CveSubProyectoEjecucion:=factura.CveSubProyectoEjecucion, CveFormaPago33:=factura.CveFormaPago33, - CveMetodoPago33:=factura.CveMetodoPago33, CveUsoCFDI:=factura.CveUsoCFDI, OrdenCompra:=TxtOrdenCompra.Text, CveCuentaTerminal:=DdlCuentasTerminal.SelectedValue.ToEntero, CveTipoRelacion:=factura.CveTipoRelacion, ImpuestoLocal:=TotalImpuestoLocal, - CveVentaRelacion:=(If(factura.CveVentaRelacion.ToEntero > 0, factura.CveVentaRelacion, -1)), ImporteRelacion:=(If(factura.ImporteRelacion <> Nothing, factura.ImporteRelacion, -1)), - CveTipoAmortizacionAnticipo:=factura.CveTipoAmortizacionAnticipo, CveEmpresaCRM:=CveEmpresaCRM, EsInterno:=EsInterno, CveAcercamientoCRM:=CveAcercamientoCRM, - DiasCredito:=factura.DiasCredito, EsDiasCreditoFijo:=factura.EsDiasCreditoFijo, AnticipoEspecial:=If(TrAntEspecial.Visible, ChkAntEspecial.Checked, False)) Then - - ErrorList.Add("Ocurrió un error al Generar la Venta.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") - - End If - - If Not GuardarUsados(ObjVentas.IniciaTransacSQL, ObjVentas.CveVenta) Then - ErrorList.Add("Error al guardar usados") - End If - - - If ErrorList.Count = 0 AndAlso ObjVentas.CveVenta > 0 Then - - factura.CveVenta = ObjVentas.CveVenta - factura.Serie = ObjVentas.Serie - factura.Folio = ObjVentas.Folio - ViewState("VentaFolio") = ObjVentas.SerieFolio - factura.Timbre.Comprobante.Serie = ObjVentas.Serie - factura.Timbre.Comprobante.Folio = ObjVentas.Folio.ToString - - If factura.TipoDocto = "Egs" AndAlso NuevaFactura = 1 Then - If DtVentasNC Is Nothing Then - InicializaDTVentasNC() - End If - CargaNCDT(factura.CveVentaPadre, factura.Total, NuevaFactura:=NuevaFactura, ObjVentas:=ObjVentas) - End If - - 'Se agregan los PS - For Each Row As DataRow In TmpDTDetalle.Rows - If Not ObjVentas.AddVentaDetalle(ObjVentas.CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, - Row("PU").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)))), 6), - Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, - TiempoEntrega:=Row("TiempoEntrega").ToString, CveVentaDetallePadre:=Row("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CvePromocionDetalle:=If(DtPromociones IsNot Nothing, DtPromociones.FiltroPrimeroValor("CvePromocionDetalle", $"CvePS={Row("CvePS").ToString}").ToEntero, -1), - IEPS:=Row("ImporteIEPS").ToString.ToDouble, CveMovimientoDetallePedido:=Row("CveMovimientoDetallePedido").ToString.ToEntero, - ImporteRetIVA:=Row("ImporteRetIVA").ToString.ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString.ToDouble, - PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString.ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString.ToDouble, CuentaPredial:=Row("CuentaPredial").ToString) Then - ErrorList.Add("Ocurrió un error al agregar un Producto o Servicio a la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") - Exit For - Else - - 'Agregamos el gasto de contrato - If CveContrato > 0 AndAlso factura.TipoDocto = "Rem" AndAlso AplicaGastoContrato Then - Dim ObjContrato As New ClsContratos - If Not ObjContrato.AddContratoGasto(CveContrato, Row("PS").ToString, Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, factura.Fecha, UsuarioActual.CveUsuario, CveVenta:=ObjVentas.CveVenta) Then - ErrorList.Add("Ocurrió un error al agregar el gasto de la Factura.") - Exit For - End If - ObjContrato.Dispose() - End If - - 'Si es devolucion se agregan a la tabla de Vta_VentasDetalleDevolucion - If factura.AplicaDevolucion Then - If Not ObjVentas.AddVentaDetalleDevolucion(Row("CveVentaDetalle").ToString.ToEntero, ObjVentas.CveVentaDetalle, Row("Cantidad").ToString.ToDouble) Then - ErrorList.Add("Ocurrió un error al agregar la venta detalle devolucion.") - End If - End If - - Dim TmpDr As DataRow = TmpDT.Select($"Consec = {Row("Consec").ToString}")(0) - TmpDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle - - Try - Dim InvDr As DataRow = DtInv.Select($"Consec = {Row("Consec").ToString}")(0) - InvDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle - Catch ex As Exception - End Try - - End If - Next - - 'Orden Produccion' - If UsuarioActual.CveEmpresa.Contiene(126) Then - If ObjVentas.CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then - If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), ObjVentas.CveVenta) Then - ErrorList.Add("Ocurrió un error al actualizar la orden de producción") - End If - End If - End If - - 'PedidoA' - If ObjVentas.CveVenta > 0 And CvePedidoA > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem") Then - If Not ObjCliente.UpdateEstatusPedido(CvePedidoA, 18, -1, UsuarioActual.CveUsuario) Then - ErrorList.Add("Ocurrió un error al actualizar el estatus del pedidoA") - End If - End If - - 'Actualiar el estatus de la venta refacturada - If ObjVentas.CveVenta > 0 AndAlso NuevaFactura = 1 AndAlso CveDevolucion > 0 Then - - 'If CveEstatusRefacturacion = 1 Then CveEstatusRefacturacion = 2 'cuando viene del proceso de refacturación con aceptació - If Not ObjVentas.UpdateEstatusRefacturacion(CveDevolucion, 2) Then ' se marca como refacturada - ErrorList.Add("Ocurrió un error al actualizar el estatus de la refacturacion") - End If - End If - - 'Pedido2' - If ObjVentas.CveVenta > 0 And CvePedido2 > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem", "PA") Then - If Not ObjCliente.UpdateEstatusPedido(CvePedido2, 21, -1, UsuarioActual.CveUsuario) Then - ErrorList.Add("Ocurrió un error al actualizar el estatus del pedido2") - End If - End If - - 'Si viene de OS, Se guarda CveVenta en OS - If CveOS > 0 Then - If Not ObjOS.UpdateVentaOS(factura.CveVenta, CveOS) Then - ErrorList.Add("Ocurrió un error al guardar la venta en Ordenes de Servicio") - End If - End If - - 'Contratos - If factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing") Then - GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, 1) - ElseIf factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then - GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, -1) - End If - - 'Impuestos Locales - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then - If Not ObjVentas.AddVentaImpuestoLocales(factura.CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1))) Then - ErrorList.Add("Ocurrió un error al Guardar Impuestos Locales") - End If - End If - End If - Next - - If DTmpF.Rows.Count > 0 Then - For Each Row As DataRow In DTmpF.Rows - If Not ObjVentas.AddVentasFirmas(factura.CveVenta, Row("Titulo").ToString, Row("Nombre").ToString, Row("Puesto").ToString, Row("Lado").ToString.ToEntero) Then - ErrorList.Add("Ocurrio un error al Guardar Firmas") - End If - Next - End If - - 'registro los metodos de pago, cuando hay corte. - If factura.CveCorte > 0 Then - 'cuando es contado - If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then - For Each DrPago As DataRow In DtPagos.Rows - If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, DrPago("CveMetodoPago").ToString.ToEntero, DrPago("Importe").ToString.ToDouble) Then - ErrorList.Add("Ocurrio un error al guardar los metodos de pago") - End If - Next - Else - 'cuando es crédito o terminal - If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, 7, TxtTotal.Text.ToDouble) Then - ErrorList.Add("Ocurrio un error al guardar los metodos de pago") - End If - End If - - End If - - - 'cuando es contado - 'If factura.CveCorte > 0 Then - ' If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then - ' For Each DrPago As DataRow In DtPagos.Rows - ' If ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, TxtFechaPago.Text.ToDate, DrPago("Folio").ToString, "", DrPago("Importe").ToString.ToDouble, DdlMoneda.SelectedValue.ToEntero, If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then - ' ErrorList.Add("Ocurrio un error al guardar los metodos de pago") - ' End If - ' Next - ' 'Else - ' ' 'cuando es crédito o terminal - ' ' If ObjBancos.AddBancos_IE(, 7, TxtFechaPago.Text.ToDate, TxtFolio.Text.ToString, "", TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then - ' ' ErrorList.Add("Ocurrio un error al guardar los metodos de pago") - ' ' End If - ' End If - 'End If - - - - 'INE COMPLEMENTOS - If ObjFactura.ComplementoINE IsNot Nothing Then - If Not ObjVentas.UpdateVentasComplementos(ObjFactura.CveVenta, ObjFactura.ComplementoINE.INETipoProceso, ObjFactura.ComplementoINE.INETipoComite, ObjFactura.ComplementoINE.INEIdContabilidad.ToString) Then - ErrorList.Add("Ocurrio un error al guardar los complementos") - End If - End If - - If ErrorList.Count = 0 Then - 'Agregamos las remisiones a la tabla - If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then - Dim CveVentaDetalle As Integer = 0 - Dim CveVentaDetallePadre As Integer = 0 - Dim Cantidad As Decimal = 0 - Dim CvePS As Integer = 0 - Dim PU As Decimal = 0 - - For Each row As DataRow In DtRemisionesPS.Rows - Cantidad = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal - CvePS = DtRemisionesTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero - PU = DtRemisionesTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal - CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero - CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero - - If Not ObjVentas.AgregarRemisionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then - ErrorList.Add("Ocurrió un error al agregar el detalle de la Remision") - End If - Next - - End If - - If DTRemisiones IsNot Nothing AndAlso DTRemisiones.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then - - Dim dt As DataTable = DTRemisiones.FiltraParametros("Aplicado = True") - If dt.Rows.Count > 0 Then - For Each row As DataRow In dt.Rows - If Not ObjVentas.UpdateVentaRemision(row("CveVenta").ToString.ToEntero, ObjFactura.CveVenta) Then - ErrorList.Add("Ocurrió un error al actualizar la remisión") - End If - Next - End If - End If - End If - - If ErrorList.Count = 0 Then - 'Agregamos los pedidos2 a la tabla - If DtPedidos2PS IsNot Nothing AndAlso DtPedidos2PS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then - Dim CveVentaDetalle As Integer = 0 - Dim CveVentaDetallePadre As Integer = 0 - Dim Cantidad As Decimal = 0 - Dim CvePS As Integer = 0 - Dim PU As Decimal = 0 - - For Each row As DataRow In DtPedidos2PS.Rows - Cantidad = DtPedidos2TmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal - CvePS = DtPedidos2TmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero - PU = DtPedidos2TmpDT.FiltroPrimeroValor("PU", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal - CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero - CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero - - If Not ObjVentas.AddVentaDetallePedido2(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then - ErrorList.Add("Ocurrió un error al agregar el detalle del Pedido2") - End If - Next - End If - - If DtPedidos2 IsNot Nothing AndAlso DtPedidos2.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then - Dim dt As DataTable = DtPedidos2.FiltraParametros("Aplicado = True") - If dt.Rows.Count > 0 Then - For Each row As DataRow In dt.Rows - If Not ObjVentas.UpdateVentaPedido2(row("CveVenta").ToString.ToEntero, ObjFactura.CveVenta) Then - ErrorList.Add("Ocurrió un error al actualizar el Pedido2") - End If - Next - End If - End If - End If - - - If ErrorList.Count = 0 Then - 'prepoliza - GuardarVentaPrePolizas(ObjConta, factura, TmpDTDetalle, CveNCaVincular, objContPaqi, ObjBancos, ObjVentas, ObjEventos:=ObjEventos) - If ErrorList.Count = 0 Then - 'inventarios - If GuardarVentaInventarios(ObjInventario, ObjConta, factura) Then - ErrorList.Add("Ocurrio un error al Guardar Inventario") - End If - If ErrorList.Count = 0 Then - 'estimaciones - GuardarVentaEstimaciones(ObjContr, factura) - If ErrorList.Count = 0 Then - 'armonizaccionContable - GuardarVentaAC(ObjVentas, factura, Msgok, objContPaqi) - If ErrorList.Count = 0 Then - 'Impuestos Locales - If GuardarVentaImpuestosLocales(ObjVentas, ObjConta, factura) Then - ErrorList.Add("Ocurrio un error al Guardar Impuestos Locales") - End If - End If - End If - End If - End If - End If - - End If - End Sub - Private Sub GuardarVentaPrePolizas(ByRef ObjConta As ClsContabilidad, factura As Modelos.Factura, TmpDTDetalleMovimientos As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing) - - Dim CveIE As Integer = -1 - Dim DT As DataTable = Nothing - - - Dim CveConceptoAfectacion As Integer = 1 'Cliente - Dim CveConceptoAntCli As Integer = 3 'Anticipo Cliente - Dim CveConceptoVenta As Integer = 4 'Venta - Dim CveConceptoCanAnt As Integer = 11 'Cancelacion Anticipos - Dim CveConceptoDSV As Integer = 12 ' DSV - Dim CveConceptoIVA As Integer = 13 'IVA Trasladado - Dim CveConceptoRetIVA As Integer = 8 'Ret IVA - Dim CveConceptoRetISR As Integer = 9 'Ret ISR - - 'P R E P O L I Z A S - If DdlTipoComprobante.SelectedValue <> "Cot" Then - If factura.CvePrePoliza > 0 Then - - If ProcesoPrepolizas(ObjConta, factura, CveIE, TmpDTDetalleMovimientos, objContPaqi, 1, ObjBancos, ObjVentas, ObjEventos:=ObjEventos) Then - ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") - End If - - Else - ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") - End If - End If - End Sub - Private Function ProcesoPrepolizas(ByRef ObjConta As ClsContabilidad, ObjFactura As Modelos.Factura, CveIE As Integer, TmpDTDetalle As DataTable, ByRef objContPaqi As ClsContPAQi, Optional ValorMultiplicador As Integer = 1, ByRef Optional ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing) As Boolean - Try - Dim DT As DataTable - Dim CvePlantilaPoliza As Integer - Dim PorcentajeAmortizacion As Decimal = 0 - Dim sumaAmorticaciones As Decimal = 0 - Dim ErrorPrepoliza As Boolean = False - Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " - Dim CveCuentaContabilizacion As Integer = 1 - Dim tipoCambio As Decimal - - Dim CuentasContablesInvalidasSIG As New StringBuilder - - If ObjFactura.TipoDocto = "Ing" Or ObjFactura.TipoDocto = "Ant" Or ObjFactura.TipoDocto = "Com" Then - CvePlantilaPoliza = 4 - ElseIf ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - CvePlantilaPoliza = 7 - ElseIf ObjFactura.TipoDocto = "Rem" Then - CvePlantilaPoliza = 4 - End If - - If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then - tipoCambio = ObjFactura.TipoCambio - ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then - tipoCambio = GlobalTipoCambio(ObjFactura.Fecha).ToString.ToDecimal - Else - tipoCambio = 1 - End If - - Dim ConceptoContable As Integer - Dim TipoMovimiento As Boolean - Dim importeMovimiento As Decimal - Dim FechaMovimiento As Date = ObjFactura.Fecha - Dim IdCtaContable As Integer - Dim CveCuenta As Integer - Dim IdCtaContableCliente As Integer - Dim CveCuentaCliente As Integer - Dim Concepto As String = ViewState("VentaFolio").ToString - Dim Referencia As String = ViewState("VentaFolio").ToString - Dim Fecha = TxtFecha.Text.Trim.ToDate - - Dim importeMX As Decimal - Dim Multiplicador As Integer - Dim CveIEPago As Integer - Dim FolioIE As Long - Dim CveIEAnticipo As Integer - Dim CveSubProyectoVenta = DdlSubProyectoDatos.SelectedValue.ToEntero - Dim CveSubProyectoContabilizar As Integer - Dim IdCtaIVAXTrasladar As Integer = 0 - Dim IdCtaIVATrasladado As Integer = 0 - Dim CveCuentaIVAxTrasladar As Integer = 0 - Dim CveCuentaIVATrasladado As Integer = 0 - Dim SeContabiliza As Boolean = True - If (UsuarioActual.Empresa.Funcionalidad(343) = "1" AndAlso ObjFactura.TipoDocto = "Ant") Or (ChkAntEspecial.Checked AndAlso ObjFactura.TipoDocto = "Ant") Then - SeContabiliza = False - End If - - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then - IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero - CveCuentaIVAxTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVAXTrasladar").ToString.ToEntero - IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero - CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero - End If - - Dim UsaComplementariaClientes As Boolean = False - If UsuarioActual.CveEmpresa.Contiene(1, 119) Then UsaComplementariaClientes = True - - If ObjConta.GetPlantillaConceptos(ObjFactura.CveEmpresa, CvePlantilaPoliza) Then - Dim dtt As DataTable = ObjConta.DtResultados - If ValorMultiplicador = -1 Then dtt = ObjConta.DtResultados.FiltraParametros("", "Orden DESC") ' se ordena contrario al registro para llevar los saldos correctos - For Each Row As DataRow In dtt.Rows - - ConceptoContable = Row("CveConcepto").ToString.ToEntero - TipoMovimiento = If(Row("TipoMovto").ToString = "True", True, False) - importeMovimiento = 0 - IdCtaContable = 0 - CveCuenta = 0 - CveSubProyectoContabilizar = 0 - Multiplicador = (Row("Multiplicador").ToString.ToEntero) - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, ConceptoContable, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", "") - Dim PorcentajeImpuesto As Decimal = 0 - - - - Select Case ConceptoContable - Case 1 'Cliente - If Not ObjFactura.TipoDocto.Contiene("Egs", "Rem") Then - importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador - importeMX = importeMovimiento * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - CveSubProyectoContabilizar = CveSubProyectoVenta - 'If ObjFactura.TipoDocto.Contiene("Ant") Then - ' TipoMovimiento = Not TipoMovimiento 'lo contrario a ingreso, en este caso es anticipo - 'End If - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - If tipoCambio = 1 Then - IdCtaContable = ObjFactura.Cliente.IdCtaContClientes - CveCuenta = ObjFactura.Cliente.CveCuentaClientes - Else - IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria - CveCuenta = 0 - - If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsaComplementariaClientes) Then - importeMX = importeMovimiento - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - End If - End If - - IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera - CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera - End If - IdCtaContableCliente = IdCtaContable - CveCuentaCliente = CveCuenta - End If - - Case 3 'Cliente - - If ObjFactura.TipoDocto = "Ant" Then - ConceptoContable = If(UsuarioActual.CveEmpresa.Contiene(1, 119), 95, ConceptoContable) - importeMovimiento = ObjFactura.SubTotal * ValorMultiplicador - importeMX = importeMovimiento * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - IdCtaContable = ObjFactura.Cliente.IdCtaContAnticipos - CveCuenta = ObjFactura.Cliente.CveCuentaAnticipos - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - End If - Case 190 'Remisión del cliente - - If ObjFactura.TipoDocto = "Rem" Then - importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador - importeMX = importeMovimiento * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - If tipoCambio = 1 Then - IdCtaContable = ObjFactura.Cliente.IdCtaContClientes - CveCuenta = ObjFactura.Cliente.CveCuentaClientes - Else - IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera - CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera - End If - IdCtaContableCliente = IdCtaContable - CveCuentaCliente = CveCuenta - - If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 190, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 193, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - Else - ErrorPrepoliza = True - End If - - importeMovimiento = 0 - ViewState("SeGuardoPrePoliza") = True - End If - - Case 12 'Nota de Credito - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - importeMovimiento = ObjFactura.Total * ValorMultiplicador - importeMX = (importeMovimiento * tipoCambio * Multiplicador).RoundSQL - FechaMovimiento = ObjFactura.FechaPago - Dim ImporteConcepto12 As Decimal = 0 - Dim ImporteAcumulado91 As Decimal = 0 - Dim CveUltimaVenta As Integer = 0 - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - If tipoCambio = 1 Then - IdCtaContable = ObjFactura.Cliente.IdCtaContClientes - CveCuenta = ObjFactura.Cliente.CveCuentaClientes - ElseIf UsaComplementariaClientes Then - - IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria - CveCuenta = 0 - - If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsaComplementariaClientes) Then - importeMX = importeMovimiento - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - End If - - IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera - CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera - End If - CveSubProyectoContabilizar = CveSubProyectoVenta - ImporteConcepto12 = importeMX.RoundSQL - If importeMovimiento <> 0 Then - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Else - ViewState("SeGuardoPrePoliza") = True - End If - End If - importeMovimiento = 0 - - If ValorMultiplicador = 1 Then - - Dim IdCtaContableClienteComplementaria As Integer = ObjFactura.Cliente.IdCtaContComplementaria - Dim TipoCambioNC As Decimal = 1 - If tipoCambio > 1 Then - TipoCambioNC = tipoCambio - Else - TipoCambioNC = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal - End If - - 'APLICA NC SALDOS DIRECTOS - If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then - For Each Dr As DataRow In DtVentasNC.Rows - - - Dim Importe91 As Decimal = 0 - Dim ImporteMN91 As Decimal = 0 - Dim Importe251 As Decimal = 0 - Dim ImporteMN251 As Decimal = 0 - - If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - Importe251 = Dr("Importe").ToString.ToDecimal - Importe91 = Dr("Importe").ToString.ToDecimal - ImporteMN91 = Dr("Importe").ToString.ToDecimal - TipoCambioNC = 1 - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - Importe251 = Dr("Importe").ToString.ToDecimal - Importe91 = Dr("Importe").ToString.ToDecimal - ImporteMN91 = Dr("Importe").ToString.ToDecimal * TipoCambioNC - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - Importe251 = Dr("Importe").ToString.ToDecimal - Importe91 = Dr("Importe").ToString.ToDecimal - ImporteMN91 = Dr("Importe").ToString.ToDecimal * TipoCambioNC - ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - Importe251 = Dr("Importe").ToString.ToDecimal - Importe91 = Dr("Importe").ToString.ToDecimal - ImporteMN91 = Dr("Importe").ToString.ToDecimal - End If - - Dim TCFluctuacion As Decimal = Dr("TCCambioValuacion").ToString.ToDecimal - If TCFluctuacion = 1 AndAlso TipoCambioNC > 1 Then - TCFluctuacion = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal - End If - - If DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - ImporteMN251 = Dr("Importe").ToString.ToDecimal * TCFluctuacion - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - ImporteMN251 = Dr("Importe").ToString.ToDecimal * TCFluctuacion - ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - ImporteMN251 = Dr("Importe").ToString.ToDecimal / TipoCambioNC - Else - ImporteMN251 = Dr("Importe").ToString.ToDecimal - End If - - Importe251 = (Importe251 * Multiplicador).RoundSQL - - Importe91 = (Importe91 * ValorMultiplicador).RoundSQL - ImporteMN91 = (ImporteMN91 * Multiplicador).RoundSQL - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${Importe91.FormatoNumero(2)}" - - CveUltimaVenta = Dr("CveVenta").ToString.ToEntero - - Dim ImporteComplementarioIngreso As Decimal = 0 - If UsaComplementariaClientes = True AndAlso tipoCambio > 1 Then - ImporteMN91 = Importe91 - ImporteComplementarioIngreso = ((Importe91 * tipoCambio) - Importe91).RoundSQL - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteComplementarioIngreso, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=Dr("TCCambioValuacion").ToString.ToDecimal) Then - ErrorPrepoliza = True - Exit For - End If - End If - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteMN91, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then - ErrorPrepoliza = True - Exit For - End If - ImporteAcumulado91 += (ImporteMN91).RoundSQL - - If UsaComplementariaClientes = True AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then - ImporteMN251 = Importe251 - Dim ImporteComplementarioNC As Decimal = ((Importe251 * Dr("TCCambioValuacion").ToString.ToDecimal) - Importe251).RoundSQL - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=Dr("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementarioNC, ImporteME:=If(Dr("TCCambioValuacion").ToString.ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString.ToDecimal) Then - ErrorPrepoliza = True - Exit For - End If - End If - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=Dr("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteMN251, ImporteME:=If(Dr("TCCambioValuacion").ToString.ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString.ToDecimal, TipoCambioPago:=tipoCambio) Then - ErrorPrepoliza = True - Exit For - End If - - - 'considero fluctuación. - - - If TipoCambioNC <> TCFluctuacion AndAlso TCFluctuacion > 1 AndAlso TipoCambioNC > 1 Then - Dim difFluctuacion As Decimal = TipoCambioNC - TCFluctuacion - Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida - Dim TipoMovtoFluctua As Boolean = True - Dim IdCtaContableFluctua As Integer - If difFluctuacion < 0 Then - CveConceptoFluctua = 65 - TipoMovtoFluctua = False - IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - Else - CveConceptoFluctua = 64 - TipoMovtoFluctua = True - IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - End If - Dim ImporteFluctuacion As Decimal = Math.Abs((Importe251 * difFluctuacion).RoundSQL) - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=TipoCambioNC, TipoCambioPago:=Dr("TCCambioValuacion").ToString.ToDecimal, CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - Exit For - End If - End If - - Next - - If ImporteConcepto12 < ImporteAcumulado91 Then - Dim ImporteOtrosIngresos As Decimal = ImporteConcepto12 - ImporteAcumulado91 - If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ImporteOtrosIngresos, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveUltimaVenta, ImporteMX:=ImporteOtrosIngresos, ImporteME:=0, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ImporteOtrosIngresos, Referencia, 211, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteME:=0, ImporteMX:=ImporteOtrosIngresos, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - Else - ErrorPrepoliza = True - End If - End If - - If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 5) Then - If ObjConta.ValorPolizaDescuadre > 0 Then - 'ErrorPrepoliza = True - GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") - - 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA - 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then - ' Dim DtTest = ObjConta.DtResultados - 'End If - End If - End If - - - If ErrorPrepoliza Then - Exit For - End If - End If - - 'APLICA DEVOLUCION SALDOS DIRECTOS - If AplicaDevolucion Then - Dim importeMovimientoDev = TxtTotal.Text.ToDecimal - importeMovimientoDev = If(SaldoVentaDevolucion < importeMovimientoDev, SaldoVentaDevolucion, importeMovimientoDev) - If importeMovimientoDev > 0 Then - Dim importeMXDev = importeMovimientoDev * tipoCambio * Multiplicador - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimientoDev.FormatoNumero(2)}" - - If UsaComplementariaClientes AndAlso tipoCambio > 1 Then - importeMXDev = importeMovimientoDev - Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * tipoCambio) - importeMovimientoDev).RoundSQL - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteComplementaria, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura) Then - ErrorPrepoliza = True - Exit For - End If - End If - - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - If UsaComplementariaClientes AndAlso TipoCambioFactura > 1 Then - importeMXDev = importeMovimientoDev - Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * TipoCambioFactura) - importeMovimientoDev).RoundSQL - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementaria, ImporteME:=If(TipoCambioFactura = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=TipoCambioFactura) Then - ErrorPrepoliza = True - Exit For - End If - End If - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - If tipoCambio <> TipoCambioFactura Then - Dim difFluctuacion As Decimal = tipoCambio - TipoCambioFactura - Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida - Dim TipoMovtoFluctua As Boolean = True - Dim IdCtaContableFluctua As Integer - If difFluctuacion < 0 Then - CveConceptoFluctua = 65 - TipoMovtoFluctua = False - IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - Else - CveConceptoFluctua = 64 - TipoMovtoFluctua = True - IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - End If - Dim ImporteFluctuacion As Decimal = Math.Abs((importeMovimientoDev * difFluctuacion).RoundSQL) - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura, CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - Exit For - End If - End If - - If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 5) Then - If ObjConta.ValorPolizaDescuadre > 0 Then - 'ErrorPrepoliza = True - GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") - - 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA - 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then - ' Dim DtTest = ObjConta.DtResultados - 'End If - End If - End If - - End If - End If - End If - End If - Case 136 'Otros Conceptos Dinamicos - For Each row2 As GridViewRow In GVOtrosConceptos.Rows - If row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal > 0 Then - - importeMovimiento = row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal * ValorMultiplicador - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - If row2.DataKey("IdCtaContable").ToEntero > 0 Then - IdCtaContable = row2.DataKey("IdCtaContable").ToEntero - Else - If ObjConta.GetRetCuenta(row2.DataKey("CveConceptoContable").ToEntero, ObjFactura.CveCliente) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContFondoGarantia").ToString.ToEntero - End If - End If - End If - - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, If(row2.DataKey("TipoMovto").ToString = "True", True, False), importeMovimiento, Referencia, row2.DataKey("CveConceptoContable").ToEntero, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - End If - - End If - Next - importeMovimiento = 0 - - Case 11 'Anticipo - - '[IPP] SI ES REFACTURACION LOS ANTICIPOS NO LOS DEBE APLICAR EN EL INGRESO REFACTURADO (VIEJO) - If NuevaFactura = 1 And ObjFactura.CveVenta = CveDevolucion Then - Exit Select - End If - - If ObjFactura.TipoDocto = "Ing" AndAlso ValorMultiplicador = -1 Then - For Each row2 As GridViewRow In GvAntNC.Rows - If row2.DataKey("CveConceptoContable").ToString().ToEntero = 11 Then - importeMovimiento = row2.DataKey("Importe").ToString().ToDecimal * ValorMultiplicador '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - IdCtaContable = IdCtaContAnticipos - CveCuenta = CveCuentaAnticipos - CveSubProyectoContabilizar = CveSubProyectoVenta - - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - Else - ViewState("SeGuardoPrePoliza") = True - End If - End If - - End If - Next - End If - - 'cuando es anticipo - ' cuando es amortización de nota de crédito, y es la nc - ' cuando es amortización por descuento, y es el ingreso - ' cuando es amortización en cero - If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 2 AndAlso ObjFactura.TipoDocto.Contiene("Egs") OrElse - DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 1 AndAlso ObjFactura.TipoDocto.Contiene("Ing") OrElse - DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 3 Then - - For Each row2 As GridViewRow In GVAnticipos.Rows - If row2.DataKey("CveConceptoContable").ToString().ToEntero = 3 Then - If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then - CveIEAnticipo = row2.DataKey("CveIE").ToString.ToEntero - importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - IdCtaContable = IdCtaContAnticipos - CveCuenta = CveCuentaAnticipos - CveSubProyectoContabilizar = CveSubProyectoVenta - - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Exit For - Else - ViewState("SeGuardoPrePoliza") = True - End If - End If - - End If - End If - Next - - End If - 'Cuando la funcionalidad de amortizacion en PS esta activa - If Not ErrorPrepoliza Then - DT = TmpDTDetalle.FiltraParametros($"CvePS = {CvePSAmortizacion}") - If DT.Rows.Count > 0 Then - For Each Row2 As DataRow In DT.Rows - importeMovimiento = Math.Abs(Row2("PU").ToString.ToDecimal) - IdCtaContable = IdCtaContAnticipos - CveCuenta = CveCuentaAnticipos - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - If importeMovimiento <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Else - ViewState("SeGuardoPrePoliza") = True - End If - End If - Next - End If - End If - - 'PorcentajeAmortizacion = sumaAmorticaciones / TxtTotal.Text.ToDecimal - importeMovimiento = 0 - - Case 91 'Amortizacion Nota de Credito - Dim Contabilizable = If(UsuarioActual.CveEmpresa = 119, False, True) - - If ValorMultiplicador = -1 Then - 'cuando es cancelación - For Each row2 As GridViewRow In GvNC.Rows - - If row2.DataKey("CveConceptoContable").ToString().ToEntero = 91 Then - - importeMovimiento = row2.DataKey("Importe").ToDecimal * ValorMultiplicador - sumaAmorticaciones += importeMovimiento - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - 'CTACONTABLE - 'IdCtaContable = IdCtaContAnticipos - 'CveCuenta = CveCuentaAnticipos - IdCtaContable = ObjFactura.Cliente.IdCtaContClientes - CveCuenta = ObjFactura.Cliente.CveCuentaClientes - - CveSubProyectoContabilizar = CveSubProyectoVenta - - If importeMovimiento <> 0 Then - - If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimiento, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVentaNC").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimiento, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString.ToEntero, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then - ErrorPrepoliza = True - Exit For - End If - Else - ErrorPrepoliza = True - Exit For - End If - - 'If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString.ToEntero, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ' ErrorPrepoliza = True - 'End If - End If - End If - Next - - Else - For Each row2 As GridViewRow In GVAnticipos.Rows - - If row2.DataKey("CveConceptoContable").ToString().ToEntero = 12 Then - - If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then - importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal - sumaAmorticaciones += importeMovimiento - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - IdCtaContable = IdCtaContAnticipos - CveCuenta = CveCuentaAnticipos - CveSubProyectoContabilizar = CveSubProyectoVenta - - If importeMovimiento <> 0 Then - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then - ErrorPrepoliza = True - End If - End If - End If - - End If - - Next - - If sumaAmorticaciones <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, sumaAmorticaciones, Referencia, 251, Concepto, FechaMovimiento, IdCtaContClientes, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=sumaAmorticaciones * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then - ErrorPrepoliza = True - Else - ViewState("SeGuardoPrePoliza") = True - End If - End If - - End If - importeMovimiento = 0 - - Case 4 'Venta Clasificacion - If Not ObjFactura.TipoDocto.Contiene("Rem", "Ant", "Egs", "Dev") Then - - Dim ConceptoContableAplicar = 4 - Dim CveVentaAplicar = ObjFactura.CveVenta - Dim CveVentaAmortizacionAplicar = -1 - - If ObjFactura.TipoDocto.Contiene("Egs") And DdlTipoComprobante.SelectedValue = "Ant" And CveDevolucion > 0 And NuevaFactura = 1 Then - ConceptoContableAplicar = 11 - CveVentaAplicar = CveDevolucion - CveVentaAmortizacionAplicar = ObjFactura.CveVenta - End If - - ' If UsuarioActual.CveEmpresa = 119 Then - - 'código fijo en base el porcentaje iva, que se afecten las clasificaciones - For i = 0 To TmpDTDetalle.Rows.Count - 1 - - 'se excluyen las clasificaciones anteriores para que se asignen las de ingreso - If Not TmpDTDetalle(i)("CveClasificacion").ToString.Contiene("19958", "19933", "18097") Then - - 'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then - ' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then - ' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8% - ' Else - ' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16% - ' End If - - ' Else - ' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0% - ' End If - - 'reclasifica la clasificación del producto, por la del ingreso correspondiente a su iva - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal).Rows.Count > 0 Then - TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal).Rows(0)("CveClasificacion").ToString - End If - - End If - - Next - - ' End If - - DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto"}) - - If DT.Rows.Count > 0 Then - 'Se agrega movimiento separado por la cuenta de ventas (ER) - For Each Row2 As DataRow In DT.Rows - importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal) * ValorMultiplicador - importeMX = importeMovimiento * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - Concepto = $"{ViewState("VentaFolio").ToString} {If(Row2("CveClasificacion").ToString.ToEntero > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"), "")} - {If(Row2("CveSubProyecto").ToString.ToEntero > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString}"), "Sin SubProyecto Asignado")}" - - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - 'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas - If ObjFactura.TipoDocto.Contiene("Egs") Then - IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero - Else - IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero - End If - - - CveCuenta = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresosSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero - - If importeMovimiento <> 0 Then - - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - Else - ViewState("SeGuardoPrePoliza") = True - End If - End If - Next - End If - End If - - importeMovimiento = 0 - Case 150 'Descuento sobre ventas - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - - Dim ConceptoContableAplicar = 150 - Dim CveVentaAplicar = ObjFactura.CveVenta - Dim CveVentaAmortizacionAplicar = -1 - - 'cuando es NC, por amortización de anticipo, no debe de registrar el concepto 11, - 'pero cuando es NC y se aplicó anticipo, debe de restarle el importe - If ObjFactura.TipoDocto.Contiene("Egs") And CveAnticipo > 0 Then - ConceptoContableAplicar = 11 - CveVentaAplicar = CveAnticipo - CveVentaAmortizacionAplicar = ObjFactura.CveVenta - End If - - If UsuarioActual.CveEmpresa = 119 Then - - 'código fijo en base el porcentaje iva, que se afecten las clasificaciones - For i = 0 To TmpDTDetalle.Rows.Count - 1 - - 'se excluyen las clasificaciones anteriores para que se asignen las de ingreso - If Not TmpDTDetalle(i)("CveClasificacion").ToString.Contiene("19958", "19933", "18097") Then - - 'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then - ' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then - ' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8% - ' Else - ' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16% - ' End If - 'Else - ' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0% - 'End If - - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then - TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveClasificacion").ToString - End If - - End If - - Next - - End If - - DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto"}) - - If DT.Rows.Count > 0 Then - 'Se agrega movimiento separado por la cuenta de ventas (ER) - For Each Row2 As DataRow In DT.Rows - importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal) * ValorMultiplicador - importeMX = importeMovimiento * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - Concepto = $"{ViewState("VentaFolio").ToString} {If(Row2("CveClasificacion").ToString.ToEntero > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"), "")} - {If(Row2("CveSubProyecto").ToString.ToEntero > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString}"), "Sin SubProyecto Asignado")}" - - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - 'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero - Else - IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero - End If - - If UsuarioActual.CveEmpresa = 119 Then - If Row2("CveClasificacion").ToString = "19930" Then IdCtaContable = 1141 - If Row2("CveClasificacion").ToString = "19929" Then IdCtaContable = 1142 - End If - - CveCuenta = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresosSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero - - If importeMovimiento <> 0 Then - - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - Else - ViewState("SeGuardoPrePoliza") = True - End If - End If - Next - End If - End If - - importeMovimiento = 0 - Case 103 'Descuento - If Not ObjFactura.TipoDocto.Contiene("Rem") AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "-1" Then - - importeMovimiento = ObjFactura.Descuento * ValorMultiplicador - importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - CveSubProyectoContabilizar = CveSubProyectoVenta - - If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString.ToEntero - 'CveCuenta = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString.ToEntero - End If - End If - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - If importeMovimiento > 0 AndAlso UsuarioActual.CveEmpresa = 119 Then - 'código fijo en base el porcentaje iva, que se afecten las clasificaciones - For i = 0 To TmpDTDetalle.Rows.Count - 1 - 'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then - ' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then - ' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8% - ' Else - ' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16% - ' End If - 'Else - ' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0% - 'End If - - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then - TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveClasificacion").ToString - End If - Next - - End If - - End If - - Case 103 'Descuento - 'si se amortiza anticipo por concepto de descuento, no debe de registrar esta partida. - If DdlTipoAmortizacionAnticipo.SelectedValue <> "1" Then - importeMovimiento = ObjFactura.Descuento * ValorMultiplicador - importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - IdCtaContable = 0 - End If - - Case 8 'Ret IVA por Trasladar - If Not ObjFactura.TipoDocto.Contiene("Rem") Then - importeMovimiento = ObjFactura.RetIVA * ValorMultiplicador - importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - 'Contabilidad ContPAQ - If IdCtaContRetIVA > 0 Then - IdCtaContable = IdCtaContRetIVA - Else - If ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - End If - End If - End If - - 'Contabilidad SIG - If CveCuentaRetIVA > 0 Then - CveCuenta = CveCuentaRetIVA - Else - If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - - Case 9 'Ret ISR por Trasladar - If Not ObjFactura.TipoDocto.Contiene("Rem") Then - importeMovimiento = ObjFactura.RetISR * ValorMultiplicador - importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - 'Contabilidad ContPAQ - If IdCtaContRetISR > 0 Then - IdCtaContable = IdCtaContRetISR - Else - If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - End If - End If - End If - - 'Contabilidad SIG - If CveCuentaRetISR > 0 Then - CveCuenta = CveCuentaRetISR - Else - If ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - End If - Case 13 'Iva por Trasladar - If Not ObjFactura.TipoDocto.Contiene("Rem") Then - importeMovimiento = ObjFactura.IVA * ValorMultiplicador - importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2) - FechaMovimiento = ObjFactura.FechaPago - PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal - IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) - CveCuenta = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - End If - - - Case 38 'IEPS por Trasladar - If Not ObjFactura.TipoDocto.Contiene("Rem") Then - importeMovimiento = ObjFactura.IEPS * ValorMultiplicador - importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2) - FechaMovimiento = ObjFactura.Fecha - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxTrasladar").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxTrasladarSIG").ToString.ToEntero - End If - End If - End If - - - Case 30 'PAGO - BANCOS - If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then - - For Each DrPago As DataRow In DtPagos.Rows - CveIEPago = -1 - - FolioIE = -1 - FolioIE = ObjBancos.GetNextFolio(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero) - If Not FolioIE > 0 Then - ErrorPrepoliza = True - Exit For - End If - - CveIEPago = ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, Fecha, FolioIE.ToString, String.Format("PAGO: {0}", TxtFolio.Text), DrPago("Importe").ToString.ToDouble, DdlMoneda.SelectedValue.ToEntero, tipoCambio, DrPago("Observaciones").ToString, "", False, False, -1, ObjFactura.CvePrePoliza, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) - - If CveIEPago > 0 Then - - importeMovimiento = DrPago("Importe").ToString.ToDecimal * ValorMultiplicador - importeMX = importeMovimiento * tipoCambio * Multiplicador - IdCtaContable = 0 - CveCuenta = 0 - CveSubProyectoContabilizar = CveSubProyectoVenta - Dim PorcentajeImpuestoPago As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal - - - If GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows.Count = 1 Then - IdCtaContable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContable").ToString.ToEntero - CveCuenta = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContableSIG").ToString.ToEntero - End If - - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.AppendFormat("
    {0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.AppendFormat("
    {0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) - CveCuentaContabilizacion = 0 - End If - - 'BANCOS - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - Exit For - End If - - 'CLIENTES - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 2, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 2, Concepto, Fecha, IdCtaContableCliente, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - 'IVA X TRASLADAR - IdCtaIVAXTrasladar = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) - CveCuentaIVAxTrasladar = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 13, Concepto, Fecha, IdCtaIVAXTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVAxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then - ErrorPrepoliza = True - Exit For - End If - - 'IVA PAGADO - IdCtaIVATrasladado = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) - CveCuentaIVATrasladado = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 61, Concepto, Fecha, IdCtaIVATrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVATrasladado, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then - ErrorPrepoliza = True - Exit For - End If - - 'IEPS X TRASLADAR - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - 'IEPS PAGADO - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSTrasladado, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - - Else - ErrorPrepoliza = True - Exit For - End If - - Next - - importeMovimiento = 0 - End If - - - End Select - - If importeMovimiento <> 0 And Not ErrorPrepoliza Then - - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then - ErrorPrepoliza = True - Else - ViewState("SeGuardoPrePoliza") = True - End If - - End If - - If ErrorPrepoliza Then - Exit For - End If - - Next - - End If - - 'Si es Facturacion de una remision cancelamos, traspasamos saldos y agregamos evento a la bitacora - If RemisionesLista.Count > 0 Then - - 'se verifica que el documento que se está generando sea "Ing", "Ant" - If Not ObjFactura.TipoDocto.Contiene("Ing", "Ant") Then - ErrorPrepoliza = True - ErrorList.Add("No se pueden facturar las remisiones, con ese tipo de comprobante seleccionado") - Else - - - For Each CveRemision As Integer In RemisionesLista - If Not ObjConta.TraspasarSaldosRemision(CveRemision, ObjFactura.CvePrePoliza, ObjFactura.CveVenta) Then - ErrorPrepoliza = True - End If - - 'Factura - If Not ObjEventos.AddEventoBitacora($"Sustituye a: Folio Factura", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then - ErrorPrepoliza = True - End If - - 'Remision - If Not ObjEventos.AddEventoBitacora($"Refacturacion en: {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveRemision) Then - ErrorPrepoliza = True - End If - Next - End If - End If - - 'REGRESA SALDO A LAS REMISIONES QUE SE FACTURARON EN EL INGRESO QUE SE ESTA CANCELANDO - If ObjFactura.TipoDocto = "Ing" And ValorMultiplicador = -1 AndAlso NuevaFactura <> 1 AndAlso Not SeCancelaRemisionProceso Then ' se debe de excluir cuando es refacturación - If ObjVentas.GetRemisionesRelacionadas(ObjFactura.CveVenta, ObjFactura.TipoDocto) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - For Each Dr As DataRow In ObjVentas.DtResultados.Rows - Dim Selecciono As Boolean = False - If ChkCanRem.Checked Then - For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows - If Gvr.DataKey("CveVenta").ToEntero = Dr("CveVenta").ToString.ToEntero AndAlso Gvr.FCCheckBox("ChkCancelarRemision").Checked Then - Selecciono = True - End If - Next - End If - If Not Selecciono Then - If Not ObjConta.TraspasarSaldosRemision(Dr("CveVenta").ToString.ToEntero, ObjFactura.CvePrePoliza, ObjFactura.CveVenta, 1) Then - ErrorPrepoliza = True - End If - - 'Remision - If Not ObjEventos.AddEventoBitacora($"Facturación cancelada en: {TxtFolio.Text}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Dr("CveVenta").ToString.ToEntero) Then - ErrorPrepoliza = True - End If - End If - Next - End If - End If - - If NuevaFactura = 1 AndAlso TotalOriginal > TxtTotal.Text.ToDouble AndAlso ObjEventos IsNot Nothing Then - If Not ObjEventos.AddEventoBitacora($"Factura a menor precio de la factura origen.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then - ErrorPrepoliza = True - Else - Alert("Factura a menor precio de la factura origen.", TipoMensaje.MsgAdvertencia) - End If - End If - - - If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 2) Then - If ObjConta.ValorPolizaDescuadre > 0 Then +#Region " GUARDAR - VENTA, PREPOLIZAS, INV, ESTIMACIONES, AC, NOTA DE CRÉDITO " + Private Sub GuardarVenta(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, factura As Modelos.Factura, TmpDTDetalle As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, Optional ByRef ObjOS As ClsOS = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, ByRef Optional ObjCGame As ClsCGame = Nothing, ByRef Optional ObjCliente As ClsClientes = Nothing) + + Dim Msgok As New StringBuilder + Dim CveAlmacenTraspasoOrigen As Integer = -1 + Dim CveAlmacenTraspasoDestino As Integer = -1 + Dim EsDevolucionVenta = -1 + Dim EsInterno As Integer = -1 + + If DdlAlmacenAsignado.Visible Or RequiereAlmacenDestino Then + CveAlmacenTraspasoDestino = DdlAlmacenAsignado.SelectedValue.ToEntero + End If + + If DdlAlmacenOrigen.Visible Or RequiereAlmacenOrigen Then + CveAlmacenTraspasoOrigen = DdlAlmacenOrigen.SelectedValue.ToEntero + End If + + If TrTipoPedido.Visible Then + EsInterno = DdlTipoPedido.SelectedValue.ToEntero() + End If + + 'Si es devolucion revertimos los almacenes + If CvePedido > 0 And TipoContrato = 2 Then + EsDevolucionVenta = 1 + CveAlmacenTraspasoOrigen = DdlAlmacenAsignado.SelectedValue.ToEntero + CveAlmacenTraspasoDestino = DdlAlmacenOrigen.SelectedValue.ToEntero + End If + + 'VALIDA ENTREGA POR ADELANTADO + If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then + 'INCRUSTAMOS ALMACEN ENTREGA POR ADELANTADO CUANDO SEA REMISION Y NO TRAIGA ASIGNADO POR EL USUARIO + If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then + CveAlmacenTraspasoDestino = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString.ToEntero + End If + + 'SI LA SUCURSAL NO TIENE ENTREGA POR ADELANTADO + If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then + ErrorList.Add("Ocurrió un error al seleccionar el almacen de entrega por adelantado de la sucursal.") + End If + End If + Dim TotalImpuestoLocal As Double = 0 + If GvImpuestosLocales2.Rows.Count > 0 Then + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then + If gvr.DataKey("TipoImpuesto") = "5" Then ' cuando es traslado local + TotalImpuestoLocal -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble + Else ' cuando es retención + TotalImpuestoLocal += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble + End If + + End If + End If + Next + End If + + + factura.CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardarVenta", factura.CvePlantillaPoliza, factura.Total, factura.Total, factura.CveMoneda, factura.Fecha, If(CveEmpresaCRM > 0, LblEmpresaCRM.Text, factura.Cliente.Nombre), factura.CveUsuario, factura.CveEmpresa) + If Not ObjVentas.AddVenta(factura.TipoDocto, factura.Folio, factura.CveCliente, factura.CveClienteSucursal, factura.SubTotalTC, factura.DescuentoTC, + factura.AmortizacionTC, factura.IVATC, factura.RetIVATC, factura.RetISRTC, + factura.TotalTC, factura.CveMoneda, factura.TipoCambio, factura.CveMetodoPago, factura.CondicionesPago, factura.FormaPago, factura.FechaPago, factura.Fecha, factura.MotivoDescuento, + factura.Observaciones, factura.FechaEjecucion, factura.CveVendedor, + factura.Alfa1, factura.Alfa2, factura.Alfa3, factura.Num1, factura.Num2, factura.Num3, + factura.Fech1, factura.Fech2, factura.Fech3, factura.CveCorte, factura.CveMesa, factura.NumeroPersonas, factura.CvePrePoliza, factura.CveUsuario, factura.CveEmpresa, + AtencionA:=factura.AtencionA, TelefonoGenerico:=TxtTelefonoGenerico.Text.Trim, CveContrato:=factura.CveContrato, CveVentaPadre:=If(AplicaDevolucion, CveVentaDevolucion, factura.CveVentaPadre), Det_FechaOrdenCompra:=factura.Det_FechaOrdenCompra, Det_OrdenCompra:=factura.Det_OrdenCompra, otros:=factura.Otros, + Entrega:=TxtEntrega.Text, Vigencia:=If(DdlTipoComprobante.SelectedValue = "Cot", TxtFechaVencimientoCotizacion.Text.ToDate, MinFecha), + CveAlmacenTraspasoDestino:=CveAlmacenTraspasoDestino, CveAlmacenTraspasoOrigen:=CveAlmacenTraspasoOrigen, CveDireccionEnvio:=If(DdlDireccionEnvio.Visible, DdlDireccionEnvio.SelectedValue.ToEntero, -1), CveOC:=CveOC, IEPS:=factura.IEPSTC, Serie:=factura.Serie, CveCondicionEntrega:=DdlFormaEntrega.SelectedValue.ToEntero, + PedidoContrato:=TxtPedidoContrato.Text, ObservacionesAlmacen:=TxtObsAlmacen.Text, CveSubProyecto:=factura.CveSubProyecto, CveSubProyectoCobranza:=factura.CveSubProyectoCobranza, CveSubProyectoEjecucion:=factura.CveSubProyectoEjecucion, CveFormaPago33:=factura.CveFormaPago33, + CveMetodoPago33:=factura.CveMetodoPago33, CveUsoCFDI:=factura.CveUsoCFDI, OrdenCompra:=TxtOrdenCompra.Text, CveCuentaTerminal:=DdlCuentasTerminal.SelectedValue.ToEntero, CveTipoRelacion:=factura.CveTipoRelacion, ImpuestoLocal:=TotalImpuestoLocal, + CveVentaRelacion:=(If(factura.CveVentaRelacion.ToEntero > 0, factura.CveVentaRelacion, -1)), ImporteRelacion:=(If(factura.ImporteRelacion <> Nothing, factura.ImporteRelacion, -1)), + CveTipoAmortizacionAnticipo:=factura.CveTipoAmortizacionAnticipo, CveEmpresaCRM:=CveEmpresaCRM, EsInterno:=EsInterno, CveAcercamientoCRM:=CveAcercamientoCRM, + DiasCredito:=factura.DiasCredito, EsDiasCreditoFijo:=factura.EsDiasCreditoFijo, AnticipoEspecial:=If(TrAntEspecial.Visible, ChkAntEspecial.Checked, False)) Then + + ErrorList.Add("Ocurrió un error al Generar la Venta.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") + + End If + + If Not GuardarUsados(ObjVentas.IniciaTransacSQL, ObjVentas.CveVenta) Then + ErrorList.Add("Error al guardar usados") + End If + + + If ErrorList.Count = 0 AndAlso ObjVentas.CveVenta > 0 Then + + factura.CveVenta = ObjVentas.CveVenta + factura.Serie = ObjVentas.Serie + factura.Folio = ObjVentas.Folio + ViewState("VentaFolio") = ObjVentas.SerieFolio + factura.Timbre.Comprobante.Serie = ObjVentas.Serie + factura.Timbre.Comprobante.Folio = ObjVentas.Folio.ToString + + If factura.TipoDocto = "Egs" AndAlso NuevaFactura = 1 Then + If DtVentasNC Is Nothing Then + InicializaDTVentasNC() + End If + CargaNCDT(factura.CveVentaPadre, factura.Total, NuevaFactura:=NuevaFactura, ObjVentas:=ObjVentas) + End If + + 'Se agregan los PS + For Each Row As DataRow In TmpDTDetalle.Rows + If Not ObjVentas.AddVentaDetalle(ObjVentas.CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, + Row("PU").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)))), 6), + Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, + TiempoEntrega:=Row("TiempoEntrega").ToString, CveVentaDetallePadre:=Row("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CvePromocionDetalle:=If(DtPromociones IsNot Nothing, DtPromociones.FiltroPrimeroValor("CvePromocionDetalle", $"CvePS={Row("CvePS").ToString}").ToEntero, -1), + IEPS:=Row("ImporteIEPS").ToString.ToDouble, CveMovimientoDetallePedido:=Row("CveMovimientoDetallePedido").ToString.ToEntero, + ImporteRetIVA:=Row("ImporteRetIVA").ToString.ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString.ToDouble, + PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString.ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString.ToDouble, CuentaPredial:=Row("CuentaPredial").ToString) Then + ErrorList.Add("Ocurrió un error al agregar un Producto o Servicio a la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") + Exit For + Else + + 'Agregamos el gasto de contrato + If CveContrato > 0 AndAlso factura.TipoDocto = "Rem" AndAlso AplicaGastoContrato Then + Dim ObjContrato As New ClsContratos + If Not ObjContrato.AddContratoGasto(CveContrato, Row("PS").ToString, Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, factura.Fecha, UsuarioActual.CveUsuario, CveVenta:=ObjVentas.CveVenta) Then + ErrorList.Add("Ocurrió un error al agregar el gasto de la Factura.") + Exit For + End If + ObjContrato.Dispose() + End If + + 'Si es devolucion se agregan a la tabla de Vta_VentasDetalleDevolucion + If factura.AplicaDevolucion Then + If Not ObjVentas.AddVentaDetalleDevolucion(Row("CveVentaDetalle").ToString.ToEntero, ObjVentas.CveVentaDetalle, Row("Cantidad").ToString.ToDouble) Then + ErrorList.Add("Ocurrió un error al agregar la venta detalle devolucion.") + End If + End If + + Dim TmpDr As DataRow = TmpDT.Select($"Consec = {Row("Consec").ToString}")(0) + TmpDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle + + Try + Dim InvDr As DataRow = DtInv.Select($"Consec = {Row("Consec").ToString}")(0) + InvDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle + Catch ex As Exception + End Try + + End If + Next + + 'Orden Produccion' + If UsuarioActual.CveEmpresa.Contiene(126) Then + If ObjVentas.CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then + If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), ObjVentas.CveVenta) Then + ErrorList.Add("Ocurrió un error al actualizar la orden de producción") + End If + End If + End If + + 'PedidoA' + If ObjVentas.CveVenta > 0 And CvePedidoA > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem") Then + If Not ObjCliente.UpdateEstatusPedido(CvePedidoA, 18, -1, UsuarioActual.CveUsuario) Then + ErrorList.Add("Ocurrió un error al actualizar el estatus del pedidoA") + End If + End If + + 'Actualiar el estatus de la venta refacturada + If ObjVentas.CveVenta > 0 AndAlso NuevaFactura = 1 AndAlso CveDevolucion > 0 Then + + 'If CveEstatusRefacturacion = 1 Then CveEstatusRefacturacion = 2 'cuando viene del proceso de refacturación con aceptació + If Not ObjVentas.UpdateEstatusRefacturacion(CveDevolucion, 2) Then ' se marca como refacturada + ErrorList.Add("Ocurrió un error al actualizar el estatus de la refacturacion") + End If + End If + + 'Pedido2' + If ObjVentas.CveVenta > 0 And CvePedido2 > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem", "PA") Then + If Not ObjCliente.UpdateEstatusPedido(CvePedido2, 21, -1, UsuarioActual.CveUsuario) Then + ErrorList.Add("Ocurrió un error al actualizar el estatus del pedido2") + End If + End If + + 'Si viene de OS, Se guarda CveVenta en OS + If CveOS > 0 Then + If Not ObjOS.UpdateVentaOS(factura.CveVenta, CveOS) Then + ErrorList.Add("Ocurrió un error al guardar la venta en Ordenes de Servicio") + End If + End If + + 'Contratos + If factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing") Then + GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, 1) + ElseIf factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then + GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, -1) + End If + + 'Impuestos Locales + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then + If Not ObjVentas.AddVentaImpuestoLocales(factura.CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1))) Then + ErrorList.Add("Ocurrió un error al Guardar Impuestos Locales") + End If + End If + End If + Next + + If DTmpF.Rows.Count > 0 Then + For Each Row As DataRow In DTmpF.Rows + If Not ObjVentas.AddVentasFirmas(factura.CveVenta, Row("Titulo").ToString, Row("Nombre").ToString, Row("Puesto").ToString, Row("Lado").ToString.ToEntero) Then + ErrorList.Add("Ocurrio un error al Guardar Firmas") + End If + Next + End If + + 'registro los metodos de pago, cuando hay corte. + If factura.CveCorte > 0 Then + 'cuando es contado + If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then + For Each DrPago As DataRow In DtPagos.Rows + If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, DrPago("CveMetodoPago").ToString.ToEntero, DrPago("Importe").ToString.ToDouble) Then + ErrorList.Add("Ocurrio un error al guardar los metodos de pago") + End If + Next + Else + 'cuando es crédito o terminal + If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, 7, TxtTotal.Text.ToDouble) Then + ErrorList.Add("Ocurrio un error al guardar los metodos de pago") + End If + End If + + End If + + + 'cuando es contado + 'If factura.CveCorte > 0 Then + ' If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then + ' For Each DrPago As DataRow In DtPagos.Rows + ' If ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, TxtFechaPago.Text.ToDate, DrPago("Folio").ToString, "", DrPago("Importe").ToString.ToDouble, DdlMoneda.SelectedValue.ToEntero, If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then + ' ErrorList.Add("Ocurrio un error al guardar los metodos de pago") + ' End If + ' Next + ' 'Else + ' ' 'cuando es crédito o terminal + ' ' If ObjBancos.AddBancos_IE(, 7, TxtFechaPago.Text.ToDate, TxtFolio.Text.ToString, "", TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then + ' ' ErrorList.Add("Ocurrio un error al guardar los metodos de pago") + ' ' End If + ' End If + 'End If + + + + 'INE COMPLEMENTOS + If ObjFactura.ComplementoINE IsNot Nothing Then + If Not ObjVentas.UpdateVentasComplementos(ObjFactura.CveVenta, ObjFactura.ComplementoINE.INETipoProceso, ObjFactura.ComplementoINE.INETipoComite, ObjFactura.ComplementoINE.INEIdContabilidad.ToString) Then + ErrorList.Add("Ocurrio un error al guardar los complementos") + End If + End If + + If ErrorList.Count = 0 Then + 'Agregamos las remisiones a la tabla + If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then + Dim CveVentaDetalle As Integer = 0 + Dim CveVentaDetallePadre As Integer = 0 + Dim Cantidad As Decimal = 0 + Dim CvePS As Integer = 0 + Dim PU As Decimal = 0 + + For Each row As DataRow In DtRemisionesPS.Rows + Cantidad = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal + CvePS = DtRemisionesTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero + PU = DtRemisionesTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal + CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero + CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero + + If Not ObjVentas.AgregarRemisionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then + ErrorList.Add("Ocurrió un error al agregar el detalle de la Remision") + End If + Next + + End If + + If DTRemisiones IsNot Nothing AndAlso DTRemisiones.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then + + Dim dt As DataTable = DTRemisiones.FiltraParametros("Aplicado = True") + If dt.Rows.Count > 0 Then + For Each row As DataRow In dt.Rows + If Not ObjVentas.UpdateVentaRemision(row("CveVenta").ToString.ToEntero, ObjFactura.CveVenta) Then + ErrorList.Add("Ocurrió un error al actualizar la remisión") + End If + Next + End If + End If + End If + + If ErrorList.Count = 0 Then + 'Agregamos los pedidos2 a la tabla + If DtPedidos2PS IsNot Nothing AndAlso DtPedidos2PS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then + Dim CveVentaDetalle As Integer = 0 + Dim CveVentaDetallePadre As Integer = 0 + Dim Cantidad As Decimal = 0 + Dim CvePS As Integer = 0 + Dim PU As Decimal = 0 + + For Each row As DataRow In DtPedidos2PS.Rows + Cantidad = DtPedidos2TmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal + CvePS = DtPedidos2TmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero + PU = DtPedidos2TmpDT.FiltroPrimeroValor("PU", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal + CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero + CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero + + If Not ObjVentas.AddVentaDetallePedido2(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then + ErrorList.Add("Ocurrió un error al agregar el detalle del Pedido2") + End If + Next + End If + + If DtPedidos2 IsNot Nothing AndAlso DtPedidos2.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then + Dim dt As DataTable = DtPedidos2.FiltraParametros("Aplicado = True") + If dt.Rows.Count > 0 Then + For Each row As DataRow In dt.Rows + If Not ObjVentas.UpdateVentaPedido2(row("CveVenta").ToString.ToEntero, ObjFactura.CveVenta) Then + ErrorList.Add("Ocurrió un error al actualizar el Pedido2") + End If + Next + End If + End If + End If + + + If ErrorList.Count = 0 Then + 'prepoliza + GuardarVentaPrePolizas(ObjConta, factura, TmpDTDetalle, CveNCaVincular, objContPaqi, ObjBancos, ObjVentas, ObjEventos:=ObjEventos) + If ErrorList.Count = 0 Then + 'inventarios + If GuardarVentaInventarios(ObjInventario, ObjConta, factura) Then + ErrorList.Add("Ocurrio un error al Guardar Inventario") + End If + If ErrorList.Count = 0 Then + 'estimaciones + GuardarVentaEstimaciones(ObjContr, factura) + If ErrorList.Count = 0 Then + 'armonizaccionContable + GuardarVentaAC(ObjVentas, factura, Msgok, objContPaqi) + If ErrorList.Count = 0 Then + 'Impuestos Locales + If GuardarVentaImpuestosLocales(ObjVentas, ObjConta, factura) Then + ErrorList.Add("Ocurrio un error al Guardar Impuestos Locales") + End If + End If + End If + End If + End If + End If + + End If + End Sub + Private Sub GuardarVentaPrePolizas(ByRef ObjConta As ClsContabilidad, factura As Modelos.Factura, TmpDTDetalleMovimientos As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing) + + Dim CveIE As Integer = -1 + Dim DT As DataTable = Nothing + + + Dim CveConceptoAfectacion As Integer = 1 'Cliente + Dim CveConceptoAntCli As Integer = 3 'Anticipo Cliente + Dim CveConceptoVenta As Integer = 4 'Venta + Dim CveConceptoCanAnt As Integer = 11 'Cancelacion Anticipos + Dim CveConceptoDSV As Integer = 12 ' DSV + Dim CveConceptoIVA As Integer = 13 'IVA Trasladado + Dim CveConceptoRetIVA As Integer = 8 'Ret IVA + Dim CveConceptoRetISR As Integer = 9 'Ret ISR + + 'P R E P O L I Z A S + If DdlTipoComprobante.SelectedValue <> "Cot" Then + If factura.CvePrePoliza > 0 Then + + If ProcesoPrepolizas(ObjConta, factura, CveIE, TmpDTDetalleMovimientos, objContPaqi, 1, ObjBancos, ObjVentas, ObjEventos:=ObjEventos) Then + ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") + End If + + Else + ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") + End If + End If + End Sub + Private Function ProcesoPrepolizas(ByRef ObjConta As ClsContabilidad, ObjFactura As Modelos.Factura, CveIE As Integer, TmpDTDetalle As DataTable, ByRef objContPaqi As ClsContPAQi, Optional ValorMultiplicador As Integer = 1, ByRef Optional ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing) As Boolean + Try + Dim DT As DataTable + Dim CvePlantilaPoliza As Integer + Dim PorcentajeAmortizacion As Decimal = 0 + Dim sumaAmorticaciones As Decimal = 0 + Dim ErrorPrepoliza As Boolean = False + Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " + Dim CveCuentaContabilizacion As Integer = 1 + Dim tipoCambio As Decimal + + Dim CuentasContablesInvalidasSIG As New StringBuilder + + If ObjFactura.TipoDocto = "Ing" Or ObjFactura.TipoDocto = "Ant" Or ObjFactura.TipoDocto = "Com" Then + CvePlantilaPoliza = 4 + ElseIf ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + CvePlantilaPoliza = 7 + ElseIf ObjFactura.TipoDocto = "Rem" Then + CvePlantilaPoliza = 4 + End If + + If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then + tipoCambio = ObjFactura.TipoCambio + ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then + tipoCambio = GlobalTipoCambio(ObjFactura.Fecha).ToString.ToDecimal + Else + tipoCambio = 1 + End If + + Dim ConceptoContable As Integer + Dim TipoMovimiento As Boolean + Dim importeMovimiento As Decimal + Dim FechaMovimiento As Date = ObjFactura.Fecha + Dim IdCtaContable As Integer + Dim CveCuenta As Integer + Dim IdCtaContableCliente As Integer + Dim CveCuentaCliente As Integer + Dim Concepto As String = ViewState("VentaFolio").ToString + Dim Referencia As String = ViewState("VentaFolio").ToString + Dim Fecha = TxtFecha.Text.Trim.ToDate + + Dim importeMX As Decimal + Dim Multiplicador As Integer + Dim CveIEPago As Integer + Dim FolioIE As Long + Dim CveIEAnticipo As Integer + Dim CveSubProyectoVenta = DdlSubProyectoDatos.SelectedValue.ToEntero + Dim CveSubProyectoContabilizar As Integer + Dim IdCtaIVAXTrasladar As Integer = 0 + Dim IdCtaIVATrasladado As Integer = 0 + Dim CveCuentaIVAxTrasladar As Integer = 0 + Dim CveCuentaIVATrasladado As Integer = 0 + Dim SeContabiliza As Boolean = True + If (UsuarioActual.Empresa.Funcionalidad(343) = "1" AndAlso ObjFactura.TipoDocto = "Ant") Or (ChkAntEspecial.Checked AndAlso ObjFactura.TipoDocto = "Ant") Then + SeContabiliza = False + End If + + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then + IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero + CveCuentaIVAxTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVAXTrasladar").ToString.ToEntero + IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero + CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero + End If + + Dim UsaComplementariaClientes As Boolean = False + If UsuarioActual.CveEmpresa.Contiene(1, 119) Then UsaComplementariaClientes = True + + If ObjConta.GetPlantillaConceptos(ObjFactura.CveEmpresa, CvePlantilaPoliza) Then + Dim dtt As DataTable = ObjConta.DtResultados + If ValorMultiplicador = -1 Then dtt = ObjConta.DtResultados.FiltraParametros("", "Orden DESC") ' se ordena contrario al registro para llevar los saldos correctos + For Each Row As DataRow In dtt.Rows + + ConceptoContable = Row("CveConcepto").ToString.ToEntero + TipoMovimiento = If(Row("TipoMovto").ToString = "True", True, False) + importeMovimiento = 0 + IdCtaContable = 0 + CveCuenta = 0 + CveSubProyectoContabilizar = 0 + Multiplicador = (Row("Multiplicador").ToString.ToEntero) + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, ConceptoContable, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", "") + Dim PorcentajeImpuesto As Decimal = 0 + + + + Select Case ConceptoContable + Case 1 'Cliente + If Not ObjFactura.TipoDocto.Contiene("Egs", "Rem") Then + importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + CveSubProyectoContabilizar = CveSubProyectoVenta + 'If ObjFactura.TipoDocto.Contiene("Ant") Then + ' TipoMovimiento = Not TipoMovimiento 'lo contrario a ingreso, en este caso es anticipo + 'End If + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + If tipoCambio = 1 Then + IdCtaContable = ObjFactura.Cliente.IdCtaContClientes + CveCuenta = ObjFactura.Cliente.CveCuentaClientes + Else + IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria + CveCuenta = 0 + + If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsaComplementariaClientes) Then + importeMX = importeMovimiento + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera + CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera + End If + IdCtaContableCliente = IdCtaContable + CveCuentaCliente = CveCuenta + End If + + Case 3 'Cliente + + If ObjFactura.TipoDocto = "Ant" Then + ConceptoContable = If(UsuarioActual.CveEmpresa.Contiene(1, 119), 95, ConceptoContable) + importeMovimiento = ObjFactura.SubTotal * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + IdCtaContable = ObjFactura.Cliente.IdCtaContAnticipos + CveCuenta = ObjFactura.Cliente.CveCuentaAnticipos + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + End If + Case 190 'Remisión del cliente + + If ObjFactura.TipoDocto = "Rem" Then + importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + If tipoCambio = 1 Then + IdCtaContable = ObjFactura.Cliente.IdCtaContClientes + CveCuenta = ObjFactura.Cliente.CveCuentaClientes + Else + IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera + CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera + End If + IdCtaContableCliente = IdCtaContable + CveCuentaCliente = CveCuenta + + If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 190, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 193, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + Else + ErrorPrepoliza = True + End If + + importeMovimiento = 0 + ViewState("SeGuardoPrePoliza") = True + End If + + Case 12 'Nota de Credito + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + importeMovimiento = ObjFactura.Total * ValorMultiplicador + importeMX = (importeMovimiento * tipoCambio * Multiplicador).RoundSQL + FechaMovimiento = ObjFactura.FechaPago + Dim ImporteConcepto12 As Decimal = 0 + Dim ImporteAcumulado91 As Decimal = 0 + Dim CveUltimaVenta As Integer = 0 + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + If tipoCambio = 1 Then + IdCtaContable = ObjFactura.Cliente.IdCtaContClientes + CveCuenta = ObjFactura.Cliente.CveCuentaClientes + ElseIf UsaComplementariaClientes Then + + IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria + CveCuenta = 0 + + If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsaComplementariaClientes) Then + importeMX = importeMovimiento + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + End If + + IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera + CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera + End If + CveSubProyectoContabilizar = CveSubProyectoVenta + ImporteConcepto12 = importeMX.RoundSQL + If importeMovimiento <> 0 Then + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Else + ViewState("SeGuardoPrePoliza") = True + End If + End If + importeMovimiento = 0 + + If ValorMultiplicador = 1 Then + + Dim IdCtaContableClienteComplementaria As Integer = ObjFactura.Cliente.IdCtaContComplementaria + Dim TipoCambioNC As Decimal = 1 + If tipoCambio > 1 Then + TipoCambioNC = tipoCambio + Else + TipoCambioNC = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal + End If + + 'APLICA NC SALDOS DIRECTOS + If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then + For Each Dr As DataRow In DtVentasNC.Rows + + + Dim Importe91 As Decimal = 0 + Dim ImporteMN91 As Decimal = 0 + Dim Importe251 As Decimal = 0 + Dim ImporteMN251 As Decimal = 0 + + If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + Importe251 = Dr("Importe").ToString.ToDecimal + Importe91 = Dr("Importe").ToString.ToDecimal + ImporteMN91 = Dr("Importe").ToString.ToDecimal + TipoCambioNC = 1 + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + Importe251 = Dr("Importe").ToString.ToDecimal + Importe91 = Dr("Importe").ToString.ToDecimal + ImporteMN91 = Dr("Importe").ToString.ToDecimal * TipoCambioNC + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + Importe251 = Dr("Importe").ToString.ToDecimal + Importe91 = Dr("Importe").ToString.ToDecimal + ImporteMN91 = Dr("Importe").ToString.ToDecimal * TipoCambioNC + ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + Importe251 = Dr("Importe").ToString.ToDecimal + Importe91 = Dr("Importe").ToString.ToDecimal + ImporteMN91 = Dr("Importe").ToString.ToDecimal + End If + + Dim TCFluctuacion As Decimal = Dr("TCCambioValuacion").ToString.ToDecimal + If TCFluctuacion = 1 AndAlso TipoCambioNC > 1 Then + TCFluctuacion = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal + End If + + If DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + ImporteMN251 = Dr("Importe").ToString.ToDecimal * TCFluctuacion + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + ImporteMN251 = Dr("Importe").ToString.ToDecimal * TCFluctuacion + ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + ImporteMN251 = Dr("Importe").ToString.ToDecimal / TipoCambioNC + Else + ImporteMN251 = Dr("Importe").ToString.ToDecimal + End If + + Importe251 = (Importe251 * Multiplicador).RoundSQL + + Importe91 = (Importe91 * ValorMultiplicador).RoundSQL + ImporteMN91 = (ImporteMN91 * Multiplicador).RoundSQL + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${Importe91.FormatoNumero(2)}" + + CveUltimaVenta = Dr("CveVenta").ToString.ToEntero + + Dim ImporteComplementarioIngreso As Decimal = 0 + If UsaComplementariaClientes = True AndAlso tipoCambio > 1 Then + ImporteMN91 = Importe91 + ImporteComplementarioIngreso = ((Importe91 * tipoCambio) - Importe91).RoundSQL + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteComplementarioIngreso, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=Dr("TCCambioValuacion").ToString.ToDecimal) Then + ErrorPrepoliza = True + Exit For + End If + End If + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteMN91, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then + ErrorPrepoliza = True + Exit For + End If + ImporteAcumulado91 += (ImporteMN91).RoundSQL + + If UsaComplementariaClientes = True AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then + ImporteMN251 = Importe251 + Dim ImporteComplementarioNC As Decimal = ((Importe251 * Dr("TCCambioValuacion").ToString.ToDecimal) - Importe251).RoundSQL + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=Dr("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementarioNC, ImporteME:=If(Dr("TCCambioValuacion").ToString.ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString.ToDecimal) Then + ErrorPrepoliza = True + Exit For + End If + End If + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=Dr("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteMN251, ImporteME:=If(Dr("TCCambioValuacion").ToString.ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString.ToDecimal, TipoCambioPago:=tipoCambio) Then + ErrorPrepoliza = True + Exit For + End If + + + 'considero fluctuación. + + + If TipoCambioNC <> TCFluctuacion AndAlso TCFluctuacion > 1 AndAlso TipoCambioNC > 1 Then + Dim difFluctuacion As Decimal = TipoCambioNC - TCFluctuacion + Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida + Dim TipoMovtoFluctua As Boolean = True + Dim IdCtaContableFluctua As Integer + If difFluctuacion < 0 Then + CveConceptoFluctua = 65 + TipoMovtoFluctua = False + IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + Else + CveConceptoFluctua = 64 + TipoMovtoFluctua = True + IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + End If + Dim ImporteFluctuacion As Decimal = Math.Abs((Importe251 * difFluctuacion).RoundSQL) + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=TipoCambioNC, TipoCambioPago:=Dr("TCCambioValuacion").ToString.ToDecimal, CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + Exit For + End If + End If + + Next + + If ImporteConcepto12 < ImporteAcumulado91 Then + Dim ImporteOtrosIngresos As Decimal = ImporteConcepto12 - ImporteAcumulado91 + If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ImporteOtrosIngresos, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveUltimaVenta, ImporteMX:=ImporteOtrosIngresos, ImporteME:=0, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ImporteOtrosIngresos, Referencia, 211, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteME:=0, ImporteMX:=ImporteOtrosIngresos, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + Else + ErrorPrepoliza = True + End If + End If + + If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 5) Then + If ObjConta.ValorPolizaDescuadre > 0 Then + 'ErrorPrepoliza = True + GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") + + 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA + 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then + ' Dim DtTest = ObjConta.DtResultados + 'End If + End If + End If + + + If ErrorPrepoliza Then + Exit For + End If + End If + + 'APLICA DEVOLUCION SALDOS DIRECTOS + If AplicaDevolucion Then + Dim importeMovimientoDev = TxtTotal.Text.ToDecimal + importeMovimientoDev = If(SaldoVentaDevolucion < importeMovimientoDev, SaldoVentaDevolucion, importeMovimientoDev) + If importeMovimientoDev > 0 Then + Dim importeMXDev = importeMovimientoDev * tipoCambio * Multiplicador + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimientoDev.FormatoNumero(2)}" + + If UsaComplementariaClientes AndAlso tipoCambio > 1 Then + importeMXDev = importeMovimientoDev + Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * tipoCambio) - importeMovimientoDev).RoundSQL + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteComplementaria, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura) Then + ErrorPrepoliza = True + Exit For + End If + End If + + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + If UsaComplementariaClientes AndAlso TipoCambioFactura > 1 Then + importeMXDev = importeMovimientoDev + Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * TipoCambioFactura) - importeMovimientoDev).RoundSQL + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementaria, ImporteME:=If(TipoCambioFactura = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=TipoCambioFactura) Then + ErrorPrepoliza = True + Exit For + End If + End If + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + If tipoCambio <> TipoCambioFactura Then + Dim difFluctuacion As Decimal = tipoCambio - TipoCambioFactura + Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida + Dim TipoMovtoFluctua As Boolean = True + Dim IdCtaContableFluctua As Integer + If difFluctuacion < 0 Then + CveConceptoFluctua = 65 + TipoMovtoFluctua = False + IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + Else + CveConceptoFluctua = 64 + TipoMovtoFluctua = True + IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + End If + Dim ImporteFluctuacion As Decimal = Math.Abs((importeMovimientoDev * difFluctuacion).RoundSQL) + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura, CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + Exit For + End If + End If + + If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 5) Then + If ObjConta.ValorPolizaDescuadre > 0 Then + 'ErrorPrepoliza = True + GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") + + 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA + 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then + ' Dim DtTest = ObjConta.DtResultados + 'End If + End If + End If + + End If + End If + End If + End If + Case 136 'Otros Conceptos Dinamicos + For Each row2 As GridViewRow In GVOtrosConceptos.Rows + If row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal > 0 Then + + importeMovimiento = row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal * ValorMultiplicador + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + If row2.DataKey("IdCtaContable").ToEntero > 0 Then + IdCtaContable = row2.DataKey("IdCtaContable").ToEntero + Else + If ObjConta.GetRetCuenta(row2.DataKey("CveConceptoContable").ToEntero, ObjFactura.CveCliente) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContFondoGarantia").ToString.ToEntero + End If + End If + End If + + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, If(row2.DataKey("TipoMovto").ToString = "True", True, False), importeMovimiento, Referencia, row2.DataKey("CveConceptoContable").ToEntero, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + End If + + End If + Next + importeMovimiento = 0 + + Case 11 'Anticipo + + '[IPP] SI ES REFACTURACION LOS ANTICIPOS NO LOS DEBE APLICAR EN EL INGRESO REFACTURADO (VIEJO) + If NuevaFactura = 1 And ObjFactura.CveVenta = CveDevolucion Then + Exit Select + End If + + If ObjFactura.TipoDocto = "Ing" AndAlso ValorMultiplicador = -1 Then + For Each row2 As GridViewRow In GvAntNC.Rows + If row2.DataKey("CveConceptoContable").ToString().ToEntero = 11 Then + importeMovimiento = row2.DataKey("Importe").ToString().ToDecimal * ValorMultiplicador '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + IdCtaContable = IdCtaContAnticipos + CveCuenta = CveCuentaAnticipos + CveSubProyectoContabilizar = CveSubProyectoVenta + + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + Else + ViewState("SeGuardoPrePoliza") = True + End If + End If + + End If + Next + End If + + 'cuando es anticipo + ' cuando es amortización de nota de crédito, y es la nc + ' cuando es amortización por descuento, y es el ingreso + ' cuando es amortización en cero + If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 2 AndAlso ObjFactura.TipoDocto.Contiene("Egs") OrElse + DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 1 AndAlso ObjFactura.TipoDocto.Contiene("Ing") OrElse + DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 3 Then + + For Each row2 As GridViewRow In GVAnticipos.Rows + If row2.DataKey("CveConceptoContable").ToString().ToEntero = 3 Then + If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then + CveIEAnticipo = row2.DataKey("CveIE").ToString.ToEntero + importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + IdCtaContable = IdCtaContAnticipos + CveCuenta = CveCuentaAnticipos + CveSubProyectoContabilizar = CveSubProyectoVenta + + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Exit For + Else + ViewState("SeGuardoPrePoliza") = True + End If + End If + + End If + End If + Next + + End If + 'Cuando la funcionalidad de amortizacion en PS esta activa + If Not ErrorPrepoliza Then + DT = TmpDTDetalle.FiltraParametros($"CvePS = {CvePSAmortizacion}") + If DT.Rows.Count > 0 Then + For Each Row2 As DataRow In DT.Rows + importeMovimiento = Math.Abs(Row2("PU").ToString.ToDecimal) + IdCtaContable = IdCtaContAnticipos + CveCuenta = CveCuentaAnticipos + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + If importeMovimiento <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Else + ViewState("SeGuardoPrePoliza") = True + End If + End If + Next + End If + End If + + 'PorcentajeAmortizacion = sumaAmorticaciones / TxtTotal.Text.ToDecimal + importeMovimiento = 0 + + Case 91 'Amortizacion Nota de Credito + Dim Contabilizable = If(UsuarioActual.CveEmpresa = 119, False, True) + + If ValorMultiplicador = -1 Then + 'cuando es cancelación + For Each row2 As GridViewRow In GvNC.Rows + + If row2.DataKey("CveConceptoContable").ToString().ToEntero = 91 Then + + importeMovimiento = row2.DataKey("Importe").ToDecimal * ValorMultiplicador + sumaAmorticaciones += importeMovimiento + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + 'CTACONTABLE + 'IdCtaContable = IdCtaContAnticipos + 'CveCuenta = CveCuentaAnticipos + IdCtaContable = ObjFactura.Cliente.IdCtaContClientes + CveCuenta = ObjFactura.Cliente.CveCuentaClientes + + CveSubProyectoContabilizar = CveSubProyectoVenta + + If importeMovimiento <> 0 Then + + If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimiento, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVentaNC").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimiento, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString.ToEntero, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then + ErrorPrepoliza = True + Exit For + End If + Else + ErrorPrepoliza = True + Exit For + End If + + 'If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString.ToEntero, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then + ' ErrorPrepoliza = True + 'End If + End If + End If + Next + + Else + For Each row2 As GridViewRow In GVAnticipos.Rows + + If row2.DataKey("CveConceptoContable").ToString().ToEntero = 12 Then + + If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then + importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal + sumaAmorticaciones += importeMovimiento + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + IdCtaContable = IdCtaContAnticipos + CveCuenta = CveCuentaAnticipos + CveSubProyectoContabilizar = CveSubProyectoVenta + + If importeMovimiento <> 0 Then + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then + ErrorPrepoliza = True + End If + End If + End If + + End If + + Next + + If sumaAmorticaciones <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, sumaAmorticaciones, Referencia, 251, Concepto, FechaMovimiento, IdCtaContClientes, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=sumaAmorticaciones * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then + ErrorPrepoliza = True + Else + ViewState("SeGuardoPrePoliza") = True + End If + End If + + End If + importeMovimiento = 0 + + Case 4 'Venta Clasificacion + If Not ObjFactura.TipoDocto.Contiene("Rem", "Ant", "Egs", "Dev") Then + + Dim ConceptoContableAplicar = 4 + Dim CveVentaAplicar = ObjFactura.CveVenta + Dim CveVentaAmortizacionAplicar = -1 + + If ObjFactura.TipoDocto.Contiene("Egs") And DdlTipoComprobante.SelectedValue = "Ant" And CveDevolucion > 0 And NuevaFactura = 1 Then + ConceptoContableAplicar = 11 + CveVentaAplicar = CveDevolucion + CveVentaAmortizacionAplicar = ObjFactura.CveVenta + End If + + ' If UsuarioActual.CveEmpresa = 119 Then + + 'código fijo en base el porcentaje iva, que se afecten las clasificaciones + For i = 0 To TmpDTDetalle.Rows.Count - 1 + + 'se excluyen las clasificaciones anteriores para que se asignen las de ingreso + If Not TmpDTDetalle(i)("CveClasificacion").ToString.Contiene("19958", "19933", "18097") Then + + 'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then + ' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then + ' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8% + ' Else + ' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16% + ' End If + + ' Else + ' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0% + ' End If + + 'reclasifica la clasificación del producto, por la del ingreso correspondiente a su iva + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal).Rows.Count > 0 Then + TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal).Rows(0)("CveClasificacion").ToString + End If + + End If + + Next + + ' End If + + DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto"}) + + If DT.Rows.Count > 0 Then + 'Se agrega movimiento separado por la cuenta de ventas (ER) + For Each Row2 As DataRow In DT.Rows + importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal) * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + Concepto = $"{ViewState("VentaFolio").ToString} {If(Row2("CveClasificacion").ToString.ToEntero > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"), "")} - {If(Row2("CveSubProyecto").ToString.ToEntero > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString}"), "Sin SubProyecto Asignado")}" + + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + 'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas + If ObjFactura.TipoDocto.Contiene("Egs") Then + IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero + Else + IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero + End If + + + CveCuenta = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresosSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero + + If importeMovimiento <> 0 Then + + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + Else + ViewState("SeGuardoPrePoliza") = True + End If + End If + Next + End If + End If + + importeMovimiento = 0 + Case 150 'Descuento sobre ventas + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + + Dim ConceptoContableAplicar = 150 + Dim CveVentaAplicar = ObjFactura.CveVenta + Dim CveVentaAmortizacionAplicar = -1 + + 'cuando es NC, por amortización de anticipo, no debe de registrar el concepto 11, + 'pero cuando es NC y se aplicó anticipo, debe de restarle el importe + If ObjFactura.TipoDocto.Contiene("Egs") And CveAnticipo > 0 Then + ConceptoContableAplicar = 11 + CveVentaAplicar = CveAnticipo + CveVentaAmortizacionAplicar = ObjFactura.CveVenta + End If + + If UsuarioActual.CveEmpresa = 119 Then + + 'código fijo en base el porcentaje iva, que se afecten las clasificaciones + For i = 0 To TmpDTDetalle.Rows.Count - 1 + + 'se excluyen las clasificaciones anteriores para que se asignen las de ingreso + If Not TmpDTDetalle(i)("CveClasificacion").ToString.Contiene("19958", "19933", "18097") Then + + 'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then + ' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then + ' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8% + ' Else + ' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16% + ' End If + 'Else + ' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0% + 'End If + + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then + TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveClasificacion").ToString + End If + + End If + + Next + + End If + + DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto"}) + + If DT.Rows.Count > 0 Then + 'Se agrega movimiento separado por la cuenta de ventas (ER) + For Each Row2 As DataRow In DT.Rows + importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal) * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + Concepto = $"{ViewState("VentaFolio").ToString} {If(Row2("CveClasificacion").ToString.ToEntero > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"), "")} - {If(Row2("CveSubProyecto").ToString.ToEntero > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString}"), "Sin SubProyecto Asignado")}" + + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + 'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero + Else + IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero + End If + + If UsuarioActual.CveEmpresa = 119 Then + If Row2("CveClasificacion").ToString = "19930" Then IdCtaContable = 1141 + If Row2("CveClasificacion").ToString = "19929" Then IdCtaContable = 1142 + End If + + CveCuenta = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresosSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero + + If importeMovimiento <> 0 Then + + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}")) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + Else + ViewState("SeGuardoPrePoliza") = True + End If + End If + Next + End If + End If + + importeMovimiento = 0 + Case 103 'Descuento + If Not ObjFactura.TipoDocto.Contiene("Rem") AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "-1" Then + + importeMovimiento = ObjFactura.Descuento * ValorMultiplicador + importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + CveSubProyectoContabilizar = CveSubProyectoVenta + + If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString.ToEntero + 'CveCuenta = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString.ToEntero + End If + End If + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + If importeMovimiento > 0 AndAlso UsuarioActual.CveEmpresa = 119 Then + 'código fijo en base el porcentaje iva, que se afecten las clasificaciones + For i = 0 To TmpDTDetalle.Rows.Count - 1 + 'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then + ' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then + ' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8% + ' Else + ' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16% + ' End If + 'Else + ' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0% + 'End If + + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then + TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveClasificacion").ToString + End If + Next + + End If + + End If + + Case 103 'Descuento + 'si se amortiza anticipo por concepto de descuento, no debe de registrar esta partida. + If DdlTipoAmortizacionAnticipo.SelectedValue <> "1" Then + importeMovimiento = ObjFactura.Descuento * ValorMultiplicador + importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + IdCtaContable = 0 + End If + + Case 8 'Ret IVA por Trasladar + If Not ObjFactura.TipoDocto.Contiene("Rem") Then + importeMovimiento = ObjFactura.RetIVA * ValorMultiplicador + importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + 'Contabilidad ContPAQ + If IdCtaContRetIVA > 0 Then + IdCtaContable = IdCtaContRetIVA + Else + If ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + End If + End If + End If + + 'Contabilidad SIG + If CveCuentaRetIVA > 0 Then + CveCuenta = CveCuentaRetIVA + Else + If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + + Case 9 'Ret ISR por Trasladar + If Not ObjFactura.TipoDocto.Contiene("Rem") Then + importeMovimiento = ObjFactura.RetISR * ValorMultiplicador + importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + 'Contabilidad ContPAQ + If IdCtaContRetISR > 0 Then + IdCtaContable = IdCtaContRetISR + Else + If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + End If + End If + End If + + 'Contabilidad SIG + If CveCuentaRetISR > 0 Then + CveCuenta = CveCuentaRetISR + Else + If ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + End If + Case 13 'Iva por Trasladar + If Not ObjFactura.TipoDocto.Contiene("Rem") Then + importeMovimiento = ObjFactura.IVA * ValorMultiplicador + importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2) + FechaMovimiento = ObjFactura.FechaPago + PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal + IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) + CveCuenta = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + End If + + + Case 38 'IEPS por Trasladar + If Not ObjFactura.TipoDocto.Contiene("Rem") Then + importeMovimiento = ObjFactura.IEPS * ValorMultiplicador + importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2) + FechaMovimiento = ObjFactura.Fecha + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxTrasladar").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxTrasladarSIG").ToString.ToEntero + End If + End If + End If + + + Case 30 'PAGO - BANCOS + If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then + + For Each DrPago As DataRow In DtPagos.Rows + CveIEPago = -1 + + FolioIE = -1 + FolioIE = ObjBancos.GetNextFolio(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero) + If Not FolioIE > 0 Then + ErrorPrepoliza = True + Exit For + End If + + CveIEPago = ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, Fecha, FolioIE.ToString, String.Format("PAGO: {0}", TxtFolio.Text), DrPago("Importe").ToString.ToDouble, DdlMoneda.SelectedValue.ToEntero, tipoCambio, DrPago("Observaciones").ToString, "", False, False, -1, ObjFactura.CvePrePoliza, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) + + If CveIEPago > 0 Then + + importeMovimiento = DrPago("Importe").ToString.ToDecimal * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + IdCtaContable = 0 + CveCuenta = 0 + CveSubProyectoContabilizar = CveSubProyectoVenta + Dim PorcentajeImpuestoPago As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal + + + If GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows.Count = 1 Then + IdCtaContable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContable").ToString.ToEntero + CveCuenta = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContableSIG").ToString.ToEntero + End If + + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.AppendFormat("
    {0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.AppendFormat("
    {0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) + CveCuentaContabilizacion = 0 + End If + + 'BANCOS + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + Exit For + End If + + 'CLIENTES + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 2, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 2, Concepto, Fecha, IdCtaContableCliente, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + 'IVA X TRASLADAR + IdCtaIVAXTrasladar = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) + CveCuentaIVAxTrasladar = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 13, Concepto, Fecha, IdCtaIVAXTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVAxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then + ErrorPrepoliza = True + Exit For + End If + + 'IVA PAGADO + IdCtaIVATrasladado = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) + CveCuentaIVATrasladado = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 61, Concepto, Fecha, IdCtaIVATrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVATrasladado, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then + ErrorPrepoliza = True + Exit For + End If + + 'IEPS X TRASLADAR + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + 'IEPS PAGADO + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSTrasladado, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + + Else + ErrorPrepoliza = True + Exit For + End If + + Next + + importeMovimiento = 0 + End If + + + End Select + + If importeMovimiento <> 0 And Not ErrorPrepoliza Then + + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + Else + ViewState("SeGuardoPrePoliza") = True + End If + + End If + + If ErrorPrepoliza Then + Exit For + End If + + Next + + End If + + 'Si es Facturacion de una remision cancelamos, traspasamos saldos y agregamos evento a la bitacora + If RemisionesLista.Count > 0 Then + + 'se verifica que el documento que se está generando sea "Ing", "Ant" + If Not ObjFactura.TipoDocto.Contiene("Ing", "Ant") Then + ErrorPrepoliza = True + ErrorList.Add("No se pueden facturar las remisiones, con ese tipo de comprobante seleccionado") + Else + + + For Each CveRemision As Integer In RemisionesLista + If Not ObjConta.TraspasarSaldosRemision(CveRemision, ObjFactura.CvePrePoliza, ObjFactura.CveVenta) Then + ErrorPrepoliza = True + End If + + 'Factura + If Not ObjEventos.AddEventoBitacora($"Sustituye a: Folio Factura", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then + ErrorPrepoliza = True + End If + + 'Remision + If Not ObjEventos.AddEventoBitacora($"Refacturacion en: {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveRemision) Then + ErrorPrepoliza = True + End If + Next + End If + End If + + 'REGRESA SALDO A LAS REMISIONES QUE SE FACTURARON EN EL INGRESO QUE SE ESTA CANCELANDO + If ObjFactura.TipoDocto = "Ing" And ValorMultiplicador = -1 AndAlso NuevaFactura <> 1 AndAlso Not SeCancelaRemisionProceso Then ' se debe de excluir cuando es refacturación + If ObjVentas.GetRemisionesRelacionadas(ObjFactura.CveVenta, ObjFactura.TipoDocto) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then + For Each Dr As DataRow In ObjVentas.DtResultados.Rows + Dim Selecciono As Boolean = False + If ChkCanRem.Checked Then + For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows + If Gvr.DataKey("CveVenta").ToEntero = Dr("CveVenta").ToString.ToEntero AndAlso Gvr.FCCheckBox("ChkCancelarRemision").Checked Then + Selecciono = True + End If + Next + End If + If Not Selecciono Then + If Not ObjConta.TraspasarSaldosRemision(Dr("CveVenta").ToString.ToEntero, ObjFactura.CvePrePoliza, ObjFactura.CveVenta, 1) Then + ErrorPrepoliza = True + End If + + 'Remision + If Not ObjEventos.AddEventoBitacora($"Facturación cancelada en: {TxtFolio.Text}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Dr("CveVenta").ToString.ToEntero) Then + ErrorPrepoliza = True + End If + End If + Next + End If + End If + + If NuevaFactura = 1 AndAlso TotalOriginal > TxtTotal.Text.ToDouble AndAlso ObjEventos IsNot Nothing Then + If Not ObjEventos.AddEventoBitacora($"Factura a menor precio de la factura origen.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then + ErrorPrepoliza = True + Else + Alert("Factura a menor precio de la factura origen.", TipoMensaje.MsgAdvertencia) + End If + End If + + + If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 2) Then + If ObjConta.ValorPolizaDescuadre > 0 Then If ObjConta.ValorPolizaDescuadre = 2 Then ErrorPrepoliza = True Alert(ObjConta.MensajePolizaDescuadre, TipoMensaje.MsgError) End If 'ErrorPrepoliza = True - GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") - - 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA - 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then - ' Dim DtTest = ObjConta.DtResultados - 'End If - End If - End If - - 'Simplificacion de PrePolizas - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - If Not ObjConta.PrePolizaSimplificacion(ObjFactura.CvePrePoliza, UsuarioActual.CveEmpresa) Then - Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) - End If - End If - - Return ErrorPrepoliza - Catch ex As Exception - GuardaLog(ex.ToString()) - Return True - End Try - - End Function - Private Function GuardarVentaInventarios(ObjInventario As ClsInventarios, ObjConta As ClsContabilidad, factura As Modelos.Factura) As Boolean - Dim OcurrioError As Boolean = False + GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") + + 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA + 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then + ' Dim DtTest = ObjConta.DtResultados + 'End If + End If + End If + + 'Simplificacion de PrePolizas + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + If Not ObjConta.PrePolizaSimplificacion(ObjFactura.CvePrePoliza, UsuarioActual.CveEmpresa) Then + Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) + End If + End If + + Return ErrorPrepoliza + Catch ex As Exception + GuardaLog(ex.ToString()) + Return True + End Try + + End Function + Private Function GuardarVentaInventarios(ObjInventario As ClsInventarios, ObjConta As ClsContabilidad, factura As Modelos.Factura) As Boolean + Dim OcurrioError As Boolean = False Try If UsuarioActual.Empresa.UsaInventarios AndAlso factura.TipoDocto.Contiene("Ing", "Egs", "Rem") Then @@ -10390,3442 +10391,3448 @@ Partial Class Ventas Catch ex As Exception OcurrioError = True OnError("Ocurrió un error al guardar el inventario", ex) - End Try - - Return OcurrioError - End Function - Private Sub GuardarVentaEstimaciones(ObjContr As ClsContratos, factura As Modelos.Factura) - Dim Str As New StringBuilder - For Each gvr As GridViewRow In GvEst.Rows - If gvr.FCCheckBox("Chk").Checked Then - Str.AppendFormat("{0},", gvr.DataKey("CveContratoAvance")) - End If - Next - 'debe de ser por contrato el movimiento - If Str.Length > 0 Then - If Not ObjContr.AddEstimaciones(CveContrato, factura.Fecha, -1, factura.CveVenta, Str.ToString, factura.CveUsuario, factura.CveEmpresa) Then - ErrorList.Add("Ocurrió un error al agregar la estimación a la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") - End If - End If - End Sub - Private Sub GuardarVentaAC(ObjVentas As ClsVentas, factura As Modelos.Factura, Msgok As StringBuilder, ObjAC As ClsContPAQi) - If UsuarioActual.Empresa.UsaAC Then - - If factura.TipoDocto.Contiene("Ing", "Egs", "OP", "Com") Then - - 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - Dim IDPoliza As Integer = GenerarPolizaAC(ObjAC, factura) - - If IDPoliza > 0 Then - - If ObjVentas.UpdateVentaPrePoliza(IDPoliza, factura.CvePrePoliza, factura.CveVenta, factura.CveEmpresa) Then - - 'Si se facturó la cotización hay que vincular la venta - Msgok.AppendFormat("Abono Registrado Correctamente.

    Ver Poliza", IDPoliza) - End If - Else - ErrorList.Add("Ocurrió un error al generar A.C. en la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") - End If - - Else - Msgok.Append("Movimiento Registrado Correctamente.

    ") - End If - - End If - End Sub - Private Function GuardarVentaImpuestosLocales(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, Factura As Modelos.Factura, Optional ValorMultiplicador As Integer = 1) As Boolean - Dim ErrorPrepoliza As Boolean = False - - If TmpDTImpuestos IsNot Nothing AndAlso Factura.CvePrePoliza > 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "Rem") Then - - Dim Importe As Decimal - Dim IdCtaContable, CveCuenta As Integer - Dim Concepto As String - Dim tipoCambio As Decimal - Dim CveSubProyectoContabilizar = DdlSubProyectoDatos.SelectedValue.ToEntero - - For Each RowIL As DataRow In TmpDTImpuestos.Rows - If RowIL("TipoImpuesto").ToString.ToEntero > 0 Then - - Importe = RowIL("Importe").ToString.ToDecimal * ValorMultiplicador - IdCtaContable = RowIL("IdCtaContable").ToString.ToEntero - CveCuenta = RowIL("IdCtaContable").ToString.ToEntero - Concepto = ViewState("VentaFolio").ToString - - If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then - tipoCambio = Factura.TipoCambio - ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then - tipoCambio = GlobalTipoCambio(Factura.Fecha).ToString.ToDecimal - Else - tipoCambio = 1 - End If - - Select Case RowIL("TipoImpuesto").ToString - Case "1" - If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - - Case "3" - If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 116, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - Case "4" - If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 58, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - Case "5" - If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, True, Importe, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - End Select - End If - Next - - End If - - Return ErrorPrepoliza - End Function - Private Function generaNC(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, ByRef ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ByRef ObjBancos As ClsBancos, ByRef ObjEventos As ClsOIEventos) As List(Of Object) - Dim Obj As New List(Of Object) - Dim CveVentaNueva As Integer = ObjVentas.CveVenta - Dim BanderaGeneraNC As Boolean = True - 'If UsuarioActual.CveEmpresa.Contiene(1, 119) Then BanderaGeneraNC = True - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) - Dim TmpDTconceptos As DataTable = Nothing - Dim CveNCaVincular As Integer = DdlNCFactura.SelectedValue.ToEntero - 'CargaCliente - Dim CveCliente As Integer = drv("CveCliente").ToString.ToEntero - If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then - Return Nothing - ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then - Return Nothing - End If - factura.TipoDocto = drv("TipoDocto").ToString - factura.Serie = drv("Serie").ToString - factura.FechaEjecucion = drv("FechaEjecucion").ToString.ToDateTime - factura.Fecha = drv("Fecha").ToString.ToDateTime - factura.CveSubProyectoEjecucion = drv("CveSubProyectoEjecucion").ToString.ToEntero - factura.CveSubProyectoCobranza = drv("CveSubProyectoCobranza").ToString.ToEntero - factura.CveClienteSucursal = drv("CveClienteSucursal").ToString.ToEntero - factura.CveSubProyecto = drv("CveSubProyecto").ToString.ToEntero - - 'Carga Detalle Sucursal - CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero, ObjVentas) - - 'CargaDetalle - If ObjVentas.GetVentaDetalle(CveVenta) Then - TmpDTconceptos = ObjVentas.DtResultados - TmpDTconceptos.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) - GvPS.DataSource = TmpDTconceptos - GvPS.DataBind() - End If - - 'Carga Totales - factura.SubTotal = drv("SubTotal").ToString.ToDecimal - factura.Descuento = drv("Descuento").ToString.ToDecimal - factura.Amortizacion = drv("Amortizacion").ToString.ToDecimal - factura.IVA = drv("IVA").ToString.ToDecimal - factura.RetIVA = drv("RetIVA").ToString.ToDecimal - factura.RetISR = drv("RetISR").ToString.ToDecimal - factura.Total = drv("Total").ToString.ToDecimal - factura.MotivoDescuento = drv("MotivoDescuento").ToString - factura.Observaciones = drv("Observaciones").ToString - factura.CveMoneda = drv("CveMoneda").ToString.ToEntero - factura.TipoCambio = drv("TipoCambio").ToString.ToDecimal - factura.CveVendedor = drv("CveVendedor").ToString.ToEntero - factura.RefDocto = drv("Ref").ToString - 'factura.SerieFolioPadre = drv("SerieFolio").ToString - HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString - - ViewState("FolioFiscal") = drv("FolioFiscal").ToString - - 'JJMQ 20160506: Se agrego para la validacion de pago de contado. - CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") - - UpContado.Update() - If factura.CveCliente > 0 Then - If Not IsNothing(TmpDTconceptos) AndAlso TmpDTconceptos.Rows.Count > 0 Then - - If Not drv("Total").ToString.ToDecimal = factura.Total Then - Return Nothing - End If - - If FolioFiscal = "" Then - CveEstatus = 4 - Else - CveEstatus = 5 - End If - - '[IPP] - CANCELA INVENTARIO DE VENTA NUEVA Y NO TRASPASA MOVTOS DE ALMACEN - 'If UsuarioActual.CveEmpresa.Contiene(1) Then - 'QUEMA DOCUMENTO NUEVO - If Not ObjInventario.ActualizarEsDevolucionVenta(CveVentaNueva, 2) Then - Return Nothing - End If - 'Else - ' 'TRASPASA ALMACEN A DOCUMENTO NUEVO - ' If Not CancelarMovimientoInventario(ObjInventario, ObjConta, CveVentaNueva, CveDevolucion) Then - ' Return Nothing - ' End If - 'End If - - 'CANCELA PAGOS - If ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Ant") Then - If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, ObjFactura.CvePrePoliza) Then - Return Nothing - End If - End If - - 'CANCELA FACTURA - - BanderaGeneraNC = True - '2019.05.10- RMF. se activa la bandera a true, para que siempre se cancele, y no genere la NC - - If Month(factura.Fecha) = Month(Now) OrElse BanderaGeneraNC = True Then - If CancelarFactura(ObjVentas, ObjConta, ObjContPaq, ObjBancos) Then - Obj.Add(factura) - Else - Return Nothing - End If - Else - ObjFacturaDevolucion.TipoDocto = "Egs" - ObjFacturaDevolucion.Fecha = Now - If RegistrarNC(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, TmpDTconceptos, ObjEventos) Then - Obj.Add(ObjFacturaDevolucion) - Else - Return Nothing - End If - End If - - 'TRASPASA PAGADO - If Not ObjConta.TraspasarSaldosPrePolizas(CveDevolucion, ObjFactura.CveVenta, ObjFactura.CvePrePoliza) Then - Return Nothing - End If - - If Not ObjInventario.TraspasaEntregaDirectaOCInv(ObjFactura.CveVenta, UsuarioActual.CveEmpresa) Then - Return Nothing - End If - - End If - End If - End If - End If - - If Obj.Count > 0 Then - Return Obj - Else - Return Nothing - End If - - End Function - Private Function RegistrarNC(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean - Dim ProcesoCorrecto As Boolean = True - RefacturacionGeneroNC = True - - ''Generamos el nuevo folio - 'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) - 'If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then - ' Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue)) - ' If DT.Rows.Count > 0 Then - ' factura.Folio = DT.Rows(0)("FActual").ToString.ToEntero - ' Else - ' ProcesoCorrecto = False - ' End If - ' DT.Dispose() - 'End If - factura.Folio = -1 - - 'Registramos la venta - GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, TmpDTconceptos, -1, ObjContPaq, ObjBancos) - 'CargaNCDT(factura.CveVentaPadre, factura.Total) - - 'ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) - ''Timbramos - 'If factura.TipoDocto.Contiene("Ing", "Egs", "Ant") AndAlso FolioFiscal <> "" Then - ' If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then - - ' Dim sw As New Diagnostics.Stopwatch - ' sw.Start() - - ' 'FACTURA INGRESO/EGRESO - ' Dim ObjTimbrado As New Modelos.Timbrado - ' Dim FM As New Modelos.FemsaFactura - ' Dim TmpDT7Eleven As New DataTable - ' Dim TmpDTComplementosTimbrado As New DataTable - - ' PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) - - ' ObjTimbrado.TimbrarFactura(UsuarioActual, factura, FM, TmpDT, TmpDTImpuestos, TmpDT7Eleven, TmpDTComplementosTimbrado, Ruta, LstFordASN, TxtFordGSDB.Text, ObjVentas) - - ' sw.Stop() - ' GuardaLogTimbrado(sw.ElapsedMilliseconds.ToString, UsuarioActual.Empresa.CvePAC) - - ' ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then - ' GeneraPDFCBB(ObjFactura.Fecha, Nothing, ObjFactura.SerieFolio, False) - ' End If - 'End If - - If ErrorList.Count > 0 Then - ProcesoCorrecto = False - End If - - Return ProcesoCorrecto + End Try + + Return OcurrioError End Function -#End Region - -#Region " VISTA PREVIA NEW " - Private Sub VistaPreviaNew() - - CreaObjetosVenta(True) - - If ObjFactura Is Nothing Or ObjFactura.Cliente Is Nothing Then - Alert("Ocurrió un error al procesar los datos para la vista previa. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgError) - ObjFactura = Nothing - Exit Sub - End If - - If UsuarioActual.Empresa.CvePlataforma = 2 Then - PdfFacturaPyME(ObjFactura, TmpDT) - Else - - 'REINICIA VALORES DE CONVERSION DE MONEDA - 'If Not ObjFactura.ConvertirPesos And ChkConvertirDoctoPesos.Checked Then - ' For Each Row As DataRow In TmpDT.Rows - ' Row("PU") = Row("PU").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal - ' Row("Total") = Row("Cantidad").ToString.ToDouble / Row("PU").ToString.ToDouble - ' Row("Descuento") = Row("Descuento").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal - ' Row("IEPS") = Row("IEPS").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal - ' Next - 'End If - - Select Case ConversionRemision - Case "*" - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Next - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TipoCambioRemision, NumeroDecimales)).FormatoNumero - End If - Next - Case "/" - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Next - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TipoCambioRemision, NumeroDecimales)).FormatoNumero - End If - Next - Case Else - - End Select - - ImprimirbytesPDF(PdfFactura(ObjFactura), "Factura", "PDF") - - Select Case ConversionRemision - Case "*" - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) - Next - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TipoCambioRemision, NumeroDecimales)).FormatoNumero - End If - Next - Case "/" - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) - Next - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TipoCambioRemision, NumeroDecimales)).FormatoNumero - End If - Next - Case Else - - End Select - - 'PdfFacturaPyME(ObjFactura, TmpDT) - End If + Private Sub GuardarVentaEstimaciones(ObjContr As ClsContratos, factura As Modelos.Factura) + Dim Str As New StringBuilder + For Each gvr As GridViewRow In GvEst.Rows + If gvr.FCCheckBox("Chk").Checked Then + Str.AppendFormat("{0},", gvr.DataKey("CveContratoAvance")) + End If + Next + 'debe de ser por contrato el movimiento + If Str.Length > 0 Then + If Not ObjContr.AddEstimaciones(CveContrato, factura.Fecha, -1, factura.CveVenta, Str.ToString, factura.CveUsuario, factura.CveEmpresa) Then + ErrorList.Add("Ocurrió un error al agregar la estimación a la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") + End If + End If End Sub + Private Sub GuardarVentaAC(ObjVentas As ClsVentas, factura As Modelos.Factura, Msgok As StringBuilder, ObjAC As ClsContPAQi) + If UsuarioActual.Empresa.UsaAC Then -#End Region + If factura.TipoDocto.Contiene("Ing", "Egs", "OP", "Com") Then -#Region "¡ P D F R E P O R T V I E W E R !" - Private Sub GeneraPDFFactura(EnviaCorreo As Boolean) - - 'CASO ESPECIAL - If UsuarioActual.CveEmpresa = 8 AndAlso ObjFactura.TipoDocto.Contiene("Cot") Then - Dim params As New List(Of ReportParameter) - params.Add(New ReportParameter("Sucursal", DdlSubProyectoDatos.SelectedItem.Text)) - 'params.Add(New ReportParameter("Fecha", FechaCotizacion.ToString)) - params.Add(New ReportParameter("Folio", ObjFactura.Folio.ToString)) - params.Add(New ReportParameter("Cliente", LtlCliente.Text)) - params.Add(New ReportParameter("PersonaDirige", TxtAtencionA.Text)) - params.Add(New ReportParameter("Total", TxtTotal.Text)) - params.Add(New ReportParameter("Observaciones", TxtObsFact.Text)) - params.Add(New ReportParameter("Vendedor", DdlVendedor.SelectedItem.Text)) - params.Add(New ReportParameter("PersonaDirige", TxtAtencionA.Text.Trim)) - 'params.Add(New ReportParameter("Folio", "")) - ImprimirPDF(String.Format("{0}Formatos\Cotizacion.rdlc", UsuarioActual.Empresa.Ruta), TmpDT, params, "Cotización", RDSName:="DsCotizacion") - End If - - 'Dim pdf As Byte() = Nothing - - 'GUARDA PDF - Dim LocalSerieFolio As String = String.Empty - Dim LocalTipoDocto As String = String.Empty - - - 'TIMBRADO NUEVO - Try - PdfFactura(ObjFactura) - 'If DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue = "Ant" Then - ' PdfFactura(ObjFactura) - ' 'Else - ' ' pdf = PdfFactura(ObjFactura) - 'End If - - Catch ex As Exception - Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError) - End Try - - LocalSerieFolio = ObjFactura.SerieFolio - LocalTipoDocto = ObjFactura.TipoDocto - 'End If - - - 'MANDA CORREO - If EnviaCorreo Then - - Dim ArchivoXML = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) - Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) - - Try - ' BytesPdfCotizacion(CveVenta) - Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF)) - Hilo.Start() - Catch ex As Exception - OnError("Ocurrió error al mandar Mail", ex) - Dim ObjVentas As New ClsVentas - If ChkEnviarFactura.Checked Then - ObjVentas.UpdateVentaMail(3, CveVenta) - Else - ObjVentas.UpdateVentaMail(0, CveVenta) - End If - ObjVentas.Dispose() - End Try - End If - - End Sub - Private Sub GeneraPDFCotizacion(EnviaCorreo As Boolean) - Dim pdf As Byte() = Nothing - - 'GUARDA PDF - Dim LocalSerieFolio As String = String.Empty - Dim LocalTipoDocto As String = String.Empty - - If CveVenta > 0 Then CreaObjetosVenta() - - 'TIMBRADO NUEVO - Try - pdf = PdfFactura(ObjFactura) - Catch ex As Exception - Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError) - End Try - - LocalSerieFolio = ObjFactura.SerieFolio - LocalTipoDocto = ObjFactura.TipoDocto - - 'MANDA CORREO - If EnviaCorreo Then - - Dim ArchivoXML = "" - Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) - - Try - ' BytesPdfCotizacion(CveVenta) - Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF)) - Hilo.Start() - Catch ex As Exception - OnError("Ocurrió error al mandar Mail", ex) - Dim ObjVentas As New ClsVentas - If ChkEnviarFactura.Checked Then - ObjVentas.UpdateVentaMail(3, CveVenta) - Else - ObjVentas.UpdateVentaMail(0, CveVenta) - End If - ObjVentas.Dispose() - End Try - End If - - End Sub - Private Sub EnviaPDFRemision(EnviaCorreo As Boolean) - 'MANDA CORREO - If EnviaCorreo Then - - 'GUARDA PDF - Dim pdf As Byte() = Nothing - Dim LocalSerieFolio As String = String.Empty - Dim LocalTipoDocto As String = String.Empty - - 'TIMBRADO NUEVO - Try - pdf = PdfFactura(ObjFactura) - Catch ex As Exception - Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError) - End Try - - LocalSerieFolio = ObjFactura.SerieFolio - LocalTipoDocto = ObjFactura.TipoDocto - - Dim ArchivoXML = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) - Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) - - Try - ' BytesPdfCotizacion(CveVenta) - Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF)) - Hilo.Start() - Catch ex As Exception - OnError("Ocurrió error al mandar Mail", ex) - Dim ObjVentas As New ClsVentas - If ChkEnviarFactura.Checked Then - ObjVentas.UpdateVentaMail(3, CveVenta) - Else - ObjVentas.UpdateVentaMail(0, CveVenta) - End If - ObjVentas.Dispose() - End Try - End If + 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + Dim IDPoliza As Integer = GenerarPolizaAC(ObjAC, factura) + + If IDPoliza > 0 Then + + If ObjVentas.UpdateVentaPrePoliza(IDPoliza, factura.CvePrePoliza, factura.CveVenta, factura.CveEmpresa) Then + + 'Si se facturó la cotización hay que vincular la venta + Msgok.AppendFormat("Abono Registrado Correctamente.

    Ver Poliza", IDPoliza) + End If + Else + ErrorList.Add("Ocurrió un error al generar A.C. en la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") + End If + + Else + Msgok.Append("Movimiento Registrado Correctamente.

    ") + End If + + End If End Sub + Private Function GuardarVentaImpuestosLocales(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, Factura As Modelos.Factura, Optional ValorMultiplicador As Integer = 1) As Boolean + Dim ErrorPrepoliza As Boolean = False -#End Region + If TmpDTImpuestos IsNot Nothing AndAlso Factura.CvePrePoliza > 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "Rem") Then -#Region " ANTICIPOS " - Private Sub CargaAnticipos(CveCliente As Integer) - - HdnTieneAnticipos.Value = "0" - If CveCliente > 0 Then - - HdnIVACalculado.Value = "0" - HdnFolioFiscalNC.Value = "0" - LblAntAplicados.Text = "" - LblAntAplicados.Visible = False - LblAmortizacion.Text = "0.00" - HdnTipoDescuento.Value = "-1" - HdnTieneAnticiposVinculados.Value = "0" - - Dim ObjMovtos As New ClsMovimientos() - If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, DdlMoneda.SelectedValue.ToEntero) Then - GVAnticipos.DataSource = ObjMovtos.DtResultados.FiltraParametros($"Saldo > 0 AND SaldoSubtotal > 0 {If(CveVenta < 0, "AND Tipo = 'Ant'", "")} {If(DdlTipoComprobante.SelectedValue = "Ant", "AND Tipo = 'NC'", "")}") - If ObjMovtos.DtResultados.SUM("Saldo", "Saldo > 0 AND SaldoSubtotal > 0 AND Tipo = 'Ant'") > 0 Then - HdnTieneAnticipos.Value = "1" - End If - Else - GVAnticipos.DataSource = Nothing - End If - ObjMovtos.Dispose() - - If CveVenta <= 0 OrElse (EsCreaApartirDe Or CveDevolucion > 0) Then - divAmortizacionTipo.Visible = True - divAmortizacionTipoRelacion.Visible = True - End If - - If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then - DdlTipoAmortizacionAnticipo.Items.Add(New ListItem("Amortización anticipo sobre factura en cero", "3")) - End If - - If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then - DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1")) - End If - - GVAnticipos.Columns(4).Visible = False - GVAnticipos.Columns(7).Visible = False - - GVAnticipos.DataBind() - End If - UpAnticipos.Update() - End Sub - - Protected Sub GVAnticipos_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowCreated - If e.Row.RowType = DataControlRowType.Header Then - e.Row.ClientIDMode = ClientIDMode.Static - e.Row.ID = String.Format("TrH{0}", e.Row.RowIndex) - ElseIf e.Row.RowType = DataControlRowType.DataRow Then - e.Row.ClientIDMode = ClientIDMode.Static - e.Row.ID = String.Format("Tr{0}", e.Row.RowIndex) - e.Row.FCCheckBox("Chk").ID = "Chk" & e.Row.RowIndex - e.Row.FCTextBox("TxtAnticipo").ID = "TxtAnticipo" & e.Row.RowIndex - e.Row.FCTextBox("TxtTC").ID = "TxtTC" & e.Row.RowIndex - DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ID = "CVAmortAnti" & e.Row.RowIndex - DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).ID = "VCOAmortAnti" & e.Row.RowIndex - DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ControlToValidate = "TxtAnticipo" & e.Row.RowIndex - DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).TargetControlID = "CVAmortAnti" & e.Row.RowIndex - End If - End Sub - Protected Sub GVAnticipos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow Then - - If e.Row.RowIndex = 0 Then - e.Row.Cells(1).Width = Unit.Pixel(60) - e.Row.Cells(2).Width = Unit.Pixel(100) - e.Row.Cells(3).Width = Unit.Pixel(80) - e.Row.Cells(4).Width = Unit.Pixel(80) - End If - - e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right - - If e.Row.DataKey("Saldo").ToDouble < 0 Then e.Row.Cells(3).ForeColor = Drawing.Color.Red - If e.Row.DataKey("Saldo").ToDouble = 0 Then e.Row.FCLiteral("LtlAnticipos").Text = "" - - Dim saldo As Decimal = 0 - Dim tipoCambio As Decimal = 0 - Dim total As Decimal = TxtTotal.Text.ToString.ToDecimal - - - If CveVentaRelacion > 0 Then ' dejo seleccionado el la venta relacionado en anticipo - If e.Row.DataKey("CveVenta").ToEntero = CveVentaRelacion Then - - e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Checked = True - e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Text = ImporteRelacion.ToString - - End If - End If - - - If e.Row.DBCampo("Tipo").ToString = "NC" And e.Row.DataKey("CveVenta").ToString.ToEntero > 0 Then - If e.Row.DBCampo("CveMoneda").ToString.ToEntero = 2 Then - tipoCambio = e.Row.DataKey("TipoCambio").ToString.ToDecimal - Else - tipoCambio = GlobalTipoCambio(e.Row.DataKey("Fecha").ToString.ToDate).ToDecimal - End If - - e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Text = tipoCambio.FormatoNumero(4) - - If DdlMoneda.SelectedValue.ToEntero = 1 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 1 Then - saldo = e.Row.DataKey("Saldo").ToDecimal - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 1 And tipoCambio > 0 Then - saldo = (e.Row.DataKey("Saldo").ToString.ToDecimal / tipoCambio) - ElseIf DdlMoneda.SelectedValue.ToEntero = 1 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 2 Then - saldo = (e.Row.DataKey("Saldo").ToString.ToDecimal * tipoCambio) - Else - saldo = e.Row.DataKey("Saldo").ToDecimal - End If - Else - saldo = e.Row.DataKey("Saldo").ToString.ToDecimal - - If CveVenta <= 0 Then - saldo = e.Row.DataKey("SaldoSubTotal").ToString.ToDecimal - e.Row.FCLiteral("LtlAnticipos").Text = saldo.FormatoNumero - End If - - End If - - Dim maxsaldo As Decimal - If total > saldo Then - maxsaldo = saldo - Else - maxsaldo = total - End If - - e.Row.FCLiteral("MonedaVenta").Text = saldo.FormatoNumero(4) - e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Attributes.Add("onclick", String.Format("chkAnt(this,{0},{1});", e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, saldo)) - e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, saldo)) - e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("CambioTipoMoneda({0},{1},{2},{3},{4});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, e.Row.DataKey("Saldo"), e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).ClientID, e.Row.DataKey("CveMoneda"))) - - If e.Row.DataKey("CveIE").ToString.ToEntero > 0 Then - e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveIE"), e.Row.DataKey("Folio")) - Else - e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveVenta"), e.Row.DataKey("Folio")) - End If - - If e.Row.DataKey("ISTotal") = "1" Then - e.Row.Cells(0).Visible = False - e.Row.Cells(1).ColumnSpan = 3 - e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Right - e.Row.FCLiteral("LtlFactura").Text = String.Format("Total {0} ", e.Row.DataKey("Tipo")) - e.Row.BackColor = Drawing.Color.LightGray - e.Row.Cells(2).Visible = False - e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Visible = False - e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False - e.Row.FCLabel("LblTotalAnticipos").Visible = True - e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right - End If - - 'SI UN REGISTRO ES DE DIFERENTE MONEDA AL DOCUMENTO SE MUESTRAN LAS COLUMNAS - If e.Row.DBCampo("CveMoneda").ToString.ToEntero > 0 And e.Row.DBCampo("CveMoneda").ToString.ToEntero <> DdlMoneda.SelectedValue.ToEntero Then - GVAnticipos.Columns(4).Visible = True - GVAnticipos.Columns(6).Visible = True - End If - - - If e.Row.DBCampo("CveMoneda").ToString.ToEntero = DdlMoneda.SelectedValue.ToEntero Then - e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False - End If - - - - - End If - End Sub - Protected Sub BtnAceptarAnticipos_Click(sender As Object, e As System.EventArgs) Handles BtnAceptarAnticipos.Click - Anticipos() - End Sub - Private Sub Anticipos() - - - If CveVenta > 0 And CveCliente > 0 And Not EsCreaApartirDe And CveDevolucion <= 0 Then - - - 'Dim TotalAnticipo As Decimal = 0 - 'Dim DescuentoTotal As Decimal = LblDescuentos.Text.ToDecimal - 'Dim CveSubProyecto As Integer = -1 - - - 'If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then - ' CveSubProyecto = TmpDT.FiltroPrimeroValor("CveSubProyecto").ToEntero - 'End If - - Dim EsAnticipo2017Jam As Boolean = False - For Each gvr As GridViewRow In GVAnticipos.Rows - If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then - If gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal > SaldoVenta Then - Alert("No puede ingresar un importe mayor al saldo", TipoMensaje.MsgAdvertencia) - Exit Sub - ElseIf UsuarioActual.CveEmpresa = 119 AndAlso gvr.DataKey("Tipo").ToString = "NC" AndAlso gvr.DataKey("Fecha").ToDate.Year <= 2017 Then - EsAnticipo2017Jam = True - End If - End If - Next - - Dim ObjConta As New ClsContabilidad - Dim ObjVenta As New ClsVentas(ObjConta.IniciaTransacSQL()) - Dim ObjContpaq As ClsContPAQi = Nothing - - Dim CvePrepoliza As Integer - Dim ErrorConta As Boolean - Dim CveIEAnticipo As Integer - Dim CvePlantillaPoliza As Integer = 10 - Dim PorcentajeAmortizacion As Decimal = 0 - Dim sumaAmorticaciones As Decimal = 0 - Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " - Dim CveCuentaContabilizacion As Integer = 1 - Dim CuentasContablesInvalidas As New StringBuilder - Dim CuentasContablesInvalidasSIG As New StringBuilder - Dim ContaIdPoliza As Integer = 0 - Dim ConceptoAmortizacion As Integer = 0 - Dim UsaComplementariaClientes As Boolean = False - If UsuarioActual.CveEmpresa.Contiene(1, 119) Then UsaComplementariaClientes = True - 'Dim FechaMaxima As Date = MinFecha - - - 'For Each gvr As GridViewRow In GVAnticipos.Rows - ' If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then - ' If gvr.FCLiteral("LtlFecha").Text.ToDate > FechaMaxima Then - ' FechaMaxima = gvr.FCLiteral("LtlFecha").Text.ToDate - ' End If - ' End If - 'Next - - ''[IPP] PARCHE TEMPORAL PARA ANTICIPOS DE JAM - 'If FechaMaxima < "01/01/2018".ToDate And UsuarioActual.CveEmpresa = 119 Then - ' FechaMaxima = "01/01/2018".ToDate - 'End If - - CvePrepoliza = ObjConta.AddPrePolizas("Ventas/Anticipos", CvePlantillaPoliza, TxtTotal.Text.ToDecimal, TxtTotal.Text.ToDecimal, DdlMoneda.SelectedValue.ToEntero, TxtFechaAnticipoCliente.Text.ToDate, String.Format("{0} {1} {2}-{3}", If(EsAnticipo2017Jam, "Aplicación Anticipo 2017", ""), NombreCliente, Serie, TxtFolio.Text), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - - If CvePrepoliza > 0 Then - Dim tipoCambioPago As Decimal = 1 - Dim tipoCambioVenta As Decimal = 1 - Dim PorcentajePago As Decimal = 100 - Dim dtConceptos As DataTable = Nothing - Dim CveMonedaVenta = DdlMoneda.SelectedValue.ToEntero - If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPoliza) Then - dtConceptos = ObjConta.DtResultados - End If - Dim PorcentajeImpuestoAmortizacion As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal - Dim IdCtaIVAXTrasladar As Integer = 0 - Dim IdCtaIVATrasladado As Integer = 0 - Dim CveCuentaIVAXTrasladar As Integer = 0 - Dim CveCuentaIVATrasladado As Integer = 0 - - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then - Dim Dr As DataRow = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).FiltroPrimero("") - IdCtaIVAXTrasladar = Dr("IdCtaIVAXTrasladar").ToString.ToEntero - IdCtaIVATrasladado = Dr("IdCtaIVATrasladado").ToString.ToEntero - CveCuentaIVAXTrasladar = Dr("CveCuentaIVAXTrasladar").ToString.ToEntero - CveCuentaIVATrasladado = Dr("CveCuentaIVATrasladado").ToString.ToEntero - End If - - For Each gvr As GridViewRow In GVAnticipos.Rows - If gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then - - If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then 'Si la venta viene en Pesos y se va a pagar en Pesos - tipoCambioPago = 1 - tipoCambioVenta = 1 - PorcentajePago = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then 'Si la venta viene en Dolares y se va a pagar en Pesos - tipoCambioPago = gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal - tipoCambioVenta = TxtTipoCambio.Text.ToDecimal - PorcentajePago = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal) / gvr.DataKey("Original").ToDecimal - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then 'Si la venta viene en Dolares y se va a pagar en DOLARES - tipoCambioPago = gvr.DataKey("TipoCambio").ToString.ToDecimal - tipoCambioVenta = TxtTipoCambio.Text.ToDecimal - PorcentajePago = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal - ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then 'Si la venta viene en pesos y se va a pagar en DOLARES - tipoCambioPago = gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal - tipoCambioVenta = 1 - PorcentajePago = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal) / gvr.DataKey("Original").ToDecimal - End If - - If dtConceptos IsNot Nothing Then - For Each Row As DataRow In dtConceptos.Rows - - Dim ConceptoContable = Row("CveConcepto").ToString.ToEntero - Dim TipoMovimiento As Boolean = If(Row("TipoMovto").ToString = "True", True, False) - Dim importeMovimiento As Decimal = 0 - Dim importeMX As Decimal = 0 - Dim IdCtaContable As Integer = 0 - Dim CveCuenta As Integer = 0 - Dim FechaMovimiento As Date = Now - Dim Concepto As String = ViewState("VentaFolio").ToString - Dim FuncionalidadFluctuacionImpuestos As Boolean = If(UsuarioActual.Empresa.Funcionalidad(159) = "1", True, False) - Dim TipoCambioGeneral As Decimal = 1 - Dim PorcentajeImpuesto As Decimal = 0 - - Select Case ConceptoContable - Case 2 'Cliente - If Not (gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66) Then - If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - importeMX = importeMovimiento - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - importeMX = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta - ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - importeMX = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta - ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - importeMX = importeMovimiento - End If - importeMovimiento = Math.Round(importeMovimiento, 2) - importeMX = Math.Round(importeMX, 2) - TipoCambioGeneral = tipoCambioVenta - - If CveMonedaVenta = 1 Then - IdCtaContable = IdCtaContClientes - CveCuenta = CveCuentaClientes - Else - IdCtaContable = IdCtaContComplementaria - CveCuenta = 0 'If(ObjFactura.Cliente IsNot Nothing AndAlso ObjFactura.Cliente.CveCuentaComplementaria > 0, ObjFactura.Cliente.CveCuentaComplementaria, -1) - If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or UsaComplementariaClientes) Then - 'Conta ContPAQ - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - 'Conta SIG - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, 0, Concepto, 207, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioVenta) Then - ErrorConta = True - End If - - importeMX = importeMovimiento - IdCtaContable = IdCtaContMonedaExtranjera - CveCuenta = 0 - - End If - - End If - ConceptoContable = 251 ' cambia para dejar el concepto 2, solamente para pago en banco - End If - Case 11 'Anticipo - If gvr.DataKey("CveConceptoContable").ToString().ToEntero = 3 Then - CveIEAnticipo = gvr.DataKey("CveIE").ToString.ToEntero - - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) - 'Mantenemos la integridad de la suma para el pagocliente - 'SumaAnticipos += row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal - 'sumaAmorticaciones += row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal - TipoCambioGeneral = tipoCambioPago - IdCtaContable = IdCtaContAnticipos - CveCuenta = CveCuentaAnticipos - - If importeMovimiento <> 0 Then - - 'Conta ContPAQ - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - 'Conta SIG - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambioPago, ImporteME:=If(tipoCambioPago = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then - ErrorConta = True - End If - End If - - ' PorcentajeAmortizacion = SumaAnticipos / TxtTotal.Text.ToDecimal - 'Los Anticipos solo ocupan los ivas por trasladar - If PorcentajePago > 0 Then - Dim Importe13 = gvr.DataKey("IVA").ToDecimal - Dim Importe8 = gvr.DataKey("RetIVA").ToDecimal - Dim Importe9 = gvr.DataKey("RetISR").ToDecimal - If Not AgregarPrePolizasXTrasladar(ObjConta, CvePrepoliza, PorcentajePago, tipoCambioPago, CuentasContablesInvalidas, idCuentaContabilizacion, CuentasContablesInvalidasSIG, CveCuentaContabilizacion, Importe13, Importe8, Importe9) Then - ErrorConta = True - End If - End If - End If - importeMovimiento = 0 - Case 91 'Amortizacion Nota de Credito - If gvr.DataKey("CveConceptoContable").ToString().ToEntero = 12 Then - If CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 1 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - importeMX = importeMovimiento - ElseIf CveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 2 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - importeMX = importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal - ElseIf CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 2 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal - importeMX = importeMovimiento * gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal - ElseIf CveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 1 Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal - importeMX = importeMovimiento - End If - importeMovimiento = Math.Round(importeMovimiento, 2) - importeMX = Math.Round(importeMX, 2) - - If ObjConta.GetRetCuenta(ConceptoContable, CveCliente) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero - End If - End If - - If importeMovimiento <> 0 Then - 'Conta ContPAQ - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - Dim ImporteComplementaria As Decimal = 0 - If UsaComplementariaClientes = True AndAlso gvr.DataKey("CveMoneda").ToString.ToDecimal > 1 Then - IdCtaContable = IdCtaContComplementaria - CveCuenta = 0 - importeMX = importeMovimiento - ImporteComplementaria = ((importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal) - importeMovimiento).RoundSQL - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, False, importeMovimiento, Concepto, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=ImporteComplementaria, ImporteME:=If(gvr.DataKey("TipoCambio").ToString.ToDecimal = 1, 0, importeMovimiento), TipoCambio:=gvr.DataKey("TipoCambio").ToString.ToDecimal) Then - ErrorConta = True - Exit For - End If - IdCtaContable = IdCtaContMonedaExtranjera - CveCuenta = 0 - End If - - If CveMonedaVenta > 1 AndAlso IdCtaContMonedaExtranjera > 0 Then - IdCtaContable = IdCtaContMonedaExtranjera - CveCuenta = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=gvr.DataKey("TipoCambio").ToString.ToDecimal) Then - ErrorConta = True - Exit For - End If - - 'AMORTIZA NC CONTRA ANTICIPO A CLIENTES - If Not ErrorConta And DdlTipoComprobante.SelectedValue = "Ant" Then - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal) * gvr.DataKey("IVA").ToDecimal) - If ObjConta.AddPrePolizasDetalle(CvePrepoliza, False, importeMovimiento, Concepto, 11, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveVentaAmortizacion:=gvr.DataKey("CveVenta").ToString.ToEntero, ImporteMX:=importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal, CveCuenta:=CveCuenta) Then - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, True, importeMovimiento, Concepto, 4, Concepto, FechaMovimiento, gvr.DataKey("IdCtaContableNC").ToEntero, -1, CveClasificacion:=gvr.DataKey("CveClasificacionNC").ToEntero, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal, CveCuenta:=gvr.DataKey("IdCtaContableNCSIG").ToEntero) Then - ErrorConta = True - Exit For - End If - Else - ErrorConta = True - Exit For - End If - End If - End If - End If - importeMovimiento = 0 - Case 92 'Amortizacion Ingreso X Comprobar - If gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66 Then - CveIEAnticipo = gvr.DataKey("CveIE").ToString.ToEntero - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - IdCtaContable = IdCtaContClientes - CveCuenta = CveCuentaClientes - - If importeMovimiento <> 0 Then - ' Agregamos el 2 - If tipoCambioPago = 1 Then - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContClientes, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento) Then - ErrorConta = True - End If - Else 'Cuando son dolares - If importeMovimiento <> 0 Then - If IdCtaContComplementaria > 0 Or 0 > 0 Then - 'Agregamos la Complementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, 0, Concepto, 207, Concepto, FechaMovimiento, IdCtaContComplementaria, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then - ErrorConta = True - End If - 'Agregamos la Extranjera - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then - ErrorConta = True - End If - Else - 'Agregamos la Extranjera - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then - ErrorConta = True - End If - End If - End If - End If - - importeMovimiento = ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / TxtTotal.Text.ToDecimal) * TxtIVA.Text.ToDecimal) - importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) - - If importeMX <> 0 Then - - - 'Agregamos el 13 - - IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) - CveCuenta = If(CveCuentaIVAXTrasladar > 0, CveCuentaIVAXTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, 13, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then - ErrorConta = True - End If - - 'Agregamos el 61 - - IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) - CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then - ErrorConta = True - End If - End If - - 'IEPS - importeMovimiento = ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / TxtTotal.Text.ToDecimal) * TxtIEPS.Text.ToDecimal) - importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) - - If importeMX <> 0 Then - - 'Agregamos el 38 - - IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSxTrasladar - CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSxTrasladar - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, 38, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then - ErrorConta = True - End If - - 'Agregamos el 39 - - IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSTrasladado - CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSTrasladado - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then - ErrorConta = True - End If - End If - - 'Agregamos el 92 - importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal 'gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo" & gvr.RowIndex).ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) - importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) - IdCtaContable = IdCtaContAnticipos - CveCuenta = CveCuentaAnticipos - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago) Then - ErrorConta = True - End If - - End If - End If - importeMovimiento = 0 - Case 64 'Ganancia - If CveMonedaVenta <> 1 OrElse gvr.DataKey("CveMoneda").ToEntero <> 1 Then - IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria - - If tipoCambioPago > tipoCambioVenta AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then - importeMovimiento = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioPago) - (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta) 'Añadimos la diferencia de ganancia en la venta - importeMovimiento = Math.Abs(Math.Round(importeMovimiento, 2)) - importeMX = importeMovimiento - End If - Dim TCImpuestos As Decimal = If(FuncionalidadFluctuacionImpuestos, tipoCambioVenta, tipoCambioPago) - TipoCambioGeneral = TCImpuestos - Else - importeMovimiento = 0 - End If - Case 65 'Perdida - If CveMonedaVenta <> 1 OrElse gvr.DataKey("CveMoneda").ToEntero <> 1 Then - IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria - CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria - - If tipoCambioPago < tipoCambioVenta AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then - importeMovimiento = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta) - (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioPago) 'Añadimos la diferencia de perdida en la venta - importeMovimiento = Math.Abs(Math.Round(importeMovimiento, 2)) - importeMX = importeMovimiento - End If - Dim TCImpuestos As Decimal = If(FuncionalidadFluctuacionImpuestos, tipoCambioVenta, tipoCambioPago) - TipoCambioGeneral = TCImpuestos - Else - importeMovimiento = 0 - End If - Case Else - importeMovimiento = 0 - End Select - - If importeMovimiento <> 0 Then - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=TipoCambioGeneral) Then - ErrorConta = True - End If - End If - Next - End If - End If - Next - Else - ErrorConta = True - End If - - If ObjConta.ValidacionPrePolizaCuadre(CvePrepoliza, 3) Then - If ObjConta.ValorPolizaDescuadre > 0 Then - GuardaLogAD($"Ventas/Ventas-Anticipos | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrepoliza}", "LogPrePolizas") - ErrorConta = True - End If - End If - - If ErrorConta Then - Alert("Ocurrió un error al amortizar el documento. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError) - ObjConta.RollBack() - If ObjContpaq IsNot Nothing Then ObjContpaq.RollBack() - Else - Dim Msg As New StringBuilder - Msg.Append("Se ha amortizado correctamente") - - 'AJUSTA POLIZA - If ContaIdPoliza > 0 Then - Msg.AppendFormat("

    Ver Póliza", ContaIdPoliza) - End If - - ObjConta.Commit() - BtnAceptarAnticipos.Enabled = False - If ObjContpaq IsNot Nothing Then - - ObjContpaq.AjustaPoliza(ContaIdPoliza) - ObjContpaq.Commit() - End If - Alert(Msg.ToString, TipoMensaje.MsgInformacion) - End If - - ObjConta.Dispose() - Else - - 'cuando no se ha registrado la venta - - If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("1", "2", "3") Then - - Dim Amortizacion As Decimal = 0 - Dim ImpuestosLocalesTemporal As Decimal = 0 - - HdnIVACalculado.Value = HdnIVAOriginal.Value - For Each gvr As GridViewRow In GVAnticipos.Rows - If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked AndAlso gvr.DataKey("CveConceptoContable").ToEntero.Contiene(3) Then - Amortizacion += gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal ' - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) - HdnIVACalculado.Value = (HdnIVACalculado.Value.ToDouble - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal)).FormatoNumero(2) - HdnFolioFiscalNC.Value = gvr.DataKey("FolioFiscal") - - 'CvePSAmortizacion = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePS", "CveConceptoContable = 11").ToEntero - End If - Next - 'Amortizacion += TmpDTImpuestos.SUM("Importe").ToDecimal 'RMF. 2018.12.20- saque de la jugada en la amortización los impuestos locales - - LtlTitDescuentos.Text = "Descuentos:" - - 'cuando es amortización DESCUENTO POR CONCEPTO - If DdlTipoAmortizacionAnticipo.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Cot") Then - LtlTitDescuentos.Text = "Amortización:" - 'If Amortizacion <> LblDescuentos.Text.ToDecimal Then - ' Alert("El importe registrado como descuento no coincide con el importe seleccionado de anticipo.", TipoMensaje.MsgAdvertencia) - ' Exit Sub - 'End If - Dim TotalCalculableImpuestos As Decimal = 0 - Dim Cantidad, PU, Descuento As Decimal - For Each dr As DataRow In TmpDT.Rows - Cantidad = dr("Cantidad").ToString.ToDecimal - PU = dr("PU").ToString.ToDecimal - 'proporcional la mortización al concepto - Descuento = PU * Cantidad / LblSubTotal1.Text.ToDecimal * Amortizacion - TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento - dr("Descuento") = Descuento - dr("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) - dr("ImporteIVA") = Math.Round(dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - dr("ImporteIEPS") = Math.Round(dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) - dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) - dr("PorcentajeRetIVA") = ClienteRetIVA - dr("PorcentajeRetISR") = ClienteRetISR - Next - GvPS.DataSource = TmpDT - GvPS.DataBind() - - Amortizacion = 0 - HdnTipoDescuento.Value = "-1" - HdnDescuento.Value = "0" - RegistraScript("BorraDescuentos();") - LblAntAplicados.Text = "Amortización por descuento" : LblAntAplicados.Visible = True - RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal") - UpPS.Update() - End If - - If DdlTipoComprobante.SelectedValue = "Rem" Then - DdlTipoComprobante.Enabled = False - TrAlmacenAsignado.Visible = False - UpParametros.Update() - End If - - - 'cuando es amortización por NOTA DE CREDITO - If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then - LblAntAplicados.Text = "Amortización por Nota de Crédito" : LblAntAplicados.Visible = True - Amortizacion = 0 - HdnTipoDescuento.Value = "-1" - HdnDescuento.Value = "0" - RegistraScript("BorraDescuentos();") - HdnTieneAnticiposVinculados.Value = "1" - - End If - - 'cuando es AMORTIZACIÓN CON FACTURA EN CERO - If DdlTipoAmortizacionAnticipo.SelectedValue = "3" Then - - If Amortizacion < TxtSubTotal.Text.ToDecimal Then - - '[IPP] LIMPIA LO SELECCIONADO EN CASO DE QUE NO SEA AMORTIZACIÓN DEL 100% 15Junio2018 - Amortizacion = 0 - For Each gvr As GridViewRow In GVAnticipos.Rows - gvr.FCCheckBox($"Chk{gvr.RowIndex}").Checked = False - Next - If CveVenta <= 0 Then - Alert("La amortización no se pudo realizar ya que los importes no cubren la totalidad del documento. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - End If - - End If - LblAmortizacion.Text = Amortizacion.FormatoNumero(2) - - HdnTipoDescuento.Value = "-1" - HdnDescuento.Value = "0" - RegistraScript("BorraDescuentos();") - HdnTieneAnticiposVinculados.Value = "1" - - - End If - CalculaTotalesVenta() - End If - End If - - System.Threading.Thread.Sleep(5) - RegistraScript("$('#DivAnticipos').modal('hide');", "jsClose") - - - End Sub - Private Function AgregarPrePolizasXTrasladar(ObjConta As ClsContabilidad, CvePrePoliza As Integer, PorcentajeAmortizacion As Decimal, TipoCambio As Decimal, ByRef CuentasContablesInvalidas As StringBuilder, ByRef idCuentaContabilizacion As Integer, ByRef CuentasContablesInvalidasSIG As StringBuilder, ByRef CveCuentaContabilizacion As Integer, Importe13 As Decimal, Importe8 As Decimal, Importe9 As Decimal) As Boolean - Dim ImporteMovimiento As Decimal - Dim ImporteMX As Decimal - Dim IdCtaContable, CveCuenta As Integer - Dim FechaMovimiento As Date = Now - Dim Concepto As String = ViewState("VentaFolio").ToString - Dim PrePolizaCorrecta = True - Dim PorcentajeImpuesto As Decimal = 0 - Dim IdCtaIVAXTrasladar As Integer = 0 - Dim CveCuentaIVAxTrasladar As Integer = 0 - - '13 Iva x Trasladar - ImporteMovimiento = Importe13 * PorcentajeAmortizacion - ImporteMX = Math.Round(ImporteMovimiento, 2) * TipoCambio - PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then - IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero - CveCuentaIVAxTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVAXTrasladar").ToString.ToEntero - End If - IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) - CveCuenta = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) - - If ImporteMovimiento > 0 Then - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 13))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 13))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 13, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then - PrePolizaCorrecta = False - End If - End If - - '8 RetIVA x Trasladar - ImporteMovimiento = Importe8 * PorcentajeAmortizacion - ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) - - If IdCtaContRetIVA <> 0 Then - IdCtaContable = IdCtaContRetIVA - CveCuenta = CveCuentaRetIVA - Else - If ObjConta.GetRetCuenta(8, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - End If - - If ImporteMovimiento > 0 Then - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 8))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 8))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 8, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then - PrePolizaCorrecta = False - End If - End If - - '9 RetISR x Trasladar - ImporteMovimiento = Importe9 * PorcentajeAmortizacion - ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) - - 'Conta ContPAQ - If IdCtaContRetISR <> 0 Then - IdCtaContable = IdCtaContRetISR - Else - If ObjConta.GetRetCuenta(9, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - End If - End If - End If - - 'ContaSIG - If CveCuentaRetISR <> 0 Then - CveCuenta = CveCuentaRetISR - Else - If ObjConta.GetRetCuenta(9, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - - If ImporteMovimiento > 0 Then - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 9))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If IdCtaContable <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 9))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 9, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then - PrePolizaCorrecta = False - End If - End If - - Return PrePolizaCorrecta - - End Function - 'Charlie - Private Function AgregarPrePolizasTrasladadas(ObjConta As ClsContabilidad, CvePrePoliza As Integer, PorcentajeAmortizacion As Decimal, TipoCambio As Decimal, ByRef CuentasContablesInvalidas As StringBuilder, ByRef idCuentaContabilizacion As Integer, Optional ByRef CuentasContablesInvalidasSIG As StringBuilder = Nothing, Optional ByRef CveCuentaContabilizacion As Integer = Nothing) As Boolean - - Dim ImporteMovimiento As Decimal - Dim ImporteMX As Decimal - Dim IdCtaContable, CveCuenta As Integer - Dim FechaMovimiento As Date = Now - Dim Concepto As String = ViewState("VentaFolio").ToString - Dim PrePolizaCorrecta = True - Dim PorcentajeImpuesto As Decimal = 0 - Dim IdCtaIVATrasladado As Integer = 0 - Dim CveCuentaIVATrasladado As Integer = 0 - - '61 Iva Trasladado - ImporteMovimiento = TxtIVA.Text.ToDecimal * PorcentajeAmortizacion - ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) - PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then - IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero - CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero - End If - IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) - CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) - - If ImporteMovimiento > 0 Then - 'ContaContPAQ - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 61))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - 'ContaSIG - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 61))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then - PrePolizaCorrecta = False - End If - End If - - '62 Ret IVA Trasladado - ImporteMovimiento = TxtRetIVA.Text.ToDecimal * PorcentajeAmortizacion - ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) - - 'Conta ContPAQ - If IdCtaContRetIVA <> 0 Then - IdCtaContable = IdCtaContRetIVA - Else - If ObjConta.GetRetCuenta(62, UsuarioActual.CveEmpresa) Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero - End If - End If - - 'Conta SIG - If CveCuentaRetIVA <> 0 Then - CveCuenta = CveCuentaRetIVA - Else - If ObjConta.GetRetCuenta(62, UsuarioActual.CveEmpresa) Then - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero - End If - End If - - If ImporteMovimiento > 0 Then - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 62))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 62))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 62, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then - PrePolizaCorrecta = False - End If - End If - - - '63 Ret ISR Trasladado - ImporteMovimiento = TxtRetISR.Text.ToDecimal * PorcentajeAmortizacion - ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) - - If IdCtaContRetISR <> 0 Then - IdCtaContable = IdCtaContRetISR - Else - If ObjConta.GetRetCuenta(63, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero - End If - End If - End If - - If CveCuentaRetISR <> 0 Then - CveCuenta = CveCuentaRetISR - Else - If ObjConta.GetRetCuenta(63, UsuarioActual.CveEmpresa) Then - If ObjConta.DtResultados.Rows.Count > 0 Then - CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero - End If - End If - End If - - If ImporteMovimiento > 0 Then - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 63))("ConceptoContable").ToString) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 63))("ConceptoContable").ToString) - CveCuentaContabilizacion = 0 - End If - - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 63, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then - PrePolizaCorrecta = False - End If - End If - - - Return PrePolizaCorrecta - + Dim Importe As Decimal + Dim IdCtaContable, CveCuenta As Integer + Dim Concepto As String + Dim tipoCambio As Decimal + Dim CveSubProyectoContabilizar = DdlSubProyectoDatos.SelectedValue.ToEntero + + For Each RowIL As DataRow In TmpDTImpuestos.Rows + If RowIL("TipoImpuesto").ToString.ToEntero > 0 Then + + Importe = RowIL("Importe").ToString.ToDecimal * ValorMultiplicador + IdCtaContable = RowIL("IdCtaContable").ToString.ToEntero + CveCuenta = RowIL("IdCtaContable").ToString.ToEntero + Concepto = ViewState("VentaFolio").ToString + + If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then + tipoCambio = Factura.TipoCambio + ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then + tipoCambio = GlobalTipoCambio(Factura.Fecha).ToString.ToDecimal + Else + tipoCambio = 1 + End If + + Select Case RowIL("TipoImpuesto").ToString + Case "1" + If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + + Case "3" + If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 116, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + Case "4" + If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 58, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + Case "5" + If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, True, Importe, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + End Select + End If + Next + + End If + + Return ErrorPrepoliza End Function -#End Region + Private Function generaNC(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, ByRef ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ByRef ObjBancos As ClsBancos, ByRef ObjEventos As ClsOIEventos) As List(Of Object) + Dim Obj As New List(Of Object) + Dim CveVentaNueva As Integer = ObjVentas.CveVenta + Dim BanderaGeneraNC As Boolean = True + 'If UsuarioActual.CveEmpresa.Contiene(1, 119) Then BanderaGeneraNC = True -#Region " BTN ELIMINAR " - Protected Sub BtnEmitir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitir.Click - - If CveVenta <= 0 Then - Alert("Ocurrió un error al emitir la factura", TipoMensaje.MsgError) - Exit Sub - End If - - If UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then - If UsuarioActual.Empresa.EstatusFacturacion Then - - CreaObjetosVenta() - 'PARA CUANDO YA ESTA GUARDADA LA VENTA - ObjFactura.CveVenta = CveVenta - ObjFactura.Serie = Serie - ObjFactura.Folio = Folio - ObjFactura.Timbre.Comprobante.Serie = Serie - ObjFactura.Timbre.Comprobante.Folio = Folio.ToString - - Dim ObjTimbrado As New Timbrado - Dim FM As New Modelos.FemsaFactura - Dim TmpDT7Eleven As New DataTable - Dim TmpDTComplementosTimbrado As New DataTable - PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) - - If ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) Then - - 'MENSAJE PRINCIPAL - MensajeAlert = New StringBuilder - MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} se generó correctamente.

    ", ObjFactura.TipoDocumento, ObjFactura.SerieFolio)) - - 'XML - Dim ArchivoXML = String.Format("{0}/XML/{1}/{2}.xml", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) - If File.Exists(ArchivoXML) Then - MensajeAlert.AppendFormat("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", ObjFactura.SerieFolio, ObjFactura.TipoDocto))) - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant", "Egs") Then - 'If Not ImprimeAlert Then - - Dim ArchivoIngPyMe As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.mrt", UsuarioActual.Empresa.Ruta)) - Dim ArchivoIng As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) - Dim ArchivoRem As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) - Dim ArchivoEgs As New System.IO.FileInfo(String.Format("{0}Formatos/NotaCredito.rdlc", UsuarioActual.Empresa.Ruta)) - - If ArchivoIng.Exists Or ArchivoRem.Exists Or ArchivoIngPyMe.Exists Or ArchivoEgs.Exists Then - MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))) - Else - MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") - End If - End If - - 'IMPRESION - GeneraPDFFactura(ChkEnviarFactura.Checked) - - If ObjFactura.TipoDocto = "Ing" AndAlso ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" Then - CreaObjetosVentaAmortizacion(Nothing, ObjTimbrado.UUID, ObjFactura.CveVentaRelacion, CveVenta) - For Each Gvr As GridViewRow In GvAntNC.Rows - If Gvr.DataKey("FolioFiscal").ToString = "" AndAlso Gvr.DataKey("TipoDocto") = "Egs" Then - ObjFacturaDevolucion.CveVenta = Gvr.DataKey("CveVenta").ToEntero - ObjFacturaDevolucion.Serie = Gvr.DataKey("Serie").ToString - ObjFacturaDevolucion.Folio = Gvr.DataKey("Folio").ToEntero - ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) - End If - Exit For - Next - If ObjFacturaDevolucion.CveVenta.ToEntero > 0 Then - Dim Obj2 As New List(Of Object) - Obj2.Add(ObjFacturaDevolucion) - If Not IsNothing(Obj2) AndAlso Obj2.Count > 0 Then - Dim ofa As Modelos.Factura = CType(Obj2(0), Modelos.Factura) - ofa.Timbre.CFDIRelacionados.UUID.Clear() - ofa.Timbre.CFDIRelacionados.UUID.Add(ObjTimbrado.UUID) - If ObjTimbrado.TimbrarFactura(UsuarioActual, ofa) Then - MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} se timbro correctamente.

    ", ofa.TipoDocumento, ofa.SerieFolio)) - Else - MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} no se timbro correctamente.

    ", ofa.TipoDocumento, ofa.SerieFolio)) - End If - End If - End If - End If - - - 'NOTIFICACION DE SMS - Dim EstatusSMS = 0 - If ObjFactura.TipoDocto = "Ing" Then - Dim ObjEventos As New ClsOIEventos - EnviarSMSTimbrado(ObjEventos) - ObjEventos.Dispose() - End If - Select Case EstatusSMS - Case 1 - MensajeAlert.AppendFormat("Notificación SMS: enviado con éxito al cliente al celular: {0}", ObjFactura.Cliente.CobranzaTelefono) - Case 2 - MensajeAlert.AppendFormat("Notificación SMS: sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.") - Case 3 - MensajeAlert.AppendFormat("Notificación SMS: sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.") - End Select - - 'MUESTA Alert OK - 'MensajeAlert.Append("El Documento se generó correctamente") - Dim Liga = If(UsuarioActual.CveRol = 1165, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}&Opt=3"";") - Alert(MensajeAlert.ToString, TipoMensaje.MsgInformacion, Liga) - - TrEmitir.Visible = False - Else - Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgError) - End If - - Else - Me.OnError("El SAT regresó el siguiente mensaje: Crédito insuficiente.", New Exception) - End If - ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then - - End If - End Sub -#End Region + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then + Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) + Dim TmpDTconceptos As DataTable = Nothing + Dim CveNCaVincular As Integer = DdlNCFactura.SelectedValue.ToEntero + 'CargaCliente + Dim CveCliente As Integer = drv("CveCliente").ToString.ToEntero + If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then + Return Nothing + ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then + Return Nothing + End If + factura.TipoDocto = drv("TipoDocto").ToString + factura.Serie = drv("Serie").ToString + factura.FechaEjecucion = drv("FechaEjecucion").ToString.ToDateTime + factura.Fecha = drv("Fecha").ToString.ToDateTime + factura.CveSubProyectoEjecucion = drv("CveSubProyectoEjecucion").ToString.ToEntero + factura.CveSubProyectoCobranza = drv("CveSubProyectoCobranza").ToString.ToEntero + factura.CveClienteSucursal = drv("CveClienteSucursal").ToString.ToEntero + factura.CveSubProyecto = drv("CveSubProyecto").ToString.ToEntero -#Region " DESCUENTOS " - Protected Sub BtnAplicarDescG_Click(sender As Object, e As System.EventArgs) Handles BtnAplicarDescG.Click - If HdnTipoDescuento.Value = "2" Then - - If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then - Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2) - Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble - - If IVAPromedio <> IVA Then - Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError) - Else - 'Dim Descuento As Double = HdnDescuento.Value.Trim.Replace(",", "").ToDouble - CalculaTotalesVenta() - 'LblDescuentos.Text = Descuento.FormatoNumero(2) - 'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Descuento - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2) - 'HdnIVAOriginal.Value = TxtIVA.Text - 'CalculaTotales(True) - HdnTipoDescuento.Value = "-1" - HdnDescuento.Value = "0" - RegistraScript("BorraDescuentos();") - End If - End If - - ElseIf HdnTipoDescuento.Value = "3" Then - If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then - Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2) - Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble - - If IVAPromedio <> IVA Then - Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError) - Else - 'Dim Amortizacion As Decimal = HdnDescuento.Value.Trim.Replace(",", "").ToDecimal - 'LblAmortizacion.Text = Amortizacion.FormatoNumero(2) - 'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Amortizacion - LblDescuentos.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2) - 'HdnIVAOriginal.Value = TxtIVA.Text - 'CalculaTotales(True) - CalculaTotalesVenta() - HdnTipoDescuento.Value = "-1" - HdnDescuento.Value = "0" - RegistraScript("BorraDescuentos();") - HdnTieneAnticiposVinculados.Value = "1" - End If - End If - - End If - - RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal") - UpPS.Update() - End Sub - Private Sub BtnAplicarOtrosConceptos_Click(sender As Object, e As EventArgs) Handles BtnAplicarOtrosConceptos.Click - TotalOtrosConceptos = 0 - - For Each row As GridViewRow In GVOtrosConceptos.Rows - TotalOtrosConceptos += row.FCTextBox("TxtCantidadConcepto").Text.ToDecimal - Next - - RegistraScript("$('#ModalOtrosConceptos').modal('hide')", "hidemodal") - End Sub - Private Sub BtnAplicarComplementos_Click(sender As Object, e As EventArgs) Handles AplicarComplementosTimbrado.Click - LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs green" - UpPS.Update() - - RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal") - End Sub - Private Sub BtnCancelarComplementos_Click(sender As Object, e As EventArgs) Handles CancelarComplementosTimbrado.Click - trEntidad.Visible = False - trContaComplementos.Visible = False - trAmbito.Visible = False - trTipoCampaña.Visible = False - - RblComplementos.SelectedIndex = -1 - TxtIdConta.Text = "" - DdlTipoCampaña.SelectedIndex = -1 - DdlAmbitoComplemento.SelectedIndex = -1 - DdlINEEntidad.SelectedIndex = -1 - - LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs gray" - UpComplementos.Update() - UpDatosComplementos.Update() - UpPS.Update() - - RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal") - End Sub - - '2019-07-31 OSCAR Nuevo cancela usando el metodo de cancelacion de facturas - Protected Sub LnkCancelarComplemetno_Click(sender As Object, e As EventArgs) - - Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).BindingContainer, GridViewRow) - - Dim ObjCancelacion As New Timbrado - Dim ObjBanco As New ClsBancos - - Dim CveComplementoPago As Integer = GvRow.DataKey("CveComplementoPago").ToEntero - Dim FolioFiscal As String = GvRow.DataKey("FolioFiscal").ToString - Dim RFCEmisor As String = UsuarioActual.Empresa.RFC - Dim RFCReceptor As String = GvRow.DataKey("RFCReceptor") - Dim CvePACCancelacion As Integer = GvRow.DataKey("CvePAC").ToEntero - - If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, 0, RFCReceptor, RFCEmisor, CvePACCancelacion) Then - - If ObjBanco.UpdateComplementoPago(CveComplementoPago, "-1", -1, UsuarioActual.CveEmpresa, 2, CvePACCancelacion, FechaCancelacion:=ObjCancelacion.CancelacionFecha, SelloCancelacion:=ObjCancelacion.CancelacionAcuse) Then - CargaComplementosPago() - Alert("El complemento se cancelo correctamente.") - End If - - Else - Alert("Se presento un error al cancelar el complemento.") - End If - - ObjBanco.Dispose() - - End Sub -#End Region + 'Carga Detalle Sucursal + CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero, ObjVentas) + 'CargaDetalle + If ObjVentas.GetVentaDetalle(CveVenta) Then + TmpDTconceptos = ObjVentas.DtResultados + TmpDTconceptos.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) + GvPS.DataSource = TmpDTconceptos + GvPS.DataBind() + End If + 'Carga Totales + factura.SubTotal = drv("SubTotal").ToString.ToDecimal + factura.Descuento = drv("Descuento").ToString.ToDecimal + factura.Amortizacion = drv("Amortizacion").ToString.ToDecimal + factura.IVA = drv("IVA").ToString.ToDecimal + factura.RetIVA = drv("RetIVA").ToString.ToDecimal + factura.RetISR = drv("RetISR").ToString.ToDecimal + factura.Total = drv("Total").ToString.ToDecimal + factura.MotivoDescuento = drv("MotivoDescuento").ToString + factura.Observaciones = drv("Observaciones").ToString + factura.CveMoneda = drv("CveMoneda").ToString.ToEntero + factura.TipoCambio = drv("TipoCambio").ToString.ToDecimal + factura.CveVendedor = drv("CveVendedor").ToString.ToEntero + factura.RefDocto = drv("Ref").ToString + 'factura.SerieFolioPadre = drv("SerieFolio").ToString + HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString -#Region " VISTA PREVIA " - Protected Sub BtnVistaPrevia_Click(sender As Object, e As System.EventArgs) Handles BtnVistaPrevia.Click - VistaPreviaNew() + ViewState("FolioFiscal") = drv("FolioFiscal").ToString + + 'JJMQ 20160506: Se agrego para la validacion de pago de contado. + CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") + + UpContado.Update() + If factura.CveCliente > 0 Then + If Not IsNothing(TmpDTconceptos) AndAlso TmpDTconceptos.Rows.Count > 0 Then + + If Not drv("Total").ToString.ToDecimal = factura.Total Then + Return Nothing + End If + + If FolioFiscal = "" Then + CveEstatus = 4 + Else + CveEstatus = 5 + End If + + '[IPP] - CANCELA INVENTARIO DE VENTA NUEVA Y NO TRASPASA MOVTOS DE ALMACEN + 'If UsuarioActual.CveEmpresa.Contiene(1) Then + 'QUEMA DOCUMENTO NUEVO + If Not ObjInventario.ActualizarEsDevolucionVenta(CveVentaNueva, 2) Then + Return Nothing + End If + 'Else + ' 'TRASPASA ALMACEN A DOCUMENTO NUEVO + ' If Not CancelarMovimientoInventario(ObjInventario, ObjConta, CveVentaNueva, CveDevolucion) Then + ' Return Nothing + ' End If + 'End If + + 'CANCELA PAGOS + If ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Ant") Then + If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, ObjFactura.CvePrePoliza) Then + Return Nothing + End If + End If + + 'CANCELA FACTURA + + BanderaGeneraNC = True + '2019.05.10- RMF. se activa la bandera a true, para que siempre se cancele, y no genere la NC + + If Month(factura.Fecha) = Month(Now) OrElse BanderaGeneraNC = True Then + If CancelarFactura(ObjVentas, ObjConta, ObjContPaq, ObjBancos) Then + Obj.Add(factura) + Else + Return Nothing + End If + Else + ObjFacturaDevolucion.TipoDocto = "Egs" + ObjFacturaDevolucion.Fecha = Now + If RegistrarNC(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, TmpDTconceptos, ObjEventos) Then + Obj.Add(ObjFacturaDevolucion) + Else + Return Nothing + End If + End If + + 'TRASPASA PAGADO + If Not ObjConta.TraspasarSaldosPrePolizas(CveDevolucion, ObjFactura.CveVenta, ObjFactura.CvePrePoliza) Then + Return Nothing + End If + + If Not ObjInventario.TraspasaEntregaDirectaOCInv(ObjFactura.CveVenta, UsuarioActual.CveEmpresa) Then + Return Nothing + End If + + End If + End If + End If + End If + + If Obj.Count > 0 Then + Return Obj + Else + Return Nothing + End If + + End Function + Private Function RegistrarNC(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean + Dim ProcesoCorrecto As Boolean = True + RefacturacionGeneroNC = True + + ''Generamos el nuevo folio + 'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) + 'If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then + ' Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue)) + ' If DT.Rows.Count > 0 Then + ' factura.Folio = DT.Rows(0)("FActual").ToString.ToEntero + ' Else + ' ProcesoCorrecto = False + ' End If + ' DT.Dispose() + 'End If + factura.Folio = -1 + + 'Registramos la venta + GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, TmpDTconceptos, -1, ObjContPaq, ObjBancos) + 'CargaNCDT(factura.CveVentaPadre, factura.Total) + + 'ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) + ''Timbramos + 'If factura.TipoDocto.Contiene("Ing", "Egs", "Ant") AndAlso FolioFiscal <> "" Then + ' If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then + + ' Dim sw As New Diagnostics.Stopwatch + ' sw.Start() + + ' 'FACTURA INGRESO/EGRESO + ' Dim ObjTimbrado As New Modelos.Timbrado + ' Dim FM As New Modelos.FemsaFactura + ' Dim TmpDT7Eleven As New DataTable + ' Dim TmpDTComplementosTimbrado As New DataTable + + ' PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) + + ' ObjTimbrado.TimbrarFactura(UsuarioActual, factura, FM, TmpDT, TmpDTImpuestos, TmpDT7Eleven, TmpDTComplementosTimbrado, Ruta, LstFordASN, TxtFordGSDB.Text, ObjVentas) + + ' sw.Stop() + ' GuardaLogTimbrado(sw.ElapsedMilliseconds.ToString, UsuarioActual.Empresa.CvePAC) + + ' ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then + ' GeneraPDFCBB(ObjFactura.Fecha, Nothing, ObjFactura.SerieFolio, False) + ' End If + 'End If + + If ErrorList.Count > 0 Then + ProcesoCorrecto = False + End If + + Return ProcesoCorrecto + End Function +#End Region + +#Region " VISTA PREVIA NEW " + Private Sub VistaPreviaNew() + + If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then + Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") + Exit Sub + End If + + CreaObjetosVenta(True) + + If ObjFactura Is Nothing Or ObjFactura.Cliente Is Nothing Then + Alert("Ocurrió un error al procesar los datos para la vista previa. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgError) + ObjFactura = Nothing + Exit Sub + End If + + If UsuarioActual.Empresa.CvePlataforma = 2 Then + PdfFacturaPyME(ObjFactura, TmpDT) + Else + + 'REINICIA VALORES DE CONVERSION DE MONEDA + 'If Not ObjFactura.ConvertirPesos And ChkConvertirDoctoPesos.Checked Then + ' For Each Row As DataRow In TmpDT.Rows + ' Row("PU") = Row("PU").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal + ' Row("Total") = Row("Cantidad").ToString.ToDouble / Row("PU").ToString.ToDouble + ' Row("Descuento") = Row("Descuento").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal + ' Row("IEPS") = Row("IEPS").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal + ' Next + 'End If + + Select Case ConversionRemision + Case "*" + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Next + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TipoCambioRemision, NumeroDecimales)).FormatoNumero + End If + Next + Case "/" + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Next + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TipoCambioRemision, NumeroDecimales)).FormatoNumero + End If + Next + Case Else + + End Select + + ImprimirbytesPDF(PdfFactura(ObjFactura), "Factura", "PDF") + + Select Case ConversionRemision + Case "*" + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * TipoCambioRemision, NumeroDecimales) + Next + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TipoCambioRemision, NumeroDecimales)).FormatoNumero + End If + Next + Case "/" + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / TipoCambioRemision, NumeroDecimales) + Next + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TipoCambioRemision, NumeroDecimales)).FormatoNumero + End If + Next + Case Else + + End Select + + 'PdfFacturaPyME(ObjFactura, TmpDT) + End If End Sub -#End Region +#End Region + +#Region "¡ P D F R E P O R T V I E W E R !" + Private Sub GeneraPDFFactura(EnviaCorreo As Boolean) + + 'CASO ESPECIAL + If UsuarioActual.CveEmpresa = 8 AndAlso ObjFactura.TipoDocto.Contiene("Cot") Then + Dim params As New List(Of ReportParameter) + params.Add(New ReportParameter("Sucursal", DdlSubProyectoDatos.SelectedItem.Text)) + 'params.Add(New ReportParameter("Fecha", FechaCotizacion.ToString)) + params.Add(New ReportParameter("Folio", ObjFactura.Folio.ToString)) + params.Add(New ReportParameter("Cliente", LtlCliente.Text)) + params.Add(New ReportParameter("PersonaDirige", TxtAtencionA.Text)) + params.Add(New ReportParameter("Total", TxtTotal.Text)) + params.Add(New ReportParameter("Observaciones", TxtObsFact.Text)) + params.Add(New ReportParameter("Vendedor", DdlVendedor.SelectedItem.Text)) + params.Add(New ReportParameter("PersonaDirige", TxtAtencionA.Text.Trim)) + 'params.Add(New ReportParameter("Folio", "")) + ImprimirPDF(String.Format("{0}Formatos\Cotizacion.rdlc", UsuarioActual.Empresa.Ruta), TmpDT, params, "Cotización", RDSName:="DsCotizacion") + End If + + 'Dim pdf As Byte() = Nothing + + 'GUARDA PDF + Dim LocalSerieFolio As String = String.Empty + Dim LocalTipoDocto As String = String.Empty + + + 'TIMBRADO NUEVO + Try + PdfFactura(ObjFactura) + 'If DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue = "Ant" Then + ' PdfFactura(ObjFactura) + ' 'Else + ' ' pdf = PdfFactura(ObjFactura) + 'End If + + Catch ex As Exception + Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError) + End Try + + LocalSerieFolio = ObjFactura.SerieFolio + LocalTipoDocto = ObjFactura.TipoDocto + 'End If + + + 'MANDA CORREO + If EnviaCorreo Then + + Dim ArchivoXML = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) + Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) + + Try + ' BytesPdfCotizacion(CveVenta) + Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF)) + Hilo.Start() + Catch ex As Exception + OnError("Ocurrió error al mandar Mail", ex) + Dim ObjVentas As New ClsVentas + If ChkEnviarFactura.Checked Then + ObjVentas.UpdateVentaMail(3, CveVenta) + Else + ObjVentas.UpdateVentaMail(0, CveVenta) + End If + ObjVentas.Dispose() + End Try + End If -#Region "I M A G E - B U T T O N S" - Protected Function CancelarMovimientoInventario(ByRef ObjInventario As ClsInventarios, ByRef ObjConta As ClsContabilidad, CveVentaNueva As Integer, CveVentaVieja As Integer) As Boolean - - 'SI YA ESTA QUEMADA DE ALMACEN LA VENTA, NO SE CANCELAN LOS MOVIMIENTOS DE INVENTARIO - If ObjInventario.GetEstatusVentaPorSurir(CveVentaVieja) Then - If ObjInventario.EsDevolucionVenta = 2 Then - Return True - End If - Else - Return False - End If - - Dim DtMovimientos As DataTable - Dim DTMovimientosDetalles As DataTable - Dim OcurrioError As Boolean = False - - 'Verificamos que la venta tenga movimientos - If ObjInventario.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjInventario.DtResultados.Rows.Count > 0 Then - DtMovimientos = ObjInventario.DtResultados.FiltraParametros("CveConcepto = 3", DistinctColumns:={"CveMovimiento"}) - DTMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0") - - For Each Mov As DataRow In DtMovimientos.Rows - If ObjInventario.GetMovimientos(Mov("CveMovimiento").ToString.ToEntero, 3, -1, UsuarioActual.CveEmpresa) Then - If ObjInventario.DtResultados.Rows.Count > 0 Then - - Dim CveAlmacen As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero - Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero - Dim Fecha As Date = Now - - 'Creamos el movimiento de entrada y el movimiento de salida - Dim CveMovimientoInventarioEntrada As Integer = ObjInventario.AddMovimiento(CveAlmacen, 18, CveMoneda, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveDevolucion, -1, -1, MovimientoFijo:=True) - Dim CveMovimientoInventarioSalida As Integer = ObjInventario.AddMovimiento(CveAlmacen, 3, CveMoneda, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVentaNueva, -1, -1, MovimientoFijo:=True) - - If CveMovimientoInventarioEntrada > 0 AndAlso CveMovimientoInventarioSalida > 0 Then - - 'Creamos sus detalles - For Each MovDet As DataRow In DTMovimientosDetalles.FiltraParametros($"CveMovimiento = {Mov("CveMovimiento")}").Rows - - Dim Cantidad As Double = MovDet("Cantidad").ToString.ToDouble - Dim CveUnidad As Integer = MovDet("CveUM").ToString.ToEntero - Dim PU As Double = MovDet("PU").ToString.ToDouble - Dim CveProducto As Integer = MovDet("CvePS").ToString.ToEntero - Dim SerieLote As String = MovDet("SerieLote").ToString - - Dim CveVentaDetalle = MovDet("CveVentaDetalle").ToString.ToEntero - - 'Entrada - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventarioEntrada, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then - OcurrioError = True - Exit For - End If - - 'Salida - CveVentaDetalle = ObjInventario.VentaDetallePadreGet(CveVentaDetalle).ToString.ToEntero - If CveVentaDetalle > 0 Then - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventarioSalida, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then - OcurrioError = True - Exit For - End If - Else - OcurrioError = True - Exit For - End If - - Next - - 'Creamos sus prepolizas - If Not OcurrioError Then - Dim tmpCostos As DataTable = DTMovimientosDetalles.FiltraParametros($"CveMovimiento = {Mov("CveMovimiento")}", "", {"CveClasificacion"}) - Dim IdCtaContable As Integer = 0 - Dim CveCuenta As Integer = 0 - Dim ValorInventario As Decimal = 0 - - For Each RowInv As DataRow In tmpCostos.Rows - ValorInventario = DTMovimientosDetalles.SUM("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).ToString.ToDecimal.RoundSQL() - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - - If ValorInventario <> 0 Then - 'Entrada - If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveDevolucion, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventarioEntrada, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then - 'Salida - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventarioSalida, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then - OcurrioError = True - Exit For - End If - Else - OcurrioError = True - Exit For - End If - End If - Next - - If OcurrioError Then - Exit For - End If - - IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {ddlAlmacen.SelectedValue}").ToEntero - CveCuenta = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {ddlAlmacen.SelectedValue}").ToEntero - ValorInventario = DTMovimientosDetalles.SUMD("Total", $"CveMovimiento = {Mov("CveMovimiento")}").RoundSQL() - - If ValorInventario <> 0 Then - 'Entrada - If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveDevolucion, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=-1, CveMovimientoAlmacen:=CveMovimientoInventarioEntrada, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta) Then - 'Salida - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ValorInventario, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=-1, CveMovimientoAlmacen:=CveMovimientoInventarioSalida, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta) Then - OcurrioError = True - Exit For - End If - Else - OcurrioError = True - Exit For - End If - End If - - End If - - Else - OcurrioError = True - Exit For - End If - - Else - 'Si no tiene Movimientos de Salida no ocupamos mas - Return Not OcurrioError - End If - - Else - OcurrioError = True - Exit For - End If - - Next - - End If - - Else - OcurrioError = True - End If - - Return Not OcurrioError - End Function - Protected Function CancelarFactura(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjAC As ClsContPAQi, ByRef ObjBancos As ClsBancos) As Boolean - Dim IDPoliza As Integer = -1 - Dim CvePrePoliza As Integer - Dim CvePlantillaPoliza As Integer - - Dim ErrorCancelar As Boolean = False - Dim Mensaje As String = "" - - Try - ObjFacturaDevolucion.TipoDocto = ObjFactura.TipoDocto - - If ObjFacturaDevolucion.TipoDocto.Contiene("Egs", "Dev") Then - CvePlantillaPoliza = 7 - ElseIf ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem", "Ant") Then - CvePlantillaPoliza = 4 - End If - - - CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - ObjFacturaDevolucion.CveVenta = CveVenta - ObjFacturaDevolucion.CvePrePoliza = CvePrePoliza - - - If NuevaFactura = 1 AndAlso UsuarioActual.TienePermisoProceso(222) Then - If ObjVentas.GetVentaDetalle(ObjFacturaDevolucion.CveVenta) Then - TmpDT = ObjVentas.DtResultados - End If - ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) - Else - ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) - End If - - If Not ErrorCancelar Then - ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFacturaDevolucion, -1) - End If - - If CveEstatus = 4 Then - - If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then - Mensaje = "El nuevo estatus se guardó correctamente" - Else - ErrorCancelar = True - End If - - 'Si se está mandando a Cancelada SAT - ElseIf CveEstatus = 5 Then - - Dim DT As DataTable = Nothing - - If FolioFiscal = "" Then - Dim XmlDoc As New XmlDocument - XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml") - ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText - End If - - Dim ObjCancelacion As New Timbrado - - Dim Total As Decimal = TxtTotal.Text.ToDecimal - Dim RFCReceptor As String = HdnRFCVenta.Value - - If Not ObjVentas.UpdateEstatusFactura(13, FolioFiscal, "", Now, CveVenta, IDPoliza) Then 'Marcamos la factura como refacturada, si no se cancelo en el SAT el estatus nos dejara cancelarla despues - ErrorCancelar = True - End If - - If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, Total, RFCReceptor, UsuarioActual.Empresa.RFC) Then - 'falta verificar traer el acuse y reenviarlo - - If UsuarioActual.Empresa.UsaAC Then - IDPoliza = GenerarPolizaAC(ObjAC, True) - If IDPoliza <= 0 Then - Mensaje = "No se pudo generar la poliza" - ErrorCancelar = True - End If - End If - - If Not ErrorCancelar Then - If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, ObjCancelacion.CancelacionAcuse, Now, CveVenta, IDPoliza, CvePAC:=UsuarioActual.Empresa.CvePAC) Then - Mensaje = "El nuevo estatus se guardó correctamente" - Else - ErrorCancelar = True - End If - End If - Else - ErrorCancelar = True - End If - - ObjCancelacion = Nothing - - End If - Catch ex As Exception - GuardaLog(ex.ToString()) - ErrorCancelar = True - End Try - - Return Not ErrorCancelar - End Function - Protected Function CancelarFactura2(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjAC As ClsContPAQi, ObjBancos As ClsBancos) As Boolean - - Dim IDPoliza As Integer = -1 - Dim CvePrePoliza As Integer - Dim CvePlantillaPoliza As Integer - - Dim ErrorCancelar As Boolean = False - Dim Mensaje As String = "" - - CreaObjetosVenta() - - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - CvePlantillaPoliza = 7 - ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem") Then - CvePlantillaPoliza = 4 - End If - - - CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - ObjFactura.CveVenta = CveVenta - ObjFactura.CvePrePoliza = CvePrePoliza - - If HplSaldoAuxiliar.Text.ToDecimal > 0 Then - ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) - End If - - If Not ErrorCancelar Then - ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, -1) - End If - - If CveEstatus = 4 Then - - If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then - Mensaje = "El nuevo estatus se guardó correctamente" - Else - ErrorCancelar = True - End If - - 'Si se está mandando a Cancelada SAT - ElseIf CveEstatus = 5 Then - - Dim DT As DataTable = Nothing - - If FolioFiscal = "" Then - Dim XmlDoc As New XmlDocument - XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml") - ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText - End If - - 'Si es cancelar en el SAT: - Dim CFDi As New ClbNegBICFDv3_2.ClsNegEDI - Dim Respuesta As New ClbNegBICFDv3_2.ClsNegRespuesta - Respuesta = CFDi.CancelaCFdi(UsuarioActual.Empresa.BIUsuario, UsuarioActual.Empresa.BIContraseña, Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoPfx, UsuarioActual.Empresa.ContraseñaKey, UsuarioActual.Empresa.RFC, FolioFiscal, "http://208.43.160.178/srvCFDi/service1.asmx") - - If Respuesta Is Nothing Then - 'Alert("La factura no se pudo cancelar.
    Posbiles causas:
      - Los servicios del SAT están ocupados.
      - El Folio Fiscal no ha quedado registrado.", TipoMensaje.MsgError) - Me.GuardaLog(CFDi.MsgError) - ErrorCancelar = True - Mensaje = "La factura no se pudo cancelar.
    Posbiles causas:
      - Los servicios del SAT están ocupados.
      - El Folio Fiscal no ha quedado registrado." - ElseIf Respuesta.NoCertificadoSAT <> String.Empty Then - - If UsuarioActual.Empresa.UsaAC Then - IDPoliza = GenerarPolizaAC(ObjAC, True) - If IDPoliza <= 0 Then - Mensaje = "No se pudo generar la poliza" - ErrorCancelar = True - End If - End If - - If Not ErrorCancelar Then - If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, Respuesta.NoCertificadoSAT, Respuesta.FechaTimbrado, CveVenta, IDPoliza) Then - Mensaje = "El nuevo estatus se guardó correctamente" - Else - ErrorCancelar = True - End If - End If - End If - - End If - - Return Not ErrorCancelar - End Function - - Protected Sub ImgBtnAddC_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddC.Click - Dim Row As DataRow = Nothing - Row = DTmpC.NewRow - - Row("Descripcion") = tbDescC.Text - DTmpC.Rows.Add(Row) - tbDescC.Text = "" - tbDescC.Focus() - GvConceptos.DataSource = DTmpC - GvConceptos.DataBind() - UPCD.Update() - End Sub - Protected Sub ImgBtnAddF_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddF.Click - Dim Row As DataRow = Nothing - Dim ObjVentas As New ClsVentas - - Row = DTmpF.NewRow - - Row("CveVenta") = 0 - Row("Titulo") = tbTituloF.Text - Row("Nombre") = tbNmbF.Text - Row("Puesto") = tbPuesF.Text - Row("Lado") = ddlPos.SelectedValue.ToEntero - DTmpF.Rows.Add(Row) - tbNmbF.Text = "" - tbPuesF.Text = "" - tbTituloF.Text = "" - ddlPos.SelectedValue = CStr(0) - GvFirmas.DataSource = DTmpF - GvFirmas.DataBind() - UPFirmas.Update() - tbTituloF.Focus() End Sub -#End Region + Private Sub GeneraPDFCotizacion(EnviaCorreo As Boolean) + Dim pdf As Byte() = Nothing + + 'GUARDA PDF + Dim LocalSerieFolio As String = String.Empty + Dim LocalTipoDocto As String = String.Empty + + If CveVenta > 0 Then CreaObjetosVenta() + + 'TIMBRADO NUEVO + Try + pdf = PdfFactura(ObjFactura) + Catch ex As Exception + Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError) + End Try + + LocalSerieFolio = ObjFactura.SerieFolio + LocalTipoDocto = ObjFactura.TipoDocto + + 'MANDA CORREO + If EnviaCorreo Then + + Dim ArchivoXML = "" + Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) + + Try + ' BytesPdfCotizacion(CveVenta) + Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF)) + Hilo.Start() + Catch ex As Exception + OnError("Ocurrió error al mandar Mail", ex) + Dim ObjVentas As New ClsVentas + If ChkEnviarFactura.Checked Then + ObjVentas.UpdateVentaMail(3, CveVenta) + Else + ObjVentas.UpdateVentaMail(0, CveVenta) + End If + ObjVentas.Dispose() + End Try + End If -#Region "D R O P - D O W N - L I S T" - Private Sub DdlPSIndexChange(CvePSParametro As Integer, Ddl As ADServerControl.Dropdownlost) - - If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then - Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") - Exit Sub - End If - - If CvePSParametro > 0 Then - Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSParametro).FiltroPrimero("") - - If drPS IsNot Nothing Then - 'HdnUnidadMedida.Value = PS.Rows(0)("CveUnidadMedida").ToString - HdnPS.Value = drPS("PS").ToString - HdnCodigoPS.Value = drPS("PSCodigo").ToString - HdnTipoPS.Value = drPS("CveTipoPS").ToString - HdnTipoInv.Value = drPS("Inv_CveMetodoInventario").ToString - HdnAplicaIEPS.Value = drPS("AplicaIEPS").ToString - HdnPorcentajeIEPS.Value = drPS("IEPSPorcentaje").ToString - DdlUnidadMedida.Items.Clear() - If UsuarioActual.Empresa.UsaInventarios Then - DdlUnidadMedida.DataSource = GlobalDTProductosServiciosEquivalencias(CvePSParametro, -1) - Else - DdlUnidadMedida.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) - End If - DdlUnidadMedida.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlUnidadMedida.SelectedValue = "-1" - DdlUnidadMedida.DataBind() - DdlUnidadMedida.SelectedValueExist(drPS("CveUnidadMedida").ToString) - DdlMoneda.SelectedValueExist(drPS("CveMoneda").ToString) - 'SUGIERE PRECIO - Dim PrecioSugerido = 0.0 - PrecioSugerido = drPS("Precio").ToString.ToDouble - - If UsuarioActual.CveEmpresa.Contiene(1) Then - Dim ObjPS As New ClsProductosServicios - If ObjPS.GetPorcentajeProductos(CveCliente) Then - Dim PrecioAplicado = ObjPS.DtResultados.FiltraParametros($"CvePS = {CvePSParametro}").FiltroPrimeroValor("PrecioA").ToDouble - If PrecioAplicado > 0 Then - PrecioSugerido = PrecioAplicado - End If - End If - ObjPS.Dispose() - End If - - If UsuarioActual.Empresa.Funcionalidad(404).ToString = "1" Then - Dim CvePrecioListaPS As Integer = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePrecioLista", "").ToEntero - If CvePrecioListaPS > 0 Then - Dim ObjPS As New ClsProductosServicios - If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then - PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble - End If - ObjPS.Dispose() - End If - - Dim PorcentajePrecio As Double = 0 - If PrecioSugerido = 0 Then - CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero - If CvePrecioListaPS > 0 Then - Dim ObjPS As New ClsProductosServicios - If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then - PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble - PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDouble - End If - ObjPS.Dispose() - End If - End If - - If PrecioSugerido = 0 Then - Dim ObjInventarios As New ClsInventarios - Dim CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) - 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal - If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1) - ObjInventarios.Dispose() - If CostoPS > 0 And PorcentajePrecio > 0 Then - PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS - End If - End If - - End If - - If PrecioSugerido > 0 Then - TxtPrecio.Text = PrecioSugerido.ToString("#,###.####") ' que muestre hasta los 4 digitos si lo requiere - End If - - - If IsNumeric(TxtCantidad.Text.Trim) Then - LblTotalPS.Text = (TxtCantidad.Text.Trim.ToDouble * TxtPrecio.Text.ToDouble).ToString.FormatoNumero(2) - Else - LblTotalPS.Text = "0.00" - End If - - HdnIVAPS.Value = If(drPS("IVA").ToString = "-1", ViewState("IVA"), drPS("IVA").ToString).ToString - HdnIVARetAPS.Value = drPS("RetIVA").ToString - HdnAsientoContable.Value = drPS("AsientoContableVentas").ToString - HdnCtaContable.Value = drPS("IdCtaContVentas").ToString - HdnAplicaParaConcepto.Value = drPS("AplicaParaConcepto").ToString - HdnCodigo.Value = drPS("Codigo").ToString - If DdlClasificacion.SelectedIndex = 0 Then - If drPS("CveClasificacion").ToString IsNot Nothing Then - DdlClasificacion.SelectedValueExist(drPS("CveClasificacion").ToString) - Else - Alert("El Productos/Servicio no tiene asignada una Clasificación.", TipoMensaje.MsgInformacion) - End If - - End If - - End If - - ElseIf CvePSParametro = -2 Then - CargaPS(DdlClasificacion.SelectedValue.ToEntero, Ddl) - End If - - UPPPS.Update() - UpPS.Update() - - End Sub - Protected Sub DdlPS_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlPS.selectedindexchange - DdlPSIndexChange(DdlPS.SelectedValue.ToEntero, DdlPS) - End Sub - Protected Sub DdlClasificacion_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlClasificacion.SelectedIndexChanged - CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS) - UpPS.Update() - End Sub - Protected Sub DdlNCFactura_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlNCFactura.SelectedIndexChanged - Dim objcompras As New ClsCompras - If objcompras.GetCompraDetallealmacen(0, DdlNCFactura.SelectedValue.ToEntero) Then - GvInvNC.DataSource = objcompras.DtResultados - If objcompras.DtResultados.Rows.Count > 0 Then - Tab.ActiveTabIndex = 1 - Updatetabs.Update() - End If - Else - GvInvNC.DataSource = Nothing - End If - GvInvNC.DataBind() - UpINVNC.Update() - objcompras.Dispose() - End Sub - Protected Sub DdlTipoComprobante_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlTipoComprobante.SelectedIndexChanged - CambiaTipoComprobante() - End Sub - Private Sub CambiaTipoComprobante() - CambiaTipoDocto() - LimpiaEscondeContado() - End Sub - Private Sub CambiaTipoDocto() - CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString.ToEntero) - ConfiguraTipoDocto() - CargaFolios() - CargaEstatusFactura(DdlTipoComprobante.SelectedValue) - UpEstatus.Update() - - If UsuarioActual.TienePermisoProceso(274) Then - TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant" - End If - - 'REINICIALIZA VALORES DE ENTREGA POR ADELANTADO - RequiereAlmacenDestino = False - TrAlmacenAsignado.Visible = False - - If DdlTipoComprobante.SelectedValue = "Cot" And UsuarioActual.Empresa.Funcionalidad(135) = "1" Then - Alert("Se ocupa una autorización.", TipoMensaje.MsgAdvertencia) - TrDireccion.Visible = False - TrCiudad.Visible = False - TrRFC.Visible = False - 'RBLPago.Enabled = False - RBLPago.SelectedValue = "2" - TxtFechaVencimientoCotizacion.Text = Now.ToString - GvPS.Columns(5).Visible = True - ThTiempoEntrega.Visible = True - ThTiempoEntrega2.Visible = True - ChkEnviarFactura.Checked = True - UpnTools.Update() - tdTelefonoGen.Visible = False - tdTxtTelefonoGen.Visible = False - If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then - ChkEnviarFactura.Checked = False - End If - - Else - If DdlTipoComprobante.SelectedValue = "Cot" Then - TrDireccion.Visible = False - TrCiudad.Visible = False - TrRFC.Visible = False - 'RBLPago.Enabled = False - 'RBLPago.SelectedValue = "2" - TxtFechaVencimientoCotizacion.Text = Now.ToString - GvPS.Columns(5).Visible = True - ThTiempoEntrega.Visible = True - ThTiempoEntrega2.Visible = True - tdTelefonoGen.Visible = False - tdTxtTelefonoGen.Visible = False - - 'CUANDO SEA COMPUPROVEEDORES NO MANDA COTIZACIONES - If UsuarioActual.CveEmpresa = 72 Then - ChkEnviarFactura.Checked = False - ChkEnviarFactura.Visible = False - LblEnviarMail.Visible = False - End If - - If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then - ChkEnviarFactura.Checked = False - End If - Else - TrDireccion.Visible = True - TrCiudad.Visible = True - TrRFC.Visible = True - GvPS.Columns(5).Visible = False - ThTiempoEntrega.Visible = False - ThTiempoEntrega2.Visible = False - RBLPago.Enabled = True - - LblMensaje.Visible = UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue.Contiene("Ing") - - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev") Then - ChkEnviarFactura.Checked = EnviarCorreoCliente - ChkEnviarFactura.Visible = True - LblEnviarMail.Visible = True - ObtenerFechaVencimientoCER() - - If DdlTipoComprobante.SelectedValue.Contiene("Egs") Then - - 'se cargan las facturas timbradas - 'CargaFacturasRelacionar() - 'RegistraScript("$('#DivRelacionarFacturasNC').modal('show');") - End If - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then - - 'ENTREGA POR ADELANTADO - If UsuarioActual.Empresa.Funcionalidad(145) = "1" And Not DdlTipoComprobante.SelectedValue.Contiene("PA") Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then - RequiereAlmacenDestino = True - - 'If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then - ' TrAlmacenAsignado.Visible = True - 'End If - - Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero - If CveAlmacenDestino > 0 Then - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)") - DdlAlmacenAsignado.DataBind() - DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString)) - DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString - Else - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (10)") - DdlAlmacenAsignado.DataBind() - End If - UpParametros.Update() - Else - RequiereAlmacenDestino = False - TrAlmacenAsignado.Visible = False - End If - - 'ENVIO DE FACTURA - If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then - ChkEnviarFactura.Checked = EnviarCorreoCliente - ChkEnviarFactura.Visible = True - LblEnviarMail.Visible = True - End If - - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "PA", "Pd2") AndAlso (ReceptorRFC = "XAXX010101000" Or LblRFC.Text = "XAXX010101000") Then - TrDireccion.Visible = False - TrCiudad.Visible = False - TrRFC.Visible = False - tdTelefonoGen.Visible = True - tdTxtTelefonoGen.Visible = True - Else - TxtAtencionA.Text = "" - TxtTelefonoGenerico.Text = "" - End If - End If - - - End If - - If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then - ' IPP 15 Julio 2017 - ERA FALSE - ImgAntiPend.Visible = False - ElseIf Opcion <> "Op" Then - ImgAntiPend.Visible = True - End If - - - - TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString - - TabAlmacen.Enabled = DdlTipoComprobante.SelectedValue <> "Ant" - - 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO - If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO - BtnEmitirImprimir.Visible = True - TrVistaPrevia.Visible = True - Else - If LblCliente.Text <> "Cliente" And Not EstatusCliente Then - Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) - End If - BtnEmitirImprimir.Visible = EstatusCliente - TrVistaPrevia.Visible = EstatusCliente - End If - - - - TrAtencionA.Visible = True - tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") - tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") - - - Updatetabs.Update() - UPCondicionesPago.Update() - UpCliente.Update() - UpPS.Update() - End Sub - Protected Sub DdlSucursalCliente_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSucursalCliente.SelectedIndexChanged - CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero) - End Sub - Protected Sub DdlCCEdit_SelectedIndexChanged(sender As Object, e As System.EventArgs) - Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) - Dim CveProyecto As String = DirectCast(sender, DropDownList).SelectedValue - - gvr.FCDropDownList("DDlSubProyecto").Items.Clear() - gvr.FCDropDownList("DDlSubProyecto").DataSource = GlobalDTSubProyectos(CveProyecto.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa) - gvr.FCDropDownList("DDlSubProyecto").DataBind() - gvr.FCDropDownList("DDlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) - - End Sub - Protected Sub DdlClasificacion_SelectedIndexChanged1(sender As Object, e As EventArgs) - Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) - CargaPS(gvr.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero, gvr.FCDropDownLost("DdlPS")) - End Sub - Protected Sub BtnEstimacion_Click(sender As Object, e As EventArgs) Handles BtnEstimacion.Click - Dim Contrato As String = "" - Dim Importe As Decimal = 0 - Dim CvePS As Integer - Dim PS As String - Dim PSCodigo As String - Dim CveUM As Integer - Dim UM As String - Dim CveClasificacion As Integer - Dim Clasificacion As String - Dim CveProyecto As Integer - Dim Proyecto As String - Dim CveSubProyecto As Integer - Dim SubProyecto As String - Dim FechaInicial As String = "" - TmpDT.Rows.Clear() - For Each Row As GridViewRow In GvEst.Rows - If Row.FCCheckBox("Chk").Checked Then - Importe += Row.FCLiteral("LtlImporte").Text.ToDecimal - Contrato = Row.DataKey("NumeroContrato") - CveContrato = Row.DataKey("CveContrato").ToEntero - FechaInicial = Row.DataKey("FechaInicial").ToString.ToDate.ToString("dd MMMM yyyy") - CveSubProyecto = Row.DataKey("CveSubProyecto").ToEntero - End If - Next - - If Importe > 0 Then - CvePS = UsuarioActual.Empresa.Funcionalidad(106).ToEntero - If CvePS > 0 Then - Dim rowPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") - If rowPS IsNot Nothing Then - PS = rowPS("PS").ToString - PSCodigo = rowPS("PSCodigo").ToString - CveUM = rowPS("CveUM").ToString.ToEntero - UM = rowPS("UnidadMedida").ToString - CveClasificacion = rowPS("CveClasificacion").ToString.ToEntero - Clasificacion = rowPS("Clasificacion").ToString - Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto={0}", CveSubProyecto)) - Proyecto = rowSP("Proyecto").ToString - CveProyecto = rowSP("CveProyecto").ToString.ToEntero - SubProyecto = rowSP("SubProyecto").ToString - AgregarProductoServicio(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero), - Importe, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) - - 'AddPS(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero), Importe, 0.16, 0, 0, 1, 0, True, "", CveProyecto, Proyecto, CveSubProyecto, SubProyecto, rowPS("CveTipoPS").ToString.ToEntero, rowPS("Inv_CveMetodoInventario").ToString.ToEntero, CodigoPS:=PSCodigo) - - - DdlTipoComprobante.SelectedValue = "Rem" - DdlTipoComprobante_SelectedIndexChanged(DdlTipoComprobante, Nothing) - - End If - UpParametros.Update() - Tab.ActiveTab = TabGenerales - Else - Alert("La empresa no contiene un producto asignado a la estimació", TipoMensaje.MsgInformacion) - End If - - - Updatetabs.Update() - End If - End Sub - Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlProyecto.SelectedIndexChanged - CargaSubProyecto() End Sub -#End Region + Private Sub EnviaPDFRemision(EnviaCorreo As Boolean) + 'MANDA CORREO + If EnviaCorreo Then -#Region " SUCURSAL FACTURACION " - Private Sub DdlSubProyectoDatos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSubProyectoDatos.SelectedIndexChanged - CambiaSucursalGeneral() - End Sub - Private Sub CambiaSucursalGeneral() - Dim ObjSubProyectos As New ClsSubProyectos - 'Dim ObjSucursal As New ClsSucursales - If ObjSubProyectos.GetSubProyectos() Then - DTSucursal = ObjSubProyectos.DtResultados.FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue.ToEntero)) - 'Dim drc As DataRow - 'drc = DTSucursal(0) - - DdlSubProyecto.Items.Clear() - DdlSubProyecto.DataSource = DTSucursal - DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlSubProyecto.SelectedValue = "-1" - DdlSubProyecto.DataBind() - DdlSubProyecto.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) - CambiaSucursal() - - DdlSubProyectoEjecucion.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) - DdlSubProyectoCobranza.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) - UpDetalle.Update() - - 'If ObjSucursal.GetSucursales(UsuarioActual.CveEmpresa) Then - ' DTSucursal = ObjSucursal.DtResultados.FiltraParametros(String.Format("CveSucursal = {0}", drc("CveSucursal").ToString.ToEntero)) - ' Dim dre As DataRow - ' dre = DTSucursal(0) - ' DdlSucursal.SelectedValue = dre("CveSucursal").ToString - ' CambiaSucursal() - 'End If - End If - ObjSubProyectos.Dispose() - End Sub - Private Sub CambiaSucursal() - CargaFormatoSucursal() - CargaFolios() - CargaVendedores() - CargarAlmacenes() - DdlPS.Attributes.Remove("data-cvesubproyecto") - DdlPS.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) - UpPS.Update() - End Sub - Private Sub CargaFolios() - If ExFolioFactura Then - Exit Sub - End If - If DdlSubProyectoDatos.SelectedValue.ToEntero <= 0 Then - Alert("No se tienen asignadas sucursales", TipoMensaje.MsgError) - Exit Sub - End If - - 'If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue <> "Cot" AndAlso (CveVenta <= 0 Or (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Or CveDevolucion > 0) Then - ' TxtFolio.Text = "" - 'Else - Dim ObjFolios As New ClsGralFolios() - Dim TipoDoctoConsulta As String = If(DdlTipoComprobante.SelectedValue = "Ant", "Ing", If(DdlTipoComprobante.SelectedValue = "PA", "Rem", DdlTipoComprobante.SelectedValue)) - - If ObjFolios.GetFolios(TipoDoctoConsulta, UsuarioActual.CveEmpresa) Then - Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue)) - If DT.Rows.Count > 0 Then - ViewState("CveFolio") = DT.Rows(0)("CveFolio").ToString.ToEntero - 'ViewState("NumAprobacion") = CLng(DT.Rows(0)("Aprobacion").ToString) - 'ViewState("FechaAprobacion") = DT.Rows(0)("FechaAprobacion").ToString.ToDate - ViewState("FolioActual") = DT.Rows(0)("FActual").ToString - LblSerie.Text = DT.Rows(0)("Serie").ToString - TxtFolio.Text = DT.Rows(0)("FActual").ToString - BtnCrearApartirDe.Enabled = True - BtnEmitirImprimir.Visible = True - TrVistaPrevia.Visible = True - UpFacturar.Update() - Else - Alert("No tiene registrados Folios para " & DdlTipoComprobante.SelectedItem.Text & " en esta sucursal.", TipoMensaje.MsgAdvertencia) - TrEmitir.Visible = False - TrVistaPrevia.Visible = False - BtnCrearApartirDe.Enabled = False - BtnEmitirImprimir.Visible = False - UpFacturar.Update() - End If - DT.Dispose() - End If - ObjFolios.Dispose() - 'End If - - End Sub - Private Sub CargaFormatoSucursal() - Dim dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue))) - If dr IsNot Nothing Then - ViewState("SucCalle") = dr("Calle") - ViewState("SucNoExt") = dr("NoExt") - ViewState("SucNoInt") = dr("NoInt") - ViewState("SucColonia") = dr("Colonia") - ViewState("SucLocalidad") = dr("Localidad") - ViewState("SucMunicipio") = dr("Municipio") - ViewState("SucEstado") = dr("Estado") - ViewState("SucPais") = dr("Pais") - ViewState("SucCP") = dr("CP") - ViewState("FormatoFactura") = dr("FormatoFactura") - ViewState("IVA") = dr("IVA") - DdlIVA.Visible = False - Select Case ViewState("IVA").ToString.ToDouble - Case 0 - DdlIVA.SelectedValue = "1" - PorcentajeIVA = ViewState("IVA").ToString.ToDecimal - Case 0.08 - DdlIVA.SelectedValue = If(EsCreaApartirDe, $"{(TmpDT.MAX("PorcentajeIVA").ToDecimal + 1).ToString}", "1.08") - PorcentajeIVA = If(EsCreaApartirDe, TmpDT.MAX("PorcentajeIVA").ToDecimal, ViewState("IVA").ToString.ToDecimal) - DdlIVA.Visible = If(Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0, True, False) - Case 0.16 - DdlIVA.SelectedValue = "1.16" - PorcentajeIVA = ViewState("IVA").ToString.ToDecimal - End Select - If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 AndAlso (Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0) Then RecalculaIVA() - 'ViewState("SubProyectoPorcentajeIVA") = dr("IVA") - ViewState("TipoFormato") = dr("TipoFormato") - ViewState("Serie") = dr("Serie") - LblSerie.Text = dr("Serie").ToString - If SerieXML <> "" Then LblSerie.Text = SerieXML - Dim CveSubProyecto As Integer = GetSubProyectoSucursal() - If CveSubProyecto > 0 Then CargaSubProyecto(CveSubProyecto) - UPPProy.Update() - - TipoVentaSucursal = dr("TipoVenta").ToString.ToEntero - - If dr("TipoVenta").ToString = "1" Then - LiBuscarPrecio.Visible = True - UpnTools.Update() - - 'activa el modo de pago efectivo directamente, y es venta nueva - If ViewState("CveVenta").ToString.ToEntero < 0 Then InicializaCondicionesPago() - - RBLPago.SelectedValue = "2" - LimpiaEscondeContado() - - If DdlCuentaEfectivo.Items.Count = 2 Then - DdlCuentaEfectivo.SelectedIndex = 0 - End If - - End If - End If - - UpFacturar.Update() - UpPS.Update() - - UpParametros.Update() - End Sub - Private Sub CargaVendedores() - - Dim CveVendedorActual = DdlVendedor.SelectedValue - - DdlVendedor.Items.Clear() - If UsuarioActual.Empresa.Funcionalidad(302) = "1" AndAlso DdlSubProyectoDatos.SelectedValue.ToEntero > 0 Then - DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue)).FiltraParametros("VendedorTipo = 1") - Else - DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros("VendedorTipo = 1") - End If - - DdlVendedor.SelectedValue = "0" - DdlVendedor.Items.Insert(0, New ListItem("Sin Asignar", "0")) - DdlVendedor.DataBind() - - DdlVendedor.SelectedValueExist(CveVendedorActual) - - If Not DdlVendedor.SelectedValue.ToEntero > 0 Then - DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) - End If + 'GUARDA PDF + Dim pdf As Byte() = Nothing + Dim LocalSerieFolio As String = String.Empty + Dim LocalTipoDocto As String = String.Empty + + 'TIMBRADO NUEVO + Try + pdf = PdfFactura(ObjFactura) + Catch ex As Exception + Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError) + End Try + + LocalSerieFolio = ObjFactura.SerieFolio + LocalTipoDocto = ObjFactura.TipoDocto + + Dim ArchivoXML = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) + Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) + + Try + ' BytesPdfCotizacion(CveVenta) + Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF)) + Hilo.Start() + Catch ex As Exception + OnError("Ocurrió error al mandar Mail", ex) + Dim ObjVentas As New ClsVentas + If ChkEnviarFactura.Checked Then + ObjVentas.UpdateVentaMail(3, CveVenta) + Else + ObjVentas.UpdateVentaMail(0, CveVenta) + End If + ObjVentas.Dispose() + End Try + End If End Sub -#End Region -#Region " AGREGAR PS " - Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click - AgregarPS() - End Sub - Private Function ValidaAgregarPS(CvePS As Integer, CveUM As Integer, PU As Double, CveTipoPS As Integer) As Boolean 'NO TOCAR - IPP - - 'VALIDA PARAMETROS - If CvePS <= 0 Or CveUM <= 0 Then - Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) - Return False - End If - - If HdnPS.Value = "" Or HdnPS.Value = "-1" Then - Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) - Return False - End If - - 'SI USA CONTABILIDAD LA CLASIFICACION ES OBLIGATORIA - If DdlClasificacion.SelectedValue.ToEntero <= 0 AndAlso UsuarioActual.Empresa.UsaContabilidad Then - Alert("La Clasificación es obligatoria, favor de seleccionarla", TipoMensaje.MsgAdvertencia) - Return False - End If - - 'SUBPROYECTO OBLIGATORIO - If DdlSubProyecto.SelectedValue.ToEntero <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(120) = "1" Then - Alert("El Subproyecto es obligatorio, favor de seleccionarlo", TipoMensaje.MsgAdvertencia) - Return False - End If - - If CveCliente <= 0 And Not CveEmpresaCRM > 0 Then - Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact', 800, 547, 'N', 'PopUpBuscar')") - Return False - End If - - 'VALIDA PROMOCIONES - Dim ObjVentas As New ClsVentas - If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero, CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then - DtPromociones = ObjVentas.DtResultados - End If - ObjVentas.Dispose() - - 'VALIDA PRECIO CERO (0) - If UsuarioActual.Empresa.Funcionalidad(139).ToString.ToEntero > 0 And PU = 0 And DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {CvePS}").ToDecimal > 0 Then - Alert($"El producto {HdnPS.Value}. No se puede vender a un importe de cero ($0)", TipoMensaje.MsgAdvertencia) - Return False - End If - - - If Not UsuarioActual.TienePermisoProceso(169) Then ' NO VALIDA EXISTENCIAS NI COSTO - PERMISO PARA NO VALIDAR - 'SOLO VALIDA EXISTENCIAS Y COSTO: SI USA INVENTARIOS, SOLO PRODUCTOS TIPO PRODUCTO, SOLO REMISIONES E INGRESOS - If UsuarioActual.Empresa.UsaInventarios AndAlso CveTipoPS = 2 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119))) Then - Dim ObjInventarios As New ClsInventarios - Dim Existencia As Decimal = ObjInventarios.GetExistenciasPS(CvePS, CveUM, UsuarioActual.CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) - Dim Costo As Decimal = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) - - 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal - If Costo = 0 Then Costo = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1) - - ObjInventarios.Dispose() - Dim PrecioMinimo As Decimal = 0 - 'RMF. condicion temporal, para reubicación, precio mínimo - If UsuarioActual.CveEmpresa = 119 Then - 'Dim CvePrecioLista As Integer = 38 - Dim objPS As New ClsProductosServicios - If objPS.GetPSSucursalesALL(CvePS, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then - PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal - If PrecioMinimo > 0 Then - Costo = PrecioMinimo - End If - End If - objPS.Dispose() - - End If - - If DdlTipoComprobante.SelectedValue <> "Cot" And ChkSinExistencia.Checked = False Then - 'VALIDA EXISTENCIA - If UsuarioActual.CveEmpresa.Contiene({72, 80, 119}) Then - If Existencia - TmpDT.SUM("Cantidad", $"CvePS = {CvePS}") < TxtCantidad.Text.ToDouble Then - Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia) - Return False - End If - End If - End If - - 'VALIDA COSTOS - If Not CveContrato > 0 Then - - 'BANDERAS PARA VALIDACIONES - Dim EsValido = False - Dim EsValidoMayor = False - Dim CostoMenor = 0.0D - Dim CostoMayor = 0.0D - - 'PRECIO MINIMO - If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then - CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) - If PrecioMinimo > 0 Then CostoMenor = PrecioMinimo - - 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA - If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= CostoMenor Then - EsValido = True - End If - Else - EsValido = True - End If - - 'PRECIO MAXIMO - If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then - CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo) - 'SI EL PRECIO ES MAYOR AL COSTO MAXIMO, SI PASA - If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) <= CostoMayor Then - EsValidoMayor = True - End If - Else - EsValidoMayor = True - End If - - 'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR - 'SIRVE PARA VALIDAR PRECIOS DEBAJO DEL PRECIO MINIMO PERMITIDO - If Not EsValido Then - If DtPromociones.FiltraParametros($"CvePS = {CvePS}").Rows.Count > 0 Then - If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {CvePS}").ToDecimal Then - EsValido = True - End If - End If - End If - - 'NO DEJA REGISTRAR MENOS AL PRECIO MINIMO - Dim MensajeCosto As New StringBuilder - Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) - If Not EsValido Then - MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio menor de su Costo
    ", HdnPS.Value) - If TienePermisoImportes Then - MensajeCosto.AppendFormat("El costo del producto es: ${0}
    ", Costo) - MensajeCosto.AppendFormat("El rango menor aceptado es: {0}% ${1}
    ", UsuarioActual.Empresa.Funcionalidad(129).ToEntero, CostoMenor) - MensajeCosto.AppendFormat("El precio indicado es: ${0} ({1}% de ganancia)
    ", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) - End If - - Alert(String.Format(MensajeCosto.ToString), TipoMensaje.MsgAdvertencia) - Return False - End If - - 'NO DEJA REGISTRAR MAS AL PRECIO MAXIMO - If Not EsValidoMayor Then - MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio mayor de su rango aceptado
    ", HdnPS.Value) - If TienePermisoImportes Then - MensajeCosto.AppendFormat("El costo del producto es: ${0}
    ", Costo) - MensajeCosto.AppendFormat("El rango mayor aceptado es: {0}% ${1}
    ", UsuarioActual.Empresa.Funcionalidad(133).ToEntero, CostoMayor) - MensajeCosto.AppendFormat("El precio indicado es: ${0} ({1}% de ganancia)
    ", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) - End If - Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia) - Return False - End If - - End If - End If - End If - - - - Return True - - End Function - Private Sub AgregarPS() - - 'SELECCIONA EL PS DEPENDIENDO LA MODALIDAD (CODIGO BARRAS - DDL) - Dim CvePS = -1 - If DIVCod.Visible Then - CvePS = HdnCvePS.Value.ToEntero - Else - CvePS = DdlPS.SelectedValue.ToEntero - End If - - If ValidaAgregarPS(CvePS, DdlUnidadMedida.SelectedValue.ToEntero, TxtPrecio.Text.Trim.ToDouble, HdnTipoPS.Value.ToEntero) Then - - If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then - CvePSAmortizacion = DdlPS.SelectedValue.ToEntero.ToEntero - End If - - Dim Descuento As Decimal = HdnDescuento.Value.ToDecimal - If HdnTipoDescuento.Value = "0" Then - Descuento = HdnDescuento.Value.ToDecimal * TxtCantidad.Text.ToDecimal - End If - - AgregarProductoServicio(TxtCantidad.Text.ToDecimal, DdlUnidadMedida.SelectedValue.ToEntero, DdlUnidadMedida.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero, DdlClasificacion.SelectedItem.Text, - CvePS, "", TxtObsPS.Text.Trim, If(CvePSAmortizacion > 0, TxtPrecio.Text.Trim.ToDecimal * -1, TxtPrecio.Text.Trim.ToDecimal), Descuento, - DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, - SerieLote:=If(DIVCod.Visible, TxtCodigoSerie.Text.Trim, ""), TiempoEntrega:=TxtTiempoEntrega.Text, CuentaPredial:=TxtCuentaPredial.Text.Trim, RegeneraIEPS:=ClienteDesglosaIEPS) - - CalculaUsados() - - CalculaTotalesVenta() - - LimpiaAgregar() - - 'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW - If AplicaComercioExterior Then - CargaGvComercioExterior() - End If - End If - - ''NO SIRVE PARA NADA - NO SE USAN LAS VARIABLES - IPP 28 AGOSTO 2017 - 'For Each gvr As GridViewRow In GVAnticipos.Rows - ' Dim total As Decimal = TxtTotal.Text.ToString.ToDecimal - ' Dim saldo As Decimal = gvr.DataKey("Saldo").ToDecimal - ' Dim maxsaldo As Decimal - ' If total > saldo Then - ' maxsaldo = saldo - ' Else - ' maxsaldo = total - ' End If - 'Next - - End Sub - - - Private Sub AgregarPSPYME() - If Modalidad = "A" Then - - Dim CveProyecto As Integer = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedValue, "0").ToString.ToEntero - Dim Proyecto As String = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedItem.Text, "").ToString - - Dim CveSubProyecto As Integer = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedValue, "0").ToString.ToEntero - Dim SubProyecto As String = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedItem.Text, "").ToString - - AgregarProductoServicio(TxtCantidadPyME.Text.ToDecimal, DdlUMPyME.SelectedValue.ToEntero, DdlUMPyME.SelectedItem.Text, DdlClasificacionPyME.SelectedValue.ToEntero, DdlClasificacionPyME.SelectedItem.Text, - DdlPSPyME.SelectedValue.ToEntero, DdlPSPyME.SelectedText, TxtObsPyME.Text, TxtPrecioPyME.Text.ToDecimal, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) - - CalculaTotalesVenta() - - - - ElseIf Modalidad = "U" Then - - Dim ErrorEdit As Boolean = True - Dim Contador As Integer = 0 - For Each row As DataRow In TmpDT.Rows - If row("Consec").ToString.ToEntero = Index Then - ErrorEdit = False - Exit For - End If - Contador = Contador + 1 - Next - If ErrorEdit = True Then - Exit Sub - Else - TmpDT.AcceptChanges() - TmpDT.Rows.RemoveAt(Contador) - TmpDT.AcceptChanges() - End If - End If - - End Sub - Private Sub LimpiaAgregar() - TxtCantidad.Text = "" - HdnPS.Value = "-1" - HdnCodigoPS.Value = "-1" - HdnTipoPS.Value = "-1" - HdnTipoInv.Value = "-1" - - DdlClasificacion.SelectedIndex = 0 - - If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then - DdlPS.SelectedValue = "-1" - Else - DdlPS.SelectedValue = "" - DdlPS.SelectedText = "" - End If - - TxtObsPS.Text = "" - TxtPrecio.Text = "" - LblTotalPS.Text = "0.00" - HdnIVAPS.Value = "-1" - HdnIVARetAPS.Value = "-1" - HdnAplicaIEPS.Value = "False" - HdnPorcentajeIEPS.Value = "0" - HdnAsientoContable.Value = "-1" - HdnCtaContable.Value = "-1" - HdnAplicaParaConcepto.Value = "False" - HdnCodigo.Value = "-1" - TxtCuentaPredial.Text = "" - ' codigo comentado RMF. 2016.06.13, esto paa que respete el que tenga selecionado e nla sucursal - 'DdlProyecto.SelectedIndex = 0 - 'DdlSubProyecto.Items.Clear() - 'DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) - TxtCantidad.Focus() - - 'Limpia descuentos - HdnTipoDescuento.Value = "-1" - HdnDescuento.Value = "0" - LblPrecio1.Text = "0.00" - LblTotalPS1.Text = "0.00" - TxtPorDescP.Text = "0" - TxtDescP.Text = "0" - LblDescuento.Text = "0.00" - LblPrecioFinal.Text = "0.00" - - 'CODIGO BARRAS - TxtCodigoBarras.Text = "" - TxtCodigoSerie.Text = "" - - 'FOCUS DEPENDIENDO MODALIDAD DE CODIGO BARRAS - If DIVCod.Visible Then - TxtCodigoBarras.Focus() - Else - TxtCantidad.Focus() - End If - - UPPDescuento.Update() - UpINV.Update() - UPPPS.Update() - End Sub - Private Function AgregarProductoServicio(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String, - PU As Decimal, Descuento As Decimal, - CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, - Optional SerieLote As String = "", Optional TiempoEntrega As String = "", Optional EntregaDirecta As Integer = 0, - Optional CveContratoDetalle As Integer = 0, Optional CveVentaDetalle As Integer = 0, Optional CveMovimientoDetallePedido As Integer = 0, - Optional CveOrdenCompraDetalle As Integer = 0, Optional CveVentaDetalleRemision As Integer = 0, Optional CveVentaDetalleCotizacion As Integer = 0, - Optional CuentaPredial As String = "", Optional RegeneraIEPS As Boolean = True, Optional CveVentaDetallePedido2 As Integer = 0, - Optional SeActualiza As Boolean = False) As Boolean - - Dim Retorno As Boolean = False - If Not CvePS > 0 Then - Alert("Ocurrió un error al cargar la información del producto a agregar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError) - Return False - End If - - If (Obs.Length + PS.Length > 1000) AndAlso DdlTipoComprobante.SelectedValue <> "Cot" Then - Alert(String.Format("El Nombre y observación del producto tiene longitud de {0} caracteres y excede los 1000 caracteres permitidos.", Obs.Length + PS.Length), TipoMensaje.MsgAdvertencia) - Return False - End If - - 'VALIDA CONCEPTOS EN CERO - YA SE VALIDA ANTES CON FUNCIONALIDAD - A MIRAS DE ELIMINAR - IPP 28 AGOSTO 2017 - If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant") Then - If UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso CveOrdenCompraDetalle = 0 Then ' si viene de una oc, se permiten valores en cero - If Cantidad * PU <= 0 Then - If Not DdlTipoComprobante.SelectedValue = "DPe" Then - Alert("El importe del concepto debe ser mayor a cero. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Return False - End If - End If - End If - End If - - Dim Row As DataRow = Nothing - Dim TotalCalculableImpuestos As Decimal = 0 - PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos - - Row = TmpDT.NewRow() - Row("CveProyecto") = CveProyecto - Row("Proyecto") = Proyecto - Row("CveSubProyecto") = CveSubProyecto - Row("SubProyecto") = SubProyecto - Row("SerieLote") = SerieLote - Row("TiempoEntrega") = TiempoEntrega - Row("Orden") = TmpDT.Rows.Count + 1 - Row("Cantidad") = Cantidad - Row("CveUM") = CveUM - Row("UM") = UM - Row("CveClasificacion") = CveClasificacion - Row("Clasificacion") = Clasificacion - Row("CvePS") = CvePS - Row("Obs") = Obs - - - - Dim DrPS As DataRow = Nothing - - DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") ' Estado = -1 - - If DrPS Is Nothing Then - Alert("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.", TipoMensaje.MsgError) - Return False - End If - - If (DrPS("SATClaveUnidadMedida").ToString = "" Or DrPS("SATClavePS").ToString = "") Then - 'VALIDA CLAVESAT - If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then 'DOCUMENTOS DONDE NO SE VALIDA - If DrPS("SATClavePS").ToString = "" Then - MensajeCveSAT.AppendFormat("{0}-{1}: Sin producto SAT
    ", DrPS("Codigo").ToString, DrPS("PS").ToString) - Return False - ElseIf DrPS("SATClaveUnidadMedida").ToString = "" Then - MensajeCveSAT.AppendFormat("{0}-{1}: Sin Unidad Medida SAT
    ", DrPS("Codigo").ToString, DrPS("PS").ToString) - Return False - End If - End If - End If - - If Not ClienteDesglosaIEPS Then - If Not RegeneraIEPS Then - PU = PU * (1 + DrPS("IEPSPorcentaje").ToString.ToDecimal) - End If - DrPS("IEPSPorcentaje") = 0 - End If - - 'verifica si tiene ventaminima - If Cantidad > 0 AndAlso DrPS("VentaMinima").ToString.ToDecimal > 0 Then - 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... - If Cantidad Mod DrPS("VentaMinima").ToString.ToDecimal <> 0 Then - Alert(String.Format("El producto se vende solo en cantidades de {0}", DrPS("VentaMinima").ToString)) - Return False - End If - End If - - TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento - - Row("PU") = PU - Row("Codigo") = DrPS("Codigo") - Row("NoIdentificacion") = DrPS("Codigo") - Row("ClaveSATFraccionArancelaria") = DrPS("ClaveSATFraccionArancelaria") - Row("ClaveSATUnidadAduana") = DrPS("ClaveSATUnidadAduana") - Row("ClaveSATFraccionArancelariaDescripcion") = DrPS("ClaveSATFraccionArancelariaDescripcion") - Row("ClaveSATUnidadAduanaDescripcion") = DrPS("ClaveSATUnidadAduanaDescripcion") - If Modalidad = "U" Then - Row("Consec") = Index - Else - Row("Consec") = TmpDT.Rows.Count + 1 - End If - - Row("PS") = DrPS("PS") - Row("CodigoPS") = DrPS("PSCodigo").ToString - Row("CveTipoPS") = DrPS("CveTipoPS") - Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario") - Row("CveTamaño") = DrPS("CveTamaño") - - If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion") - If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion") - - If DrPS("IVA").ToString.Contiene("-1", "") Then - Row("PorcentajeIVA") = PorcentajeIVA - Else - Row("PorcentajeIVA") = DrPS("IVA") - End If - - Row("IVA") = Row("PorcentajeIVA") - Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - - - Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) - Row("PorcentajeRetIVA") = ClienteRetIVA - Row("PorcentajeRetISR") = ClienteRetISR - Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje") - Row("ImporteIEPS") = Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - Row("IEPS") = Row("ImporteIEPS") - Row("Descuento") = Math.Round(Descuento, NumeroDecimales) - Row("TipoDescuento") = HdnTipoDescuento.Value - Row("Total") = (Cantidad * PU) - Row("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) - 'Row("AsientoContableVentas") = DrPS("AsientoContableVentas") - ' Row("IdCtaContVentas") = IdCtaContable - ' Row("AplicaParaConcepto") = AplicaParaConcepto - - Row("SATClaveProdServ") = DrPS("SATClavePS") - Row("SATClaveUM") = DrPS("SATClaveUnidadMedida") - - If UsuarioActual.Empresa.UsaAC Then - Row("CvePresupuestoIngreso") = Me.DdlFuenteRecaudacion.SelectedValue - End If - - Row("EntregaDirecta") = EntregaDirecta - 'Contratos - Row("CveContratoDetalle") = CveContratoDetalle - Row("CveVentaDetalle") = CveVentaDetalle - Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido - Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle - Row("CveVentaDetalleRemision") = CveVentaDetalleRemision - Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion - Row("CveVentaDetallePedido2") = CveVentaDetallePedido2 - Row("CuentaPredial") = CuentaPredial - - If UsuarioActual.CveEmpresa = 119 Then - If Not RemisionesLista.Count > 0 Then 'SI VIENE DE REMISION NO SE CONSIDERA - - 'MONEDA DIFERENTE DEL PS AL PRIMER PS AGREGADO - If DdlMoneda.Enabled = False And CveVenta < 0 And TmpDT.Rows.Count > 0 Then - If DdlMoneda.SelectedValue <> DrPS("CveMoneda").ToString Then - Alert($"La moneda base del producto: {DrPS("PSCodigo").ToString} es diferente a la moneda del documento.", TipoMensaje.MsgAdvertencia) - Return False - End If - End If - - 'ACTIVA PRODUCTOS DE LA MISMA MONEDA - If TmpDT.Rows.Count = 0 And CveVenta < 0 Then - DdlMoneda.SelectedValueExist(DrPS("CveMoneda").ToString) - CambiaMoneda() - DdlMoneda.Enabled = False - End If - End If - End If - - - 'RECARGAR GV - TmpDT.Rows.Add(Row) - - - 'AGREGA PS ADICIONAL - If UsuarioActual.Empresa.Funcionalidad(561).ToString = "1" AndAlso GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows.Count > 0 AndAlso ChkPoliza.Checked AndAlso Not SeActualiza Then - For Each Dr As DataRow In GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows - Dim CvePSAdicional As Integer = Dr("CvePSAdicional").ToString.ToEntero - Dim DrPoliza As DataRow = TmpDT.NewRow() - DrPoliza.ItemArray = Row.ItemArray - Dim DrPSAdicional = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSAdicional).Rows(0) - If DrPSAdicional IsNot Nothing Then - DrPoliza("CvePS") = CvePSAdicional - DrPoliza("PS") = DrPSAdicional("PS").ToString - DrPoliza("CveUM") = DrPSAdicional("CveUM").ToString.ToEntero - DrPoliza("UM") = DrPSAdicional("UnidadMedida").ToString - DrPoliza("CveClasificacion") = DrPSAdicional("CveClasificacion").ToString.ToEntero - DrPoliza("Clasificacion") = DrPSAdicional("Clasificacion").ToString - DrPoliza("CodigoPS") = DrPSAdicional("PSCodigo").ToString - DrPoliza("CveTipoPS") = DrPSAdicional("CveTipoPS") - DrPoliza("CveTipoInvPS") = DrPSAdicional("Inv_CveMetodoInventario") - DrPoliza("NoIdentificacion") = DrPSAdicional("Codigo") - If Modalidad = "U" Then - DrPoliza("Consec") = Index - Else - DrPoliza("Consec") = TmpDT.Rows.Count + 1 - End If - Row("Orden") = TmpDT.Rows.Count + 1 - DrPoliza("Cantidad") = If(Dr("Cantidad").ToString.ToDecimal > 0, Dr("Cantidad").ToString.ToDecimal, Cantidad) - PU = 0 - - Dim PrecioSugerido As Decimal = 0 - Dim CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero - If CvePrecioListaPS > 0 Then - Dim ObjPS As New ClsProductosServicios - If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSAdicional) Then - - PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDecimal - If PrecioSugerido = 0 Then - Dim ObjInventarios As New ClsInventarios - Dim CostoPS = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString.ToDecimal, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) - - 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal - If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString.ToDecimal, -1, "-1", TxtFecha.Text.ToDate, -1) - - ObjInventarios.Dispose() - Dim PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal - If CostoPS > 0 And PorcentajePrecio > 0 Then - PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS - End If - End If - ObjPS.Dispose() - End If - End If - - - If PrecioSugerido > 0 Then - PU = PrecioSugerido - End If - PU = Math.Round(PU, 6) - DrPoliza("PU") = PU - TotalCalculableImpuestos = (DrPoliza("Cantidad").ToString.ToDecimal * (PU)) - Descuento - - If DrPSAdicional("IVA").ToString.Contiene("-1", "") Then - DrPoliza("PorcentajeIVA") = PorcentajeIVA - Else - DrPoliza("PorcentajeIVA") = DrPSAdicional("IVA") - End If - DrPoliza("IVA") = DrPoliza("PorcentajeIVA") - DrPoliza("ImporteIVA") = Math.Round(DrPoliza("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - DrPoliza("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) - DrPoliza("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) - DrPoliza("PorcentajeRetIVA") = ClienteRetIVA - DrPoliza("PorcentajeRetISR") = ClienteRetISR - DrPoliza("PorcentajeIEPS") = DrPSAdicional("IEPSPorcentaje") - DrPoliza("ImporteIEPS") = Math.Round(DrPSAdicional("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) - DrPoliza("IEPS") = DrPoliza("ImporteIEPS") - DrPoliza("Descuento") = Math.Round(Descuento, NumeroDecimales) - DrPoliza("TipoDescuento") = HdnTipoDescuento.Value - DrPoliza("Total") = (DrPoliza("Cantidad").ToString.ToDecimal * PU) - DrPoliza("TotalImporte") = Math.Round(DrPoliza("Cantidad").ToString.ToDecimal * PU, NumeroDecimales) - DrPoliza("SATClaveProdServ") = DrPSAdicional("SATClavePS") - DrPoliza("SATClaveUM") = DrPSAdicional("SATClaveUnidadMedida") - - TmpDT.Rows.Add(DrPoliza) - End If - Next - End If - - Retorno = True - Return Retorno +#End Region + +#Region " ANTICIPOS " + Private Sub CargaAnticipos(CveCliente As Integer) + + HdnTieneAnticipos.Value = "0" + If CveCliente > 0 Then + + HdnIVACalculado.Value = "0" + HdnFolioFiscalNC.Value = "0" + LblAntAplicados.Text = "" + LblAntAplicados.Visible = False + LblAmortizacion.Text = "0.00" + HdnTipoDescuento.Value = "-1" + HdnTieneAnticiposVinculados.Value = "0" + + Dim ObjMovtos As New ClsMovimientos() + If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, DdlMoneda.SelectedValue.ToEntero) Then + GVAnticipos.DataSource = ObjMovtos.DtResultados.FiltraParametros($"Saldo > 0 AND SaldoSubtotal > 0 {If(CveVenta < 0, "AND Tipo = 'Ant'", "")} {If(DdlTipoComprobante.SelectedValue = "Ant", "AND Tipo = 'NC'", "")}") + If ObjMovtos.DtResultados.SUM("Saldo", "Saldo > 0 AND SaldoSubtotal > 0 AND Tipo = 'Ant'") > 0 Then + HdnTieneAnticipos.Value = "1" + End If + Else + GVAnticipos.DataSource = Nothing + End If + ObjMovtos.Dispose() + + If CveVenta <= 0 OrElse (EsCreaApartirDe Or CveDevolucion > 0) Then + divAmortizacionTipo.Visible = True + divAmortizacionTipoRelacion.Visible = True + End If + + If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then + DdlTipoAmortizacionAnticipo.Items.Add(New ListItem("Amortización anticipo sobre factura en cero", "3")) + End If + + If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then + DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1")) + End If + + GVAnticipos.Columns(4).Visible = False + GVAnticipos.Columns(7).Visible = False + + GVAnticipos.DataBind() + End If + UpAnticipos.Update() + End Sub + + Protected Sub GVAnticipos_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowCreated + If e.Row.RowType = DataControlRowType.Header Then + e.Row.ClientIDMode = ClientIDMode.Static + e.Row.ID = String.Format("TrH{0}", e.Row.RowIndex) + ElseIf e.Row.RowType = DataControlRowType.DataRow Then + e.Row.ClientIDMode = ClientIDMode.Static + e.Row.ID = String.Format("Tr{0}", e.Row.RowIndex) + e.Row.FCCheckBox("Chk").ID = "Chk" & e.Row.RowIndex + e.Row.FCTextBox("TxtAnticipo").ID = "TxtAnticipo" & e.Row.RowIndex + e.Row.FCTextBox("TxtTC").ID = "TxtTC" & e.Row.RowIndex + DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ID = "CVAmortAnti" & e.Row.RowIndex + DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).ID = "VCOAmortAnti" & e.Row.RowIndex + DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ControlToValidate = "TxtAnticipo" & e.Row.RowIndex + DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).TargetControlID = "CVAmortAnti" & e.Row.RowIndex + End If + End Sub + Protected Sub GVAnticipos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + + If e.Row.RowIndex = 0 Then + e.Row.Cells(1).Width = Unit.Pixel(60) + e.Row.Cells(2).Width = Unit.Pixel(100) + e.Row.Cells(3).Width = Unit.Pixel(80) + e.Row.Cells(4).Width = Unit.Pixel(80) + End If + + e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right + + If e.Row.DataKey("Saldo").ToDouble < 0 Then e.Row.Cells(3).ForeColor = Drawing.Color.Red + If e.Row.DataKey("Saldo").ToDouble = 0 Then e.Row.FCLiteral("LtlAnticipos").Text = "" + + Dim saldo As Decimal = 0 + Dim tipoCambio As Decimal = 0 + Dim total As Decimal = TxtTotal.Text.ToString.ToDecimal + + + If CveVentaRelacion > 0 Then ' dejo seleccionado el la venta relacionado en anticipo + If e.Row.DataKey("CveVenta").ToEntero = CveVentaRelacion Then + + e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Checked = True + e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Text = ImporteRelacion.ToString + + End If + End If + + + If e.Row.DBCampo("Tipo").ToString = "NC" And e.Row.DataKey("CveVenta").ToString.ToEntero > 0 Then + If e.Row.DBCampo("CveMoneda").ToString.ToEntero = 2 Then + tipoCambio = e.Row.DataKey("TipoCambio").ToString.ToDecimal + Else + tipoCambio = GlobalTipoCambio(e.Row.DataKey("Fecha").ToString.ToDate).ToDecimal + End If + + e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Text = tipoCambio.FormatoNumero(4) + + If DdlMoneda.SelectedValue.ToEntero = 1 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 1 Then + saldo = e.Row.DataKey("Saldo").ToDecimal + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 1 And tipoCambio > 0 Then + saldo = (e.Row.DataKey("Saldo").ToString.ToDecimal / tipoCambio) + ElseIf DdlMoneda.SelectedValue.ToEntero = 1 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 2 Then + saldo = (e.Row.DataKey("Saldo").ToString.ToDecimal * tipoCambio) + Else + saldo = e.Row.DataKey("Saldo").ToDecimal + End If + Else + saldo = e.Row.DataKey("Saldo").ToString.ToDecimal + + If CveVenta <= 0 Then + saldo = e.Row.DataKey("SaldoSubTotal").ToString.ToDecimal + e.Row.FCLiteral("LtlAnticipos").Text = saldo.FormatoNumero + End If + + End If + + Dim maxsaldo As Decimal + If total > saldo Then + maxsaldo = saldo + Else + maxsaldo = total + End If + + e.Row.FCLiteral("MonedaVenta").Text = saldo.FormatoNumero(4) + e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Attributes.Add("onclick", String.Format("chkAnt(this,{0},{1});", e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, saldo)) + e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, saldo)) + e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("CambioTipoMoneda({0},{1},{2},{3},{4});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, e.Row.DataKey("Saldo"), e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).ClientID, e.Row.DataKey("CveMoneda"))) + + If e.Row.DataKey("CveIE").ToString.ToEntero > 0 Then + e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveIE"), e.Row.DataKey("Folio")) + Else + e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveVenta"), e.Row.DataKey("Folio")) + End If + + If e.Row.DataKey("ISTotal") = "1" Then + e.Row.Cells(0).Visible = False + e.Row.Cells(1).ColumnSpan = 3 + e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Right + e.Row.FCLiteral("LtlFactura").Text = String.Format("Total {0} ", e.Row.DataKey("Tipo")) + e.Row.BackColor = Drawing.Color.LightGray + e.Row.Cells(2).Visible = False + e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Visible = False + e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False + e.Row.FCLabel("LblTotalAnticipos").Visible = True + e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right + End If + + 'SI UN REGISTRO ES DE DIFERENTE MONEDA AL DOCUMENTO SE MUESTRAN LAS COLUMNAS + If e.Row.DBCampo("CveMoneda").ToString.ToEntero > 0 And e.Row.DBCampo("CveMoneda").ToString.ToEntero <> DdlMoneda.SelectedValue.ToEntero Then + GVAnticipos.Columns(4).Visible = True + GVAnticipos.Columns(6).Visible = True + End If + + + If e.Row.DBCampo("CveMoneda").ToString.ToEntero = DdlMoneda.SelectedValue.ToEntero Then + e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False + End If + + + + + End If + End Sub + Protected Sub BtnAceptarAnticipos_Click(sender As Object, e As System.EventArgs) Handles BtnAceptarAnticipos.Click + Anticipos() + End Sub + Private Sub Anticipos() + + + If CveVenta > 0 And CveCliente > 0 And Not EsCreaApartirDe And CveDevolucion <= 0 Then + + + 'Dim TotalAnticipo As Decimal = 0 + 'Dim DescuentoTotal As Decimal = LblDescuentos.Text.ToDecimal + 'Dim CveSubProyecto As Integer = -1 + + + 'If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then + ' CveSubProyecto = TmpDT.FiltroPrimeroValor("CveSubProyecto").ToEntero + 'End If + + Dim EsAnticipo2017Jam As Boolean = False + For Each gvr As GridViewRow In GVAnticipos.Rows + If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then + If gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal > SaldoVenta Then + Alert("No puede ingresar un importe mayor al saldo", TipoMensaje.MsgAdvertencia) + Exit Sub + ElseIf UsuarioActual.CveEmpresa = 119 AndAlso gvr.DataKey("Tipo").ToString = "NC" AndAlso gvr.DataKey("Fecha").ToDate.Year <= 2017 Then + EsAnticipo2017Jam = True + End If + End If + Next + + Dim ObjConta As New ClsContabilidad + Dim ObjVenta As New ClsVentas(ObjConta.IniciaTransacSQL()) + Dim ObjContpaq As ClsContPAQi = Nothing + + Dim CvePrepoliza As Integer + Dim ErrorConta As Boolean + Dim CveIEAnticipo As Integer + Dim CvePlantillaPoliza As Integer = 10 + Dim PorcentajeAmortizacion As Decimal = 0 + Dim sumaAmorticaciones As Decimal = 0 + Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " + Dim CveCuentaContabilizacion As Integer = 1 + Dim CuentasContablesInvalidas As New StringBuilder + Dim CuentasContablesInvalidasSIG As New StringBuilder + Dim ContaIdPoliza As Integer = 0 + Dim ConceptoAmortizacion As Integer = 0 + Dim UsaComplementariaClientes As Boolean = False + If UsuarioActual.CveEmpresa.Contiene(1, 119) Then UsaComplementariaClientes = True + 'Dim FechaMaxima As Date = MinFecha + + + 'For Each gvr As GridViewRow In GVAnticipos.Rows + ' If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then + ' If gvr.FCLiteral("LtlFecha").Text.ToDate > FechaMaxima Then + ' FechaMaxima = gvr.FCLiteral("LtlFecha").Text.ToDate + ' End If + ' End If + 'Next + + ''[IPP] PARCHE TEMPORAL PARA ANTICIPOS DE JAM + 'If FechaMaxima < "01/01/2018".ToDate And UsuarioActual.CveEmpresa = 119 Then + ' FechaMaxima = "01/01/2018".ToDate + 'End If + + CvePrepoliza = ObjConta.AddPrePolizas("Ventas/Anticipos", CvePlantillaPoliza, TxtTotal.Text.ToDecimal, TxtTotal.Text.ToDecimal, DdlMoneda.SelectedValue.ToEntero, TxtFechaAnticipoCliente.Text.ToDate, String.Format("{0} {1} {2}-{3}", If(EsAnticipo2017Jam, "Aplicación Anticipo 2017", ""), NombreCliente, Serie, TxtFolio.Text), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + + If CvePrepoliza > 0 Then + Dim tipoCambioPago As Decimal = 1 + Dim tipoCambioVenta As Decimal = 1 + Dim PorcentajePago As Decimal = 100 + Dim dtConceptos As DataTable = Nothing + Dim CveMonedaVenta = DdlMoneda.SelectedValue.ToEntero + If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPoliza) Then + dtConceptos = ObjConta.DtResultados + End If + Dim PorcentajeImpuestoAmortizacion As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal + Dim IdCtaIVAXTrasladar As Integer = 0 + Dim IdCtaIVATrasladado As Integer = 0 + Dim CveCuentaIVAXTrasladar As Integer = 0 + Dim CveCuentaIVATrasladado As Integer = 0 + + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then + Dim Dr As DataRow = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).FiltroPrimero("") + IdCtaIVAXTrasladar = Dr("IdCtaIVAXTrasladar").ToString.ToEntero + IdCtaIVATrasladado = Dr("IdCtaIVATrasladado").ToString.ToEntero + CveCuentaIVAXTrasladar = Dr("CveCuentaIVAXTrasladar").ToString.ToEntero + CveCuentaIVATrasladado = Dr("CveCuentaIVATrasladado").ToString.ToEntero + End If + + For Each gvr As GridViewRow In GVAnticipos.Rows + If gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then + + If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then 'Si la venta viene en Pesos y se va a pagar en Pesos + tipoCambioPago = 1 + tipoCambioVenta = 1 + PorcentajePago = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then 'Si la venta viene en Dolares y se va a pagar en Pesos + tipoCambioPago = gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal + tipoCambioVenta = TxtTipoCambio.Text.ToDecimal + PorcentajePago = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal) / gvr.DataKey("Original").ToDecimal + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then 'Si la venta viene en Dolares y se va a pagar en DOLARES + tipoCambioPago = gvr.DataKey("TipoCambio").ToString.ToDecimal + tipoCambioVenta = TxtTipoCambio.Text.ToDecimal + PorcentajePago = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal + ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then 'Si la venta viene en pesos y se va a pagar en DOLARES + tipoCambioPago = gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal + tipoCambioVenta = 1 + PorcentajePago = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal) / gvr.DataKey("Original").ToDecimal + End If + + If dtConceptos IsNot Nothing Then + For Each Row As DataRow In dtConceptos.Rows + + Dim ConceptoContable = Row("CveConcepto").ToString.ToEntero + Dim TipoMovimiento As Boolean = If(Row("TipoMovto").ToString = "True", True, False) + Dim importeMovimiento As Decimal = 0 + Dim importeMX As Decimal = 0 + Dim IdCtaContable As Integer = 0 + Dim CveCuenta As Integer = 0 + Dim FechaMovimiento As Date = Now + Dim Concepto As String = ViewState("VentaFolio").ToString + Dim FuncionalidadFluctuacionImpuestos As Boolean = If(UsuarioActual.Empresa.Funcionalidad(159) = "1", True, False) + Dim TipoCambioGeneral As Decimal = 1 + Dim PorcentajeImpuesto As Decimal = 0 + + Select Case ConceptoContable + Case 2 'Cliente + If Not (gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66) Then + If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal + importeMX = importeMovimiento + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal + importeMX = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta + ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal + importeMX = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta + ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal + importeMX = importeMovimiento + End If + importeMovimiento = Math.Round(importeMovimiento, 2) + importeMX = Math.Round(importeMX, 2) + TipoCambioGeneral = tipoCambioVenta + + If CveMonedaVenta = 1 Then + IdCtaContable = IdCtaContClientes + CveCuenta = CveCuentaClientes + Else + IdCtaContable = IdCtaContComplementaria + CveCuenta = 0 'If(ObjFactura.Cliente IsNot Nothing AndAlso ObjFactura.Cliente.CveCuentaComplementaria > 0, ObjFactura.Cliente.CveCuentaComplementaria, -1) + If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or UsaComplementariaClientes) Then + 'Conta ContPAQ + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + 'Conta SIG + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, 0, Concepto, 207, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioVenta) Then + ErrorConta = True + End If + + importeMX = importeMovimiento + IdCtaContable = IdCtaContMonedaExtranjera + CveCuenta = 0 + + End If + + End If + ConceptoContable = 251 ' cambia para dejar el concepto 2, solamente para pago en banco + End If + Case 11 'Anticipo + If gvr.DataKey("CveConceptoContable").ToString().ToEntero = 3 Then + CveIEAnticipo = gvr.DataKey("CveIE").ToString.ToEntero + + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) + 'Mantenemos la integridad de la suma para el pagocliente + 'SumaAnticipos += row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal + 'sumaAmorticaciones += row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal + TipoCambioGeneral = tipoCambioPago + IdCtaContable = IdCtaContAnticipos + CveCuenta = CveCuentaAnticipos + + If importeMovimiento <> 0 Then + + 'Conta ContPAQ + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + 'Conta SIG + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambioPago, ImporteME:=If(tipoCambioPago = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then + ErrorConta = True + End If + End If + + ' PorcentajeAmortizacion = SumaAnticipos / TxtTotal.Text.ToDecimal + 'Los Anticipos solo ocupan los ivas por trasladar + If PorcentajePago > 0 Then + Dim Importe13 = gvr.DataKey("IVA").ToDecimal + Dim Importe8 = gvr.DataKey("RetIVA").ToDecimal + Dim Importe9 = gvr.DataKey("RetISR").ToDecimal + If Not AgregarPrePolizasXTrasladar(ObjConta, CvePrepoliza, PorcentajePago, tipoCambioPago, CuentasContablesInvalidas, idCuentaContabilizacion, CuentasContablesInvalidasSIG, CveCuentaContabilizacion, Importe13, Importe8, Importe9) Then + ErrorConta = True + End If + End If + End If + importeMovimiento = 0 + Case 91 'Amortizacion Nota de Credito + If gvr.DataKey("CveConceptoContable").ToString().ToEntero = 12 Then + If CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 1 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal + importeMX = importeMovimiento + ElseIf CveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 2 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal + importeMX = importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal + ElseIf CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 2 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal + importeMX = importeMovimiento * gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal + ElseIf CveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 1 Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal + importeMX = importeMovimiento + End If + importeMovimiento = Math.Round(importeMovimiento, 2) + importeMX = Math.Round(importeMX, 2) + + If ObjConta.GetRetCuenta(ConceptoContable, CveCliente) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero + End If + End If + + If importeMovimiento <> 0 Then + 'Conta ContPAQ + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + Dim ImporteComplementaria As Decimal = 0 + If UsaComplementariaClientes = True AndAlso gvr.DataKey("CveMoneda").ToString.ToDecimal > 1 Then + IdCtaContable = IdCtaContComplementaria + CveCuenta = 0 + importeMX = importeMovimiento + ImporteComplementaria = ((importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal) - importeMovimiento).RoundSQL + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, False, importeMovimiento, Concepto, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=ImporteComplementaria, ImporteME:=If(gvr.DataKey("TipoCambio").ToString.ToDecimal = 1, 0, importeMovimiento), TipoCambio:=gvr.DataKey("TipoCambio").ToString.ToDecimal) Then + ErrorConta = True + Exit For + End If + IdCtaContable = IdCtaContMonedaExtranjera + CveCuenta = 0 + End If + + If CveMonedaVenta > 1 AndAlso IdCtaContMonedaExtranjera > 0 Then + IdCtaContable = IdCtaContMonedaExtranjera + CveCuenta = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=gvr.DataKey("TipoCambio").ToString.ToDecimal) Then + ErrorConta = True + Exit For + End If + + 'AMORTIZA NC CONTRA ANTICIPO A CLIENTES + If Not ErrorConta And DdlTipoComprobante.SelectedValue = "Ant" Then + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal) * gvr.DataKey("IVA").ToDecimal) + If ObjConta.AddPrePolizasDetalle(CvePrepoliza, False, importeMovimiento, Concepto, 11, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveVentaAmortizacion:=gvr.DataKey("CveVenta").ToString.ToEntero, ImporteMX:=importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal, CveCuenta:=CveCuenta) Then + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, True, importeMovimiento, Concepto, 4, Concepto, FechaMovimiento, gvr.DataKey("IdCtaContableNC").ToEntero, -1, CveClasificacion:=gvr.DataKey("CveClasificacionNC").ToEntero, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal, CveCuenta:=gvr.DataKey("IdCtaContableNCSIG").ToEntero) Then + ErrorConta = True + Exit For + End If + Else + ErrorConta = True + Exit For + End If + End If + End If + End If + importeMovimiento = 0 + Case 92 'Amortizacion Ingreso X Comprobar + If gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66 Then + CveIEAnticipo = gvr.DataKey("CveIE").ToString.ToEntero + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal + IdCtaContable = IdCtaContClientes + CveCuenta = CveCuentaClientes + + If importeMovimiento <> 0 Then + ' Agregamos el 2 + If tipoCambioPago = 1 Then + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContClientes, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento) Then + ErrorConta = True + End If + Else 'Cuando son dolares + If importeMovimiento <> 0 Then + If IdCtaContComplementaria > 0 Or 0 > 0 Then + 'Agregamos la Complementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, 0, Concepto, 207, Concepto, FechaMovimiento, IdCtaContComplementaria, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then + ErrorConta = True + End If + 'Agregamos la Extranjera + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then + ErrorConta = True + End If + Else + 'Agregamos la Extranjera + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then + ErrorConta = True + End If + End If + End If + End If + + importeMovimiento = ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / TxtTotal.Text.ToDecimal) * TxtIVA.Text.ToDecimal) + importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) + + If importeMX <> 0 Then + + + 'Agregamos el 13 + + IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) + CveCuenta = If(CveCuentaIVAXTrasladar > 0, CveCuentaIVAXTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, 13, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then + ErrorConta = True + End If + + 'Agregamos el 61 + + IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) + CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then + ErrorConta = True + End If + End If + + 'IEPS + importeMovimiento = ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / TxtTotal.Text.ToDecimal) * TxtIEPS.Text.ToDecimal) + importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) + + If importeMX <> 0 Then + + 'Agregamos el 38 + + IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSxTrasladar + CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSxTrasladar + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, 38, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then + ErrorConta = True + End If + + 'Agregamos el 39 + + IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSTrasladado + CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSTrasladado + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then + ErrorConta = True + End If + End If + + 'Agregamos el 92 + importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal 'gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo" & gvr.RowIndex).ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) + importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) + IdCtaContable = IdCtaContAnticipos + CveCuenta = CveCuentaAnticipos + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago) Then + ErrorConta = True + End If + + End If + End If + importeMovimiento = 0 + Case 64 'Ganancia + If CveMonedaVenta <> 1 OrElse gvr.DataKey("CveMoneda").ToEntero <> 1 Then + IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria + + If tipoCambioPago > tipoCambioVenta AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then + importeMovimiento = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioPago) - (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta) 'Añadimos la diferencia de ganancia en la venta + importeMovimiento = Math.Abs(Math.Round(importeMovimiento, 2)) + importeMX = importeMovimiento + End If + Dim TCImpuestos As Decimal = If(FuncionalidadFluctuacionImpuestos, tipoCambioVenta, tipoCambioPago) + TipoCambioGeneral = TCImpuestos + Else + importeMovimiento = 0 + End If + Case 65 'Perdida + If CveMonedaVenta <> 1 OrElse gvr.DataKey("CveMoneda").ToEntero <> 1 Then + IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria + CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria + + If tipoCambioPago < tipoCambioVenta AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then + importeMovimiento = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVenta) - (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioPago) 'Añadimos la diferencia de perdida en la venta + importeMovimiento = Math.Abs(Math.Round(importeMovimiento, 2)) + importeMX = importeMovimiento + End If + Dim TCImpuestos As Decimal = If(FuncionalidadFluctuacionImpuestos, tipoCambioVenta, tipoCambioPago) + TipoCambioGeneral = TCImpuestos + Else + importeMovimiento = 0 + End If + Case Else + importeMovimiento = 0 + End Select + + If importeMovimiento <> 0 Then + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=TipoCambioGeneral) Then + ErrorConta = True + End If + End If + Next + End If + End If + Next + Else + ErrorConta = True + End If + + If ObjConta.ValidacionPrePolizaCuadre(CvePrepoliza, 3) Then + If ObjConta.ValorPolizaDescuadre > 0 Then + GuardaLogAD($"Ventas/Ventas-Anticipos | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrepoliza}", "LogPrePolizas") + ErrorConta = True + End If + End If + + If ErrorConta Then + Alert("Ocurrió un error al amortizar el documento. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError) + ObjConta.RollBack() + If ObjContpaq IsNot Nothing Then ObjContpaq.RollBack() + Else + Dim Msg As New StringBuilder + Msg.Append("Se ha amortizado correctamente") + + 'AJUSTA POLIZA + If ContaIdPoliza > 0 Then + Msg.AppendFormat("

    Ver Póliza", ContaIdPoliza) + End If + + ObjConta.Commit() + BtnAceptarAnticipos.Enabled = False + If ObjContpaq IsNot Nothing Then + + ObjContpaq.AjustaPoliza(ContaIdPoliza) + ObjContpaq.Commit() + End If + Alert(Msg.ToString, TipoMensaje.MsgInformacion) + End If + + ObjConta.Dispose() + Else + + 'cuando no se ha registrado la venta + + If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("1", "2", "3") Then + + Dim Amortizacion As Decimal = 0 + Dim ImpuestosLocalesTemporal As Decimal = 0 + + HdnIVACalculado.Value = HdnIVAOriginal.Value + For Each gvr As GridViewRow In GVAnticipos.Rows + If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked AndAlso gvr.DataKey("CveConceptoContable").ToEntero.Contiene(3) Then + Amortizacion += gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal ' - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) + HdnIVACalculado.Value = (HdnIVACalculado.Value.ToDouble - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal)).FormatoNumero(2) + HdnFolioFiscalNC.Value = gvr.DataKey("FolioFiscal") + + 'CvePSAmortizacion = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePS", "CveConceptoContable = 11").ToEntero + End If + Next + 'Amortizacion += TmpDTImpuestos.SUM("Importe").ToDecimal 'RMF. 2018.12.20- saque de la jugada en la amortización los impuestos locales + + LtlTitDescuentos.Text = "Descuentos:" + + 'cuando es amortización DESCUENTO POR CONCEPTO + If DdlTipoAmortizacionAnticipo.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Cot") Then + LtlTitDescuentos.Text = "Amortización:" + 'If Amortizacion <> LblDescuentos.Text.ToDecimal Then + ' Alert("El importe registrado como descuento no coincide con el importe seleccionado de anticipo.", TipoMensaje.MsgAdvertencia) + ' Exit Sub + 'End If + Dim TotalCalculableImpuestos As Decimal = 0 + Dim Cantidad, PU, Descuento As Decimal + For Each dr As DataRow In TmpDT.Rows + Cantidad = dr("Cantidad").ToString.ToDecimal + PU = dr("PU").ToString.ToDecimal + 'proporcional la mortización al concepto + Descuento = PU * Cantidad / LblSubTotal1.Text.ToDecimal * Amortizacion + TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento + dr("Descuento") = Descuento + dr("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) + dr("ImporteIVA") = Math.Round(dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + dr("ImporteIEPS") = Math.Round(dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) + dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) + dr("PorcentajeRetIVA") = ClienteRetIVA + dr("PorcentajeRetISR") = ClienteRetISR + Next + GvPS.DataSource = TmpDT + GvPS.DataBind() + + Amortizacion = 0 + HdnTipoDescuento.Value = "-1" + HdnDescuento.Value = "0" + RegistraScript("BorraDescuentos();") + LblAntAplicados.Text = "Amortización por descuento" : LblAntAplicados.Visible = True + RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal") + UpPS.Update() + End If + + If DdlTipoComprobante.SelectedValue = "Rem" Then + DdlTipoComprobante.Enabled = False + TrAlmacenAsignado.Visible = False + UpParametros.Update() + End If + + + 'cuando es amortización por NOTA DE CREDITO + If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then + LblAntAplicados.Text = "Amortización por Nota de Crédito" : LblAntAplicados.Visible = True + Amortizacion = 0 + HdnTipoDescuento.Value = "-1" + HdnDescuento.Value = "0" + RegistraScript("BorraDescuentos();") + HdnTieneAnticiposVinculados.Value = "1" + + End If + + 'cuando es AMORTIZACIÓN CON FACTURA EN CERO + If DdlTipoAmortizacionAnticipo.SelectedValue = "3" Then + + If Amortizacion < TxtSubTotal.Text.ToDecimal Then + + '[IPP] LIMPIA LO SELECCIONADO EN CASO DE QUE NO SEA AMORTIZACIÓN DEL 100% 15Junio2018 + Amortizacion = 0 + For Each gvr As GridViewRow In GVAnticipos.Rows + gvr.FCCheckBox($"Chk{gvr.RowIndex}").Checked = False + Next + If CveVenta <= 0 Then + Alert("La amortización no se pudo realizar ya que los importes no cubren la totalidad del documento. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + End If + + End If + LblAmortizacion.Text = Amortizacion.FormatoNumero(2) + + HdnTipoDescuento.Value = "-1" + HdnDescuento.Value = "0" + RegistraScript("BorraDescuentos();") + HdnTieneAnticiposVinculados.Value = "1" + + + End If + CalculaTotalesVenta() + End If + End If + + System.Threading.Thread.Sleep(5) + RegistraScript("$('#DivAnticipos').modal('hide');", "jsClose") + + + End Sub + Private Function AgregarPrePolizasXTrasladar(ObjConta As ClsContabilidad, CvePrePoliza As Integer, PorcentajeAmortizacion As Decimal, TipoCambio As Decimal, ByRef CuentasContablesInvalidas As StringBuilder, ByRef idCuentaContabilizacion As Integer, ByRef CuentasContablesInvalidasSIG As StringBuilder, ByRef CveCuentaContabilizacion As Integer, Importe13 As Decimal, Importe8 As Decimal, Importe9 As Decimal) As Boolean + Dim ImporteMovimiento As Decimal + Dim ImporteMX As Decimal + Dim IdCtaContable, CveCuenta As Integer + Dim FechaMovimiento As Date = Now + Dim Concepto As String = ViewState("VentaFolio").ToString + Dim PrePolizaCorrecta = True + Dim PorcentajeImpuesto As Decimal = 0 + Dim IdCtaIVAXTrasladar As Integer = 0 + Dim CveCuentaIVAxTrasladar As Integer = 0 + + '13 Iva x Trasladar + ImporteMovimiento = Importe13 * PorcentajeAmortizacion + ImporteMX = Math.Round(ImporteMovimiento, 2) * TipoCambio + PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then + IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero + CveCuentaIVAxTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVAXTrasladar").ToString.ToEntero + End If + IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) + CveCuenta = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) + + If ImporteMovimiento > 0 Then + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 13))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 13))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 13, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then + PrePolizaCorrecta = False + End If + End If + + '8 RetIVA x Trasladar + ImporteMovimiento = Importe8 * PorcentajeAmortizacion + ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) + + If IdCtaContRetIVA <> 0 Then + IdCtaContable = IdCtaContRetIVA + CveCuenta = CveCuentaRetIVA + Else + If ObjConta.GetRetCuenta(8, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + End If + + If ImporteMovimiento > 0 Then + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 8))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 8))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 8, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then + PrePolizaCorrecta = False + End If + End If + + '9 RetISR x Trasladar + ImporteMovimiento = Importe9 * PorcentajeAmortizacion + ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) + + 'Conta ContPAQ + If IdCtaContRetISR <> 0 Then + IdCtaContable = IdCtaContRetISR + Else + If ObjConta.GetRetCuenta(9, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + End If + End If + End If + + 'ContaSIG + If CveCuentaRetISR <> 0 Then + CveCuenta = CveCuentaRetISR + Else + If ObjConta.GetRetCuenta(9, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + + If ImporteMovimiento > 0 Then + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 9))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If IdCtaContable <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 9))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 9, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then + PrePolizaCorrecta = False + End If + End If + + Return PrePolizaCorrecta + + End Function + 'Charlie + Private Function AgregarPrePolizasTrasladadas(ObjConta As ClsContabilidad, CvePrePoliza As Integer, PorcentajeAmortizacion As Decimal, TipoCambio As Decimal, ByRef CuentasContablesInvalidas As StringBuilder, ByRef idCuentaContabilizacion As Integer, Optional ByRef CuentasContablesInvalidasSIG As StringBuilder = Nothing, Optional ByRef CveCuentaContabilizacion As Integer = Nothing) As Boolean + + Dim ImporteMovimiento As Decimal + Dim ImporteMX As Decimal + Dim IdCtaContable, CveCuenta As Integer + Dim FechaMovimiento As Date = Now + Dim Concepto As String = ViewState("VentaFolio").ToString + Dim PrePolizaCorrecta = True + Dim PorcentajeImpuesto As Decimal = 0 + Dim IdCtaIVATrasladado As Integer = 0 + Dim CveCuentaIVATrasladado As Integer = 0 + + '61 Iva Trasladado + ImporteMovimiento = TxtIVA.Text.ToDecimal * PorcentajeAmortizacion + ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) + PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then + IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero + CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero + End If + IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) + CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) + + If ImporteMovimiento > 0 Then + 'ContaContPAQ + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 61))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + 'ContaSIG + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 61))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then + PrePolizaCorrecta = False + End If + End If + + '62 Ret IVA Trasladado + ImporteMovimiento = TxtRetIVA.Text.ToDecimal * PorcentajeAmortizacion + ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) + + 'Conta ContPAQ + If IdCtaContRetIVA <> 0 Then + IdCtaContable = IdCtaContRetIVA + Else + If ObjConta.GetRetCuenta(62, UsuarioActual.CveEmpresa) Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero + End If + End If + + 'Conta SIG + If CveCuentaRetIVA <> 0 Then + CveCuenta = CveCuentaRetIVA + Else + If ObjConta.GetRetCuenta(62, UsuarioActual.CveEmpresa) Then + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero + End If + End If + + If ImporteMovimiento > 0 Then + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 62))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 62))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 62, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then + PrePolizaCorrecta = False + End If + End If + + + '63 Ret ISR Trasladado + ImporteMovimiento = TxtRetISR.Text.ToDecimal * PorcentajeAmortizacion + ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2) + + If IdCtaContRetISR <> 0 Then + IdCtaContable = IdCtaContRetISR + Else + If ObjConta.GetRetCuenta(63, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero + End If + End If + End If + + If CveCuentaRetISR <> 0 Then + CveCuenta = CveCuentaRetISR + Else + If ObjConta.GetRetCuenta(63, UsuarioActual.CveEmpresa) Then + If ObjConta.DtResultados.Rows.Count > 0 Then + CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero + End If + End If + End If + + If ImporteMovimiento > 0 Then + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 63))("ConceptoContable").ToString) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 63))("ConceptoContable").ToString) + CveCuentaContabilizacion = 0 + End If + + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 63, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then + PrePolizaCorrecta = False + End If + End If + + + Return PrePolizaCorrecta + + End Function +#End Region + +#Region " BTN ELIMINAR " + Protected Sub BtnEmitir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitir.Click + + If CveVenta <= 0 Then + Alert("Ocurrió un error al emitir la factura", TipoMensaje.MsgError) + Exit Sub + End If + + If UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then + If UsuarioActual.Empresa.EstatusFacturacion Then + + CreaObjetosVenta() + 'PARA CUANDO YA ESTA GUARDADA LA VENTA + ObjFactura.CveVenta = CveVenta + ObjFactura.Serie = Serie + ObjFactura.Folio = Folio + ObjFactura.Timbre.Comprobante.Serie = Serie + ObjFactura.Timbre.Comprobante.Folio = Folio.ToString + + Dim ObjTimbrado As New Timbrado + Dim FM As New Modelos.FemsaFactura + Dim TmpDT7Eleven As New DataTable + Dim TmpDTComplementosTimbrado As New DataTable + PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) + + If ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) Then + + 'MENSAJE PRINCIPAL + MensajeAlert = New StringBuilder + MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} se generó correctamente.

    ", ObjFactura.TipoDocumento, ObjFactura.SerieFolio)) + + 'XML + Dim ArchivoXML = String.Format("{0}/XML/{1}/{2}.xml", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) + If File.Exists(ArchivoXML) Then + MensajeAlert.AppendFormat("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", ObjFactura.SerieFolio, ObjFactura.TipoDocto))) + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant", "Egs") Then + 'If Not ImprimeAlert Then + + Dim ArchivoIngPyMe As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.mrt", UsuarioActual.Empresa.Ruta)) + Dim ArchivoIng As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) + Dim ArchivoRem As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) + Dim ArchivoEgs As New System.IO.FileInfo(String.Format("{0}Formatos/NotaCredito.rdlc", UsuarioActual.Empresa.Ruta)) + + If ArchivoIng.Exists Or ArchivoRem.Exists Or ArchivoIngPyMe.Exists Or ArchivoEgs.Exists Then + MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))) + Else + MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") + End If + End If + + 'IMPRESION + GeneraPDFFactura(ChkEnviarFactura.Checked) + + If ObjFactura.TipoDocto = "Ing" AndAlso ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" Then + CreaObjetosVentaAmortizacion(Nothing, ObjTimbrado.UUID, ObjFactura.CveVentaRelacion, CveVenta) + For Each Gvr As GridViewRow In GvAntNC.Rows + If Gvr.DataKey("FolioFiscal").ToString = "" AndAlso Gvr.DataKey("TipoDocto") = "Egs" Then + ObjFacturaDevolucion.CveVenta = Gvr.DataKey("CveVenta").ToEntero + ObjFacturaDevolucion.Serie = Gvr.DataKey("Serie").ToString + ObjFacturaDevolucion.Folio = Gvr.DataKey("Folio").ToEntero + ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) + End If + Exit For + Next + If ObjFacturaDevolucion.CveVenta.ToEntero > 0 Then + Dim Obj2 As New List(Of Object) + Obj2.Add(ObjFacturaDevolucion) + If Not IsNothing(Obj2) AndAlso Obj2.Count > 0 Then + Dim ofa As Modelos.Factura = CType(Obj2(0), Modelos.Factura) + ofa.Timbre.CFDIRelacionados.UUID.Clear() + ofa.Timbre.CFDIRelacionados.UUID.Add(ObjTimbrado.UUID) + If ObjTimbrado.TimbrarFactura(UsuarioActual, ofa) Then + MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} se timbro correctamente.

    ", ofa.TipoDocumento, ofa.SerieFolio)) + Else + MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} no se timbro correctamente.

    ", ofa.TipoDocumento, ofa.SerieFolio)) + End If + End If + End If + End If + + + 'NOTIFICACION DE SMS + Dim EstatusSMS = 0 + If ObjFactura.TipoDocto = "Ing" Then + Dim ObjEventos As New ClsOIEventos + EnviarSMSTimbrado(ObjEventos) + ObjEventos.Dispose() + End If + Select Case EstatusSMS + Case 1 + MensajeAlert.AppendFormat("Notificación SMS: enviado con éxito al cliente al celular: {0}", ObjFactura.Cliente.CobranzaTelefono) + Case 2 + MensajeAlert.AppendFormat("Notificación SMS: sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.") + Case 3 + MensajeAlert.AppendFormat("Notificación SMS: sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.") + End Select + + 'MUESTA Alert OK + 'MensajeAlert.Append("El Documento se generó correctamente") + Dim Liga = If(UsuarioActual.CveRol = 1165, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}&Opt=3"";") + Alert(MensajeAlert.ToString, TipoMensaje.MsgInformacion, Liga) + + TrEmitir.Visible = False + Else + Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgError) + End If + + Else + Me.OnError("El SAT regresó el siguiente mensaje: Crédito insuficiente.", New Exception) + End If + ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then + + End If + End Sub +#End Region + +#Region " DESCUENTOS " + Protected Sub BtnAplicarDescG_Click(sender As Object, e As System.EventArgs) Handles BtnAplicarDescG.Click + If HdnTipoDescuento.Value = "2" Then + + If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then + Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2) + Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble + + If IVAPromedio <> IVA Then + Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError) + Else + 'Dim Descuento As Double = HdnDescuento.Value.Trim.Replace(",", "").ToDouble + CalculaTotalesVenta() + 'LblDescuentos.Text = Descuento.FormatoNumero(2) + 'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Descuento - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2) + 'HdnIVAOriginal.Value = TxtIVA.Text + 'CalculaTotales(True) + HdnTipoDescuento.Value = "-1" + HdnDescuento.Value = "0" + RegistraScript("BorraDescuentos();") + End If + End If + + ElseIf HdnTipoDescuento.Value = "3" Then + If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then + Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2) + Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble + + If IVAPromedio <> IVA Then + Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError) + Else + 'Dim Amortizacion As Decimal = HdnDescuento.Value.Trim.Replace(",", "").ToDecimal + 'LblAmortizacion.Text = Amortizacion.FormatoNumero(2) + 'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Amortizacion - LblDescuentos.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2) + 'HdnIVAOriginal.Value = TxtIVA.Text + 'CalculaTotales(True) + CalculaTotalesVenta() + HdnTipoDescuento.Value = "-1" + HdnDescuento.Value = "0" + RegistraScript("BorraDescuentos();") + HdnTieneAnticiposVinculados.Value = "1" + End If + End If + + End If + + RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal") + UpPS.Update() + End Sub + Private Sub BtnAplicarOtrosConceptos_Click(sender As Object, e As EventArgs) Handles BtnAplicarOtrosConceptos.Click + TotalOtrosConceptos = 0 + + For Each row As GridViewRow In GVOtrosConceptos.Rows + TotalOtrosConceptos += row.FCTextBox("TxtCantidadConcepto").Text.ToDecimal + Next + + RegistraScript("$('#ModalOtrosConceptos').modal('hide')", "hidemodal") + End Sub + Private Sub BtnAplicarComplementos_Click(sender As Object, e As EventArgs) Handles AplicarComplementosTimbrado.Click + LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs green" + UpPS.Update() + + RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal") + End Sub + Private Sub BtnCancelarComplementos_Click(sender As Object, e As EventArgs) Handles CancelarComplementosTimbrado.Click + trEntidad.Visible = False + trContaComplementos.Visible = False + trAmbito.Visible = False + trTipoCampaña.Visible = False + + RblComplementos.SelectedIndex = -1 + TxtIdConta.Text = "" + DdlTipoCampaña.SelectedIndex = -1 + DdlAmbitoComplemento.SelectedIndex = -1 + DdlINEEntidad.SelectedIndex = -1 + + LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs gray" + UpComplementos.Update() + UpDatosComplementos.Update() + UpPS.Update() + + RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal") + End Sub + + '2019-07-31 OSCAR Nuevo cancela usando el metodo de cancelacion de facturas + Protected Sub LnkCancelarComplemetno_Click(sender As Object, e As EventArgs) + + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).BindingContainer, GridViewRow) + + Dim ObjCancelacion As New Timbrado + Dim ObjBanco As New ClsBancos + + Dim CveComplementoPago As Integer = GvRow.DataKey("CveComplementoPago").ToEntero + Dim FolioFiscal As String = GvRow.DataKey("FolioFiscal").ToString + Dim RFCEmisor As String = UsuarioActual.Empresa.RFC + Dim RFCReceptor As String = GvRow.DataKey("RFCReceptor") + Dim CvePACCancelacion As Integer = GvRow.DataKey("CvePAC").ToEntero + + If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, 0, RFCReceptor, RFCEmisor, CvePACCancelacion) Then + + If ObjBanco.UpdateComplementoPago(CveComplementoPago, "-1", -1, UsuarioActual.CveEmpresa, 2, CvePACCancelacion, FechaCancelacion:=ObjCancelacion.CancelacionFecha, SelloCancelacion:=ObjCancelacion.CancelacionAcuse) Then + CargaComplementosPago() + Alert("El complemento se cancelo correctamente.") + End If + + Else + Alert("Se presento un error al cancelar el complemento.") + End If + + ObjBanco.Dispose() + + End Sub +#End Region + + + +#Region " VISTA PREVIA " + Protected Sub BtnVistaPrevia_Click(sender As Object, e As System.EventArgs) Handles BtnVistaPrevia.Click + VistaPreviaNew() + End Sub + +#End Region + +#Region "I M A G E - B U T T O N S" + Protected Function CancelarMovimientoInventario(ByRef ObjInventario As ClsInventarios, ByRef ObjConta As ClsContabilidad, CveVentaNueva As Integer, CveVentaVieja As Integer) As Boolean + + 'SI YA ESTA QUEMADA DE ALMACEN LA VENTA, NO SE CANCELAN LOS MOVIMIENTOS DE INVENTARIO + If ObjInventario.GetEstatusVentaPorSurir(CveVentaVieja) Then + If ObjInventario.EsDevolucionVenta = 2 Then + Return True + End If + Else + Return False + End If + + Dim DtMovimientos As DataTable + Dim DTMovimientosDetalles As DataTable + Dim OcurrioError As Boolean = False + + 'Verificamos que la venta tenga movimientos + If ObjInventario.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjInventario.DtResultados.Rows.Count > 0 Then + DtMovimientos = ObjInventario.DtResultados.FiltraParametros("CveConcepto = 3", DistinctColumns:={"CveMovimiento"}) + DTMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0") + + For Each Mov As DataRow In DtMovimientos.Rows + If ObjInventario.GetMovimientos(Mov("CveMovimiento").ToString.ToEntero, 3, -1, UsuarioActual.CveEmpresa) Then + If ObjInventario.DtResultados.Rows.Count > 0 Then + + Dim CveAlmacen As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero + Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero + Dim Fecha As Date = Now + + 'Creamos el movimiento de entrada y el movimiento de salida + Dim CveMovimientoInventarioEntrada As Integer = ObjInventario.AddMovimiento(CveAlmacen, 18, CveMoneda, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveDevolucion, -1, -1, MovimientoFijo:=True) + Dim CveMovimientoInventarioSalida As Integer = ObjInventario.AddMovimiento(CveAlmacen, 3, CveMoneda, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVentaNueva, -1, -1, MovimientoFijo:=True) + + If CveMovimientoInventarioEntrada > 0 AndAlso CveMovimientoInventarioSalida > 0 Then + + 'Creamos sus detalles + For Each MovDet As DataRow In DTMovimientosDetalles.FiltraParametros($"CveMovimiento = {Mov("CveMovimiento")}").Rows + + Dim Cantidad As Double = MovDet("Cantidad").ToString.ToDouble + Dim CveUnidad As Integer = MovDet("CveUM").ToString.ToEntero + Dim PU As Double = MovDet("PU").ToString.ToDouble + Dim CveProducto As Integer = MovDet("CvePS").ToString.ToEntero + Dim SerieLote As String = MovDet("SerieLote").ToString + + Dim CveVentaDetalle = MovDet("CveVentaDetalle").ToString.ToEntero + + 'Entrada + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventarioEntrada, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then + OcurrioError = True + Exit For + End If + + 'Salida + CveVentaDetalle = ObjInventario.VentaDetallePadreGet(CveVentaDetalle).ToString.ToEntero + If CveVentaDetalle > 0 Then + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventarioSalida, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then + OcurrioError = True + Exit For + End If + Else + OcurrioError = True + Exit For + End If + + Next + + 'Creamos sus prepolizas + If Not OcurrioError Then + Dim tmpCostos As DataTable = DTMovimientosDetalles.FiltraParametros($"CveMovimiento = {Mov("CveMovimiento")}", "", {"CveClasificacion"}) + Dim IdCtaContable As Integer = 0 + Dim CveCuenta As Integer = 0 + Dim ValorInventario As Decimal = 0 + + For Each RowInv As DataRow In tmpCostos.Rows + ValorInventario = DTMovimientosDetalles.SUM("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).ToString.ToDecimal.RoundSQL() + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + + If ValorInventario <> 0 Then + 'Entrada + If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveDevolucion, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventarioEntrada, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then + 'Salida + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventarioSalida, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then + OcurrioError = True + Exit For + End If + Else + OcurrioError = True + Exit For + End If + End If + Next + + If OcurrioError Then + Exit For + End If + + IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {ddlAlmacen.SelectedValue}").ToEntero + CveCuenta = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {ddlAlmacen.SelectedValue}").ToEntero + ValorInventario = DTMovimientosDetalles.SUMD("Total", $"CveMovimiento = {Mov("CveMovimiento")}").RoundSQL() + + If ValorInventario <> 0 Then + 'Entrada + If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveDevolucion, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=-1, CveMovimientoAlmacen:=CveMovimientoInventarioEntrada, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta) Then + 'Salida + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ValorInventario, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=-1, CveMovimientoAlmacen:=CveMovimientoInventarioSalida, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta) Then + OcurrioError = True + Exit For + End If + Else + OcurrioError = True + Exit For + End If + End If + + End If + + Else + OcurrioError = True + Exit For + End If + + Else + 'Si no tiene Movimientos de Salida no ocupamos mas + Return Not OcurrioError + End If + + Else + OcurrioError = True + Exit For + End If + + Next + + End If + + Else + OcurrioError = True + End If + + Return Not OcurrioError + End Function + Protected Function CancelarFactura(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjAC As ClsContPAQi, ByRef ObjBancos As ClsBancos) As Boolean + Dim IDPoliza As Integer = -1 + Dim CvePrePoliza As Integer + Dim CvePlantillaPoliza As Integer + + Dim ErrorCancelar As Boolean = False + Dim Mensaje As String = "" + + Try + ObjFacturaDevolucion.TipoDocto = ObjFactura.TipoDocto + + If ObjFacturaDevolucion.TipoDocto.Contiene("Egs", "Dev") Then + CvePlantillaPoliza = 7 + ElseIf ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem", "Ant") Then + CvePlantillaPoliza = 4 + End If + + + CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + ObjFacturaDevolucion.CveVenta = CveVenta + ObjFacturaDevolucion.CvePrePoliza = CvePrePoliza + + + If NuevaFactura = 1 AndAlso UsuarioActual.TienePermisoProceso(222) Then + If ObjVentas.GetVentaDetalle(ObjFacturaDevolucion.CveVenta) Then + TmpDT = ObjVentas.DtResultados + End If + ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) + Else + ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) + End If + + If Not ErrorCancelar Then + ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFacturaDevolucion, -1) + End If + + If CveEstatus = 4 Then + + If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then + Mensaje = "El nuevo estatus se guardó correctamente" + Else + ErrorCancelar = True + End If + + 'Si se está mandando a Cancelada SAT + ElseIf CveEstatus = 5 Then + + Dim DT As DataTable = Nothing + + If FolioFiscal = "" Then + Dim XmlDoc As New XmlDocument + XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml") + ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText + End If + + Dim ObjCancelacion As New Timbrado + + Dim Total As Decimal = TxtTotal.Text.ToDecimal + Dim RFCReceptor As String = HdnRFCVenta.Value + + If Not ObjVentas.UpdateEstatusFactura(13, FolioFiscal, "", Now, CveVenta, IDPoliza) Then 'Marcamos la factura como refacturada, si no se cancelo en el SAT el estatus nos dejara cancelarla despues + ErrorCancelar = True + End If + + If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, Total, RFCReceptor, UsuarioActual.Empresa.RFC) Then + 'falta verificar traer el acuse y reenviarlo + + If UsuarioActual.Empresa.UsaAC Then + IDPoliza = GenerarPolizaAC(ObjAC, True) + If IDPoliza <= 0 Then + Mensaje = "No se pudo generar la poliza" + ErrorCancelar = True + End If + End If + + If Not ErrorCancelar Then + If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, ObjCancelacion.CancelacionAcuse, Now, CveVenta, IDPoliza, CvePAC:=UsuarioActual.Empresa.CvePAC) Then + Mensaje = "El nuevo estatus se guardó correctamente" + Else + ErrorCancelar = True + End If + End If + Else + ErrorCancelar = True + End If + + ObjCancelacion = Nothing + + End If + Catch ex As Exception + GuardaLog(ex.ToString()) + ErrorCancelar = True + End Try + + Return Not ErrorCancelar + End Function + Protected Function CancelarFactura2(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjAC As ClsContPAQi, ObjBancos As ClsBancos) As Boolean + + Dim IDPoliza As Integer = -1 + Dim CvePrePoliza As Integer + Dim CvePlantillaPoliza As Integer + + Dim ErrorCancelar As Boolean = False + Dim Mensaje As String = "" + + CreaObjetosVenta() + + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + CvePlantillaPoliza = 7 + ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem") Then + CvePlantillaPoliza = 4 + End If + + + CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + ObjFactura.CveVenta = CveVenta + ObjFactura.CvePrePoliza = CvePrePoliza + + If HplSaldoAuxiliar.Text.ToDecimal > 0 Then + ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) + End If + + If Not ErrorCancelar Then + ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, -1) + End If + + If CveEstatus = 4 Then + + If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then + Mensaje = "El nuevo estatus se guardó correctamente" + Else + ErrorCancelar = True + End If + + 'Si se está mandando a Cancelada SAT + ElseIf CveEstatus = 5 Then + + Dim DT As DataTable = Nothing + + If FolioFiscal = "" Then + Dim XmlDoc As New XmlDocument + XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml") + ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText + End If + + 'Si es cancelar en el SAT: + Dim CFDi As New ClbNegBICFDv3_2.ClsNegEDI + Dim Respuesta As New ClbNegBICFDv3_2.ClsNegRespuesta + Respuesta = CFDi.CancelaCFdi(UsuarioActual.Empresa.BIUsuario, UsuarioActual.Empresa.BIContraseña, Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoPfx, UsuarioActual.Empresa.ContraseñaKey, UsuarioActual.Empresa.RFC, FolioFiscal, "http://208.43.160.178/srvCFDi/service1.asmx") + + If Respuesta Is Nothing Then + 'Alert("La factura no se pudo cancelar.
    Posbiles causas:
      - Los servicios del SAT están ocupados.
      - El Folio Fiscal no ha quedado registrado.", TipoMensaje.MsgError) + Me.GuardaLog(CFDi.MsgError) + ErrorCancelar = True + Mensaje = "La factura no se pudo cancelar.
    Posbiles causas:
      - Los servicios del SAT están ocupados.
      - El Folio Fiscal no ha quedado registrado." + ElseIf Respuesta.NoCertificadoSAT <> String.Empty Then + + If UsuarioActual.Empresa.UsaAC Then + IDPoliza = GenerarPolizaAC(ObjAC, True) + If IDPoliza <= 0 Then + Mensaje = "No se pudo generar la poliza" + ErrorCancelar = True + End If + End If + + If Not ErrorCancelar Then + If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, Respuesta.NoCertificadoSAT, Respuesta.FechaTimbrado, CveVenta, IDPoliza) Then + Mensaje = "El nuevo estatus se guardó correctamente" + Else + ErrorCancelar = True + End If + End If + End If + + End If + + Return Not ErrorCancelar End Function -#End Region + Protected Sub ImgBtnAddC_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddC.Click + Dim Row As DataRow = Nothing + Row = DTmpC.NewRow -#Region "D A T A - T A B L E S" - Private Sub CreaDTVentas() - TmpDT = New DataTable - TmpDT.Columns.Add("CveVenta", GetType(Integer)) - 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("SATClaveUM", GetType(String)) - TmpDT.Columns.Add("CveClasificacion", GetType(Integer)) - TmpDT.Columns.Add("Clasificacion", GetType(String)) - TmpDT.Columns.Add("CvePS", GetType(Integer)) - TmpDT.Columns.Add("PS", GetType(String)) - TmpDT.Columns.Add("CodigoPS", GetType(String)) - TmpDT.Columns.Add("SATClaveProdServ", GetType(String)) - TmpDT.Columns.Add("NoIdentificacion", GetType(String)) - TmpDT.Columns.Add("CveTipoPS", GetType(Integer)) - TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer)) - TmpDT.Columns.Add("SerieLote", GetType(String)) - TmpDT.Columns.Add("CuentaPredial", GetType(String)) - TmpDT.Columns.Add("Obs", GetType(String)) - TmpDT.Columns.Add("TiempoEntrega", GetType(String)) - TmpDT.Columns.Add("PU", GetType(Decimal)) - TmpDT.Columns.Add("IVA", GetType(Decimal)) - TmpDT.Columns.Add("ImporteIVA", GetType(Decimal)) - TmpDT.Columns.Add("PorcentajeIVA", GetType(Decimal)) - TmpDT.Columns.Add("ImporteRetIVA", GetType(Decimal)) - TmpDT.Columns.Add("ImporteRetISR", GetType(Decimal)) - TmpDT.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) - TmpDT.Columns.Add("PorcentajeRetISR", GetType(Decimal)) - TmpDT.Columns.Add("ImporteIEPS", GetType(Decimal)) - TmpDT.Columns.Add("IEPS", GetType(Decimal)) - TmpDT.Columns.Add("PorcentajeIEPS", GetType(Decimal)) - TmpDT.Columns.Add("Descuento", GetType(Decimal)) - TmpDT.Columns.Add("TipoDescuento", GetType(Integer)) - TmpDT.Columns.Add("TotalImporte", GetType(Decimal)) - TmpDT.Columns.Add("Total", GetType(Decimal)) - 'Para uso del módulo contable - TmpDT.Columns.Add("AsientoContableVentas", GetType(Integer)) - TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer)) - TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean)) - TmpDT.Columns.Add("CveProyecto", GetType(Integer)) - TmpDT.Columns.Add("Proyecto", GetType(String)) - TmpDT.Columns.Add("CveSubProyecto", GetType(Integer)) - TmpDT.Columns.Add("SubProyecto", GetType(String)) - TmpDT.Columns.Add("CveVentaDetallePadre", GetType(Integer)) - - 'TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto - TmpDT.Columns.Add("CvePresupuestoIngreso", GetType(Integer)) - TmpDT.Columns.Add("CveFuenteRecaudacion", GetType(Integer)) - 'Contratos - TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer)) - 'Remisiones a Facturas - TmpDT.Columns.Add("CveVentaDetalle", GetType(Integer)) - TmpDT.Columns.Add("CveVentaDetalleRemision", GetType(Integer)) - TmpDT.Columns.Add("CveVentaDetalleCotizacion", GetType(Integer)) - - 'Pedido2 a Facturas - TmpDT.Columns.Add("CveVentaDetallePedido2", GetType(Integer)) - - TmpDT.Columns.Add("Origen", GetType(Integer)) - 'Ordenes Servicio - TmpDT.Columns.Add("CveOS", GetType(Integer)) - TmpDT.Columns.Add("CveOSDetalle", GetType(Integer)) - TmpDT.Columns.Add("SeFacturara", GetType(Integer)) - TmpDT.Columns.Add("Folio", GetType(Integer)) - TmpDT.Columns.Add("Estatus", GetType(String)) - 'Ordenamiento - TmpDT.Columns.Add("Orden", GetType(Integer)) - TmpDT.Columns.Add("TipoDocto", GetType(String)) - 'OC - TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer)) - TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) - - TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) - TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) - TmpDT.Columns.Add("CantidadFacturadaCot", GetType(Decimal)) - TmpDT.Columns.Add("CantidadFacturadaPed2", GetType(Decimal)) - TmpDT.Columns.Add("CantidadInventario", GetType(Decimal)) - - TmpDT.Columns.Add("ClaveSATFraccionArancelaria", GetType(String)) - TmpDT.Columns.Add("ClaveSATUnidadAduana", GetType(String)) - TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", GetType(String)) - TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", GetType(String)) - - TmpDT.Columns.Add("CveTamaño", GetType(Integer)) - - End Sub - Private Sub CreaDTmpC() - DTmpC = New DataTable - DTmpC.Columns.Add("Descripcion", GetType(String)) - End Sub - Private Sub CreaDTmpF() - DTmpF = New DataTable - DTmpF.Columns.Add("CveVenta", GetType(Integer)) - DTmpF.Columns.Add("Titulo", GetType(String)) - DTmpF.Columns.Add("Nombre", GetType(String)) - DTmpF.Columns.Add("Puesto", GetType(String)) - DTmpF.Columns.Add("Lado", GetType(Integer)) - End Sub - Private Sub CreaDTImpuestos() - TmpDTImpuestos = New DataTable - TmpDTImpuestos.Columns.Add("CveImpuestoLocal", GetType(Integer)) - TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String)) - TmpDTImpuestos.Columns.Add("Porcentaje", GetType(Decimal)) - TmpDTImpuestos.Columns.Add("Importe", GetType(Decimal)) - TmpDTImpuestos.Columns.Add("TipoImpuesto", GetType(Integer)) - TmpDTImpuestos.Columns.Add("IdCtaContable", GetType(Integer)) - TmpDTImpuestos.Columns.Add("CveCuenta", GetType(Integer)) - TmpDTImpuestos.Columns.Add("Orden", GetType(Integer)) - End Sub - Private Sub CreaDTImpuestosIVAIEPS() - TmpDTImpuestosIVAIEPS = New DataTable - TmpDTImpuestosIVAIEPS.Columns.Add("Impuesto", GetType(String)) - TmpDTImpuestosIVAIEPS.Columns.Add("tasa", GetType(String)) - TmpDTImpuestosIVAIEPS.Columns.Add("Importe", GetType(Decimal)) - TmpDTImpuestosIVAIEPS.Columns.Add("Orden", GetType(Integer)) - End Sub - Private Sub CreaDTDocumentosRelacionados() - TmpDTDocumentosRelacionados = New DataTable - TmpDTDocumentosRelacionados.Columns.Add("SerieFolio", GetType(String)) - TmpDTDocumentosRelacionados.Columns.Add("Fecha", GetType(String)) - TmpDTDocumentosRelacionados.Columns.Add("Importe", GetType(Decimal)) - TmpDTDocumentosRelacionados.Columns.Add("FolioFiscal", GetType(Integer)) + Row("Descripcion") = tbDescC.Text + DTmpC.Rows.Add(Row) + tbDescC.Text = "" + tbDescC.Focus() + GvConceptos.DataSource = DTmpC + GvConceptos.DataBind() + UPCD.Update() End Sub -#End Region + Protected Sub ImgBtnAddF_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddF.Click + Dim Row As DataRow = Nothing + Dim ObjVentas As New ClsVentas -#Region "P D F" + Row = DTmpF.NewRow + + Row("CveVenta") = 0 + Row("Titulo") = tbTituloF.Text + Row("Nombre") = tbNmbF.Text + Row("Puesto") = tbPuesF.Text + Row("Lado") = ddlPos.SelectedValue.ToEntero + DTmpF.Rows.Add(Row) + tbNmbF.Text = "" + tbPuesF.Text = "" + tbTituloF.Text = "" + ddlPos.SelectedValue = CStr(0) + GvFirmas.DataSource = DTmpF + GvFirmas.DataBind() + UPFirmas.Update() + tbTituloF.Focus() + End Sub +#End Region + +#Region "D R O P - D O W N - L I S T" + Private Sub DdlPSIndexChange(CvePSParametro As Integer, Ddl As ADServerControl.Dropdownlost) + + If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then + Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") + Exit Sub + End If + + If CvePSParametro > 0 Then + Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSParametro).FiltroPrimero("") + + If drPS IsNot Nothing Then + 'HdnUnidadMedida.Value = PS.Rows(0)("CveUnidadMedida").ToString + HdnPS.Value = drPS("PS").ToString + HdnCodigoPS.Value = drPS("PSCodigo").ToString + HdnTipoPS.Value = drPS("CveTipoPS").ToString + HdnTipoInv.Value = drPS("Inv_CveMetodoInventario").ToString + HdnAplicaIEPS.Value = drPS("AplicaIEPS").ToString + HdnPorcentajeIEPS.Value = drPS("IEPSPorcentaje").ToString + DdlUnidadMedida.Items.Clear() + If UsuarioActual.Empresa.UsaInventarios Then + DdlUnidadMedida.DataSource = GlobalDTProductosServiciosEquivalencias(CvePSParametro, -1) + Else + DdlUnidadMedida.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) + End If + DdlUnidadMedida.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlUnidadMedida.SelectedValue = "-1" + DdlUnidadMedida.DataBind() + DdlUnidadMedida.SelectedValueExist(drPS("CveUnidadMedida").ToString) + DdlMoneda.SelectedValueExist(drPS("CveMoneda").ToString) + CambiaMoneda() + 'SUGIERE PRECIO + Dim PrecioSugerido = 0.0 + PrecioSugerido = drPS("Precio").ToString.ToDouble + + If UsuarioActual.CveEmpresa.Contiene(1) Then + Dim ObjPS As New ClsProductosServicios + If ObjPS.GetPorcentajeProductos(CveCliente) Then + Dim PrecioAplicado = ObjPS.DtResultados.FiltraParametros($"CvePS = {CvePSParametro}").FiltroPrimeroValor("PrecioA").ToDouble + If PrecioAplicado > 0 Then + PrecioSugerido = PrecioAplicado + End If + End If + ObjPS.Dispose() + End If + + If UsuarioActual.Empresa.Funcionalidad(404).ToString = "1" Then + Dim CvePrecioListaPS As Integer = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePrecioLista", "").ToEntero + If CvePrecioListaPS > 0 Then + Dim ObjPS As New ClsProductosServicios + If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then + PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble + End If + ObjPS.Dispose() + End If + + Dim PorcentajePrecio As Double = 0 + If PrecioSugerido = 0 Then + CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero + If CvePrecioListaPS > 0 Then + Dim ObjPS As New ClsProductosServicios + If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then + PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble + PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDouble + End If + ObjPS.Dispose() + End If + End If + + If PrecioSugerido = 0 Then + Dim ObjInventarios As New ClsInventarios + Dim CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) + 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal + If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1) + ObjInventarios.Dispose() + If CostoPS > 0 And PorcentajePrecio > 0 Then + PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS + End If + End If + + End If + + If PrecioSugerido > 0 Then + TxtPrecio.Text = PrecioSugerido.ToString("#,###.####") ' que muestre hasta los 4 digitos si lo requiere + End If -#End Region + If IsNumeric(TxtCantidad.Text.Trim) Then + LblTotalPS.Text = (TxtCantidad.Text.Trim.ToDouble * TxtPrecio.Text.ToDouble).ToString.FormatoNumero(2) + Else + LblTotalPS.Text = "0.00" + End If -#Region "A C T U A L I Z A " + HdnIVAPS.Value = If(drPS("IVA").ToString = "-1", ViewState("IVA"), drPS("IVA").ToString).ToString + HdnIVARetAPS.Value = drPS("RetIVA").ToString + HdnAsientoContable.Value = drPS("AsientoContableVentas").ToString + HdnCtaContable.Value = drPS("IdCtaContVentas").ToString + HdnAplicaParaConcepto.Value = drPS("AplicaParaConcepto").ToString + HdnCodigo.Value = drPS("Codigo").ToString + If DdlClasificacion.SelectedIndex = 0 Then + If drPS("CveClasificacion").ToString IsNot Nothing Then + DdlClasificacion.SelectedValueExist(drPS("CveClasificacion").ToString) + Else + Alert("El Productos/Servicio no tiene asignada una Clasificación.", TipoMensaje.MsgInformacion) + End If -#Region "New" + End If + + End If + + ElseIf CvePSParametro = -2 Then + CargaPS(DdlClasificacion.SelectedValue.ToEntero, Ddl) + End If + + UPPPS.Update() + UpPS.Update() + + End Sub + Protected Sub DdlPS_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlPS.selectedindexchange + DdlPSIndexChange(DdlPS.SelectedValue.ToEntero, DdlPS) + End Sub + Protected Sub DdlClasificacion_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlClasificacion.SelectedIndexChanged + CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS) + UpPS.Update() + End Sub + Protected Sub DdlNCFactura_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlNCFactura.SelectedIndexChanged + Dim objcompras As New ClsCompras + If objcompras.GetCompraDetallealmacen(0, DdlNCFactura.SelectedValue.ToEntero) Then + GvInvNC.DataSource = objcompras.DtResultados + If objcompras.DtResultados.Rows.Count > 0 Then + Tab.ActiveTabIndex = 1 + Updatetabs.Update() + End If + Else + GvInvNC.DataSource = Nothing + End If + GvInvNC.DataBind() + UpINVNC.Update() + objcompras.Dispose() + End Sub + Protected Sub DdlTipoComprobante_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlTipoComprobante.SelectedIndexChanged + CambiaTipoComprobante() + End Sub + Private Sub CambiaTipoComprobante() + CambiaTipoDocto() + LimpiaEscondeContado() + End Sub + Private Sub CambiaTipoDocto() + CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString.ToEntero) + ConfiguraTipoDocto() + CargaFolios() + CargaEstatusFactura(DdlTipoComprobante.SelectedValue) + UpEstatus.Update() + + If UsuarioActual.TienePermisoProceso(274) Then + TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant" + End If + + 'REINICIALIZA VALORES DE ENTREGA POR ADELANTADO + RequiereAlmacenDestino = False + TrAlmacenAsignado.Visible = False + + If DdlTipoComprobante.SelectedValue = "Cot" And UsuarioActual.Empresa.Funcionalidad(135) = "1" Then + Alert("Se ocupa una autorización.", TipoMensaje.MsgAdvertencia) + TrDireccion.Visible = False + TrCiudad.Visible = False + TrRFC.Visible = False + 'RBLPago.Enabled = False + RBLPago.SelectedValue = "2" + TxtFechaVencimientoCotizacion.Text = Now.ToString + GvPS.Columns(5).Visible = True + ThTiempoEntrega.Visible = True + ThTiempoEntrega2.Visible = True + ChkEnviarFactura.Checked = True + UpnTools.Update() + tdTelefonoGen.Visible = False + tdTxtTelefonoGen.Visible = False + If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then + ChkEnviarFactura.Checked = False + End If + + Else + If DdlTipoComprobante.SelectedValue = "Cot" Then + TrDireccion.Visible = False + TrCiudad.Visible = False + TrRFC.Visible = False + 'RBLPago.Enabled = False + 'RBLPago.SelectedValue = "2" + TxtFechaVencimientoCotizacion.Text = Now.ToString + GvPS.Columns(5).Visible = True + ThTiempoEntrega.Visible = True + ThTiempoEntrega2.Visible = True + tdTelefonoGen.Visible = False + tdTxtTelefonoGen.Visible = False + + 'CUANDO SEA COMPUPROVEEDORES NO MANDA COTIZACIONES + If UsuarioActual.CveEmpresa = 72 Then + ChkEnviarFactura.Checked = False + ChkEnviarFactura.Visible = False + LblEnviarMail.Visible = False + End If + + If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then + ChkEnviarFactura.Checked = False + End If + Else + TrDireccion.Visible = True + TrCiudad.Visible = True + TrRFC.Visible = True + GvPS.Columns(5).Visible = False + ThTiempoEntrega.Visible = False + ThTiempoEntrega2.Visible = False + RBLPago.Enabled = True + + LblMensaje.Visible = UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue.Contiene("Ing") + + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev") Then + ChkEnviarFactura.Checked = EnviarCorreoCliente + ChkEnviarFactura.Visible = True + LblEnviarMail.Visible = True + ObtenerFechaVencimientoCER() + + If DdlTipoComprobante.SelectedValue.Contiene("Egs") Then + + 'se cargan las facturas timbradas + 'CargaFacturasRelacionar() + 'RegistraScript("$('#DivRelacionarFacturasNC').modal('show');") + End If + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then + + 'ENTREGA POR ADELANTADO + If UsuarioActual.Empresa.Funcionalidad(145) = "1" And Not DdlTipoComprobante.SelectedValue.Contiene("PA") Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then + RequiereAlmacenDestino = True + + 'If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then + ' TrAlmacenAsignado.Visible = True + 'End If + + Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero + If CveAlmacenDestino > 0 Then + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)") + DdlAlmacenAsignado.DataBind() + DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString)) + DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString + Else + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (10)") + DdlAlmacenAsignado.DataBind() + End If + UpParametros.Update() + Else + RequiereAlmacenDestino = False + TrAlmacenAsignado.Visible = False + End If + + 'ENVIO DE FACTURA + If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then + ChkEnviarFactura.Checked = EnviarCorreoCliente + ChkEnviarFactura.Visible = True + LblEnviarMail.Visible = True + End If + + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "PA", "Pd2") AndAlso (ReceptorRFC = "XAXX010101000" Or LblRFC.Text = "XAXX010101000") Then + TrDireccion.Visible = False + TrCiudad.Visible = False + TrRFC.Visible = False + tdTelefonoGen.Visible = True + tdTxtTelefonoGen.Visible = True + Else + TxtAtencionA.Text = "" + TxtTelefonoGenerico.Text = "" + End If + End If + + + End If + + If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then + ' IPP 15 Julio 2017 - ERA FALSE + ImgAntiPend.Visible = False + ElseIf Opcion <> "Op" Then + ImgAntiPend.Visible = True + End If + + + + TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString + + TabAlmacen.Enabled = DdlTipoComprobante.SelectedValue <> "Ant" + + 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO + If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO + BtnEmitirImprimir.Visible = True + TrVistaPrevia.Visible = True + Else + If LblCliente.Text <> "Cliente" And Not EstatusCliente Then + Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) + End If + BtnEmitirImprimir.Visible = EstatusCliente + TrVistaPrevia.Visible = EstatusCliente + End If + + + + TrAtencionA.Visible = True + tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") + tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") + + + Updatetabs.Update() + UPCondicionesPago.Update() + UpCliente.Update() + UpPS.Update() + End Sub + Protected Sub DdlSucursalCliente_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSucursalCliente.SelectedIndexChanged + CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero) + End Sub + Protected Sub DdlCCEdit_SelectedIndexChanged(sender As Object, e As System.EventArgs) + Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) + Dim CveProyecto As String = DirectCast(sender, DropDownList).SelectedValue + + gvr.FCDropDownList("DDlSubProyecto").Items.Clear() + gvr.FCDropDownList("DDlSubProyecto").DataSource = GlobalDTSubProyectos(CveProyecto.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa) + gvr.FCDropDownList("DDlSubProyecto").DataBind() + gvr.FCDropDownList("DDlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) + + End Sub + Protected Sub DdlClasificacion_SelectedIndexChanged1(sender As Object, e As EventArgs) + Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) + CargaPS(gvr.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero, gvr.FCDropDownLost("DdlPS")) + End Sub + Protected Sub BtnEstimacion_Click(sender As Object, e As EventArgs) Handles BtnEstimacion.Click + Dim Contrato As String = "" + Dim Importe As Decimal = 0 + Dim CvePS As Integer + Dim PS As String + Dim PSCodigo As String + Dim CveUM As Integer + Dim UM As String + Dim CveClasificacion As Integer + Dim Clasificacion As String + Dim CveProyecto As Integer + Dim Proyecto As String + Dim CveSubProyecto As Integer + Dim SubProyecto As String + Dim FechaInicial As String = "" + TmpDT.Rows.Clear() + For Each Row As GridViewRow In GvEst.Rows + If Row.FCCheckBox("Chk").Checked Then + Importe += Row.FCLiteral("LtlImporte").Text.ToDecimal + Contrato = Row.DataKey("NumeroContrato") + CveContrato = Row.DataKey("CveContrato").ToEntero + FechaInicial = Row.DataKey("FechaInicial").ToString.ToDate.ToString("dd MMMM yyyy") + CveSubProyecto = Row.DataKey("CveSubProyecto").ToEntero + End If + Next + + If Importe > 0 Then + CvePS = UsuarioActual.Empresa.Funcionalidad(106).ToEntero + If CvePS > 0 Then + Dim rowPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") + If rowPS IsNot Nothing Then + PS = rowPS("PS").ToString + PSCodigo = rowPS("PSCodigo").ToString + CveUM = rowPS("CveUM").ToString.ToEntero + UM = rowPS("UnidadMedida").ToString + CveClasificacion = rowPS("CveClasificacion").ToString.ToEntero + Clasificacion = rowPS("Clasificacion").ToString + Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto={0}", CveSubProyecto)) + Proyecto = rowSP("Proyecto").ToString + CveProyecto = rowSP("CveProyecto").ToString.ToEntero + SubProyecto = rowSP("SubProyecto").ToString + AgregarProductoServicio(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero), + Importe, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) + + 'AddPS(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero), Importe, 0.16, 0, 0, 1, 0, True, "", CveProyecto, Proyecto, CveSubProyecto, SubProyecto, rowPS("CveTipoPS").ToString.ToEntero, rowPS("Inv_CveMetodoInventario").ToString.ToEntero, CodigoPS:=PSCodigo) + + + DdlTipoComprobante.SelectedValue = "Rem" + DdlTipoComprobante_SelectedIndexChanged(DdlTipoComprobante, Nothing) + + End If + UpParametros.Update() + Tab.ActiveTab = TabGenerales + Else + Alert("La empresa no contiene un producto asignado a la estimació", TipoMensaje.MsgInformacion) + End If + + + Updatetabs.Update() + End If + End Sub + Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlProyecto.SelectedIndexChanged + CargaSubProyecto() + End Sub +#End Region + +#Region " SUCURSAL FACTURACION " + Private Sub DdlSubProyectoDatos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSubProyectoDatos.SelectedIndexChanged + CambiaSucursalGeneral() + End Sub + Private Sub CambiaSucursalGeneral() + Dim ObjSubProyectos As New ClsSubProyectos + 'Dim ObjSucursal As New ClsSucursales + If ObjSubProyectos.GetSubProyectos() Then + DTSucursal = ObjSubProyectos.DtResultados.FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue.ToEntero)) + 'Dim drc As DataRow + 'drc = DTSucursal(0) + + DdlSubProyecto.Items.Clear() + DdlSubProyecto.DataSource = DTSucursal + DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlSubProyecto.SelectedValue = "-1" + DdlSubProyecto.DataBind() + DdlSubProyecto.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) + CambiaSucursal() + + DdlSubProyectoEjecucion.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) + DdlSubProyectoCobranza.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) + UpDetalle.Update() + + 'If ObjSucursal.GetSucursales(UsuarioActual.CveEmpresa) Then + ' DTSucursal = ObjSucursal.DtResultados.FiltraParametros(String.Format("CveSucursal = {0}", drc("CveSucursal").ToString.ToEntero)) + ' Dim dre As DataRow + ' dre = DTSucursal(0) + ' DdlSucursal.SelectedValue = dre("CveSucursal").ToString + ' CambiaSucursal() + 'End If + End If + ObjSubProyectos.Dispose() + End Sub + Private Sub CambiaSucursal() + CargaFormatoSucursal() + CargaFolios() + CargaVendedores() + CargarAlmacenes() + DdlPS.Attributes.Remove("data-cvesubproyecto") + DdlPS.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) + UpPS.Update() + End Sub + Private Sub CargaFolios() + If ExFolioFactura Then + Exit Sub + End If + If DdlSubProyectoDatos.SelectedValue.ToEntero <= 0 Then + Alert("No se tienen asignadas sucursales", TipoMensaje.MsgError) + Exit Sub + End If + + 'If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue <> "Cot" AndAlso (CveVenta <= 0 Or (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Or CveDevolucion > 0) Then + ' TxtFolio.Text = "" + 'Else + Dim ObjFolios As New ClsGralFolios() + Dim TipoDoctoConsulta As String = If(DdlTipoComprobante.SelectedValue = "Ant", "Ing", If(DdlTipoComprobante.SelectedValue = "PA", "Rem", DdlTipoComprobante.SelectedValue)) + + If ObjFolios.GetFolios(TipoDoctoConsulta, UsuarioActual.CveEmpresa) Then + Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue)) + If DT.Rows.Count > 0 Then + ViewState("CveFolio") = DT.Rows(0)("CveFolio").ToString.ToEntero + 'ViewState("NumAprobacion") = CLng(DT.Rows(0)("Aprobacion").ToString) + 'ViewState("FechaAprobacion") = DT.Rows(0)("FechaAprobacion").ToString.ToDate + ViewState("FolioActual") = DT.Rows(0)("FActual").ToString + LblSerie.Text = DT.Rows(0)("Serie").ToString + TxtFolio.Text = DT.Rows(0)("FActual").ToString + BtnCrearApartirDe.Enabled = True + BtnEmitirImprimir.Visible = True + TrVistaPrevia.Visible = True + UpFacturar.Update() + Else + Alert("No tiene registrados Folios para " & DdlTipoComprobante.SelectedItem.Text & " en esta sucursal.", TipoMensaje.MsgAdvertencia) + TrEmitir.Visible = False + TrVistaPrevia.Visible = False + BtnCrearApartirDe.Enabled = False + BtnEmitirImprimir.Visible = False + UpFacturar.Update() + End If + DT.Dispose() + End If + ObjFolios.Dispose() + 'End If + + End Sub + Private Sub CargaFormatoSucursal() + Dim dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue))) + If dr IsNot Nothing Then + ViewState("SucCalle") = dr("Calle") + ViewState("SucNoExt") = dr("NoExt") + ViewState("SucNoInt") = dr("NoInt") + ViewState("SucColonia") = dr("Colonia") + ViewState("SucLocalidad") = dr("Localidad") + ViewState("SucMunicipio") = dr("Municipio") + ViewState("SucEstado") = dr("Estado") + ViewState("SucPais") = dr("Pais") + ViewState("SucCP") = dr("CP") + ViewState("FormatoFactura") = dr("FormatoFactura") + ViewState("IVA") = dr("IVA") + DdlIVA.Visible = False + Select Case ViewState("IVA").ToString.ToDouble + Case 0 + DdlIVA.SelectedValue = "1" + PorcentajeIVA = ViewState("IVA").ToString.ToDecimal + Case 0.08 + DdlIVA.SelectedValue = If(EsCreaApartirDe, $"{(TmpDT.MAX("PorcentajeIVA").ToDecimal + 1).ToString}", "1.08") + PorcentajeIVA = If(EsCreaApartirDe, TmpDT.MAX("PorcentajeIVA").ToDecimal, ViewState("IVA").ToString.ToDecimal) + DdlIVA.Visible = If(Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0, True, False) + Case 0.16 + DdlIVA.SelectedValue = "1.16" + PorcentajeIVA = ViewState("IVA").ToString.ToDecimal + End Select + If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 AndAlso (Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0) Then RecalculaIVA() + 'ViewState("SubProyectoPorcentajeIVA") = dr("IVA") + ViewState("TipoFormato") = dr("TipoFormato") + ViewState("Serie") = dr("Serie") + LblSerie.Text = dr("Serie").ToString + If SerieXML <> "" Then LblSerie.Text = SerieXML + Dim CveSubProyecto As Integer = GetSubProyectoSucursal() + If CveSubProyecto > 0 Then CargaSubProyecto(CveSubProyecto) + UPPProy.Update() + + TipoVentaSucursal = dr("TipoVenta").ToString.ToEntero + + If dr("TipoVenta").ToString = "1" Then + LiBuscarPrecio.Visible = True + UpnTools.Update() + + 'activa el modo de pago efectivo directamente, y es venta nueva + If ViewState("CveVenta").ToString.ToEntero < 0 Then InicializaCondicionesPago() + + RBLPago.SelectedValue = "2" + LimpiaEscondeContado() + + If DdlCuentaEfectivo.Items.Count = 2 Then + DdlCuentaEfectivo.SelectedIndex = 0 + End If + + End If + End If + + UpFacturar.Update() + UpPS.Update() + + UpParametros.Update() + End Sub + Private Sub CargaVendedores() + + Dim CveVendedorActual = DdlVendedor.SelectedValue + + DdlVendedor.Items.Clear() + If UsuarioActual.Empresa.Funcionalidad(302) = "1" AndAlso DdlSubProyectoDatos.SelectedValue.ToEntero > 0 Then + DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue)).FiltraParametros("VendedorTipo = 1") + Else + DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros("VendedorTipo = 1") + End If + + DdlVendedor.SelectedValue = "0" + DdlVendedor.Items.Insert(0, New ListItem("Sin Asignar", "0")) + DdlVendedor.DataBind() + + DdlVendedor.SelectedValueExist(CveVendedorActual) + + If Not DdlVendedor.SelectedValue.ToEntero > 0 Then + DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString) + End If + End Sub +#End Region + +#Region " AGREGAR PS " + Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click + AgregarPS() + End Sub + Private Function ValidaAgregarPS(CvePS As Integer, CveUM As Integer, PU As Double, CveTipoPS As Integer) As Boolean 'NO TOCAR - IPP + + 'VALIDA PARAMETROS + If CvePS <= 0 Or CveUM <= 0 Then + Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) + Return False + End If + + If HdnPS.Value = "" Or HdnPS.Value = "-1" Then + Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) + Return False + End If + + 'SI USA CONTABILIDAD LA CLASIFICACION ES OBLIGATORIA + If DdlClasificacion.SelectedValue.ToEntero <= 0 AndAlso UsuarioActual.Empresa.UsaContabilidad Then + Alert("La Clasificación es obligatoria, favor de seleccionarla", TipoMensaje.MsgAdvertencia) + Return False + End If + + 'SUBPROYECTO OBLIGATORIO + If DdlSubProyecto.SelectedValue.ToEntero <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(120) = "1" Then + Alert("El Subproyecto es obligatorio, favor de seleccionarlo", TipoMensaje.MsgAdvertencia) + Return False + End If + + If CveCliente <= 0 And Not CveEmpresaCRM > 0 Then + Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact', 800, 547, 'N', 'PopUpBuscar')") + Return False + End If + + 'VALIDA PROMOCIONES + Dim ObjVentas As New ClsVentas + If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero, CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then + DtPromociones = ObjVentas.DtResultados + End If + ObjVentas.Dispose() + + 'VALIDA PRECIO CERO (0) + If UsuarioActual.Empresa.Funcionalidad(139).ToString.ToEntero > 0 And PU = 0 And DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {CvePS}").ToDecimal > 0 Then + Alert($"El producto {HdnPS.Value}. No se puede vender a un importe de cero ($0)", TipoMensaje.MsgAdvertencia) + Return False + End If + + + If Not UsuarioActual.TienePermisoProceso(169) Then ' NO VALIDA EXISTENCIAS NI COSTO - PERMISO PARA NO VALIDAR + 'SOLO VALIDA EXISTENCIAS Y COSTO: SI USA INVENTARIOS, SOLO PRODUCTOS TIPO PRODUCTO, SOLO REMISIONES E INGRESOS + If UsuarioActual.Empresa.UsaInventarios AndAlso CveTipoPS = 2 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119))) Then + Dim ObjInventarios As New ClsInventarios + Dim Existencia As Decimal = ObjInventarios.GetExistenciasPS(CvePS, CveUM, UsuarioActual.CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) + Dim Costo As Decimal = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) + + 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal + If Costo = 0 Then Costo = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1) + + ObjInventarios.Dispose() + Dim PrecioMinimo As Decimal = 0 + 'RMF. condicion temporal, para reubicación, precio mínimo + If UsuarioActual.CveEmpresa = 119 Then + 'Dim CvePrecioLista As Integer = 38 + Dim objPS As New ClsProductosServicios + If objPS.GetPSSucursalesALL(CvePS, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then + PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal + If PrecioMinimo > 0 Then + Costo = PrecioMinimo + End If + End If + objPS.Dispose() + + End If + + If DdlTipoComprobante.SelectedValue <> "Cot" And ChkSinExistencia.Checked = False Then + 'VALIDA EXISTENCIA + If UsuarioActual.CveEmpresa.Contiene({72, 80, 119}) Then + If Existencia - TmpDT.SUM("Cantidad", $"CvePS = {CvePS}") < TxtCantidad.Text.ToDouble Then + Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia) + Return False + End If + End If + End If + + 'VALIDA COSTOS + If Not CveContrato > 0 Then + + 'BANDERAS PARA VALIDACIONES + Dim EsValido = False + Dim EsValidoMayor = False + Dim CostoMenor = 0.0D + Dim CostoMayor = 0.0D + + 'PRECIO MINIMO + If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then + CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) + If PrecioMinimo > 0 Then CostoMenor = PrecioMinimo + + 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA + If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= CostoMenor Then + EsValido = True + End If + Else + EsValido = True + End If + + 'PRECIO MAXIMO + If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then + CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo) + 'SI EL PRECIO ES MAYOR AL COSTO MAXIMO, SI PASA + If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) <= CostoMayor Then + EsValidoMayor = True + End If + Else + EsValidoMayor = True + End If + + 'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR + 'SIRVE PARA VALIDAR PRECIOS DEBAJO DEL PRECIO MINIMO PERMITIDO + If Not EsValido Then + If DtPromociones.FiltraParametros($"CvePS = {CvePS}").Rows.Count > 0 Then + If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {CvePS}").ToDecimal Then + EsValido = True + End If + End If + End If + + 'NO DEJA REGISTRAR MENOS AL PRECIO MINIMO + Dim MensajeCosto As New StringBuilder + Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) + If Not EsValido Then + MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio menor de su Costo
    ", HdnPS.Value) + If TienePermisoImportes Then + MensajeCosto.AppendFormat("El costo del producto es: ${0}
    ", Costo) + MensajeCosto.AppendFormat("El rango menor aceptado es: {0}% ${1}
    ", UsuarioActual.Empresa.Funcionalidad(129).ToEntero, CostoMenor) + MensajeCosto.AppendFormat("El precio indicado es: ${0} ({1}% de ganancia)
    ", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) + End If + + Alert(String.Format(MensajeCosto.ToString), TipoMensaje.MsgAdvertencia) + Return False + End If + + 'NO DEJA REGISTRAR MAS AL PRECIO MAXIMO + If Not EsValidoMayor Then + MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio mayor de su rango aceptado
    ", HdnPS.Value) + If TienePermisoImportes Then + MensajeCosto.AppendFormat("El costo del producto es: ${0}
    ", Costo) + MensajeCosto.AppendFormat("El rango mayor aceptado es: {0}% ${1}
    ", UsuarioActual.Empresa.Funcionalidad(133).ToEntero, CostoMayor) + MensajeCosto.AppendFormat("El precio indicado es: ${0} ({1}% de ganancia)
    ", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) + End If + Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia) + Return False + End If + + End If + End If + End If + + + + Return True + + End Function + Private Sub AgregarPS() + + 'SELECCIONA EL PS DEPENDIENDO LA MODALIDAD (CODIGO BARRAS - DDL) + Dim CvePS = -1 + If DIVCod.Visible Then + CvePS = HdnCvePS.Value.ToEntero + Else + CvePS = DdlPS.SelectedValue.ToEntero + End If + + If ValidaAgregarPS(CvePS, DdlUnidadMedida.SelectedValue.ToEntero, TxtPrecio.Text.Trim.ToDouble, HdnTipoPS.Value.ToEntero) Then + + If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then + CvePSAmortizacion = DdlPS.SelectedValue.ToEntero.ToEntero + End If + + Dim Descuento As Decimal = HdnDescuento.Value.ToDecimal + If HdnTipoDescuento.Value = "0" Then + Descuento = HdnDescuento.Value.ToDecimal * TxtCantidad.Text.ToDecimal + End If + + AgregarProductoServicio(TxtCantidad.Text.ToDecimal, DdlUnidadMedida.SelectedValue.ToEntero, DdlUnidadMedida.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero, DdlClasificacion.SelectedItem.Text, + CvePS, "", TxtObsPS.Text.Trim, If(CvePSAmortizacion > 0, TxtPrecio.Text.Trim.ToDecimal * -1, TxtPrecio.Text.Trim.ToDecimal), Descuento, + DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, + SerieLote:=If(DIVCod.Visible, TxtCodigoSerie.Text.Trim, ""), TiempoEntrega:=TxtTiempoEntrega.Text, CuentaPredial:=TxtCuentaPredial.Text.Trim, RegeneraIEPS:=ClienteDesglosaIEPS) + + CalculaUsados() + + CalculaTotalesVenta() + + LimpiaAgregar() + + 'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW + If AplicaComercioExterior Then + CargaGvComercioExterior() + End If + End If + + ''NO SIRVE PARA NADA - NO SE USAN LAS VARIABLES - IPP 28 AGOSTO 2017 + 'For Each gvr As GridViewRow In GVAnticipos.Rows + ' Dim total As Decimal = TxtTotal.Text.ToString.ToDecimal + ' Dim saldo As Decimal = gvr.DataKey("Saldo").ToDecimal + ' Dim maxsaldo As Decimal + ' If total > saldo Then + ' maxsaldo = saldo + ' Else + ' maxsaldo = total + ' End If + 'Next + + End Sub + + + Private Sub AgregarPSPYME() + If Modalidad = "A" Then + + Dim CveProyecto As Integer = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedValue, "0").ToString.ToEntero + Dim Proyecto As String = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedItem.Text, "").ToString + + Dim CveSubProyecto As Integer = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedValue, "0").ToString.ToEntero + Dim SubProyecto As String = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedItem.Text, "").ToString + + AgregarProductoServicio(TxtCantidadPyME.Text.ToDecimal, DdlUMPyME.SelectedValue.ToEntero, DdlUMPyME.SelectedItem.Text, DdlClasificacionPyME.SelectedValue.ToEntero, DdlClasificacionPyME.SelectedItem.Text, + DdlPSPyME.SelectedValue.ToEntero, DdlPSPyME.SelectedText, TxtObsPyME.Text, TxtPrecioPyME.Text.ToDecimal, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) + + CalculaTotalesVenta() + + + + ElseIf Modalidad = "U" Then + + Dim ErrorEdit As Boolean = True + Dim Contador As Integer = 0 + For Each row As DataRow In TmpDT.Rows + If row("Consec").ToString.ToEntero = Index Then + ErrorEdit = False + Exit For + End If + Contador = Contador + 1 + Next + If ErrorEdit = True Then + Exit Sub + Else + TmpDT.AcceptChanges() + TmpDT.Rows.RemoveAt(Contador) + TmpDT.AcceptChanges() + End If + End If + + End Sub + Private Sub LimpiaAgregar() + TxtCantidad.Text = "" + HdnPS.Value = "-1" + HdnCodigoPS.Value = "-1" + HdnTipoPS.Value = "-1" + HdnTipoInv.Value = "-1" + + DdlClasificacion.SelectedIndex = 0 + + If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then + DdlPS.SelectedValue = "-1" + Else + DdlPS.SelectedValue = "" + DdlPS.SelectedText = "" + End If + + TxtObsPS.Text = "" + TxtPrecio.Text = "" + LblTotalPS.Text = "0.00" + HdnIVAPS.Value = "-1" + HdnIVARetAPS.Value = "-1" + HdnAplicaIEPS.Value = "False" + HdnPorcentajeIEPS.Value = "0" + HdnAsientoContable.Value = "-1" + HdnCtaContable.Value = "-1" + HdnAplicaParaConcepto.Value = "False" + HdnCodigo.Value = "-1" + TxtCuentaPredial.Text = "" + ' codigo comentado RMF. 2016.06.13, esto paa que respete el que tenga selecionado e nla sucursal + 'DdlProyecto.SelectedIndex = 0 + 'DdlSubProyecto.Items.Clear() + 'DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) + TxtCantidad.Focus() + + 'Limpia descuentos + HdnTipoDescuento.Value = "-1" + HdnDescuento.Value = "0" + LblPrecio1.Text = "0.00" + LblTotalPS1.Text = "0.00" + TxtPorDescP.Text = "0" + TxtDescP.Text = "0" + LblDescuento.Text = "0.00" + LblPrecioFinal.Text = "0.00" + + 'CODIGO BARRAS + TxtCodigoBarras.Text = "" + TxtCodigoSerie.Text = "" + + 'FOCUS DEPENDIENDO MODALIDAD DE CODIGO BARRAS + If DIVCod.Visible Then + TxtCodigoBarras.Focus() + Else + TxtCantidad.Focus() + End If + + UPPDescuento.Update() + UpINV.Update() + UPPPS.Update() + End Sub + Private Function AgregarProductoServicio(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String, + PU As Decimal, Descuento As Decimal, + CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, + Optional SerieLote As String = "", Optional TiempoEntrega As String = "", Optional EntregaDirecta As Integer = 0, + Optional CveContratoDetalle As Integer = 0, Optional CveVentaDetalle As Integer = 0, Optional CveMovimientoDetallePedido As Integer = 0, + Optional CveOrdenCompraDetalle As Integer = 0, Optional CveVentaDetalleRemision As Integer = 0, Optional CveVentaDetalleCotizacion As Integer = 0, + Optional CuentaPredial As String = "", Optional RegeneraIEPS As Boolean = True, Optional CveVentaDetallePedido2 As Integer = 0, + Optional SeActualiza As Boolean = False) As Boolean + + Dim Retorno As Boolean = False + If Not CvePS > 0 Then + Alert("Ocurrió un error al cargar la información del producto a agregar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError) + Return False + End If + + If (Obs.Length + PS.Length > 1000) AndAlso DdlTipoComprobante.SelectedValue <> "Cot" Then + Alert(String.Format("El Nombre y observación del producto tiene longitud de {0} caracteres y excede los 1000 caracteres permitidos.", Obs.Length + PS.Length), TipoMensaje.MsgAdvertencia) + Return False + End If + + 'VALIDA CONCEPTOS EN CERO - YA SE VALIDA ANTES CON FUNCIONALIDAD - A MIRAS DE ELIMINAR - IPP 28 AGOSTO 2017 + If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant") Then + If UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso CveOrdenCompraDetalle = 0 Then ' si viene de una oc, se permiten valores en cero + If Cantidad * PU <= 0 Then + If Not DdlTipoComprobante.SelectedValue = "DPe" Then + Alert("El importe del concepto debe ser mayor a cero. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Return False + End If + End If + End If + End If + + Dim Row As DataRow = Nothing + Dim TotalCalculableImpuestos As Decimal = 0 + PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos + + Row = TmpDT.NewRow() + Row("CveProyecto") = CveProyecto + Row("Proyecto") = Proyecto + Row("CveSubProyecto") = CveSubProyecto + Row("SubProyecto") = SubProyecto + Row("SerieLote") = SerieLote + Row("TiempoEntrega") = TiempoEntrega + Row("Orden") = TmpDT.Rows.Count + 1 + Row("Cantidad") = Cantidad + Row("CveUM") = CveUM + Row("UM") = UM + Row("CveClasificacion") = CveClasificacion + Row("Clasificacion") = Clasificacion + Row("CvePS") = CvePS + Row("Obs") = Obs + + + + Dim DrPS As DataRow = Nothing + + DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") ' Estado = -1 + + If DrPS Is Nothing Then + Alert("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.", TipoMensaje.MsgError) + Return False + End If + + If (DrPS("SATClaveUnidadMedida").ToString = "" Or DrPS("SATClavePS").ToString = "") Then + 'VALIDA CLAVESAT + If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then 'DOCUMENTOS DONDE NO SE VALIDA + If DrPS("SATClavePS").ToString = "" Then + MensajeCveSAT.AppendFormat("{0}-{1}: Sin producto SAT
    ", DrPS("Codigo").ToString, DrPS("PS").ToString) + Return False + ElseIf DrPS("SATClaveUnidadMedida").ToString = "" Then + MensajeCveSAT.AppendFormat("{0}-{1}: Sin Unidad Medida SAT
    ", DrPS("Codigo").ToString, DrPS("PS").ToString) + Return False + End If + End If + End If + + If Not ClienteDesglosaIEPS Then + If Not RegeneraIEPS Then + PU = PU * (1 + DrPS("IEPSPorcentaje").ToString.ToDecimal) + End If + DrPS("IEPSPorcentaje") = 0 + End If + + 'verifica si tiene ventaminima + If Cantidad > 0 AndAlso DrPS("VentaMinima").ToString.ToDecimal > 0 Then + 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... + If Cantidad Mod DrPS("VentaMinima").ToString.ToDecimal <> 0 Then + Alert(String.Format("El producto se vende solo en cantidades de {0}", DrPS("VentaMinima").ToString)) + Return False + End If + End If + + TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento + + Row("PU") = PU + Row("Codigo") = DrPS("Codigo") + Row("NoIdentificacion") = DrPS("Codigo") + Row("ClaveSATFraccionArancelaria") = DrPS("ClaveSATFraccionArancelaria") + Row("ClaveSATUnidadAduana") = DrPS("ClaveSATUnidadAduana") + Row("ClaveSATFraccionArancelariaDescripcion") = DrPS("ClaveSATFraccionArancelariaDescripcion") + Row("ClaveSATUnidadAduanaDescripcion") = DrPS("ClaveSATUnidadAduanaDescripcion") + If Modalidad = "U" Then + Row("Consec") = Index + Else + Row("Consec") = TmpDT.Rows.Count + 1 + End If + + Row("PS") = DrPS("PS") + Row("CodigoPS") = DrPS("PSCodigo").ToString + Row("CveTipoPS") = DrPS("CveTipoPS") + Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario") + Row("CveTamaño") = DrPS("CveTamaño") + + If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion") + If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion") + + If DrPS("IVA").ToString.Contiene("-1", "") Then + Row("PorcentajeIVA") = PorcentajeIVA + Else + Row("PorcentajeIVA") = DrPS("IVA") + End If + + Row("IVA") = Row("PorcentajeIVA") + Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + + + Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) + Row("PorcentajeRetIVA") = ClienteRetIVA + Row("PorcentajeRetISR") = ClienteRetISR + Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje") + Row("ImporteIEPS") = Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + Row("IEPS") = Row("ImporteIEPS") + Row("Descuento") = Math.Round(Descuento, NumeroDecimales) + Row("TipoDescuento") = HdnTipoDescuento.Value + Row("Total") = (Cantidad * PU) + Row("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales) + 'Row("AsientoContableVentas") = DrPS("AsientoContableVentas") + ' Row("IdCtaContVentas") = IdCtaContable + ' Row("AplicaParaConcepto") = AplicaParaConcepto + + Row("SATClaveProdServ") = DrPS("SATClavePS") + Row("SATClaveUM") = DrPS("SATClaveUnidadMedida") + + If UsuarioActual.Empresa.UsaAC Then + Row("CvePresupuestoIngreso") = Me.DdlFuenteRecaudacion.SelectedValue + End If + + Row("EntregaDirecta") = EntregaDirecta + 'Contratos + Row("CveContratoDetalle") = CveContratoDetalle + Row("CveVentaDetalle") = CveVentaDetalle + Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido + Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle + Row("CveVentaDetalleRemision") = CveVentaDetalleRemision + Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion + Row("CveVentaDetallePedido2") = CveVentaDetallePedido2 + Row("CuentaPredial") = CuentaPredial + + If UsuarioActual.CveEmpresa = 119 Then + If Not RemisionesLista.Count > 0 Then 'SI VIENE DE REMISION NO SE CONSIDERA + + 'MONEDA DIFERENTE DEL PS AL PRIMER PS AGREGADO + If DdlMoneda.Enabled = False And CveVenta < 0 And TmpDT.Rows.Count > 0 Then + If DdlMoneda.SelectedValue <> DrPS("CveMoneda").ToString Then + Alert($"La moneda base del producto: {DrPS("PSCodigo").ToString} es diferente a la moneda del documento.", TipoMensaje.MsgAdvertencia) + Return False + End If + End If + + 'ACTIVA PRODUCTOS DE LA MISMA MONEDA + If TmpDT.Rows.Count = 0 And CveVenta < 0 Then + DdlMoneda.SelectedValueExist(DrPS("CveMoneda").ToString) + CambiaMoneda() + DdlMoneda.Enabled = False + End If + End If + End If + + + 'RECARGAR GV + TmpDT.Rows.Add(Row) + + + 'AGREGA PS ADICIONAL + If UsuarioActual.Empresa.Funcionalidad(561).ToString = "1" AndAlso GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows.Count > 0 AndAlso ChkPoliza.Checked AndAlso Not SeActualiza Then + For Each Dr As DataRow In GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows + Dim CvePSAdicional As Integer = Dr("CvePSAdicional").ToString.ToEntero + Dim DrPoliza As DataRow = TmpDT.NewRow() + DrPoliza.ItemArray = Row.ItemArray + Dim DrPSAdicional = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSAdicional).Rows(0) + If DrPSAdicional IsNot Nothing Then + DrPoliza("CvePS") = CvePSAdicional + DrPoliza("PS") = DrPSAdicional("PS").ToString + DrPoliza("CveUM") = DrPSAdicional("CveUM").ToString.ToEntero + DrPoliza("UM") = DrPSAdicional("UnidadMedida").ToString + DrPoliza("CveClasificacion") = DrPSAdicional("CveClasificacion").ToString.ToEntero + DrPoliza("Clasificacion") = DrPSAdicional("Clasificacion").ToString + DrPoliza("CodigoPS") = DrPSAdicional("PSCodigo").ToString + DrPoliza("CveTipoPS") = DrPSAdicional("CveTipoPS") + DrPoliza("CveTipoInvPS") = DrPSAdicional("Inv_CveMetodoInventario") + DrPoliza("NoIdentificacion") = DrPSAdicional("Codigo") + If Modalidad = "U" Then + DrPoliza("Consec") = Index + Else + DrPoliza("Consec") = TmpDT.Rows.Count + 1 + End If + Row("Orden") = TmpDT.Rows.Count + 1 + DrPoliza("Cantidad") = If(Dr("Cantidad").ToString.ToDecimal > 0, Dr("Cantidad").ToString.ToDecimal, Cantidad) + PU = 0 + + Dim PrecioSugerido As Decimal = 0 + Dim CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero + If CvePrecioListaPS > 0 Then + Dim ObjPS As New ClsProductosServicios + If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSAdicional) Then + + PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDecimal + If PrecioSugerido = 0 Then + Dim ObjInventarios As New ClsInventarios + Dim CostoPS = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString.ToDecimal, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero) + + 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal + If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString.ToDecimal, -1, "-1", TxtFecha.Text.ToDate, -1) + + ObjInventarios.Dispose() + Dim PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal + If CostoPS > 0 And PorcentajePrecio > 0 Then + PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS + End If + End If + ObjPS.Dispose() + End If + End If + + + If PrecioSugerido > 0 Then + PU = PrecioSugerido + End If + PU = Math.Round(PU, 6) + DrPoliza("PU") = PU + TotalCalculableImpuestos = (DrPoliza("Cantidad").ToString.ToDecimal * (PU)) - Descuento + + If DrPSAdicional("IVA").ToString.Contiene("-1", "") Then + DrPoliza("PorcentajeIVA") = PorcentajeIVA + Else + DrPoliza("PorcentajeIVA") = DrPSAdicional("IVA") + End If + DrPoliza("IVA") = DrPoliza("PorcentajeIVA") + DrPoliza("ImporteIVA") = Math.Round(DrPoliza("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + DrPoliza("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) + DrPoliza("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) + DrPoliza("PorcentajeRetIVA") = ClienteRetIVA + DrPoliza("PorcentajeRetISR") = ClienteRetISR + DrPoliza("PorcentajeIEPS") = DrPSAdicional("IEPSPorcentaje") + DrPoliza("ImporteIEPS") = Math.Round(DrPSAdicional("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) + DrPoliza("IEPS") = DrPoliza("ImporteIEPS") + DrPoliza("Descuento") = Math.Round(Descuento, NumeroDecimales) + DrPoliza("TipoDescuento") = HdnTipoDescuento.Value + DrPoliza("Total") = (DrPoliza("Cantidad").ToString.ToDecimal * PU) + DrPoliza("TotalImporte") = Math.Round(DrPoliza("Cantidad").ToString.ToDecimal * PU, NumeroDecimales) + DrPoliza("SATClaveProdServ") = DrPSAdicional("SATClavePS") + DrPoliza("SATClaveUM") = DrPSAdicional("SATClaveUnidadMedida") + + TmpDT.Rows.Add(DrPoliza) + End If + Next + End If + + Retorno = True + Return Retorno + End Function + +#End Region + +#Region "D A T A - T A B L E S" + Private Sub CreaDTVentas() + TmpDT = New DataTable + TmpDT.Columns.Add("CveVenta", GetType(Integer)) + 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("SATClaveUM", GetType(String)) + TmpDT.Columns.Add("CveClasificacion", GetType(Integer)) + TmpDT.Columns.Add("Clasificacion", GetType(String)) + TmpDT.Columns.Add("CvePS", GetType(Integer)) + TmpDT.Columns.Add("PS", GetType(String)) + TmpDT.Columns.Add("CodigoPS", GetType(String)) + TmpDT.Columns.Add("SATClaveProdServ", GetType(String)) + TmpDT.Columns.Add("NoIdentificacion", GetType(String)) + TmpDT.Columns.Add("CveTipoPS", GetType(Integer)) + TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer)) + TmpDT.Columns.Add("SerieLote", GetType(String)) + TmpDT.Columns.Add("CuentaPredial", GetType(String)) + TmpDT.Columns.Add("Obs", GetType(String)) + TmpDT.Columns.Add("TiempoEntrega", GetType(String)) + TmpDT.Columns.Add("PU", GetType(Decimal)) + TmpDT.Columns.Add("IVA", GetType(Decimal)) + TmpDT.Columns.Add("ImporteIVA", GetType(Decimal)) + TmpDT.Columns.Add("PorcentajeIVA", GetType(Decimal)) + TmpDT.Columns.Add("ImporteRetIVA", GetType(Decimal)) + TmpDT.Columns.Add("ImporteRetISR", GetType(Decimal)) + TmpDT.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) + TmpDT.Columns.Add("PorcentajeRetISR", GetType(Decimal)) + TmpDT.Columns.Add("ImporteIEPS", GetType(Decimal)) + TmpDT.Columns.Add("IEPS", GetType(Decimal)) + TmpDT.Columns.Add("PorcentajeIEPS", GetType(Decimal)) + TmpDT.Columns.Add("Descuento", GetType(Decimal)) + TmpDT.Columns.Add("TipoDescuento", GetType(Integer)) + TmpDT.Columns.Add("TotalImporte", GetType(Decimal)) + TmpDT.Columns.Add("Total", GetType(Decimal)) + 'Para uso del módulo contable + TmpDT.Columns.Add("AsientoContableVentas", GetType(Integer)) + TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer)) + TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean)) + TmpDT.Columns.Add("CveProyecto", GetType(Integer)) + TmpDT.Columns.Add("Proyecto", GetType(String)) + TmpDT.Columns.Add("CveSubProyecto", GetType(Integer)) + TmpDT.Columns.Add("SubProyecto", GetType(String)) + TmpDT.Columns.Add("CveVentaDetallePadre", GetType(Integer)) + + 'TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto + TmpDT.Columns.Add("CvePresupuestoIngreso", GetType(Integer)) + TmpDT.Columns.Add("CveFuenteRecaudacion", GetType(Integer)) + 'Contratos + TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer)) + 'Remisiones a Facturas + TmpDT.Columns.Add("CveVentaDetalle", GetType(Integer)) + TmpDT.Columns.Add("CveVentaDetalleRemision", GetType(Integer)) + TmpDT.Columns.Add("CveVentaDetalleCotizacion", GetType(Integer)) + + 'Pedido2 a Facturas + TmpDT.Columns.Add("CveVentaDetallePedido2", GetType(Integer)) + + TmpDT.Columns.Add("Origen", GetType(Integer)) + 'Ordenes Servicio + TmpDT.Columns.Add("CveOS", GetType(Integer)) + TmpDT.Columns.Add("CveOSDetalle", GetType(Integer)) + TmpDT.Columns.Add("SeFacturara", GetType(Integer)) + TmpDT.Columns.Add("Folio", GetType(Integer)) + TmpDT.Columns.Add("Estatus", GetType(String)) + 'Ordenamiento + TmpDT.Columns.Add("Orden", GetType(Integer)) + TmpDT.Columns.Add("TipoDocto", GetType(String)) + 'OC + TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer)) + TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) + + TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) + TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) + TmpDT.Columns.Add("CantidadFacturadaCot", GetType(Decimal)) + TmpDT.Columns.Add("CantidadFacturadaPed2", GetType(Decimal)) + TmpDT.Columns.Add("CantidadInventario", GetType(Decimal)) + + TmpDT.Columns.Add("ClaveSATFraccionArancelaria", GetType(String)) + TmpDT.Columns.Add("ClaveSATUnidadAduana", GetType(String)) + TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", GetType(String)) + TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", GetType(String)) + + TmpDT.Columns.Add("CveTamaño", GetType(Integer)) + + End Sub + Private Sub CreaDTmpC() + DTmpC = New DataTable + DTmpC.Columns.Add("Descripcion", GetType(String)) + End Sub + Private Sub CreaDTmpF() + DTmpF = New DataTable + DTmpF.Columns.Add("CveVenta", GetType(Integer)) + DTmpF.Columns.Add("Titulo", GetType(String)) + DTmpF.Columns.Add("Nombre", GetType(String)) + DTmpF.Columns.Add("Puesto", GetType(String)) + DTmpF.Columns.Add("Lado", GetType(Integer)) + End Sub + Private Sub CreaDTImpuestos() + TmpDTImpuestos = New DataTable + TmpDTImpuestos.Columns.Add("CveImpuestoLocal", GetType(Integer)) + TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String)) + TmpDTImpuestos.Columns.Add("Porcentaje", GetType(Decimal)) + TmpDTImpuestos.Columns.Add("Importe", GetType(Decimal)) + TmpDTImpuestos.Columns.Add("TipoImpuesto", GetType(Integer)) + TmpDTImpuestos.Columns.Add("IdCtaContable", GetType(Integer)) + TmpDTImpuestos.Columns.Add("CveCuenta", GetType(Integer)) + TmpDTImpuestos.Columns.Add("Orden", GetType(Integer)) + End Sub + Private Sub CreaDTImpuestosIVAIEPS() + TmpDTImpuestosIVAIEPS = New DataTable + TmpDTImpuestosIVAIEPS.Columns.Add("Impuesto", GetType(String)) + TmpDTImpuestosIVAIEPS.Columns.Add("tasa", GetType(String)) + TmpDTImpuestosIVAIEPS.Columns.Add("Importe", GetType(Decimal)) + TmpDTImpuestosIVAIEPS.Columns.Add("Orden", GetType(Integer)) + End Sub + Private Sub CreaDTDocumentosRelacionados() + TmpDTDocumentosRelacionados = New DataTable + TmpDTDocumentosRelacionados.Columns.Add("SerieFolio", GetType(String)) + TmpDTDocumentosRelacionados.Columns.Add("Fecha", GetType(String)) + TmpDTDocumentosRelacionados.Columns.Add("Importe", GetType(Decimal)) + TmpDTDocumentosRelacionados.Columns.Add("FolioFiscal", GetType(Integer)) + End Sub +#End Region + +#Region "P D F" + + +#End Region + +#Region "A C T U A L I Z A " + +#Region "New" 'Private Function ActualizaTimbrado(Timbro As Boolean, CveVenta As Integer) As Boolean ' Dim Retorno = False ' Dim ObjVentas As New ClsVentas() @@ -13850,781 +13857,781 @@ Partial Class Ventas ' ObjCliente.UpdateClienteFactura(NumCtaPago, MetodoDePago, CveCliente, UsuarioActual.CveUsuario) ' ObjCliente.Dispose() 'End Sub -#End Region -#End Region +#End Region +#End Region -#Region "M E T O D O S" - Private Sub CargaOtrosConceptos() - Dim ObjVentas As New ClsVentas - If ObjVentas.GetVentaOtrosConceptos(UsuarioActual.CveEmpresa, CveVenta) Then - GVOtrosConceptos.DataSource = ObjVentas.DtResultados - GVOtrosConceptos.DataBind() - UpOtrosConceptos.Update() - End If - ObjVentas.Dispose() - End Sub - Private Function GenerarPolizaAC(ObjAC As ClsContPAQi, factura As Modelos.Factura, Optional CancelacionIngreso As Boolean = False) As Integer - Dim Retorno As Integer = 0 - Dim IDPoliza As Integer = 0 - - Dim ErrorAC As Boolean = False - 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - Dim Fecha As Date = factura.Fecha - Dim Concepto As String = String.Format("GD {0}", factura.Cliente.Nombre) - Dim Paridad As Integer = 1 - Dim TipoMovto As Boolean = False - - If CancelacionIngreso Then - Concepto = String.Format("Cancelación GD {0}", factura.Cliente.Nombre) - Paridad = -1 - TipoMovto = True - End If - - Dim TipoPoliza = If(factura.TipoDocto = "OP" Or factura.TipoDocto = "Com", 3, 1) - - IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, factura.Total * 2, factura.Total * 2, factura.CveUsuario, Fecha) - Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue)) - 'Dim Importe As Double = TxtTotal.Text.ToDouble - Dim CtaCliente As Integer = factura.Cliente.IdCtaContClientes - Dim CtaISSSTESON As Integer = 643 - Dim CtaISPT As Integer = 1745 - ' Dim NombreCliente As String = ViewState("NombreCliente").ToString - - If IDPoliza > 0 Then - - 'Orden de PAGO - If factura.TipoDocto = "OP" Then - - If DdlOrdenPago.SelectedValue.ToEntero = 1 Then - 'ISSSTESON - - If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then - If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then - ErrorAC = True - End If - Else - ErrorAC = True - End If - - Else - 'ISPT - - If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then - If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then - ErrorAC = True - End If - Else - ErrorAC = True - End If - End If - - ' NORMAL - Else - Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)() - Group gvr By Grp = New With { - Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero - } Into Group - Select Grp.CvePresupuestoIngreso, - TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble) - - - 'Select Case TipoComprobante - ' Case "Ing", "Egs" - For Each grp In Detalles - dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso)) - Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString, TxtFolio.Text) - - If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString.ToEntero, False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - 'CARGO la deuda del cliente - If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - 'abono, - If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString.ToEntero, Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - ErrorAC = True - End If - Else - ErrorAC = True - End If - Else - ErrorAC = True - End If - Else - ErrorAC = True - End If - Next - - 'Case "OP", "Com" - ' Dim Importe As Decimal = 0 - ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then - ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then - - ' End If - ' End If - 'End Select - End If - - Else - ErrorAC = True - - End If - - If Not ErrorAC Then - ObjAC.AjustaPoliza(IDPoliza) - - Retorno = IDPoliza - Else - - Alert("Error al agregar la Póliza de AC.", TipoMensaje.MsgError) - End If - - ' ObjAC.Dispose() - - Return Retorno - - End Function - Private Function GenerarPolizaAC(ObjAC As ClsContPAQi, Optional CancelacionIngreso As Boolean = False) As Integer - Dim Retorno As Integer = 0 - Dim IDPoliza As Integer = 0 - - Dim ErrorAC As Boolean = False - 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - Dim Fecha As Date = TxtFecha.Text.ToDate - Dim Concepto As String = String.Format("GD {0}", NombreCliente) - Dim Paridad As Integer = 1 - Dim TipoMovto As Boolean = False - - If CancelacionIngreso Then - Concepto = String.Format("Cancelación GD {0}", NombreCliente) - Paridad = -1 - TipoMovto = True - End If - - Dim TipoPoliza = If(DdlTipoComprobante.SelectedValue.ToString = "OP" Or DdlTipoComprobante.SelectedValue.ToString = "Com", 3, 1) - - IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, TxtTotal.Text.ToDouble * 2, TxtTotal.Text.ToDouble * 2, UsuarioActual.CveUsuario, Fecha) - Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue)) - 'Dim Importe As Double = TxtTotal.Text.ToDouble - Dim CtaCliente As Integer = ViewState("IdCtaContClientes").ToString.ToEntero - Dim CtaISSSTESON As Integer = 643 - Dim CtaISPT As Integer = 1745 - ' Dim NombreCliente As String = ViewState("NombreCliente").ToString - - If IDPoliza > 0 Then - - 'Orden de PAGO - If DdlTipoComprobante.SelectedValue.ToString = "OP" Then - - If DdlOrdenPago.SelectedValue.ToEntero = 1 Then - 'ISSSTESON - - If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then - If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then - ErrorAC = True - End If - Else - ErrorAC = True - End If - - Else - 'ISPT - - If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then - If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then - ErrorAC = True - End If - Else - ErrorAC = True - End If - End If - - ' NORMAL - Else - Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)() - Group gvr By Grp = New With { - Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero - } Into Group - Select Grp.CvePresupuestoIngreso, - TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble) - - - 'Select Case TipoComprobante - ' Case "Ing", "Egs" - For Each grp In Detalles - dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso)) - Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString, TxtFolio.Text) - - If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString.ToEntero, False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - 'CARGO la deuda del cliente - If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - 'abono, - If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString.ToEntero, Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then - ErrorAC = True - End If - Else - ErrorAC = True - End If - Else - ErrorAC = True - End If - Else - ErrorAC = True - End If - Next - - 'Case "OP", "Com" - ' Dim Importe As Decimal = 0 - ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then - ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then - - ' End If - ' End If - 'End Select - End If - - Else - ErrorAC = True - - End If - - If Not ErrorAC Then - ObjAC.AjustaPoliza(IDPoliza) - - Retorno = IDPoliza - Else - - Alert("Error al Agregar la Póliza de AC.", TipoMensaje.MsgError) - End If - - ' ObjAC.Dispose() - - Return Retorno - - End Function - Private Sub SetValues() - ViewState("TipoCambio") = 1 - - If UsuarioActual.Empresa.MostrarRetIVA Then TrRetIVA.Style.Add("display", "") - If UsuarioActual.Empresa.MostrarRetISR Then TrRetISR.Style.Add("display", "") - - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then ' agregar en el modal de PS. que forme el código del producto - TxtPS.Enabled = False - DivDdlTipo.Visible = True - DivTxtModelo.Visible = True - DivTxtAdicional.Visible = True - DdlTipo.Attributes.Add("onChange", "CreaDescripcionPS();") - DdlMarcaPSDes.Attributes.Add("onChange", "CreaDescripcionPS();") - TxtModelo.Attributes.Add("onKeyUp ", "CreaDescripcionPS();") - TxtAdicional.Attributes.Add("onKeyUp ", "CreaDescripcionPS();") - - CargaClasificacionesDetalles() - ClasificacionModal() - - End If - - If Not UsuarioActual.CveEmpresa.Contiene(1, 119) Then 'PAGO CON TERMINAL PARA JAM - RBLPago.Items.RemoveAt(2) - End If - - - End Sub - Private Sub SetPermisos() - If CveVenta < 1 Then - 'Puede cotizar - If Not UsuarioActual.TienePermisoProceso(59) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) - End If - - 'Puede Hacer NC - If Not UsuarioActual.TienePermisoProceso(175) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) - End If - - 'Puede Hacer Devolución - If Not UsuarioActual.TienePermisoProceso(264) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) - End If - - 'Puede facturar - If Not UsuarioActual.TienePermisoProceso(60) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) - End If - - 'Puede remisionar - If Not UsuarioActual.TienePermisoProceso(199) Then - DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) - LnkFacturarRemision.Visible = False - LnkRemisiones.Visible = False - End If - - '[IPP]: FALTA CONFIGURAR Y DAR PERMISO A TODOS LOS QUE TENGAN ACCESO A VENTAS - ''Puede remisionar - 'If Not UsuarioActual.TienePermisoProceso(199) Then - ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) - 'End If - - ''MODO SOLO LECTURA - 'If DdlTipoComprobante.Items.Count = 0 Then - ' DdlTipoComprobante.Items.Insert(0, New ListItem("Solo lectura", "-1")) - ' TrBotones.Visible = False - 'End If - - ConfiguraTipoDocto() - End If - End Sub - Private Sub CalculaTotalesVenta(Optional RecalculaImpuestosLocales As Boolean = True) - - Dim TotalSubTotal As Decimal = TmpDT.SUM("TotalImporte").ToDecimal - Dim TotalDescuentos As Decimal = TmpDT.SUM("Descuento").ToDecimal - Dim TotalAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal - Dim TotalIVA As Decimal = TmpDT.SUM("ImporteIVA").ToDecimal - Dim TotalIEPS As Decimal = TmpDT.SUM("ImporteIEPS").ToDecimal - Dim TotalRetIVA As Decimal = TmpDT.SUM("ImporteRetIVA").ToDecimal - Dim TotalRetISR As Decimal = TmpDT.SUM("ImporteRetISR").ToDecimal - Dim Total As Decimal = 0 - Dim TotalImpuestosLocales As Decimal = 0 - - If TotalAmortizacion > 0 AndAlso TotalSubTotal = TotalAmortizacion Then ' si se amortizó completa la factura, debe de limpiar los impuestos - If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("3") Then - For Each dr As DataRow In TmpDT.Rows - dr("ImporteIVA") = 0 : dr("ImporteIEPS") = 0 : dr("ImporteRetIVA") = 0 : dr("ImporteRetISR") = 0 : dr("PorcentajeIVA") = 0 : dr("IVA") = 0 - Next - - If TmpDTImpuestos IsNot Nothing Then - For Each dr2 As DataRow In TmpDTImpuestos.Rows - dr2("Importe") = 0 - Next - TmpDTImpuestos.AcceptChanges() - End If - - TmpDT.AcceptChanges() - TotalIVA = TmpDT.SUM("ImporteIVA").ToDecimal - TotalIEPS = TmpDT.SUM("ImporteIEPS").ToDecimal - TotalRetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal - TotalRetISR = TmpDT.SUM("ImporteRetISR").ToDecimal - TotalImpuestosLocales = TmpDTImpuestos.SUM("Importe").ToDecimal - End If - End If - - If RecalculaImpuestosLocales AndAlso TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then - If TotalSubTotal <> TotalAmortizacion Then - For Each drt As DataRow In TmpDTImpuestos.Rows - drt("Importe") = drt("Porcentaje").ToString.ToDecimal * TotalSubTotal / 100 - Next - End If - - GvImpuestosLocales2.DataSource = TmpDTImpuestos - GvImpuestosLocales2.DataBind() - End If - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - - If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal > 0 Then - If gvr.DataKey("TipoImpuesto") = "5" Then ' traslado de imp local - TotalImpuestosLocales -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal - Else - TotalImpuestosLocales += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal - End If - End If - End If - Next - - 'If TotalDescuentos > 0 Then GvPS.Columns(ColumnaDescuento).Visible = True : thEncDesc1.Visible = True : thEncDesc2.Visible = True Else GvPS.Columns(ColumnaDescuento).Visible = False : thEncDesc1.Visible = False : thEncDesc2.Visible = False - If TotalIEPS > 0 Then TrIEPS.Visible = True : GvPS.Columns(ColumnaIEPS).Visible = True : thEncIEPS1.Visible = True : thEncIEPS2.Visible = True Else TrIEPS.Visible = False : GvPS.Columns(ColumnaIEPS).Visible = False : thEncIEPS1.Visible = False : thEncIEPS2.Visible = False - If TotalRetIVA > 0 Then GvPS.Columns(ColumnaRetIVA).Visible = True Else GvPS.Columns(ColumnaRetIVA).Visible = False - If TotalRetISR > 0 Then GvPS.Columns(ColumnaRetISR).Visible = True Else GvPS.Columns(ColumnaRetISR).Visible = False - - If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero.Contiene(2, 1) Then - TotalAmortizacion = 0 - End If - - - Total = (TotalSubTotal - TotalDescuentos - TotalAmortizacion + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) - LblSubTotal1.Text = TotalSubTotal.FormatoNumero(2) - TxtSubTotal.Text = TotalSubTotal.FormatoNumero(2) - LblDescuentos.Text = TotalDescuentos.FormatoNumero - TxtSubTotal2.Text = (TotalSubTotal - TotalDescuentos - TotalAmortizacion).FormatoNumero(2) - TxtRetIVA.Text = TotalRetIVA.FormatoNumero(2) - TxtRetISR.Text = TotalRetISR.FormatoNumero(2) - TxtIVA.Text = TotalIVA.FormatoNumero - TxtIEPS.Text = TotalIEPS.FormatoNumero - TxtTotal.Text = Total.FormatoNumero - - LblAmort.Text = TxtSubTotal.Text - If CveVenta <= 0 OrElse (CveDevolucion > 0 And NuevaFactura = 1) Then - HdnVentaSaldo.Value = Total.ToString - Else - HdnVentaSaldo.Value = SaldoVenta.ToString - End If - HdnIVAOriginal.Value = TxtIVA.Text - - 'JJMQ 20160506: Se agrego para la validacion de pago de contado. - CVImporteContado.ValueToCompare = Total.ToString - - If MensajeCveSAT IsNot Nothing AndAlso MensajeCveSAT.ToString.Length > 0 Then - Alert($"Los siguientes conceptos hace falta especificar clave SAT

    {MensajeCveSAT.ToString}", TipoMensaje.MsgAdvertencia) - MensajeCveSAT.Clear() - End If - - Dim view As DataView = New DataView(TmpDT) - view.Sort = "Consec" - GvPS.DataSource = view - GvPS.DataBind() - - 'RECARGA GV INVENTARIO - If Not CveVenta > 0 Then - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - CargaGVInv(DtInv) - End If - - UpContado.Update() - UpPS.Update() - RegistraScript("BorraDescuentos();", "BorraDescuentos") - End Sub - Private Function ValidaAdendaFEMSA() As Boolean - Dim Retorno As Boolean = False - - If Not AplicaFEMSA Then - Retorno = True - Else - If TxtFEMSA_Version.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_Version.Text.Trim) Then - Retorno = False - Alert("La versión de la Adenda es requerida y debe ser numérica. Por favor corrija.", TipoMensaje.MsgAdvertencia) - ElseIf TxtFEMSA_NumSociedad.Text.Trim.Length = 0 Then - Retorno = False - Alert("El número de Sociedad para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) - ElseIf TxtFEMSA_NumProveedor.Text.Trim.Length = 0 Then - Retorno = False - Alert("El número de Proveedor para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) - ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumPedido.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumPedido.Text.Trim)) Then - Retorno = False - Alert("El número de Pedido para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) - ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumEntrada.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumEntrada.Text.Trim)) Then - Retorno = False - Alert("El número de Entrada para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) - ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso TxtFEMSA_NumRemision.Text.Trim.Length = 0 Then - Retorno = False - Alert("El número de Remisión para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) - ElseIf TxtFEMSA_Mail.Text.Trim.Length = 0 Then - Retorno = False - Alert("El Mail para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) - Else - Retorno = True - End If - End If - - Return Retorno - End Function - Private Function ValidaComplementoDetallista() As Boolean - Dim Retorno As Boolean = False - - If Not AplicaDetallista Then - Retorno = True - Else - If TxtDet_OrdenCompra.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_OrdenCompra.Text.Trim) Then - Retorno = False - Alert("El campo Orden de Compra es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia, "") - ElseIf TxtDet_FechaOrdenCompra.Text.Trim.Length = 0 OrElse Not IsDate(TxtDet_FechaOrdenCompra.Text.Trim) Then - Retorno = False - Alert("El campo Fecha de Orden de Compra es requerido y debe de contar con un formato válido de fecha. Por favor corrija.", TipoMensaje.MsgAdvertencia) - ElseIf TxtDet_GLNComprador.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNComprador.Text.Trim) Then - Retorno = False - Alert("El campo GLN-Comprador es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) - ElseIf TxtDet_Departamento.Text.Trim.Length = 0 Then - Retorno = False - Alert("El campo Departamento es requerido. Por favor ingrese uno.", TipoMensaje.MsgAdvertencia) - ElseIf TxtDet_GLNVendedor.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNVendedor.Text.Trim) Then - Retorno = False - Alert("El campo GLN-Vendedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) - ElseIf TxtDet_NumProv.Text.Trim.Length = 0 Then - Retorno = False - Alert("El campo Número de Proveedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) - Else - Retorno = True - End If - End If - - Return Retorno - End Function - Private Function ValidaComplementoFord() As Boolean - Dim Retorno As Boolean = False - - If Not AplicaFord Then - Retorno = True - Else - If TxtFordGSDB.Text.Trim.Length = 0 Then - Retorno = False - Alert("El campo GSDB es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia) - Else - If LstFordASN.Items.Count = 0 Then - Retorno = True - 'Alert("El campo ASN es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia) - Else - Retorno = True - End If - - End If - End If - - Return Retorno - End Function - Private Sub VinculaCotizacionVenta() - Dim ObjVentas As New ClsVentas() - ObjVentas.UpdateVentaCotizacion(CveVenta, Request("CveVenta").ToEntero) - ObjVentas.Dispose() - End Sub - Private Sub GeneraAddenda7Eleven(Archivo As String) - Dim cfdi As String = "" - Dim SB As New StringBuilder - Try - Using sr As New StreamReader(Archivo) - - cfdi = sr.ReadToEnd() - - End Using - Catch e As Exception - Alert("The file could not be read:", TipoMensaje.MsgError) - - End Try - - - cfdi = cfdi.Replace("", "") - - SB.Append(cfdi) - - SB.Append("") - SB.AppendFormat("", Txt7ElevenNumProveedor.Text.Trim) - SB.AppendFormat("", Txt7ElevenFolio.Text.Trim, Txt7ElevenTienda.Text.Trim, Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-MM-dd")) - - For Each Row As DataRow In TmpDT.Rows - - SB.AppendFormat("", Row("Codigo"), Row("PS"), Row("Cantidad").ToString.ToDouble.FormatoNumero(), Row("PU").ToString.ToDouble.FormatoNumero()) - - Next - - SB.Append("") - - - Using outfile As New StreamWriter(Archivo) - outfile.Write(SB.ToString()) - End Using - - 'Exit Sub - - - - 'Dim MyXmlDocument As New XmlDocument() - - 'MyXmlDocument.Load("C:/Temp/aaa.xml") - 'Dim nsmgr = New XmlNamespaceManager(MyXmlDocument.NameTable) - 'nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3") - 'Dim ParentElement As XmlElement = MyXmlDocument.CreateElement("cfdi:Addenda", "https://edixcfisecure.ekomercio.com/esquemas") - 'ParentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") - 'ParentElement.SetAttribute("xsi:schemaLocation", "https://edixcfisecure.ekomercio.com/esquemas https:/edixcfdisecure.ekomercio.com/esquemas/7Eleven.xsd") - - 'Dim Prov As XmlElement = MyXmlDocument.CreateElement("cfdi:Proveedor", "") - 'Prov.SetAttribute("Clave", "3125") - - 'Dim ns As String = "cfdi" 'MyXmlDocument.DocumentElement.GetNamespaceOfPrefix("cfdi") - 'Dim Recepciones As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepciones") - 'Recepciones.Prefix = "cfdi" - 'Dim Recepcion As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepcion") - 'Recepcion.SetAttribute("folio", Txt7ElevenFolio.Text.Trim) - 'Recepcion.SetAttribute("tienda", Txt7ElevenTienda.Text.Trim) - 'Recepcion.SetAttribute("fecha", Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-dd-MM")) - - 'Dim Productos As XmlElement = MyXmlDocument.CreateElement("cfdi:Productos") - ''dentro de un ciclo - 'Dim Producto As XmlElement = MyXmlDocument.CreateElement("cfdi:Producto") - 'Producto.SetAttribute("codigo", "cod1") - 'Producto.SetAttribute("descripcion", "prod1") - 'Producto.SetAttribute("cantidad", "99") - 'Producto.SetAttribute("precio", "2000") - 'Productos.AppendChild(Producto) - ''fin de ciclo - - 'Recepcion.AppendChild(Productos) - - 'Recepciones.AppendChild(Recepcion) - - 'ParentElement.AppendChild(Prov) - - 'ParentElement.AppendChild(Recepciones) - - - 'MyXmlDocument.DocumentElement.AppendChild(ParentElement) - 'MyXmlDocument.Save("C:/Temp/aa.xml") - - End Sub - Protected Sub DdlFuenteRecaudacion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFuenteRecaudacion.SelectedIndexChanged - For Each dr As DataRow In TmpDT.Rows - dr("CvePresupuestoIngreso") = DdlFuenteRecaudacion.SelectedValue - Next - - GvPS.DataSource = TmpDT - GvPS.DataBind() - - UpPS.Update() - End Sub - Protected Sub DdlFR_SelectedIndexChanged(sender As Object, e As EventArgs) - Dim DdlFR_Gv As DropDownList = CType(sender, DropDownList) - Dim index As Integer = CType(DdlFR_Gv.NamingContainer, GridViewRow).FCLiteral("LtlConsecutivo").Text.ToString.ToEntero - - If UsuarioActual.Empresa.UsaAC Then - TmpDT(index - 1)("CvePresupuestoIngreso") = DdlFR_Gv.SelectedValue - End If - TmpDT.AcceptChanges() - End Sub - Protected Sub LnkASN_Click(sender As Object, e As EventArgs) Handles LnkASN.Click - If TxtFordASN.Text.Trim.Length > 20 Then Alert("Maximo 20 Caracteres", TipoMensaje.MsgAdvertencia) : Exit Sub - LstFordASN.Items.Add(New ListItem(TxtFordASN.Text.Trim)) - TxtFordASN.Text = "" - TxtFordASN.Focus() - End Sub - Protected Sub LnkFordQuitar_Click(sender As Object, e As EventArgs) Handles LnkFordQuitar.Click - LstFordASN.Items.RemoveAt(LstFordASN.SelectedIndex) - - End Sub - Private Sub LnkImprimir_Click(sender As Object, e As EventArgs) Handles LnkImprimir.Click - GeneraPDFCot(TxtFecha.Text.Trim.ToDate, Nothing, VentaFolio, False, False) - End Sub - Protected Sub TxtCodigo_TextChanged(sender As Object, e As System.EventArgs) Handles TxtCodigo.TextChanged - - Dim ObjClientes As New ClsClientes() - - Dim Nombre As String = "-1" - Dim Codigo As String = "-1" - Dim NombreCorto As String = "-1" - Dim RFC As String = "-1" - Dim Telefono As String = "-1" - Dim Mail As String = "-1" - - If TxtCodigo.Text.Trim <> String.Empty Then Codigo = TxtCodigo.Text.Trim - - If Codigo <> "-1" Then - If ObjClientes.GetClientes(-1, Nombre, Codigo, NombreCorto, RFC, Telefono, Mail, -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then - If ObjClientes.DtResultados.Rows.Count > 0 Then - If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not ObjClientes.CveCliente.Contiene(10450, 10460, 10458) Then - TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False - UpFacturar.Update() - Exit Sub - ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not ObjClientes.CveCliente.Contiene(27448) Then - TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False - UpFacturar.Update() - Exit Sub - Else - HdnCveCliente.Value = ObjClientes.CveCliente.ToString - End If - BtnBuscarCliente_Click(sender, e) - Else - Alert("No se encontró el cliente con el código: " & TxtCodigo.Text.Trim & ".", Extensiones.TipoMensaje.MsgAdvertencia) - TxtCodigo.Text = "" - LblCliente.Text = "Cliente" - LblDireccion.Text = "Dirección" - LblColonia.Text = "Colonia" - LblCiudad.Text = "Ciudad" - LblEstado.Text = "Estado" - LblCP.Text = "00000" - LblRFC.Text = "AAA010101AAA" - LblTelefono.Text = "9999999999" - trsucursalciente.Visible = False - End If - End If - ObjClientes.Dispose() - - End If - End Sub - Protected Sub TxtFolio_TextChanged(sender As Object, e As System.EventArgs) Handles TxtFolio.TextChanged - ViewState("EstablecioFolio") = True - End Sub - Private Sub ConfiguraTipoDocto() - - 'Esconde Todo - TdOrdenPago.Visible = False - Tr33.Visible = False - - 'si tiene la funcionalidad que se active independiente del tipo de documento RMF 15-10-2017 - Tr33.Visible = True - - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then - BtnEmitirImprimir.Text = "Emitir e Imprimir" - 'TdReferencia.Style.Add("display", "none") - ElseIf DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then - BtnEmitirImprimir.Text = "Emitir e Imprimir" - 'TdReferencia.Style.Remove("display") - ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then - BtnEmitirImprimir.Text = "Registrar" - 'TdReferencia.Style.Add("display", "none") - ElseIf DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC", "PA", "Pd2") Then - BtnEmitirImprimir.Text = "Registrar" - 'TdReferencia.Style.Add("display", "none") - ElseIf DdlTipoComprobante.SelectedValue = "Cot" Then - BtnEmitirImprimir.Text = "Cotizar" - 'TdReferencia.Style.Add("display", "none") - - 'FACTURACION 3.3 - Tr33.Visible = True - - ElseIf DdlTipoComprobante.SelectedValue = "Com" Then - BtnEmitirImprimir.Text = "Registrar" - 'TdReferencia.Style.Add("display", "none") - ElseIf DdlTipoComprobante.SelectedValue.ToString = "OP" Then - BtnEmitirImprimir.Text = "Registrar" - TdOrdenPago.Visible = True - End If - - UpFacturar.Update() - - End Sub - Private Sub EliminaPoliza() - Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) - ObjAC.IniciaTransacSQL() - Dim ObjConta As New ClsContabilidad - ObjConta.IniciaTransacSQL() - - Dim ErrorMovimiento = False - - 'Elimina la poliza - If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 Then - If Not ObjAC.RemovePoliza(IdPoliza) Then - ErrorMovimiento = True - End If - End If - - 'Desasocia la poliza - If Not ErrorMovimiento Then - If Not ObjConta.DesasociarPoliza(IdPoliza, UsuarioActual.CveEmpresa) Then - ErrorMovimiento = True - End If - End If - - If Not ErrorMovimiento Then - Alert("La póliza ha sido desvinculada y eliminada con éxito.", TipoMensaje.MsgInformacion) - ObjAC.Commit() - ObjConta.Commit() - BtnDescontabilizar.Visible = False - Else - Alert("Ocurrió un error al desvincular y/o eliminar la póliza. Por favor intente de nuevo ", TipoMensaje.MsgError) - ObjAC.RollBack() - ObjConta.RollBack() - End If - - ObjAC.Dispose() - ObjConta.Dispose() - - End Sub - Protected Sub DdlPS_SelectedIndexChanged1(sender As Object, e As EventArgs) - Dim Ddl As DropDownList = CType(sender, DropDownList) - Dim gvr As GridViewRow = CType(Ddl.BindingContainer, GridViewRow) - gvr.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(Ddl.SelectedValue.ToEntero, -1) - gvr.FCDropDownList("DdlUnidadMedida").DataBind() - - End Sub - Private Function TraspasoAlmacen(ByRef ObjInventario As ClsInventarios, CveRemision As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer) As Boolean +#Region "M E T O D O S" + Private Sub CargaOtrosConceptos() + Dim ObjVentas As New ClsVentas + If ObjVentas.GetVentaOtrosConceptos(UsuarioActual.CveEmpresa, CveVenta) Then + GVOtrosConceptos.DataSource = ObjVentas.DtResultados + GVOtrosConceptos.DataBind() + UpOtrosConceptos.Update() + End If + ObjVentas.Dispose() + End Sub + Private Function GenerarPolizaAC(ObjAC As ClsContPAQi, factura As Modelos.Factura, Optional CancelacionIngreso As Boolean = False) As Integer + Dim Retorno As Integer = 0 + Dim IDPoliza As Integer = 0 + + Dim ErrorAC As Boolean = False + 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + Dim Fecha As Date = factura.Fecha + Dim Concepto As String = String.Format("GD {0}", factura.Cliente.Nombre) + Dim Paridad As Integer = 1 + Dim TipoMovto As Boolean = False + + If CancelacionIngreso Then + Concepto = String.Format("Cancelación GD {0}", factura.Cliente.Nombre) + Paridad = -1 + TipoMovto = True + End If + + Dim TipoPoliza = If(factura.TipoDocto = "OP" Or factura.TipoDocto = "Com", 3, 1) + + IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, factura.Total * 2, factura.Total * 2, factura.CveUsuario, Fecha) + Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue)) + 'Dim Importe As Double = TxtTotal.Text.ToDouble + Dim CtaCliente As Integer = factura.Cliente.IdCtaContClientes + Dim CtaISSSTESON As Integer = 643 + Dim CtaISPT As Integer = 1745 + ' Dim NombreCliente As String = ViewState("NombreCliente").ToString + + If IDPoliza > 0 Then + + 'Orden de PAGO + If factura.TipoDocto = "OP" Then + + If DdlOrdenPago.SelectedValue.ToEntero = 1 Then + 'ISSSTESON + + If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then + If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + + Else + 'ISPT + + If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then + If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + End If + + ' NORMAL + Else + Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)() + Group gvr By Grp = New With { + Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero + } Into Group + Select Grp.CvePresupuestoIngreso, + TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble) + + + 'Select Case TipoComprobante + ' Case "Ing", "Egs" + For Each grp In Detalles + dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso)) + Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString, TxtFolio.Text) + + If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString.ToEntero, False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + 'CARGO la deuda del cliente + If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + 'abono, + If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString.ToEntero, Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + Else + ErrorAC = True + End If + Else + ErrorAC = True + End If + Next + + 'Case "OP", "Com" + ' Dim Importe As Decimal = 0 + ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then + ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then + + ' End If + ' End If + 'End Select + End If + + Else + ErrorAC = True + + End If + + If Not ErrorAC Then + ObjAC.AjustaPoliza(IDPoliza) + + Retorno = IDPoliza + Else + + Alert("Error al agregar la Póliza de AC.", TipoMensaje.MsgError) + End If + + ' ObjAC.Dispose() + + Return Retorno + + End Function + Private Function GenerarPolizaAC(ObjAC As ClsContPAQi, Optional CancelacionIngreso As Boolean = False) As Integer + Dim Retorno As Integer = 0 + Dim IDPoliza As Integer = 0 + + Dim ErrorAC As Boolean = False + 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + Dim Fecha As Date = TxtFecha.Text.ToDate + Dim Concepto As String = String.Format("GD {0}", NombreCliente) + Dim Paridad As Integer = 1 + Dim TipoMovto As Boolean = False + + If CancelacionIngreso Then + Concepto = String.Format("Cancelación GD {0}", NombreCliente) + Paridad = -1 + TipoMovto = True + End If + + Dim TipoPoliza = If(DdlTipoComprobante.SelectedValue.ToString = "OP" Or DdlTipoComprobante.SelectedValue.ToString = "Com", 3, 1) + + IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, TxtTotal.Text.ToDouble * 2, TxtTotal.Text.ToDouble * 2, UsuarioActual.CveUsuario, Fecha) + Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue)) + 'Dim Importe As Double = TxtTotal.Text.ToDouble + Dim CtaCliente As Integer = ViewState("IdCtaContClientes").ToString.ToEntero + Dim CtaISSSTESON As Integer = 643 + Dim CtaISPT As Integer = 1745 + ' Dim NombreCliente As String = ViewState("NombreCliente").ToString + + If IDPoliza > 0 Then + + 'Orden de PAGO + If DdlTipoComprobante.SelectedValue.ToString = "OP" Then + + If DdlOrdenPago.SelectedValue.ToEntero = 1 Then + 'ISSSTESON + + If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then + If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + + Else + 'ISPT + + If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then + If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + End If + + ' NORMAL + Else + Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)() + Group gvr By Grp = New With { + Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero + } Into Group + Select Grp.CvePresupuestoIngreso, + TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble) + + + 'Select Case TipoComprobante + ' Case "Ing", "Egs" + For Each grp In Detalles + dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso)) + Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString, TxtFolio.Text) + + If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString.ToEntero, False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + 'CARGO la deuda del cliente + If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + 'abono, + If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString.ToEntero, Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + Else + ErrorAC = True + End If + Else + ErrorAC = True + End If + Next + + 'Case "OP", "Com" + ' Dim Importe As Decimal = 0 + ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then + ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then + + ' End If + ' End If + 'End Select + End If + + Else + ErrorAC = True + + End If + + If Not ErrorAC Then + ObjAC.AjustaPoliza(IDPoliza) + + Retorno = IDPoliza + Else + + Alert("Error al Agregar la Póliza de AC.", TipoMensaje.MsgError) + End If + + ' ObjAC.Dispose() + + Return Retorno + + End Function + Private Sub SetValues() + ViewState("TipoCambio") = 1 + + If UsuarioActual.Empresa.MostrarRetIVA Then TrRetIVA.Style.Add("display", "") + If UsuarioActual.Empresa.MostrarRetISR Then TrRetISR.Style.Add("display", "") + + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then ' agregar en el modal de PS. que forme el código del producto + TxtPS.Enabled = False + DivDdlTipo.Visible = True + DivTxtModelo.Visible = True + DivTxtAdicional.Visible = True + DdlTipo.Attributes.Add("onChange", "CreaDescripcionPS();") + DdlMarcaPSDes.Attributes.Add("onChange", "CreaDescripcionPS();") + TxtModelo.Attributes.Add("onKeyUp ", "CreaDescripcionPS();") + TxtAdicional.Attributes.Add("onKeyUp ", "CreaDescripcionPS();") + + CargaClasificacionesDetalles() + ClasificacionModal() + + End If + + If Not UsuarioActual.CveEmpresa.Contiene(1, 119) Then 'PAGO CON TERMINAL PARA JAM + RBLPago.Items.RemoveAt(2) + End If + + + End Sub + Private Sub SetPermisos() + If CveVenta < 1 Then + 'Puede cotizar + If Not UsuarioActual.TienePermisoProceso(59) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) + End If + + 'Puede Hacer NC + If Not UsuarioActual.TienePermisoProceso(175) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) + End If + + 'Puede Hacer Devolución + If Not UsuarioActual.TienePermisoProceso(264) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) + End If + + 'Puede facturar + If Not UsuarioActual.TienePermisoProceso(60) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) + End If + + 'Puede remisionar + If Not UsuarioActual.TienePermisoProceso(199) Then + DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) + LnkFacturarRemision.Visible = False + LnkRemisiones.Visible = False + End If + + '[IPP]: FALTA CONFIGURAR Y DAR PERMISO A TODOS LOS QUE TENGAN ACCESO A VENTAS + ''Puede remisionar + 'If Not UsuarioActual.TienePermisoProceso(199) Then + ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) + 'End If + + ''MODO SOLO LECTURA + 'If DdlTipoComprobante.Items.Count = 0 Then + ' DdlTipoComprobante.Items.Insert(0, New ListItem("Solo lectura", "-1")) + ' TrBotones.Visible = False + 'End If + + ConfiguraTipoDocto() + End If + End Sub + Private Sub CalculaTotalesVenta(Optional RecalculaImpuestosLocales As Boolean = True) + + Dim TotalSubTotal As Decimal = TmpDT.SUM("TotalImporte").ToDecimal + Dim TotalDescuentos As Decimal = TmpDT.SUM("Descuento").ToDecimal + Dim TotalAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal + Dim TotalIVA As Decimal = TmpDT.SUM("ImporteIVA").ToDecimal + Dim TotalIEPS As Decimal = TmpDT.SUM("ImporteIEPS").ToDecimal + Dim TotalRetIVA As Decimal = TmpDT.SUM("ImporteRetIVA").ToDecimal + Dim TotalRetISR As Decimal = TmpDT.SUM("ImporteRetISR").ToDecimal + Dim Total As Decimal = 0 + Dim TotalImpuestosLocales As Decimal = 0 + + If TotalAmortizacion > 0 AndAlso TotalSubTotal = TotalAmortizacion Then ' si se amortizó completa la factura, debe de limpiar los impuestos + If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("3") Then + For Each dr As DataRow In TmpDT.Rows + dr("ImporteIVA") = 0 : dr("ImporteIEPS") = 0 : dr("ImporteRetIVA") = 0 : dr("ImporteRetISR") = 0 : dr("PorcentajeIVA") = 0 : dr("IVA") = 0 + Next + + If TmpDTImpuestos IsNot Nothing Then + For Each dr2 As DataRow In TmpDTImpuestos.Rows + dr2("Importe") = 0 + Next + TmpDTImpuestos.AcceptChanges() + End If + + TmpDT.AcceptChanges() + TotalIVA = TmpDT.SUM("ImporteIVA").ToDecimal + TotalIEPS = TmpDT.SUM("ImporteIEPS").ToDecimal + TotalRetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal + TotalRetISR = TmpDT.SUM("ImporteRetISR").ToDecimal + TotalImpuestosLocales = TmpDTImpuestos.SUM("Importe").ToDecimal + End If + End If + + If RecalculaImpuestosLocales AndAlso TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then + If TotalSubTotal <> TotalAmortizacion Then + For Each drt As DataRow In TmpDTImpuestos.Rows + drt("Importe") = drt("Porcentaje").ToString.ToDecimal * TotalSubTotal / 100 + Next + End If + + GvImpuestosLocales2.DataSource = TmpDTImpuestos + GvImpuestosLocales2.DataBind() + End If + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + + If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal > 0 Then + If gvr.DataKey("TipoImpuesto") = "5" Then ' traslado de imp local + TotalImpuestosLocales -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal + Else + TotalImpuestosLocales += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal + End If + End If + End If + Next + + 'If TotalDescuentos > 0 Then GvPS.Columns(ColumnaDescuento).Visible = True : thEncDesc1.Visible = True : thEncDesc2.Visible = True Else GvPS.Columns(ColumnaDescuento).Visible = False : thEncDesc1.Visible = False : thEncDesc2.Visible = False + If TotalIEPS > 0 Then TrIEPS.Visible = True : GvPS.Columns(ColumnaIEPS).Visible = True : thEncIEPS1.Visible = True : thEncIEPS2.Visible = True Else TrIEPS.Visible = False : GvPS.Columns(ColumnaIEPS).Visible = False : thEncIEPS1.Visible = False : thEncIEPS2.Visible = False + If TotalRetIVA > 0 Then GvPS.Columns(ColumnaRetIVA).Visible = True Else GvPS.Columns(ColumnaRetIVA).Visible = False + If TotalRetISR > 0 Then GvPS.Columns(ColumnaRetISR).Visible = True Else GvPS.Columns(ColumnaRetISR).Visible = False + + If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero.Contiene(2, 1) Then + TotalAmortizacion = 0 + End If + + + Total = (TotalSubTotal - TotalDescuentos - TotalAmortizacion + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) + LblSubTotal1.Text = TotalSubTotal.FormatoNumero(2) + TxtSubTotal.Text = TotalSubTotal.FormatoNumero(2) + LblDescuentos.Text = TotalDescuentos.FormatoNumero + TxtSubTotal2.Text = (TotalSubTotal - TotalDescuentos - TotalAmortizacion).FormatoNumero(2) + TxtRetIVA.Text = TotalRetIVA.FormatoNumero(2) + TxtRetISR.Text = TotalRetISR.FormatoNumero(2) + TxtIVA.Text = TotalIVA.FormatoNumero + TxtIEPS.Text = TotalIEPS.FormatoNumero + TxtTotal.Text = Total.FormatoNumero + + LblAmort.Text = TxtSubTotal.Text + If CveVenta <= 0 OrElse (CveDevolucion > 0 And NuevaFactura = 1) Then + HdnVentaSaldo.Value = Total.ToString + Else + HdnVentaSaldo.Value = SaldoVenta.ToString + End If + HdnIVAOriginal.Value = TxtIVA.Text + + 'JJMQ 20160506: Se agrego para la validacion de pago de contado. + CVImporteContado.ValueToCompare = Total.ToString + + If MensajeCveSAT IsNot Nothing AndAlso MensajeCveSAT.ToString.Length > 0 Then + Alert($"Los siguientes conceptos hace falta especificar clave SAT

    {MensajeCveSAT.ToString}", TipoMensaje.MsgAdvertencia) + MensajeCveSAT.Clear() + End If + + Dim view As DataView = New DataView(TmpDT) + view.Sort = "Consec" + GvPS.DataSource = view + GvPS.DataBind() + + 'RECARGA GV INVENTARIO + If Not CveVenta > 0 Then + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + CargaGVInv(DtInv) + End If + + UpContado.Update() + UpPS.Update() + RegistraScript("BorraDescuentos();", "BorraDescuentos") + End Sub + Private Function ValidaAdendaFEMSA() As Boolean + Dim Retorno As Boolean = False + + If Not AplicaFEMSA Then + Retorno = True + Else + If TxtFEMSA_Version.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_Version.Text.Trim) Then + Retorno = False + Alert("La versión de la Adenda es requerida y debe ser numérica. Por favor corrija.", TipoMensaje.MsgAdvertencia) + ElseIf TxtFEMSA_NumSociedad.Text.Trim.Length = 0 Then + Retorno = False + Alert("El número de Sociedad para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) + ElseIf TxtFEMSA_NumProveedor.Text.Trim.Length = 0 Then + Retorno = False + Alert("El número de Proveedor para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) + ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumPedido.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumPedido.Text.Trim)) Then + Retorno = False + Alert("El número de Pedido para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) + ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumEntrada.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumEntrada.Text.Trim)) Then + Retorno = False + Alert("El número de Entrada para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) + ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso TxtFEMSA_NumRemision.Text.Trim.Length = 0 Then + Retorno = False + Alert("El número de Remisión para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) + ElseIf TxtFEMSA_Mail.Text.Trim.Length = 0 Then + Retorno = False + Alert("El Mail para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) + Else + Retorno = True + End If + End If + + Return Retorno + End Function + Private Function ValidaComplementoDetallista() As Boolean + Dim Retorno As Boolean = False + + If Not AplicaDetallista Then + Retorno = True + Else + If TxtDet_OrdenCompra.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_OrdenCompra.Text.Trim) Then + Retorno = False + Alert("El campo Orden de Compra es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia, "") + ElseIf TxtDet_FechaOrdenCompra.Text.Trim.Length = 0 OrElse Not IsDate(TxtDet_FechaOrdenCompra.Text.Trim) Then + Retorno = False + Alert("El campo Fecha de Orden de Compra es requerido y debe de contar con un formato válido de fecha. Por favor corrija.", TipoMensaje.MsgAdvertencia) + ElseIf TxtDet_GLNComprador.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNComprador.Text.Trim) Then + Retorno = False + Alert("El campo GLN-Comprador es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) + ElseIf TxtDet_Departamento.Text.Trim.Length = 0 Then + Retorno = False + Alert("El campo Departamento es requerido. Por favor ingrese uno.", TipoMensaje.MsgAdvertencia) + ElseIf TxtDet_GLNVendedor.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNVendedor.Text.Trim) Then + Retorno = False + Alert("El campo GLN-Vendedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) + ElseIf TxtDet_NumProv.Text.Trim.Length = 0 Then + Retorno = False + Alert("El campo Número de Proveedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) + Else + Retorno = True + End If + End If + + Return Retorno + End Function + Private Function ValidaComplementoFord() As Boolean + Dim Retorno As Boolean = False + + If Not AplicaFord Then + Retorno = True + Else + If TxtFordGSDB.Text.Trim.Length = 0 Then + Retorno = False + Alert("El campo GSDB es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia) + Else + If LstFordASN.Items.Count = 0 Then + Retorno = True + 'Alert("El campo ASN es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia) + Else + Retorno = True + End If + + End If + End If + + Return Retorno + End Function + Private Sub VinculaCotizacionVenta() + Dim ObjVentas As New ClsVentas() + ObjVentas.UpdateVentaCotizacion(CveVenta, Request("CveVenta").ToEntero) + ObjVentas.Dispose() + End Sub + Private Sub GeneraAddenda7Eleven(Archivo As String) + Dim cfdi As String = "" + Dim SB As New StringBuilder + Try + Using sr As New StreamReader(Archivo) + + cfdi = sr.ReadToEnd() + + End Using + Catch e As Exception + Alert("The file could not be read:", TipoMensaje.MsgError) + + End Try + + + cfdi = cfdi.Replace("", "") + + SB.Append(cfdi) + + SB.Append("") + SB.AppendFormat("", Txt7ElevenNumProveedor.Text.Trim) + SB.AppendFormat("", Txt7ElevenFolio.Text.Trim, Txt7ElevenTienda.Text.Trim, Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-MM-dd")) + + For Each Row As DataRow In TmpDT.Rows + + SB.AppendFormat("", Row("Codigo"), Row("PS"), Row("Cantidad").ToString.ToDouble.FormatoNumero(), Row("PU").ToString.ToDouble.FormatoNumero()) + + Next + + SB.Append("") + + + Using outfile As New StreamWriter(Archivo) + outfile.Write(SB.ToString()) + End Using + + 'Exit Sub + + + + 'Dim MyXmlDocument As New XmlDocument() + + 'MyXmlDocument.Load("C:/Temp/aaa.xml") + 'Dim nsmgr = New XmlNamespaceManager(MyXmlDocument.NameTable) + 'nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3") + 'Dim ParentElement As XmlElement = MyXmlDocument.CreateElement("cfdi:Addenda", "https://edixcfisecure.ekomercio.com/esquemas") + 'ParentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") + 'ParentElement.SetAttribute("xsi:schemaLocation", "https://edixcfisecure.ekomercio.com/esquemas https:/edixcfdisecure.ekomercio.com/esquemas/7Eleven.xsd") + + 'Dim Prov As XmlElement = MyXmlDocument.CreateElement("cfdi:Proveedor", "") + 'Prov.SetAttribute("Clave", "3125") + + 'Dim ns As String = "cfdi" 'MyXmlDocument.DocumentElement.GetNamespaceOfPrefix("cfdi") + 'Dim Recepciones As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepciones") + 'Recepciones.Prefix = "cfdi" + 'Dim Recepcion As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepcion") + 'Recepcion.SetAttribute("folio", Txt7ElevenFolio.Text.Trim) + 'Recepcion.SetAttribute("tienda", Txt7ElevenTienda.Text.Trim) + 'Recepcion.SetAttribute("fecha", Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-dd-MM")) + + 'Dim Productos As XmlElement = MyXmlDocument.CreateElement("cfdi:Productos") + ''dentro de un ciclo + 'Dim Producto As XmlElement = MyXmlDocument.CreateElement("cfdi:Producto") + 'Producto.SetAttribute("codigo", "cod1") + 'Producto.SetAttribute("descripcion", "prod1") + 'Producto.SetAttribute("cantidad", "99") + 'Producto.SetAttribute("precio", "2000") + 'Productos.AppendChild(Producto) + ''fin de ciclo + + 'Recepcion.AppendChild(Productos) + + 'Recepciones.AppendChild(Recepcion) + + 'ParentElement.AppendChild(Prov) + + 'ParentElement.AppendChild(Recepciones) + + + 'MyXmlDocument.DocumentElement.AppendChild(ParentElement) + 'MyXmlDocument.Save("C:/Temp/aa.xml") + + End Sub + Protected Sub DdlFuenteRecaudacion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFuenteRecaudacion.SelectedIndexChanged + For Each dr As DataRow In TmpDT.Rows + dr("CvePresupuestoIngreso") = DdlFuenteRecaudacion.SelectedValue + Next + + GvPS.DataSource = TmpDT + GvPS.DataBind() + + UpPS.Update() + End Sub + Protected Sub DdlFR_SelectedIndexChanged(sender As Object, e As EventArgs) + Dim DdlFR_Gv As DropDownList = CType(sender, DropDownList) + Dim index As Integer = CType(DdlFR_Gv.NamingContainer, GridViewRow).FCLiteral("LtlConsecutivo").Text.ToString.ToEntero + + If UsuarioActual.Empresa.UsaAC Then + TmpDT(index - 1)("CvePresupuestoIngreso") = DdlFR_Gv.SelectedValue + End If + TmpDT.AcceptChanges() + End Sub + Protected Sub LnkASN_Click(sender As Object, e As EventArgs) Handles LnkASN.Click + If TxtFordASN.Text.Trim.Length > 20 Then Alert("Maximo 20 Caracteres", TipoMensaje.MsgAdvertencia) : Exit Sub + LstFordASN.Items.Add(New ListItem(TxtFordASN.Text.Trim)) + TxtFordASN.Text = "" + TxtFordASN.Focus() + End Sub + Protected Sub LnkFordQuitar_Click(sender As Object, e As EventArgs) Handles LnkFordQuitar.Click + LstFordASN.Items.RemoveAt(LstFordASN.SelectedIndex) + + End Sub + Private Sub LnkImprimir_Click(sender As Object, e As EventArgs) Handles LnkImprimir.Click + GeneraPDFCot(TxtFecha.Text.Trim.ToDate, Nothing, VentaFolio, False, False) + End Sub + Protected Sub TxtCodigo_TextChanged(sender As Object, e As System.EventArgs) Handles TxtCodigo.TextChanged + + Dim ObjClientes As New ClsClientes() + + Dim Nombre As String = "-1" + Dim Codigo As String = "-1" + Dim NombreCorto As String = "-1" + Dim RFC As String = "-1" + Dim Telefono As String = "-1" + Dim Mail As String = "-1" + + If TxtCodigo.Text.Trim <> String.Empty Then Codigo = TxtCodigo.Text.Trim + + If Codigo <> "-1" Then + If ObjClientes.GetClientes(-1, Nombre, Codigo, NombreCorto, RFC, Telefono, Mail, -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then + If ObjClientes.DtResultados.Rows.Count > 0 Then + If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not ObjClientes.CveCliente.Contiene(10450, 10460, 10458) Then + TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False + UpFacturar.Update() + Exit Sub + ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not ObjClientes.CveCliente.Contiene(27448) Then + TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False + UpFacturar.Update() + Exit Sub + Else + HdnCveCliente.Value = ObjClientes.CveCliente.ToString + End If + BtnBuscarCliente_Click(sender, e) + Else + Alert("No se encontró el cliente con el código: " & TxtCodigo.Text.Trim & ".", Extensiones.TipoMensaje.MsgAdvertencia) + TxtCodigo.Text = "" + LblCliente.Text = "Cliente" + LblDireccion.Text = "Dirección" + LblColonia.Text = "Colonia" + LblCiudad.Text = "Ciudad" + LblEstado.Text = "Estado" + LblCP.Text = "00000" + LblRFC.Text = "AAA010101AAA" + LblTelefono.Text = "9999999999" + trsucursalciente.Visible = False + End If + End If + ObjClientes.Dispose() + + End If + End Sub + Protected Sub TxtFolio_TextChanged(sender As Object, e As System.EventArgs) Handles TxtFolio.TextChanged + ViewState("EstablecioFolio") = True + End Sub + Private Sub ConfiguraTipoDocto() + + 'Esconde Todo + TdOrdenPago.Visible = False + Tr33.Visible = False + + 'si tiene la funcionalidad que se active independiente del tipo de documento RMF 15-10-2017 + Tr33.Visible = True + + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then + BtnEmitirImprimir.Text = "Emitir e Imprimir" + 'TdReferencia.Style.Add("display", "none") + ElseIf DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then + BtnEmitirImprimir.Text = "Emitir e Imprimir" + 'TdReferencia.Style.Remove("display") + ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then + BtnEmitirImprimir.Text = "Registrar" + 'TdReferencia.Style.Add("display", "none") + ElseIf DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC", "PA", "Pd2") Then + BtnEmitirImprimir.Text = "Registrar" + 'TdReferencia.Style.Add("display", "none") + ElseIf DdlTipoComprobante.SelectedValue = "Cot" Then + BtnEmitirImprimir.Text = "Cotizar" + 'TdReferencia.Style.Add("display", "none") + + 'FACTURACION 3.3 + Tr33.Visible = True + + ElseIf DdlTipoComprobante.SelectedValue = "Com" Then + BtnEmitirImprimir.Text = "Registrar" + 'TdReferencia.Style.Add("display", "none") + ElseIf DdlTipoComprobante.SelectedValue.ToString = "OP" Then + BtnEmitirImprimir.Text = "Registrar" + TdOrdenPago.Visible = True + End If + + UpFacturar.Update() + + End Sub + Private Sub EliminaPoliza() + Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) + ObjAC.IniciaTransacSQL() + Dim ObjConta As New ClsContabilidad + ObjConta.IniciaTransacSQL() + + Dim ErrorMovimiento = False + + 'Elimina la poliza + If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 Then + If Not ObjAC.RemovePoliza(IdPoliza) Then + ErrorMovimiento = True + End If + End If + + 'Desasocia la poliza + If Not ErrorMovimiento Then + If Not ObjConta.DesasociarPoliza(IdPoliza, UsuarioActual.CveEmpresa) Then + ErrorMovimiento = True + End If + End If + + If Not ErrorMovimiento Then + Alert("La póliza ha sido desvinculada y eliminada con éxito.", TipoMensaje.MsgInformacion) + ObjAC.Commit() + ObjConta.Commit() + BtnDescontabilizar.Visible = False + Else + Alert("Ocurrió un error al desvincular y/o eliminar la póliza. Por favor intente de nuevo ", TipoMensaje.MsgError) + ObjAC.RollBack() + ObjConta.RollBack() + End If + + ObjAC.Dispose() + ObjConta.Dispose() + + End Sub + Protected Sub DdlPS_SelectedIndexChanged1(sender As Object, e As EventArgs) + Dim Ddl As DropDownList = CType(sender, DropDownList) + Dim gvr As GridViewRow = CType(Ddl.BindingContainer, GridViewRow) + gvr.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(Ddl.SelectedValue.ToEntero, -1) + gvr.FCDropDownList("DdlUnidadMedida").DataBind() + + End Sub + Private Function TraspasoAlmacen(ByRef ObjInventario As ClsInventarios, CveRemision As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer) As Boolean Dim OcurrioError As Boolean = False Try Dim DtMovimientos As DataTable @@ -14740,939 +14747,939 @@ Partial Class Ventas OcurrioError = True OnError("Ocurrió un error al realizar el traspaso", ex) End Try - Return Not OcurrioError - End Function - Private Function CuadrarFacturaMovimientos(MovDetalle As DataTable) As DataTable - Dim MovDTCuadrados As New DataTable - MovDTCuadrados = MovDetalle.Clone - MovDTCuadrados.Clear() - - 'Llenamos el DT solo si es primera llamada - If DtRemConceptosSurtidos Is Nothing Then - DtRemConceptosSurtidos = New DataTable - DtRemConceptosSurtidos.Columns.Add("CveVentaDetalle", GetType(Integer)) - DtRemConceptosSurtidos.Columns.Add("Cantidad", GetType(Decimal)) - DtRemConceptosSurtidos.Columns.Add("Surtido", GetType(Decimal)) - - For Each dr As DataRow In DtRemisionesTmpDT.Rows - Dim dtr As DataRow = DtRemConceptosSurtidos.NewRow - dtr("CveVentaDetalle") = dr("CveVentaDetalle") - dtr("Cantidad") = dr("Cantidad") - dtr("Surtido") = 0 - DtRemConceptosSurtidos.Rows.Add(dtr) - Next - End If - - For Each dr As DataRow In MovDetalle.Rows - Dim rowSurtidos As DataRow = DtRemConceptosSurtidos.FiltroPrimero($"CveVentaDetalle={dr("CveVentaDetalle")}") - Dim rowSurtidosP As DataRow = DtRemConceptosSurtidos.Select($"CveVentaDetalle={dr("CveVentaDetalle")}").FirstOrDefault - Dim Indice As Integer = DtRemConceptosSurtidos.Rows.IndexOf(rowSurtidosP) - - 'Si no se ha terminado de surtir agregamos el movimiento - If Indice >= 0 Then - ' rowSurtidos("Surtido").ToString.ToDouble < rowSurtidos("Cantidad").ToString.ToDouble AndAlso (dr("CantidadDisponible").ToString.ToDouble - rowSurtidos("Surtido").ToString.ToDouble > 0 Or dr("SerieLote").ToString <> "") - If rowSurtidos("Surtido").ToString.ToDecimal < rowSurtidos("Cantidad").ToString.ToDecimal Then - Dim CantidadSurtida As Double = If(dr("CantidadDisponible").ToString.ToDecimal < rowSurtidos("Cantidad").ToString.ToDouble, dr("CantidadDisponible").ToString.ToDecimal, rowSurtidos("Cantidad").ToString.ToDecimal) - MovDTCuadrados.ImportRow(dr) - MovDTCuadrados(MovDTCuadrados.Rows.Count - 1)("Cantidad") = CantidadSurtida - DtRemConceptosSurtidos(Indice)("Surtido") = rowSurtidos("Surtido").ToString.ToDecimal + CantidadSurtida - End If - Else - ErrorList.Add("Ocurrió un error al traspasar el inventario de la remisión") - Exit For - End If - Next - - Return MovDTCuadrados - End Function - Private Function SalidaEntradaAlmacen(ByRef ObjInventario As ClsInventarios, CveRemision As Integer, ByRef ObjConta As ClsContabilidad) As Boolean - Dim OcurrioError As Boolean = False - Dim DtMovimientos As DataTable - Dim DtMovimientosDetalles As DataTable - - 'Obtenemos los movimientos detalle - If ObjInventario.GetInv_Mov(CveRemision, UsuarioActual.CveEmpresa) Then - - If ObjInventario.DtResultados.Rows.Count > 0 Then - - DtMovimientos = ObjInventario.DtResultados.FiltraParametros("", DistinctColumns:={"CveMovimiento"}) - DtMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0") - - For Each dr As DataRow In DtMovimientos.Rows - - 'Obtenemos los Movimientos de salida - If ObjInventario.GetMovimientos(dr("CveMovimiento").ToString.ToEntero, 3, -1, UsuarioActual.CveEmpresa) Then - - Dim CveAlmacenSalida As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero - Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero - - 'Le damos entrada - If Not GenerarMovimientoAlmacen(ObjInventario, DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}"), CveAlmacenSalida, 2, CveMoneda, CveRemision) > 0 Then - OcurrioError = True - End If - - End If - Next - - End If - - End If - - Return Not OcurrioError - End Function - Private Function GenerarMovimientoAlmacen(ByRef ObjInventario As ClsInventarios, DtMovDetalle As DataTable, CveAlmacen As Integer, ConceptoEntrada As Integer, CveMoneda As Integer, CveVenta As Integer, Optional MovimientoPrePoliza As Boolean = False, Optional ByRef ObjConta As ClsContabilidad = Nothing, Optional CveMovimientoRelacionado As Integer = -1) As Integer - Dim OcurrioError As Boolean = False - Dim ContadorMovtosDetalles = 0 - - 'Creamos el movimiento - Dim CveMovimientoInventario As Integer = ObjInventario.AddMovimiento(CveAlmacen, ConceptoEntrada, CveMoneda, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, CveMovimientoRelacionado:=CveMovimientoRelacionado) - - If CveMovimientoInventario > 0 Then - - 'Agregamos los detalles - For Each MovDet As DataRow In DtMovDetalle.Rows - - Dim Cantidad = 0.0 - Dim CantidadRemision = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={MovDet("CveVentaDetalle").ToString}").ToDouble - Dim CantidadInventario = MovDet("Cantidad").ToString.ToDecimal - - If RemisionesLista.Count > 0 AndAlso ChkRemProductos.Checked AndAlso CantidadInventario >= CantidadRemision Then - Cantidad = CantidadRemision - Else - Cantidad = CantidadInventario - End If - - Dim CveUnidad As Integer = MovDet("CveUM").ToString.ToEntero - Dim PU As Decimal = MovDet("PU").ToString.ToDecimal - Dim CveProducto As Integer = MovDet("CvePS").ToString.ToEntero - Dim SerieLote As String = MovDet("SerieLote").ToString - Dim Consec As Integer = DtRemisionesTmpDT.FiltroPrimeroValor("Consec", $"CveVentaDetalle = {MovDet("CveVentaDetalle").ToString}").ToEntero - - 'COMIENZA: VENTADETALLE - 'CUANDO SEA SALIDA VA POR LA VENTA DETALLE DE LA FACTURA DE LA REMISION - OJO!! SOLO FUNCIONA HASTA ORITA QUE SE HACE SALIDA SOLO CUANDO SE FACTURA LA REMISION - Dim CveVentaDetalle = If(ConceptoEntrada = 3, TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"Consec={Consec}").ToEntero, MovDet("CveVentaDetalle").ToString.ToEntero) - 'CUANDO LA VENTADETALLE NO TENGA VALOR DEBE MARCAR ERROR, NUEVA RESTRICCION DE ALMACEN - If CveVentaDetalle < 0 Then - OcurrioError = True - Exit For - End If - 'TERMINA: VENTADETALLE - - If Cantidad < 0 Then - Alert("Ocurrió un Error al generar los movimientos de almacén. Por favor comuniquese con atención SIG.", TipoMensaje.MsgError) - OcurrioError = True - Exit For - End If - - If ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then - ContadorMovtosDetalles += 1 - Else - OcurrioError = True - Exit For - End If - Next - - 'Agregamos las PrePolizas - If Not OcurrioError Then - If MovimientoPrePoliza AndAlso CveMovimientoInventario > 0 Then - If ObjInventario.GetMovimientosDetalle(CveMovimientoInventario, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then - Dim DtCostos = ObjInventario.DtResultados.Copy - Dim DtCostosDistinct As DataTable = ObjInventario.DtResultados.FiltraParametros("", "", {"CveClasificacion"}) - Dim IdCtaContable As Integer = 0 - Dim CveCuenta As Integer = 0 - Dim ValorInventario As Decimal - Dim TotalCostoAcumulado As Decimal = 0D - Dim Cont As Integer = 1 - Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL - - For Each RowInv As DataRow In DtCostosDistinct.Rows - ValorInventario = DtCostos.SUMD("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).RoundSQL - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - TotalCostoAcumulado += ValorInventario - - 'cuando es el último movimiento y hay diferencias en los importes - If Cont = DtCostosDistinct.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then - ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) - End If - - Try - If ValorInventario <> 0 Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then - OcurrioError = True - Exit For - End If - End If - Catch ex As Exception - OcurrioError = True - End Try - Cont += 1 - Next - - If Not OcurrioError Then - IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacen)).ToEntero - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, TotalCosto, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=TotalCosto, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then - OcurrioError = True - End If - End If - Else - OcurrioError = True - End If - End If - End If - - - 'VALIDA QUE SE HALLAN AGREGADO DETALLES AL MOVIMIENTO - If ContadorMovtosDetalles = 0 Then - OcurrioError = True - End If - - Else - OcurrioError = True - End If - - - - If OcurrioError Then - Return -1 - Else - Return CveMovimientoInventario - End If - 'Return Not OcurrioError - - End Function - Private Function SalidaAlmacenMateriales(ByRef ObjInventario As ClsInventarios, CveOS As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer) As Boolean - Dim TieneError As Boolean = False - Dim CveMovimientoSalida = 0 - Dim CveMovimientoEntrada = 0 - - Dim CveMovimientoSalida2 = 0 - Dim CveMovimientoEntrada2 = 0 - - Dim CveMovimientoSalida3 = 0 - Dim CveMovimientoEntrada3 = 0 - - Dim AlmacenEntrada = -1 - Dim FolioSalida = 0 - Dim FolioEntrada = 0 - - Dim TextoError = "" - Dim TextoExistencia As StringBuilder = New StringBuilder - - 'Obtenemos los movimientos detalle - If ObjInventario.GetMovimientosOS(9, CveOS, UsuarioActual.CveEmpresa) Then - If ObjInventario.DtResultados.Rows.Count > 0 Then - Dim CveMovimiento As Integer = ObjInventario.DtResultados(0)("CveMovimiento").ToString.ToEntero - Dim CveAlmacenOrigen As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero - Dim CveAlmacenDestino As Integer = ObjInventario.DtResultados(0)("AlmacenDestino2").ToString.ToEntero - Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero - Dim CveTipoAlmacen As Integer = ObjInventario.DtResultados(0)("CveTipoAlmacen").ToString.ToEntero - - 'AGREGAMOS LA ENTRADA Movto 1 - If Not TieneError Then - AlmacenEntrada = CveAlmacenOrigen - - CveMovimientoEntrada = ObjInventario.AddMovimiento(AlmacenEntrada, 8, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida, CveOS:=CveOS) - FolioEntrada = ObjInventario.Folio - - If CveMovimientoEntrada <= 0 Then - TextoError = "No se pudo generar el movimiento de entrada correctamente" - TieneError = True - Else - - If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then - - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then - TieneError = True - TextoError = "Ocurrió un Error al guardar los movimientos de entrada" - Exit For - End If - Next - - End If - - End If - End If - - 'AGREGAMOS LA ENTRADA Movto 2 - If Not TieneError Then - AlmacenEntrada = CveAlmacenDestino - - CveMovimientoEntrada2 = ObjInventario.AddMovimiento(AlmacenEntrada, 9, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida2, CveOS:=CveOS) - FolioEntrada = ObjInventario.Folio - - If CveMovimientoEntrada2 <= 0 Then - TextoError = "No se pudo generar el movimiento de entrada correctamente" - TieneError = True - Else - - If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada, UsuarioActual.CveEmpresa) Then - - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada2, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then - TieneError = True - TextoError = "Ocurrió un Error al guardar los movimientos de entrada" - Exit For - End If - Next - - End If - - End If - End If - - 'AGREGAMOS LA ENTRADA Movto 3 - If Not TieneError Then - AlmacenEntrada = CveAlmacenDestino - - CveMovimientoEntrada3 = ObjInventario.AddMovimiento(AlmacenEntrada, 3, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida3, CveOS:=CveOS) - FolioEntrada = ObjInventario.Folio - - If CveMovimientoEntrada3 <= 0 Then - TextoError = "No se pudo generar el movimiento de entrada correctamente" - TieneError = True - Else - - If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada2, UsuarioActual.CveEmpresa) Then - - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada3, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then - TieneError = True - TextoError = "Ocurrió un Error al guardar los movimientos de entrada" - Exit For - End If - Next - - End If - - End If - End If - - End If - End If - - Return TieneError + Return Not OcurrioError + End Function + Private Function CuadrarFacturaMovimientos(MovDetalle As DataTable) As DataTable + Dim MovDTCuadrados As New DataTable + MovDTCuadrados = MovDetalle.Clone + MovDTCuadrados.Clear() + + 'Llenamos el DT solo si es primera llamada + If DtRemConceptosSurtidos Is Nothing Then + DtRemConceptosSurtidos = New DataTable + DtRemConceptosSurtidos.Columns.Add("CveVentaDetalle", GetType(Integer)) + DtRemConceptosSurtidos.Columns.Add("Cantidad", GetType(Decimal)) + DtRemConceptosSurtidos.Columns.Add("Surtido", GetType(Decimal)) + + For Each dr As DataRow In DtRemisionesTmpDT.Rows + Dim dtr As DataRow = DtRemConceptosSurtidos.NewRow + dtr("CveVentaDetalle") = dr("CveVentaDetalle") + dtr("Cantidad") = dr("Cantidad") + dtr("Surtido") = 0 + DtRemConceptosSurtidos.Rows.Add(dtr) + Next + End If + + For Each dr As DataRow In MovDetalle.Rows + Dim rowSurtidos As DataRow = DtRemConceptosSurtidos.FiltroPrimero($"CveVentaDetalle={dr("CveVentaDetalle")}") + Dim rowSurtidosP As DataRow = DtRemConceptosSurtidos.Select($"CveVentaDetalle={dr("CveVentaDetalle")}").FirstOrDefault + Dim Indice As Integer = DtRemConceptosSurtidos.Rows.IndexOf(rowSurtidosP) + + 'Si no se ha terminado de surtir agregamos el movimiento + If Indice >= 0 Then + ' rowSurtidos("Surtido").ToString.ToDouble < rowSurtidos("Cantidad").ToString.ToDouble AndAlso (dr("CantidadDisponible").ToString.ToDouble - rowSurtidos("Surtido").ToString.ToDouble > 0 Or dr("SerieLote").ToString <> "") + If rowSurtidos("Surtido").ToString.ToDecimal < rowSurtidos("Cantidad").ToString.ToDecimal Then + Dim CantidadSurtida As Double = If(dr("CantidadDisponible").ToString.ToDecimal < rowSurtidos("Cantidad").ToString.ToDouble, dr("CantidadDisponible").ToString.ToDecimal, rowSurtidos("Cantidad").ToString.ToDecimal) + MovDTCuadrados.ImportRow(dr) + MovDTCuadrados(MovDTCuadrados.Rows.Count - 1)("Cantidad") = CantidadSurtida + DtRemConceptosSurtidos(Indice)("Surtido") = rowSurtidos("Surtido").ToString.ToDecimal + CantidadSurtida + End If + Else + ErrorList.Add("Ocurrió un error al traspasar el inventario de la remisión") + Exit For + End If + Next + + Return MovDTCuadrados + End Function + Private Function SalidaEntradaAlmacen(ByRef ObjInventario As ClsInventarios, CveRemision As Integer, ByRef ObjConta As ClsContabilidad) As Boolean + Dim OcurrioError As Boolean = False + Dim DtMovimientos As DataTable + Dim DtMovimientosDetalles As DataTable + + 'Obtenemos los movimientos detalle + If ObjInventario.GetInv_Mov(CveRemision, UsuarioActual.CveEmpresa) Then + + If ObjInventario.DtResultados.Rows.Count > 0 Then + + DtMovimientos = ObjInventario.DtResultados.FiltraParametros("", DistinctColumns:={"CveMovimiento"}) + DtMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0") + + For Each dr As DataRow In DtMovimientos.Rows + + 'Obtenemos los Movimientos de salida + If ObjInventario.GetMovimientos(dr("CveMovimiento").ToString.ToEntero, 3, -1, UsuarioActual.CveEmpresa) Then + + Dim CveAlmacenSalida As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero + Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero + + 'Le damos entrada + If Not GenerarMovimientoAlmacen(ObjInventario, DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}"), CveAlmacenSalida, 2, CveMoneda, CveRemision) > 0 Then + OcurrioError = True + End If + + End If + Next + + End If + + End If + + Return Not OcurrioError + End Function + Private Function GenerarMovimientoAlmacen(ByRef ObjInventario As ClsInventarios, DtMovDetalle As DataTable, CveAlmacen As Integer, ConceptoEntrada As Integer, CveMoneda As Integer, CveVenta As Integer, Optional MovimientoPrePoliza As Boolean = False, Optional ByRef ObjConta As ClsContabilidad = Nothing, Optional CveMovimientoRelacionado As Integer = -1) As Integer + Dim OcurrioError As Boolean = False + Dim ContadorMovtosDetalles = 0 + + 'Creamos el movimiento + Dim CveMovimientoInventario As Integer = ObjInventario.AddMovimiento(CveAlmacen, ConceptoEntrada, CveMoneda, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, CveMovimientoRelacionado:=CveMovimientoRelacionado) + + If CveMovimientoInventario > 0 Then + + 'Agregamos los detalles + For Each MovDet As DataRow In DtMovDetalle.Rows + + Dim Cantidad = 0.0 + Dim CantidadRemision = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={MovDet("CveVentaDetalle").ToString}").ToDouble + Dim CantidadInventario = MovDet("Cantidad").ToString.ToDecimal + + If RemisionesLista.Count > 0 AndAlso ChkRemProductos.Checked AndAlso CantidadInventario >= CantidadRemision Then + Cantidad = CantidadRemision + Else + Cantidad = CantidadInventario + End If + + Dim CveUnidad As Integer = MovDet("CveUM").ToString.ToEntero + Dim PU As Decimal = MovDet("PU").ToString.ToDecimal + Dim CveProducto As Integer = MovDet("CvePS").ToString.ToEntero + Dim SerieLote As String = MovDet("SerieLote").ToString + Dim Consec As Integer = DtRemisionesTmpDT.FiltroPrimeroValor("Consec", $"CveVentaDetalle = {MovDet("CveVentaDetalle").ToString}").ToEntero + + 'COMIENZA: VENTADETALLE + 'CUANDO SEA SALIDA VA POR LA VENTA DETALLE DE LA FACTURA DE LA REMISION - OJO!! SOLO FUNCIONA HASTA ORITA QUE SE HACE SALIDA SOLO CUANDO SE FACTURA LA REMISION + Dim CveVentaDetalle = If(ConceptoEntrada = 3, TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"Consec={Consec}").ToEntero, MovDet("CveVentaDetalle").ToString.ToEntero) + 'CUANDO LA VENTADETALLE NO TENGA VALOR DEBE MARCAR ERROR, NUEVA RESTRICCION DE ALMACEN + If CveVentaDetalle < 0 Then + OcurrioError = True + Exit For + End If + 'TERMINA: VENTADETALLE + + If Cantidad < 0 Then + Alert("Ocurrió un Error al generar los movimientos de almacén. Por favor comuniquese con atención SIG.", TipoMensaje.MsgError) + OcurrioError = True + Exit For + End If + + If ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then + ContadorMovtosDetalles += 1 + Else + OcurrioError = True + Exit For + End If + Next + + 'Agregamos las PrePolizas + If Not OcurrioError Then + If MovimientoPrePoliza AndAlso CveMovimientoInventario > 0 Then + If ObjInventario.GetMovimientosDetalle(CveMovimientoInventario, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then + Dim DtCostos = ObjInventario.DtResultados.Copy + Dim DtCostosDistinct As DataTable = ObjInventario.DtResultados.FiltraParametros("", "", {"CveClasificacion"}) + Dim IdCtaContable As Integer = 0 + Dim CveCuenta As Integer = 0 + Dim ValorInventario As Decimal + Dim TotalCostoAcumulado As Decimal = 0D + Dim Cont As Integer = 1 + Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL + + For Each RowInv As DataRow In DtCostosDistinct.Rows + ValorInventario = DtCostos.SUMD("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).RoundSQL + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + TotalCostoAcumulado += ValorInventario + + 'cuando es el último movimiento y hay diferencias en los importes + If Cont = DtCostosDistinct.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then + ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) + End If + + Try + 'If ValorInventario <> 0 Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then + OcurrioError = True + Exit For + End If + 'End If + Catch ex As Exception + OcurrioError = True + End Try + Cont += 1 + Next + + If Not OcurrioError Then + IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacen)).ToEntero + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, TotalCosto, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=TotalCosto, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then + OcurrioError = True + End If + End If + Else + OcurrioError = True + End If + End If + End If + + + 'VALIDA QUE SE HALLAN AGREGADO DETALLES AL MOVIMIENTO + If ContadorMovtosDetalles = 0 Then + OcurrioError = True + End If + + Else + OcurrioError = True + End If + + + + If OcurrioError Then + Return -1 + Else + Return CveMovimientoInventario + End If + 'Return Not OcurrioError + + End Function + Private Function SalidaAlmacenMateriales(ByRef ObjInventario As ClsInventarios, CveOS As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer) As Boolean + Dim TieneError As Boolean = False + Dim CveMovimientoSalida = 0 + Dim CveMovimientoEntrada = 0 + + Dim CveMovimientoSalida2 = 0 + Dim CveMovimientoEntrada2 = 0 + + Dim CveMovimientoSalida3 = 0 + Dim CveMovimientoEntrada3 = 0 + + Dim AlmacenEntrada = -1 + Dim FolioSalida = 0 + Dim FolioEntrada = 0 + + Dim TextoError = "" + Dim TextoExistencia As StringBuilder = New StringBuilder + + 'Obtenemos los movimientos detalle + If ObjInventario.GetMovimientosOS(9, CveOS, UsuarioActual.CveEmpresa) Then + If ObjInventario.DtResultados.Rows.Count > 0 Then + Dim CveMovimiento As Integer = ObjInventario.DtResultados(0)("CveMovimiento").ToString.ToEntero + Dim CveAlmacenOrigen As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero + Dim CveAlmacenDestino As Integer = ObjInventario.DtResultados(0)("AlmacenDestino2").ToString.ToEntero + Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero + Dim CveTipoAlmacen As Integer = ObjInventario.DtResultados(0)("CveTipoAlmacen").ToString.ToEntero + + 'AGREGAMOS LA ENTRADA Movto 1 + If Not TieneError Then + AlmacenEntrada = CveAlmacenOrigen + + CveMovimientoEntrada = ObjInventario.AddMovimiento(AlmacenEntrada, 8, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida, CveOS:=CveOS) + FolioEntrada = ObjInventario.Folio + + If CveMovimientoEntrada <= 0 Then + TextoError = "No se pudo generar el movimiento de entrada correctamente" + TieneError = True + Else + + If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then + + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then + TieneError = True + TextoError = "Ocurrió un Error al guardar los movimientos de entrada" + Exit For + End If + Next + + End If + + End If + End If + + 'AGREGAMOS LA ENTRADA Movto 2 + If Not TieneError Then + AlmacenEntrada = CveAlmacenDestino + + CveMovimientoEntrada2 = ObjInventario.AddMovimiento(AlmacenEntrada, 9, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida2, CveOS:=CveOS) + FolioEntrada = ObjInventario.Folio + + If CveMovimientoEntrada2 <= 0 Then + TextoError = "No se pudo generar el movimiento de entrada correctamente" + TieneError = True + Else + + If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada, UsuarioActual.CveEmpresa) Then + + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada2, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then + TieneError = True + TextoError = "Ocurrió un Error al guardar los movimientos de entrada" + Exit For + End If + Next + + End If + + End If + End If + + 'AGREGAMOS LA ENTRADA Movto 3 + If Not TieneError Then + AlmacenEntrada = CveAlmacenDestino + + CveMovimientoEntrada3 = ObjInventario.AddMovimiento(AlmacenEntrada, 3, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida3, CveOS:=CveOS) + FolioEntrada = ObjInventario.Folio + + If CveMovimientoEntrada3 <= 0 Then + TextoError = "No se pudo generar el movimiento de entrada correctamente" + TieneError = True + Else + + If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada2, UsuarioActual.CveEmpresa) Then + + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada3, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then + TieneError = True + TextoError = "Ocurrió un Error al guardar los movimientos de entrada" + Exit For + End If + Next + + End If + + End If + End If + + End If + End If + + Return TieneError End Function 'Protected Sub LbVerInventario_Click(sender As Object, e As EventArgs) Handles LbVerInventario.Click ' RegistraScript(String.Format("AbrirVentana('/Inventarios/PopUpExistenciasAlmacen.aspx?CvePS={0}',800,547,'N');", DdlPS.SelectedValue)) 'End Sub -#End Region +#End Region + +#Region " MANDA CORREO " + Private Sub MandaMails(CveVenta As Integer, EnviarFactura As Boolean, XML As String, PDF As String) + + Dim ObjMail As New ClsSisMail() + Dim ObjVentas As New ClsVentas + + Try + + Dim Asunto As String = String.Empty + Dim Cuerpo As String = String.Empty + Dim ResultadoMail As Integer = 0 + + Dim TipoComprobante = "" + + If DdlTipoComprobante.SelectedValue.ToString = "Ing" Then TipoComprobante = "Factura" + If DdlTipoComprobante.SelectedValue.ToString = "Egs" Then TipoComprobante = "Nota de Crédito" + If DdlTipoComprobante.SelectedValue.ToString = "Dev" Then TipoComprobante = "Nota de Devolución" + If DdlTipoComprobante.SelectedValue.ToString = "Rem" Then TipoComprobante = "Remisión" + If DdlTipoComprobante.SelectedValue.ToString = "Cot" Then TipoComprobante = "Cotización" + If DdlTipoComprobante.SelectedValue.ToString = "Ant" Then TipoComprobante = "Anticipo" + + If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then + Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta + Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa) + Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim) + Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante) + Cuerpo = Cuerpo.Replace("{""Fecha""}", TxtFecha.Text) + Cuerpo = Cuerpo.Replace("{""Total""}", TxtTotal.Text) + Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", TxtFechaPago.Text) + Cuerpo = Cuerpo.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}") + End If + + If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then + Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta + Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante) + Asunto = Asunto.Replace("{""Sucursal""}", DdlSubProyectoDatos.SelectedItem.Text) + Asunto = Asunto.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}") + End If + + If Not EnviarFactura Then + ObjVentas.UpdateVentaMail(0, CveVenta) + End If + + Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) + If DdlTipoComprobante.SelectedValue = "Cot" Then + LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) + Else + LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) + LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML}) + End If + + Dim DisplayName As String = "" + If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM" + + If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then + ResultadoMail = 1 + Else + ResultadoMail = 3 + End If + ObjVentas.UpdateVentaMail(ResultadoMail, CveVenta) + + 'CASO ESPECIAL + If CveUsuarioActual = 1446 Then ' Flora + Dim str As String = "Flora Envio: Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString + str.GuardaLog() + ElseIf CveUsuarioActual = 1513 Then ' Flora + Dim str As String = "Flora Envio (secundario): Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString + str.GuardaLog() + End If + + 'Next + + Catch ex As Exception + OnError("Ocurrió error al mandar el Mail", ex) + ObjVentas.UpdateVentaMail(3, CveVenta) + Finally + ObjVentas.Dispose() + End Try -#Region " MANDA CORREO " - Private Sub MandaMails(CveVenta As Integer, EnviarFactura As Boolean, XML As String, PDF As String) - - Dim ObjMail As New ClsSisMail() - Dim ObjVentas As New ClsVentas - - Try - - Dim Asunto As String = String.Empty - Dim Cuerpo As String = String.Empty - Dim ResultadoMail As Integer = 0 - - Dim TipoComprobante = "" - - If DdlTipoComprobante.SelectedValue.ToString = "Ing" Then TipoComprobante = "Factura" - If DdlTipoComprobante.SelectedValue.ToString = "Egs" Then TipoComprobante = "Nota de Crédito" - If DdlTipoComprobante.SelectedValue.ToString = "Dev" Then TipoComprobante = "Nota de Devolución" - If DdlTipoComprobante.SelectedValue.ToString = "Rem" Then TipoComprobante = "Remisión" - If DdlTipoComprobante.SelectedValue.ToString = "Cot" Then TipoComprobante = "Cotización" - If DdlTipoComprobante.SelectedValue.ToString = "Ant" Then TipoComprobante = "Anticipo" - - If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then - Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta - Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa) - Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim) - Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante) - Cuerpo = Cuerpo.Replace("{""Fecha""}", TxtFecha.Text) - Cuerpo = Cuerpo.Replace("{""Total""}", TxtTotal.Text) - Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", TxtFechaPago.Text) - Cuerpo = Cuerpo.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}") - End If - - If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then - Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta - Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante) - Asunto = Asunto.Replace("{""Sucursal""}", DdlSubProyectoDatos.SelectedItem.Text) - Asunto = Asunto.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}") - End If - - If Not EnviarFactura Then - ObjVentas.UpdateVentaMail(0, CveVenta) - End If - - Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) - If DdlTipoComprobante.SelectedValue = "Cot" Then - LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) - Else - LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) - LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML}) - End If - - Dim DisplayName As String = "" - If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM" - - If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then - ResultadoMail = 1 - Else - ResultadoMail = 3 - End If - ObjVentas.UpdateVentaMail(ResultadoMail, CveVenta) - - 'CASO ESPECIAL - If CveUsuarioActual = 1446 Then ' Flora - Dim str As String = "Flora Envio: Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString - str.GuardaLog() - ElseIf CveUsuarioActual = 1513 Then ' Flora - Dim str As String = "Flora Envio (secundario): Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString - str.GuardaLog() - End If - - 'Next - - Catch ex As Exception - OnError("Ocurrió error al mandar el Mail", ex) - ObjVentas.UpdateVentaMail(3, CveVenta) - Finally - ObjVentas.Dispose() - End Try - End Sub -#End Region +#End Region -#Region " ESTIMACIONES " +#Region " ESTIMACIONES " + + Protected Sub DdlContrato_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContrato.SelectedIndexChanged + Dim valueselect = DdlContrato.SelectedValue + CargaDatosEstimaciones(CveCliente) + DdlContrato.SelectedValue = valueselect + If DdlContrato.SelectedValue.ToEntero > 0 Then + For Each gvr As GridViewRow In GvEst.Rows + If gvr.DataKey("CveContratoAvance").ToEntero > 0 Then + gvr.FCCheckBox("Chk").Checked = True + gvr.FCCheckBox("Chk").Visible = True + End If + Next + BtnEstimacion.Visible = True + End If - Protected Sub DdlContrato_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContrato.SelectedIndexChanged - Dim valueselect = DdlContrato.SelectedValue - CargaDatosEstimaciones(CveCliente) - DdlContrato.SelectedValue = valueselect - If DdlContrato.SelectedValue.ToEntero > 0 Then - For Each gvr As GridViewRow In GvEst.Rows - If gvr.DataKey("CveContratoAvance").ToEntero > 0 Then - gvr.FCCheckBox("Chk").Checked = True - gvr.FCCheckBox("Chk").Visible = True - End If - Next - BtnEstimacion.Visible = True - End If - - End Sub - Private Sub CargaDatosEstimaciones(CveCliente As Integer) - If CveVenta > 0 Then - Exit Sub - End If - Dim Con As New ClsContratos - If Con.GetEstimacionesPorFacturar(-1, CveCliente, DdlContrato.SelectedValue.ToEntero, 0, UsuarioActual.CveEmpresa) Then - GvEst.DataSource = Con.DtResultados - If Con.DtResultados.Rows.Count > 0 Then - 'BtnEstimacion.Visible = True - DdlContrato.Items.Clear() - DdlContrato.Items.Add(New ListItem("Todos", "-1")) - DdlContrato.DataSource = Con.DtResultados.FiltraParametros("CveContrato > 0", "NumeroContrato", DistinctColumns:={"CveContrato", "NumeroContrato"}) - End If - End If - UPEstimaciones.Update() - Con.Dispose() - DdlContrato.DataBind() - GvEst.DataBind() - 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(300) 'Seccion - e.Row.Cells(2).Width = Unit.Pixel(100) 'Cantidad - e.Row.CssClass = "Totales" - Else - If e.Row.DBCampo("CveContratoAvance").ToString.ToEntero > 0 Then - ' e.Row.FCCheckBox("Chk").Visible = True - Else - If e.Row.DBCampo("CveSubFamilias").ToString.ToEntero > 0 Then - e.Row.CssClass = "SubTotales3" - Else - If e.Row.DBCampo("CveFamilias").ToString.ToEntero > 0 Then - e.Row.CssClass = "SubTotales2" - Else - e.Row.CssClass = "SubTotales" - End If - End If - End If - End If - End If - End Sub - - Private Sub ObtenerFechaVencimientoCER() - Try - - Dim CerFile As New FileStream(Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoCer, FileMode.Open, FileAccess.Read) - Dim Size As Integer = CerFile.Length.ToString.ToEntero() - Dim Data As Byte() = New Byte(Size - 1) {} - Size = CerFile.Read(Data, 0, Size) - CerFile.Close() - CerFile.Dispose() - - Dim x509 As New X509Certificate2() - x509.Import(Data) - - If x509.NotAfter <= Now() Then - TrVistaPrevia.Visible = False - TrEmitir.Visible = False - BtnEmitirImprimir.Visible = False - BtnCrearApartirDe.Enabled = False - Alert("La fecha del certificado ha expirado", TipoMensaje.MsgAdvertencia) - End If - - Catch ex As Exception - Alert("No se pudo verificar la fecha del certificado", TipoMensaje.MsgError) - End Try End Sub -#End Region - -#Region "E V E N T O - B I T A C O R A" - Protected Sub GvEB_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 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 - - Dim ObjEventos As New ClsOIEventos() - If ObjEventos.AddEventoBitacora(TxtEventoDescripcion.Text.Trim, String.Format(".{0}", FileExtension), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - If Filename <> "" Then - Filename.FilesMove(String.Format("OI{0}", ObjEventos.CveEvento.ToString), String.Format("Empresas\{0}\OI", UsuarioActual.CveEmpresa)) - End If - End If - ObjEventos.Dispose() - CargaEventoBitacora() - UPEventoBitacora.Update() - - End Sub - Private Sub CargaEventoBitacora() - If CveVenta <= 0 Then Exit Sub - - Dim ObjEventoBitacora As New ClsOIEventos() - If ObjEventoBitacora.GetAgendaBitacora(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - GvEB.DataSource = ObjEventoBitacora.DtResultados.FiltraParametros("CveTipoEvento = 6 OR CveTipoEvento = 2") - Else - GvEB.DataSource = Nothing - End If - ObjEventoBitacora.Dispose() - - GvEB.DataBind() - 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 + Private Sub CargaDatosEstimaciones(CveCliente As Integer) + If CveVenta > 0 Then + Exit Sub + End If + Dim Con As New ClsContratos + If Con.GetEstimacionesPorFacturar(-1, CveCliente, DdlContrato.SelectedValue.ToEntero, 0, UsuarioActual.CveEmpresa) Then + GvEst.DataSource = Con.DtResultados + If Con.DtResultados.Rows.Count > 0 Then + 'BtnEstimacion.Visible = True + DdlContrato.Items.Clear() + DdlContrato.Items.Add(New ListItem("Todos", "-1")) + DdlContrato.DataSource = Con.DtResultados.FiltraParametros("CveContrato > 0", "NumeroContrato", DistinctColumns:={"CveContrato", "NumeroContrato"}) + End If + End If + UPEstimaciones.Update() + Con.Dispose() + DdlContrato.DataBind() + GvEst.DataBind() + 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(300) 'Seccion + e.Row.Cells(2).Width = Unit.Pixel(100) 'Cantidad + e.Row.CssClass = "Totales" + Else + If e.Row.DBCampo("CveContratoAvance").ToString.ToEntero > 0 Then + ' e.Row.FCCheckBox("Chk").Visible = True + Else + If e.Row.DBCampo("CveSubFamilias").ToString.ToEntero > 0 Then + e.Row.CssClass = "SubTotales3" + Else + If e.Row.DBCampo("CveFamilias").ToString.ToEntero > 0 Then + e.Row.CssClass = "SubTotales2" + Else + e.Row.CssClass = "SubTotales" + End If + End If + End If + End If + End If End Sub -#End Region + Private Sub ObtenerFechaVencimientoCER() + Try + + Dim CerFile As New FileStream(Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoCer, FileMode.Open, FileAccess.Read) + Dim Size As Integer = CerFile.Length.ToString.ToEntero() + Dim Data As Byte() = New Byte(Size - 1) {} + Size = CerFile.Read(Data, 0, Size) + CerFile.Close() + CerFile.Dispose() + + Dim x509 As New X509Certificate2() + x509.Import(Data) + + If x509.NotAfter <= Now() Then + TrVistaPrevia.Visible = False + TrEmitir.Visible = False + BtnEmitirImprimir.Visible = False + BtnCrearApartirDe.Enabled = False + Alert("La fecha del certificado ha expirado", TipoMensaje.MsgAdvertencia) + End If + + Catch ex As Exception + Alert("No se pudo verificar la fecha del certificado", TipoMensaje.MsgError) + End Try + End Sub +#End Region + +#Region "E V E N T O - B I T A C O R A" + Protected Sub GvEB_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 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 + + Dim ObjEventos As New ClsOIEventos() + If ObjEventos.AddEventoBitacora(TxtEventoDescripcion.Text.Trim, String.Format(".{0}", FileExtension), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + If Filename <> "" Then + Filename.FilesMove(String.Format("OI{0}", ObjEventos.CveEvento.ToString), String.Format("Empresas\{0}\OI", UsuarioActual.CveEmpresa)) + End If + End If + ObjEventos.Dispose() + CargaEventoBitacora() + UPEventoBitacora.Update() + + End Sub + Private Sub CargaEventoBitacora() + If CveVenta <= 0 Then Exit Sub + + Dim ObjEventoBitacora As New ClsOIEventos() + If ObjEventoBitacora.GetAgendaBitacora(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + GvEB.DataSource = ObjEventoBitacora.DtResultados.FiltraParametros("CveTipoEvento = 6 OR CveTipoEvento = 2") + Else + GvEB.DataSource = Nothing + End If + ObjEventoBitacora.Dispose() + + GvEB.DataBind() + 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 + +#End Region + +#Region "BTN 'S" + Protected Sub LnkActualizarOrdenProduccion_Click(sender As Object, e As EventArgs) + If DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then + Dim ObjCGame As New ClsCGame + If ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero, CveVenta) Then + Alert("La orden de producción fue actualizada con exito.") + End If + ObjCGame.Dispose() + Else + Alert("Tiene que seleccionar una orden de producción.", TipoMensaje.MsgAdvertencia) + End If + End Sub + Protected Sub LnkContratoAcptar_Click(sender As Object, e As EventArgs) Handles LnkContratoAcptar.Click + Dim objcontra As New ClsContratos + objcontra.IniciaTransacSQL() + If objcontra.AddContratosAceptados(ViewState("CveVenta").ToString.ToEntero, TxtNombreContrato.Text, 13, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then '-----------------------------------------------Falata la CveContrato!!!!!!!!!!!!!! + objcontra.Commit() + Alert("La cotización fue aceptada" & objcontra.CveContrato, TipoMensaje.MsgInformacion) + Else + objcontra.RollBack() + Alert("La cotización no fue aceptada", TipoMensaje.MsgError) + End If + objcontra.Dispose() + End Sub + Private Sub BtnGarantia_Click(sender As Object, e As EventArgs) Handles LkGarantia.Click + Dim s As String = "" + + 'Nos vamos a la nueva factura + Dim url As String = String.Format("/RMA/Garantias.aspx?CveVenta={0}", CveVenta) + Response.Redirect(url) + + End Sub + Private Sub BtnGenerarNC_Click(sender As Object, e As EventArgs) Handles LkDevolucion.Click + + Dim url As String = String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=0", CveVenta) + Response.Redirect(url) + + End Sub + 'Private Sub LkNotaCreditoC_Click(sender As Object, e As EventArgs) Handles LkNotaCredito.Click + + ' Dim url As String = String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=2", CveVenta) + ' Response.Redirect(url) + + 'End Sub + Private Sub BtnNuevaFactura_Click(sender As Object, e As EventArgs) Handles LkRefacturacion.Click + 'Nos vamos a la nueva factura + Dim script As String = "" + + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then + Dim sb As New StringBuilder() + + If Not String.IsNullOrEmpty(FolioFiscal) Then + sb.Append("La factura se encuentra en el siguiente estatus del SAT:
    ") + + Dim TotalT As Decimal = TxtTotal.Text.ToDecimal + Dim RFCReceptor As String = LblRFC.Text.Trim + Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True) + If Vigencia IsNot Nothing Then + + If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then + Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + If Vigencia.EsCancelable = "Cancelable sin aceptación" Then + script = "BtnRefacturacionConfirmarAceptacion();" + sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) + sb.Append("Está seguro de realizar la refacturación?.") + End If + + If Vigencia.EsCancelable = "Cancelable con aceptación" OrElse String.IsNullOrEmpty(Vigencia.EsCancelable) Then + script = "BtnRefacturacionConfirmar();" + sb.AppendFormat("{0}
    ", "Cancelable con aceptación") + sb.Append("Está seguro de cancelar el documento para realizar la refacturación?.") + End If + Else + sb.Append("No encontrado
    ") + End If + Else + sb.Append("¿Desea realizar la refacturación?
    ") + script = "BtnRefacturacionConfirmarAceptacion();" + End If + + Alert(sb.ToString(), TipoMensaje.MsgConfirmacion, JSBtnAceptar:=script, TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") + End If + End Sub + 'BtnRefacturacionConfirmar + Private Sub BtnRefacturacionConfirmar_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmar.Click + CancelarDocumento(True) + End Sub + Private Sub BtnRefacturacionConfirmarAceptacion_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmarAceptacion.Click + Response.Redirect(String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", CveVenta)) + End Sub + Private Sub BtnContabilizar_Click(sender As Object, e As System.EventArgs) Handles BtnContabilizar.Click + 'Dim ObjMov As New ClsContabilidad + 'Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " + + + 'If ObjMov.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.Empresa, 2) Then + ' Alert(alertaContabilizacion & ObjMov.AlertaMensaje, ModExtensiones.TipoMensaje.MsgInformacion) + 'Else + ' Alert(String.Format("Ocurrio un error al contabilizar {0}", ObjMov.AlertaMensaje)) + 'End If + + 'ObjMov.Dispose() + + End Sub + 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 + Private Sub BtnMateriales_Click(sender As Object, e As EventArgs) Handles BtnMateriales.Click + Dim OS As New ClsOS + Dim DtDetalle As DataTable = Nothing + Dim DtDetalleMateriales As DataTable = Nothing + + DtDetalle = TmpDT.Copy + + For Each Row As DataRow In DtDetalle.Rows + If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString.ToEntero, CveOS) Then + Dim Cons As Integer = TmpDT.Rows.Count + 1 + + For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows + Dim drt As DataRow = TmpDT.NewRow + FacturaMateriales = 1 + drt("Consec") = Cons + drt("CveClasificacion") = dr("CveClasificacion") + drt("Clasificacion") = dr("Clasificacion") + drt("CvePS") = dr("CvePS") + drt("PS") = dr("PS") + drt("CodigoPS") = dr("CodigoPS") + drt("Cantidad") = dr("Cantidad") + drt("CveOSDetalle") = dr("CveOSDetalle") + drt("CveSubProyecto") = dr("CveSubProyecto") + drt("SubProyecto") = dr("SubProyecto") + TmpDT.Rows.Add(drt) + Cons = Cons + 1 + Next + End If + DtDetalleMateriales = OS.DtResultados.FiltraParametros("SeFacturara = 1 ") + Next + OS.Dispose() + + GvPS.DataSource = TmpDT + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + GvPS.DataBind() + UpPS.Update() + End Sub + + Private Sub BtnPermisoEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarRemision.Click + BtnEditarRemision.Visible = True + BtnPermisoEditarRemision.Visible = False + BtnCrearApartirDe.Visible = False + TxtObsFact.Enabled = True + TxtOrdenCompra.Enabled = True + TxtPedidoContrato.Enabled = True + TxtObsAlmacen.Enabled = True + + ModalidadEdicion = True + + ViewState("CveClienteAnterior") = CveCliente + + 'SI EL DETALLE NO TIENE MOVIMIENTOS DE INVENTARIO ES VISIBLE + Dim CantidadFacturadaRemision = 0.0 + For Each Gvr As GridViewRow In GvPS.Rows + Gvr.FCLinkButton("imgE").Visible = Not Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble > 0 + Gvr.FCLinkButton("imgD").Visible = Not Gvr.DataKey("CantidadInventario").ToString.ToDouble > 0 + CantidadFacturadaRemision += Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble + 'If GvInv.Rows.Count > 0 Then + ' Gvr.FCLinkButton("imgE").Enabled = False + ' Gvr.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen." + 'End If + Next + + 'ACTIVA CAMBIO DE CLIENTE - SI NO TIENE NADA FACTURADO + If Not CantidadFacturadaRemision > 0 Then + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto") + TxtCodigo.ReadOnly = False + End If + + TxtCantidad.Enabled = True + DdlClasificacion.Enabled = True + DdlPS.Enabled = True + TxtObsPS.Enabled = True + DdlProyecto.Enabled = True + DdlSubProyecto.Enabled = True + TxtPrecio.Enabled = True + LbAgregar.Enabled = True + LnkAgregarPyME.Enabled = True + ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") + LblSubTotal1.Text = TxtSubTotal.Text + LblAmort.Text = TxtSubTotal.Text + + UpPS.Update() + UpCliente.Update() + UPObservaciones.Update() + End Sub + Private Sub BtnEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnEditarRemision.Click + Dim OcurrioError As Boolean = False + Dim ObjVentas As New ClsVentas + Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) + Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) + Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) + Dim ObjAC As ClsContPAQi = Nothing + Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero + Dim TipoCambio As Double = TxtTipoCambio.Text.ToDouble + EditoRemision = True + 'Dim SubTotal, Descuento, IVA, RetIVA, RetISR, IEPS, Total As Decimal + ObjVentas.IniciaTransacSQL() + + + 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS + If DdlMoneda.SelectedValue.ToEntero <> 2 AndAlso ChkConvertirDolares.Checked Then + + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, 6) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) + Next + + Dim ImpuestosLocales As Double = 0 + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal).FormatoNumero + ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) + End If + Next + + TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero + LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero + LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero + TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero + TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero + TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero + TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero + TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero + + TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal + Moneda = 2 + End If + + 'CONVERTIR REMISION - TIPO MONEDA -PESO A DOLARES + If DdlMoneda.SelectedValue.ToEntero <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then + + For Each Row As DataRow In TmpDT.Rows + Row("PU") = Math.Round(Row("PU").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, 6) + Row("Total") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) + Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) + Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) + Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) + Next + + Dim ImpuestosLocales As Double = 0 + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal).FormatoNumero + ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) + End If + Next + + TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero + LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero + LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero + TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero + TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero + TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero + TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero + TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero + + + TipoCambio = 1 + Moneda = 1 + End If + + 'Actualizo los parametros de la venta + If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDecimal, LblDescuentos.Text.ToDecimal, TxtIVA.Text.ToDecimal, TxtIEPS.Text.ToDecimal, TxtTotal.Text.ToDecimal, Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, + UsuarioActual.CveEmpresa, CveVenta, 0, 0, + Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1), + PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero, TipoDocto:="Rem", CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal) Then + OcurrioError = True + End If + + 'Cargo de nueva cuenta el detalle de Ventas (Conceptos) + If Not OcurrioError Then + Dim index As Integer = 0 + For Each Row As DataRow In TmpDT.Rows + Dim CveVentaDetalle As Integer = Row("CveVentaDetalle").ToString.ToEntero() + If CveVentaDetalle > 0 Then + If Not ObjVentas.UpdateVentaDetalleRemision(Row("CveVentaDetalle").ToString.ToEntero, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDecimal, Row("PU").ToString.ToDecimal(), Row("ImporteIEPS").ToString.ToDecimal(), Row("Obs").ToString, UsuarioActual.CveUsuario) Then + OcurrioError = True + Exit For + End If + Else + If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, + Row("PU").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)))), 6), + Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, IEPS:=Row("IEPS").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString, + CveVentaDetallePadre:=Row("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CvePromocionDetalle:=If(DtPromociones IsNot Nothing, DtPromociones.FiltroPrimeroValor("CvePromocionDetalle", $"CvePS={Row("CvePS").ToString}").ToEntero, -1), + ImporteRetIVA:=Row("ImporteRetIVA").ToString.ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString.ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString.ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString.ToDouble, CuentaPredial:=Row("CuentaPredial").ToString) Then + OcurrioError = True + Exit For + Else + TmpDT.Rows(index)("CveVentaDetalle") = ObjVentas.CveVentaDetalle + End If + End If + index = index + 1 + Next + End If + + 'ELIMINA LOS DETALLES + If Not OcurrioError Then + Dim DtEliminados As New DataTable + If ObjVentas.GetVentaDetalle(CveVenta) Then + DtEliminados = ObjVentas.DtResultados.FiltraParametros("", "", {"CveVentaDetalle"}) + For Each Dr1 As DataRow In DtEliminados.Rows + If TmpDT.FiltraParametros($"CveVentaDetalle = {Dr1("CveVentaDetalle")}").Rows.Count = 0 Then + If Not ObjVentas.RemoveVentasDetalle(CveVenta, Dr1("CveVentaDetalle").ToString.ToEntero) Then + OcurrioError = True + End If + End If + Next + Else + OcurrioError = True + End If + End If + + 'OcurrioError = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, 1, ObjBancos, ObjVentas) + + 'Actualizo impuestos locales + If Not OcurrioError Then + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal) Then + OcurrioError = True + End If + End If + Next + End If + + 'Orden Produccion' + If Not OcurrioError Then + If UsuarioActual.CveEmpresa.Contiene(126) Then + If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then + If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then + ErrorList.Add("Ocurrió un error al actualizar la orden de producción") + End If + End If + End If + End If -#Region "BTN 'S" - Protected Sub LnkActualizarOrdenProduccion_Click(sender As Object, e As EventArgs) - If DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then - Dim ObjCGame As New ClsCGame - If ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero, CveVenta) Then - Alert("La orden de producción fue actualizada con exito.") - End If - ObjCGame.Dispose() - Else - Alert("Tiene que seleccionar una orden de producción.", TipoMensaje.MsgAdvertencia) - End If - End Sub - Protected Sub LnkContratoAcptar_Click(sender As Object, e As EventArgs) Handles LnkContratoAcptar.Click - Dim objcontra As New ClsContratos - objcontra.IniciaTransacSQL() - If objcontra.AddContratosAceptados(ViewState("CveVenta").ToString.ToEntero, TxtNombreContrato.Text, 13, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then '-----------------------------------------------Falata la CveContrato!!!!!!!!!!!!!! - objcontra.Commit() - Alert("La cotización fue aceptada" & objcontra.CveContrato, TipoMensaje.MsgInformacion) - Else - objcontra.RollBack() - Alert("La cotización no fue aceptada", TipoMensaje.MsgError) - End If - objcontra.Dispose() - End Sub - Private Sub BtnGarantia_Click(sender As Object, e As EventArgs) Handles LkGarantia.Click - Dim s As String = "" - - 'Nos vamos a la nueva factura - Dim url As String = String.Format("/RMA/Garantias.aspx?CveVenta={0}", CveVenta) - Response.Redirect(url) - - End Sub - Private Sub BtnGenerarNC_Click(sender As Object, e As EventArgs) Handles LkDevolucion.Click - - Dim url As String = String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=0", CveVenta) - Response.Redirect(url) - - End Sub - 'Private Sub LkNotaCreditoC_Click(sender As Object, e As EventArgs) Handles LkNotaCredito.Click - - ' Dim url As String = String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=2", CveVenta) - ' Response.Redirect(url) - - 'End Sub - Private Sub BtnNuevaFactura_Click(sender As Object, e As EventArgs) Handles LkRefacturacion.Click - 'Nos vamos a la nueva factura - Dim script As String = "" - - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then - Dim sb As New StringBuilder() - - If Not String.IsNullOrEmpty(FolioFiscal) Then - sb.Append("La factura se encuentra en el siguiente estatus del SAT:
    ") - - Dim TotalT As Decimal = TxtTotal.Text.ToDecimal - Dim RFCReceptor As String = LblRFC.Text.Trim - Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True) - If Vigencia IsNot Nothing Then - - If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then - Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - If Vigencia.EsCancelable = "Cancelable sin aceptación" Then - script = "BtnRefacturacionConfirmarAceptacion();" - sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) - sb.Append("Está seguro de realizar la refacturación?.") - End If - - If Vigencia.EsCancelable = "Cancelable con aceptación" OrElse String.IsNullOrEmpty(Vigencia.EsCancelable) Then - script = "BtnRefacturacionConfirmar();" - sb.AppendFormat("{0}
    ", "Cancelable con aceptación") - sb.Append("Está seguro de cancelar el documento para realizar la refacturación?.") - End If - Else - sb.Append("No encontrado
    ") - End If - Else - sb.Append("¿Desea realizar la refacturación?
    ") - script = "BtnRefacturacionConfirmarAceptacion();" - End If - - Alert(sb.ToString(), TipoMensaje.MsgConfirmacion, JSBtnAceptar:=script, TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") - End If - End Sub - 'BtnRefacturacionConfirmar - Private Sub BtnRefacturacionConfirmar_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmar.Click - CancelarDocumento(True) - End Sub - Private Sub BtnRefacturacionConfirmarAceptacion_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmarAceptacion.Click - Response.Redirect(String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", CveVenta)) - End Sub - Private Sub BtnContabilizar_Click(sender As Object, e As System.EventArgs) Handles BtnContabilizar.Click - 'Dim ObjMov As New ClsContabilidad - 'Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " - - - 'If ObjMov.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.Empresa, 2) Then - ' Alert(alertaContabilizacion & ObjMov.AlertaMensaje, ModExtensiones.TipoMensaje.MsgInformacion) - 'Else - ' Alert(String.Format("Ocurrio un error al contabilizar {0}", ObjMov.AlertaMensaje)) - 'End If - - 'ObjMov.Dispose() - - End Sub - 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 - Private Sub BtnMateriales_Click(sender As Object, e As EventArgs) Handles BtnMateriales.Click - Dim OS As New ClsOS - Dim DtDetalle As DataTable = Nothing - Dim DtDetalleMateriales As DataTable = Nothing - - DtDetalle = TmpDT.Copy - - For Each Row As DataRow In DtDetalle.Rows - If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString.ToEntero, CveOS) Then - Dim Cons As Integer = TmpDT.Rows.Count + 1 - - For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows - Dim drt As DataRow = TmpDT.NewRow - FacturaMateriales = 1 - drt("Consec") = Cons - drt("CveClasificacion") = dr("CveClasificacion") - drt("Clasificacion") = dr("Clasificacion") - drt("CvePS") = dr("CvePS") - drt("PS") = dr("PS") - drt("CodigoPS") = dr("CodigoPS") - drt("Cantidad") = dr("Cantidad") - drt("CveOSDetalle") = dr("CveOSDetalle") - drt("CveSubProyecto") = dr("CveSubProyecto") - drt("SubProyecto") = dr("SubProyecto") - TmpDT.Rows.Add(drt) - Cons = Cons + 1 - Next - End If - DtDetalleMateriales = OS.DtResultados.FiltraParametros("SeFacturara = 1 ") - Next - OS.Dispose() - - GvPS.DataSource = TmpDT - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - GvPS.DataBind() - UpPS.Update() - End Sub - - Private Sub BtnPermisoEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarRemision.Click - BtnEditarRemision.Visible = True - BtnPermisoEditarRemision.Visible = False - BtnCrearApartirDe.Visible = False - TxtObsFact.Enabled = True - TxtOrdenCompra.Enabled = True - TxtPedidoContrato.Enabled = True - TxtObsAlmacen.Enabled = True - - ModalidadEdicion = True - - ViewState("CveClienteAnterior") = CveCliente - - 'SI EL DETALLE NO TIENE MOVIMIENTOS DE INVENTARIO ES VISIBLE - Dim CantidadFacturadaRemision = 0.0 - For Each Gvr As GridViewRow In GvPS.Rows - Gvr.FCLinkButton("imgE").Visible = Not Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble > 0 - Gvr.FCLinkButton("imgD").Visible = Not Gvr.DataKey("CantidadInventario").ToString.ToDouble > 0 - CantidadFacturadaRemision += Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble - 'If GvInv.Rows.Count > 0 Then - ' Gvr.FCLinkButton("imgE").Enabled = False - ' Gvr.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen." - 'End If - Next - - 'ACTIVA CAMBIO DE CLIENTE - SI NO TIENE NADA FACTURADO - If Not CantidadFacturadaRemision > 0 Then - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto") - TxtCodigo.ReadOnly = False - End If - - TxtCantidad.Enabled = True - DdlClasificacion.Enabled = True - DdlPS.Enabled = True - TxtObsPS.Enabled = True - DdlProyecto.Enabled = True - DdlSubProyecto.Enabled = True - TxtPrecio.Enabled = True - LbAgregar.Enabled = True - LnkAgregarPyME.Enabled = True - ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") - LblSubTotal1.Text = TxtSubTotal.Text - LblAmort.Text = TxtSubTotal.Text - - UpPS.Update() - UpCliente.Update() - UPObservaciones.Update() - End Sub - Private Sub BtnEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnEditarRemision.Click - Dim OcurrioError As Boolean = False - Dim ObjVentas As New ClsVentas - Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) - Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) - Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) - Dim ObjAC As ClsContPAQi = Nothing - Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero - Dim TipoCambio As Double = TxtTipoCambio.Text.ToDouble - EditoRemision = True - 'Dim SubTotal, Descuento, IVA, RetIVA, RetISR, IEPS, Total As Decimal - ObjVentas.IniciaTransacSQL() - - - 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS - If DdlMoneda.SelectedValue.ToEntero <> 2 AndAlso ChkConvertirDolares.Checked Then - - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, 6) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) - Next - - Dim ImpuestosLocales As Double = 0 - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal).FormatoNumero - ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) - End If - Next - - TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero - LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero - LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero - TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero - TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero - TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero - TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero - TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero - - TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal - Moneda = 2 - End If - - 'CONVERTIR REMISION - TIPO MONEDA -PESO A DOLARES - If DdlMoneda.SelectedValue.ToEntero <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then - - For Each Row As DataRow In TmpDT.Rows - Row("PU") = Math.Round(Row("PU").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, 6) - Row("Total") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) - Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales) - Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) - Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) - Next - - Dim ImpuestosLocales As Double = 0 - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal).FormatoNumero - ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) - End If - Next - - TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero - LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero - LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero - TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero - TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero - TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero - TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero - TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero - - - TipoCambio = 1 - Moneda = 1 - End If - - 'Actualizo los parametros de la venta - If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDecimal, LblDescuentos.Text.ToDecimal, TxtIVA.Text.ToDecimal, TxtIEPS.Text.ToDecimal, TxtTotal.Text.ToDecimal, Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, - UsuarioActual.CveEmpresa, CveVenta, 0, 0, - Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1), - PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero, TipoDocto:="Rem", CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal) Then - OcurrioError = True - End If - - 'Cargo de nueva cuenta el detalle de Ventas (Conceptos) - If Not OcurrioError Then - Dim index As Integer = 0 - For Each Row As DataRow In TmpDT.Rows - Dim CveVentaDetalle As Integer = Row("CveVentaDetalle").ToString.ToEntero() - If CveVentaDetalle > 0 Then - If Not ObjVentas.UpdateVentaDetalleRemision(Row("CveVentaDetalle").ToString.ToEntero, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDecimal, Row("PU").ToString.ToDecimal(), Row("ImporteIEPS").ToString.ToDecimal(), Row("Obs").ToString, UsuarioActual.CveUsuario) Then - OcurrioError = True - Exit For - End If - Else - If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, - Row("PU").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)))), 6), - Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, IEPS:=Row("IEPS").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString, - CveVentaDetallePadre:=Row("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CvePromocionDetalle:=If(DtPromociones IsNot Nothing, DtPromociones.FiltroPrimeroValor("CvePromocionDetalle", $"CvePS={Row("CvePS").ToString}").ToEntero, -1), - ImporteRetIVA:=Row("ImporteRetIVA").ToString.ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString.ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString.ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString.ToDouble, CuentaPredial:=Row("CuentaPredial").ToString) Then - OcurrioError = True - Exit For - Else - TmpDT.Rows(index)("CveVentaDetalle") = ObjVentas.CveVentaDetalle - End If - End If - index = index + 1 - Next - End If - - 'ELIMINA LOS DETALLES - If Not OcurrioError Then - Dim DtEliminados As New DataTable - If ObjVentas.GetVentaDetalle(CveVenta) Then - DtEliminados = ObjVentas.DtResultados.FiltraParametros("", "", {"CveVentaDetalle"}) - For Each Dr1 As DataRow In DtEliminados.Rows - If TmpDT.FiltraParametros($"CveVentaDetalle = {Dr1("CveVentaDetalle")}").Rows.Count = 0 Then - If Not ObjVentas.RemoveVentasDetalle(CveVenta, Dr1("CveVentaDetalle").ToString.ToEntero) Then - OcurrioError = True - End If - End If - Next - Else - OcurrioError = True - End If - End If - - 'OcurrioError = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, 1, ObjBancos, ObjVentas) - - 'Actualizo impuestos locales - If Not OcurrioError Then - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal) Then - OcurrioError = True - End If - End If - Next - End If - - 'Orden Produccion' - If Not OcurrioError Then - If UsuarioActual.CveEmpresa.Contiene(126) Then - If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then - If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then - ErrorList.Add("Ocurrió un error al actualizar la orden de producción") - End If - End If - End If - End If - If ObjConta.ValidacionPrePolizaCuadre(-1, 2, CveVenta) Then If ObjConta.ValorPolizaDescuadre > 0 Then If ObjConta.ValorPolizaDescuadre = 2 Then @@ -15680,3935 +15687,3935 @@ Partial Class Ventas ErrorList.Add(ObjConta.MensajePolizaDescuadre) End If End If - End If - - If Not OcurrioError Then - If RegeneracionPolizas(ObjVentas, ObjAC) Then - OcurrioError = True - End If - End If - - If OcurrioError Then - ObjVentas.RollBack() - Alert("Ocurrió un error al guardar los cambios. Por favor intente de nuevo.", TipoMensaje.MsgError) - Else - ObjVentas.Commit() - If ObjAC IsNot Nothing Then ObjAC.Commit() - Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();") - End If - - ObjVentas.Dispose() - ObjConta.Dispose() - ObjBancos.Dispose() - If ObjAC IsNot Nothing Then ObjAC.Dispose() - End Sub - Private Sub BtnActualizarCuentaTerminal_Click(sender As Object, e As EventArgs) Handles BtnActualizarCuentaTerminal.Click - Dim ObjVentas As New ClsVentas - ObjVentas.IniciaTransacSQL() - Dim TieneError = False - - If Not ObjVentas.UpdateVentaCuentaTerminal(DdlCuentaTerminalModal.SelectedValue.ToEntero, CveVenta) Then - TieneError = True - End If - - If TieneError Then - ObjVentas.RollBack() - Else - ObjVentas.Commit() - RegistraScript("$('#ModalCuentaTerminal').modal('hide')") - Alert("Se asignó correctamente la cuenta terminal", JSBtnAceptar:="BtnRefrescarPagina();") - End If - ObjVentas.Dispose() + End If + + If Not OcurrioError Then + If RegeneracionPolizas(ObjVentas, ObjAC) Then + OcurrioError = True + End If + End If + + If OcurrioError Then + ObjVentas.RollBack() + Alert("Ocurrió un error al guardar los cambios. Por favor intente de nuevo.", TipoMensaje.MsgError) + Else + ObjVentas.Commit() + If ObjAC IsNot Nothing Then ObjAC.Commit() + Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();") + End If + + ObjVentas.Dispose() + ObjConta.Dispose() + ObjBancos.Dispose() + If ObjAC IsNot Nothing Then ObjAC.Dispose() End Sub -#End Region + Private Sub BtnActualizarCuentaTerminal_Click(sender As Object, e As EventArgs) Handles BtnActualizarCuentaTerminal.Click + Dim ObjVentas As New ClsVentas + ObjVentas.IniciaTransacSQL() + Dim TieneError = False + + If Not ObjVentas.UpdateVentaCuentaTerminal(DdlCuentaTerminalModal.SelectedValue.ToEntero, CveVenta) Then + TieneError = True + End If + + If TieneError Then + ObjVentas.RollBack() + Else + ObjVentas.Commit() + RegistraScript("$('#ModalCuentaTerminal').modal('hide')") + Alert("Se asignó correctamente la cuenta terminal", JSBtnAceptar:="BtnRefrescarPagina();") + End If + ObjVentas.Dispose() + End Sub +#End Region + +#Region "CODIGO DE BARRAS" + Protected Sub ChkClasificacion_CheckedChanged(sender As Object, e As EventArgs) + If ChkClasificacion.Checked Then + DIVClasificacion.Visible = False + DIVClasif.Visible = False + DIVCodBarras.Visible = True + DIVCod.Visible = True + TxtCodigoBarras.Focus() + Else + DIVClasificacion.Visible = True + DIVClasif.Visible = True + DIVCodBarras.Visible = False + DIVCod.Visible = False + End If + End Sub + Protected Sub CargarCodigo() + Dim TipoVenta As Integer = 0 + Dim drSucursal As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue))) + + If drSucursal IsNot Nothing Then TipoVenta = drSucursal("TipoVenta").ToString.ToEntero + + If TipoVenta = 1 Then + ChkClasificacion.Checked = True + DIVClasif.Visible = False + DIVClasificacion.Visible = False + DIVCodBarras.Visible = True + DIVCod.Visible = True + TxtCodigoBarras.Focus() + 'RegistraScript(String.Format("$( document ).ready(function() {{$('#{0}').focus()}});", TxtCodigoBarras.ClientID), "cb") + Else + ChkClasificacion.Visible = False + End If + End Sub + Protected Sub BtnCodigoBarras_Click(sender As Object, e As EventArgs) Handles BtnCodigoBarrasSerie.Click + + Dim DrProducto As DataRow = Nothing + If TxtCantidad.Text.Trim.ToDouble <= 0 Then TxtCantidad.Text = "1" + Dim SerieLote As String = "" + Dim CodigoBarras As String = "" + Dim CvePS As Integer + + 'LIMPIA "PROPIEDAD" + HdnCvePS.Value = "" + + 'BUSCA POR SERIE E IGNORA CODIGO DE BARRAS (LIMPIA) + If TxtCodigoSerie.Text.Trim <> "" Then + SerieLote = TxtCodigoSerie.Text.Trim().ToUpper() + Dim Objinventarios As New ClsInventarios + Dim Existencia = Objinventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, -1, SerieLote:=SerieLote, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) + Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", SerieLote)) + CvePS = Objinventarios.CvePS + Objinventarios.Dispose() + + If Existencia - ExistenciaActual > 0 Then + If CvePS > 0 Then + DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") + If DrProducto IsNot Nothing Then + HdnCvePS.Value = CvePS.ToString + TxtCantidad.Text = "1" + Else + Alert($"No se encontró un producto con la serie: {SerieLote}. Por favor verifique y vuelva a intentar ", TipoMensaje.MsgAdvertencia) + End If + End If + Else + Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", SerieLote), TipoMensaje.MsgAdvertencia) + TxtCodigoSerie.Focus() + RegistraScript($"$('#{TxtCodigoSerie.ClientID}').select();") + Exit Sub + End If + End If + + + 'BUSCA POR CODIGO DE BARRAS + If Not CvePS > 0 Then + CodigoBarras = TxtCodigoBarras.Text.Trim() + DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero($"CodigoBarras = '{CodigoBarras}'") + If DrProducto IsNot Nothing Then + If DrProducto("Inv_CveMetodoInventario").ToString = "5" Then 'si es serielote + TxtCodigoSerie.Focus() + Exit Sub + Else + CvePS = DrProducto("CvePS").ToString.ToEntero + HdnCvePS.Value = CvePS.ToString + End If + Else + TxtCodigoBarras.Focus() + RegistraScript($"$('#{TxtCodigoBarras.ClientID}').select();") + Alert($"No se encontró un producto con el código de barras: {SerieLote}. Por favor verifique y vuelva a intentar ", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + + If DrProducto Is Nothing Then + Alert("El producto no fue encontrado", TipoMensaje.MsgAdvertencia) + End If + + 'CARGA VALORES DEL PS + DdlPSIndexChange(CvePS, DdlPS) + If Not TxtCantidad.Text.ToDouble > 0 Then TxtCantidad.Text = "1" + TxtPrecio.Focus() + RegistraScript($"$('#{TxtPrecio.ClientID}').select();") + + 'LO DE ABAJO YA NO SE USA - ES VIEJO + Exit Sub + + + + 'PARA AGREGAR PS DIRECTO + If DrProducto IsNot Nothing Then + TxtObsPS.Text = "" + If UsuarioActual.CveEmpresa = 80 Then + + 'BUSCA EL PRECIO DE LA SUCURSAL + Dim ObjPS As New ClsProductosServicios + If ObjPS.GetPSSucursales(DrProducto("CvePS").ToString.ToEntero, UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero) Then + Dim dtt As DataTable = ObjPS.DtResultados + Dim drPrecio As DataRow = dtt.FiltroPrimero("") + + If drPrecio IsNot Nothing And TxtPrecio.Enabled = False Then + TxtPrecio.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4") + End If + dtt.Dispose() + End If + ObjPS.Dispose() + + 'SI NO CARGA PRECIO DE LA SUCURSAL TOMA EL DEL PS + If TxtPrecio.Text.ToDouble <= 0 Then + TxtPrecio.Text = DrProducto("Precio").ToString.ToDouble.ToString("N4") + End If + + HdnPS.Value = DrProducto("PS").ToString + HdnCodigoPS.Value = DrProducto("PSCodigo").ToString + HdnTipoPS.Value = DrProducto("CveTipoPS").ToString + HdnTipoInv.Value = DrProducto("Inv_CveMetodoInventario").ToString + HdnAplicaIEPS.Value = DrProducto("AplicaIEPS").ToString + HdnPorcentajeIEPS.Value = DrProducto("IEPSPorcentaje").ToString + HdnIVAPS.Value = If(DrProducto("IVA").ToString = "-1", ViewState("IVA"), DrProducto("IVA").ToString).ToString + HdnIVARetAPS.Value = DrProducto("RetIVA").ToString + HdnAsientoContable.Value = DrProducto("AsientoContableVentas").ToString + HdnCtaContable.Value = DrProducto("IdCtaContVentas").ToString + HdnAplicaParaConcepto.Value = DrProducto("AplicaParaConcepto").ToString + HdnCodigo.Value = DrProducto("Codigo").ToString + + If ValidaAgregarPS(DrProducto("CvePS").ToString.ToEntero, DrProducto("CveUM").ToString.ToEntero, TxtPrecio.Text.Trim.ToDouble, DrProducto("CveTipoPS").ToString.ToEntero) Then + + If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then + CvePSAmortizacion = DdlPS.SelectedValue.ToEntero.ToEntero + End If + + AgregarProductoServicio(TxtCantidad.Text.Trim.ToDecimal, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString, + DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDecimal, 0, + DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text) + + + 'AddPS(TxtCantidad.Text.Trim.ToDouble, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString, + ' DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDouble, HdnIVAPS.Value.ToDouble, 0, 0, + ' -1, -1, True, DrProducto("Codigo").ToString, DdlProyecto.SelectedValue.ToEntero, + ' DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, DrProducto("CveTipoPS").ToString.ToEntero, DrProducto("Inv_CveMetodoInventario").ToString.ToEntero, SerieLote:=SerieLote, CodigoPS:=DrProducto("PSCodigo").ToString) + + LimpiaAgregar() + End If + + End If + + Else + Alert("El producto no fue encontrado.", TipoMensaje.MsgAdvertencia) + End If + End Sub + Private Sub DdlMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMoneda.SelectedIndexChanged + CambiaMoneda() + End Sub + Private Sub CambiaMoneda() + TrConversionTipoCambio.Visible = False + TrConversionDolares.Visible = False + + Select Case DdlMoneda.SelectedValue + Case "1" + TxtTipoCambio.Text = "1" + TxtTipoCambioDlls.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString + TrConversionDolares.Visible = True + Case "2" + TxtTipoCambioDlls.Text = "1" + TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString + TrConversionTipoCambio.Visible = True + Case Else + TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString + TrConversionTipoCambio.Visible = True + End Select + UpPS.Update() + + If CveCliente > 0 Then + CargaAnticipos(CveCliente) + End If + End Sub + Private Sub btnBuscarPrecio_Click(sender As Object, e As EventArgs) Handles btnBuscarPrecio.Click + Dim Codigo, CodigoBarras As String + Dim CvePS As Integer + CvePS = If(DdlBPPS.SelectedValue.ToEntero > 0, DdlBPPS.SelectedValue.ToEntero, -1) + Codigo = If(TxtBPCodigo.Text.Trim.Length = 0, "", TxtBPCodigo.Text) + CodigoBarras = If(TxtBPCodigoBarras.Text.Trim.Length = 0, "", TxtBPCodigoBarras.Text) + + Dim ObjPS As New ClsProductosServicios + If ObjPS.GetPSSucursalesALL(DdlPS.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, Codigo:=Codigo, CodigoBarras:=CodigoBarras) Then + GVBuscarPrecio.DataSource = ObjPS.DtResultados + Else + GVBuscarPrecio.DataSource = Nothing + End If + ObjPS.Dispose() + GVBuscarPrecio.DataBind() + UpBuscarPrecio.Update() -#Region "CODIGO DE BARRAS" - Protected Sub ChkClasificacion_CheckedChanged(sender As Object, e As EventArgs) - If ChkClasificacion.Checked Then - DIVClasificacion.Visible = False - DIVClasif.Visible = False - DIVCodBarras.Visible = True - DIVCod.Visible = True - TxtCodigoBarras.Focus() - Else - DIVClasificacion.Visible = True - DIVClasif.Visible = True - DIVCodBarras.Visible = False - DIVCod.Visible = False - End If - End Sub - Protected Sub CargarCodigo() - Dim TipoVenta As Integer = 0 - Dim drSucursal As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue))) - - If drSucursal IsNot Nothing Then TipoVenta = drSucursal("TipoVenta").ToString.ToEntero - - If TipoVenta = 1 Then - ChkClasificacion.Checked = True - DIVClasif.Visible = False - DIVClasificacion.Visible = False - DIVCodBarras.Visible = True - DIVCod.Visible = True - TxtCodigoBarras.Focus() - 'RegistraScript(String.Format("$( document ).ready(function() {{$('#{0}').focus()}});", TxtCodigoBarras.ClientID), "cb") - Else - ChkClasificacion.Visible = False - End If - End Sub - Protected Sub BtnCodigoBarras_Click(sender As Object, e As EventArgs) Handles BtnCodigoBarrasSerie.Click - - Dim DrProducto As DataRow = Nothing - If TxtCantidad.Text.Trim.ToDouble <= 0 Then TxtCantidad.Text = "1" - Dim SerieLote As String = "" - Dim CodigoBarras As String = "" - Dim CvePS As Integer - - 'LIMPIA "PROPIEDAD" - HdnCvePS.Value = "" - - 'BUSCA POR SERIE E IGNORA CODIGO DE BARRAS (LIMPIA) - If TxtCodigoSerie.Text.Trim <> "" Then - SerieLote = TxtCodigoSerie.Text.Trim().ToUpper() - Dim Objinventarios As New ClsInventarios - Dim Existencia = Objinventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, -1, SerieLote:=SerieLote, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) - Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", SerieLote)) - CvePS = Objinventarios.CvePS - Objinventarios.Dispose() - - If Existencia - ExistenciaActual > 0 Then - If CvePS > 0 Then - DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") - If DrProducto IsNot Nothing Then - HdnCvePS.Value = CvePS.ToString - TxtCantidad.Text = "1" - Else - Alert($"No se encontró un producto con la serie: {SerieLote}. Por favor verifique y vuelva a intentar ", TipoMensaje.MsgAdvertencia) - End If - End If - Else - Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", SerieLote), TipoMensaje.MsgAdvertencia) - TxtCodigoSerie.Focus() - RegistraScript($"$('#{TxtCodigoSerie.ClientID}').select();") - Exit Sub - End If - End If - - - 'BUSCA POR CODIGO DE BARRAS - If Not CvePS > 0 Then - CodigoBarras = TxtCodigoBarras.Text.Trim() - DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero($"CodigoBarras = '{CodigoBarras}'") - If DrProducto IsNot Nothing Then - If DrProducto("Inv_CveMetodoInventario").ToString = "5" Then 'si es serielote - TxtCodigoSerie.Focus() - Exit Sub - Else - CvePS = DrProducto("CvePS").ToString.ToEntero - HdnCvePS.Value = CvePS.ToString - End If - Else - TxtCodigoBarras.Focus() - RegistraScript($"$('#{TxtCodigoBarras.ClientID}').select();") - Alert($"No se encontró un producto con el código de barras: {SerieLote}. Por favor verifique y vuelva a intentar ", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - - If DrProducto Is Nothing Then - Alert("El producto no fue encontrado", TipoMensaje.MsgAdvertencia) - End If - - 'CARGA VALORES DEL PS - DdlPSIndexChange(CvePS, DdlPS) - If Not TxtCantidad.Text.ToDouble > 0 Then TxtCantidad.Text = "1" - TxtPrecio.Focus() - RegistraScript($"$('#{TxtPrecio.ClientID}').select();") - - 'LO DE ABAJO YA NO SE USA - ES VIEJO - Exit Sub - - - - 'PARA AGREGAR PS DIRECTO - If DrProducto IsNot Nothing Then - TxtObsPS.Text = "" - If UsuarioActual.CveEmpresa = 80 Then - - 'BUSCA EL PRECIO DE LA SUCURSAL - Dim ObjPS As New ClsProductosServicios - If ObjPS.GetPSSucursales(DrProducto("CvePS").ToString.ToEntero, UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero) Then - Dim dtt As DataTable = ObjPS.DtResultados - Dim drPrecio As DataRow = dtt.FiltroPrimero("") - - If drPrecio IsNot Nothing And TxtPrecio.Enabled = False Then - TxtPrecio.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4") - End If - dtt.Dispose() - End If - ObjPS.Dispose() - - 'SI NO CARGA PRECIO DE LA SUCURSAL TOMA EL DEL PS - If TxtPrecio.Text.ToDouble <= 0 Then - TxtPrecio.Text = DrProducto("Precio").ToString.ToDouble.ToString("N4") - End If - - HdnPS.Value = DrProducto("PS").ToString - HdnCodigoPS.Value = DrProducto("PSCodigo").ToString - HdnTipoPS.Value = DrProducto("CveTipoPS").ToString - HdnTipoInv.Value = DrProducto("Inv_CveMetodoInventario").ToString - HdnAplicaIEPS.Value = DrProducto("AplicaIEPS").ToString - HdnPorcentajeIEPS.Value = DrProducto("IEPSPorcentaje").ToString - HdnIVAPS.Value = If(DrProducto("IVA").ToString = "-1", ViewState("IVA"), DrProducto("IVA").ToString).ToString - HdnIVARetAPS.Value = DrProducto("RetIVA").ToString - HdnAsientoContable.Value = DrProducto("AsientoContableVentas").ToString - HdnCtaContable.Value = DrProducto("IdCtaContVentas").ToString - HdnAplicaParaConcepto.Value = DrProducto("AplicaParaConcepto").ToString - HdnCodigo.Value = DrProducto("Codigo").ToString - - If ValidaAgregarPS(DrProducto("CvePS").ToString.ToEntero, DrProducto("CveUM").ToString.ToEntero, TxtPrecio.Text.Trim.ToDouble, DrProducto("CveTipoPS").ToString.ToEntero) Then - - If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then - CvePSAmortizacion = DdlPS.SelectedValue.ToEntero.ToEntero - End If - - AgregarProductoServicio(TxtCantidad.Text.Trim.ToDecimal, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString, - DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDecimal, 0, - DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text) - - - 'AddPS(TxtCantidad.Text.Trim.ToDouble, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString, - ' DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDouble, HdnIVAPS.Value.ToDouble, 0, 0, - ' -1, -1, True, DrProducto("Codigo").ToString, DdlProyecto.SelectedValue.ToEntero, - ' DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, DrProducto("CveTipoPS").ToString.ToEntero, DrProducto("Inv_CveMetodoInventario").ToString.ToEntero, SerieLote:=SerieLote, CodigoPS:=DrProducto("PSCodigo").ToString) - - LimpiaAgregar() - End If - - End If - - Else - Alert("El producto no fue encontrado.", TipoMensaje.MsgAdvertencia) - End If - End Sub - Private Sub DdlMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMoneda.SelectedIndexChanged - CambiaMoneda() - End Sub - Private Sub CambiaMoneda() - TrConversionTipoCambio.Visible = False - TrConversionDolares.Visible = False - - Select Case DdlMoneda.SelectedValue - Case "1" - TxtTipoCambio.Text = "1" - TxtTipoCambioDlls.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString - TrConversionDolares.Visible = True - Case "2" - TxtTipoCambioDlls.Text = "1" - TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString - TrConversionTipoCambio.Visible = True - Case Else - TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString - TrConversionTipoCambio.Visible = True - End Select - UpPS.Update() - - If CveCliente > 0 Then - CargaAnticipos(CveCliente) - End If - End Sub - Private Sub btnBuscarPrecio_Click(sender As Object, e As EventArgs) Handles btnBuscarPrecio.Click - Dim Codigo, CodigoBarras As String - Dim CvePS As Integer - CvePS = If(DdlBPPS.SelectedValue.ToEntero > 0, DdlBPPS.SelectedValue.ToEntero, -1) - Codigo = If(TxtBPCodigo.Text.Trim.Length = 0, "", TxtBPCodigo.Text) - CodigoBarras = If(TxtBPCodigoBarras.Text.Trim.Length = 0, "", TxtBPCodigoBarras.Text) - - Dim ObjPS As New ClsProductosServicios - If ObjPS.GetPSSucursalesALL(DdlPS.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, Codigo:=Codigo, CodigoBarras:=CodigoBarras) Then - GVBuscarPrecio.DataSource = ObjPS.DtResultados - Else - GVBuscarPrecio.DataSource = Nothing - End If - ObjPS.Dispose() - GVBuscarPrecio.DataBind() - UpBuscarPrecio.Update() - End Sub -#End Region +#End Region -#Region " CONDICIONES DE PAGO " - Private Sub InicializaCondicionesPago() - DtPagos = New DataTable - - DtPagos.Columns.Add("CveTipoMovimiento", GetType(String)) - DtPagos.Columns.Add("TipoMovimiento", GetType(String)) - DtPagos.Columns.Add("CveCuenta", GetType(String)) - DtPagos.Columns.Add("Cuenta", GetType(String)) - DtPagos.Columns.Add("Folio", GetType(String)) - DtPagos.Columns.Add("Importe", GetType(Decimal)) - DtPagos.Columns.Add("Observaciones", GetType(String)) - DtPagos.Columns.Add("Tipo", GetType(String)) - DtPagos.Columns.Add("CveMetodoPago", GetType(Integer)) - - CargaCuentas() - - End Sub - Private Sub LimpiaContado() - CargaCuentas() - DdlCuentaEfectivo.SelectedValueExist(-1) - TxtImporteEfectivo.Text = "0.00" - TxtImporteCredito.Text = "0.00" - TxtImporteDebito.Text = "0.00" - TxtImporteCheque.Text = "0.00" - TxtImporteTransferencia.Text = "0.00" - TxtImporteContado.Text = "0.00" - End Sub - Private Sub LimpiaEscondeContado() - 'LIMPIA - DivContado.Visible = False - DivTerminal.Visible = False - - If DtPagos IsNot Nothing Then DtPagos.Rows.Clear() - CargaGridContado() - - Select Case RBLPago.SelectedValue.ToEntero - Case 1 'CREDITO - TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString - Case 2 'CONTADO - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then - DivContado.Visible = True - TxtImporteContado.Text = TxtTotal.Text - End If - TxtFechaPago.Text = Now.ToShortDateString - Case 3 ' TERMINAL - DivTerminal.Visible = True - TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString - End Select - - LimpiaContado() - UpContado.Update() - End Sub - Private Sub CargaCuentas() - - DdlCuentaEfectivo.Items.Clear() - DdlCuentaTarjetaCredito.Items.Clear() - DdlCuentaTarjetaDebito.Items.Clear() - DdlCuentaCheque.Items.Clear() - DdlCuentaTransferencia.Items.Clear() - - - DdlCuentaEfectivo.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) - DdlCuentaTarjetaCredito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) - DdlCuentaTarjetaDebito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) - DdlCuentaCheque.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) - DdlCuentaTransferencia.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) - - DdlCuentaEfectivo.DataBind() - DdlCuentaTarjetaCredito.DataBind() - DdlCuentaTarjetaDebito.DataBind() - DdlCuentaCheque.DataBind() - DdlCuentaTransferencia.DataBind() - - End Sub - Private Function CargaFolioContado(CveCuenta As Integer, TipoTransaccion As Integer) As Long - Dim Folio As Long - - If CveCuenta > 0 And TipoTransaccion > 0 Then - Dim Banco As New ClsBancos - Folio = Banco.GetNextFolio(CveCuenta, TipoTransaccion) - Banco.Dispose() - Else - Folio = -1 - End If - - Return Folio - End Function - Private Sub CargaGridContado() - GvPagos.DataSource = DtPagos - GvPagos.DataBind() - End Sub - Protected Sub GvPagos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvPagos.RowDeleting - DtPagos.Rows.RemoveAt(e.RowIndex) - - 'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P. - Dim abonado = DtPagos.SUM("Importe") - Dim saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado - CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString - - CargaGridContado() - UpContado.Update() - End Sub - Private Sub BtnAgregarPago_Click(sender As Object, e As EventArgs) Handles BtnAgregarPago.Click - Dim abonado, saldo As Double - Dim total As Decimal = TxtImporteEfectivo.Text.ToDecimal + TxtImporteCredito.Text.ToDecimal + TxtImporteDebito.Text.ToDecimal + TxtImporteCheque.Text.ToDecimal + TxtImporteTransferencia.Text.ToDecimal - - DtPagos = Nothing - InicializaCondicionesPago() - - If total <= 0 Then Alert("No se ha ingresado importe", TipoMensaje.MsgAdvertencia) : Exit Sub - - If DtPagos.SUM("Importe").ToString.ToDecimal + total > TxtTotal.Text.ToDecimal Then - Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor rectifique.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'Pago en Efectivo - If TxtImporteEfectivo.Text.ToDecimal > 0 Then - If DdlCuentaEfectivo.Items.Count > 0 Then - Dim DrEfectivo = DtPagos.NewRow - DrEfectivo("CveTipoMovimiento") = 13 - DrEfectivo("TipoMovimiento") = "Pago en Efectivo" - DrEfectivo("CveCuenta") = DdlCuentaEfectivo.SelectedValue - DrEfectivo("Cuenta") = DdlCuentaEfectivo.SelectedItem.Text - DrEfectivo("Importe") = TxtImporteEfectivo.Text - DrEfectivo("Folio") = CargaFolioContado(DdlCuentaEfectivo.SelectedValue.ToEntero, 6) - DrEfectivo("Observaciones") = "" - DrEfectivo("Tipo") = "Caja Chica" - DrEfectivo("CveMetodoPago") = 1 - DtPagos.Rows.Add(DrEfectivo) - Else - Alert("Debe seleccionar una cuenta válida de caja", TipoMensaje.MsgAdvertencia) - End If - End If - - 'Pago Tarjeta Credito - If TxtImporteCredito.Text.ToDecimal > 0 Then - If DdlCuentaTarjetaCredito.Items.Count > 0 Then - Dim DrCredito = DtPagos.NewRow - DrCredito("CveTipoMovimiento") = 12 - DrCredito("TipoMovimiento") = "Tarjeta de Crédito" - DrCredito("CveCuenta") = DdlCuentaTarjetaCredito.SelectedValue - DrCredito("Cuenta") = DdlCuentaTarjetaCredito.SelectedItem.Text - DrCredito("Importe") = TxtImporteCredito.Text - DrCredito("Folio") = CargaFolioContado(DdlCuentaTarjetaCredito.SelectedValue.ToEntero, 12) - DrCredito("Observaciones") = "" - DrCredito("Tipo") = "Tarjeta de Crédito" - DrCredito("CveMetodoPago") = 4 - DtPagos.Rows.Add(DrCredito) - Else - Alert("Debe seleccionar una cuenta válida de crédito", TipoMensaje.MsgAdvertencia) - End If - End If - - 'Pago Tarjeta Debito - If TxtImporteDebito.Text.ToDecimal > 0 Then - If DdlCuentaTarjetaDebito.Items.Count > 0 Then - Dim DrDebito = DtPagos.NewRow - DrDebito("CveTipoMovimiento") = 11 - DrDebito("TipoMovimiento") = "Tarjeta de Debito" - DrDebito("CveCuenta") = DdlCuentaTarjetaDebito.SelectedValue - DrDebito("Cuenta") = DdlCuentaTarjetaDebito.SelectedItem.Text - DrDebito("Importe") = TxtImporteDebito.Text - DrDebito("Folio") = CargaFolioContado(DdlCuentaTarjetaDebito.SelectedValue.ToEntero, 11) - DrDebito("Observaciones") = "" - DrDebito("Tipo") = "Tarjeta de Débito" - DrDebito("CveMetodoPago") = 5 - - DtPagos.Rows.Add(DrDebito) - Else - Alert("Debe seleccionar una cuenta válida de débito", TipoMensaje.MsgAdvertencia) - End If - End If - - 'Pago Tarjeta Debito - If TxtImporteCheque.Text.ToDecimal > 0 Then - If DdlCuentaCheque.Items.Count > 0 Then - Dim DrCheque = DtPagos.NewRow - DrCheque("CveTipoMovimiento") = 3 - DrCheque("TipoMovimiento") = "Cheque" - DrCheque("CveCuenta") = DdlCuentaCheque.SelectedValue - DrCheque("Cuenta") = DdlCuentaCheque.SelectedItem.Text - DrCheque("Importe") = TxtImporteCheque.Text - DrCheque("Folio") = CargaFolioContado(DdlCuentaCheque.SelectedValue.ToEntero, 3) - DrCheque("Observaciones") = "" - DrCheque("Tipo") = "Cheque" - DrCheque("CveMetodoPago") = 2 - - DtPagos.Rows.Add(DrCheque) - Else - Alert("Debe seleccionar una cuenta de cheque", TipoMensaje.MsgAdvertencia) - End If - End If - - 'Pago Transferencia - If TxtImporteTransferencia.Text.ToDecimal > 0 Then - If DdlCuentaTransferencia.Items.Count > 0 Then - Dim DrCheque = DtPagos.NewRow - DrCheque("CveTipoMovimiento") = 8 - DrCheque("TipoMovimiento") = "Transferencia" - DrCheque("CveCuenta") = DdlCuentaTransferencia.SelectedValue - DrCheque("Cuenta") = DdlCuentaTransferencia.SelectedItem.Text - DrCheque("Importe") = TxtImporteTransferencia.Text - DrCheque("Folio") = CargaFolioContado(DdlCuentaTransferencia.SelectedValue.ToEntero, 8) - DrCheque("Observaciones") = "" - DrCheque("Tipo") = "Transferencia" - DrCheque("CveMetodoPago") = 3 - - DtPagos.Rows.Add(DrCheque) - Else - Alert("Debe seleccionar una cuenta de transferencia", TipoMensaje.MsgAdvertencia) - End If - End If - - 'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P. - abonado = DtPagos.SUM("Importe") - saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado - CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString - - CargaGridContado() - UpContado.Update() - - End Sub - Private Sub RBLPago_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLPago.SelectedIndexChanged - LimpiaEscondeContado() - End Sub - Private Function ValidaPagosContado() As Boolean - Dim Retorno = False - - If DtPagos.SUM("Importe").ToString.ToDecimal > TxtTotal.Text.ToDecimal Then - Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor verifique.", TipoMensaje.MsgAdvertencia) - Retorno = True - End If - - Return Retorno +#Region " CONDICIONES DE PAGO " + Private Sub InicializaCondicionesPago() + DtPagos = New DataTable + + DtPagos.Columns.Add("CveTipoMovimiento", GetType(String)) + DtPagos.Columns.Add("TipoMovimiento", GetType(String)) + DtPagos.Columns.Add("CveCuenta", GetType(String)) + DtPagos.Columns.Add("Cuenta", GetType(String)) + DtPagos.Columns.Add("Folio", GetType(String)) + DtPagos.Columns.Add("Importe", GetType(Decimal)) + DtPagos.Columns.Add("Observaciones", GetType(String)) + DtPagos.Columns.Add("Tipo", GetType(String)) + DtPagos.Columns.Add("CveMetodoPago", GetType(Integer)) + + CargaCuentas() + + End Sub + Private Sub LimpiaContado() + CargaCuentas() + DdlCuentaEfectivo.SelectedValueExist(-1) + TxtImporteEfectivo.Text = "0.00" + TxtImporteCredito.Text = "0.00" + TxtImporteDebito.Text = "0.00" + TxtImporteCheque.Text = "0.00" + TxtImporteTransferencia.Text = "0.00" + TxtImporteContado.Text = "0.00" + End Sub + Private Sub LimpiaEscondeContado() + 'LIMPIA + DivContado.Visible = False + DivTerminal.Visible = False + + If DtPagos IsNot Nothing Then DtPagos.Rows.Clear() + CargaGridContado() + + Select Case RBLPago.SelectedValue.ToEntero + Case 1 'CREDITO + TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString + Case 2 'CONTADO + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then + DivContado.Visible = True + TxtImporteContado.Text = TxtTotal.Text + End If + TxtFechaPago.Text = Now.ToShortDateString + Case 3 ' TERMINAL + DivTerminal.Visible = True + TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString + End Select + + LimpiaContado() + UpContado.Update() + End Sub + Private Sub CargaCuentas() + + DdlCuentaEfectivo.Items.Clear() + DdlCuentaTarjetaCredito.Items.Clear() + DdlCuentaTarjetaDebito.Items.Clear() + DdlCuentaCheque.Items.Clear() + DdlCuentaTransferencia.Items.Clear() + + + DdlCuentaEfectivo.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) + DdlCuentaTarjetaCredito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) + DdlCuentaTarjetaDebito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) + DdlCuentaCheque.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) + DdlCuentaTransferencia.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) + + DdlCuentaEfectivo.DataBind() + DdlCuentaTarjetaCredito.DataBind() + DdlCuentaTarjetaDebito.DataBind() + DdlCuentaCheque.DataBind() + DdlCuentaTransferencia.DataBind() + + End Sub + Private Function CargaFolioContado(CveCuenta As Integer, TipoTransaccion As Integer) As Long + Dim Folio As Long + + If CveCuenta > 0 And TipoTransaccion > 0 Then + Dim Banco As New ClsBancos + Folio = Banco.GetNextFolio(CveCuenta, TipoTransaccion) + Banco.Dispose() + Else + Folio = -1 + End If + + Return Folio End Function -#End Region + Private Sub CargaGridContado() + GvPagos.DataSource = DtPagos + GvPagos.DataBind() + End Sub + Protected Sub GvPagos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvPagos.RowDeleting + DtPagos.Rows.RemoveAt(e.RowIndex) -#Region " SERIE ALMACEN " + 'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P. + Dim abonado = DtPagos.SUM("Importe") + Dim saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado + CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString - Protected Sub BtnSerie_Click(sender As Object, e As EventArgs) - Dim Row = CType(CType(sender, Button).NamingContainer, GridViewRow) - - If Row.FCTextBox("TxtSerie").Text.Trim = "" Then Exit Sub - - Dim Index = Row.RowIndex - Dim ObjInventarios As New ClsInventarios - Dim Existencia = ObjInventarios.GetExistenciasPSSerie(Row.FCTextBox("TxtSerie").Text.ToString, ddlAlmacen.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) - Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Row.FCTextBox("TxtSerie").Text.ToString)) - - 'Valida Existencia - If Existencia - ExistenciaActual <= 0 Then - Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", Row.FCTextBox("TxtSerie").Text.ToString), TipoMensaje.MsgAdvertencia) - Row.FCTextBox("TxtSerie").Text = "" - Row.FCHiddenField("HdnSerie").Value = "" - TmpDT.Rows(Index)("SerieLote") = "" - Else - Row.FCHiddenField("HdnSerie").Value = Row.FCTextBox("TxtSerie").Text - TmpDT.Rows(Index)("SerieLote") = Row.FCTextBox("TxtSerie").Text - End If - - TmpDT.AcceptChanges() - DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") - - ObjInventarios.Dispose() - UpINV.Update() - End Sub - Private Function ValidaSerieINV() As Boolean - Dim Retorno = False - Dim Existencia = 0.0 - Dim ExistenciaActual = 0.0 - Dim ObjInventarios As New ClsInventarios - - For Each Gvr As GridViewRow In GvInv.Rows - If Gvr.FCCheckBox("cbInv").Checked Then - 'VACIO - If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim = "" Then - Alert("Algun producto con salida de inventario no tiene especificada la SERIE. Por favor verifique.", TipoMensaje.MsgAdvertencia) - Retorno = True - Exit For - End If - 'SIN EXISTENCIA - If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim <> "" Then - - Existencia = ObjInventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, ddlAlmacen.SelectedValue.ToEntero, SerieLote:=Gvr.FCTextBox("TxtSerie").Text.ToString, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) - ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Gvr.FCTextBox("TxtSerie").Text.Trim)) - - 'Valida Existencia - If Existencia - ExistenciaActual < 0 Then - Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", Gvr.FCTextBox("TxtSerie").Text.ToString), TipoMensaje.MsgAdvertencia) - Gvr.FCTextBox("TxtSerie").Text = "" - Retorno = True - Exit For - End If - - End If - End If - Next - - Return Retorno + CargaGridContado() + UpContado.Update() + End Sub + Private Sub BtnAgregarPago_Click(sender As Object, e As EventArgs) Handles BtnAgregarPago.Click + Dim abonado, saldo As Double + Dim total As Decimal = TxtImporteEfectivo.Text.ToDecimal + TxtImporteCredito.Text.ToDecimal + TxtImporteDebito.Text.ToDecimal + TxtImporteCheque.Text.ToDecimal + TxtImporteTransferencia.Text.ToDecimal + + DtPagos = Nothing + InicializaCondicionesPago() + + If total <= 0 Then Alert("No se ha ingresado importe", TipoMensaje.MsgAdvertencia) : Exit Sub + + If DtPagos.SUM("Importe").ToString.ToDecimal + total > TxtTotal.Text.ToDecimal Then + Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor rectifique.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'Pago en Efectivo + If TxtImporteEfectivo.Text.ToDecimal > 0 Then + If DdlCuentaEfectivo.Items.Count > 0 Then + Dim DrEfectivo = DtPagos.NewRow + DrEfectivo("CveTipoMovimiento") = 13 + DrEfectivo("TipoMovimiento") = "Pago en Efectivo" + DrEfectivo("CveCuenta") = DdlCuentaEfectivo.SelectedValue + DrEfectivo("Cuenta") = DdlCuentaEfectivo.SelectedItem.Text + DrEfectivo("Importe") = TxtImporteEfectivo.Text + DrEfectivo("Folio") = CargaFolioContado(DdlCuentaEfectivo.SelectedValue.ToEntero, 6) + DrEfectivo("Observaciones") = "" + DrEfectivo("Tipo") = "Caja Chica" + DrEfectivo("CveMetodoPago") = 1 + DtPagos.Rows.Add(DrEfectivo) + Else + Alert("Debe seleccionar una cuenta válida de caja", TipoMensaje.MsgAdvertencia) + End If + End If + + 'Pago Tarjeta Credito + If TxtImporteCredito.Text.ToDecimal > 0 Then + If DdlCuentaTarjetaCredito.Items.Count > 0 Then + Dim DrCredito = DtPagos.NewRow + DrCredito("CveTipoMovimiento") = 12 + DrCredito("TipoMovimiento") = "Tarjeta de Crédito" + DrCredito("CveCuenta") = DdlCuentaTarjetaCredito.SelectedValue + DrCredito("Cuenta") = DdlCuentaTarjetaCredito.SelectedItem.Text + DrCredito("Importe") = TxtImporteCredito.Text + DrCredito("Folio") = CargaFolioContado(DdlCuentaTarjetaCredito.SelectedValue.ToEntero, 12) + DrCredito("Observaciones") = "" + DrCredito("Tipo") = "Tarjeta de Crédito" + DrCredito("CveMetodoPago") = 4 + DtPagos.Rows.Add(DrCredito) + Else + Alert("Debe seleccionar una cuenta válida de crédito", TipoMensaje.MsgAdvertencia) + End If + End If + + 'Pago Tarjeta Debito + If TxtImporteDebito.Text.ToDecimal > 0 Then + If DdlCuentaTarjetaDebito.Items.Count > 0 Then + Dim DrDebito = DtPagos.NewRow + DrDebito("CveTipoMovimiento") = 11 + DrDebito("TipoMovimiento") = "Tarjeta de Debito" + DrDebito("CveCuenta") = DdlCuentaTarjetaDebito.SelectedValue + DrDebito("Cuenta") = DdlCuentaTarjetaDebito.SelectedItem.Text + DrDebito("Importe") = TxtImporteDebito.Text + DrDebito("Folio") = CargaFolioContado(DdlCuentaTarjetaDebito.SelectedValue.ToEntero, 11) + DrDebito("Observaciones") = "" + DrDebito("Tipo") = "Tarjeta de Débito" + DrDebito("CveMetodoPago") = 5 + + DtPagos.Rows.Add(DrDebito) + Else + Alert("Debe seleccionar una cuenta válida de débito", TipoMensaje.MsgAdvertencia) + End If + End If + + 'Pago Tarjeta Debito + If TxtImporteCheque.Text.ToDecimal > 0 Then + If DdlCuentaCheque.Items.Count > 0 Then + Dim DrCheque = DtPagos.NewRow + DrCheque("CveTipoMovimiento") = 3 + DrCheque("TipoMovimiento") = "Cheque" + DrCheque("CveCuenta") = DdlCuentaCheque.SelectedValue + DrCheque("Cuenta") = DdlCuentaCheque.SelectedItem.Text + DrCheque("Importe") = TxtImporteCheque.Text + DrCheque("Folio") = CargaFolioContado(DdlCuentaCheque.SelectedValue.ToEntero, 3) + DrCheque("Observaciones") = "" + DrCheque("Tipo") = "Cheque" + DrCheque("CveMetodoPago") = 2 + + DtPagos.Rows.Add(DrCheque) + Else + Alert("Debe seleccionar una cuenta de cheque", TipoMensaje.MsgAdvertencia) + End If + End If + + 'Pago Transferencia + If TxtImporteTransferencia.Text.ToDecimal > 0 Then + If DdlCuentaTransferencia.Items.Count > 0 Then + Dim DrCheque = DtPagos.NewRow + DrCheque("CveTipoMovimiento") = 8 + DrCheque("TipoMovimiento") = "Transferencia" + DrCheque("CveCuenta") = DdlCuentaTransferencia.SelectedValue + DrCheque("Cuenta") = DdlCuentaTransferencia.SelectedItem.Text + DrCheque("Importe") = TxtImporteTransferencia.Text + DrCheque("Folio") = CargaFolioContado(DdlCuentaTransferencia.SelectedValue.ToEntero, 8) + DrCheque("Observaciones") = "" + DrCheque("Tipo") = "Transferencia" + DrCheque("CveMetodoPago") = 3 + + DtPagos.Rows.Add(DrCheque) + Else + Alert("Debe seleccionar una cuenta de transferencia", TipoMensaje.MsgAdvertencia) + End If + End If + + 'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P. + abonado = DtPagos.SUM("Importe") + saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado + CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString + + CargaGridContado() + UpContado.Update() + + End Sub + Private Sub RBLPago_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLPago.SelectedIndexChanged + LimpiaEscondeContado() + End Sub + Private Function ValidaPagosContado() As Boolean + Dim Retorno = False + + If DtPagos.SUM("Importe").ToString.ToDecimal > TxtTotal.Text.ToDecimal Then + Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor verifique.", TipoMensaje.MsgAdvertencia) + Retorno = True + End If + + Return Retorno + End Function +#End Region + +#Region " SERIE ALMACEN " + + Protected Sub BtnSerie_Click(sender As Object, e As EventArgs) + Dim Row = CType(CType(sender, Button).NamingContainer, GridViewRow) + + If Row.FCTextBox("TxtSerie").Text.Trim = "" Then Exit Sub + + Dim Index = Row.RowIndex + Dim ObjInventarios As New ClsInventarios + Dim Existencia = ObjInventarios.GetExistenciasPSSerie(Row.FCTextBox("TxtSerie").Text.ToString, ddlAlmacen.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) + Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Row.FCTextBox("TxtSerie").Text.ToString)) + + 'Valida Existencia + If Existencia - ExistenciaActual <= 0 Then + Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", Row.FCTextBox("TxtSerie").Text.ToString), TipoMensaje.MsgAdvertencia) + Row.FCTextBox("TxtSerie").Text = "" + Row.FCHiddenField("HdnSerie").Value = "" + TmpDT.Rows(Index)("SerieLote") = "" + Else + Row.FCHiddenField("HdnSerie").Value = Row.FCTextBox("TxtSerie").Text + TmpDT.Rows(Index)("SerieLote") = Row.FCTextBox("TxtSerie").Text + End If + + TmpDT.AcceptChanges() + DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") + + ObjInventarios.Dispose() + UpINV.Update() + End Sub + Private Function ValidaSerieINV() As Boolean + Dim Retorno = False + Dim Existencia = 0.0 + Dim ExistenciaActual = 0.0 + Dim ObjInventarios As New ClsInventarios + + For Each Gvr As GridViewRow In GvInv.Rows + If Gvr.FCCheckBox("cbInv").Checked Then + 'VACIO + If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim = "" Then + Alert("Algun producto con salida de inventario no tiene especificada la SERIE. Por favor verifique.", TipoMensaje.MsgAdvertencia) + Retorno = True + Exit For + End If + 'SIN EXISTENCIA + If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim <> "" Then + + Existencia = ObjInventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, ddlAlmacen.SelectedValue.ToEntero, SerieLote:=Gvr.FCTextBox("TxtSerie").Text.ToString, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) + ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Gvr.FCTextBox("TxtSerie").Text.Trim)) + + 'Valida Existencia + If Existencia - ExistenciaActual < 0 Then + Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", Gvr.FCTextBox("TxtSerie").Text.ToString), TipoMensaje.MsgAdvertencia) + Gvr.FCTextBox("TxtSerie").Text = "" + Retorno = True + Exit For + End If + + End If + End If + Next + + Return Retorno End Function -#End Region +#End Region -#Region " BUSCAR CLIENTE " - Protected Sub BtnBuscarCliente_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnBuscarCliente.Click - ViewState("CveCliente") = HdnCveCliente.Value.ToEntero - CargaCliente(HdnCveCliente.Value.ToEntero) - If DdlPS.SelectedValue IsNot Nothing AndAlso DdlPS.SelectedValue.ToEntero > 0 Then - DdlPS_SelectedIndexChanged(sender, e) - DdlPS.Focus() - Else - TxtCantidad.Focus() - End If - 'DdlPS.SelectedIndex = 14 - 'DdlPS_SelectedIndexChanged(sender, e) - 'TxtCantidad.Focus() - - 'CARGA CONTRATOS - VerificarContrato() +#Region " BUSCAR CLIENTE " + Protected Sub BtnBuscarCliente_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnBuscarCliente.Click + ViewState("CveCliente") = HdnCveCliente.Value.ToEntero + CargaCliente(HdnCveCliente.Value.ToEntero) + If DdlPS.SelectedValue IsNot Nothing AndAlso DdlPS.SelectedValue.ToEntero > 0 Then + DdlPS_SelectedIndexChanged(sender, e) + DdlPS.Focus() + Else + TxtCantidad.Focus() + End If + 'DdlPS.SelectedIndex = 14 + 'DdlPS_SelectedIndexChanged(sender, e) + 'TxtCantidad.Focus() + + 'CARGA CONTRATOS + VerificarContrato() End Sub -#End Region +#End Region -#Region " INVENTARIO POR ENTREGA" - Private Sub InventarioMov(Optional CveVentaPadre As Integer = -1) - If CveVentaPadre > 0 Then - Dim ObjVentas As New ClsVentas() - If ObjVentas.GetVenta(CveVentaPadre, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados.Rows.Count > 0 AndAlso ObjVentas.DtResultados.Rows(0)("TipoDocto").ToString() = "Ing" AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then - ' Dim CveEstatusRefacturacion As Integer = ObjVentas.DtResultados.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero() - - ' If CveEstatusRefacturacion = 2 Then - CargaInventario(Me.CveVenta) - 'End If - - Else - CargaInventario(Me.CveVenta) - End If - End If - ObjVentas.Dispose() - Else - CargaInventario(Me.CveVenta) - End If - End Sub - Private Sub CargaInventario(CveVenta As Integer) - Dim ObjInv As New ClsInventarios - If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjInv.DtResultados.Rows.Count > 0 Then - CargaGVInv(ObjInv.DtResultados) - End If - End If - ObjInv.Dispose() - End Sub - Private Sub CargaGVInv(DtTemporal As DataTable) - - If Not DtTemporal.Columns.Contains("Lote") Then - DtTemporal.Columns.Add("Lote", Type.GetType("System.String")) - End If - - If Not DtTemporal.Columns.Contains("Batch") Then - DtTemporal.Columns.Add("Batch", Type.GetType("System.String")) - End If - - GvInv.Columns(4).Visible = DtTemporal.MAX("SerieLote", "SerieLote <> ''") <> "" Or CveVenta <= 0 - GvInv.Columns(5).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> "" - GvInv.Columns(6).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> "" - - GvInv.DataSource = DtTemporal - GvInv.DataBind() - UpINV.Update() +#Region " INVENTARIO POR ENTREGA" + Private Sub InventarioMov(Optional CveVentaPadre As Integer = -1) + If CveVentaPadre > 0 Then + Dim ObjVentas As New ClsVentas() + If ObjVentas.GetVenta(CveVentaPadre, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados.Rows.Count > 0 AndAlso ObjVentas.DtResultados.Rows(0)("TipoDocto").ToString() = "Ing" AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then + ' Dim CveEstatusRefacturacion As Integer = ObjVentas.DtResultados.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero() + + ' If CveEstatusRefacturacion = 2 Then + CargaInventario(Me.CveVenta) + 'End If + + Else + CargaInventario(Me.CveVenta) + End If + End If + ObjVentas.Dispose() + Else + CargaInventario(Me.CveVenta) + End If End Sub -#End Region + Private Sub CargaInventario(CveVenta As Integer) + Dim ObjInv As New ClsInventarios + If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjInv.DtResultados.Rows.Count > 0 Then + CargaGVInv(ObjInv.DtResultados) + End If + End If + ObjInv.Dispose() + End Sub + Private Sub CargaGVInv(DtTemporal As DataTable) -#Region "IMPUESTOS LOCALES" - Private Sub GvImpuestosLocales2_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvImpuestosLocales2.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow Then - 'e.Row.FCTextBox("TxtImpuestoLocalPS").Text = (TxtSubTotal.Text.ToDouble - (TxtSubTotal.Text.ToDouble * (e.Row.DBCampo("Porcentaje").ToString.ToDouble) / 100)).ToString - e.Row.FCTextBox("TxtImpuestoLocalPS").Attributes.Add("onKeyUp", String.Format("FnSuma();")) - - End If - End Sub - - - Private Function RegeneracionPolizas(ByRef ObjVentas As ClsVentas, ByRef ObjAC As ClsContPAQi) As Boolean - Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) - Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) - - Dim CvePlantillaPoliza As Integer - - Dim ErrorCancelar As Boolean = False - Dim Mensaje As String = "" - - CreaObjetosVenta() - If UsuarioActual.Empresa.UsaAC Then - ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - End If - - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - CvePlantillaPoliza = 7 - ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem", "Ant") Then - CvePlantillaPoliza = 4 - Else - CvePlantillaPoliza = 4 - End If - - 'Removemos los conceptos de la prepoliza - ObjConta.RemovePrePolizasDetalle(CvePrePoliza, -1, CveVenta, 2) - - ObjFactura.CveVenta = CveVenta - ObjFactura.CvePrePoliza = CvePrePoliza - ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, 1, ObjBancos, ObjVentas) - If Not ErrorCancelar Then ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, 1) - - Return ErrorCancelar + If Not DtTemporal.Columns.Contains("Lote") Then + DtTemporal.Columns.Add("Lote", Type.GetType("System.String")) + End If + + If Not DtTemporal.Columns.Contains("Batch") Then + DtTemporal.Columns.Add("Batch", Type.GetType("System.String")) + End If + + GvInv.Columns(4).Visible = DtTemporal.MAX("SerieLote", "SerieLote <> ''") <> "" Or CveVenta <= 0 + GvInv.Columns(5).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> "" + GvInv.Columns(6).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> "" + + GvInv.DataSource = DtTemporal + GvInv.DataBind() + UpINV.Update() + End Sub +#End Region + +#Region "IMPUESTOS LOCALES" + Private Sub GvImpuestosLocales2_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvImpuestosLocales2.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + 'e.Row.FCTextBox("TxtImpuestoLocalPS").Text = (TxtSubTotal.Text.ToDouble - (TxtSubTotal.Text.ToDouble * (e.Row.DBCampo("Porcentaje").ToString.ToDouble) / 100)).ToString + e.Row.FCTextBox("TxtImpuestoLocalPS").Attributes.Add("onKeyUp", String.Format("FnSuma();")) + + End If + End Sub + + + Private Function RegeneracionPolizas(ByRef ObjVentas As ClsVentas, ByRef ObjAC As ClsContPAQi) As Boolean + Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) + Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) + + Dim CvePlantillaPoliza As Integer + + Dim ErrorCancelar As Boolean = False + Dim Mensaje As String = "" + + CreaObjetosVenta() + If UsuarioActual.Empresa.UsaAC Then + ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + End If + + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + CvePlantillaPoliza = 7 + ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem", "Ant") Then + CvePlantillaPoliza = 4 + Else + CvePlantillaPoliza = 4 + End If + + 'Removemos los conceptos de la prepoliza + ObjConta.RemovePrePolizasDetalle(CvePrePoliza, -1, CveVenta, 2) + + ObjFactura.CveVenta = CveVenta + ObjFactura.CvePrePoliza = CvePrePoliza + ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, 1, ObjBancos, ObjVentas) + If Not ErrorCancelar Then ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, 1) + + Return ErrorCancelar End Function -#End Region +#End Region -#Region " DEVOLUCION ALMACEN " - Private Sub InicializaDevolucionAlmacen() - If Not GvInv.Rows.Count > 0 Then - Exit Sub - End If - - - If CveVenta > 0 AndAlso SaldoVenta = TxtTotal.Text.ToDecimal Then 'And (DdlTipoComprobante.SelectedValue.Contiene({"Rem", "Ped"}) Or (DdlTipoComprobante.SelectedValue.Contiene({"Ing"}) And TxtFecha.Text.ToDate.Month = Now.Month And TxtFecha.Text.ToDate.Year = Now.Year)) Then - - If Not DevolucionAlmacen = 2 Then - 'If UsuarioActual.Empresa.Funcionalidad(555) = "1" Then - - LiDevolucionAlmacen.Visible = True - - 'End If - End If - - If DevolucionAlmacen = 1 Then - LBDevolucionAlmacen.Text = " Cancelar Devolución Almacén" - LBDevolucionAlmacen.ToolTip = "¿Está seguro de Cancelar la Devolución de Almacén?" - Else - LBDevolucionAlmacen.Text = " Solicitar Devolución Almacén" - LBDevolucionAlmacen.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) - Dim ObjVentas As New ClsVentas - - Dim EstatusDevolucion = If(DevolucionAlmacen = 0, 1, 0) - - If ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then - Alert("La solicitud de Devolución de Almacén se guardó correctamente") - End If - - DevolucionAlmacen = EstatusDevolucion - InicializaDevolucionAlmacen() - UpnTools.Update() - - ObjVentas.Dispose() +#Region " DEVOLUCION ALMACEN " + Private Sub InicializaDevolucionAlmacen() + If Not GvInv.Rows.Count > 0 Then + Exit Sub + End If + + + If CveVenta > 0 AndAlso SaldoVenta = TxtTotal.Text.ToDecimal Then 'And (DdlTipoComprobante.SelectedValue.Contiene({"Rem", "Ped"}) Or (DdlTipoComprobante.SelectedValue.Contiene({"Ing"}) And TxtFecha.Text.ToDate.Month = Now.Month And TxtFecha.Text.ToDate.Year = Now.Year)) Then + + If Not DevolucionAlmacen = 2 Then + 'If UsuarioActual.Empresa.Funcionalidad(555) = "1" Then + + LiDevolucionAlmacen.Visible = True + + 'End If + End If + + If DevolucionAlmacen = 1 Then + LBDevolucionAlmacen.Text = " Cancelar Devolución Almacén" + LBDevolucionAlmacen.ToolTip = "¿Está seguro de Cancelar la Devolución de Almacén?" + Else + LBDevolucionAlmacen.Text = " Solicitar Devolución Almacén" + LBDevolucionAlmacen.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) + Dim ObjVentas As New ClsVentas + + Dim EstatusDevolucion = If(DevolucionAlmacen = 0, 1, 0) + + If ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then + Alert("La solicitud de Devolución de Almacén se guardó correctamente") + End If + + DevolucionAlmacen = EstatusDevolucion + InicializaDevolucionAlmacen() + UpnTools.Update() + + ObjVentas.Dispose() End Sub -#End Region +#End Region + +#Region "D I R E C C I O N E N V I O" + Private Sub CargaDireccionesEnvio() + Dim ObjClientes As New ClsClientes + Dim TieneError = False + + DdlDireccionEnvio.Items.Clear() + If ObjClientes.DireccionEnvioGet(-1, CveCliente, CveClienteSucursal) Then + DdlDireccionEnvio.DataSource = ObjClientes.DtResultados.FiltraParametros(String.Format("Estatus = 1")) + DdlDireccionEnvio.DataBind() + 'DdlDireccionEnvio.Items.Insert(0, New ListItem("Seleccione", "-1")) + TmpDTEnvioDireccion = ObjClientes.DtResultados + Else + TieneError = True + End If + + If TieneError Then + Alert("Ocurrió un error al obtener las direcciones de envío", TipoMensaje.MsgError) + End If + + ObjClientes.Dispose() + UpCliente.Update() -#Region "D I R E C C I O N E N V I O" - Private Sub CargaDireccionesEnvio() - Dim ObjClientes As New ClsClientes - Dim TieneError = False - - DdlDireccionEnvio.Items.Clear() - If ObjClientes.DireccionEnvioGet(-1, CveCliente, CveClienteSucursal) Then - DdlDireccionEnvio.DataSource = ObjClientes.DtResultados.FiltraParametros(String.Format("Estatus = 1")) - DdlDireccionEnvio.DataBind() - 'DdlDireccionEnvio.Items.Insert(0, New ListItem("Seleccione", "-1")) - TmpDTEnvioDireccion = ObjClientes.DtResultados - Else - TieneError = True - End If - - If TieneError Then - Alert("Ocurrió un error al obtener las direcciones de envío", TipoMensaje.MsgError) - End If - - ObjClientes.Dispose() - UpCliente.Update() - - End Sub - Private Sub ChkDireccionEnvio_CheckedChanged(sender As Object, e As EventArgs) Handles ChkDireccionEnvio.CheckedChanged - If ChkDireccionEnvio.Checked Then - DdlDireccionEnvio.Visible = True - LnkOtraDireccion.Visible = True - Else - DdlDireccionEnvio.Visible = False - LnkOtraDireccion.Visible = False - End If - End Sub - Private Sub BtnAgregarDireccion_Click(sender As Object, e As EventArgs) Handles BtnAgregarDireccion.Click - Dim ObjClientes As New ClsClientes - Dim TieneError = False - Dim CveDireccionEnvio As Integer - - CveDireccionEnvio = ObjClientes.DireccionEnvioAdd(CveCliente, TxtDireccion.Text.Trim, TxtNoExt.Text.Trim, TxtNoInt.Text.Trim, TxtColonia.Text.Trim, TxtCiudad.Text.Trim, TxtEstado.Text.Trim, TxtCP.Text.ToEntero, TxtContacto.Text.Trim, UsuarioActual.CveUsuario, 1, CveClienteSucursal:=CveClienteSucursal, EnvioDepartamento:=If(TxtDepartamento.Text.Trim = "", "-1", TxtDepartamento.Text.Trim)) - - If CveDireccionEnvio < 0 Then - TieneError = True - End If - - If Not TieneError Then - TxtDireccion.Text = "" - TxtColonia.Text = "" - TxtCiudad.Text = "" - TxtEstado.Text = "" - TxtCP.Text = "" - TxtNoExt.Text = "" - TxtNoInt.Text = "" - TxtContacto.Text = "" - TxtDepartamento.Text = "" - CargaDireccionesEnvio() - DdlDireccionEnvio.SelectedValueExist(CveDireccionEnvio) - End If - - ObjClientes.Dispose() - RegistraScript("$('#divAddDireccionEnvio').modal('hide');LimpiaModal();") - End Sub - Private Sub LnkOtraDireccion_Click(sender As Object, e As EventArgs) Handles LnkOtraDireccion.Click - TxtDireccion.Text = LblDireccion.Text.Trim - TxtNoExt.Text = CliNoExt.Trim - TxtNoInt.Text = CliNoInt.Trim - TxtColonia.Text = LblColonia.Text.Trim - TxtCiudad.Text = LblCiudad.Text.Trim - TxtEstado.Text = LblEstado.Text.Trim - TxtCP.Text = LblCP.Text.Trim - UpBodyDireccion.Update() - RegistraScript("$('#divAddDireccionEnvio').modal();") End Sub -#End Region + Private Sub ChkDireccionEnvio_CheckedChanged(sender As Object, e As EventArgs) Handles ChkDireccionEnvio.CheckedChanged + If ChkDireccionEnvio.Checked Then + DdlDireccionEnvio.Visible = True + LnkOtraDireccion.Visible = True + Else + DdlDireccionEnvio.Visible = False + LnkOtraDireccion.Visible = False + End If + End Sub + Private Sub BtnAgregarDireccion_Click(sender As Object, e As EventArgs) Handles BtnAgregarDireccion.Click + Dim ObjClientes As New ClsClientes + Dim TieneError = False + Dim CveDireccionEnvio As Integer + + CveDireccionEnvio = ObjClientes.DireccionEnvioAdd(CveCliente, TxtDireccion.Text.Trim, TxtNoExt.Text.Trim, TxtNoInt.Text.Trim, TxtColonia.Text.Trim, TxtCiudad.Text.Trim, TxtEstado.Text.Trim, TxtCP.Text.ToEntero, TxtContacto.Text.Trim, UsuarioActual.CveUsuario, 1, CveClienteSucursal:=CveClienteSucursal, EnvioDepartamento:=If(TxtDepartamento.Text.Trim = "", "-1", TxtDepartamento.Text.Trim)) + + If CveDireccionEnvio < 0 Then + TieneError = True + End If + + If Not TieneError Then + TxtDireccion.Text = "" + TxtColonia.Text = "" + TxtCiudad.Text = "" + TxtEstado.Text = "" + TxtCP.Text = "" + TxtNoExt.Text = "" + TxtNoInt.Text = "" + TxtContacto.Text = "" + TxtDepartamento.Text = "" + CargaDireccionesEnvio() + DdlDireccionEnvio.SelectedValueExist(CveDireccionEnvio) + End If + + ObjClientes.Dispose() + RegistraScript("$('#divAddDireccionEnvio').modal('hide');LimpiaModal();") + End Sub + Private Sub LnkOtraDireccion_Click(sender As Object, e As EventArgs) Handles LnkOtraDireccion.Click + TxtDireccion.Text = LblDireccion.Text.Trim + TxtNoExt.Text = CliNoExt.Trim + TxtNoInt.Text = CliNoInt.Trim + TxtColonia.Text = LblColonia.Text.Trim + TxtCiudad.Text = LblCiudad.Text.Trim + TxtEstado.Text = LblEstado.Text.Trim + TxtCP.Text = LblCP.Text.Trim + UpBodyDireccion.Update() + RegistraScript("$('#divAddDireccionEnvio').modal();") + End Sub +#End Region + +#Region " CARGA FACTURA OC " + Private Sub CargaFacturaOC() + + + CveOC = IfNull(Request("CveOC"), -1).ToString.ToEntero + + If CveOC > 0 Then + Dim tDT As DataTable = Nothing + Dim ObjOC As New ClsOC + If ObjOC.GetOCFacturacion(CveOC, UsuarioActual.CveEmpresa) Then + tDT = ObjOC.DtResultados + 'tTmpDT.Columns.Add("TipoDocto", GetType(String)) + 'tTmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) + 'tTmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) + Else + Alert("Ocurrió un error al obtener los detalles de la orden de compra. Por favor vuelva a intentar.", TipoMensaje.MsgError) + End If + ObjOC.Dispose() + + + If tDT IsNot Nothing AndAlso tDT.Rows.Count > 0 Then + + + ViewState("CveCliente") = ObjOC.DtResultados.Rows(0)("CveCliente") + HdnCveCliente.Value = CveCliente.ToString + CargaCliente(CveCliente) + + For Each Dr As DataRow In tDT.Rows + + AgregarProductoServicio(Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, + Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, + Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, + CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero) + Next + + 'GvPS.DataSource = TmpDT + 'GvPS.DataBind() + + 'TxtSubTotal.Text = TmpDT.SUM("Total").FormatoNumero(2) + 'TxtIVA.Text = (TxtSubTotal.Text.ToDecimal * ViewState("IVA").ToString.ToDecimal).ToString + 'CalculaTotalesImpuestosLocales() + 'CalculaTotales(False) + UpPS.Update() + + + VerificarContrato(True) + + If UsuarioActual.TienePermisoProceso(175) Then + DdlTipoComprobante.Items.FindByText("Egresos").Enabled = False + End If + DdlTipoComprobante.Items.FindByText("Cotización").Enabled = False + DdlTipoComprobante.Items.FindByText("Anticipos").Enabled = False + + 'DESACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto disabled") + TxtCodigo.ReadOnly = True + + + UpCliente.Update() + + tDT.Dispose() + Else + Alert("No se encontró la orden de compra especificada. Por favor verifique y vuelta a intentar.", TipoMensaje.MsgAdvertencia) + End If + CalculaTotalesVenta() + End If + -#Region " CARGA FACTURA OC " - Private Sub CargaFacturaOC() - - - CveOC = IfNull(Request("CveOC"), -1).ToString.ToEntero - - If CveOC > 0 Then - Dim tDT As DataTable = Nothing - Dim ObjOC As New ClsOC - If ObjOC.GetOCFacturacion(CveOC, UsuarioActual.CveEmpresa) Then - tDT = ObjOC.DtResultados - 'tTmpDT.Columns.Add("TipoDocto", GetType(String)) - 'tTmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) - 'tTmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) - Else - Alert("Ocurrió un error al obtener los detalles de la orden de compra. Por favor vuelva a intentar.", TipoMensaje.MsgError) - End If - ObjOC.Dispose() - - - If tDT IsNot Nothing AndAlso tDT.Rows.Count > 0 Then - - - ViewState("CveCliente") = ObjOC.DtResultados.Rows(0)("CveCliente") - HdnCveCliente.Value = CveCliente.ToString - CargaCliente(CveCliente) - - For Each Dr As DataRow In tDT.Rows - - AgregarProductoServicio(Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, - Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, - Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, - CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero) - Next - - 'GvPS.DataSource = TmpDT - 'GvPS.DataBind() - - 'TxtSubTotal.Text = TmpDT.SUM("Total").FormatoNumero(2) - 'TxtIVA.Text = (TxtSubTotal.Text.ToDecimal * ViewState("IVA").ToString.ToDecimal).ToString - 'CalculaTotalesImpuestosLocales() - 'CalculaTotales(False) - UpPS.Update() - - - VerificarContrato(True) - - If UsuarioActual.TienePermisoProceso(175) Then - DdlTipoComprobante.Items.FindByText("Egresos").Enabled = False - End If - DdlTipoComprobante.Items.FindByText("Cotización").Enabled = False - DdlTipoComprobante.Items.FindByText("Anticipos").Enabled = False - - 'DESACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto disabled") - TxtCodigo.ReadOnly = True - - - UpCliente.Update() - - tDT.Dispose() - Else - Alert("No se encontró la orden de compra especificada. Por favor verifique y vuelta a intentar.", TipoMensaje.MsgAdvertencia) - End If - CalculaTotalesVenta() - End If - - End Sub -#End Region +#End Region -#Region "CargaFactura" - Private Function CargaFactura(CveFactura As Integer) As String - Dim RFC As String = "" - - Dim XMLDoc As New XmlDocument - Dim Archivo As String = String.Format("{0}Empresas\{1}\Ventas\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Request("RFC"), $"{Request("CveFactura")}.xml") - If IO.File.Exists(Archivo) Then - - Dim Validada As Boolean = True - - - LbAgregar.Visible = False - - - If Validada Then - - XMLDoc.Load(Archivo) - - CreaDTConceptos() - CargaConceptosXML(XMLDoc) - - CargaComprobanteXML(XMLDoc) - Select Case TipoComprobante - Case "ingreso" : DdlTipoComprobante.SelectedValue = "Ing" - Case "egreso" : DdlTipoComprobante.SelectedValue = "Egs" - End Select - - - RFC = ReceptorRFC - TxtFecha.Text = Fecha - TxtFolio.Text = FolioXML.ToString - If (FolioXML <> "") Then - ViewState("ExFolioFactura") = True - End If - - - - Dim IVA As Decimal - IVA = TrasladoIVA - - If Not UsuarioActual.TienePermisoProceso(130) Then - TxtFolio.Enabled = False - End If - - DdlTipoComprobante.Enabled = False - TxtFecha.Enabled = False - ImgFecha.Enabled = False - TxtSubTotal.Enabled = False - TxtSubTotal2.Enabled = False - TxtIVA.Enabled = False - 'TxtTotal.Enabled = False - RegistraScript("SetDisabledTxtTotal(true);") - If TxtFolio.Text.Trim = "" Then TxtFolio.Enabled = True - - If UsuarioActual.TienePermisoProceso(112) Then - TxtSubTotal.Enabled = True - TxtSubTotal2.Enabled = True - TxtIVA.Enabled = True - 'TxtTotal.Enabled = True - RegistraScript("SetDisabledTxtTotal(false);") - End If - - TxtIVA.Text = IVA.FormatoNumero - TxtRetIVA.Text = RetencionIVA.FormatoNumero - LblDescuentos.Text = Descuentos.FormatoNumero - TxtFecha.Text = Fecha.ToDate.ToShortDateString - - Dim Msg As String = "" - - 'PRUEBA - 'http://rm/Compras/Compras.aspx?CveFactura=122518 Emp: 48 - - 'tTotal = Math.Round(SubTotal2 + IVA - RetencionIVA - RetencionISR + IEPS + OtrosImpuestos, 2) - - Dim AjustaUltimoConcepto = False - - '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 = Math.Round(Total + RetencionISR + RetencionIVA - IVA + Descuentos, 2) ' NO se incluye otros impuestos para ajustar esa cifra - Dim DiferenciaTotales As Decimal = SubTotalReal - Math.Round(SubTotalConceptos, 2) - ViewState("Folio") = FolioXML - - End If - - Else - Alert("No se encontró la factura", TipoMensaje.MsgAdvertencia) - End If - - 'GvPS.DataSource = 'DTConceptos - 'GvPS.DataBind() - - - - - Return RFC - End Function - Private Sub CreaDTConceptos() - DTConceptos = New DataTable - DTConceptos.Columns.Add("Consec", GetType(Integer)) - DTConceptos.Columns.Add("Cantidad", GetType(Decimal)) - DTConceptos.Columns.Add("UM", GetType(String)) - DTConceptos.Columns.Add("CveClasificacion", GetType(Integer)) - DTConceptos.Columns.Add("PS", GetType(String)) - DTConceptos.Columns.Add("PU", GetType(Decimal)) - DTConceptos.Columns.Add("Descuento", GetType(Decimal)) - DTConceptos.Columns.Add("IVA", GetType(Decimal)) - DTConceptos.Columns.Add("Total", GetType(Decimal)) - End Sub - Private Sub CargaConceptosXML(XMLDoc As XmlDocument) - Dim i As Integer = 0 - Dim node As XmlNode - Dim PU As Decimal = 0 - Dim Descuento As Double = 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 - - 'GLOBALS - Dim DtUM = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa).AsEnumerable - Dim DtUMAlias = GlobalDTUnidadesMedidaAlias(UsuarioActual.CveEmpresa).AsEnumerable - 'Dim DtPS = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).AsEnumerable - Dim DtPS = GlobalDTPS(UsuarioActual.CveEmpresa).AsEnumerable - Dim DtPSAlias = GlobalDTProductosServiciosAlias(UsuarioActual.CveEmpresa).AsEnumerable - - ''AGREGA EN TABLA TEMPORAL - 'Dim DtPSTemp = TmpDT.Clone - 'Dim Row As DataRow = Nothing - - - For i = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1 - - ' 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 - - - '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").ToDouble <= 0 And ValorXML(node, "importe").ToDouble > 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.ToDouble - - '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(" ", " ") - 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 - Else - tCvePS = 20168 - 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 - - '' AGREGA PS - 'AGREGA A TMPDT - 'AddPS(ValorXML(node, "cantidad").ToDouble, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, TipoPS, "-1", "SE", "SE", Obs, PU, Total, 0, 0, PSCodigo:=tPSCodigo, TCalculaTotales:=False) - AgregarProductoServicio(ValorXML(node, "cantidad").ToDecimal, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, Obs, PU, 0, 0, "", 0, "") - - - Next - - CalculaTotalesVenta() - 'AddPS2(False) - - - 'Dim SubTotalConceptos = Math.Round(SubTotalTemp, 2) - 'TmpDT = DtPSTemp.Copy - 'DtPSTemp.Dispose() - - End Sub - Private Sub CargaComprobanteXML(XMLDoc As XmlDocument) - Dim nodo As XmlNode = XMLDoc.DocumentElement - - _SerieXML = ValorXML(nodo, "serie") - If _SerieXML <> "" Then _SerieXML = _SerieXML - - _Version = ValorXML(nodo, "version") - _FolioXML = 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") - - - Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) - Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" - Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) - - 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 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") - 'EmisorNombre = ValorXML(node, "nombre") - End If - 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 - - 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}:Retencion", Prefijo), namespaces) - - TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDecimal - - For Each retencion As XmlNode In nodeRetenciones - If retencion.Attributes("impuesto").Value = "IVA" Then - RetencionIVA += retencion.Attributes("importe").Value.ToDecimal - End If - If retencion.Attributes("impuesto").Value = "ISR" Then - RetencionISR += retencion.Attributes("importe").Value.ToDecimal - End If - ' Do something. - Next - SumaTotalRetenciones += RetencionIVA - SumaTotalRetenciones += RetencionISR - - TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDecimal - - Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) - For Each traslado As XmlNode In nodeTraslados - If traslado.Attributes("impuesto").Value = "IVA" Then - TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal - End If - If traslado.Attributes("impuesto").Value = "IEPS" Then - TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal - End If - 'If traslado.Attributes("impuesto").Value = "ISR" Then - ' TrasladoISR = traslado.Attributes("importe").Value - 'End If - ' Do something. - Next - 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 - _FolioXML = 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 - - If RetencionIVA <= 0 AndAlso ValorXML(node, "TotaldeRetenciones", "0").ToDouble > 0 Then RetencionIVA = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal - - - 'For Each retencion As XmlNode In nodeImpLocales - ' If retencion.Attributes("impuesto").Value = "IVA" Then - ' RetencionIVA += retencion.Attributes("importe").Value.ToDouble - ' End If - ' If retencion.Attributes("impuesto").Value = "ISR" Then - ' RetencionISR += retencion.Attributes("importe").Value.ToDouble - ' End If - ' ' Do something. - 'Next - ' SumaTotalRetenciones += RetencionIVA - ' SumaTotalRetenciones += RetencionISR - - 'TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble - - 'Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) - 'For Each traslado As XmlNode In nodeTraslados - ' If traslado.Attributes("impuesto").Value = "IVA" Then - ' TrasladoIVA += traslado.Attributes("importe").Value.ToDouble - ' End If - ' If traslado.Attributes("impuesto").Value = "IEPS" Then - ' TrasladoIEPS += traslado.Attributes("importe").Value.ToDouble - ' End If - ' 'If traslado.Attributes("impuesto").Value = "ISR" Then - ' ' TrasladoISR = traslado.Attributes("importe").Value - ' 'End If - ' ' Do something. - 'Next - 'SumaTotalTraslados += TrasladoIVA - 'SumaTotalTraslados += TrasladoIEPS - End If - - End If - - - - - End Sub - 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 +#Region "CargaFactura" + Private Function CargaFactura(CveFactura As Integer) As String + Dim RFC As String = "" + + Dim XMLDoc As New XmlDocument + Dim Archivo As String = String.Format("{0}Empresas\{1}\Ventas\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Request("RFC"), $"{Request("CveFactura")}.xml") + If IO.File.Exists(Archivo) Then + + Dim Validada As Boolean = True + + + LbAgregar.Visible = False + + + If Validada Then + + XMLDoc.Load(Archivo) + + CreaDTConceptos() + CargaConceptosXML(XMLDoc) + + CargaComprobanteXML(XMLDoc) + Select Case TipoComprobante + Case "ingreso" : DdlTipoComprobante.SelectedValue = "Ing" + Case "egreso" : DdlTipoComprobante.SelectedValue = "Egs" + End Select + + + RFC = ReceptorRFC + TxtFecha.Text = Fecha + TxtFolio.Text = FolioXML.ToString + If (FolioXML <> "") Then + ViewState("ExFolioFactura") = True + End If + + + + Dim IVA As Decimal + IVA = TrasladoIVA + + If Not UsuarioActual.TienePermisoProceso(130) Then + TxtFolio.Enabled = False + End If + + DdlTipoComprobante.Enabled = False + TxtFecha.Enabled = False + ImgFecha.Enabled = False + TxtSubTotal.Enabled = False + TxtSubTotal2.Enabled = False + TxtIVA.Enabled = False + 'TxtTotal.Enabled = False + RegistraScript("SetDisabledTxtTotal(true);") + If TxtFolio.Text.Trim = "" Then TxtFolio.Enabled = True + + If UsuarioActual.TienePermisoProceso(112) Then + TxtSubTotal.Enabled = True + TxtSubTotal2.Enabled = True + TxtIVA.Enabled = True + 'TxtTotal.Enabled = True + RegistraScript("SetDisabledTxtTotal(false);") + End If + + TxtIVA.Text = IVA.FormatoNumero + TxtRetIVA.Text = RetencionIVA.FormatoNumero + LblDescuentos.Text = Descuentos.FormatoNumero + TxtFecha.Text = Fecha.ToDate.ToShortDateString + + Dim Msg As String = "" + + 'PRUEBA + 'http://rm/Compras/Compras.aspx?CveFactura=122518 Emp: 48 + + 'tTotal = Math.Round(SubTotal2 + IVA - RetencionIVA - RetencionISR + IEPS + OtrosImpuestos, 2) + + Dim AjustaUltimoConcepto = False + + '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 = Math.Round(Total + RetencionISR + RetencionIVA - IVA + Descuentos, 2) ' NO se incluye otros impuestos para ajustar esa cifra + Dim DiferenciaTotales As Decimal = SubTotalReal - Math.Round(SubTotalConceptos, 2) + ViewState("Folio") = FolioXML + + End If + + Else + Alert("No se encontró la factura", TipoMensaje.MsgAdvertencia) + End If + + 'GvPS.DataSource = 'DTConceptos + 'GvPS.DataBind() + + + + + Return RFC End Function -#End Region - -#Region "Metodos Viejos" - Private Sub GeneraPDF(FechaFactura As DateTime, FolioFiscal As String, NoSerieCertificado As String, FechaCertificacion As DateTime, NoSerieCertificadoContribuyente As String, - DTConceptos As DataTable, SelloCFDi As String, SelloSAT As String, CBB As String, Folio As String, RutaXML As String, EsVistaPrevia As Boolean, MuestraAlert As Boolean, Optional MR As ReportViewer = Nothing) - - Alert("No se pudo generar el PDF", TipoMensaje.MsgError) - - End Sub - Private Sub GeneraPDFCBB(FechaFactura As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean) - - End Sub - Private Sub GeneraPDFCot(FechaCotizacion As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean, GeneraDescarga As Boolean) - - End Sub - Private Sub LkEliminarFactura_Click(sender As Object, e As EventArgs) Handles LkEliminarFactura.Click - If HdnPagado.Value.ToDecimal = 0 Then - Dim ObjVentas As New ClsVentas - ObjVentas.IniciaTransacSQL() - - If ObjVentas.EliminarVenta(CveVenta) Then - ObjVentas.Commit() - Alert("La venta ha sido eliminada correctamente.", TipoMensaje.MsgInformacion) - Else - ObjVentas.RollBack() - End If - - ObjVentas.Dispose() - Else - Alert("La venta no se puede eliminar ya que tiene pagos vinculados.", TipoMensaje.MsgError) - End If - End Sub - Private Sub RblComplementos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblComplementos.SelectedIndexChanged - If RblComplementos.SelectedValue.Contiene("5", "6") Then 'Directivo/Ejecutivo Estatal - trEntidad.Visible = True - trContaComplementos.Visible = True - trAmbito.Visible = False - trTipoCampaña.Visible = False - - ElseIf RblComplementos.SelectedValue = "7" Then 'Ejecutivo Nacional - trEntidad.Visible = False - trContaComplementos.Visible = True - trAmbito.Visible = False - trTipoCampaña.Visible = False - - ElseIf RblComplementos.SelectedValue = "8" Then 'Campaña/PreCampaña - trEntidad.Visible = True - trContaComplementos.Visible = True - trAmbito.Visible = True - trTipoCampaña.Visible = True - - End If - - UpDatosComplementos.Update() - End Sub - Private Sub GvPS_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPS.RowCommand - If e.CommandName = "Clonar" Then - Dim RowNum As Integer = Convert.ToInt32(e.CommandArgument) - Dim GvRow As GridViewRow = GvPS.Rows(RowNum) - TxtCantidad.Text = GvPS.Rows(RowNum).FCLiteral("LtlCantidad").Text - DdlClasificacion.SelectedValue = GvRow.DataKey("CveClasificacion") - DdlPS.SelectedValue = GvRow.DataKey("CvePS") - DdlPS_SelectedIndexChanged(Nothing, Nothing) - DdlUnidadMedida.SelectedValue = GvRow.DataKey("CveUM") - TxtObsPS.Text = GvRow.FCLiteral("LtlObsPS").Text - DdlProyecto.SelectedValue = GvRow.DataKey("CveProyecto") - DdlProyecto_SelectedIndexChanged(Nothing, Nothing) - DdlSubProyecto.SelectedValue = GvRow.DataKey("CveSubProyecto") - TxtPrecio.Text = GvRow.FCLiteral("LtlPU").Text - RegistraScript("Recalcula();") - LbAgregar_Click(Nothing, Nothing) - End If - End Sub - Protected Sub OrdenarGvPS(ByVal sender As Object, ByVal e As EventArgs) - - For Each row As GridViewRow In GvPS.Rows - TmpDT.Rows(row.RowIndex)("Orden") = row.FCTextBox("TxtOrden").Text.ToEntero - Next - - Dim resultados = From OrdenDT In TmpDT - Order By OrdenDT("Orden").ToString.ToEntero - Select OrdenDT - TmpDT = resultados.CopyToDataTable - CalculaTotalesVenta() - - GvPS.DataSource = TmpDT - GvPS.DataBind() - UpPS.Update() - - End Sub - Private Sub LkCotizacionAutorizar_Click(sender As Object, e As EventArgs) Handles LkCotizacionAutorizar.Click - EsSupervisor = True - GeneraPDFCotizacion(True) - Alert("La cotización ha sido enviada al correo de nuestro cliente:" & Mail) + Private Sub CreaDTConceptos() + DTConceptos = New DataTable + DTConceptos.Columns.Add("Consec", GetType(Integer)) + DTConceptos.Columns.Add("Cantidad", GetType(Decimal)) + DTConceptos.Columns.Add("UM", GetType(String)) + DTConceptos.Columns.Add("CveClasificacion", GetType(Integer)) + DTConceptos.Columns.Add("PS", GetType(String)) + DTConceptos.Columns.Add("PU", GetType(Decimal)) + DTConceptos.Columns.Add("Descuento", GetType(Decimal)) + DTConceptos.Columns.Add("IVA", GetType(Decimal)) + DTConceptos.Columns.Add("Total", GetType(Decimal)) End Sub -#End Region + Private Sub CargaConceptosXML(XMLDoc As XmlDocument) + Dim i As Integer = 0 + Dim node As XmlNode + Dim PU As Decimal = 0 + Dim Descuento As Double = 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 + + 'GLOBALS + Dim DtUM = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa).AsEnumerable + Dim DtUMAlias = GlobalDTUnidadesMedidaAlias(UsuarioActual.CveEmpresa).AsEnumerable + 'Dim DtPS = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).AsEnumerable + Dim DtPS = GlobalDTPS(UsuarioActual.CveEmpresa).AsEnumerable + Dim DtPSAlias = GlobalDTProductosServiciosAlias(UsuarioActual.CveEmpresa).AsEnumerable + + ''AGREGA EN TABLA TEMPORAL + 'Dim DtPSTemp = TmpDT.Clone + 'Dim Row As DataRow = Nothing + + + For i = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1 + + ' 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 + + + '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").ToDouble <= 0 And ValorXML(node, "importe").ToDouble > 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.ToDouble + + '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(" ", " ") + 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 + Else + tCvePS = 20168 + 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 + + '' AGREGA PS + 'AGREGA A TMPDT + 'AddPS(ValorXML(node, "cantidad").ToDouble, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, TipoPS, "-1", "SE", "SE", Obs, PU, Total, 0, 0, PSCodigo:=tPSCodigo, TCalculaTotales:=False) + AgregarProductoServicio(ValorXML(node, "cantidad").ToDecimal, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, Obs, PU, 0, 0, "", 0, "") + + + Next + + CalculaTotalesVenta() + 'AddPS2(False) + + + 'Dim SubTotalConceptos = Math.Round(SubTotalTemp, 2) + 'TmpDT = DtPSTemp.Copy + 'DtPSTemp.Dispose() -#Region "Cancelar, Generar y mandar por correo el acuse de cancelación." - Private Sub BtnEnviarMailCancelacion_Click(sender As Object, e As EventArgs) Handles BtnEnviarMailCancelacion.Click - ImprimeCancelacion(CveVenta) - End Sub - Public Sub ImprimeCancelacion(CveVenta As Integer) - Dim ObjVentas As New ClsVentas - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) - Dim FolioFiscal = drv("FolioFiscal").ToString - Dim SelloCancelacion = drv("SelloCancelacion").ToString - Dim FechaCancelacion = drv("FechaCancelacion").ToString.ToDateTime.ToString("dd/MM/yyyy HH:mm:ss") - Dim RFC = UsuarioActual.Empresa.RFC - Dim Archivo As New System.IO.FileInfo("Empresas\Grales\Formatos\AcuseCancelacion.rdlc") - Dim params As New List(Of ReportParameter) - params.Add(New ReportParameter("FechaCancelacion", FechaCancelacion.ToString)) - params.Add(New ReportParameter("FolioFiscal", FolioFiscal)) - params.Add(New ReportParameter("RFCEmisor", RFC)) - params.Add(New ReportParameter("SelloCancelacion", SelloCancelacion)) - - Dim ObjetoPDF As Byte() = StreamPDF("Empresas\Grales\Formatos\AcuseCancelacion.rdlc", ObjVentas.DtResultados, params, "AcuseCancelacion" & CveVenta) - Dim ObjMail As New ClsSisMail - Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) - Dim Asunto As String = String.Empty - Dim Cuerpo As String = String.Empty - Dim ResultadoMail As Integer - Dim sb As New StringBuilder() - If UsuarioActual.CveEmpresa = 119 Then - sb.Append("") - sb.Append("") - sb.Append("") - sb.Append("") - sb.Append(" Acuse De Cancelación") - sb.Append(" ") - sb.Append("") - sb.Append("") - sb.Append(" ") - sb.Append($" Estimado Cliente {NombreCliente},

    ") - sb.Append($" Le informamos que Agroquímicos JAM, S.A. DE C.V ha cancelado el CFDI {Serie}-{Folio}, el cual ha quedado sin Efectos Fiscales y encontrará adjunto en este correo el Acuse de
    ") - sb.Append($" cancelación del SAT.
    ") - sb.Append(" POR LO QUE PEDIMOS ELIMINARLO Y NO INCLUIRLO EN SU CONTABILIDAD, YA QUE PUEDE REPRESENTAR UN PROBLEMA FISCAL PARA USTED O SU EMPRESA CUANDO EL SAT REALICE UNA FUTURA AUDITORIA
    ") - sb.Append(" EN SU CONTABILIDAD.
    ") - sb.Append(" ") - sb.Append("




    ") - sb.Append(" Este correo se generó automaticamente, favor de no responder este mensaje.") - sb.Append("
    ") - sb.Append("") - sb.Append("") - Else - sb.Append("") - sb.Append("") - sb.Append("") - sb.Append("") - sb.Append(" Acuse De Cancelación") - sb.Append(" ") - sb.Append("") - sb.Append("") - sb.Append(" ") - sb.Append($" Estimado Cliente {NombreCliente},

    ") - sb.Append($" A través del presente medio la Empresa {UsuarioActual.Empresa.Empresa} - {RFC}, canceló el documento tipo {DdlTipoComprobante.SelectedItem.Text}
    ") - sb.Append($" con folio {Serie}-{Folio} y el Importe de ${TxtTotal.Text}.

    ") - sb.Append(" Le hacemos llegar el acuse de cancelación.
    ") - sb.Append(" ") - sb.Append("




    ") - sb.Append(" Este correo se generó automaticamente, favor de no responder este mensaje.") - sb.Append("
    ") - sb.Append("") - sb.Append("") - End If - Asunto = $"Acuse de Cancelacion {Serie}-{Folio}" - Cuerpo = sb.ToString - Dim DisplayName As String = "" - If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM" - LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.ArchivoBinario = ObjetoPDF, .NombreArchivo = $"AcuseCancelacion{Serie}-{Folio}.pdf"}) - If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then - ResultadoMail = 1 - Alert("El acuse de cancelación ha sido envíado correctamente.") - Else - ResultadoMail = 0 - End If - - End If - End Sub - - Private Sub LbCancelarDocumento_Click(sender As Object, e As EventArgs) Handles LbCancelarDocumento.Click - If VentaSaldoAlmacen > 0 Then - Alert("El pedido no se puede cancelar ya que tiene movimientos de almacén.
    Nota: Primero hay que hacer la devolución al almacén", TipoMensaje.MsgAdvertencia) - Else - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then - Dim sb As New StringBuilder() - sb.Append("La factura se encuentra en el siguiente estatus del SAT:
    ") - - Dim TotalT As Decimal = TxtTotal.Text.ToDecimal - Dim RFCReceptor As String = LblRFC.Text.Trim - Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True) - If Vigencia IsNot Nothing Then - If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then - Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - If String.IsNullOrEmpty(Vigencia.EsCancelable) Then - sb.Append("No encontrado
    ") - Else - sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) - End If - Else - sb.Append("No encontrado
    ") - End If - - sb.Append("Está seguro de cancelar el documento?.") - - LblCancelarDocumento.Text = sb.ToString() - - RegistraScript("$('#ModalCancelarDocumento').modal();") - UpCancelarDocumento.Update() - 'Alert(sb.ToString(), TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnCancelarDocumentoConfirmar()", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") - Else - CancelarDocumento() - End If - End If - - End Sub - Protected Sub BtnCancelarDocumento_Click(sender As Object, e As EventArgs) - CancelarDocumento() - RegistraScript("$('#ModalCancelarDocumento').modal('hide');") - End Sub - - Private Sub CancelarRefacturada() - Dim CancelacionFecha As Date - Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() - Dim CancelacionAcuse As String = "" - Dim Mensaje As String = "" - Dim ObjCancelacion As New Timbrado - Dim TotalT As Decimal = TxtTotal.Text.ToDecimal - Dim RFCReceptor As String = LblRFC.Text.Trim - Dim CvePACCancelacion As Integer = CvePAC - Dim CveEstatus As Integer = 4 - - Try - If FolioFiscal <> "" Then - If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then - 'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017 - CancelacionFecha = ObjCancelacion.CancelacionFecha - CancelacionAcuse = ObjCancelacion.CancelacionAcuse - CveEstatus = 5 - Else - Alert("La factura no se pudo cancelar ante el SAT", TipoMensaje.MsgError) - Exit Sub - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - - If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IdPoliza, CvePAC:=CvePACCancelacion) Then - ObjVentas.Commit() - Alert("El nuevo estatus se guardó correctamente") - Else - ObjVentas.RollBack() - Alert("Ocurrió un error al intentar cancelar la factura") - End If - - Catch ex As Exception - ObjVentas.RollBack() - Mensaje = "Ocurrio un error al Cancelar la factura" - GuardaLog($"{ex.Message}") - End Try - - ObjVentas.Dispose() - End Sub - Private Function DecodeBase64(ByVal strXMLCodificado As String) As String - Try - Dim decbuff As Byte() = Convert.FromBase64String(strXMLCodificado) - Return System.Text.Encoding.UTF8.GetString(decbuff) - Catch - Return "" - End Try - End Function - 'Private Sub ActualizaEstatusVentaCancelada(Optional CveEstatusCancelacion As Integer = 5) - ' Me.CveEstatus = CveEstatusCancelacion - - ' Dim ObjVentas As New ClsVentas() - ' If CveEstatusCancelacion = 5 Then - ' Dim IDPoliza As Integer = -1 - ' Dim ErrorCancelar As Boolean = False - ' Dim MensajeError As String = "" - ' Dim CvePACCancelacion As Integer = CvePAC - - ' Dim ObjAC As ClsContPAQi = Nothing - ' ObjVentas.IniciaTransacSQL() - ' Try - ' If UsuarioActual.Empresa.UsaAC Then - ' ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - ' IDPoliza = GenerarPolizaAC(ObjAC, True) - ' If IDPoliza <= 0 Then - ' ErrorCancelar = True - ' MensajeError = "Ocurrió un error al generar la poliza de cancelación." - ' End If - ' End If - - ' Dim solicitud = New WSGF.Service1SoapClient() - ' Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) - - ' If acuse.Estado = 0 Then - ' Dim xmlAcuse = New System.Xml.XmlDocument() - ' xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) - ' Dim CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText - ' Dim CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() - - ' If Not ObjVentas.UpdateEstatusFactura(Me.CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion) Then - ' ErrorCancelar = True - ' MensajeError = "Ocurrió un error al guardar el estatus de cancelación." - ' End If - ' Else - ' 'sino se pudo sacar el acuse, porque se canceló en el SAT, debe de marcarlo - ' End If - ' Catch ex As Exception - ' ErrorCancelar = True - ' Alert("Ocurrió un error al actualizar el estatus", TipoMensaje.MsgError) - ' Finally - ' If Not ErrorCancelar Then - ' ObjVentas.Commit() - - ' If Me.CveEstatus = 5 Then - ' Dim MensajeAlert As New StringBuilder - ' MensajeAlert.Append("El Documento se canceló correctamente.") - ' MensajeAlert.Append($"
    Imprimir Acuse") - ' MensajeAlert.Append("

    ¿Desea enviar el Acuse de Cancelación al Cliente?") - ' Alert(MensajeAlert.ToString, TipoMensaje.MsgConfirmacion, "BtnEnviarMailCancelacion()", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") - ' Else - ' Alert("El documento se canceló exitosamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="location.reload();") - ' End If - ' LbCancelarDocumento.Enabled = False - ' If ObjAC IsNot Nothing Then ObjAC.Commit() - ' Else - ' Alert(MensajeError, TipoMensaje.MsgError) - ' ObjVentas.RollBack() - ' If ObjAC IsNot Nothing Then ObjAC.RollBack() - ' End If - - ' ObjVentas.Dispose() - ' If ObjAC IsNot Nothing Then ObjAC.Dispose() - ' End Try - - ' ElseIf CveEstatusCancelacion = 20 Then - ' If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta) Then - ' Alert("El estatus de la factura fue cambiado a 'Cancelación en Proceso'") - ' End If - ' ObjVentas.Dispose() - ' End If - - - 'End Sub - - Private Sub CancelarDocumento(Optional EsRefacturacion As Boolean = False) - - 'Si es cancelacion de una refactura ignoramos las condiciones - If Me.CveEstatus = 13 Then - CancelarRefacturada() - End If - - 'La validacion de saldos cuando es refacturacion se hace antes asi que si es refacturacion ignoramos esta condicion, si es Anticipo verifica que no esté aplicado - If DdlTipoComprobante.SelectedValue = "Ant" AndAlso (HdnPagado.Value.ToDecimal > 0 Or GvAntNC.Rows.Count > 0) Then - Alert("La factura no se puede cancelar debido a que tiene pagos vinculados.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'La validacion de saldos cuando es refacturacion se hace antes asi que si es refacturacion ignoramos esta condicion - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") AndAlso HdnPagado.Value.ToDecimal > 0 Then - Alert("La factura no se puede cancelar debido a que tiene pagos vinculados.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - - 'Si la remision esta facturada no se puede cancelar - If DdlTipoComprobante.SelectedValue = "Rem" Then - Dim ObjV As New ClsVentas - If ObjV.VerificarRemisionFacturada(CveVenta) Then - If ObjV.DtResultados.Rows.Count > 0 Then - Alert("La remisión no se puede cancelar debido a que ya esta vinculada a una factura.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - ObjV.Dispose() - End If - - 'CARGA REMISIONES DE LA VENTA DEVUELTA - Dim DtDevRem As New DataTable - If Not EsRefacturacion Then - Dim ObjInventarioTemporal As New ClsInventarios() - If ObjInventarioTemporal.GetDevolucionRemisionesCanceladas(CveVenta) Then - DtDevRem = ObjInventarioTemporal.DtResultados - Else - Alert("Ocurrió un error al verificar los movimientos de almacén relacionados al documento.", TipoMensaje.MsgError) - ObjInventarioTemporal.Dispose() - Exit Sub - End If - ObjInventarioTemporal.Dispose() - End If - - '[IPP] FALTA TERMINAR 27/Noviembre/2018 - '' si tiene movimientos en almacen que se hallan surtido en el documento actual, y sigue sin ser marcado como devuelto - 'If (GvInv.Rows.Count > 0 AndAlso DevolucionAlmacen.Contiene(0, 1)) And DtDevRem.COUNT("CantidadSurtida", "ISNULL(CveRem,0) = 0") > 0 Then ' [COMENTADO IPP 3 Agosto 2017] | AndAlso Not (DdlTipoComprobante.SelectedValue.Contiene("Rem", "DPe")) | REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN - ' Alert("La factura no se puede cancelar debido a que tiene movimientos de inventario.", TipoMensaje.MsgAdvertencia) - ' Exit Sub - 'End If - - Dim ReviveRemision As Boolean = False - 'RMF. ANOTACION. cuando se cancela, y tiene relacionada una remisión, y esta no se cancelará. debe de hacer en automático los movimientos al almacen de entrega por adelantado - If Not EsRefacturacion AndAlso ChkCanRem.Visible AndAlso ChkCanRem.Checked = False Then - ReviveRemision = True - End If - If Not EsRefacturacion AndAlso (VentaSaldoAlmacen > 0 AndAlso DevolucionAlmacen.Contiene(0, 1)) AndAlso Not ChkDevAlm.Checked And ReviveRemision = False Then ' [COMENTADO IPP 3 Agosto 2017] | AndAlso Not (DdlTipoComprobante.SelectedValue.Contiene("Rem", "DPe")) | REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN - Alert("La factura no se puede cancelar debido a que tiene movimientos de inventario.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - Dim CancelacionFecha As Date - Dim CancelacionAcuse As String = "" - Dim MensajeError As String = "" - Dim ObjCancelacion As New Timbrado - Dim TotalT As Decimal = TxtTotal.Text.ToDecimal - Dim RFCReceptor As String = LblRFC.Text.Trim - Dim CvePACCancelacion As Integer = CvePAC - Dim CveEstatus As Integer = 4 - Dim IDPoliza As Integer = -1 - Dim CvePrePoliza As Integer - Dim CvePlantillaPoliza As Integer - Dim ErrorCancelar As Boolean = False - - Dim Continuar As Boolean = False - Dim ContinuarCancelacion As Boolean = False - Dim ObtenerAcuse As Boolean = False - Dim RequiereAceptacion As Boolean = False - Dim Mensaje As String = "" - Try - If FolioFiscal <> "" Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then - - Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), UsuarioActual.Empresa.FacturaProduccion) - If Vigencia IsNot Nothing Then - If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then - Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - If Vigencia.Estado.ToUpper().Contains("CANCELADO") Then - ContinuarCancelacion = False - ObtenerAcuse = True - Dim solicitud = New WSGF.Service1SoapClient() - Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) - - If acuse.Estado = 0 Then - Dim xmlAcuse = New System.Xml.XmlDocument() - xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) - CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText - CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() - CveEstatus = 5 - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - CveEstatus = 5 - End If - - ElseIf Vigencia.Estado.ToUpper().Contains("VIGENTE") Then - - If Vigencia.EstatusCancelacion.ToUpper() = "EN PROCESO" Then - CveEstatus = 20 - ContinuarCancelacion = False - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE CON ACEPTACIÓN" Then - CveEstatus = 20 - ContinuarCancelacion = True - RequiereAceptacion = True - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then - ContinuarCancelacion = True - CveEstatus = 5 - End If - - Else - If Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then - ContinuarCancelacion = True - CveEstatus = 5 - Else - 'Alert("La factura no se puede cancelar debido a que no se encontro su estatus en el SAT.", TipoMensaje.MsgAdvertencia) - 'Exit Sub - CveEstatus = 20 - ContinuarCancelacion = False - CancelacionFecha = Now.Date - CancelacionAcuse = "" - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - End If - End If - Else - Alert("No se pudo comprobar la vigencia de la factura.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - If Not ObtenerAcuse Then - If ContinuarCancelacion Then - If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then - 'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017 - If RequiereAceptacion Then - CancelacionFecha = Now.Date - CancelacionAcuse = "" - CveEstatus = 20 - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - Else - CancelacionFecha = ObjCancelacion.CancelacionFecha - CancelacionAcuse = ObjCancelacion.CancelacionAcuse - CveEstatus = 5 - End If - Else - Alert("La factura no se pudo cancelar ante el SAT", TipoMensaje.MsgError) - Exit Sub - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - Catch ex As Exception - MensajeError = "Ocurrió un Error al Cancelar la factura con los servicios del SAT." - GuardaLog($"{MensajeError} - Error:{ex.Message}") - Alert(MensajeError, TipoMensaje.MsgError) - Exit Sub - End Try - - Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() - Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) - Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) - Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) - Dim ObjContrato As New ClsContratos(ObjVentas.IniciaTransacSQL()) - Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) - Dim ObjAC As ClsContPAQi = Nothing - If UsuarioActual.Empresa.UsaAC Then - ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - End If - CreaObjetosVenta() - - ObjFactura.CveVenta = CveVenta - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - CvePlantillaPoliza = 7 - ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem", "Ant") Then - CvePlantillaPoliza = 4 - Else - CvePlantillaPoliza = 4 - End If - - If ((HplSaldoAuxiliar.Text.ToDecimal > 0 OrElse (TxtTotal.Text.ToDecimal = 0 AndAlso UsuarioActual.CveEmpresa.Contiene(72) AndAlso ObjFactura.TipoDocto.Contiene("Ing"))) AndAlso CveEstatus.Contiene(4, 5)) OrElse CvePlantillaPoliza = 7 Then - 'RMF. 2018.08.08 cuando se cancela, la póliza debe de ser de diario - CvePrePoliza = ObjConta.AddPrePolizas("Ventas/CancelarDocumento", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=3) - ObjFactura.CvePrePoliza = CvePrePoliza - - 'CANCELAR PAGOS - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - If Not ErrorCancelar Then - If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, CvePrePoliza) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al generar la prepoliza de cancelación de pago." - End If - End If - End If - - 'CANCELA PREPOLIZA - If Not ErrorCancelar Then - ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas, ObjEventos) - MensajeError = "Ocurrió un error al generar la prepoliza de cancelación." - End If - - 'CANCELA IMPUESTOS LOCALES - If Not ErrorCancelar Then - ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, -1) - MensajeError = "Ocurrió un error al cancelar los impuestos locales." - End If - End If - - 'CANCELA CONTRATOS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - ErrorList = New List(Of String) - If ObjFactura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then - GuardarContratoAvanceEstimaciones(ObjContrato, ObjFactura, ErrorList, -1, True) - ErrorCancelar = ErrorList.Count > 0 - MensajeError = "Ocurrió un error al cancelar las estimaciones del contrato." - ElseIf ObjFactura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then - GuardarContratoAvanceEstimaciones(ObjContrato, ObjFactura, ErrorList, 1, True) - ErrorCancelar = ErrorList.Count > 0 - MensajeError = "Ocurrió un error al cancelar los avances del contrato." - End If - End If - End If - - - 'DESVINCULA COTIZACIONES PREDECESORAS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then - If Not ObjVentas.LiberarCotizacionesFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las cotizaciones." - End If - End If - End If - End If - - 'DESVINCULA PEDIDOS2 PREDECESORES - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then - If Not ObjVentas.LiberarPedidos2Facturados(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular los pedidos." - End If - End If - End If - End If - - - 'DESVINCULA OCs PREDECESORAS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue = "Ing" Then - If Not ObjVentas.LiberarOCFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las Ordenes de Compra." - End If - End If - End If - End If - - 'ELIMINA LAS VENTAS DETALLE DE LA DEVOLUCION - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue = "Dev" Then - If Not ObjVentas.RemoveVentaDetalleDevolucion(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al eliminar las ventas detalle devolución." - End If - End If - End If - End If - 'POLIZA DE CANCELACION - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If UsuarioActual.Empresa.UsaAC Then - IDPoliza = GenerarPolizaAC(ObjAC, True) - If IDPoliza <= 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al generar la poliza de cancelación." - End If - End If - End If - End If - - 'DEVOLUCION DE ALMACEN - If ChkDevAlm.Checked Or ReviveRemision Then - Dim TieneSalida As Boolean = False - Dim DtDatos As New DataTable - Dim DtExistencias As New DataTable - - If DevolucionAlmacen = 0 Then - Dim EstatusDevolucion = 1 - If Not ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al solicitar la devolucion de almacen." - End If - End If - - If Not ErrorCancelar AndAlso ObjInventario.EntregaAlmacenGet(CveVenta) Then - If ObjInventario.DtResultados IsNot Nothing AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then - DtDatos = ObjInventario.DtResultados - DtDatos.Columns.Add("Consec", GetType(Integer)) - DtDatos.Columns.Add("CantidadGV", GetType(Double)) - DtDatos.Columns.Add("CantidadTraspaso", GetType(Double)) - Dim Index = 1 - For Each Dr As DataRow In DtDatos.Rows - Dr("Consec") = Index - Dr("CantidadGV") = Dr("CantidadF") - Index += 1 - Next - - If DtDatos IsNot Nothing AndAlso DtDatos.Rows.Count > 0 AndAlso ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero > 0 Then - Dim Filtro As String '= If(ObjInventario.DtResultados.Rows(0)("TipoDocto").ToString.Contiene({"Ing", "Dev", "Ped"}), "CveConcepto = 3", "CveConcepto = 9") - Select Case ObjInventario.DtResultados.Rows(0)("TipoDocto").ToString - Case "Ing", "Ped" - Filtro = "CveConcepto = 3" - Case "Dev" - Filtro = "CveConcepto = 3" - Case Else - Filtro = "CveConcepto = 9" - End Select - If ObjInventario.GetInv_Mov(ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero, UsuarioActual.CveEmpresa) Then - DtExistencias = ObjInventario.DtResultados.FiltraParametros($"CvePS Is Not NULL AND {Filtro}") - - If DtExistencias.Rows.Count > 0 Then - TieneSalida = True - End If - - Else - ErrorCancelar = True - MensajeError = "Ocurrió un error al cargar los datos de devolución. Por favor vuelva a intentar." - End If - End If - End If - End If - - If Not ErrorCancelar AndAlso TieneSalida Then - Dim DtDatosDetalle As New DataTable - DtDatosDetalle.Columns.Add("CveVentaDetalle", GetType(Integer)) - DtDatosDetalle.Columns.Add("Consec", GetType(Integer)) - DtDatosDetalle.Columns.Add("ConsecId", GetType(Integer)) - DtDatosDetalle.Columns.Add("CvePS", GetType(Integer)) - DtDatosDetalle.Columns.Add("PS", GetType(String)) - DtDatosDetalle.Columns.Add("CveUM", GetType(Integer)) - DtDatosDetalle.Columns.Add("SerieLote", GetType(String)) - DtDatosDetalle.Columns.Add("FechaCaducidad", GetType(String)) - DtDatosDetalle.Columns.Add("FueTraspaso", GetType(Integer)) - - Dim DtDatosDetalleLote As New DataTable - DtDatosDetalleLote.Columns.Add("CveVentaDetalle", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("Consec", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("ConsecId", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("Cantidad", GetType(Double)) - DtDatosDetalleLote.Columns.Add("CvePS", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("PS", GetType(String)) - DtDatosDetalleLote.Columns.Add("CveUM", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("Lote", GetType(String)) - DtDatosDetalleLote.Columns.Add("Batch", GetType(String)) - DtDatosDetalleLote.Columns.Add("FechaCaducidad", GetType(String)) - DtDatosDetalleLote.Columns.Add("FueTraspaso", GetType(Integer)) - - Dim DtTraspasos As New DataTable - DtTraspasos.Columns.Add("CveAlmacen", GetType(Integer)) - DtTraspasos.Columns.Add("Almacen", GetType(String)) - DtTraspasos.Columns.Add("CveMovimientoSalida", GetType(Integer)) - DtTraspasos.Columns.Add("FolioSalida", GetType(Integer)) - DtTraspasos.Columns.Add("CveMovimientoEntrada", GetType(Integer)) - DtTraspasos.Columns.Add("FolioEntrada", GetType(Integer)) - - Dim ConceptoMovimiento = 18 - Dim CveMovimiento As Integer = 0 - Dim Folio As Integer = 0 - Dim CantidadPendiente As Decimal = 0 - Dim DtDetalle As New DataTable - Dim DtDetalleLote As New DataTable - - CveMovimiento = ObjInventario.AddMovimiento(CveAlmacenDevolucion, ConceptoMovimiento, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveAlmacenDestino:=-1) - Folio = ObjInventario.Folio - - 'SALIDA DE ALMACEN - SALIDA POR TRASPASO CUANDO ES REMISION - DEVOLUCION (SI ES TRASPASO Y TIENE CONTRATO NO HACE DEVOLUCIóN) - 'If Not (CveContrato > 0 And CveAlmacenTraspasoDestino > 0) Then - If CveMovimiento > 0 Then - - 'ES EL MOVIMIENTO PRINCIPAL - CantidadPendiente = 0 - For Each Dr As DataRow In DtDatos.Rows - CantidadPendiente = Dr("CantidadGV").ToString.ToDecimal - Dr("CantidadTraspaso").ToString.ToDecimal - If CantidadPendiente > 0 Then - Dim PU As Decimal = 0 - - 'SI FUE POR SERIELOTE - DtDetalle = DtDatosDetalle.FiltraParametros(String.Format("ConsecId = {0} AND FueTraspaso IS NULL", Dr("Consec"))) - DtDetalleLote = DtDatosDetalleLote.FiltraParametros(String.Format("ConsecId = {0} AND FueTraspaso IS NULL", Dr("Consec"))) - If DtDetalle.Rows.Count > 0 Then - For Each Dr1 As DataRow In DtDetalle.Rows - If DtExistencias IsNot Nothing Then - PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero} AND SerieLote = '{Dr1("SerieLote").ToString}'").ToString.ToDecimal - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, 1, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, SerieLote:=Dr1("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos con serie. Por favor vuelva a intentar." - Exit For - End If - Next - ElseIf DtDetalleLote.Rows.Count > 0 Then - For Each Dr1 As DataRow In DtDetalleLote.Rows - If DtExistencias IsNot Nothing Then - PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero} AND SerieLote = '{Dr1("SerieLote").ToString}'").ToString.ToDecimal - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, Dr1("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, Lote:=Dr1("Lote").ToString, Batch:=Dr1("Batch").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos con serie. Por favor vuelva a intentar." - Exit For - End If - Next - Else - If DtExistencias IsNot Nothing Then - PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero}").ToString.ToDecimal - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, CantidadPendiente, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos de salida. Por favor vuelva a intentar." - Exit For - End If - End If - - End If - Next - Else - ErrorCancelar = True - End If - - If Not ErrorCancelar Then - Dim DtCostos As DataTable = Nothing - Dim ValorInventario As Decimal = 0 - If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then - DtCostos = ObjInventario.DtResultados - - Dim tmpCostos As DataTable = DtCostos.FiltraParametros("", "", {"CveClasificacion"}) - Dim IdCtaContableAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero - Dim CveCuentaAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero - Dim IdCtaContable As Integer = 0 - Dim CveCuenta As Integer = 0 - If tmpCostos.Rows.Count > 0 Then - - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - Dim Fecha As Date = Now - Dim CveCliente As Integer = ObjVentas.DtResultados(0)("CveCliente").ToString.ToEntero - Dim ClienteNombre As String = ObjVentas.DtResultados(0)("ClienteNombre").ToString - Dim SerieFolio As String = ObjVentas.DtResultados(0)("SerieFolio").ToString - Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL() - Dim TotalCostoAcumulado As Decimal = 0 - Dim cont As Integer = 1 - - Dim CvePrePolizaDev As Integer = ObjConta.AddPrePolizas("Inventario/RecepcionEntrega", 4, TotalCosto, TotalCosto, 1, Fecha, ClienteNombre, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - 'Se agrega movimiento separado por la cuenta de ventas (ER) - For Each RowInv As DataRow In tmpCostos.Rows - ValorInventario = DtCostos.SUMD("Total", $"CveClasificacion = {RowInv("CveClasificacion")}").RoundSQL() - TotalCostoAcumulado += ValorInventario - - 'cuando es el último movimiento y hay diferencias en los importes - If cont = DtCostos.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then - ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) - End If - - 'Concepto = String.Format("{0} - {1}", Row2("Clasificacion").ToString, Row2("SubProyecto").ToString) - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostosSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - - If Not ErrorCancelar Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, False, -1 * ValorInventario, SerieFolio, 69, SerieFolio, Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ImporteMX:=-1 * ValorInventario, CveCuenta:=CveCuenta, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero) Then - ErrorCancelar = True - End If - End If - - cont += 1 - Next - - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, True, -1 * TotalCosto, SerieFolio, 68, SerieFolio, Fecha, IdCtaContableAlmacen, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ImporteMX:=-1 * TotalCosto, CveCuenta:=CveCuentaAlmacen) Then - ErrorCancelar = True - End If - - 'AutoConta - El movimiento 1 es el de Venta - - Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" - - If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue = "Ant" Then - AutoConta = False - End If - - If AutoConta And Not ErrorCancelar Then - Dim ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) - - If IdCtaContable > 0 Then - If Not ObjConta.ContabilizarPrePoliza(CvePrePolizaDev, UsuarioActual.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then - Alert("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico") - End If - Else - Alert(String.Format("No se puede contabilizar ya que falta asignación de las cuentas contables"), TipoMensaje.MsgAdvertencia) - End If - - ObjContPaq.Dispose() - End If - - Else - ErrorCancelar = True - MensajeError = "Ocurrió un Error al ingresar las prepolizas" - End If - - End If - End If - End If - - If Not ErrorCancelar Then - If ObjInventario.VentasAlmacenApartadosGet(CveVenta) Then - - Dim DtTempApartados = ObjInventario.DtResultados.FiltraParametros("CveTipoAlmacen = 9", "CveAlmacen") - Dim CveMovimientoSalidaApartado = -1 - Dim CveAlmacenApartado = -1 - Dim CveAlmacenOrigen = CveAlmacenDevolucion - Dim FolioSalida As Integer = 0, FolioEntrada = 0, CveMovimientoSalida = 0, CveMovimientoEntradaApartado = 0 - - For Each Dr As DataRow In DtTempApartados.Rows - - If CveMovimientoSalidaApartado = -1 Or CveAlmacenApartado <> Dr("CveAlmacen").ToString.ToEntero Then - CveMovimientoSalidaApartado = ObjInventario.AddMovimiento(CveAlmacenOrigen, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveVendedor:=1, CveCliente:=CveCliente, CveAlmacenDestino:=Dr("CveAlmacen").ToString.ToEntero) - FolioSalida = ObjInventario.Folio - CveAlmacenApartado = Dr("CveAlmacen").ToString.ToEntero - - Dim DrMovto = DtTraspasos.NewRow - DrMovto("Almacen") = Dr("Almacen").ToString.ToEntero - DrMovto("CveAlmacen") = Dr("CveAlmacen").ToString.ToEntero - DrMovto("CveMovimientoSalida") = CveMovimientoSalidaApartado - DrMovto("FolioSalida") = FolioSalida - DtTraspasos.Rows.Add(DrMovto) - End If - - If Not CveMovimientoSalidaApartado > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de control de apartados" - Exit For - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de control de apartados" - Exit For - End If - Next - - If Not ErrorCancelar Then - For Each Dr1 As DataRow In DtTraspasos.Rows - CveMovimientoSalida = Dr1("CveMovimientoSalida").ToString.ToEntero - - CveMovimientoEntradaApartado = ObjInventario.AddMovimiento(Dr1("CveAlmacen").ToString.ToEntero, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", CveAlmacenDestino:=CveAlmacenDevolucion, CveMovimientoRelacionado:=CveMovimientoSalida, Guia:="", CveContrato:=CveContrato, CveVendedor:=-1, CveCliente:=CveCliente) - FolioEntrada = ObjInventario.Folio - - If Not CveMovimientoEntradaApartado > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los movimientos de traspaso de apartado. Por favor vuelva a intentar." - Exit For - End If - - Dr1("CveMovimientoEntrada") = CveMovimientoEntradaApartado - Dr1("FolioEntrada") = FolioEntrada - - If ObjInventario.GetMovimientosDetalle(CveMovimientoSalida, UsuarioActual.CveEmpresa) Then - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos de traspaso de apartado. Por favor vuelva a intentar." - Exit For - End If - Next - End If - - If ErrorCancelar Then Exit For - Next - End If - - End If - End If - - 'DEVOLUCION REMISION - REGRESA LAS EXISTENCIAS A ENTREGA POR ADELANTADO SI LA FACTURA VIENE DE REMISION - If Not ErrorCancelar Then - Dim DtMovtosDev As New DataTable - Dim CveAlmacenTraspasoDestinoDevRem = -1 - - Dim CveVentaDetalleRem = -1 - Dim CantidadDevolver As Decimal = 0 - Dim CantidadRem As Decimal = 0 - Dim CveMovimientoSalidaDevRem As Integer = 0 - Dim FolioMovimientoSalidaDevRem As Integer = 0 - Dim CveMovimientoEntradaDevRem As Integer = 0 - Dim FolioMovimientoEntradaDevRem As Integer = 0 - - 'CARGA REMISIONES DE LA VENTA DEVUELTA - If ObjInventario.GetDevolucionRemisionesFacturadas(CveVenta) Then - DtDevRem = ObjInventario.DtResultados.FiltraParametros("CantidadAlmacen > 0") - Else - ErrorCancelar = True - End If - - 'CARGA CONCEPTOS DEVUELTOS EN LA VENTA - If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then - DtMovtosDev = ObjInventario.DtResultados - Else - ErrorCancelar = True - End If - - If Not ErrorCancelar Then - If DtDevRem.Rows.Count > 0 And DtMovtosDev.Rows.Count > 0 Then - - For Each DrMovtos As DataRow In DtDevRem.FiltraParametros("", "CveRem", {"CveRem", "CveAlmacenTraspasoDestino"}).Rows - - 'CHECO SI NO SE VA A CANCELAR - Dim SeCancela As Boolean = False - If ChkCanRem.Checked Then - For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows - If Gvr.FCCheckBox("ChkCancelarRemision").Checked AndAlso DrMovtos("CveRem").ToString.ToEntero = Gvr.DataKey("CveVenta").ToString.ToEntero Then - SeCancela = True - Exit For - End If - Next - End If - - If Not SeCancela Then - - CveAlmacenTraspasoDestinoDevRem = DrMovtos("CveAlmacenTraspasoDestino").ToString.ToEntero - If Not CveAlmacenTraspasoDestinoDevRem > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al obtener el almacén de devolucion de remisión." - Exit For - End If - - 'SALIDA GENERAL - CveMovimientoSalidaDevRem = ObjInventario.AddMovimiento(CveAlmacenDevolucion, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimiento, CveAlmacenDestino:=CveAlmacenTraspasoDestinoDevRem) - FolioMovimientoSalidaDevRem = ObjInventario.Folio - - 'ENTRADA ADELANTADO - CveMovimientoEntradaDevRem = ObjInventario.AddMovimiento(CveAlmacenTraspasoDestinoDevRem, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimientoSalidaDevRem, CveAlmacenDestino:=CveAlmacenDevolucion) - FolioMovimientoEntradaDevRem = ObjInventario.Folio - - If Not (CveMovimientoSalidaDevRem > 0 And CveMovimientoEntradaDevRem > 0) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al generar los movimientos de devolución a remisión." - Exit For - End If - - - 'SALIDA POR TRAPASO DE GENERAL - For Each DrRem As DataRow In DtDevRem.FiltraParametros($"CveRem = {DrMovtos("CveRem")}").Rows - CveVentaDetalleRem = DrRem("CveVentaDetalleRem").ToString.ToEntero - CantidadRem = DrRem("CantidadFacturada").ToString.ToDecimal - 'CantidadDevolver = DtMovtosDev.FiltroPrimeroValor("Cantidad", $"CveVentaDetalle = {DrRem("CveVentaDetalle").ToString.ToEntero}").ToDouble - 'If (Dr("Cantidad").ToString.ToDouble > CantidadRem, CantidadRem, Dr("Cantidad").ToString.ToDouble) Then - - If Not CveVentaDetalleRem > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al obtener la relación de la venta con la remisión." - Exit For - End If - - For Each Dr As DataRow In DtMovtosDev.FiltraParametros($"CveVentaDetalle = {DrRem("CveVentaDetalle").ToString.ToEntero}").Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=CveVentaDetalleRem, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de salida de traspaso de devolucion de remisión." - Exit For - End If - Next - - If ErrorCancelar Then - Exit For - End If - Next - - If ErrorCancelar Then - Exit For - End If - - 'ENTRADA POR TRAPASO A ENTREGA POR ADELANTADO - If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaDevRem, UsuarioActual.CveEmpresa) Then - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de entrada de traspaso de devolucion de remisión." - Exit For - End If - Next - - If ErrorCancelar Then - Exit For - End If - - Else - ErrorCancelar = True - MensajeError = "Ocurrió un error al obtener los detalles de la devolución de almacén" - Exit For - End If - - - If Not ObjVentas.UpdateVentasDevolucionAlmacen(0, DrMovtos("CveRem").ToString.ToEntero) Then - MensajeError = "Ocurrió un error al hacer la devolucion hacia la remision. Por favor vuelva a intentar." - ErrorCancelar = True - Exit For - End If - - End If - - Next - End If - Else - MensajeError = "Ocurrió un error al hacer la devolucion a remisión. Por favor vuelva a intentar." - ErrorCancelar = True - End If - - End If - - If Not ErrorCancelar Then - 'QUEMA DEVOLUCION | QUEMA = LA QUITA DE PENDIENTE POR RECIBIR (DEVOLVER) - If Not ErrorCancelar Then - If Not ObjVentas.UpdateVentasDevolucionAlmacen(2, CveVenta) Then - MensajeError = "Ocurrió un error al hacer la devolucion. Por favor vuelva a intentar." - ErrorCancelar = True - End If - End If - - 'AGREGA BITACORA A VENTA - If Not ErrorCancelar Then - Dim MensajeBitacora = "Devuelta" - If Not ObjEventos.AddEventoBitacora(String.Format("Venta {2} en Folio: {1}", CveMovimiento, Folio, MensajeBitacora), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - ErrorCancelar = True - End If - End If - End If - - End If - End If - - 'DESVINCULA REMISIONES PREDECESORAS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then - If Not ChkCanRem.Checked Then - If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las remisiones." - End If - Else - For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows - If Not Gvr.FCCheckBox("ChkCancelarRemision").Checked Then - If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta, Gvr.DataKey("CveVenta").ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las remisiones." - End If - End If - Next - End If - End If - End If - End If - - - 'ACTUALIZA ESTATUS - If Not ErrorCancelar Then - Select Case DdlTipoComprobante.SelectedValue - Case "Rem" - CveEstatus = 12 - Case "Com" - CveEstatus = 9 - End Select - '0 Sin Refacturacion, 1 Refacturacion en Proceso, 3. Refacturación en proceso sin aceptación - Me.CveEstatusRefacturacion = 0 - If EsRefacturacion Then - If CveEstatus = 5 Then - CveEstatusRefacturacion = 3 ' refacturación en proceso sin autorización de cancelación - Else - CveEstatusRefacturacion = 1 ' refacturación en proceso con autorización de cancelación - End If - End If - - - If Not ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion, CveEstatusRefacturacion:=CveEstatusRefacturacion, - CveUsuarioCambiaEstatus:=UsuarioActual.CveUsuario, FechaCambioEstatus:=Now.ToString("yyyy-MM-dd hh:mm:ss.mmm")) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar el estatus de cancelación." - End If - - If ChkCanRem.Checked Then - For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows - If Gvr.FCCheckBox("ChkCancelarRemision").Checked Then - If Not SeCancelaRemisionProceso Then - If Not ObjVentas.UpdateEstatusFactura(12, "", "", CancelacionFecha, Gvr.DataKey("CveVenta").ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar el estatus de cancelación de la remisión." - End If - Else - If Not ObjVentas.AddRemisionesXCancelar(CveVenta, Gvr.DataKey("CveVenta").ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar la remisión x cancelar." - End If - End If - End If - Next - End If - If SeCancelaRemisionProceso Then - If Not ObjVentas.UpdateCancelaRemision(CveVenta, SeCancelaRemisionProceso) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al actualizar que la remision sea cancelable." - End If - End If - End If - - If Not ErrorCancelar Then - ObjVentas.Commit() - - If CveEstatus = 5 Then - Dim MensajeAlert As New StringBuilder - MensajeAlert.Append("El Documento se canceló correctamente.") - MensajeAlert.Append($"
    Imprimir Acuse") - MensajeAlert.Append("

    ¿Desea enviar el Acuse de Cancelación al Cliente?") - Alert(MensajeAlert.ToString, TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnEnviarMailCancelacion();", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") - - Else - If Not EsRefacturacion Then - Alert("El documento se canceló exitosamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();") - Else - Response.Redirect($"/Ventas/RepCancelacionesPorRespuesta.aspx?CveVenta={Me.CveVenta}") - End If - End If - - Me.CveEstatus = CveEstatus - If CveEstatus = 5 Then LbCancelarDocumento.Enabled = False - If ObjAC IsNot Nothing Then ObjAC.Commit() - Else - Alert(MensajeError, TipoMensaje.MsgError) - ObjVentas.RollBack() - If ObjAC IsNot Nothing Then ObjAC.RollBack() - End If - - ObjVentas.Dispose() - ObjBancos.Dispose() - ObjInventario.Dispose() - ObjContrato.Dispose() - ObjConta.Dispose() - If ObjAC IsNot Nothing Then ObjAC.Dispose() - - UpEstatus.Update() - End Sub + Private Sub CargaComprobanteXML(XMLDoc As XmlDocument) + Dim nodo As XmlNode = XMLDoc.DocumentElement + + _SerieXML = ValorXML(nodo, "serie") + If _SerieXML <> "" Then _SerieXML = _SerieXML + + _Version = ValorXML(nodo, "version") + _FolioXML = 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") + + + Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) + Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" + Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) + + 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 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") + 'EmisorNombre = ValorXML(node, "nombre") + End If + 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 + + 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}:Retencion", Prefijo), namespaces) + + TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDecimal + + For Each retencion As XmlNode In nodeRetenciones + If retencion.Attributes("impuesto").Value = "IVA" Then + RetencionIVA += retencion.Attributes("importe").Value.ToDecimal + End If + If retencion.Attributes("impuesto").Value = "ISR" Then + RetencionISR += retencion.Attributes("importe").Value.ToDecimal + End If + ' Do something. + Next + SumaTotalRetenciones += RetencionIVA + SumaTotalRetenciones += RetencionISR + + TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDecimal + + Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) + For Each traslado As XmlNode In nodeTraslados + If traslado.Attributes("impuesto").Value = "IVA" Then + TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal + End If + If traslado.Attributes("impuesto").Value = "IEPS" Then + TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal + End If + 'If traslado.Attributes("impuesto").Value = "ISR" Then + ' TrasladoISR = traslado.Attributes("importe").Value + 'End If + ' Do something. + Next + 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 + _FolioXML = 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 + + If RetencionIVA <= 0 AndAlso ValorXML(node, "TotaldeRetenciones", "0").ToDouble > 0 Then RetencionIVA = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal + + + 'For Each retencion As XmlNode In nodeImpLocales + ' If retencion.Attributes("impuesto").Value = "IVA" Then + ' RetencionIVA += retencion.Attributes("importe").Value.ToDouble + ' End If + ' If retencion.Attributes("impuesto").Value = "ISR" Then + ' RetencionISR += retencion.Attributes("importe").Value.ToDouble + ' End If + ' ' Do something. + 'Next + ' SumaTotalRetenciones += RetencionIVA + ' SumaTotalRetenciones += RetencionISR + + 'TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble + + 'Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) + 'For Each traslado As XmlNode In nodeTraslados + ' If traslado.Attributes("impuesto").Value = "IVA" Then + ' TrasladoIVA += traslado.Attributes("importe").Value.ToDouble + ' End If + ' If traslado.Attributes("impuesto").Value = "IEPS" Then + ' TrasladoIEPS += traslado.Attributes("importe").Value.ToDouble + ' End If + ' 'If traslado.Attributes("impuesto").Value = "ISR" Then + ' ' TrasladoISR = traslado.Attributes("importe").Value + ' 'End If + ' ' Do something. + 'Next + 'SumaTotalTraslados += TrasladoIVA + 'SumaTotalTraslados += TrasladoIEPS + End If + + End If + -#End Region -#Region "CiclosComerciales" - Private Sub CargaCicloComercialURL() - Dim ObjContratos As New ClsContratos - Dim huboerror = False - Dim SubProyecto As String = "" - Dim CveSubProyecto As Integer = -1 - Dim Proyecto As String = "" - If ObjContratos.CicloComercialGet(-1, -1, CveCicloComercial, UsuarioActual.CveEmpresa, MinFecha, MaxFecha, -1) Then - If ObjContratos.DtResultados.Rows.Count > 0 Then - Dim i As Integer = 0 - Dim PU As Decimal = 0 - Dim Descuento As Double = 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 - - 'Cargamos los datos del Cliente - DtContratos = ObjContratos.DtResultados - If ObjContratos.DtResultados(0)("IVA").ToString.ToDecimal > 0 Then - ViewState("IVA") = ObjContratos.DtResultados(0)("IVA").ToString.ToDecimal - End If - ViewState("CveCliente") = ObjContratos.DtResultados(0)("CveCliente").ToString.ToEntero - ViewState("CveContrato") = ObjContratos.DtResultados(0)("CveContrato").ToString.ToEntero - HdnCveCliente.Value = ObjContratos.DtResultados(0)("CveCliente").ToString - CargaCliente(CveCliente) - DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) - DdlTipoComprobante.SelectedValue = "Ing" - DdlTipoComprobante.Enabled = False - DdlAlmacenAsignado.Enabled = False - - 'CARGO DATOS DE PS/CONTRATO - SubProyecto = ObjContratos.DtResultados(0)("SubProyectoContrato").ToString - CveSubProyecto = ObjContratos.DtResultados(0)("CveSubProyecto").ToString.ToEntero - Proyecto = ObjContratos.DtResultados(0)("ProyectoContrato").ToString - DdlSubProyectoDatos.SelectedValueExist(CveSubProyecto) - ContratoDetalles.Visible = True - DivEstimaciones.Visible = False - - DdlContratosModal.DataSource = DtContratos - DdlContratosModal.DataBind() - DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) - UPEstimaciones.Update() - - Tab.ActiveTab = TabE - TabGenerales.Enabled = False - Updatetabs.Update() - - DdlContratosModal.DataSource = ObjContratos.DtResultados - DdlContratosModal.SelectedValue = ObjContratos.DtResultados(0)("CveContrato").ToString - DdlContratosModal_SelectedIndexChanged(Nothing, Nothing) - GvContratoDetalles.HeaderRow.Cells(1).Style.Add("display", "none") - BtnCargarContratoDetalles_Click(Nothing, Nothing) - LbAgregar.Visible = True - UpPS.Update() - 'AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento - Else - Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) - huboerror = True - End If - Else - Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) - huboerror = True - End If - ObjContratos.Dispose() End Sub -#End Region - -#Region "DESCARGAR E IMPRIMIR LISTADO" - Public Sub DescargarFormato() - Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & "Empresas\Grales\Formatos\FormatoVentas.xlsx" - - Dim Archivo As New IO.FileInfo(Directorio) - If Archivo.Exists Then - Response.Clear() - Response.ClearHeaders() - Response.ClearContent() - Response.AddHeader("Content-Disposition", "attachment; filename=" + Archivo.Name) - Response.AddHeader("Content-Length", Archivo.Length.ToString()) - Response.ContentType = "text/plain" - Response.Flush() - Response.TransmitFile(Archivo.FullName) - Response.End() - End If - End Sub - Public Sub LbDescargarExcel_Click(sender As Object, e As EventArgs) Handles LbDescargarExcelVentas.Click - DescargarFormato() - End Sub - Private Sub CargarArchivo(Ruta As String, FileName As String, Tipo As String) - Dim dt As New DataTable - Dim Conexion As Odbc.OdbcConnection = Nothing - Dim ErrorArchivo = False - Dim n As Integer = 0 - Try - Select Case Tipo - Case "EXCEL" - Conexion = New Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + Ruta + FileName + ";") - Conexion.Open() - Dim cmd = Conexion.CreateCommand() - cmd.CommandType = CommandType.Text - cmd.CommandText = "Select * FROM [Hoja1$]" - Dim DataAdapter = New Odbc.OdbcDataAdapter(cmd) - DataAdapter.Fill(dt) - Case Else - Alert("El archivo no tiene el formato correcto", TipoMensaje.MsgError) - Exit Sub - End Select - Catch ex As Exception - ErrorArchivo = True - OnError("Ocurrio un Error al leer el archivo
    " & ex.Message, ex) - End Try - Conexion.Close() - If Not ErrorArchivo Then - If Not dt.Columns(0).ColumnName = "Cantidad" Then - Alert("El nombre de la primera columna debe ser 'Cantidad'.Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - If Not dt.Columns(1).ColumnName = "Código" Then - Alert("El nombre de la segunda columna debe ser 'Código'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - If Not dt.Columns(2).ColumnName = "Codigo Barras" Then - Alert("El nombre de la tecera columna debe ser 'Codigo Barras'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - If Not dt.Columns(3).ColumnName = "Producto/Servicio" Then - Alert("El nombre de la cuarta columna debe ser 'Producto/Servicio'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - If Not dt.Columns(4).ColumnName = "UM" Then - Alert("El nombre de la quinta columna debe ser 'U.M'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - If Not dt.Columns(5).ColumnName = "Precio Unitario" Then - Alert("El nombre de la sexta columna debe ser 'Precio Unitario'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - If Not dt.Columns(6).ColumnName = "Proyecto" Then - Alert("El nombre de la séptima columna debe ser 'Proyecto'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - If Not dt.Columns(7).ColumnName = "Observaciones" Then - Alert("El nombre de la octava columna debe ser 'Observaciones'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - - If Not dt.Columns(8).ColumnName = "Tiempo Entrega" Then - Alert("El nombre de la octava columna debe ser 'Tiempo Entrega'. Favor de corregirlo", TipoMensaje.MsgError) - Exit Sub - End If - - dt.TableName = "Datos" - - If Not ErrorArchivo Then - NumRow = 1 - Dim RowNoEncontrados As String = "" - Dim NumAgregados As Integer = 0 - For Each Row As DataRow In dt.Rows - Dim Cantidad As Decimal = Row("Cantidad").ToString.ToDecimal - Dim UM As String = Row("UM").ToString - Dim Codigo As String = Row("Código").ToString.Trim.ToUpper - Dim CodigoBarras As String = Row("Codigo Barras").ToString.Trim.ToUpper - Dim ProductoServicio As String = Row("Producto/Servicio").ToString.Trim.ToUpper - Dim PrecioUnitario As Decimal = Row("Precio Unitario").ToString.ToDecimal - Dim Proyecto As String = Row("Proyecto").ToString.Trim.ToUpper - Dim Observaciones As String = Row("Observaciones").ToString.Trim.ToUpper - Dim TiempoEntrega As String = Row("Tiempo Entrega").ToString - Dim CvePS As Integer = 0 - Dim CveUM As Integer = 0 - Dim CodigoPS As Integer = 0 - Dim DrProyecto As DataRow - Dim SubProyecto As String = "" - Dim CveProyecto As Integer = 0 - Dim CveSubProyecto As Integer = 0 - NumRow = NumRow + 1 - - If Proyecto <> "" Then - Dim DtSubProyecto As DataTable = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa) - DtSubProyecto.CaseSensitive = False - DrProyecto = DtSubProyecto.FiltroPrimero($"(SubProyecto) = '{Proyecto}'") - If DrProyecto IsNot Nothing Then - CveSubProyecto = DrProyecto("CveSubProyecto").ToString.ToEntero - CveProyecto = DrProyecto("CveProyecto").ToString.ToEntero - SubProyecto = DrProyecto("SubProyecto").ToString - End If - Else - CveProyecto = -1 - CveSubProyecto = -1 - End If - - If Codigo <> "" Then - Dim StrArray() As String = GetPS("Codigo", Codigo).Split("|"c) - If StrArray.Length > 0 Then - If CBool(StrArray(0)) = True Then - CvePS = StrArray(1).ToEntero - Else - RowNoEncontrados &= StrArray(1) & "<\BR>" - End If - End If - ElseIf CodigoBarras <> "" Then - Dim StrArray() As String = GetPS("CodigoBarras", CodigoBarras).Split("|"c) - If StrArray.Length > 0 Then - If CBool(StrArray(0)) = True Then - CvePS = StrArray(1).ToEntero - Else - RowNoEncontrados &= StrArray(1) & "<\BR>" - End If - End If - ElseIf ProductoServicio <> "" Then - Dim StrArray() As String = GetPS("PS", ProductoServicio).Split("|"c) - If StrArray.Length > 0 Then - If CBool(StrArray(0)) = True Then - CvePS = StrArray(1).ToEntero - Else - RowNoEncontrados &= StrArray(1) & "<\BR>" - End If - End If - Else - RowNoEncontrados &= "<\BR>    - En la fila " & NumRow & " no se especificó código, código de barras ó descripción." - End If - - If CvePS > 0 Then - CveUM = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveUnidadMedida", $"CvePS = '{CvePS}'").ToString.ToEntero - - AgregarProductoServicio(Cantidad, CveUM, UM, -1, "", - CvePS, HdnPS.Value, Observaciones, PrecioUnitario, HdnDescuento.Value.ToDecimal, - CveProyecto, Proyecto, CveSubProyecto, SubProyecto, - TiempoEntrega:=TiempoEntrega) - - - 'If TmpDT IsNot Nothing Then - ' Dim dr As DataRow = TmpDT.NewRow - ' TxtCantidad.Text = Cantidad.ToString - ' DdlPS.SelectedValue = CvePS.ToString - ' DdlPS_SelectedIndexChanged(Nothing, Nothing) - ' DdlUnidadMedida.SelectedValueExist(CveUM.ToString) - ' TxtObsPS.Text = Observaciones - ' DdlProyecto.SelectedValue = CveProyecto.ToString - ' DdlProyecto_SelectedIndexChanged(Nothing, Nothing) - ' DdlSubProyecto.SelectedValue = CveSubProyecto.ToString - ' TxtPrecio.Text = PrecioUnitario.ToString - ' TxtTiempoEntrega.Text = TiempoEntrega.ToString - ' RegistraScript("Recalcula();") - ' LbAgregar_Click(Nothing, Nothing) - ' NumAgregados = NumAgregados + 1 - 'End If - End If - - - Next - - - - CalculaTotalesVenta() - - If RowNoEncontrados.Length > 0 Then - Alert("Los siguientes productos o servicios no se encontraron en la Base de Datos.<\BR>" & RowNoEncontrados, TipoMensaje.MsgAdvertencia) - Else - Alert("Se cargaron " & NumAgregados & " productos o servicios correctamente.") - End If - End If - End If - dt.Dispose() - End Sub - Private Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcel.Click - If TxtExcel.getfiles().Archivos.Count > 0 Then - Dim file As Archivo = TxtExcel.getfiles().Archivos(0) - Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & file.patch - Dim Tipo As String = If(file.Extencion.Contiene("xlsx", "xlsx", "xlsm", "xlsb"), "EXCEL", "CSV") - CargarArchivo(Directorio, file.filename, Tipo) - Else - Alert("No existe el archivo. Favor de subir un archivo excel a la plataforma.", TipoMensaje.MsgError) - End If - End Sub - Private Function GetPS(Opt As String, Valor As String) As String - Dim StrReturn As String = String.Empty - Dim CvePS As Integer = 0 - CvePS = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePS", Opt & " = '" & Valor & "'").ToString.ToEntero - If CvePS > 0 Then - StrReturn = "True|" & CvePS.ToString - Else - StrReturn = "False|    - No se encontró " & Valor & " en la fila " & NumRow & ", columna " & Opt - End If - Return StrReturn + 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 -#End Region +#End Region -#Region "P E D I D O S" - Private Sub CargaNotificacionContrato() - Dim ObjContratos As New ClsContratos - If ObjContratos.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then - If ObjContratos.DtResultados IsNot Nothing AndAlso ObjContratos.DtResultados.Rows.Count > 0 Then - CorreoNotificacionPedDev = ObjContratos.DtResultados(0)("CorreoNotificacionPedDev").ToString - End If - End If - ObjContratos.Dispose() - End Sub - Private Sub EnviarCorreoDevPed() - Try - Dim Body As String = GeneraCorreoDevPed() - Dim Asunto As String = $"SIG - Favor de surtir el siguiente {DdlTipoComprobante.SelectedItem.Text}" - Dim Hilo As New System.Threading.Thread(Sub() MandaCorreoDevPed(CorreoNotificacionPedDev, Asunto, Body)) - Hilo.Start() - Catch ex As Exception - OnError($"Ocurrió error al mandar el correo de solicitud de {DdlTipoComprobante.SelectedItem.Text}", ex) - End Try - End Sub - Private Sub MandaCorreoDevPed(Para As String, Asunto As String, Body As String) - Dim Mail As New ClsSisMail() - Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body) - End Sub - Private Function GeneraCorreoDevPed() As String - Dim strBody As New StringBuilder - - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.Append(" ") - strBody.AppendFormat("
    Favor de surtir el siguiente {0}

    ", DdlTipoComprobante.SelectedItem.Text) - strBody.AppendFormat("
    Datos de {0} ", DdlTipoComprobante.SelectedItem.Text) - strBody.Append(" ") - strBody.Append(" ") - strBody.AppendFormat(" ", LblSerie.Text, TxtFolio.Text) - strBody.Append(" ") - strBody.Append(" ") - strBody.AppendFormat(" ", UsuarioActual.Empresa.Empresa) - strBody.Append(" ") - strBody.Append(" ") - strBody.AppendFormat(" ", LblCliente.Text) - strBody.Append(" ") - strBody.Append(" ") - strBody.AppendFormat(" ", DdlSubProyectoDatos.SelectedItem.Text) - strBody.Append(" ") - strBody.Append(" ") - strBody.AppendFormat(" ", TxtFecha.Text) - strBody.Append(" ") - strBody.Append("
    Serie-Folio:{0}-{1}
    Empresa:{0}
    Cliente:{0}
    Sucursal:{0}
    Fecha:{0}
    ") - strBody.Append("
    ") - strBody.Append("
    ") - 'Cargo el detalle - - strBody.Append("
    ") - strBody.Append("
    ") - strBody.Append(" Productos/Servicios ") - strBody.Append(" ") - strBody.Append(" ") - - For Each dr As DataRow In TmpDT.Rows - strBody.AppendFormat("", - dr("Cantidad").ToString().FormatoNumero(), dr("UM").ToString(), dr("PS").ToString(), dr("Obs").ToString(), dr("SubProyecto").ToString(), dr("PU").ToString().FormatoNumero()) - - Next - - strBody.Append("
    CantidadUnidadProducto/ServicioNo. SerieProyectoPrecio
    {0}{1}{2}{3}{4}{5}
    ") - strBody.Append("
    ") - strBody.Append("
    ") - strBody.Append("") - - - Return strBody.ToString +#Region "Metodos Viejos" + Private Sub GeneraPDF(FechaFactura As DateTime, FolioFiscal As String, NoSerieCertificado As String, FechaCertificacion As DateTime, NoSerieCertificadoContribuyente As String, + DTConceptos As DataTable, SelloCFDi As String, SelloSAT As String, CBB As String, Folio As String, RutaXML As String, EsVistaPrevia As Boolean, MuestraAlert As Boolean, Optional MR As ReportViewer = Nothing) + + Alert("No se pudo generar el PDF", TipoMensaje.MsgError) + + End Sub + Private Sub GeneraPDFCBB(FechaFactura As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean) + + End Sub + Private Sub GeneraPDFCot(FechaCotizacion As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean, GeneraDescarga As Boolean) + + End Sub + Private Sub LkEliminarFactura_Click(sender As Object, e As EventArgs) Handles LkEliminarFactura.Click + If HdnPagado.Value.ToDecimal = 0 Then + Dim ObjVentas As New ClsVentas + ObjVentas.IniciaTransacSQL() + + If ObjVentas.EliminarVenta(CveVenta) Then + ObjVentas.Commit() + Alert("La venta ha sido eliminada correctamente.", TipoMensaje.MsgInformacion) + Else + ObjVentas.RollBack() + End If + + ObjVentas.Dispose() + Else + Alert("La venta no se puede eliminar ya que tiene pagos vinculados.", TipoMensaje.MsgError) + End If + End Sub + Private Sub RblComplementos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblComplementos.SelectedIndexChanged + If RblComplementos.SelectedValue.Contiene("5", "6") Then 'Directivo/Ejecutivo Estatal + trEntidad.Visible = True + trContaComplementos.Visible = True + trAmbito.Visible = False + trTipoCampaña.Visible = False + + ElseIf RblComplementos.SelectedValue = "7" Then 'Ejecutivo Nacional + trEntidad.Visible = False + trContaComplementos.Visible = True + trAmbito.Visible = False + trTipoCampaña.Visible = False + + ElseIf RblComplementos.SelectedValue = "8" Then 'Campaña/PreCampaña + trEntidad.Visible = True + trContaComplementos.Visible = True + trAmbito.Visible = True + trTipoCampaña.Visible = True + + End If + + UpDatosComplementos.Update() + End Sub + Private Sub GvPS_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPS.RowCommand + If e.CommandName = "Clonar" Then + Dim RowNum As Integer = Convert.ToInt32(e.CommandArgument) + Dim GvRow As GridViewRow = GvPS.Rows(RowNum) + TxtCantidad.Text = GvPS.Rows(RowNum).FCLiteral("LtlCantidad").Text + DdlClasificacion.SelectedValue = GvRow.DataKey("CveClasificacion") + DdlPS.SelectedValue = GvRow.DataKey("CvePS") + DdlPS_SelectedIndexChanged(Nothing, Nothing) + DdlUnidadMedida.SelectedValue = GvRow.DataKey("CveUM") + TxtObsPS.Text = GvRow.FCLiteral("LtlObsPS").Text + DdlProyecto.SelectedValue = GvRow.DataKey("CveProyecto") + DdlProyecto_SelectedIndexChanged(Nothing, Nothing) + DdlSubProyecto.SelectedValue = GvRow.DataKey("CveSubProyecto") + TxtPrecio.Text = GvRow.FCLiteral("LtlPU").Text + RegistraScript("Recalcula();") + LbAgregar_Click(Nothing, Nothing) + End If + End Sub + Protected Sub OrdenarGvPS(ByVal sender As Object, ByVal e As EventArgs) + + For Each row As GridViewRow In GvPS.Rows + TmpDT.Rows(row.RowIndex)("Orden") = row.FCTextBox("TxtOrden").Text.ToEntero + Next + + Dim resultados = From OrdenDT In TmpDT + Order By OrdenDT("Orden").ToString.ToEntero + Select OrdenDT + TmpDT = resultados.CopyToDataTable + CalculaTotalesVenta() + + GvPS.DataSource = TmpDT + GvPS.DataBind() + UpPS.Update() + + End Sub + Private Sub LkCotizacionAutorizar_Click(sender As Object, e As EventArgs) Handles LkCotizacionAutorizar.Click + EsSupervisor = True + GeneraPDFCotizacion(True) + Alert("La cotización ha sido enviada al correo de nuestro cliente:" & Mail) + End Sub +#End Region + +#Region "Cancelar, Generar y mandar por correo el acuse de cancelación." + Private Sub BtnEnviarMailCancelacion_Click(sender As Object, e As EventArgs) Handles BtnEnviarMailCancelacion.Click + ImprimeCancelacion(CveVenta) + End Sub + Public Sub ImprimeCancelacion(CveVenta As Integer) + Dim ObjVentas As New ClsVentas + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) + Dim FolioFiscal = drv("FolioFiscal").ToString + Dim SelloCancelacion = drv("SelloCancelacion").ToString + Dim FechaCancelacion = drv("FechaCancelacion").ToString.ToDateTime.ToString("dd/MM/yyyy HH:mm:ss") + Dim RFC = UsuarioActual.Empresa.RFC + Dim Archivo As New System.IO.FileInfo("Empresas\Grales\Formatos\AcuseCancelacion.rdlc") + Dim params As New List(Of ReportParameter) + params.Add(New ReportParameter("FechaCancelacion", FechaCancelacion.ToString)) + params.Add(New ReportParameter("FolioFiscal", FolioFiscal)) + params.Add(New ReportParameter("RFCEmisor", RFC)) + params.Add(New ReportParameter("SelloCancelacion", SelloCancelacion)) + + Dim ObjetoPDF As Byte() = StreamPDF("Empresas\Grales\Formatos\AcuseCancelacion.rdlc", ObjVentas.DtResultados, params, "AcuseCancelacion" & CveVenta) + Dim ObjMail As New ClsSisMail + Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) + Dim Asunto As String = String.Empty + Dim Cuerpo As String = String.Empty + Dim ResultadoMail As Integer + Dim sb As New StringBuilder() + If UsuarioActual.CveEmpresa = 119 Then + sb.Append("") + sb.Append("") + sb.Append("") + sb.Append("") + sb.Append(" Acuse De Cancelación") + sb.Append(" ") + sb.Append("") + sb.Append("") + sb.Append(" ") + sb.Append($" Estimado Cliente {NombreCliente},

    ") + sb.Append($" Le informamos que Agroquímicos JAM, S.A. DE C.V ha cancelado el CFDI {Serie}-{Folio}, el cual ha quedado sin Efectos Fiscales y encontrará adjunto en este correo el Acuse de
    ") + sb.Append($" cancelación del SAT.
    ") + sb.Append(" POR LO QUE PEDIMOS ELIMINARLO Y NO INCLUIRLO EN SU CONTABILIDAD, YA QUE PUEDE REPRESENTAR UN PROBLEMA FISCAL PARA USTED O SU EMPRESA CUANDO EL SAT REALICE UNA FUTURA AUDITORIA
    ") + sb.Append(" EN SU CONTABILIDAD.
    ") + sb.Append(" ") + sb.Append("




    ") + sb.Append(" Este correo se generó automaticamente, favor de no responder este mensaje.") + sb.Append("
    ") + sb.Append("") + sb.Append("") + Else + sb.Append("") + sb.Append("") + sb.Append("") + sb.Append("") + sb.Append(" Acuse De Cancelación") + sb.Append(" ") + sb.Append("") + sb.Append("") + sb.Append(" ") + sb.Append($" Estimado Cliente {NombreCliente},

    ") + sb.Append($" A través del presente medio la Empresa {UsuarioActual.Empresa.Empresa} - {RFC}, canceló el documento tipo {DdlTipoComprobante.SelectedItem.Text}
    ") + sb.Append($" con folio {Serie}-{Folio} y el Importe de ${TxtTotal.Text}.

    ") + sb.Append(" Le hacemos llegar el acuse de cancelación.
    ") + sb.Append(" ") + sb.Append("




    ") + sb.Append(" Este correo se generó automaticamente, favor de no responder este mensaje.") + sb.Append("
    ") + sb.Append("") + sb.Append("") + End If + Asunto = $"Acuse de Cancelacion {Serie}-{Folio}" + Cuerpo = sb.ToString + Dim DisplayName As String = "" + If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM" + LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.ArchivoBinario = ObjetoPDF, .NombreArchivo = $"AcuseCancelacion{Serie}-{Folio}.pdf"}) + If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then + ResultadoMail = 1 + Alert("El acuse de cancelación ha sido envíado correctamente.") + Else + ResultadoMail = 0 + End If + + End If + End Sub + + Private Sub LbCancelarDocumento_Click(sender As Object, e As EventArgs) Handles LbCancelarDocumento.Click + If VentaSaldoAlmacen > 0 Then + Alert("El pedido no se puede cancelar ya que tiene movimientos de almacén.
    Nota: Primero hay que hacer la devolución al almacén", TipoMensaje.MsgAdvertencia) + Else + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then + Dim sb As New StringBuilder() + sb.Append("La factura se encuentra en el siguiente estatus del SAT:
    ") + + Dim TotalT As Decimal = TxtTotal.Text.ToDecimal + Dim RFCReceptor As String = LblRFC.Text.Trim + Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True) + If Vigencia IsNot Nothing Then + If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then + Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + If String.IsNullOrEmpty(Vigencia.EsCancelable) Then + sb.Append("No encontrado
    ") + Else + sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) + End If + Else + sb.Append("No encontrado
    ") + End If + + sb.Append("Está seguro de cancelar el documento?.") + + LblCancelarDocumento.Text = sb.ToString() + + RegistraScript("$('#ModalCancelarDocumento').modal();") + UpCancelarDocumento.Update() + 'Alert(sb.ToString(), TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnCancelarDocumentoConfirmar()", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") + Else + CancelarDocumento() + End If + End If + + End Sub + Protected Sub BtnCancelarDocumento_Click(sender As Object, e As EventArgs) + CancelarDocumento() + RegistraScript("$('#ModalCancelarDocumento').modal('hide');") + End Sub + + Private Sub CancelarRefacturada() + Dim CancelacionFecha As Date + Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() + Dim CancelacionAcuse As String = "" + Dim Mensaje As String = "" + Dim ObjCancelacion As New Timbrado + Dim TotalT As Decimal = TxtTotal.Text.ToDecimal + Dim RFCReceptor As String = LblRFC.Text.Trim + Dim CvePACCancelacion As Integer = CvePAC + Dim CveEstatus As Integer = 4 + + Try + If FolioFiscal <> "" Then + If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then + 'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017 + CancelacionFecha = ObjCancelacion.CancelacionFecha + CancelacionAcuse = ObjCancelacion.CancelacionAcuse + CveEstatus = 5 + Else + Alert("La factura no se pudo cancelar ante el SAT", TipoMensaje.MsgError) + Exit Sub + End If + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + + If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IdPoliza, CvePAC:=CvePACCancelacion) Then + ObjVentas.Commit() + Alert("El nuevo estatus se guardó correctamente") + Else + ObjVentas.RollBack() + Alert("Ocurrió un error al intentar cancelar la factura") + End If + + Catch ex As Exception + ObjVentas.RollBack() + Mensaje = "Ocurrio un error al Cancelar la factura" + GuardaLog($"{ex.Message}") + End Try + + ObjVentas.Dispose() + End Sub + Private Function DecodeBase64(ByVal strXMLCodificado As String) As String + Try + Dim decbuff As Byte() = Convert.FromBase64String(strXMLCodificado) + Return System.Text.Encoding.UTF8.GetString(decbuff) + Catch + Return "" + End Try End Function -#End Region + 'Private Sub ActualizaEstatusVentaCancelada(Optional CveEstatusCancelacion As Integer = 5) + ' Me.CveEstatus = CveEstatusCancelacion + + ' Dim ObjVentas As New ClsVentas() + ' If CveEstatusCancelacion = 5 Then + ' Dim IDPoliza As Integer = -1 + ' Dim ErrorCancelar As Boolean = False + ' Dim MensajeError As String = "" + ' Dim CvePACCancelacion As Integer = CvePAC + + ' Dim ObjAC As ClsContPAQi = Nothing + ' ObjVentas.IniciaTransacSQL() + ' Try + ' If UsuarioActual.Empresa.UsaAC Then + ' ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + ' IDPoliza = GenerarPolizaAC(ObjAC, True) + ' If IDPoliza <= 0 Then + ' ErrorCancelar = True + ' MensajeError = "Ocurrió un error al generar la poliza de cancelación." + ' End If + ' End If + + ' Dim solicitud = New WSGF.Service1SoapClient() + ' Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) + + ' If acuse.Estado = 0 Then + ' Dim xmlAcuse = New System.Xml.XmlDocument() + ' xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) + ' Dim CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText + ' Dim CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() + + ' If Not ObjVentas.UpdateEstatusFactura(Me.CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion) Then + ' ErrorCancelar = True + ' MensajeError = "Ocurrió un error al guardar el estatus de cancelación." + ' End If + ' Else + ' 'sino se pudo sacar el acuse, porque se canceló en el SAT, debe de marcarlo + ' End If + ' Catch ex As Exception + ' ErrorCancelar = True + ' Alert("Ocurrió un error al actualizar el estatus", TipoMensaje.MsgError) + ' Finally + ' If Not ErrorCancelar Then + ' ObjVentas.Commit() + + ' If Me.CveEstatus = 5 Then + ' Dim MensajeAlert As New StringBuilder + ' MensajeAlert.Append("El Documento se canceló correctamente.") + ' MensajeAlert.Append($"
    Imprimir Acuse") + ' MensajeAlert.Append("

    ¿Desea enviar el Acuse de Cancelación al Cliente?") + ' Alert(MensajeAlert.ToString, TipoMensaje.MsgConfirmacion, "BtnEnviarMailCancelacion()", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") + ' Else + ' Alert("El documento se canceló exitosamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="location.reload();") + ' End If + ' LbCancelarDocumento.Enabled = False + ' If ObjAC IsNot Nothing Then ObjAC.Commit() + ' Else + ' Alert(MensajeError, TipoMensaje.MsgError) + ' ObjVentas.RollBack() + ' If ObjAC IsNot Nothing Then ObjAC.RollBack() + ' End If + + ' ObjVentas.Dispose() + ' If ObjAC IsNot Nothing Then ObjAC.Dispose() + ' End Try + + ' ElseIf CveEstatusCancelacion = 20 Then + ' If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta) Then + ' Alert("El estatus de la factura fue cambiado a 'Cancelación en Proceso'") + ' End If + ' ObjVentas.Dispose() + ' End If + + + 'End Sub + + Private Sub CancelarDocumento(Optional EsRefacturacion As Boolean = False) + + 'Si es cancelacion de una refactura ignoramos las condiciones + If Me.CveEstatus = 13 Then + CancelarRefacturada() + End If + + 'La validacion de saldos cuando es refacturacion se hace antes asi que si es refacturacion ignoramos esta condicion, si es Anticipo verifica que no esté aplicado + If DdlTipoComprobante.SelectedValue = "Ant" AndAlso (HdnPagado.Value.ToDecimal > 0 Or GvAntNC.Rows.Count > 0) Then + Alert("La factura no se puede cancelar debido a que tiene pagos vinculados.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'La validacion de saldos cuando es refacturacion se hace antes asi que si es refacturacion ignoramos esta condicion + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") AndAlso HdnPagado.Value.ToDecimal > 0 Then + Alert("La factura no se puede cancelar debido a que tiene pagos vinculados.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + + 'Si la remision esta facturada no se puede cancelar + If DdlTipoComprobante.SelectedValue = "Rem" Then + Dim ObjV As New ClsVentas + If ObjV.VerificarRemisionFacturada(CveVenta) Then + If ObjV.DtResultados.Rows.Count > 0 Then + Alert("La remisión no se puede cancelar debido a que ya esta vinculada a una factura.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + ObjV.Dispose() + End If + + 'CARGA REMISIONES DE LA VENTA DEVUELTA + Dim DtDevRem As New DataTable + If Not EsRefacturacion Then + Dim ObjInventarioTemporal As New ClsInventarios() + If ObjInventarioTemporal.GetDevolucionRemisionesCanceladas(CveVenta) Then + DtDevRem = ObjInventarioTemporal.DtResultados + Else + Alert("Ocurrió un error al verificar los movimientos de almacén relacionados al documento.", TipoMensaje.MsgError) + ObjInventarioTemporal.Dispose() + Exit Sub + End If + ObjInventarioTemporal.Dispose() + End If + + '[IPP] FALTA TERMINAR 27/Noviembre/2018 + '' si tiene movimientos en almacen que se hallan surtido en el documento actual, y sigue sin ser marcado como devuelto + 'If (GvInv.Rows.Count > 0 AndAlso DevolucionAlmacen.Contiene(0, 1)) And DtDevRem.COUNT("CantidadSurtida", "ISNULL(CveRem,0) = 0") > 0 Then ' [COMENTADO IPP 3 Agosto 2017] | AndAlso Not (DdlTipoComprobante.SelectedValue.Contiene("Rem", "DPe")) | REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN + ' Alert("La factura no se puede cancelar debido a que tiene movimientos de inventario.", TipoMensaje.MsgAdvertencia) + ' Exit Sub + 'End If + + Dim ReviveRemision As Boolean = False + 'RMF. ANOTACION. cuando se cancela, y tiene relacionada una remisión, y esta no se cancelará. debe de hacer en automático los movimientos al almacen de entrega por adelantado + If Not EsRefacturacion AndAlso ChkCanRem.Visible AndAlso ChkCanRem.Checked = False Then + ReviveRemision = True + End If + If Not EsRefacturacion AndAlso (VentaSaldoAlmacen > 0 AndAlso DevolucionAlmacen.Contiene(0, 1)) AndAlso Not ChkDevAlm.Checked And ReviveRemision = False Then ' [COMENTADO IPP 3 Agosto 2017] | AndAlso Not (DdlTipoComprobante.SelectedValue.Contiene("Rem", "DPe")) | REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN + Alert("La factura no se puede cancelar debido a que tiene movimientos de inventario.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + Dim CancelacionFecha As Date + Dim CancelacionAcuse As String = "" + Dim MensajeError As String = "" + Dim ObjCancelacion As New Timbrado + Dim TotalT As Decimal = TxtTotal.Text.ToDecimal + Dim RFCReceptor As String = LblRFC.Text.Trim + Dim CvePACCancelacion As Integer = CvePAC + Dim CveEstatus As Integer = 4 + Dim IDPoliza As Integer = -1 + Dim CvePrePoliza As Integer + Dim CvePlantillaPoliza As Integer + Dim ErrorCancelar As Boolean = False + + Dim Continuar As Boolean = False + Dim ContinuarCancelacion As Boolean = False + Dim ObtenerAcuse As Boolean = False + Dim RequiereAceptacion As Boolean = False + Dim Mensaje As String = "" + Try + If FolioFiscal <> "" Then + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then + + Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), UsuarioActual.Empresa.FacturaProduccion) + If Vigencia IsNot Nothing Then + If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then + Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + If Vigencia.Estado.ToUpper().Contains("CANCELADO") Then + ContinuarCancelacion = False + ObtenerAcuse = True + Dim solicitud = New WSGF.Service1SoapClient() + Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) + + If acuse.Estado = 0 Then + Dim xmlAcuse = New System.Xml.XmlDocument() + xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) + CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText + CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() + CveEstatus = 5 + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + CveEstatus = 5 + End If + + ElseIf Vigencia.Estado.ToUpper().Contains("VIGENTE") Then + + If Vigencia.EstatusCancelacion.ToUpper() = "EN PROCESO" Then + CveEstatus = 20 + ContinuarCancelacion = False + If ChkCanRem.Checked Then SeCancelaRemisionProceso = True + ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE CON ACEPTACIÓN" Then + CveEstatus = 20 + ContinuarCancelacion = True + RequiereAceptacion = True + If ChkCanRem.Checked Then SeCancelaRemisionProceso = True + ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then + ContinuarCancelacion = True + CveEstatus = 5 + End If + + Else + If Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then + ContinuarCancelacion = True + CveEstatus = 5 + Else + 'Alert("La factura no se puede cancelar debido a que no se encontro su estatus en el SAT.", TipoMensaje.MsgAdvertencia) + 'Exit Sub + CveEstatus = 20 + ContinuarCancelacion = False + CancelacionFecha = Now.Date + CancelacionAcuse = "" + If ChkCanRem.Checked Then SeCancelaRemisionProceso = True + End If + End If + Else + Alert("No se pudo comprobar la vigencia de la factura.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + If Not ObtenerAcuse Then + If ContinuarCancelacion Then + If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then + 'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017 + If RequiereAceptacion Then + CancelacionFecha = Now.Date + CancelacionAcuse = "" + CveEstatus = 20 + If ChkCanRem.Checked Then SeCancelaRemisionProceso = True + Else + CancelacionFecha = ObjCancelacion.CancelacionFecha + CancelacionAcuse = ObjCancelacion.CancelacionAcuse + CveEstatus = 5 + End If + Else + Alert("La factura no se pudo cancelar ante el SAT", TipoMensaje.MsgError) + Exit Sub + End If + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + End If + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + Catch ex As Exception + MensajeError = "Ocurrió un Error al Cancelar la factura con los servicios del SAT." + GuardaLog($"{MensajeError} - Error:{ex.Message}") + Alert(MensajeError, TipoMensaje.MsgError) + Exit Sub + End Try + + Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() + Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) + Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) + Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) + Dim ObjContrato As New ClsContratos(ObjVentas.IniciaTransacSQL()) + Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) + Dim ObjAC As ClsContPAQi = Nothing + If UsuarioActual.Empresa.UsaAC Then + ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + End If + CreaObjetosVenta() + + ObjFactura.CveVenta = CveVenta + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + CvePlantillaPoliza = 7 + ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem", "Ant") Then + CvePlantillaPoliza = 4 + Else + CvePlantillaPoliza = 4 + End If + + If ((HplSaldoAuxiliar.Text.ToDecimal > 0 OrElse (TxtTotal.Text.ToDecimal = 0 AndAlso UsuarioActual.CveEmpresa.Contiene(72) AndAlso ObjFactura.TipoDocto.Contiene("Ing"))) AndAlso CveEstatus.Contiene(4, 5)) OrElse CvePlantillaPoliza = 7 Then + 'RMF. 2018.08.08 cuando se cancela, la póliza debe de ser de diario + CvePrePoliza = ObjConta.AddPrePolizas("Ventas/CancelarDocumento", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=3) + ObjFactura.CvePrePoliza = CvePrePoliza + + 'CANCELAR PAGOS + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + If Not ErrorCancelar Then + If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, CvePrePoliza) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al generar la prepoliza de cancelación de pago." + End If + End If + End If + + 'CANCELA PREPOLIZA + If Not ErrorCancelar Then + ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas, ObjEventos) + MensajeError = "Ocurrió un error al generar la prepoliza de cancelación." + End If + + 'CANCELA IMPUESTOS LOCALES + If Not ErrorCancelar Then + ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, -1) + MensajeError = "Ocurrió un error al cancelar los impuestos locales." + End If + End If + + 'CANCELA CONTRATOS + If Not EsRefacturacion Then + If Not ErrorCancelar Then + ErrorList = New List(Of String) + If ObjFactura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then + GuardarContratoAvanceEstimaciones(ObjContrato, ObjFactura, ErrorList, -1, True) + ErrorCancelar = ErrorList.Count > 0 + MensajeError = "Ocurrió un error al cancelar las estimaciones del contrato." + ElseIf ObjFactura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then + GuardarContratoAvanceEstimaciones(ObjContrato, ObjFactura, ErrorList, 1, True) + ErrorCancelar = ErrorList.Count > 0 + MensajeError = "Ocurrió un error al cancelar los avances del contrato." + End If + End If + End If + + + 'DESVINCULA COTIZACIONES PREDECESORAS + If Not EsRefacturacion Then + If Not ErrorCancelar Then + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then + If Not ObjVentas.LiberarCotizacionesFacturadas(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular las cotizaciones." + End If + End If + End If + End If + + 'DESVINCULA PEDIDOS2 PREDECESORES + If Not EsRefacturacion Then + If Not ErrorCancelar Then + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then + If Not ObjVentas.LiberarPedidos2Facturados(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular los pedidos." + End If + End If + End If + End If + + + 'DESVINCULA OCs PREDECESORAS + If Not EsRefacturacion Then + If Not ErrorCancelar Then + If DdlTipoComprobante.SelectedValue = "Ing" Then + If Not ObjVentas.LiberarOCFacturadas(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular las Ordenes de Compra." + End If + End If + End If + End If + + 'ELIMINA LAS VENTAS DETALLE DE LA DEVOLUCION + If Not EsRefacturacion Then + If Not ErrorCancelar Then + If DdlTipoComprobante.SelectedValue = "Dev" Then + If Not ObjVentas.RemoveVentaDetalleDevolucion(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al eliminar las ventas detalle devolución." + End If + End If + End If + End If + 'POLIZA DE CANCELACION + If Not EsRefacturacion Then + If Not ErrorCancelar Then + If UsuarioActual.Empresa.UsaAC Then + IDPoliza = GenerarPolizaAC(ObjAC, True) + If IDPoliza <= 0 Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al generar la poliza de cancelación." + End If + End If + End If + End If + + 'DEVOLUCION DE ALMACEN + If ChkDevAlm.Checked Or ReviveRemision Then + Dim TieneSalida As Boolean = False + Dim DtDatos As New DataTable + Dim DtExistencias As New DataTable + + If DevolucionAlmacen = 0 Then + Dim EstatusDevolucion = 1 + If Not ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al solicitar la devolucion de almacen." + End If + End If + + If Not ErrorCancelar AndAlso ObjInventario.EntregaAlmacenGet(CveVenta) Then + If ObjInventario.DtResultados IsNot Nothing AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then + DtDatos = ObjInventario.DtResultados + DtDatos.Columns.Add("Consec", GetType(Integer)) + DtDatos.Columns.Add("CantidadGV", GetType(Double)) + DtDatos.Columns.Add("CantidadTraspaso", GetType(Double)) + Dim Index = 1 + For Each Dr As DataRow In DtDatos.Rows + Dr("Consec") = Index + Dr("CantidadGV") = Dr("CantidadF") + Index += 1 + Next + + If DtDatos IsNot Nothing AndAlso DtDatos.Rows.Count > 0 AndAlso ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero > 0 Then + Dim Filtro As String '= If(ObjInventario.DtResultados.Rows(0)("TipoDocto").ToString.Contiene({"Ing", "Dev", "Ped"}), "CveConcepto = 3", "CveConcepto = 9") + Select Case ObjInventario.DtResultados.Rows(0)("TipoDocto").ToString + Case "Ing", "Ped" + Filtro = "CveConcepto = 3" + Case "Dev" + Filtro = "CveConcepto = 3" + Case Else + Filtro = "CveConcepto = 9" + End Select + If ObjInventario.GetInv_Mov(ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero, UsuarioActual.CveEmpresa) Then + DtExistencias = ObjInventario.DtResultados.FiltraParametros($"CvePS Is Not NULL AND {Filtro}") + + If DtExistencias.Rows.Count > 0 Then + TieneSalida = True + End If + + Else + ErrorCancelar = True + MensajeError = "Ocurrió un error al cargar los datos de devolución. Por favor vuelva a intentar." + End If + End If + End If + End If + + If Not ErrorCancelar AndAlso TieneSalida Then + Dim DtDatosDetalle As New DataTable + DtDatosDetalle.Columns.Add("CveVentaDetalle", GetType(Integer)) + DtDatosDetalle.Columns.Add("Consec", GetType(Integer)) + DtDatosDetalle.Columns.Add("ConsecId", GetType(Integer)) + DtDatosDetalle.Columns.Add("CvePS", GetType(Integer)) + DtDatosDetalle.Columns.Add("PS", GetType(String)) + DtDatosDetalle.Columns.Add("CveUM", GetType(Integer)) + DtDatosDetalle.Columns.Add("SerieLote", GetType(String)) + DtDatosDetalle.Columns.Add("FechaCaducidad", GetType(String)) + DtDatosDetalle.Columns.Add("FueTraspaso", GetType(Integer)) + + Dim DtDatosDetalleLote As New DataTable + DtDatosDetalleLote.Columns.Add("CveVentaDetalle", GetType(Integer)) + DtDatosDetalleLote.Columns.Add("Consec", GetType(Integer)) + DtDatosDetalleLote.Columns.Add("ConsecId", GetType(Integer)) + DtDatosDetalleLote.Columns.Add("Cantidad", GetType(Double)) + DtDatosDetalleLote.Columns.Add("CvePS", GetType(Integer)) + DtDatosDetalleLote.Columns.Add("PS", GetType(String)) + DtDatosDetalleLote.Columns.Add("CveUM", GetType(Integer)) + DtDatosDetalleLote.Columns.Add("Lote", GetType(String)) + DtDatosDetalleLote.Columns.Add("Batch", GetType(String)) + DtDatosDetalleLote.Columns.Add("FechaCaducidad", GetType(String)) + DtDatosDetalleLote.Columns.Add("FueTraspaso", GetType(Integer)) + + Dim DtTraspasos As New DataTable + DtTraspasos.Columns.Add("CveAlmacen", GetType(Integer)) + DtTraspasos.Columns.Add("Almacen", GetType(String)) + DtTraspasos.Columns.Add("CveMovimientoSalida", GetType(Integer)) + DtTraspasos.Columns.Add("FolioSalida", GetType(Integer)) + DtTraspasos.Columns.Add("CveMovimientoEntrada", GetType(Integer)) + DtTraspasos.Columns.Add("FolioEntrada", GetType(Integer)) + + Dim ConceptoMovimiento = 18 + Dim CveMovimiento As Integer = 0 + Dim Folio As Integer = 0 + Dim CantidadPendiente As Decimal = 0 + Dim DtDetalle As New DataTable + Dim DtDetalleLote As New DataTable + + CveMovimiento = ObjInventario.AddMovimiento(CveAlmacenDevolucion, ConceptoMovimiento, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveAlmacenDestino:=-1) + Folio = ObjInventario.Folio + + 'SALIDA DE ALMACEN - SALIDA POR TRASPASO CUANDO ES REMISION - DEVOLUCION (SI ES TRASPASO Y TIENE CONTRATO NO HACE DEVOLUCIóN) + 'If Not (CveContrato > 0 And CveAlmacenTraspasoDestino > 0) Then + If CveMovimiento > 0 Then + + 'ES EL MOVIMIENTO PRINCIPAL + CantidadPendiente = 0 + For Each Dr As DataRow In DtDatos.Rows + CantidadPendiente = Dr("CantidadGV").ToString.ToDecimal - Dr("CantidadTraspaso").ToString.ToDecimal + If CantidadPendiente > 0 Then + Dim PU As Decimal = 0 + + 'SI FUE POR SERIELOTE + DtDetalle = DtDatosDetalle.FiltraParametros(String.Format("ConsecId = {0} AND FueTraspaso IS NULL", Dr("Consec"))) + DtDetalleLote = DtDatosDetalleLote.FiltraParametros(String.Format("ConsecId = {0} AND FueTraspaso IS NULL", Dr("Consec"))) + If DtDetalle.Rows.Count > 0 Then + For Each Dr1 As DataRow In DtDetalle.Rows + If DtExistencias IsNot Nothing Then + PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero} AND SerieLote = '{Dr1("SerieLote").ToString}'").ToString.ToDecimal + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, 1, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, SerieLote:=Dr1("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al procesar los conceptos con serie. Por favor vuelva a intentar." + Exit For + End If + Next + ElseIf DtDetalleLote.Rows.Count > 0 Then + For Each Dr1 As DataRow In DtDetalleLote.Rows + If DtExistencias IsNot Nothing Then + PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero} AND SerieLote = '{Dr1("SerieLote").ToString}'").ToString.ToDecimal + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, Dr1("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, Lote:=Dr1("Lote").ToString, Batch:=Dr1("Batch").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al procesar los conceptos con serie. Por favor vuelva a intentar." + Exit For + End If + Next + Else + If DtExistencias IsNot Nothing Then + PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero}").ToString.ToDecimal + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, CantidadPendiente, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al procesar los conceptos de salida. Por favor vuelva a intentar." + Exit For + End If + End If + + End If + Next + Else + ErrorCancelar = True + End If + + If Not ErrorCancelar Then + Dim DtCostos As DataTable = Nothing + Dim ValorInventario As Decimal = 0 + If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then + DtCostos = ObjInventario.DtResultados + + Dim tmpCostos As DataTable = DtCostos.FiltraParametros("", "", {"CveClasificacion"}) + Dim IdCtaContableAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero + Dim CveCuentaAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero + Dim IdCtaContable As Integer = 0 + Dim CveCuenta As Integer = 0 + If tmpCostos.Rows.Count > 0 Then + + + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + Dim Fecha As Date = Now + Dim CveCliente As Integer = ObjVentas.DtResultados(0)("CveCliente").ToString.ToEntero + Dim ClienteNombre As String = ObjVentas.DtResultados(0)("ClienteNombre").ToString + Dim SerieFolio As String = ObjVentas.DtResultados(0)("SerieFolio").ToString + Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL() + Dim TotalCostoAcumulado As Decimal = 0 + Dim cont As Integer = 1 + + Dim CvePrePolizaDev As Integer = ObjConta.AddPrePolizas("Inventario/RecepcionEntrega", 4, TotalCosto, TotalCosto, 1, Fecha, ClienteNombre, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + 'Se agrega movimiento separado por la cuenta de ventas (ER) + For Each RowInv As DataRow In tmpCostos.Rows + ValorInventario = DtCostos.SUMD("Total", $"CveClasificacion = {RowInv("CveClasificacion")}").RoundSQL() + TotalCostoAcumulado += ValorInventario + + 'cuando es el último movimiento y hay diferencias en los importes + If cont = DtCostos.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then + ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) + End If + + 'Concepto = String.Format("{0} - {1}", Row2("Clasificacion").ToString, Row2("SubProyecto").ToString) + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostosSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + + If Not ErrorCancelar Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, False, -1 * ValorInventario, SerieFolio, 69, SerieFolio, Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ImporteMX:=-1 * ValorInventario, CveCuenta:=CveCuenta, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero) Then + ErrorCancelar = True + End If + End If + + cont += 1 + Next + + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, True, -1 * TotalCosto, SerieFolio, 68, SerieFolio, Fecha, IdCtaContableAlmacen, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ImporteMX:=-1 * TotalCosto, CveCuenta:=CveCuentaAlmacen) Then + ErrorCancelar = True + End If + + 'AutoConta - El movimiento 1 es el de Venta + + Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" + + If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue = "Ant" Then + AutoConta = False + End If + + If AutoConta And Not ErrorCancelar Then + Dim ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) + + If IdCtaContable > 0 Then + If Not ObjConta.ContabilizarPrePoliza(CvePrePolizaDev, UsuarioActual.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then + Alert("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico") + End If + Else + Alert(String.Format("No se puede contabilizar ya que falta asignación de las cuentas contables"), TipoMensaje.MsgAdvertencia) + End If + + ObjContPaq.Dispose() + End If + + Else + ErrorCancelar = True + MensajeError = "Ocurrió un Error al ingresar las prepolizas" + End If + + End If + End If + End If + + If Not ErrorCancelar Then + If ObjInventario.VentasAlmacenApartadosGet(CveVenta) Then + + Dim DtTempApartados = ObjInventario.DtResultados.FiltraParametros("CveTipoAlmacen = 9", "CveAlmacen") + Dim CveMovimientoSalidaApartado = -1 + Dim CveAlmacenApartado = -1 + Dim CveAlmacenOrigen = CveAlmacenDevolucion + Dim FolioSalida As Integer = 0, FolioEntrada = 0, CveMovimientoSalida = 0, CveMovimientoEntradaApartado = 0 + + For Each Dr As DataRow In DtTempApartados.Rows + + If CveMovimientoSalidaApartado = -1 Or CveAlmacenApartado <> Dr("CveAlmacen").ToString.ToEntero Then + CveMovimientoSalidaApartado = ObjInventario.AddMovimiento(CveAlmacenOrigen, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveVendedor:=1, CveCliente:=CveCliente, CveAlmacenDestino:=Dr("CveAlmacen").ToString.ToEntero) + FolioSalida = ObjInventario.Folio + CveAlmacenApartado = Dr("CveAlmacen").ToString.ToEntero + + Dim DrMovto = DtTraspasos.NewRow + DrMovto("Almacen") = Dr("Almacen").ToString.ToEntero + DrMovto("CveAlmacen") = Dr("CveAlmacen").ToString.ToEntero + DrMovto("CveMovimientoSalida") = CveMovimientoSalidaApartado + DrMovto("FolioSalida") = FolioSalida + DtTraspasos.Rows.Add(DrMovto) + End If + + If Not CveMovimientoSalidaApartado > 0 Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar los movimientos de control de apartados" + Exit For + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar los movimientos de control de apartados" + Exit For + End If + Next + + If Not ErrorCancelar Then + For Each Dr1 As DataRow In DtTraspasos.Rows + CveMovimientoSalida = Dr1("CveMovimientoSalida").ToString.ToEntero + + CveMovimientoEntradaApartado = ObjInventario.AddMovimiento(Dr1("CveAlmacen").ToString.ToEntero, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", CveAlmacenDestino:=CveAlmacenDevolucion, CveMovimientoRelacionado:=CveMovimientoSalida, Guia:="", CveContrato:=CveContrato, CveVendedor:=-1, CveCliente:=CveCliente) + FolioEntrada = ObjInventario.Folio + + If Not CveMovimientoEntradaApartado > 0 Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al procesar los movimientos de traspaso de apartado. Por favor vuelva a intentar." + Exit For + End If + + Dr1("CveMovimientoEntrada") = CveMovimientoEntradaApartado + Dr1("FolioEntrada") = FolioEntrada + + If ObjInventario.GetMovimientosDetalle(CveMovimientoSalida, UsuarioActual.CveEmpresa) Then + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al procesar los conceptos de traspaso de apartado. Por favor vuelva a intentar." + Exit For + End If + Next + End If + + If ErrorCancelar Then Exit For + Next + End If + + End If + End If + + 'DEVOLUCION REMISION - REGRESA LAS EXISTENCIAS A ENTREGA POR ADELANTADO SI LA FACTURA VIENE DE REMISION + If Not ErrorCancelar Then + Dim DtMovtosDev As New DataTable + Dim CveAlmacenTraspasoDestinoDevRem = -1 + + Dim CveVentaDetalleRem = -1 + Dim CantidadDevolver As Decimal = 0 + Dim CantidadRem As Decimal = 0 + Dim CveMovimientoSalidaDevRem As Integer = 0 + Dim FolioMovimientoSalidaDevRem As Integer = 0 + Dim CveMovimientoEntradaDevRem As Integer = 0 + Dim FolioMovimientoEntradaDevRem As Integer = 0 + + 'CARGA REMISIONES DE LA VENTA DEVUELTA + If ObjInventario.GetDevolucionRemisionesFacturadas(CveVenta) Then + DtDevRem = ObjInventario.DtResultados.FiltraParametros("CantidadAlmacen > 0") + Else + ErrorCancelar = True + End If + + 'CARGA CONCEPTOS DEVUELTOS EN LA VENTA + If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then + DtMovtosDev = ObjInventario.DtResultados + Else + ErrorCancelar = True + End If + + If Not ErrorCancelar Then + If DtDevRem.Rows.Count > 0 And DtMovtosDev.Rows.Count > 0 Then + + For Each DrMovtos As DataRow In DtDevRem.FiltraParametros("", "CveRem", {"CveRem", "CveAlmacenTraspasoDestino"}).Rows + + 'CHECO SI NO SE VA A CANCELAR + Dim SeCancela As Boolean = False + If ChkCanRem.Checked Then + For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows + If Gvr.FCCheckBox("ChkCancelarRemision").Checked AndAlso DrMovtos("CveRem").ToString.ToEntero = Gvr.DataKey("CveVenta").ToString.ToEntero Then + SeCancela = True + Exit For + End If + Next + End If + + If Not SeCancela Then + + CveAlmacenTraspasoDestinoDevRem = DrMovtos("CveAlmacenTraspasoDestino").ToString.ToEntero + If Not CveAlmacenTraspasoDestinoDevRem > 0 Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al obtener el almacén de devolucion de remisión." + Exit For + End If + + 'SALIDA GENERAL + CveMovimientoSalidaDevRem = ObjInventario.AddMovimiento(CveAlmacenDevolucion, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimiento, CveAlmacenDestino:=CveAlmacenTraspasoDestinoDevRem) + FolioMovimientoSalidaDevRem = ObjInventario.Folio + + 'ENTRADA ADELANTADO + CveMovimientoEntradaDevRem = ObjInventario.AddMovimiento(CveAlmacenTraspasoDestinoDevRem, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimientoSalidaDevRem, CveAlmacenDestino:=CveAlmacenDevolucion) + FolioMovimientoEntradaDevRem = ObjInventario.Folio + + If Not (CveMovimientoSalidaDevRem > 0 And CveMovimientoEntradaDevRem > 0) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al generar los movimientos de devolución a remisión." + Exit For + End If + + + 'SALIDA POR TRAPASO DE GENERAL + For Each DrRem As DataRow In DtDevRem.FiltraParametros($"CveRem = {DrMovtos("CveRem")}").Rows + CveVentaDetalleRem = DrRem("CveVentaDetalleRem").ToString.ToEntero + CantidadRem = DrRem("CantidadFacturada").ToString.ToDecimal + 'CantidadDevolver = DtMovtosDev.FiltroPrimeroValor("Cantidad", $"CveVentaDetalle = {DrRem("CveVentaDetalle").ToString.ToEntero}").ToDouble + 'If (Dr("Cantidad").ToString.ToDouble > CantidadRem, CantidadRem, Dr("Cantidad").ToString.ToDouble) Then + + If Not CveVentaDetalleRem > 0 Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al obtener la relación de la venta con la remisión." + Exit For + End If + + For Each Dr As DataRow In DtMovtosDev.FiltraParametros($"CveVentaDetalle = {DrRem("CveVentaDetalle").ToString.ToEntero}").Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=CveVentaDetalleRem, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar los movimientos de salida de traspaso de devolucion de remisión." + Exit For + End If + Next + + If ErrorCancelar Then + Exit For + End If + Next + + If ErrorCancelar Then + Exit For + End If + + 'ENTRADA POR TRAPASO A ENTREGA POR ADELANTADO + If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaDevRem, UsuarioActual.CveEmpresa) Then + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar los movimientos de entrada de traspaso de devolucion de remisión." + Exit For + End If + Next + + If ErrorCancelar Then + Exit For + End If + + Else + ErrorCancelar = True + MensajeError = "Ocurrió un error al obtener los detalles de la devolución de almacén" + Exit For + End If + + + If Not ObjVentas.UpdateVentasDevolucionAlmacen(0, DrMovtos("CveRem").ToString.ToEntero) Then + MensajeError = "Ocurrió un error al hacer la devolucion hacia la remision. Por favor vuelva a intentar." + ErrorCancelar = True + Exit For + End If + + End If + + Next + End If + Else + MensajeError = "Ocurrió un error al hacer la devolucion a remisión. Por favor vuelva a intentar." + ErrorCancelar = True + End If + + End If + + If Not ErrorCancelar Then + 'QUEMA DEVOLUCION | QUEMA = LA QUITA DE PENDIENTE POR RECIBIR (DEVOLVER) + If Not ErrorCancelar Then + If Not ObjVentas.UpdateVentasDevolucionAlmacen(2, CveVenta) Then + MensajeError = "Ocurrió un error al hacer la devolucion. Por favor vuelva a intentar." + ErrorCancelar = True + End If + End If + + 'AGREGA BITACORA A VENTA + If Not ErrorCancelar Then + Dim MensajeBitacora = "Devuelta" + If Not ObjEventos.AddEventoBitacora(String.Format("Venta {2} en Folio: {1}", CveMovimiento, Folio, MensajeBitacora), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + ErrorCancelar = True + End If + End If + End If + + End If + End If + + 'DESVINCULA REMISIONES PREDECESORAS + If Not EsRefacturacion Then + If Not ErrorCancelar Then + If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then + If Not ChkCanRem.Checked Then + If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular las remisiones." + End If + Else + For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows + If Not Gvr.FCCheckBox("ChkCancelarRemision").Checked Then + If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta, Gvr.DataKey("CveVenta").ToEntero) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular las remisiones." + End If + End If + Next + End If + End If + End If + End If + + + 'ACTUALIZA ESTATUS + If Not ErrorCancelar Then + Select Case DdlTipoComprobante.SelectedValue + Case "Rem" + CveEstatus = 12 + Case "Com" + CveEstatus = 9 + End Select + '0 Sin Refacturacion, 1 Refacturacion en Proceso, 3. Refacturación en proceso sin aceptación + Me.CveEstatusRefacturacion = 0 + If EsRefacturacion Then + If CveEstatus = 5 Then + CveEstatusRefacturacion = 3 ' refacturación en proceso sin autorización de cancelación + Else + CveEstatusRefacturacion = 1 ' refacturación en proceso con autorización de cancelación + End If + End If + + + If Not ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion, CveEstatusRefacturacion:=CveEstatusRefacturacion, + CveUsuarioCambiaEstatus:=UsuarioActual.CveUsuario, FechaCambioEstatus:=Now.ToString("yyyy-MM-dd hh:mm:ss.mmm")) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar el estatus de cancelación." + End If + + If ChkCanRem.Checked Then + For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows + If Gvr.FCCheckBox("ChkCancelarRemision").Checked Then + If Not SeCancelaRemisionProceso Then + If Not ObjVentas.UpdateEstatusFactura(12, "", "", CancelacionFecha, Gvr.DataKey("CveVenta").ToEntero) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar el estatus de cancelación de la remisión." + End If + Else + If Not ObjVentas.AddRemisionesXCancelar(CveVenta, Gvr.DataKey("CveVenta").ToEntero) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar la remisión x cancelar." + End If + End If + End If + Next + End If + If SeCancelaRemisionProceso Then + If Not ObjVentas.UpdateCancelaRemision(CveVenta, SeCancelaRemisionProceso) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al actualizar que la remision sea cancelable." + End If + End If + End If + + If Not ErrorCancelar Then + ObjVentas.Commit() + + If CveEstatus = 5 Then + Dim MensajeAlert As New StringBuilder + MensajeAlert.Append("El Documento se canceló correctamente.") + MensajeAlert.Append($"
    Imprimir Acuse") + MensajeAlert.Append("

    ¿Desea enviar el Acuse de Cancelación al Cliente?") + Alert(MensajeAlert.ToString, TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnEnviarMailCancelacion();", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") + + Else + If Not EsRefacturacion Then + Alert("El documento se canceló exitosamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();") + Else + Response.Redirect($"/Ventas/RepCancelacionesPorRespuesta.aspx?CveVenta={Me.CveVenta}") + End If + End If + + Me.CveEstatus = CveEstatus + If CveEstatus = 5 Then LbCancelarDocumento.Enabled = False + If ObjAC IsNot Nothing Then ObjAC.Commit() + Else + Alert(MensajeError, TipoMensaje.MsgError) + ObjVentas.RollBack() + If ObjAC IsNot Nothing Then ObjAC.RollBack() + End If + + ObjVentas.Dispose() + ObjBancos.Dispose() + ObjInventario.Dispose() + ObjContrato.Dispose() + ObjConta.Dispose() + If ObjAC IsNot Nothing Then ObjAC.Dispose() + + UpEstatus.Update() -#Region " CANCELAR PEDIDO " - Protected Sub LBCancelarPedido_Click(sender As Object, e As EventArgs) - Dim ObjVentas As New ClsVentas - - If ObjVentas.CancelarPedido(CveVenta, UsuarioActual.CveEmpresa) Then - Alert("El pedido se canceló correctamente.", TipoMensaje.MsgInformacion) - - 'DdlEstatus.Items.Clear() - 'DdlEstatus.Items.Insert(0, New ListItem(GlobalDTEstatusFactura.FiltroPrimeroValor("EstatusFactura", "CveEstatusFactura = 14"), "14")) - 'DdlEstatus.SelectedValue = "14" - 'DdlEstatus.DataBind() - 'DdlEstatus.Enabled = False - CveEstatus = 14 - UpEstatus.Update() - - End If - ObjVentas.Dispose() End Sub -#End Region -#Region "D E V O L U C I O N D E P E D I D O " - Private Sub CargaFacturaDevolucionPedido() - Dim CveVenta As Integer = Me.CveVenta - Dim MovInv As Integer = ViewState("MovInv").ToString.ToEntero - - Dim ObjVentas As New ClsVentas() - Dim ObjInventarios As New ClsInventarios - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0) - - 'CargaCliente - Dim CveCliente As Integer = DbRowVenta("CveCliente").ToString.ToEntero - If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then - Exit Sub - ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then - Exit Sub - End If - - HdnCveCliente.Value = CveCliente.ToString - ViewState("CveCliente") = CveCliente - CargaCliente(CveCliente, -1) 'Estatus activo, se requiere para cargar una factura en la que el cliente a sido eliminado - TxtFecha.Text = Now.ToShortDateString - - 'TxtSubTotal.Text = DbRowVenta("SubTotal").ToString.FormatoNumero(2) - 'LblDescuentos.Text = DbRowVenta("Descuento").ToString.FormatoNumero(2) - 'LblAmortizacion.Text = DbRowVenta("Amortizacion").ToString.FormatoNumero(2) - 'TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) - 'TxtIVA.Text = DbRowVenta("IVA").ToString.FormatoNumero(2) - 'TxtRetIVA.Text = DbRowVenta("RetIVA").ToString.FormatoNumero(2) - 'TxtRetISR.Text = DbRowVenta("RetISR").ToString.FormatoNumero(2) - 'TxtIEPS.Text = DbRowVenta("IEPS").ToString.FormatoNumero(2) - CveContrato = DbRowVenta("CveContrato").ToString.ToEntero - TxtMotivoDescuento.Text = DbRowVenta("MotivoDescuento").ToString - TxtObsFact.Text = DbRowVenta("Observaciones").ToString - HdnIVAOriginal.Value = TxtIVA.Text - TxtPedidoContrato.Text = DbRowVenta("PedidoContrato").ToString - TxtPedidoContrato.Enabled = False - TxtOrdenCompra.Text = DbRowVenta("OrdenCompra").ToString - TxtOrdenCompra.Enabled = False - TxtObsAlmacen.Text = DbRowVenta("ObservacionesAlmacen").ToString - TxtFechaEjecucion.Text = DbRowVenta("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy") - 'DdlSucursalEjecucion.SelectedValueExist(DbRowVenta("CveSucursalEjecucion").ToString) - 'DdlSucursalCobranza.SelectedValueExist(DbRowVenta("CveSucursalCobranza").ToString) - DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").ToString) - 'DdlSucursal.SelectedValueExist(DbRowVenta("CveSucursal").ToString) - DdlSubProyectoDatos.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString) - DdlSubProyectoCobranza.SelectedValueExist(DbRowVenta("CveSubProyectoCobranza").ToString) - DdlSubProyectoEjecucion.SelectedValueExist(DbRowVenta("CveSubProyectoEjecucion").ToString) - CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString.ToEntero) - - DdlMetodoPago33.SelectedIndex = 1 - DdlFormaPago33.SelectedIndex = 1 - DdlUsoCFDI.SelectedIndex = 1 - - RequiereAlmacenDestino = True - DdlAlmacenAsignado.Items.Clear() - DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1")) - DdlAlmacenAsignado.SelectedValue = "-1" - DdlAlmacenAsignado.DataBind() - DdlAlmacenAsignado.Items.Insert(0, New ListItem("Almacen", DbRowVenta("CveAlmacenTraspasoOrigen").ToString)) - DdlAlmacenAsignado.SelectedValueExist(DbRowVenta("CveAlmacenTraspasoOrigen").ToString) - - RequiereAlmacenOrigen = True - DdlAlmacenOrigen.Items.Clear() - DdlAlmacenOrigen.Items.Insert(0, New ListItem(" Seleccione ", "-1")) - DdlAlmacenOrigen.SelectedValue = "-1" - DdlAlmacenOrigen.DataBind() - DdlAlmacenOrigen.Items.Insert(0, New ListItem("Almacen", DbRowVenta("CveAlmacenTraspasoDestino").ToString)) - DdlAlmacenOrigen.SelectedValueExist(DbRowVenta("CveAlmacenTraspasoDestino").ToString) - - - If ObjInventarios.GetMovimientosDetalle(MovInv, UsuarioActual.CveEmpresa) AndAlso ObjInventarios.DtResultados.Rows.Count > 0 Then - Dim Cons As Integer = 1 - TmpDT.Clear() - - Dim Cantidad = 0.0D, PU = 0.0D, Descuento = 0.0D - Dim Filtro As String = "" - If ViewState("CveMovimientoDetalle").ToString.ToEntero > 0 Then - Filtro = $"AND CveMovimientoDetalle = {ViewState("CveMovimientoDetalle").ToString.ToEntero}" - End If - For Each dr As DataRow In ObjInventarios.DtResultados.FiltraParametros($"ExistenciaPedido > 0 {Filtro}").Rows - AgregarProductoServicio(dr("Cantidad").ToString.ToDecimal, dr("CveUM").ToString.ToEntero, dr("UnidadMedida").ToString, dr("CveClasificacion").ToString.ToEntero, dr("Clasificacion").ToString, - dr("CvePS").ToString.ToEntero, dr("PS").ToString, dr("SerieLote").ToString, dr("PU").ToString.ToDecimal, 0.0D, - dr("CveProyecto").ToString.ToEntero, dr("Proyecto").ToString, dr("CveSubProyecto").ToString.ToEntero, dr("SubProyecto").ToString, - CveMovimientoDetallePedido:=dr("CveMovimientoDetalle").ToString.ToEntero) - Next - CalculaTotalesVenta() - End If - - - 'Ocultamos los botones Editar, Clonar y Ordenar - GvPS.Columns(17).Visible = False - GvPS.Columns(19).Visible = False - GvPS.Columns(20).Visible = False - - DdlVendedor.SelectedValue = DbRowVenta("CveVendedor").ToString - DdlTipoComprobante.Enabled = False - 'DdlSucursal.Enabled = False - DdlSubProyectoDatos.Enabled = False - BtnBuscarCliente.Enabled = False - 'TxtDocto.Enabled = False - - 'DESACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto disabled") - TxtCodigo.ReadOnly = True - - ChkEnviarFactura.Enabled = False - TxtCantidad.Enabled = False - DdlClasificacion.Enabled = False - DdlPS.Enabled = False - TxtObsPS.Enabled = False - DdlProyecto.Enabled = False - DdlSubProyecto.Enabled = False - TxtPrecio.Enabled = False - ImgDescPU.Attributes.Clear() - ImgDescTotal.Attributes.Clear() - ImgDescConcepto.Attributes.Clear() - LbAgregar.Enabled = False - LnkAgregarPyME.Enabled = False - divcondicionespago.Visible = False - - BtnEmitirImprimir.Text = "Guardar" - BtnEmitirImprimir.Visible = True - UpFacturar.Update() - End If - End If - ObjVentas.Dispose() - ObjInventarios.Dispose() - - UpFacturar.Update() - UpPS.Update() - UpCliente.Update() - UpEstatus.Update() +#End Region + +#Region "CiclosComerciales" + Private Sub CargaCicloComercialURL() + Dim ObjContratos As New ClsContratos + Dim huboerror = False + Dim SubProyecto As String = "" + Dim CveSubProyecto As Integer = -1 + Dim Proyecto As String = "" + If ObjContratos.CicloComercialGet(-1, -1, CveCicloComercial, UsuarioActual.CveEmpresa, MinFecha, MaxFecha, -1) Then + If ObjContratos.DtResultados.Rows.Count > 0 Then + Dim i As Integer = 0 + Dim PU As Decimal = 0 + Dim Descuento As Double = 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 + + 'Cargamos los datos del Cliente + DtContratos = ObjContratos.DtResultados + If ObjContratos.DtResultados(0)("IVA").ToString.ToDecimal > 0 Then + ViewState("IVA") = ObjContratos.DtResultados(0)("IVA").ToString.ToDecimal + End If + ViewState("CveCliente") = ObjContratos.DtResultados(0)("CveCliente").ToString.ToEntero + ViewState("CveContrato") = ObjContratos.DtResultados(0)("CveContrato").ToString.ToEntero + HdnCveCliente.Value = ObjContratos.DtResultados(0)("CveCliente").ToString + CargaCliente(CveCliente) + DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) + DdlTipoComprobante.SelectedValue = "Ing" + DdlTipoComprobante.Enabled = False + DdlAlmacenAsignado.Enabled = False + + 'CARGO DATOS DE PS/CONTRATO + SubProyecto = ObjContratos.DtResultados(0)("SubProyectoContrato").ToString + CveSubProyecto = ObjContratos.DtResultados(0)("CveSubProyecto").ToString.ToEntero + Proyecto = ObjContratos.DtResultados(0)("ProyectoContrato").ToString + DdlSubProyectoDatos.SelectedValueExist(CveSubProyecto) + ContratoDetalles.Visible = True + DivEstimaciones.Visible = False + + DdlContratosModal.DataSource = DtContratos + DdlContratosModal.DataBind() + DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) + UPEstimaciones.Update() + + Tab.ActiveTab = TabE + TabGenerales.Enabled = False + Updatetabs.Update() + + DdlContratosModal.DataSource = ObjContratos.DtResultados + DdlContratosModal.SelectedValue = ObjContratos.DtResultados(0)("CveContrato").ToString + DdlContratosModal_SelectedIndexChanged(Nothing, Nothing) + GvContratoDetalles.HeaderRow.Cells(1).Style.Add("display", "none") + BtnCargarContratoDetalles_Click(Nothing, Nothing) + LbAgregar.Visible = True + UpPS.Update() + 'AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento + Else + Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) + huboerror = True + End If + Else + Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) + huboerror = True + End If + ObjContratos.Dispose() End Sub -#End Region +#End Region -#Region " FLETES " +#Region "DESCARGAR E IMPRIMIR LISTADO" + Public Sub DescargarFormato() + Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & "Empresas\Grales\Formatos\FormatoVentas.xlsx" - Private Sub CargaFletes() - - If UsuarioActual.CveEmpresa <> 125 Or CveVenta > 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() + Dim Archivo As New IO.FileInfo(Directorio) + If Archivo.Exists Then + Response.Clear() + Response.ClearHeaders() + Response.ClearContent() + Response.AddHeader("Content-Disposition", "attachment; filename=" + Archivo.Name) + Response.AddHeader("Content-Length", Archivo.Length.ToString()) + Response.ContentType = "text/plain" + Response.Flush() + Response.TransmitFile(Archivo.FullName) + Response.End() + End If + End Sub + Public Sub LbDescargarExcel_Click(sender As Object, e As EventArgs) Handles LbDescargarExcelVentas.Click + DescargarFormato() + End Sub + Private Sub CargarArchivo(Ruta As String, FileName As String, Tipo As String) + Dim dt As New DataTable + Dim Conexion As Odbc.OdbcConnection = Nothing + Dim ErrorArchivo = False + Dim n As Integer = 0 + Try + Select Case Tipo + Case "EXCEL" + Conexion = New Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + Ruta + FileName + ";") + Conexion.Open() + Dim cmd = Conexion.CreateCommand() + cmd.CommandType = CommandType.Text + cmd.CommandText = "Select * FROM [Hoja1$]" + Dim DataAdapter = New Odbc.OdbcDataAdapter(cmd) + DataAdapter.Fill(dt) + Case Else + Alert("El archivo no tiene el formato correcto", TipoMensaje.MsgError) + Exit Sub + End Select + Catch ex As Exception + ErrorArchivo = True + OnError("Ocurrio un Error al leer el archivo
    " & ex.Message, ex) + End Try + Conexion.Close() + If Not ErrorArchivo Then + If Not dt.Columns(0).ColumnName = "Cantidad" Then + Alert("El nombre de la primera columna debe ser 'Cantidad'.Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(1).ColumnName = "Código" Then + Alert("El nombre de la segunda columna debe ser 'Código'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(2).ColumnName = "Codigo Barras" Then + Alert("El nombre de la tecera columna debe ser 'Codigo Barras'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(3).ColumnName = "Producto/Servicio" Then + Alert("El nombre de la cuarta columna debe ser 'Producto/Servicio'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(4).ColumnName = "UM" Then + Alert("El nombre de la quinta columna debe ser 'U.M'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(5).ColumnName = "Precio Unitario" Then + Alert("El nombre de la sexta columna debe ser 'Precio Unitario'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(6).ColumnName = "Proyecto" Then + Alert("El nombre de la séptima columna debe ser 'Proyecto'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + If Not dt.Columns(7).ColumnName = "Observaciones" Then + Alert("El nombre de la octava columna debe ser 'Observaciones'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + + If Not dt.Columns(8).ColumnName = "Tiempo Entrega" Then + Alert("El nombre de la octava columna debe ser 'Tiempo Entrega'. Favor de corregirlo", TipoMensaje.MsgError) + Exit Sub + End If + + dt.TableName = "Datos" + + If Not ErrorArchivo Then + NumRow = 1 + Dim RowNoEncontrados As String = "" + Dim NumAgregados As Integer = 0 + For Each Row As DataRow In dt.Rows + Dim Cantidad As Decimal = Row("Cantidad").ToString.ToDecimal + Dim UM As String = Row("UM").ToString + Dim Codigo As String = Row("Código").ToString.Trim.ToUpper + Dim CodigoBarras As String = Row("Codigo Barras").ToString.Trim.ToUpper + Dim ProductoServicio As String = Row("Producto/Servicio").ToString.Trim.ToUpper + Dim PrecioUnitario As Decimal = Row("Precio Unitario").ToString.ToDecimal + Dim Proyecto As String = Row("Proyecto").ToString.Trim.ToUpper + Dim Observaciones As String = Row("Observaciones").ToString.Trim.ToUpper + Dim TiempoEntrega As String = Row("Tiempo Entrega").ToString + Dim CvePS As Integer = 0 + Dim CveUM As Integer = 0 + Dim CodigoPS As Integer = 0 + Dim DrProyecto As DataRow + Dim SubProyecto As String = "" + Dim CveProyecto As Integer = 0 + Dim CveSubProyecto As Integer = 0 + NumRow = NumRow + 1 + + If Proyecto <> "" Then + Dim DtSubProyecto As DataTable = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa) + DtSubProyecto.CaseSensitive = False + DrProyecto = DtSubProyecto.FiltroPrimero($"(SubProyecto) = '{Proyecto}'") + If DrProyecto IsNot Nothing Then + CveSubProyecto = DrProyecto("CveSubProyecto").ToString.ToEntero + CveProyecto = DrProyecto("CveProyecto").ToString.ToEntero + SubProyecto = DrProyecto("SubProyecto").ToString + End If + Else + CveProyecto = -1 + CveSubProyecto = -1 + End If + + If Codigo <> "" Then + Dim StrArray() As String = GetPS("Codigo", Codigo).Split("|"c) + If StrArray.Length > 0 Then + If CBool(StrArray(0)) = True Then + CvePS = StrArray(1).ToEntero + Else + RowNoEncontrados &= StrArray(1) & "<\BR>" + End If + End If + ElseIf CodigoBarras <> "" Then + Dim StrArray() As String = GetPS("CodigoBarras", CodigoBarras).Split("|"c) + If StrArray.Length > 0 Then + If CBool(StrArray(0)) = True Then + CvePS = StrArray(1).ToEntero + Else + RowNoEncontrados &= StrArray(1) & "<\BR>" + End If + End If + ElseIf ProductoServicio <> "" Then + Dim StrArray() As String = GetPS("PS", ProductoServicio).Split("|"c) + If StrArray.Length > 0 Then + If CBool(StrArray(0)) = True Then + CvePS = StrArray(1).ToEntero + Else + RowNoEncontrados &= StrArray(1) & "<\BR>" + End If + End If + Else + RowNoEncontrados &= "<\BR>    - En la fila " & NumRow & " no se especificó código, código de barras ó descripción." + End If + + If CvePS > 0 Then + CveUM = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveUnidadMedida", $"CvePS = '{CvePS}'").ToString.ToEntero + + AgregarProductoServicio(Cantidad, CveUM, UM, -1, "", + CvePS, HdnPS.Value, Observaciones, PrecioUnitario, HdnDescuento.Value.ToDecimal, + CveProyecto, Proyecto, CveSubProyecto, SubProyecto, + TiempoEntrega:=TiempoEntrega) + + + 'If TmpDT IsNot Nothing Then + ' Dim dr As DataRow = TmpDT.NewRow + ' TxtCantidad.Text = Cantidad.ToString + ' DdlPS.SelectedValue = CvePS.ToString + ' DdlPS_SelectedIndexChanged(Nothing, Nothing) + ' DdlUnidadMedida.SelectedValueExist(CveUM.ToString) + ' TxtObsPS.Text = Observaciones + ' DdlProyecto.SelectedValue = CveProyecto.ToString + ' DdlProyecto_SelectedIndexChanged(Nothing, Nothing) + ' DdlSubProyecto.SelectedValue = CveSubProyecto.ToString + ' TxtPrecio.Text = PrecioUnitario.ToString + ' TxtTiempoEntrega.Text = TiempoEntrega.ToString + ' RegistraScript("Recalcula();") + ' LbAgregar_Click(Nothing, Nothing) + ' NumAgregados = NumAgregados + 1 + 'End If + End If + + + Next + + + + CalculaTotalesVenta() + + If RowNoEncontrados.Length > 0 Then + Alert("Los siguientes productos o servicios no se encontraron en la Base de Datos.<\BR>" & RowNoEncontrados, TipoMensaje.MsgAdvertencia) + Else + Alert("Se cargaron " & NumAgregados & " productos o servicios correctamente.") + End If + End If + End If + dt.Dispose() + End Sub + Private Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcel.Click + If TxtExcel.getfiles().Archivos.Count > 0 Then + Dim file As Archivo = TxtExcel.getfiles().Archivos(0) + Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & file.patch + Dim Tipo As String = If(file.Extencion.Contiene("xlsx", "xlsx", "xlsm", "xlsb"), "EXCEL", "CSV") + CargarArchivo(Directorio, file.filename, Tipo) + Else + Alert("No existe el archivo. Favor de subir un archivo excel a la plataforma.", TipoMensaje.MsgError) + End If + End Sub + Private Function GetPS(Opt As String, Valor As String) As String + Dim StrReturn As String = String.Empty + Dim CvePS As Integer = 0 + CvePS = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePS", Opt & " = '" & Valor & "'").ToString.ToEntero + If CvePS > 0 Then + StrReturn = "True|" & CvePS.ToString + Else + StrReturn = "False|    - No se encontró " & Valor & " en la fila " & NumRow & ", columna " & Opt + End If + Return StrReturn + End Function +#End Region + +#Region "P E D I D O S" + Private Sub CargaNotificacionContrato() + Dim ObjContratos As New ClsContratos + If ObjContratos.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then + If ObjContratos.DtResultados IsNot Nothing AndAlso ObjContratos.DtResultados.Rows.Count > 0 Then + CorreoNotificacionPedDev = ObjContratos.DtResultados(0)("CorreoNotificacionPedDev").ToString + End If + End If + ObjContratos.Dispose() + End Sub + Private Sub EnviarCorreoDevPed() + Try + Dim Body As String = GeneraCorreoDevPed() + Dim Asunto As String = $"SIG - Favor de surtir el siguiente {DdlTipoComprobante.SelectedItem.Text}" + Dim Hilo As New System.Threading.Thread(Sub() MandaCorreoDevPed(CorreoNotificacionPedDev, Asunto, Body)) + Hilo.Start() + Catch ex As Exception + OnError($"Ocurrió error al mandar el correo de solicitud de {DdlTipoComprobante.SelectedItem.Text}", ex) + End Try + End Sub + Private Sub MandaCorreoDevPed(Para As String, Asunto As String, Body As String) + Dim Mail As New ClsSisMail() + Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body) + End Sub + Private Function GeneraCorreoDevPed() As String + Dim strBody As New StringBuilder + + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.Append(" ") + strBody.AppendFormat("
    Favor de surtir el siguiente {0}

    ", DdlTipoComprobante.SelectedItem.Text) + strBody.AppendFormat("
    Datos de {0} ", DdlTipoComprobante.SelectedItem.Text) + strBody.Append(" ") + strBody.Append(" ") + strBody.AppendFormat(" ", LblSerie.Text, TxtFolio.Text) + strBody.Append(" ") + strBody.Append(" ") + strBody.AppendFormat(" ", UsuarioActual.Empresa.Empresa) + strBody.Append(" ") + strBody.Append(" ") + strBody.AppendFormat(" ", LblCliente.Text) + strBody.Append(" ") + strBody.Append(" ") + strBody.AppendFormat(" ", DdlSubProyectoDatos.SelectedItem.Text) + strBody.Append(" ") + strBody.Append(" ") + strBody.AppendFormat(" ", TxtFecha.Text) + strBody.Append(" ") + strBody.Append("
    Serie-Folio:{0}-{1}
    Empresa:{0}
    Cliente:{0}
    Sucursal:{0}
    Fecha:{0}
    ") + strBody.Append("
    ") + strBody.Append("
    ") + 'Cargo el detalle + + strBody.Append("
    ") + strBody.Append("
    ") + strBody.Append(" Productos/Servicios ") + strBody.Append(" ") + strBody.Append(" ") + + For Each dr As DataRow In TmpDT.Rows + strBody.AppendFormat("", + dr("Cantidad").ToString().FormatoNumero(), dr("UM").ToString(), dr("PS").ToString(), dr("Obs").ToString(), dr("SubProyecto").ToString(), dr("PU").ToString().FormatoNumero()) + + Next + + strBody.Append("
    CantidadUnidadProducto/ServicioNo. SerieProyectoPrecio
    {0}{1}{2}{3}{4}{5}
    ") + strBody.Append("
    ") + strBody.Append("
    ") + strBody.Append("") + + + Return strBody.ToString + End Function +#End Region + +#Region " CANCELAR PEDIDO " + Protected Sub LBCancelarPedido_Click(sender As Object, e As EventArgs) + Dim ObjVentas As New ClsVentas + + If ObjVentas.CancelarPedido(CveVenta, UsuarioActual.CveEmpresa) Then + Alert("El pedido se canceló correctamente.", TipoMensaje.MsgInformacion) + + 'DdlEstatus.Items.Clear() + 'DdlEstatus.Items.Insert(0, New ListItem(GlobalDTEstatusFactura.FiltroPrimeroValor("EstatusFactura", "CveEstatusFactura = 14"), "14")) + 'DdlEstatus.SelectedValue = "14" + 'DdlEstatus.DataBind() + 'DdlEstatus.Enabled = False + CveEstatus = 14 + UpEstatus.Update() + + End If + ObjVentas.Dispose() + End Sub + +#End Region + +#Region "D E V O L U C I O N D E P E D I D O " + Private Sub CargaFacturaDevolucionPedido() + Dim CveVenta As Integer = Me.CveVenta + Dim MovInv As Integer = ViewState("MovInv").ToString.ToEntero + + Dim ObjVentas As New ClsVentas() + Dim ObjInventarios As New ClsInventarios + + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then + Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0) + + 'CargaCliente + Dim CveCliente As Integer = DbRowVenta("CveCliente").ToString.ToEntero + If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then + Exit Sub + ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then + Exit Sub + End If + + HdnCveCliente.Value = CveCliente.ToString + ViewState("CveCliente") = CveCliente + CargaCliente(CveCliente, -1) 'Estatus activo, se requiere para cargar una factura en la que el cliente a sido eliminado + TxtFecha.Text = Now.ToShortDateString + + 'TxtSubTotal.Text = DbRowVenta("SubTotal").ToString.FormatoNumero(2) + 'LblDescuentos.Text = DbRowVenta("Descuento").ToString.FormatoNumero(2) + 'LblAmortizacion.Text = DbRowVenta("Amortizacion").ToString.FormatoNumero(2) + 'TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) + 'TxtIVA.Text = DbRowVenta("IVA").ToString.FormatoNumero(2) + 'TxtRetIVA.Text = DbRowVenta("RetIVA").ToString.FormatoNumero(2) + 'TxtRetISR.Text = DbRowVenta("RetISR").ToString.FormatoNumero(2) + 'TxtIEPS.Text = DbRowVenta("IEPS").ToString.FormatoNumero(2) + CveContrato = DbRowVenta("CveContrato").ToString.ToEntero + TxtMotivoDescuento.Text = DbRowVenta("MotivoDescuento").ToString + TxtObsFact.Text = DbRowVenta("Observaciones").ToString + HdnIVAOriginal.Value = TxtIVA.Text + TxtPedidoContrato.Text = DbRowVenta("PedidoContrato").ToString + TxtPedidoContrato.Enabled = False + TxtOrdenCompra.Text = DbRowVenta("OrdenCompra").ToString + TxtOrdenCompra.Enabled = False + TxtObsAlmacen.Text = DbRowVenta("ObservacionesAlmacen").ToString + TxtFechaEjecucion.Text = DbRowVenta("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy") + 'DdlSucursalEjecucion.SelectedValueExist(DbRowVenta("CveSucursalEjecucion").ToString) + 'DdlSucursalCobranza.SelectedValueExist(DbRowVenta("CveSucursalCobranza").ToString) + DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").ToString) + 'DdlSucursal.SelectedValueExist(DbRowVenta("CveSucursal").ToString) + DdlSubProyectoDatos.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString) + DdlSubProyectoCobranza.SelectedValueExist(DbRowVenta("CveSubProyectoCobranza").ToString) + DdlSubProyectoEjecucion.SelectedValueExist(DbRowVenta("CveSubProyectoEjecucion").ToString) + CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString.ToEntero) + + DdlMetodoPago33.SelectedIndex = 1 + DdlFormaPago33.SelectedIndex = 1 + DdlUsoCFDI.SelectedIndex = 1 + + RequiereAlmacenDestino = True + DdlAlmacenAsignado.Items.Clear() + DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1")) + DdlAlmacenAsignado.SelectedValue = "-1" + DdlAlmacenAsignado.DataBind() + DdlAlmacenAsignado.Items.Insert(0, New ListItem("Almacen", DbRowVenta("CveAlmacenTraspasoOrigen").ToString)) + DdlAlmacenAsignado.SelectedValueExist(DbRowVenta("CveAlmacenTraspasoOrigen").ToString) + + RequiereAlmacenOrigen = True + DdlAlmacenOrigen.Items.Clear() + DdlAlmacenOrigen.Items.Insert(0, New ListItem(" Seleccione ", "-1")) + DdlAlmacenOrigen.SelectedValue = "-1" + DdlAlmacenOrigen.DataBind() + DdlAlmacenOrigen.Items.Insert(0, New ListItem("Almacen", DbRowVenta("CveAlmacenTraspasoDestino").ToString)) + DdlAlmacenOrigen.SelectedValueExist(DbRowVenta("CveAlmacenTraspasoDestino").ToString) + + + If ObjInventarios.GetMovimientosDetalle(MovInv, UsuarioActual.CveEmpresa) AndAlso ObjInventarios.DtResultados.Rows.Count > 0 Then + Dim Cons As Integer = 1 + TmpDT.Clear() + + Dim Cantidad = 0.0D, PU = 0.0D, Descuento = 0.0D + Dim Filtro As String = "" + If ViewState("CveMovimientoDetalle").ToString.ToEntero > 0 Then + Filtro = $"AND CveMovimientoDetalle = {ViewState("CveMovimientoDetalle").ToString.ToEntero}" + End If + For Each dr As DataRow In ObjInventarios.DtResultados.FiltraParametros($"ExistenciaPedido > 0 {Filtro}").Rows + AgregarProductoServicio(dr("Cantidad").ToString.ToDecimal, dr("CveUM").ToString.ToEntero, dr("UnidadMedida").ToString, dr("CveClasificacion").ToString.ToEntero, dr("Clasificacion").ToString, + dr("CvePS").ToString.ToEntero, dr("PS").ToString, dr("SerieLote").ToString, dr("PU").ToString.ToDecimal, 0.0D, + dr("CveProyecto").ToString.ToEntero, dr("Proyecto").ToString, dr("CveSubProyecto").ToString.ToEntero, dr("SubProyecto").ToString, + CveMovimientoDetallePedido:=dr("CveMovimientoDetalle").ToString.ToEntero) + Next + CalculaTotalesVenta() + End If + + + 'Ocultamos los botones Editar, Clonar y Ordenar + GvPS.Columns(17).Visible = False + GvPS.Columns(19).Visible = False + GvPS.Columns(20).Visible = False + + DdlVendedor.SelectedValue = DbRowVenta("CveVendedor").ToString + DdlTipoComprobante.Enabled = False + 'DdlSucursal.Enabled = False + DdlSubProyectoDatos.Enabled = False + BtnBuscarCliente.Enabled = False + 'TxtDocto.Enabled = False + + 'DESACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto disabled") + TxtCodigo.ReadOnly = True + + ChkEnviarFactura.Enabled = False + TxtCantidad.Enabled = False + DdlClasificacion.Enabled = False + DdlPS.Enabled = False + TxtObsPS.Enabled = False + DdlProyecto.Enabled = False + DdlSubProyecto.Enabled = False + TxtPrecio.Enabled = False + ImgDescPU.Attributes.Clear() + ImgDescTotal.Attributes.Clear() + ImgDescConcepto.Attributes.Clear() + LbAgregar.Enabled = False + LnkAgregarPyME.Enabled = False + divcondicionespago.Visible = False + + BtnEmitirImprimir.Text = "Guardar" + BtnEmitirImprimir.Visible = True + UpFacturar.Update() + End If + End If + ObjVentas.Dispose() + ObjInventarios.Dispose() + + UpFacturar.Update() + UpPS.Update() + UpCliente.Update() + UpEstatus.Update() + End Sub +#End Region + +#Region " FLETES " + + Private Sub CargaFletes() + + If UsuarioActual.CveEmpresa <> 125 Or CveVenta > 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 +#End Region -#Region "A G R E G A R P S M O D A L" - Private Sub CargaMetodosPSModal() - CargaTipoProductos() - CargaClasificacionesPS() - 'CargarMetodosInv() - CargaUnidadesMedida() - CargarMarcas() - End Sub - 'Private Sub CargarMetodosInv() - ' DdlMetodoInv.Items.Clear() - ' DdlMetodoInv.DataSource = GlobalDTInvMetodosInventario - ' DdlMetodoInv.DataBind() - ' DdlMetodoInv.Items.Insert(0, New ListItem("Seleccione", "-1")) - 'End Sub - - Private Sub CargaClasificacionesDetalles() - DdlTipo.Items.Clear() - DdlTipo.DataSource = GlobalDTClasificacionesDetalle(UsuarioActual.CveEmpresa) - - DdlTipo.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlTipo.DataBind() - End Sub - Private Sub CargaClasificacionesPS() - If UsuarioActual.Empresa.UsaAC Then - DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") - 'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") - Else - DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion") - 'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion") - End If - - - 'BLOQUEA DDL CLASIFICACION - If UsuarioActual.Empresa.Funcionalidad(121) = "1" Then - If Not UsuarioActual.TienePermisoProceso(147) Then - DdlClasificacionPS.Enabled = False - 'DdlTipo.Enabled = False - End If - End If - DdlClasificacionPS.DataBind() - 'DdlTipo.DataBind() - End Sub - Private Sub CargaTipoProductos() - 'BLOQUEA DDL TIPO PRODUCTO - If UsuarioActual.Empresa.Funcionalidad(122) = "1" Then - If Not UsuarioActual.TienePermisoProceso(149) Then - DdlTipoPS.Enabled = False - DdlTipoPS.SelectedValueExist("2") - End If - End If - End Sub - Private Sub CargaUnidadesMedida() - DdlUnidadMedidaPS.Items.Clear() - DdlUnidadMedidaPS.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) - DdlUnidadMedidaPS.DataBind() - DdlUnidadMedidaPS.Items.Insert(0, New ListItem("Seleccione", "-1")) - End Sub - Protected Sub CargarMarcas() - If UsuarioActual.Empresa.Funcionalidad(130) = "1" Then - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then - DivMarcaPSDes.Visible = True - Else - DivMarca.Visible = True - End If - DdlMarca.Items.Clear() - DdlMarcaPSDes.Items.Clear() - Dim ObjMarcas As New ClsProductosServicios - ObjMarcas.GetMarcas(UsuarioActual.CveEmpresa) - DdlMarca.DataSource = ObjMarcas.DtResultados - DdlMarcaPSDes.DataSource = ObjMarcas.DtResultados - ObjMarcas.Dispose() - DdlMarca.DataBind() - DdlMarcaPSDes.DataBind() - End If - DdlMarca.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlMarcaPSDes.Items.Insert(0, New ListItem("Seleccione", "-1")) - End Sub - Private Sub BtnModalAddPS_Click(sender As Object, e As EventArgs) Handles BtnModalAddPS.Click - TxtCodigoPS.Text = "" - TxtCodigoBarrasPS.Text = "" - TxtPS.Text = "" - TxtModelo.Text = "" - TxtAdicional.Text = "" - - DdlTipoPS.SelectedIndex = 0 - DdlUnidadMedidaPS.SelectedIndex = 0 - DdlClasificacionPS.SelectedIndex = 0 - 'DdlMetodoInv.SelectedIndex = 0 - ChkRequiereSerie.Checked = False - DdlMarca.SelectedIndex = 0 - DdlMarcaPSDes.SelectedIndex = 0 - CargaClasificacionesDetalles() - - UpAddPS.Update() - RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddPS")) - End Sub - Private Sub LbAddPS_Click(sender As Object, e As EventArgs) Handles LbAddPS.Click - If (TxtCodigoPS.Text = TxtCodigoBarrasPS.Text AndAlso TxtCodigoPS.Text <> "") Then - Alert("Los codigos no pueden ser iguales. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Return - End If - - If UsuarioActual.Empresa.Funcionalidad(265) = "1" And TxtCodigoPS.Text = "" Then - Alert("El código es requerido.", TipoMensaje.MsgAdvertencia) - Return - End If - - If TxtCodigoPS.Text <> "" AndAlso Not TxtCodigoPS.Text.Length >= 3 Then - Alert("El código tiene que que tener una longitud de al menos 3 digitos.", TipoMensaje.MsgAdvertencia) - Return - End If - - Dim CveMetodoInventario As Integer = 0 - If ChkRequiereSerie.Checked Then CveMetodoInventario = 5 Else CveMetodoInventario = 1 - - Dim CveMarca As Integer = 0 - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then CveMarca = DdlMarcaPSDes.SelectedValue.ToEntero Else CveMarca = DdlMarca.SelectedValue.ToEntero - - Dim ObjProductosServicios As New ClsProductosServicios() - If ObjProductosServicios.AddPS(DdlClasificacionPS.SelectedValue.ToEntero, -1, DdlUnidadMedidaPS.SelectedValue.ToEntero, TxtCodigoPS.Text.Trim, "", TxtCodigoBarrasPS.Text.Trim, TxtPS.Text.Trim, 0, -1, 0, False, 0, False, True, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveMetodoInventario, 0, CveTipoPS:=DdlTipoPS.SelectedValue.ToEntero, CveMarca:=CveMarca, CveSATPS:=DdlSATPS.SelectedValue.ToEntero, CveClasificacionDetalle:=DdlTipo.SelectedValue.ToEntero) > 0 Then - DdlClasificacion.SelectedValueExist(DdlClasificacionPS.SelectedValue.ToEntero) - DdlClasificacion_SelectedIndexChanged(DdlClasificacionPS, e) - - 'SI ES DDLOST - If UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then - DdlPS.SelectedValue = ObjProductosServicios.CvePS.ToString - DdlPS.SelectedText = TxtPS.Text.Trim - Else - DdlPS.ddl.Items.Insert(2, New ListItem(TxtPS.Text.Trim, ObjProductosServicios.CvePS.ToString)) - DdlPS.ddl.SelectedValueExist(ObjProductosServicios.CvePS) - End If - - DdlUnidadMedida.Items.Clear() - DdlUnidadMedida.Items.Insert(0, New ListItem(DdlUnidadMedidaPS.SelectedItem.Text, DdlUnidadMedidaPS.SelectedValue)) - DdlUnidadMedida.SelectedValueExist(DdlUnidadMedidaPS.SelectedValue) - - HdnPS.Value = TxtPS.Text.Trim - HdnCodigoPS.Value = $"{TxtCodigoPS.Text.Trim}-{TxtPS.Text.Trim}" - HdnTipoPS.Value = DdlTipoPS.SelectedValue - HdnTipoInv.Value = CveMetodoInventario.ToString - HdnAplicaIEPS.Value = "False" - HdnPorcentajeIEPS.Value = "-1" - HdnIVAPS.Value = "0.16" - HdnIVARetAPS.Value = "0" - HdnAsientoContable.Value = "1" - HdnCtaContable.Value = "0" - HdnAplicaParaConcepto.Value = "False" - HdnCodigo.Value = TxtCodigoPS.Text.Trim - End If - - - ObjProductosServicios.Dispose() - UpPS.Update() - RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddPS")) - RecargaGlobal() - End Sub - Private Sub RecargaGlobal() - Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDT) - Hilo.Start() - End Sub - Private Sub GeneraGlobalDT() - Dim ObjPS As New ClsProductosServicios - - If (ObjPS.GetPSSimplificado(-1)) Then - Application("GlobalDTPSSimplificado") = ObjPS.DtResultados.AsEnumerable 'Cargamos el GlobalDTPSSimplificado - End If - - If ObjPS.GetPSEquivalencias(-1, -1) Then - GlobalDTProductosServiciosEquivalencias(-1, -1) = ObjPS.DtResultados - End If - - ObjPS.Dispose() +#Region "A G R E G A R P S M O D A L" + Private Sub CargaMetodosPSModal() + CargaTipoProductos() + CargaClasificacionesPS() + 'CargarMetodosInv() + CargaUnidadesMedida() + CargarMarcas() End Sub -#End Region + 'Private Sub CargarMetodosInv() + ' DdlMetodoInv.Items.Clear() + ' DdlMetodoInv.DataSource = GlobalDTInvMetodosInventario + ' DdlMetodoInv.DataBind() + ' DdlMetodoInv.Items.Insert(0, New ListItem("Seleccione", "-1")) + 'End Sub -#Region "P Y M E" - Private Sub LnkAddVenta_Click(sender As Object, e As EventArgs) Handles LnkAddVenta.Click - Modalidad = "A" - LnkAgregarPyME.Text = "Agregar" - TxtCantidadPyME.Text = "" - TxtObsPyME.Text = "" - TxtPrecioPyME.Text = "0.00" - LblTotalPyME.Text = "0.00" - If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then - DdlPSPyME.SelectedValue = "-1" - Else - DdlPSPyME.SelectedValue = "" - DdlPSPyME.SelectedText = "" - End If - DdlClasificacionPyME.SelectedIndex = -1 - DdlProyectoPyME.SelectedIndex = -1 - DdlSubProyectoPyME.SelectedIndex = -1 - DdlUMPyME.Items.Clear() - ChkAgregar.Checked = True - divagregrarotrops.Visible = True - UpVenta.Update() - RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta")) - - End Sub - - Public Sub Edit_Click(sender As Object, e As EventArgs) - Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - Modalidad = "U" - Index = GvRow.DataKey("Consec").ToEntero - LnkAgregarPyME.Text = "Actualizar" - DdlClasificacionPyME.SelectedValueExist(GvRow.DataKey("CveClasificacion")) - CargaPSPyME(DdlClasificacionPyME.SelectedValue.ToEntero, DdlPSPyME) - UpClasificacionPyME.Update() - If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then - DdlPSPyME.SelectedValue = GvRow.DataKey("CvePS") - Else - DdlPSPyME.SelectedValue = GvRow.DataKey("CvePS") - DdlPSPyME.SelectedText = GvRow.DataKey("PS") - End If - DdlPSPyMEIndexChange() - DdlProyectoPyME.SelectedValueExist(GvRow.DataKey("CveProyecto")) - CargaSubProyecto() - DdlSubProyectoPyME.SelectedValueExist(GvRow.DataKey("CveSubProyecto")) - DdlUMPyME.SelectedValueExist(GvRow.DataKey("CveUM")) - TxtCantidadPyME.Text = GvRow.DataKey("Cantidad") - TxtObsPyME.Text = GvRow.DataKey("Obs") - TxtPrecioPyME.Text = GvRow.DataKey("PU") - TotAnt = GvRow.DataKey("Total").ToDecimal - LblTotalPyME.Text = GvRow.DataKey("Total") - ChkAgregar.Checked = False - divagregrarotrops.Visible = False - UpVenta.Update() - RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta"), "EdicionVenta") - End Sub - - Private Sub LnkAgregarPyME_Click(sender As Object, e As EventArgs) Handles LnkAgregarPyME.Click - AgregarPSPYME() - - If ChkAgregar.Checked = True And Modalidad = "A" Then - LnkAgregarPyME.Text = "Agregar" - TxtCantidadPyME.Text = "" - TxtObsPyME.Text = "" - TxtPrecioPyME.Text = "0.00" - LblTotalPyME.Text = "0.00" - If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then - DdlPSPyME.SelectedValue = "-1" - Else - DdlPSPyME.SelectedValue = "" - DdlPSPyME.SelectedText = "" - End If - DdlClasificacionPyME.SelectedIndex = -1 - DdlProyectoPyME.SelectedIndex = -1 - DdlSubProyectoPyME.SelectedIndex = -1 - DdlUMPyME.Items.Clear() - UpVenta.Update() - RegistraScript("displayToastr(1);", "display") - Else - If Modalidad = "A" Then RegistraScript("displayToastr(1);", "display1") - If Modalidad = "U" Then RegistraScript("displayToastr(2);", "display2") - RegistraScript("ClosePopup();", "AddUpdatePS") - End If - - End Sub - - Private Sub DdlPSPyME_selectedindexchange(sender As Object, e As EventArgs) Handles DdlPSPyME.selectedindexchange - DdlPSPyMEIndexChange() - End Sub - - Private Sub CargaPSPyME(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost) - - DdlPSPyME.setEsWebService(If(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1", True, False)) - - If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then - Objeto.ddl.Items.Clear() - 'Objeto.ddl.DataSource = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) - Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) - Objeto.ddl.DataBind() - Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2")) - Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1")) - Else - DdlPSPyME.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) - End If - - End Sub - - Private Sub DdlPSPyMEIndexChange() - If CveCliente > 0 OrElse DdlPSPyME.SelectedValue = "-2" Then - If DdlPSPyME.SelectedValue IsNot Nothing AndAlso DdlPSPyME.SelectedValue.ToEntero > 0 Then - Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPSPyME.SelectedValue.ToEntero).FiltroPrimero("") - - If drPS IsNot Nothing Then - 'HdnUnidadMedida.Value = PS.Rows(0)("CveUnidadMedida").ToString - HdnPS.Value = drPS("PS").ToString - HdnCodigoPS.Value = drPS("PSCodigo").ToString - HdnTipoPS.Value = drPS("CveTipoPS").ToString - HdnTipoInv.Value = drPS("Inv_CveMetodoInventario").ToString - HdnAplicaIEPS.Value = drPS("AplicaIEPS").ToString - HdnPorcentajeIEPS.Value = drPS("IEPSPorcentaje").ToString - DdlUMPyME.Items.Clear() - If UsuarioActual.Empresa.UsaInventarios Then - DdlUMPyME.DataSource = GlobalDTProductosServiciosEquivalencias(DdlPSPyME.SelectedValue.ToEntero, -1) - Else - DdlUMPyME.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) - End If - DdlUMPyME.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlUMPyME.SelectedValue = "-1" - DdlUMPyME.DataBind() - DdlUMPyME.SelectedValueExist(drPS("CveUnidadMedida").ToString) - - 'LblUnidadMedida.Text = PS.Rows(0)("UnidadMedida").ToString - TxtPrecioPyME.Text = drPS("Precio").ToString.FormatoNumero(2).Replace(","c, "") - - If UsuarioActual.CveEmpresa = 80 Then - 'busca el precio de la sucursal - Dim ObjPS As New ClsProductosServicios - If ObjPS.GetPSSucursales(DdlPSPyME.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero) Then - Dim dtt As DataTable = ObjPS.DtResultados - Dim drPrecio As DataRow = dtt.FiltroPrimero("") - - If drPrecio IsNot Nothing Then - TxtPrecioPyME.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4") - End If - dtt.Dispose() - End If - - ObjPS.Dispose() - End If - - 'If IsNumeric(TxtCantidad.Text.Trim) Then - ' LblTotalPyME.Text = (TxtCantidad.Text.Trim.ToDouble * TxtPrecio.Text.ToDouble).ToString.FormatoNumero(2) - 'End If - HdnIVAPS.Value = If(drPS("IVA").ToString = "-1", ViewState("IVA"), drPS("IVA").ToString).ToString - HdnIVARetAPS.Value = drPS("RetIVA").ToString - HdnAsientoContable.Value = drPS("AsientoContableVentas").ToString - HdnCtaContable.Value = drPS("IdCtaContVentas").ToString - HdnAplicaParaConcepto.Value = drPS("AplicaParaConcepto").ToString - HdnCodigo.Value = drPS("Codigo").ToString - If DdlClasificacionPyME.SelectedIndex = 0 Then - If drPS("CveClasificacion").ToString IsNot Nothing Then - DdlClasificacionPyME.SelectedValueExist(drPS("CveClasificacion").ToString) - Else - Alert("El Productos/Servicio no tiene asignada una Clasificación.") - End If - - End If - - End If - 'RegistraScript("Recalcula();") - 'PS.Dispose() - ElseIf DdlPSPyME.SelectedValue = "-2" Then - CargaPSPyME(-1, DdlPSPyME) - End If - Else - Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") - End If - - UpVenta.Update() - - End Sub - - Private Sub DdlClasificacionPyME_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlClasificacionPyME.SelectedIndexChanged - CargaPSPyME(DdlClasificacionPyME.SelectedValue.ToEntero, DdlPSPyME) - UpClasificacionPyME.Update() + Private Sub CargaClasificacionesDetalles() + DdlTipo.Items.Clear() + DdlTipo.DataSource = GlobalDTClasificacionesDetalle(UsuarioActual.CveEmpresa) + + DdlTipo.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlTipo.DataBind() + End Sub + Private Sub CargaClasificacionesPS() + If UsuarioActual.Empresa.UsaAC Then + DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") + 'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") + Else + DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion") + 'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion") + End If + + + 'BLOQUEA DDL CLASIFICACION + If UsuarioActual.Empresa.Funcionalidad(121) = "1" Then + If Not UsuarioActual.TienePermisoProceso(147) Then + DdlClasificacionPS.Enabled = False + 'DdlTipo.Enabled = False + End If + End If + DdlClasificacionPS.DataBind() + 'DdlTipo.DataBind() + End Sub + Private Sub CargaTipoProductos() + 'BLOQUEA DDL TIPO PRODUCTO + If UsuarioActual.Empresa.Funcionalidad(122) = "1" Then + If Not UsuarioActual.TienePermisoProceso(149) Then + DdlTipoPS.Enabled = False + DdlTipoPS.SelectedValueExist("2") + End If + End If + End Sub + Private Sub CargaUnidadesMedida() + DdlUnidadMedidaPS.Items.Clear() + DdlUnidadMedidaPS.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) + DdlUnidadMedidaPS.DataBind() + DdlUnidadMedidaPS.Items.Insert(0, New ListItem("Seleccione", "-1")) + End Sub + Protected Sub CargarMarcas() + If UsuarioActual.Empresa.Funcionalidad(130) = "1" Then + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then + DivMarcaPSDes.Visible = True + Else + DivMarca.Visible = True + End If + DdlMarca.Items.Clear() + DdlMarcaPSDes.Items.Clear() + Dim ObjMarcas As New ClsProductosServicios + ObjMarcas.GetMarcas(UsuarioActual.CveEmpresa) + DdlMarca.DataSource = ObjMarcas.DtResultados + DdlMarcaPSDes.DataSource = ObjMarcas.DtResultados + ObjMarcas.Dispose() + DdlMarca.DataBind() + DdlMarcaPSDes.DataBind() + End If + DdlMarca.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlMarcaPSDes.Items.Insert(0, New ListItem("Seleccione", "-1")) + End Sub + Private Sub BtnModalAddPS_Click(sender As Object, e As EventArgs) Handles BtnModalAddPS.Click + TxtCodigoPS.Text = "" + TxtCodigoBarrasPS.Text = "" + TxtPS.Text = "" + TxtModelo.Text = "" + TxtAdicional.Text = "" + + DdlTipoPS.SelectedIndex = 0 + DdlUnidadMedidaPS.SelectedIndex = 0 + DdlClasificacionPS.SelectedIndex = 0 + 'DdlMetodoInv.SelectedIndex = 0 + ChkRequiereSerie.Checked = False + DdlMarca.SelectedIndex = 0 + DdlMarcaPSDes.SelectedIndex = 0 + CargaClasificacionesDetalles() + + UpAddPS.Update() + RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddPS")) + End Sub + Private Sub LbAddPS_Click(sender As Object, e As EventArgs) Handles LbAddPS.Click + If (TxtCodigoPS.Text = TxtCodigoBarrasPS.Text AndAlso TxtCodigoPS.Text <> "") Then + Alert("Los codigos no pueden ser iguales. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Return + End If + + If UsuarioActual.Empresa.Funcionalidad(265) = "1" And TxtCodigoPS.Text = "" Then + Alert("El código es requerido.", TipoMensaje.MsgAdvertencia) + Return + End If + + If TxtCodigoPS.Text <> "" AndAlso Not TxtCodigoPS.Text.Length >= 3 Then + Alert("El código tiene que que tener una longitud de al menos 3 digitos.", TipoMensaje.MsgAdvertencia) + Return + End If + + Dim CveMetodoInventario As Integer = 0 + If ChkRequiereSerie.Checked Then CveMetodoInventario = 5 Else CveMetodoInventario = 1 + + Dim CveMarca As Integer = 0 + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then CveMarca = DdlMarcaPSDes.SelectedValue.ToEntero Else CveMarca = DdlMarca.SelectedValue.ToEntero + + Dim ObjProductosServicios As New ClsProductosServicios() + If ObjProductosServicios.AddPS(DdlClasificacionPS.SelectedValue.ToEntero, -1, DdlUnidadMedidaPS.SelectedValue.ToEntero, TxtCodigoPS.Text.Trim, "", TxtCodigoBarrasPS.Text.Trim, TxtPS.Text.Trim, 0, -1, 0, False, 0, False, True, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveMetodoInventario, 0, CveTipoPS:=DdlTipoPS.SelectedValue.ToEntero, CveMarca:=CveMarca, CveSATPS:=DdlSATPS.SelectedValue.ToEntero, CveClasificacionDetalle:=DdlTipo.SelectedValue.ToEntero) > 0 Then + DdlClasificacion.SelectedValueExist(DdlClasificacionPS.SelectedValue.ToEntero) + DdlClasificacion_SelectedIndexChanged(DdlClasificacionPS, e) + + 'SI ES DDLOST + If UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then + DdlPS.SelectedValue = ObjProductosServicios.CvePS.ToString + DdlPS.SelectedText = TxtPS.Text.Trim + Else + DdlPS.ddl.Items.Insert(2, New ListItem(TxtPS.Text.Trim, ObjProductosServicios.CvePS.ToString)) + DdlPS.ddl.SelectedValueExist(ObjProductosServicios.CvePS) + End If + + DdlUnidadMedida.Items.Clear() + DdlUnidadMedida.Items.Insert(0, New ListItem(DdlUnidadMedidaPS.SelectedItem.Text, DdlUnidadMedidaPS.SelectedValue)) + DdlUnidadMedida.SelectedValueExist(DdlUnidadMedidaPS.SelectedValue) + + HdnPS.Value = TxtPS.Text.Trim + HdnCodigoPS.Value = $"{TxtCodigoPS.Text.Trim}-{TxtPS.Text.Trim}" + HdnTipoPS.Value = DdlTipoPS.SelectedValue + HdnTipoInv.Value = CveMetodoInventario.ToString + HdnAplicaIEPS.Value = "False" + HdnPorcentajeIEPS.Value = "-1" + HdnIVAPS.Value = "0.16" + HdnIVARetAPS.Value = "0" + HdnAsientoContable.Value = "1" + HdnCtaContable.Value = "0" + HdnAplicaParaConcepto.Value = "False" + HdnCodigo.Value = TxtCodigoPS.Text.Trim + End If + + + ObjProductosServicios.Dispose() + UpPS.Update() + RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddPS")) + RecargaGlobal() + End Sub + Private Sub RecargaGlobal() + Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDT) + Hilo.Start() + End Sub + Private Sub GeneraGlobalDT() + Dim ObjPS As New ClsProductosServicios + + If (ObjPS.GetPSSimplificado(-1)) Then + Application("GlobalDTPSSimplificado") = ObjPS.DtResultados.AsEnumerable 'Cargamos el GlobalDTPSSimplificado + End If + + If ObjPS.GetPSEquivalencias(-1, -1) Then + GlobalDTProductosServiciosEquivalencias(-1, -1) = ObjPS.DtResultados + End If + + ObjPS.Dispose() + End Sub +#End Region + +#Region "P Y M E" + Private Sub LnkAddVenta_Click(sender As Object, e As EventArgs) Handles LnkAddVenta.Click + Modalidad = "A" + LnkAgregarPyME.Text = "Agregar" + TxtCantidadPyME.Text = "" + TxtObsPyME.Text = "" + TxtPrecioPyME.Text = "0.00" + LblTotalPyME.Text = "0.00" + If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then + DdlPSPyME.SelectedValue = "-1" + Else + DdlPSPyME.SelectedValue = "" + DdlPSPyME.SelectedText = "" + End If + DdlClasificacionPyME.SelectedIndex = -1 + DdlProyectoPyME.SelectedIndex = -1 + DdlSubProyectoPyME.SelectedIndex = -1 + DdlUMPyME.Items.Clear() + ChkAgregar.Checked = True + divagregrarotrops.Visible = True + UpVenta.Update() + RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta")) + + End Sub + + Public Sub Edit_Click(sender As Object, e As EventArgs) + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + Modalidad = "U" + Index = GvRow.DataKey("Consec").ToEntero + LnkAgregarPyME.Text = "Actualizar" + DdlClasificacionPyME.SelectedValueExist(GvRow.DataKey("CveClasificacion")) + CargaPSPyME(DdlClasificacionPyME.SelectedValue.ToEntero, DdlPSPyME) + UpClasificacionPyME.Update() + If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then + DdlPSPyME.SelectedValue = GvRow.DataKey("CvePS") + Else + DdlPSPyME.SelectedValue = GvRow.DataKey("CvePS") + DdlPSPyME.SelectedText = GvRow.DataKey("PS") + End If + DdlPSPyMEIndexChange() + DdlProyectoPyME.SelectedValueExist(GvRow.DataKey("CveProyecto")) + CargaSubProyecto() + DdlSubProyectoPyME.SelectedValueExist(GvRow.DataKey("CveSubProyecto")) + DdlUMPyME.SelectedValueExist(GvRow.DataKey("CveUM")) + TxtCantidadPyME.Text = GvRow.DataKey("Cantidad") + TxtObsPyME.Text = GvRow.DataKey("Obs") + TxtPrecioPyME.Text = GvRow.DataKey("PU") + TotAnt = GvRow.DataKey("Total").ToDecimal + LblTotalPyME.Text = GvRow.DataKey("Total") + ChkAgregar.Checked = False + divagregrarotrops.Visible = False + UpVenta.Update() + RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta"), "EdicionVenta") + End Sub + + Private Sub LnkAgregarPyME_Click(sender As Object, e As EventArgs) Handles LnkAgregarPyME.Click + AgregarPSPYME() + + If ChkAgregar.Checked = True And Modalidad = "A" Then + LnkAgregarPyME.Text = "Agregar" + TxtCantidadPyME.Text = "" + TxtObsPyME.Text = "" + TxtPrecioPyME.Text = "0.00" + LblTotalPyME.Text = "0.00" + If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then + DdlPSPyME.SelectedValue = "-1" + Else + DdlPSPyME.SelectedValue = "" + DdlPSPyME.SelectedText = "" + End If + DdlClasificacionPyME.SelectedIndex = -1 + DdlProyectoPyME.SelectedIndex = -1 + DdlSubProyectoPyME.SelectedIndex = -1 + DdlUMPyME.Items.Clear() + UpVenta.Update() + RegistraScript("displayToastr(1);", "display") + Else + If Modalidad = "A" Then RegistraScript("displayToastr(1);", "display1") + If Modalidad = "U" Then RegistraScript("displayToastr(2);", "display2") + RegistraScript("ClosePopup();", "AddUpdatePS") + End If + + End Sub + + Private Sub DdlPSPyME_selectedindexchange(sender As Object, e As EventArgs) Handles DdlPSPyME.selectedindexchange + DdlPSPyMEIndexChange() + End Sub + + Private Sub CargaPSPyME(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost) + + DdlPSPyME.setEsWebService(If(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1", True, False)) + + If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then + Objeto.ddl.Items.Clear() + 'Objeto.ddl.DataSource = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) + Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) + Objeto.ddl.DataBind() + Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2")) + Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1")) + Else + DdlPSPyME.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) + End If + + End Sub + + Private Sub DdlPSPyMEIndexChange() + If CveCliente > 0 OrElse DdlPSPyME.SelectedValue = "-2" Then + If DdlPSPyME.SelectedValue IsNot Nothing AndAlso DdlPSPyME.SelectedValue.ToEntero > 0 Then + Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPSPyME.SelectedValue.ToEntero).FiltroPrimero("") + + If drPS IsNot Nothing Then + 'HdnUnidadMedida.Value = PS.Rows(0)("CveUnidadMedida").ToString + HdnPS.Value = drPS("PS").ToString + HdnCodigoPS.Value = drPS("PSCodigo").ToString + HdnTipoPS.Value = drPS("CveTipoPS").ToString + HdnTipoInv.Value = drPS("Inv_CveMetodoInventario").ToString + HdnAplicaIEPS.Value = drPS("AplicaIEPS").ToString + HdnPorcentajeIEPS.Value = drPS("IEPSPorcentaje").ToString + DdlUMPyME.Items.Clear() + If UsuarioActual.Empresa.UsaInventarios Then + DdlUMPyME.DataSource = GlobalDTProductosServiciosEquivalencias(DdlPSPyME.SelectedValue.ToEntero, -1) + Else + DdlUMPyME.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) + End If + DdlUMPyME.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlUMPyME.SelectedValue = "-1" + DdlUMPyME.DataBind() + DdlUMPyME.SelectedValueExist(drPS("CveUnidadMedida").ToString) + + 'LblUnidadMedida.Text = PS.Rows(0)("UnidadMedida").ToString + TxtPrecioPyME.Text = drPS("Precio").ToString.FormatoNumero(2).Replace(","c, "") + + If UsuarioActual.CveEmpresa = 80 Then + 'busca el precio de la sucursal + Dim ObjPS As New ClsProductosServicios + If ObjPS.GetPSSucursales(DdlPSPyME.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero) Then + Dim dtt As DataTable = ObjPS.DtResultados + Dim drPrecio As DataRow = dtt.FiltroPrimero("") + + If drPrecio IsNot Nothing Then + TxtPrecioPyME.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4") + End If + dtt.Dispose() + End If + + ObjPS.Dispose() + End If + + 'If IsNumeric(TxtCantidad.Text.Trim) Then + ' LblTotalPyME.Text = (TxtCantidad.Text.Trim.ToDouble * TxtPrecio.Text.ToDouble).ToString.FormatoNumero(2) + 'End If + HdnIVAPS.Value = If(drPS("IVA").ToString = "-1", ViewState("IVA"), drPS("IVA").ToString).ToString + HdnIVARetAPS.Value = drPS("RetIVA").ToString + HdnAsientoContable.Value = drPS("AsientoContableVentas").ToString + HdnCtaContable.Value = drPS("IdCtaContVentas").ToString + HdnAplicaParaConcepto.Value = drPS("AplicaParaConcepto").ToString + HdnCodigo.Value = drPS("Codigo").ToString + If DdlClasificacionPyME.SelectedIndex = 0 Then + If drPS("CveClasificacion").ToString IsNot Nothing Then + DdlClasificacionPyME.SelectedValueExist(drPS("CveClasificacion").ToString) + Else + Alert("El Productos/Servicio no tiene asignada una Clasificación.") + End If + + End If + + End If + 'RegistraScript("Recalcula();") + 'PS.Dispose() + ElseIf DdlPSPyME.SelectedValue = "-2" Then + CargaPSPyME(-1, DdlPSPyME) + End If + Else + Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") + End If + + UpVenta.Update() + + End Sub + + Private Sub DdlClasificacionPyME_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlClasificacionPyME.SelectedIndexChanged + CargaPSPyME(DdlClasificacionPyME.SelectedValue.ToEntero, DdlPSPyME) + UpClasificacionPyME.Update() End Sub -#End Region +#End Region -#Region "REORDENAR" - Protected Sub BtnReordenar_Click(sender As Object, e As EventArgs) Handles BtnReordenar.Click - Dim sArray As String() - sArray = HdnIndices.Value.Split(";"c) - Dim DTClon As DataTable = TmpDT.Clone - Dim Consec As Integer = 1 - For Each indice As String In sArray - If IsNumeric(indice) Then - Dim dr As DataRow = TmpDT.Rows(indice.ToEntero) - dr("Consec") = Consec - dr.AcceptChanges() - DTClon.ImportRow(dr) - Consec += 1 - End If - Next - TmpDT = DTClon - Dim view As DataView = New DataView(TmpDT) - view.Sort = "Consec" - GvPS.DataSource = view - GvPS.DataBind() - CalculaTotalesVenta() - DTClon.Dispose() +#Region "REORDENAR" + Protected Sub BtnReordenar_Click(sender As Object, e As EventArgs) Handles BtnReordenar.Click + Dim sArray As String() + sArray = HdnIndices.Value.Split(";"c) + Dim DTClon As DataTable = TmpDT.Clone + Dim Consec As Integer = 1 + For Each indice As String In sArray + If IsNumeric(indice) Then + Dim dr As DataRow = TmpDT.Rows(indice.ToEntero) + dr("Consec") = Consec + dr.AcceptChanges() + DTClon.ImportRow(dr) + Consec += 1 + End If + Next + TmpDT = DTClon + Dim view As DataView = New DataView(TmpDT) + view.Sort = "Consec" + GvPS.DataSource = view + GvPS.DataBind() + CalculaTotalesVenta() + DTClon.Dispose() End Sub -#End Region +#End Region -#Region " CONTRATO DE CONSIGNACION DE VENTA - SURTIDO DE ALMACÉN " - Function RegistraAlmacenConsignacionVenta(ByRef ObjInventario As ClsInventarios, factura As Modelos.Factura) As Boolean - If Not (UsuarioActual.Empresa.UsaInventarios AndAlso CveAlmacenExistenciasContrato > 0) Then - Return True - End If - - Dim CveMovimientoSalidaConsignacion = -1 - Dim CveMovimientoEntradaGeneral = -1 - Dim CveMovimientoSalidaGeneral = -1 - - - 'MOVIMIENTO DE SALIDA POR TRASPASO DEL ALMACEN DE CONSIGNACION - CveMovimientoSalidaConsignacion = ObjInventario.AddMovimiento(CveAlmacenExistenciasContrato, 8, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1) - If CveMovimientoSalidaConsignacion > 0 Then - Dim CveProducto As Integer - Dim CveUnidad As Integer - Dim Cantidad As Double - Dim Existencia As Double - For Each Dr As DataRow In TmpDT.Rows - CveProducto = Dr("CvePS").ToString.ToEntero - CveUnidad = Dr("CveUM").ToString.ToEntero - Cantidad = Dr("Cantidad").ToString.ToDouble - - If Not CveProducto > 0 Then - Return False - End If - - If Dr("CveTipoInvPS").ToString.ToEntero = 5 Then - For Each Dr2 As DataRow In DtContratosSerieDetalle.FiltraParametros($"ConsecId = {Dr("CveContratoDetalle")}").Rows - Existencia = ObjInventario.GetExistenciasPS(CveProducto, CveUnidad, factura.CveEmpresa, CveAlmacenExistenciasContrato, SerieLote:=Dr2("Serie").ToString, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ExcluyeAdelantado:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) - If Existencia < 1 Then - Return False - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaConsignacion, 1, CveUnidad, CveProducto, 0, -1, SerieLote:=Dr2("Serie").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - Return False - End If - Next - Else - Existencia = ObjInventario.GetExistenciasPS(CveProducto, CveUnidad, factura.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ExcluyeAdelantado:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) - If Existencia < Cantidad Then - Return False - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaConsignacion, Cantidad, CveUnidad, CveProducto, 0, -1, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - Return False - End If - End If - Next - Else - Return False - End If - - - 'ENTRADA POR TRASPASO A GENERAL - CveMovimientoEntradaGeneral = ObjInventario.AddMovimiento(CveAlmacenOrigenContrato, 9, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1, CveMovimientoRelacionado:=CveMovimientoSalidaConsignacion) - If CveMovimientoEntradaGeneral > 0 Then - If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaConsignacion, UsuarioActual.CveEmpresa) Then - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaGeneral, Dr("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, Dr("CveSeccionAlmacen").ToString.ToEntero, Dr("SerieLote").ToString, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - Return False - End If - Next - End If - Else - Return False - End If - - 'SALIDA GENERAL - CveMovimientoEntradaGeneral = ObjInventario.AddMovimiento(CveAlmacenOrigenContrato, 3, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1) - If CveMovimientoEntradaGeneral > 0 Then - If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaConsignacion, UsuarioActual.CveEmpresa) Then - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaGeneral, Dr("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, Dr("CveSeccionAlmacen").ToString.ToEntero, Dr("SerieLote").ToString, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - Return False - End If - Next - End If - Else - Return False - End If - - - Return True +#Region " CONTRATO DE CONSIGNACION DE VENTA - SURTIDO DE ALMACÉN " + Function RegistraAlmacenConsignacionVenta(ByRef ObjInventario As ClsInventarios, factura As Modelos.Factura) As Boolean + If Not (UsuarioActual.Empresa.UsaInventarios AndAlso CveAlmacenExistenciasContrato > 0) Then + Return True + End If + + Dim CveMovimientoSalidaConsignacion = -1 + Dim CveMovimientoEntradaGeneral = -1 + Dim CveMovimientoSalidaGeneral = -1 + + + 'MOVIMIENTO DE SALIDA POR TRASPASO DEL ALMACEN DE CONSIGNACION + CveMovimientoSalidaConsignacion = ObjInventario.AddMovimiento(CveAlmacenExistenciasContrato, 8, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1) + If CveMovimientoSalidaConsignacion > 0 Then + Dim CveProducto As Integer + Dim CveUnidad As Integer + Dim Cantidad As Double + Dim Existencia As Double + For Each Dr As DataRow In TmpDT.Rows + CveProducto = Dr("CvePS").ToString.ToEntero + CveUnidad = Dr("CveUM").ToString.ToEntero + Cantidad = Dr("Cantidad").ToString.ToDouble + + If Not CveProducto > 0 Then + Return False + End If + + If Dr("CveTipoInvPS").ToString.ToEntero = 5 Then + For Each Dr2 As DataRow In DtContratosSerieDetalle.FiltraParametros($"ConsecId = {Dr("CveContratoDetalle")}").Rows + Existencia = ObjInventario.GetExistenciasPS(CveProducto, CveUnidad, factura.CveEmpresa, CveAlmacenExistenciasContrato, SerieLote:=Dr2("Serie").ToString, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ExcluyeAdelantado:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) + If Existencia < 1 Then + Return False + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaConsignacion, 1, CveUnidad, CveProducto, 0, -1, SerieLote:=Dr2("Serie").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + Return False + End If + Next + Else + Existencia = ObjInventario.GetExistenciasPS(CveProducto, CveUnidad, factura.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ExcluyeAdelantado:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) + If Existencia < Cantidad Then + Return False + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaConsignacion, Cantidad, CveUnidad, CveProducto, 0, -1, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + Return False + End If + End If + Next + Else + Return False + End If + + + 'ENTRADA POR TRASPASO A GENERAL + CveMovimientoEntradaGeneral = ObjInventario.AddMovimiento(CveAlmacenOrigenContrato, 9, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1, CveMovimientoRelacionado:=CveMovimientoSalidaConsignacion) + If CveMovimientoEntradaGeneral > 0 Then + If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaConsignacion, UsuarioActual.CveEmpresa) Then + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaGeneral, Dr("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, Dr("CveSeccionAlmacen").ToString.ToEntero, Dr("SerieLote").ToString, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + Return False + End If + Next + End If + Else + Return False + End If + + 'SALIDA GENERAL + CveMovimientoEntradaGeneral = ObjInventario.AddMovimiento(CveAlmacenOrigenContrato, 3, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1) + If CveMovimientoEntradaGeneral > 0 Then + If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaConsignacion, UsuarioActual.CveEmpresa) Then + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaGeneral, Dr("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, Dr("CveSeccionAlmacen").ToString.ToEntero, Dr("SerieLote").ToString, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + Return False + End If + Next + End If + Else + Return False + End If + + + Return True End Function -#Region " AGREGA POR SERIE/LOTE " - Private Sub CreaConsignacionSerieDetalle() - If DtContratosSerieDetalle Is Nothing Then - DtContratosSerieDetalle = New DataTable - DtContratosSerieDetalle.Columns.Add("Consec", GetType(Integer)) - DtContratosSerieDetalle.Columns.Add("ConsecId", GetType(Integer)) - DtContratosSerieDetalle.Columns.Add("CvePS", GetType(Integer)) - DtContratosSerieDetalle.Columns.Add("CveUM", GetType(Integer)) - DtContratosSerieDetalle.Columns.Add("Serie", GetType(String)) - Else - DtContratosSerieDetalle.Clear() - End If - End Sub - Protected Sub BtnSerieConsignacion_Click(sender As Object, e As EventArgs) - Dim Argumentos = CType(sender, Button).CommandArgument.Split("°"c) - - CveConsecSerieLote = Argumentos(0).ToEntero - CvePSSerieLote = Argumentos(1).ToEntero - CveUMSerieLote = Argumentos(2).ToEntero - LbProducto.Text = Argumentos(3) - LbCantidad.Text = If(Argumentos(4).ToDecimal < 0.0D, 0, Argumentos(4).ToDecimal).FormatoNumero - LimitaCantidadSerieLote = Argumentos(5).ToEntero - - CargaSerie() - End Sub - - - Private Sub CargaSerie(Optional CerrarCompletado As Boolean = False) - RegistraScript("$('#DivSerieConsignacion').modal();", "ModalLote") - - GvSerie.DataSource = DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", CveConsecSerieLote), "Consec DESC") - GvSerie.DataBind() - - 'VALIDA QUE SIGA AGREGANDO - If DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", CveConsecSerieLote)).Rows.Count = LbCantidad.Text.ToEntero And LimitaCantidadSerieLote = 1 Then - BtnAgregarPS.Enabled = False - If CerrarCompletado Then - RegistraScript("$('#DivSerieConsignacion').modal('hide');") - End If - Else - BtnAgregarPS.Enabled = True - End If - - - - UpSerieConsignacion.Update() - TxtSerieLote.Text = "" - TxtSerieLote.Focus() - - End Sub - Protected Sub BtnAgregarPS_Click(sender As Object, e As EventArgs) - AgregaSerieLote(TxtSerieLote.Text.Replace(" ", String.Empty)) - End Sub - Private Sub AgregaSerieLote(SerieLote As String) - 'SerieLote = SerieLote.Trim.Replace(" ", " ") - - If SerieLote.Trim = "" Then - Alert("El campo Serie es obligatorio. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - Dim SeriesArreglo = SerieLote.Trim.Split(";"c) - - 'VALIDACION DE SERIES DUPLICADAS - Dim MensajeAlert As New StringBuilder - Dim DtDuplicado As New DataTable - Dim DtSeriesNuevas As New DataTable - DtSeriesNuevas.Columns.Add("Serie", GetType(String)) - - 'PARA VALIDAR SI LA SERIE ES IGUAL AL CODIGO O CODIGOBARRAS - ' Dim dr As DataRow = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CvePS = {0}", CvePSSerieLote), "PS") - Dim dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSSerieLote).FiltroPrimero("", "PS") - - For Each SerieRow In SeriesArreglo - SerieRow = SerieRow.ToUpper - - DtDuplicado = DtContratosSerieDetalle.FiltraParametros($"ConsecId = {CveConsecSerieLote} AND Serie = '{SerieRow}'") - If DtDuplicado IsNot Nothing AndAlso DtDuplicado.Rows.Count > 0 Then - MensajeAlert.Append($"
    El numero de Serie ""{SerieRow}"" proporcionado ya se encuentra ingresado.") - Continue For - End If - - DtDuplicado = DtSeriesNuevas.FiltraParametros($"Serie = '{SerieRow}'") - If DtDuplicado IsNot Nothing AndAlso DtDuplicado.Rows.Count > 0 Then - MensajeAlert.Append($"
    El numero de Serie ""{SerieRow}"" proporcionado se encuentra duplicado.") - Continue For - End If - - 'PARA VALIDAR SI LA SERIE ES IGUAL AL CODIGO O CODIGOBARRAS - If SerieRow = dr("Codigo").ToString.ToUpper Or SerieRow = dr("CodigoBarras").ToString.ToUpper Then - MensajeAlert.Append($"
    El numero de Serie {SerieRow} coincide con el codigo o codigo de barras del producto. Por favor rectifique y vuelva a intentar.") - Continue For - End If - - Dim Row = DtSeriesNuevas.NewRow - Row("Serie") = SerieRow - DtSeriesNuevas.Rows.Add(Row) - Next - - If MensajeAlert.ToString <> "" Then - Alert(MensajeAlert.ToString, TipoMensaje.MsgAdvertencia) - RegistraScript("playsonidito('142608__autistic-lucario__error.wav')", "Error") - Exit Sub - End If - - - Dim MensajeSinExistencias As New StringBuilder - Dim ObjInventarios As New ClsInventarios - Dim Index = 0 - - For Each SerieRow In SeriesArreglo - Dim Row = DtContratosSerieDetalle.NewRow - - Index = Index + 1 - If Index > LbCantidad.Text.ToEntero And LimitaCantidadSerieLote = 1 Then - MensajeSinExistencias.Append($"Serie: {SerieRow} - En esta serie ocurrió un error por favor de comunicarse con soporte tecnico..
    ") - Continue For - End If - - 'VERIFICA EXISTENCIAS - Dim Existencia = ObjInventarios.GetExistenciasPS(CvePSSerieLote, CveUMSerieLote, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=TxtFecha.Text.ToDateTime.ToString("yyyy/MM/dd HH:mm"), SerieLote:=SerieRow) - If Existencia < 1 Then - MensajeSinExistencias.Append($"Serie: {SerieRow}.
    ") - Continue For - End If - - Row("ConsecId") = CveConsecSerieLote - Row("Consec") = DtContratosSerieDetalle.Rows.Count + 1 - Row("CvePS") = CvePSSerieLote - Row("CveUM") = CveUMSerieLote - Row("Serie") = SerieRow - - DtContratosSerieDetalle.Rows.Add(Row) - Next - ObjInventarios.Dispose() - - TxtSerieLote.Text = "" - - CargaCantidadSerieGV() - - CargaSerie(True) - - If MensajeSinExistencias.ToString <> "" Then - Alert($"Las siguientes Series no cuentan con la existencia suficiente por lo cual se omitieron.
    {MensajeSinExistencias.ToString}", TipoMensaje.MsgAdvertencia) - RegistraScript("playsonidito('142608__autistic-lucario__error.wav')", "Error") - Else - RegistraScript("playsonidito('beep-07.wav')", "Existo") - End If - - End Sub - - Protected Sub GvSerie_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvSerie.RowDeleting - Try - Dim keySerieLote As String = e.Keys("Serie").ToString - For Each dr As DataRow In DtContratosSerieDetalle.Rows - If dr("Serie").ToString = keySerieLote Then - dr.Delete() - End If - Next - Catch ex As Exception - - Finally - DtContratosSerieDetalle.AcceptChanges() - CargaCantidadSerieGV() - CargaSerie() - End Try - End Sub - Private Sub CargaCantidadSerieGV() - 'MODIFICA CANTIDAD DEL GV CONTRATOS - For Each Gvr As GridViewRow In GvContratoDetalles.Rows - If Gvr.DataKey("CvePS").ToEntero = CvePSSerieLote Then - Dim Contador = DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", Gvr.DataKey("CveContratoDetalle"))).Rows.Count - Gvr.FCTextBox("TxtCant").Text = Contador.ToString - UPEstimaciones.Update() - Exit For - End If - Next +#Region " AGREGA POR SERIE/LOTE " + Private Sub CreaConsignacionSerieDetalle() + If DtContratosSerieDetalle Is Nothing Then + DtContratosSerieDetalle = New DataTable + DtContratosSerieDetalle.Columns.Add("Consec", GetType(Integer)) + DtContratosSerieDetalle.Columns.Add("ConsecId", GetType(Integer)) + DtContratosSerieDetalle.Columns.Add("CvePS", GetType(Integer)) + DtContratosSerieDetalle.Columns.Add("CveUM", GetType(Integer)) + DtContratosSerieDetalle.Columns.Add("Serie", GetType(String)) + Else + DtContratosSerieDetalle.Clear() + End If + End Sub + Protected Sub BtnSerieConsignacion_Click(sender As Object, e As EventArgs) + Dim Argumentos = CType(sender, Button).CommandArgument.Split("°"c) + + CveConsecSerieLote = Argumentos(0).ToEntero + CvePSSerieLote = Argumentos(1).ToEntero + CveUMSerieLote = Argumentos(2).ToEntero + LbProducto.Text = Argumentos(3) + LbCantidad.Text = If(Argumentos(4).ToDecimal < 0.0D, 0, Argumentos(4).ToDecimal).FormatoNumero + LimitaCantidadSerieLote = Argumentos(5).ToEntero + + CargaSerie() End Sub -#End Region -#End Region + Private Sub CargaSerie(Optional CerrarCompletado As Boolean = False) + RegistraScript("$('#DivSerieConsignacion').modal();", "ModalLote") -#Region " ENVIAR SMS - CONFIRMACION DE TIMBRADO " - Private Function EnviarSMSTimbrado(ByRef ObjEventos As ClsOIEventos) As Integer - 'NOTA: - '0 = NO APLICA - '1 = TODO FINO - '2 = ERROR - '3 = SIN CELULAR - PROBLEMA CON EL CELULAR - - Dim Mensaje = UsuarioActual.Empresa.Funcionalidad(152) - If Mensaje = "" Then Return 0 - - Dim Celular = ObjFactura.Cliente.CobranzaTelefono - If Celular.Length <> 10 Then Return 3 - - 'ARMA MENSAJE - '4: VSH Monitoreo aviso de: Factura pendiente {SerieFolio} del {Fecha} por ${Importe} fecha limite de pago {FechaPago} Bancomer 0171426931-{ClienteNombreCorto} - Mensaje = Mensaje.Replace("{SerieFolio}", ObjFactura.SerieFolio) - Mensaje = Mensaje.Replace("{Fecha}", ObjFactura.Fecha.ToString("dd-MMM-yyyy").Replace(".", "")) - Mensaje = Mensaje.Replace("{Importe}", ObjFactura.Total.FormatoNumero) - Mensaje = Mensaje.Replace("{FechaPago}", ObjFactura.FechaPago.ToString("dd-MMM-yyyy").Replace(".", "")) - Mensaje = Mensaje.Replace("{ClienteNombreCorto}", ObjFactura.Cliente.NombreCorto) - If Mensaje = "" Then Return 2 - - Dim ObjMensaje As New ClsTecnoMovil - If ObjMensaje.EnviarMensajeWS(Celular, Mensaje) Then - If ObjEventos.AddEventoBitacora($"Notificación al cliente via SMS. Mensaje: {Mensaje}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCliente:=ObjFactura.CveCliente, CveVenta:=ObjFactura.CveVenta) Then - End If - Return 1 - Else - Return 2 - End If + GvSerie.DataSource = DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", CveConsecSerieLote), "Consec DESC") + GvSerie.DataBind() + + 'VALIDA QUE SIGA AGREGANDO + If DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", CveConsecSerieLote)).Rows.Count = LbCantidad.Text.ToEntero And LimitaCantidadSerieLote = 1 Then + BtnAgregarPS.Enabled = False + If CerrarCompletado Then + RegistraScript("$('#DivSerieConsignacion').modal('hide');") + End If + Else + BtnAgregarPS.Enabled = True + End If + + + + UpSerieConsignacion.Update() + TxtSerieLote.Text = "" + TxtSerieLote.Focus() + + End Sub + Protected Sub BtnAgregarPS_Click(sender As Object, e As EventArgs) + AgregaSerieLote(TxtSerieLote.Text.Replace(" ", String.Empty)) + End Sub + Private Sub AgregaSerieLote(SerieLote As String) + 'SerieLote = SerieLote.Trim.Replace(" ", " ") + + If SerieLote.Trim = "" Then + Alert("El campo Serie es obligatorio. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + Dim SeriesArreglo = SerieLote.Trim.Split(";"c) + + 'VALIDACION DE SERIES DUPLICADAS + Dim MensajeAlert As New StringBuilder + Dim DtDuplicado As New DataTable + Dim DtSeriesNuevas As New DataTable + DtSeriesNuevas.Columns.Add("Serie", GetType(String)) + + 'PARA VALIDAR SI LA SERIE ES IGUAL AL CODIGO O CODIGOBARRAS + ' Dim dr As DataRow = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CvePS = {0}", CvePSSerieLote), "PS") + Dim dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSSerieLote).FiltroPrimero("", "PS") + + For Each SerieRow In SeriesArreglo + SerieRow = SerieRow.ToUpper + + DtDuplicado = DtContratosSerieDetalle.FiltraParametros($"ConsecId = {CveConsecSerieLote} AND Serie = '{SerieRow}'") + If DtDuplicado IsNot Nothing AndAlso DtDuplicado.Rows.Count > 0 Then + MensajeAlert.Append($"
    El numero de Serie ""{SerieRow}"" proporcionado ya se encuentra ingresado.") + Continue For + End If + + DtDuplicado = DtSeriesNuevas.FiltraParametros($"Serie = '{SerieRow}'") + If DtDuplicado IsNot Nothing AndAlso DtDuplicado.Rows.Count > 0 Then + MensajeAlert.Append($"
    El numero de Serie ""{SerieRow}"" proporcionado se encuentra duplicado.") + Continue For + End If + + 'PARA VALIDAR SI LA SERIE ES IGUAL AL CODIGO O CODIGOBARRAS + If SerieRow = dr("Codigo").ToString.ToUpper Or SerieRow = dr("CodigoBarras").ToString.ToUpper Then + MensajeAlert.Append($"
    El numero de Serie {SerieRow} coincide con el codigo o codigo de barras del producto. Por favor rectifique y vuelva a intentar.") + Continue For + End If + + Dim Row = DtSeriesNuevas.NewRow + Row("Serie") = SerieRow + DtSeriesNuevas.Rows.Add(Row) + Next + + If MensajeAlert.ToString <> "" Then + Alert(MensajeAlert.ToString, TipoMensaje.MsgAdvertencia) + RegistraScript("playsonidito('142608__autistic-lucario__error.wav')", "Error") + Exit Sub + End If + + + Dim MensajeSinExistencias As New StringBuilder + Dim ObjInventarios As New ClsInventarios + Dim Index = 0 + + For Each SerieRow In SeriesArreglo + Dim Row = DtContratosSerieDetalle.NewRow + + Index = Index + 1 + If Index > LbCantidad.Text.ToEntero And LimitaCantidadSerieLote = 1 Then + MensajeSinExistencias.Append($"Serie: {SerieRow} - En esta serie ocurrió un error por favor de comunicarse con soporte tecnico..
    ") + Continue For + End If + + 'VERIFICA EXISTENCIAS + Dim Existencia = ObjInventarios.GetExistenciasPS(CvePSSerieLote, CveUMSerieLote, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=TxtFecha.Text.ToDateTime.ToString("yyyy/MM/dd HH:mm"), SerieLote:=SerieRow) + If Existencia < 1 Then + MensajeSinExistencias.Append($"Serie: {SerieRow}.
    ") + Continue For + End If + + Row("ConsecId") = CveConsecSerieLote + Row("Consec") = DtContratosSerieDetalle.Rows.Count + 1 + Row("CvePS") = CvePSSerieLote + Row("CveUM") = CveUMSerieLote + Row("Serie") = SerieRow + + DtContratosSerieDetalle.Rows.Add(Row) + Next + ObjInventarios.Dispose() + + TxtSerieLote.Text = "" + + CargaCantidadSerieGV() + + CargaSerie(True) + + If MensajeSinExistencias.ToString <> "" Then + Alert($"Las siguientes Series no cuentan con la existencia suficiente por lo cual se omitieron.
    {MensajeSinExistencias.ToString}", TipoMensaje.MsgAdvertencia) + RegistraScript("playsonidito('142608__autistic-lucario__error.wav')", "Error") + Else + RegistraScript("playsonidito('beep-07.wav')", "Existo") + End If + + End Sub + + Protected Sub GvSerie_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvSerie.RowDeleting + Try + Dim keySerieLote As String = e.Keys("Serie").ToString + For Each dr As DataRow In DtContratosSerieDetalle.Rows + If dr("Serie").ToString = keySerieLote Then + dr.Delete() + End If + Next + Catch ex As Exception + + Finally + DtContratosSerieDetalle.AcceptChanges() + CargaCantidadSerieGV() + CargaSerie() + End Try + End Sub + Private Sub CargaCantidadSerieGV() + 'MODIFICA CANTIDAD DEL GV CONTRATOS + For Each Gvr As GridViewRow In GvContratoDetalles.Rows + If Gvr.DataKey("CvePS").ToEntero = CvePSSerieLote Then + Dim Contador = DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", Gvr.DataKey("CveContratoDetalle"))).Rows.Count + Gvr.FCTextBox("TxtCant").Text = Contador.ToString + UPEstimaciones.Update() + Exit For + End If + Next + End Sub + +#End Region + +#End Region + +#Region " ENVIAR SMS - CONFIRMACION DE TIMBRADO " + Private Function EnviarSMSTimbrado(ByRef ObjEventos As ClsOIEventos) As Integer + 'NOTA: + '0 = NO APLICA + '1 = TODO FINO + '2 = ERROR + '3 = SIN CELULAR - PROBLEMA CON EL CELULAR + + Dim Mensaje = UsuarioActual.Empresa.Funcionalidad(152) + If Mensaje = "" Then Return 0 + + Dim Celular = ObjFactura.Cliente.CobranzaTelefono + If Celular.Length <> 10 Then Return 3 + + 'ARMA MENSAJE + '4: VSH Monitoreo aviso de: Factura pendiente {SerieFolio} del {Fecha} por ${Importe} fecha limite de pago {FechaPago} Bancomer 0171426931-{ClienteNombreCorto} + Mensaje = Mensaje.Replace("{SerieFolio}", ObjFactura.SerieFolio) + Mensaje = Mensaje.Replace("{Fecha}", ObjFactura.Fecha.ToString("dd-MMM-yyyy").Replace(".", "")) + Mensaje = Mensaje.Replace("{Importe}", ObjFactura.Total.FormatoNumero) + Mensaje = Mensaje.Replace("{FechaPago}", ObjFactura.FechaPago.ToString("dd-MMM-yyyy").Replace(".", "")) + Mensaje = Mensaje.Replace("{ClienteNombreCorto}", ObjFactura.Cliente.NombreCorto) + If Mensaje = "" Then Return 2 + + Dim ObjMensaje As New ClsTecnoMovil + If ObjMensaje.EnviarMensajeWS(Celular, Mensaje) Then + If ObjEventos.AddEventoBitacora($"Notificación al cliente via SMS. Mensaje: {Mensaje}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCliente:=ObjFactura.CveCliente, CveVenta:=ObjFactura.CveVenta) Then + End If + Return 1 + Else + Return 2 + End If End Function -#End Region +#End Region -#Region " COMPLEMENTOS PAGO " - Private Sub CargaComplementosPago() - - Dim ObjBancos As New ClsBancos - - If UsuarioActual.CveRol = 1 Then - GvComplementoPagos.Columns(8).Visible = True - - End If - - - If ObjBancos.GetComplementoPagos(-1, -1, CveVenta, UsuarioActual.CveEmpresa) Then - GvComplementoPagos.DataSource = ObjBancos.DtResultados - End If - - ObjBancos.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(2).Text = String.Format("
    ", Encripta(String.Format("OP=CompP&EXT=xml&SerieFolio={0}&CveComplementoPago={1}&CveIE={2}", e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("CveIE")))) - e.Row.Cells(3).Text = String.Format("", Encripta(String.Format("OP=CompP&EXT=pdf&SerieFolio={0}&CveComplementoPago={1}&CveIE={2}", e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("CveIE")))) - - If e.Row.DataKey("Estatus").Contiene("1", "3") Then - e.Row.FCLinkButton("LnkCancelarComplemetno").Visible = True - End If - - - End If - End Sub - Protected Sub LnkSendMail_Click(sender As Object, e As EventArgs) - Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) - HdnSerieFolioPago.Value = gvRow.DataKey("SerieFolio").ToString - TxtParaMail.Text = gvRow.DataKey("CobranzaCorreo").ToString - UpSendMail.Update() - RegistraScript("$('#ModalDivMail').modal('show');") - End Sub - Private Sub LnkComplementoPago_Click(sender As Object, e As EventArgs) Handles LnkComplementoPago.Click - CargaComplementosPago() - RegistraScript("$('#ModalComplementoPagos').modal('show');") - - End Sub - Protected Sub BtnSendMail_Click(sender As Object, e As System.EventArgs) Handles BtnSendMail.Click - Try - - If HdnSerieFolioPago.Value <> "-1" Then - - If TxtParaMail.Text = "" Then - Alert("Tiene que introducir un correo en el campo Correo de Pago el cual se encuentra en el expediente del cliente en la pestaña cuentas x cobrar. ", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - Dim ObjMail As New ClsSisMail() - Dim RutaXML As String = String.Format("{0}\XML\Pag\{1}.xml", UsuarioActual.Empresa.Ruta, HdnSerieFolioPago.Value) - Dim RutaPDF As String = String.Format("{0}\PDF\Pag\{1}.pdf", UsuarioActual.Empresa.Ruta, HdnSerieFolioPago.Value) - - Dim Cuerpo As String = "Se hace entrega del comprobante de pago" - Dim Asunto As String = "Entrega de comprobante de pago" - - 'If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then - ' Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta - ' Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa) - ' Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante) - 'End If - - - 'If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then - ' Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta - ' Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante) - 'End If - - If IO.File.Exists(RutaPDF) AndAlso IO.File.Exists(RutaXML) Then - - - Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) - - LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = RutaPDF}) - LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = RutaXML}) - - If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, Asunto, Cuerpo, TxtCC.Text.Trim, LSRutasMail) Then - - TxtCC.Text = "" - RegistraScript("$('#ModalDivMail').modal('hide');") - Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion) - - Else - Alert("No se pudo enviar el correo electrónico.", TipoMensaje.MsgError) - End If - - - Else - Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError) - End If - - End If - - - - Catch ex As Exception - OnError("Ocurrió error al mandar MAIL", ex) - - End Try +#Region " COMPLEMENTOS PAGO " + Private Sub CargaComplementosPago() + + Dim ObjBancos As New ClsBancos + + If UsuarioActual.CveRol = 1 Then + GvComplementoPagos.Columns(8).Visible = True + + End If + + + If ObjBancos.GetComplementoPagos(-1, -1, CveVenta, UsuarioActual.CveEmpresa) Then + GvComplementoPagos.DataSource = ObjBancos.DtResultados + End If + + ObjBancos.Dispose() + GvComplementoPagos.DataBind() + UpComplementoPagos.Update() End Sub -#End Region + Protected Sub GvComplementoPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvComplementoPagos.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then -#Region "RELACIONAR FACTURAS A NC " + e.Row.Cells(2).Text = String.Format("", Encripta(String.Format("OP=CompP&EXT=xml&SerieFolio={0}&CveComplementoPago={1}&CveIE={2}", e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("CveIE")))) + e.Row.Cells(3).Text = String.Format("", Encripta(String.Format("OP=CompP&EXT=pdf&SerieFolio={0}&CveComplementoPago={1}&CveIE={2}", e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("CveComplementoPago"), e.Row.DBCampo("CveIE")))) + + If e.Row.DataKey("Estatus").Contiene("1", "3") Then + e.Row.FCLinkButton("LnkCancelarComplemetno").Visible = True + End If + + + End If + End Sub + Protected Sub LnkSendMail_Click(sender As Object, e As EventArgs) + Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) + HdnSerieFolioPago.Value = gvRow.DataKey("SerieFolio").ToString + TxtParaMail.Text = gvRow.DataKey("CobranzaCorreo").ToString + UpSendMail.Update() + RegistraScript("$('#ModalDivMail').modal('show');") + End Sub + Private Sub LnkComplementoPago_Click(sender As Object, e As EventArgs) Handles LnkComplementoPago.Click + CargaComplementosPago() + RegistraScript("$('#ModalComplementoPagos').modal('show');") + + End Sub + Protected Sub BtnSendMail_Click(sender As Object, e As System.EventArgs) Handles BtnSendMail.Click + Try + + If HdnSerieFolioPago.Value <> "-1" Then + + If TxtParaMail.Text = "" Then + Alert("Tiene que introducir un correo en el campo Correo de Pago el cual se encuentra en el expediente del cliente en la pestaña cuentas x cobrar. ", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + Dim ObjMail As New ClsSisMail() + Dim RutaXML As String = String.Format("{0}\XML\Pag\{1}.xml", UsuarioActual.Empresa.Ruta, HdnSerieFolioPago.Value) + Dim RutaPDF As String = String.Format("{0}\PDF\Pag\{1}.pdf", UsuarioActual.Empresa.Ruta, HdnSerieFolioPago.Value) + + Dim Cuerpo As String = "Se hace entrega del comprobante de pago" + Dim Asunto As String = "Entrega de comprobante de pago" + + 'If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then + ' Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta + ' Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa) + ' Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante) + 'End If + + + 'If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then + ' Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta + ' Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante) + 'End If + + If IO.File.Exists(RutaPDF) AndAlso IO.File.Exists(RutaXML) Then + + + Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) + + LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = RutaPDF}) + LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = RutaXML}) + + If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, Asunto, Cuerpo, TxtCC.Text.Trim, LSRutasMail) Then + + TxtCC.Text = "" + RegistraScript("$('#ModalDivMail').modal('hide');") + Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion) + + Else + Alert("No se pudo enviar el correo electrónico.", TipoMensaje.MsgError) + End If + + + Else + Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgError) + End If + + End If + + + + Catch ex As Exception + OnError("Ocurrió error al mandar MAIL", ex) + + End Try + End Sub +#End Region + +#Region "RELACIONAR FACTURAS A NC " 'Private Sub CargaFacturasRelacionar() ' Dim ObjVentas As New ClsVentas @@ -19627,1618 +19634,1618 @@ Partial Class Ventas ' If dtt IsNot Nothing Then dtt.Dispose() ' UPRelacionarNC.Update() 'End Sub -#End Region +#End Region -#Region " DOCUMENTACION VENTAS" - Property DtDocumentacionCliente As DataTable - Get - If ViewState("DtDocumentacionCliente") Is Nothing Then - Return New DataTable - Else - Return DirectCast(ViewState("DtDocumentacionCliente"), DataTable) - End If - End Get - Set(value As DataTable) - ViewState("DtDocumentacionCliente") = value - End Set - End Property - - Property IndexDocumentoCliente As Integer - Get - If ViewState("IndexDocumentoCliente") Is Nothing Then - Return -1 - Else - Return DirectCast(ViewState("IndexDocumentoCliente"), Integer) - End If - End Get - Set(value As Integer) - ViewState("IndexDocumentoCliente") = value - End Set - End Property - - Property AdjuntoDocumentacion As String - Get - If ViewState("AdjuntoDocumentacion") Is Nothing Then - Return "" - Else - Return DirectCast(ViewState("AdjuntoDocumentacion"), String) - End If - End Get - Set(value As String) - ViewState("AdjuntoDocumentacion") = value - End Set - End Property - - Protected Sub LnkDocCliente_Click(sender As Object, e As EventArgs) - RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });") - End Sub - - Private Sub CargaDocumentacionCliente() - LiDocumentoCliente.Visible = False - Dim objRH As New ClsEdocumentacion - - Dim TempCliente As Integer = If(CveVenta <= 0, CveCliente, -1) - Dim TipoDocumento As Integer = If(CveVenta <= 0, 14, -1) - - If objRH.DocumentacionElectronicaGet(-1, TempCliente, -1, UsuarioActual.CveEmpresa, TipoDocumento, CveVenta) Then - DtDocumentacionCliente = objRH.DtResultados.FiltraParametros("CveDocumentacionElectronica > 0") - DtDocumentacionCliente.Columns.Add("Accion", Type.GetType("System.String")) - DtDocumentacionCliente.Columns.Add("RutaArchivo", Type.GetType("System.String")) - DtDocumentacionCliente.Columns.Add("UpArchivo", Type.GetType("System.String")) - DtDocumentacionCliente.AcceptChanges() - GvDocumentosCliente.DataSource = DtDocumentacionCliente - LiDocumentoCliente.Visible = True - Else - DtDocumentacionCliente = Nothing - GvDocumentosCliente.DataSource = Nothing - End If - - objRH.Dispose() - GvDocumentosCliente.DataBind() - UpDocsCliente.Update() - - End Sub - - Protected Sub LnkUploadDocumentacionCliente_Click(sender As Object, e As EventArgs) - - Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - IndexDocumentoCliente = GvRow.RowIndex - - Dim Documentacion As String = GvRow.DataKey("Documentacion").ToString - AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString - - LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion - BtnModalClienteDocumentoCancelar.Visible = True - UpModalTitleUploadDocumentoCliente.Update() - UpModalButtonUploadDocumentoCliente.Update() - RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});") - - - End Sub - - Protected Sub BtnModalClienteDocumentoUpload_Click(sender As Object, e As EventArgs) Handles BtnModalClienteDocumentoUpload.Click - - If Not TxtFileCliente.getfiles().Archivos.Count > 0 Then - Alert("Tiene que cargar un archivo", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - Dim FileExtension As String = "-1" - Dim Filesgral As List(Of Archivo) = TxtFileCliente.getfiles().Archivos - Dim Filename As String = "" - - For Each fileItem As Archivo In Filesgral - Try - - FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "") - Dim tempArray() As String - tempArray = fileItem.filename.ToString().Split("-".ToCharArray()) - If RequiereOC And Not BtnModalClienteDocumentoCancelar.Visible Then - Dim Count = 0 - For Each GvRow As GridViewRow In GvDocumentosCliente.Rows - If GvRow.DataKey("Orden").ToEntero = 1 Then - IndexDocumentoCliente = Count - CargaDocumentoOC = True - Exit For - End If - Count = +1 - Next - End If - DtDocumentacionCliente(IndexDocumentoCliente)("RutaArchivo") = fileItem.FileUrl - DtDocumentacionCliente(IndexDocumentoCliente)("UpArchivo") = "1" - - TxtFileCliente.Text = "" - UpModalUploadClienteDocumento.Update() - Alert("Documento cargado", TipoMensaje.MsgInformacion) - Catch ex As Exception - OnError("Error al cargar archivo", ex) - End Try - - Next - - GvDocumentosCliente.DataSource = DtDocumentacionCliente - GvDocumentosCliente.DataBind() - - DtDocumentacionCliente.AcceptChanges() - UpDocsCliente.Update() - RegistraScript("$('#DivDocsClienteUpload').modal('hide')", "hidemodal3") - End Sub - - Private Sub GvDocumentosCliente_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDocumentosCliente.RowDataBound - - If e.Row.RowType = DataControlRowType.DataRow Then - - Dim ArchivoRuta As String = e.Row.DataKey("RutaArchivo") - Dim Adjunto As String = e.Row.DBCampo("Adjunto").ToString - Dim ImgDownLoad As Literal = e.Row.FCLiteral("ImgDownLoad") - Dim Chk As CheckBox = e.Row.FCCheckBox("chkEstatus") - Chk.Checked = If(e.Row.DataKey("Estatus").ToString = "1", True, False) - - If ArchivoRuta.Trim.Length > 0 Then - - Dim fi As New FileInfo(ArchivoRuta) - Dim linkDescarga As String = "" - If fi.Exists Then - linkDescarga = $"/Temp/{fi.Name}" - ImgDownLoad.Text = String.Format(" ", linkDescarga) - ImgDownLoad.Visible = True - End If - - Else - - If Adjunto.Trim.Length > 0 Then - ArchivoRuta = UsuarioActual.Empresa.Ruta & "Documentacion\Ventas\" & Adjunto - Dim fi As New FileInfo(ArchivoRuta) - Dim linkDescarga As String = "" - If fi.Exists() Then - linkDescarga = $"/Empresas/{UsuarioActual.CveEmpresa}/Documentacion/ventas/{fi.Name}" - ImgDownLoad.Text = String.Format(" ", linkDescarga) - ImgDownLoad.Visible = True - End If - - End If - End If - 'Else - - ' If ArchivoRuta.Trim.Length > 0 Then - - ' Dim fi As New FileInfo(ArchivoRuta) - ' Dim linkDescarga As String = "" - ' If fi.Exists Then - ' linkDescarga = $"/Temp/{fi.Name}" - ' ImgDownLoad.Visible = True - ' ImgDownLoad.Text = String.Format(" ", linkDescarga) - ' Else - ' ImgDownLoad.Visible = False - ' End If - - ' Else - ' ImgDownLoad.Visible = False - ' End If - - 'End If - End If - - End Sub - - Private Sub GuardaVentaDocumentosCliente(tCveVenta As Integer, ByRef objDocumentacion As ClsEdocumentacion) - - If tCveVenta > 0 Then - - For Each DRow As DataRow In DtDocumentacionCliente.FiltraParametros("RutaArchivo <> '' ").Rows - Dim CveDocumentacion As Integer = DRow("CveDocumentacion").ToString.ToEntero - Dim Estatus As Integer = DRow("Estatus").ToString.ToEntero - Dim Adjunto As String = DRow("Adjunto").ToString - Dim NombreArchivo As String = "" - Dim ArchivoRuta As String = DRow("RutaArchivo").ToString - If ArchivoRuta.Length > 0 Then Adjunto = ArchivoRuta - Dim Extension As String = Path.GetExtension(Adjunto) - - Dim CveDocumentacionElectronica As Integer = objDocumentacion.DocumentacionElectronicaAdd(CveDocumentacion, -1, -1, -1, 1, DRow("Observacion").ToString, Extension, UsuarioActual.CveUsuario, New Date(1900, 1, 1), CveVenta:=tCveVenta) - - If CveDocumentacionElectronica <= 0 Then ErrorList.Add("No se pudo registrar el documento ") - NombreArchivo = $"{CveDocumentacionElectronica}{Extension}" - - If ArchivoRuta.Length > 0 And NombreArchivo.Length > 0 Then - If Not Directory.Exists($"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\") Then - Directory.CreateDirectory($"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\") - End If - - Dim ArchivoExistenteRuta As String = $"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\{NombreArchivo}" - - If File.Exists(ArchivoExistenteRuta) Then File.Delete(ArchivoExistenteRuta) - - Try - - File.Move(ArchivoRuta, ArchivoExistenteRuta) - Catch ex As Exception - ErrorList.Add("No se pudo guardar el documento de la venta") - Exit For - End Try - - End If - Next - - End If - - End Sub - - Protected Sub chkEstatus_CheckedChanged(sender As Object, e As EventArgs) - - Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, CheckBox).NamingContainer, GridViewRow) - Dim chk As CheckBox = GvRow.FCCheckBox("chkEstatus") - - - IndexDocumentoCliente = GvRow.RowIndex - - - If chk.Checked Then - DtDocumentacionCliente(IndexDocumentoCliente)("Estatus") = True - Else - DtDocumentacionCliente(IndexDocumentoCliente)("Estatus") = False - End If - - DtDocumentacionCliente.AcceptChanges() - - - End Sub - - Protected Sub CargarArchivosOC(sender As Object, e As EventArgs) - Dim Documentacion As String = "" - RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });", "ModalArchivos") - Dim Count = 0 - For Each GvRow As GridViewRow In GvDocumentosCliente.Rows - If GvRow.DataKey("Orden").ToEntero = 1 Then - IndexDocumentoCliente = Count - Documentacion = GvRow.DataKey("Documentacion").ToString - AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString - Exit For - End If - Count = +1 - Next - LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion - BtnModalClienteDocumentoCancelar.Visible = False - UpModalTitleUploadDocumentoCliente.Update() - UpModalButtonUploadDocumentoCliente.Update() - RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});", "modalOC") - End Sub -#End Region +#Region " DOCUMENTACION VENTAS" + Property DtDocumentacionCliente As DataTable + Get + If ViewState("DtDocumentacionCliente") Is Nothing Then + Return New DataTable + Else + Return DirectCast(ViewState("DtDocumentacionCliente"), DataTable) + End If + End Get + Set(value As DataTable) + ViewState("DtDocumentacionCliente") = value + End Set + End Property -#Region " SALDAR VENTA " - Protected Sub BtnSaldarVenta_Click(sender As Object, e As EventArgs) - SaldarVenta() - End Sub - Private Sub SaldarVenta() - 'Dim ObjVenta As New ClsVentas - - 'If ObjVenta.VentasSaldar(CveVenta, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 0, -1, -1, TxtFechaSaldarVenta.Text.ToDate) Then - ' Alert("Documento Saldado") - 'End If - - 'ObjVenta.Dispose() - - 'RegistraScript("$('#ModalSaldarVenta').modal('hide')", "ModalSaldarVentaHidde") - - Dim ObjConta As New ClsContabilidad - ObjConta.IniciaTransacSQL() - Dim CvePrePoliza As Integer = 0 - Dim MsgError As String = "" - - Dim ObjIE As New ClsBancos - Dim FechaUltimaFluctuacion As Date = MinFecha - Dim TipoCambioFluctuacion As Decimal = 1 - If ObjIE.GetFluctuacionesBitacora(UsuarioActual.CveEmpresa) Then - If ObjIE.DtResultados.Rows.Count > 0 Then - Dim tFecha As Date = TxtFechaSaldarVenta.Text.ToDate - Dim Fecha As String = String.Format("{0}/{1}/{2}", tFecha.Year, tFecha.Month, tFecha.Day) - Dim drr As DataRow = ObjIE.DtResultados.FiltroPrimero("Fecha < #" & Fecha & "#", "Fecha DESC") - - If drr IsNot Nothing Then - FechaUltimaFluctuacion = drr("Fecha").ToString.ToDate - TipoCambioFluctuacion = drr("TipoCambio").ToString.ToDecimal - End If - - End If - End If - - ObjIE.Dispose() - - - Dim IdCtaContable As Integer = IdCtaContClientes - Dim CveCuenta As Integer = 0 - Dim PorcentajePago As Decimal = SaldoVenta / TxtTotal.Text.ToDecimal - Dim Saldo As Decimal = SaldoVenta - Dim SubTotal As Decimal = PorcentajePago * TxtSubTotal.Text.ToDecimal - Dim IVA As Decimal = PorcentajePago * TxtIVA.Text.ToDecimal - Dim IEPS As Decimal = PorcentajePago * TxtIEPS.Text.ToDecimal - Dim TCVenta As Decimal = TxtTipoCambio.Text.ToDecimal - Dim FechaVenta As Date = TxtFecha.Text.ToDate - Dim FechaPago As Date = TxtFechaSaldarVenta.Text.ToDate - Dim tCveMoneda As Integer = DdlMoneda.SelectedValue.ToEntero - Dim TCPago As Decimal = GlobalTipoCambio(TxtFechaSaldarVenta.Text.ToDate).FormatoNumero(4).ToDecimal - Dim CveConceptoDeduccion As Integer = 211 - - - 'si la fecha del documento es anterior a su ultima fluctuación. toma el Tc de la fluctuacion - If tCveMoneda = 2 Then - If FechaVenta < FechaUltimaFluctuacion Then - TCVenta = TipoCambioFluctuacion - End If - End If - - - 'condicionante - Dim ClienteMovto As Boolean = True - Dim SubtotalMovto As Boolean = False - Dim CveConceptoCliente As Integer = 2 - Dim ImpuestosMovto As Boolean = False - Dim IdCuentaContableNoDeducible As Integer = 0 - Dim SerieFolio As String = LblSerie.Text & "-" & TxtFolio.Text - Dim ConceptoPartida As String = "saldado " & SerieFolio - ' Dim CveSubProyecto As Integer = gr.DataKey("CveSubProyecto").ToEntero - - If CveConceptoDeduccion = 255 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(266).ToEntero - If CveConceptoDeduccion = 211 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(559).ToEntero - If CveConceptoDeduccion = 263 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(537).ToEntero - If CveConceptoDeduccion = 252 Then IdCuentaContableNoDeducible = 0 - If CveConceptoDeduccion = 78 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.IdCuentaOtrosIngresos - - If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122) Then - ClienteMovto = False : Saldo = Saldo * -1 - ImpuestosMovto = True : IVA = IVA * -1 - CveConceptoCliente = 1 - 'falta cuenta incobrable - IdCuentaContableNoDeducible = 3114 - End If - - Dim UsaComplementaria As Boolean = False - - If UsuarioActual.CveEmpresa = 119 Then - UsaComplementaria = True - End If - - If MsgError = "" Then - CvePrePoliza = ObjConta.AddPrePolizas("Ventas/Saldarr", 47, SaldoVenta, SaldoVenta, tCveMoneda, TxtFechaSaldarVenta.Text.ToDate, ConceptoPartida, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - - If tCveMoneda = 2 Then - IdCtaContable = IdCtaContMonedaExtranjera - Else - IdCtaContable = IdCtaContClientes - End If - - If UsaComplementaria AndAlso tCveMoneda = 2 Then - 'normal - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, Saldo, SerieFolio, CveConceptoCliente, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContable, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, Saldo), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - 'complementaria - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, 0, SerieFolio, 207, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContComplementaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, (Saldo * TCVenta) - Saldo), ImporteME:=Saldo, CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - - Else - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, Saldo, SerieFolio, CveConceptoCliente, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContable, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, Saldo * TCVenta), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - - End If - - 'fluctuación. - If tCveMoneda = 2 Then - Dim ImporteFluctuacion As Decimal = 0 - ImporteFluctuacion = Saldo * (TCPago - TCVenta) - If TCPago > TCVenta Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Math.Abs(ImporteFluctuacion), SerieFolio, 64, ConceptoPartida, FechaPago, IdCtaContable:=UsuarioActual.Empresa.IdCuentaGananciaCambiaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=Math.Abs(ImporteFluctuacion), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - Else - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Math.Abs(ImporteFluctuacion), SerieFolio, 65, ConceptoPartida, FechaPago, IdCtaContable:=UsuarioActual.Empresa.IdCuentaPerdidaCambiaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=Math.Abs(ImporteFluctuacion), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - End If - - 'cuando hay pago en dólares, se ajusta el concepto de subtotal, - SubTotal = (Saldo * TCVenta) + ImporteFluctuacion - (IVA * TCVenta) - (IEPS * TCVenta) - - End If - - - ' iva - Dim PorcentajeImpuesto As Decimal = DdlIVA.SelectedValue.ToEntero - - Dim IdCtaIVATrasladado As Integer = 0 - Dim CveCuentaIVATrasladado As Integer = 0 - - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then - IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero - CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero - End If - - IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) - CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) - If IVA > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ImpuestosMovto, IVA, SerieFolio, 61, ConceptoPartida, FechaPago, IdCtaContable, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, IVA, IVA * TCVenta), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - - IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSTrasladado - CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSTrasladado - If IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ImpuestosMovto, IEPS, SerieFolio, 39, ConceptoPartida, FechaPago, IdCtaContable, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, IEPS, IEPS * TCVenta), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - - 'al gasto,Subtotal - If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, SubtotalMovto, SubTotal, SerieFolio, CveConceptoDeduccion, ConceptoPartida, FechaPago, IdCuentaContableNoDeducible, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=SubTotal, CveCuenta:=-1, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then - MsgError = "Ocurrio un error al saldar el movimiento" - End If - - If ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 5) Then - If ObjConta.ValorPolizaDescuadre > 0 Then - MsgError = ObjConta.MensajePolizaDescuadre + " " + ObjConta.ValorDiferencia - GuardaLogAD($"Ventas/ClientesAbonar | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas") - - End If - End If - End If - - - If MsgError = "" Then - 'ObjConta.RollBack() - ObjConta.Commit() - - RegistraScript("$('#ModalSaldarVenta').modal('hide')", "ModalSaldarVentaHidde") - Alert("Documento Saldado") - Else - ObjConta.RollBack() - Alert(MsgError, TipoMensaje.MsgError) - End If - - - ObjConta.Dispose() - - End Sub -#End Region + Property IndexDocumentoCliente As Integer + Get + If ViewState("IndexDocumentoCliente") Is Nothing Then + Return -1 + Else + Return DirectCast(ViewState("IndexDocumentoCliente"), Integer) + End If + End Get + Set(value As Integer) + ViewState("IndexDocumentoCliente") = value + End Set + End Property -#Region "PAQUETERIA GUIAS" + Property AdjuntoDocumentacion As String + Get + If ViewState("AdjuntoDocumentacion") Is Nothing Then + Return "" + Else + Return DirectCast(ViewState("AdjuntoDocumentacion"), String) + End If + End Get + Set(value As String) + ViewState("AdjuntoDocumentacion") = value + End Set + End Property - Protected Sub LnkAgregarGuia_Click(sender As Object, e As EventArgs) - ''DivModalGuias - 'DdlPaqueteria.Items.Clear() - 'DdlPaqueteria.DataSource = GlobalDTPaqueterias - 'DdlPaqueteria.DataBind() - 'DdlPaqueteria.Items.Insert(0, New ListItem("Seleccione ", "-1")) - 'UpModalGuias.Update() - 'CargaGvPaqueteria() - - 'RegistraScript("$('#DivModalGuias').modal({ backdrop: 'static', keyboard: false });") - - '' 21/Marzo/2018 - Se agrego Link a Modulo Paqueterias Guias - RegistraScript(String.Format("AbrirVentana('/General/PopUpPaqueteriasGuias.aspx?CveVenta={0}',800,620);", CveVenta)) - - End Sub - Protected Sub BtnAgregarGuia_Click(sender As Object, e As EventArgs) - - Dim objInventario As New ClsInventarios - Dim CvePaqueteriaGuia As Integer - - If objInventario.AddPaqueteriaGuia(DdlPaqueteria.SelectedValue.ToEntero, -1, TxtPaqueteriaGuia.Text.Trim, TxtPaqueteriaNumcajas.Text.ToEntero, TxtPaqueteriaPeso.Text.ToDecimal, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, - TxtRastreo.Text.Trim, TxtDimensiones.Text.Trim, TxtFechaEst.Text.Trim, CveVenta:=CveVenta) Then - - CvePaqueteriaGuia = objInventario.DtResultados.Rows(0)(0).ToString.ToEntero - CargaGvPaqueteria() - LimpiacontrolesPaqueteria() - - 'Envia notificacion se agrego guia vacia eliminada - If TxtPaqueteriaGuia.Text.Trim.Length = 0 Then - EnviarCorreoNotificacionGuias(2, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CvePaqueteriaGuia:=CvePaqueteriaGuia) - End If - - End If - - objInventario.Dispose() - - End Sub - Protected Sub LnkRemovePaqueteriaGuia_Click(sender As Object, e As EventArgs) - - Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - Dim CvePaqueteriaGuia As Integer = GvRow.DataKey("CvePaqueteriaGuia").ToString.ToEntero - Dim Guia As String = GvRow.DataKey("Guia").ToString - - Dim objInventario As New ClsInventarios - - If objInventario.RemovePaqueteriaGuia(CvePaqueteriaGuia, UsuarioActual.CveEmpresa) Then - CargaGvPaqueteria() - - If Guia.Trim.Length = 0 Then - 'Envia notificacion se elimino guia vacia eliminada - EnviarCorreoNotificacionGuias(3, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CvePaqueteriaGuia:=CvePaqueteriaGuia) - - End If - - End If - - objInventario.Dispose() - - End Sub - Private Sub CargaGvPaqueteria() - - Dim objInventario As New ClsInventarios - - If objInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - - GvPaqueriaGuias.DataSource = objInventario.DtResultados - - If objInventario.DtResultados.Rows.Count > 0 Then - BtnAgregarGuia.Attributes.Add("data-toggle", "confirmation") - BtnAgregarGuia.Attributes.Add("data-popout", "true") - BtnAgregarGuia.Attributes.Add("data-original-title", "¿Está seguro de registrar una nueva guia a la factura?") - BtnAgregarGuia.Attributes.Add("data-btn-ok-label", "si") - Else - BtnAgregarGuia.Attributes.Remove("data-toggle") - BtnAgregarGuia.Attributes.Remove("data-popout") - BtnAgregarGuia.Attributes.Remove("data-original-title") - BtnAgregarGuia.Attributes.Remove("data-btn-ok-label") - End If - - If objInventario.DtResultados.Rows.Count > 1 Then - EnviarCorreoNotificacionGuias(4, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CountPaqueteria:=objInventario.DtResultados.Rows.Count) - End If - Else - GvPaqueriaGuias.DataSource = Nothing - End If - - objInventario.Dispose() - GvPaqueriaGuias.DataBind() - UpModalGuias.Update() - - End Sub - Private Sub LimpiacontrolesPaqueteria() - - DdlPaqueteria.SelectedIndex = 0 - TxtPaqueteriaGuia.Text = "" - TxtPaqueteriaNumcajas.Text = "" - TxtPaqueteriaPeso.Text = "" - - TxtRastreo.Text = "" - TxtDimensiones.Text = "" - TxtFechaEst.Text = "" - - End Sub - Protected Sub LnkGuiaPaqueteriaGuia_Click(sender As Object, e As EventArgs) - - Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - Dim CveMovimiento As Integer = -1 - Dim CvePaqueteriaGuia As Integer = GvRow.DataKey("CvePaqueteriaGuia").ToString.ToEntero - Dim NumCajas As String = GvRow.DataKey("NumCajas").ToString - Dim Guia As String = GvRow.DataKey("Guia").ToString - Dim Peso As String = GvRow.DataKey("Peso").ToString.ToDecimal.ToString("####.00") - Dim DTDatosClienteGuia As New DataTable - Dim DTMovimientosDetalle As New DataTable - Dim CvePaqueteria As Integer = GvRow.DataKey("CvePaqueteria").ToString.ToEntero - Dim RutaRdlc As String = Server.MapPath("~") & "\Empresas\Grales\Formatos\GuiasFormato" & CvePaqueteria & ".rdlc" - - Dim Rastreo As String = GvRow.DataKey("Rastreo") - Dim Dimensiones As String = GvRow.DataKey("Dimensiones") - Dim FechaEstimada As String = GvRow.DataKey("FechaEstimada") - Dim ValorStimado As Double = 0 - - If Not File.Exists(RutaRdlc) Then - RutaRdlc = Server.MapPath("~") & "\Empresas\Grales\Formatos\GuiasFormato0.rdlc" - End If - - RutaRdlc = RutaRdlc.Replace(Server.MapPath("~") & "\", "") - - Dim params As New List(Of ReportParameter) - Dim ObjInventario As New ClsInventarios - - If ObjInventario.GetPaqueteriaGuiasInfoFormato(CveMovimiento, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - DTDatosClienteGuia = ObjInventario.DtResultados - Else - ObjInventario.Dispose() - Exit Sub - End If - - If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then - - DTMovimientosDetalle = ObjInventario.DtResultados - DTMovimientosDetalle.Columns.Add("Peso") - DTMovimientosDetalle.Columns.Add("Dimensiones") - DTMovimientosDetalle.AcceptChanges() - - For Each Drow As DataRow In DTMovimientosDetalle.Rows - Drow("Peso") = Peso - Drow("Dimensiones") = Dimensiones - DTMovimientosDetalle.AcceptChanges() - Next - - ValorStimado = DTMovimientosDetalle.SUM("PU") - ObjInventario.Dispose() - Else - ObjInventario.Dispose() - Exit Sub - End If - - If DTDatosClienteGuia.Rows.Count > 0 Then - params.Add(New ReportParameter("NombreComercial", DTDatosClienteGuia.Rows(0)("NombreComercial").ToString)) - params.Add(New ReportParameter("Direccion", DTDatosClienteGuia.Rows(0)("Direccion").ToString)) - params.Add(New ReportParameter("Colonia", DTDatosClienteGuia.Rows(0)("Colonia").ToString)) - params.Add(New ReportParameter("NoExt", DTDatosClienteGuia.Rows(0)("NoExt").ToString)) - params.Add(New ReportParameter("NoInt", DTDatosClienteGuia.Rows(0)("NoInt").ToString)) - params.Add(New ReportParameter("Localidad", DTDatosClienteGuia.Rows(0)("Localidad").ToString)) - params.Add(New ReportParameter("Telefono", DTDatosClienteGuia.Rows(0)("Telefono").ToString)) - params.Add(New ReportParameter("RFCCliente", DTDatosClienteGuia.Rows(0)("RFC").ToString)) - params.Add(New ReportParameter("CiudadCliente", DTDatosClienteGuia.Rows(0)("Ciudad").ToString)) - Else - Exit Sub - End If - - Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) - Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) - - params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) - params.Add(New ReportParameter("EmpresaDireccion", UsuarioActual.Empresa.Direccion)) - params.Add(New ReportParameter("EmpresaTelefono", UsuarioActual.Empresa.Telefono)) - params.Add(New ReportParameter("EmpresaColonia", UsuarioActual.Empresa.Colonia)) - params.Add(New ReportParameter("EmpresaLocalidad", UsuarioActual.Empresa.Localidad)) - params.Add(New ReportParameter("RFCEmpresa", UsuarioActual.Empresa.RFC)) - params.Add(New ReportParameter("CiudadEmpresa", UsuarioActual.Empresa.Ciudad)) - - params.Add(New ReportParameter("EmpresaTelefono", UsuarioActual.Empresa.Telefono)) - params.Add(New ReportParameter("NumCajas", NumCajas)) - params.Add(New ReportParameter("Peso", Peso)) - params.Add(New ReportParameter("Guia", Guia)) - - params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) - params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) - - params.Add(New ReportParameter("Anio", Now.Year.ToString)) - params.Add(New ReportParameter("Mes", Now.Month.ToString("00"))) - params.Add(New ReportParameter("Dia", Now.Day.ToString("00"))) - - params.Add(New ReportParameter("Rastreo", Rastreo)) - params.Add(New ReportParameter("Dimensiones", Dimensiones)) - params.Add(New ReportParameter("FechaEstimada", FechaEstimada)) - - If Imagen.Exists Then - params.Add(New ReportParameter("LogoPath", logouri)) - Else - params.Add(New ReportParameter("LogoPath", "")) - End If - - ImprimirPDF(RutaRdlc, DTMovimientosDetalle, params, $"ReporteGuia_{Now.ToString("yyyyMMddhhmmss")}") - - End Sub - Private Sub GvPaqueriaGuias_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvPaqueriaGuias.RowDataBound - - If e.Row.RowType = DataControlRowType.DataRow Then - Dim Lnk As LinkButton = e.Row.FCLinkButton("LnkGuiaPaqueteriaGuia") - Dim Destinatario As String = e.Row.DataKey("Mail").ToString - - If Destinatario.Length = 0 Then - e.Row.FCLinkButton("LnkGuiaPaqueteriaMail").Visible = False - Else - e.Row.FCLinkButton("LnkGuiaPaqueteriaMail").Attributes.Add("title", "Enviar correo a: " & Destinatario) - End If - - ScriptManager.GetCurrent(Me).RegisterPostBackControl(Lnk) - End If - - End Sub - Private Sub GvPaqueteriaCreaEnlaces() - - For Each GvRow As GridViewRow In GvPaqueriaGuias.Rows - - If GvRow.RowType = DataControlRowType.DataRow Then - Dim Lnk As LinkButton = GvRow.FCLinkButton("LnkGuiaPaqueteriaGuia") - ScriptManager.GetCurrent(Me).RegisterPostBackControl(Lnk) - End If - - Next - End Sub - Protected Sub LnkGuiaPaqueteriaMail_Click(sender As Object, e As EventArgs) - - Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - - Dim SerieFolio As String = GvRow.DataKey("SerieFolio").ToString - Dim NombreComercial As String = GvRow.DataKey("NombreComercial").ToString - Dim Destinatario As String = GvRow.DataKey("Mail").ToString - Dim Paqueteria As String = GvRow.DataKey("Paqueteria").ToString - Dim Guia As String = GvRow.DataKey("Guia").ToString - Dim Rastreo As String = GvRow.DataKey("Rastreo").ToString - Dim CveVenta As Integer = GvRow.DataKey("CveVenta").ToEntero - - EnviarCorreoNotificacionGuias(1, SerieFolio, NombreComercial, Destinatario, Paqueteria, Guia, Rastreo, CveVenta, New DataTable) - - End Sub - Private Sub EnviarCorreoNotificacionGuias(Tipo As Integer, SerieFolio As String, NombreComercial As String, Destinatario As String, Paqueteria As String, Guia As String, Rastreo As String, CveVenta As Integer, tDtMovimientos As DataTable, Optional CountPaqueteria As Integer = Nothing, Optional CvePaqueteriaGuia As Integer = -1) - - Dim Correo As New ClsSisMail() - Dim Asunto As String = UsuarioActual.Empresa.NombreCorto & " Envio de pedido: " & SerieFolio - Dim Cuerpo As New StringBuilder - - - Select Case Tipo - Case 1 'Notificacion Normal - - ' Dim ObjCliente As New ClsClientes() - - - - 'Dim FolioOC As String = "" - 'Dim FolioPedido As String = "" - 'Dim CorreoDestino = "" - 'Dim CveVendedor As Integer = DdlVendedor.SelectedValue.ToEntero - 'Dim CorreoVendedor As String = "" - 'Dim CorreoVendedorUsuarioActual As String = "" - - - 'If CveVendedor > 0 Then - ' Dim DtTemp As New DataTable - ' DtTemp = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros($"CveVendedor={CveVendedor}") - - ' If DtTemp.Rows.Count > 0 Then - ' CorreoVendedor = DtTemp.Rows(0)("Correo").ToString - ' End If - - 'End If - - 'Try - ' If UsuarioActual.CveVendedor > 0 Then - ' Dim DtTemp As New DataTable - ' DtTemp = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros($"CveVendedor={ UsuarioActual.CveVendedor}") - - ' If DtTemp.Rows.Count > 0 Then - ' CorreoVendedorUsuarioActual = DtTemp.Rows(0)("Correo").ToString - ' End If - - ' End If - - 'Catch ex As Exception - - 'End Try - - - 'If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, -1, TipoCliente:=-1) Then - - ' If ObjCliente.CobranzaCorreo <> ObjCliente.Mail Then - ' CorreoDestino = $"{ObjCliente.CobranzaCorreo};{ObjCliente.Mail }" - ' Else - ' CorreoDestino = $"{ObjCliente.Mail}" - ' End If - - 'End If - 'ObjCliente.Dispose() - - - 'If CorreoVendedor.Trim.Length > 0 Then - ' CorreoDestino = $"{CorreoDestino};{CorreoVendedor}" - 'End If - - 'If CorreoVendedorUsuarioActual.Trim.Length > 0 Then - ' CorreoDestino = $"{CorreoDestino};{CorreoVendedorUsuarioActual}" - 'End If - - 'If CveOC > 0 Then - ' Dim ObjOC As New ClsOC - ' If ObjOC.GetOC(CveOC, UsuarioActual.CveEmpresa) Then - ' FolioOC = ObjOC.Folio.ToString - ' End If - ' ObjOC.Dispose() - 'End If - - - 'If CvePedido > 0 Then - ' Dim ObjVenta As New ClsVentas - ' If ObjVenta.GetVenta(CvePedido, UsuarioActual.CveEmpresa) Then - ' FolioPedido = ObjVenta.Folio.ToString - ' End If - ' ObjVenta.Dispose() - 'End If - - - Cuerpo.AppendLine($"Estimado {NombreComercial} le informamos que los productos de la factura {SerieFolio} han sido enviados mediante la paquetería {Paqueteria} con Guia {Guia} , Rastreo {Rastreo} .

    ") - - If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then - Cuerpo.AppendLine("") - Cuerpo.AppendLine("") - - For Each Drow As DataRow In tDtMovimientos.Rows - Cuerpo.AppendLine($"") - Next - Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") - End If - - Cuerpo.AppendLine("

    Dudas y aclaraciones con su coordinador empresarial.") - - - ' Destinatario = "sig.buzon@gmail.com" - - - If Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) Then - GuardarBitacora(CveVenta, "", "Notificación de envío de productos al cliente") - Alert("Correo envíado exitosamente a " & Destinatario) - Else - Alert("Ocurrió un error al envíar el correo a " & Destinatario) - End If - - Exit Select - Case 2 'Notificacion Guia vacia - - 'Cuerpo.AppendLine($"Se informa que en la venta {SerieFolio} se agrego la paqueteria {Paqueteria} con guia vacia por el usuario { UsuarioActual.Nombre }.

    ") - - 'If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then - ' Cuerpo.AppendLine("") - ' Cuerpo.AppendLine("") - - ' For Each Drow As DataRow In tDtMovimientos.Rows - ' Cuerpo.AppendLine($"") - ' Next - ' Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") - 'End If - 'Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) - - 'Exit Select - - Case 3 'Notificacion Gui Vacia Eliminada - 'Cuerpo.AppendLine($"Se informa que en la venta {SerieFolio} se elimino la paqueteria {Paqueteria} con guia vacia por el usuario { UsuarioActual.Nombre }.

    ") - - 'If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then - ' Cuerpo.AppendLine("") - ' Cuerpo.AppendLine("") - - ' For Each Drow As DataRow In tDtMovimientos.Rows - ' Cuerpo.AppendLine($"") - ' Next - ' Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") - ' Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) - 'End If - - Exit Select - Case 4 'mas de una guia - Cuerpo.AppendLine($"Se informa que en la venta {SerieFolio} cuenta con { CountPaqueteria } paqueterias, se agrego la paqueteria {Paqueteria}, usuario { UsuarioActual.Nombre }.

    ") - Destinatario = "" - If UsuarioActual.CveEmpresa.Contiene(72, 80) Then - Destinatario = "luzdelmarcoeto@compuproveedores.com;ramonmartinez@compuproveedores.com" - End If - 'correo a ramón y a luz - - If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then - Cuerpo.AppendLine("") - Cuerpo.AppendLine("") - - For Each Drow As DataRow In tDtMovimientos.Rows - Cuerpo.AppendLine($"") - Next - Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") - End If - Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) - Exit Select - - End Select - - - - - End Sub - Private Sub GuardarBitacora(CveVenta As Integer, RutaAdjunto As String, Obser As String) - Dim ObjEventos As New ClsOIEventos() - - Try - If ObjEventos.AddEventoBitacora(Obser, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - - End If - Catch ex As Exception - OnError("Se presento un Error al guardar la Bitacora", ex) - End Try - - ObjEventos.Dispose() - End Sub -#End Region - -#Region " APLICAR NOTA DE CREDITO " - Private Sub InicializaAplicarNC() - 'If Not UsuarioActual.CveUsuario = 100 Then - ' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then - ' Exit Sub - ' End If - 'End If - - If CveVenta <= 0 Or Not DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Or Not HplSaldoAuxiliar.Text.ToDouble > 0 Then - ''If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then LkNotaCredito.Visible = False - Exit Sub - End If - - 'sino tiene el permiso de peude generar NC - If Not UsuarioActual.TienePermisoProceso(175) Then - Exit Sub - End If - - - AplicaNCMasiva = False - AplicaNC = False - LBNotaCredito.Visible = True - 'LkNotaCredito.Visible = False - - TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNC();") - TxtNCImporte.Attributes.Add("onkeyup", "CalculaPorcentajeNC();") - - Dim PorcentajeMaximo = 0.0 - If TxtTotal.Text.ToDouble > 0 Then - PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.ToDouble - Else - RVNCPorcentaje.MinimumValue = "0" - RVTxtNCImporte.MinimumValue = "0" - End If - - TxtNCPorcentaje.Text = PorcentajeMaximo.FormatoNumero(4) - If PorcentajeMaximo < RVNCPorcentaje.MinimumValue.ToDouble Then - RVNCPorcentaje.MinimumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString - End If - RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString - - TxtNCImporte.Text = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero - If ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble < RVTxtNCImporte.MinimumValue.ToDouble Then - RVTxtNCImporte.MinimumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString - End If - RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString - - UpAplicarNC.Update() - End Sub - - Private Sub InicializaAplicarNCMasiva() - - 'If Not UsuarioActual.CveUsuario = 100 Then - ' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then - ' Exit Sub - ' End If - 'End If - - 'sino tiene el permiso de peude generar NC - If Not UsuarioActual.TienePermisoProceso(175) Then - Exit Sub - End If - - AplicaNCMasiva = True - LBNotaCredito.Visible = True - 'LkNotaCredito.Visible = False - DivGvCxC.Visible = True - CargaCxC() - TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNCMasivo();") - TxtNCImporte.Text = "0.00" - TxtNCImporte.Enabled = False - RVTxtNCImporte.Enabled = False - - UpAplicarNC.Update() - - End Sub - - Private Sub CargaCxC() - Dim ObjMovtos As New ClsMovimientos() - If ObjMovtos.GetCxCClienteDetalle(ViewState("CveCliente").ToString.ToEntero, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa, DdlSucursalCliente.SelectedValue.ToEntero) Then - Dim DtTemporal As DataTable = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act' AND CveVenta > 0", "Moneda, OrdenVencimiento, FechaVencimiento") - GvCxC.DataSource = DtTemporal - End If - ObjMovtos.Dispose() - GvCxC.DataBind() - End Sub - - Protected Sub GvCxC_RowDataBound(sender As Object, e As GridViewRowEventArgs) - If e.Row.RowType = DataControlRowType.DataRow Then - e.Row.FCCheckBox("ChkCxC").Attributes.Add("onclick", $"CalculaTotalChk({e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble},{TxtNCPorcentaje.Text.ToDouble}, this);") - e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaCantidadNCMasivo({TxtNCPorcentaje.Text.ToDouble()},{e.Row.DBCampo("Saldo").ToDouble},{e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{TxtNCImporte.ClientID},{e.Row.FCCheckBox("ChkCxC").ClientID}, this);") - End If - End Sub - - Protected Sub DdlNCNivelImporte_SelectedIndexChanged(sender As Object, e As EventArgs) - Dim ImporteReferencia As Double = 0, PorcentajeMaximo As Double = 0 - If Not AplicaNCMasiva Then - ImporteReferencia = If(DdlNCNivelImporte.SelectedValue.ToEntero = 1, TxtTotal.Text.Trim.ToDouble, TxtSubTotal.Text.Trim.ToDouble) - PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.Trim.ToDouble - RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString - RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * ImporteReferencia) / 100).FormatoNumero().ToDouble.ToString - End If - - If AplicaNCMasiva Then RegistraScript($"CalculaImporteNCMasivo()", "CalculaImporteNCMasivo") Else RegistraScript("CalculaImporteNC();", "CalculaImporteNC") - UpAplicarNC.Update() - End Sub - - Protected Sub BtnAplicarNC_Click(sender As Object, e As EventArgs) - - Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlNCPS.SelectedValue.ToEntero).FiltroPrimero("") - If DrPS Is Nothing Then - Alert("Ocurrió un error al cargar la información del producto. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError) - Exit Sub - Else - 'VALIDA CLAVES SAT - If DrPS("SATClavePS").ToString = "" Then - Alert($"El concepto {DrPS("Codigo").ToString}-{DrPS("PS").ToString} no cuenta con producto SAT. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - If DrPS("SATClaveUnidadMedida").ToString = "" Then - Alert($"El concepto {DrPS("Codigo").ToString}-{DrPS("PS").ToString} no cuenta con Unidad Medida SAT. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - - If DdlTipoComprobante.SelectedValue = "Ant" Then CveAnticipo = CveVenta - - DdlTipoComprobante.SelectedValueExist("Egs") - - 'CREAMOS DT PARA UTILIZAR AL TIMBRAR - InicializaDTVentasNC() - - Dim DtImpuestos As New DataTable - DtImpuestos.Columns.Add("ImportePU", GetType(Double)) - DtImpuestos.Columns.Add("ImporteTotal", GetType(Double)) - DtImpuestos.Columns.Add("PorcentajeIVA", GetType(Double)) - DtImpuestos.Columns.Add("ImporteIVA", GetType(Double)) - DtImpuestos.Columns.Add("PorcentajeRetIVA", GetType(Double)) - DtImpuestos.Columns.Add("ImporteRetIVA", GetType(Double)) - DtImpuestos.Columns.Add("PorcentajeRetISR", GetType(Double)) - DtImpuestos.Columns.Add("ImporteRetISR", GetType(Double)) - DtImpuestos.Columns.Add("PorcentajeIEPS", GetType(Double)) - DtImpuestos.Columns.Add("ImporteIEPS", GetType(Double)) - DtImpuestos.Columns.Add("CveSubProyecto", GetType(Integer)) - DtImpuestos.AcceptChanges() - - If AplicaNCMasiva Then - For Each Gvr As GridViewRow In GvCxC.Rows - If Gvr.FCCheckBox("ChkCxC").Checked Then - DtImpuestos.Merge(CargaDtImpuestosNC(Gvr.DataKey("CveVenta").ToString.ToEntero, Gvr.FCTextBox("TxtImporte").Text.ToString.ToDecimal), True, MissingSchemaAction.Ignore) - 'CARGA FACTURA A LA CUAL SE APLICA LA NC - CargaNCDT(Gvr.DataKey("CveVenta").ToString.ToEntero, Gvr.FCTextBox("TxtImporte").Text.ToString.ToDecimal) - End If - Next - Else - DtImpuestos = CargaDtImpuestosNC(CveVenta, TxtNCImporte.Text.Trim.ToDecimal) - End If - - Dim query = From dr In DtImpuestos - Group By PorcentajeIVA = dr("PorcentajeIVA").ToString.ToDecimal, - PorcentajeRetIVA = dr("PorcentajeRetIVA").ToString.ToDecimal, - PorcentajeRetISR = dr("PorcentajeRetISR").ToString.ToDecimal, - PorcentajeIEPS = dr("PorcentajeIEPS").ToString.ToDecimal - Into x = Group - Select ImportePU = x.Sum(Function(s) s("ImportePU").ToString.ToDecimal), - ImporteTotal = x.Sum(Function(s) s("ImporteTotal").ToString.ToDecimal), - ImporteIVA = x.Sum(Function(s) s("ImporteIVA").ToString.ToDecimal), - ImporteRetIVA = x.Sum(Function(s) s("ImporteRetIVA").ToString.ToDecimal), - ImporteRetISR = x.Sum(Function(s) s("ImporteRetISR").ToString.ToDecimal), - ImporteIEPS = x.Sum(Function(s) s("ImporteIEPS").ToString.ToDecimal), - PorcentajeIVA = PorcentajeIVA, - PorcentajeRetIVA = PorcentajeRetIVA, - PorcentajeRetISR = PorcentajeRetISR, - PorcentajeIEPS = PorcentajeIEPS - - Dim DrSubProyecto = GlobalDTSubProyectos(-1, TmpDT.FiltroPrimeroValor("CveSubProyecto", "", "ImporteTotal DESC").ToEntero, UsuarioActual.CveEmpresa, -1).FiltroPrimero("") - If DrSubProyecto Is Nothing Then - Alert("Ocurrió un error al cargar la información de centro de costos. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError) - Exit Sub - End If - - - DtImpuestos = query.QueryToDataTable(False) - - LimpiaDocumentoNC() - - Dim CveSubProyecto = DrSubProyecto("CveSubProyecto").ToString.ToEntero - Dim SubProyecto = DrSubProyecto("SubProyecto").ToString - Dim CveProyecto = DrSubProyecto("CveProyecto").ToString.ToEntero - Dim Proyecto = DrSubProyecto("Proyecto").ToString - - For Each Dr As DataRow In DtImpuestos.Rows - AgregaTempDT(DrPS("CvePS").ToString.ToEntero, DrPS("PS").ToString, DrPS("Codigo").ToString, DrPS("PSCodigo").ToString, DrPS("CveTipoPS").ToString.ToEntero, DrPS("Inv_CveMetodoInventario").ToString.ToEntero, - DrPS("CveUM").ToString.ToEntero, DrPS("UnidadMedida").ToString, DrPS("CveClasificacion").ToString.ToEntero, DrPS("Clasificacion").ToString, CveProyecto, Proyecto, CveSubProyecto, SubProyecto, - TxtNCObservaciones.Text.Trim, 1, Dr("ImportePU").ToString.ToDecimal, Dr("PorcentajeIVA").ToString.ToDecimal, Dr("ImporteIVA").ToString.ToDecimal, Dr("PorcentajeRetIVA").ToString.ToDecimal, Dr("ImporteRetIVA").ToString.ToDecimal, - Dr("PorcentajeRetISR").ToString.ToDecimal, Dr("ImporteRetISR").ToString.ToDecimal, Dr("PorcentajeIEPS").ToString.ToDecimal, Dr("ImporteIEPS").ToString.ToDecimal, -1, 0.0, Dr("ImporteTotal").ToString.ToDecimal, "", "", -1, -1, - DrPS("SATClavePS").ToString, DrPS("SATClaveUnidadMedida").ToString, -1, -1, -1, -1, -1, -1) - Next - - TrTipoRelacion.Visible = True - DdlTiposRelacion.SelectedValueExist("1") - - GvPS.DataSource = TmpDT - GvPS.DataBind() - - CalculaTotalesVenta(True) - - - 'condicióon, en la que se verifica que el importe total de aplicación de la nota de crédito sea igual al del total de la nota de crédito, ej. saldo de la factura 1000.01 y la nota de crédito se generó po 1000.00 - If Not AplicaNCMasiva Then - Dim TT As Decimal = TxtNCImporte.Text.ToDecimal - If TT > TxtTotal.Text.ToDecimal Then TT = TxtTotal.Text.ToDecimal - CargaNCDT(CveVenta, TT) - End If - - UpPS.Update() - - LBNotaCredito.Visible = False - RegistraScript("$('#ModalAplicarNC').modal('hide');", "EscondeModalNC") - AplicaNC = True - - CambiaTipoDocto() - - End Sub - - Private Function CargaDtImpuestosNC(CveVentaNC As Integer, Importe As Decimal) As DataTable - Dim Total As Decimal = 0, SubTotal As Decimal = 0, Saldo As Decimal = 0 - - Dim ObjVentas As New ClsVentas - - If ObjVentas.GetVentaDetalle(CveVentaNC) Then - TmpDT = ObjVentas.DtResultados - TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) - TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) - End If - - If AplicaNCMasiva Then - If ObjVentas.GetVenta(CveVentaNC, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - Total = ObjVentas.DtResultados()(0)("Total").ToString.ToDecimal - SubTotal = ObjVentas.DtResultados()(0)("SubTotal").ToString.ToDecimal - End If - End If - Else - Total = TxtTotal.Text.ToDecimal - SubTotal = TxtSubTotal.Text.ToDecimal - - - End If - ObjVentas.Dispose() - - Dim DtImpuestosLocal = TmpDT.FiltraParametros("", "", {"PorcentajeIVA", "PorcentajeRetIVA", "PorcentajeRetISR", "PorcentajeIEPS", "CveSubProyecto"}).Copy - DtImpuestosLocal.Columns.Add("ImportePU", GetType(Double)) - DtImpuestosLocal.Columns.Add("ImporteTotal", GetType(Double)) - DtImpuestosLocal.Columns.Add("ImporteIVA", GetType(Double)) - DtImpuestosLocal.Columns.Add("ImporteRetIVA", GetType(Double)) - DtImpuestosLocal.Columns.Add("ImporteRetISR", GetType(Double)) - DtImpuestosLocal.Columns.Add("ImporteIEPS", GetType(Double)) - - Dim ImporteReferencia As Decimal = If(DdlNCNivelImporte.SelectedValue.ToEntero = 1, Total, SubTotal) - Dim Porcentaje As Decimal = ((Importe * 100) / ImporteReferencia) / 100 - - For Each Dr As DataRow In DtImpuestosLocal.Rows - Dr("ImporteTotal") = Math.Round(Porcentaje * (TmpDT.SUM("TotalImporte", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ") - TmpDT.SUM("Descuento", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ")), 2) - ' COMENTANDO POR JESUS MURUA ALIAS EL CHOLO, LO HIZO EL RAUL ARRIBA ALV ! 28/02/2018 - 'Dr("ImporteTotal") = Porcentaje * TmpDT.SUM("TotalImporte", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ") - Dr("ImporteIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIVA", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' "), 2) - Dr("ImporteRetIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetIVA", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' "), 2) - Dr("ImporteRetISR") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetISR", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}'"), 2) - Dr("ImporteIEPS") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIEPS", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}'"), 2) - Dr("ImportePU") = Dr("ImporteTotal").ToString.ToDecimal '(Dr("ImporteTotal").ToString.ToDecimal - Dr("ImporteIVA").ToString.ToDecimal - Dr("ImporteRetIVA").ToString.ToDecimal - Dr("ImporteRetISR").ToString.ToDecimal - Dr("ImporteIEPS").ToString.ToDecimal) - Next - 'codigo para ajuste de centavo, si el importe total no cuadra con los totales - Dim difTmp As Decimal = Importe - (DtImpuestosLocal.SUMD("ImporteTotal") + DtImpuestosLocal.SUMD("ImporteIVA") + DtImpuestosLocal.SUMD("ImporteIEPS") - DtImpuestosLocal.SUMD("ImporteRetIVA") - DtImpuestosLocal.SUMD("ImporteRetISR")) - If Math.Abs(difTmp) >= 0.01 Then - 'asusto la diferencia en el último concepto - DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal") = DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal").ToString.ToDecimal + difTmp - End If - - 'CARGA FACTURA A LA CUAL SE APLICA LA NC - 'CargaNCDT(CveVentaNC, Importe.ToDecimal) - Return DtImpuestosLocal - End Function - - Private Sub AgregaTempDT(CvePS As Integer, PS As String, Codigo As String, CodigoPS As String, CveTipoPS As Integer, CveTipoInvPS As Integer, CveUM As Integer, UM As String, - CveClasificacion As Integer, Clasificacion As String, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, - Obs As String, Cantidad As Double, PU As Double, PorcentajeIVA As Double, ImporteIVA As Double, PorcentajeRetIVA As Double, ImporteRetIVA As Double, - PorcentajeRetISR As Double, ImporteRetISR As Double, PorcentajeIEPS As Double, ImporteIEPS As Double, TipoDescuento As Integer, Descuento As Double, - Total As Double, SerieLote As String, TiempoEntrega As String, CvePresupuestoIngreso As Integer, EntregaDirecta As Integer, SATClaveProdServ As String, - SATClaveUM As String, CveContratoDetalle As Integer, CveVentaDetalle As Integer, CveMovimientoDetallePedido As Integer, CveOrdenCompraDetalle As Integer, - CveVentaDetalleRemision As Integer, CveVentaDetalleCotizacion As Integer) - - Dim Row As DataRow = Nothing - Row = TmpDT.NewRow() - - Row("Consec") = TmpDT.Rows.Count + 1 - Row("Orden") = TmpDT.Rows.Count + 1 - - Row("CvePS") = CvePS - Row("PS") = PS - Row("Codigo") = Codigo - Row("CodigoPS") = CodigoPS - Row("CveTipoPS") = CveTipoPS - Row("CveTipoInvPS") = CveTipoInvPS - - Row("CveUM") = CveUM - Row("UM") = UM - - Row("CveClasificacion") = CveClasificacion - Row("Clasificacion") = Clasificacion - Row("CveProyecto") = CveProyecto - Row("Proyecto") = Proyecto - Row("CveSubProyecto") = CveSubProyecto - Row("SubProyecto") = SubProyecto - - Row("Obs") = Obs - Row("Cantidad") = Cantidad - Row("PU") = Math.Round(PU, 6) - Row("PorcentajeIVA") = PorcentajeIVA - Row("IVA") = PorcentajeIVA - Row("ImporteIVA") = Math.Round(ImporteIVA, NumeroDecimales) - Row("PorcentajeRetIVA") = PorcentajeRetIVA - Row("ImporteRetIVA") = Math.Round(ImporteRetIVA, NumeroDecimales) - Row("PorcentajeRetISR") = PorcentajeRetISR - Row("ImporteRetISR") = Math.Round(ImporteRetISR, NumeroDecimales) - Row("PorcentajeIEPS") = PorcentajeIEPS - Row("ImporteIEPS") = Math.Round(ImporteIEPS, NumeroDecimales) - Row("IEPS") = Math.Round(ImporteIEPS, NumeroDecimales) - Row("TipoDescuento") = TipoDescuento - Row("Descuento") = Math.Round(Descuento, NumeroDecimales) - Row("Total") = Math.Round(Total, NumeroDecimales) - Row("TotalImporte") = Math.Round(Total, NumeroDecimales) - - - Row("SerieLote") = SerieLote - Row("TiempoEntrega") = TiempoEntrega - Row("CvePresupuestoIngreso") = CvePresupuestoIngreso - Row("EntregaDirecta") = EntregaDirecta - Row("SATClaveProdServ") = SATClaveProdServ - Row("SATClaveUM") = SATClaveUM - - 'Contratos - Row("CveContratoDetalle") = CveContratoDetalle - Row("CveVentaDetalle") = CveVentaDetalle - Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido - Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle - Row("CveVentaDetalleRemision") = CveVentaDetalleRemision - Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion - - TmpDT.Rows.Add(Row) - End Sub - - Private Sub LimpiaDocumentoNC() - - EsCreaApartirDe = True - DivEstatusFac.Visible = False - TabAlmacen.Visible = False - - 'LIMPIA ACCIONES - HLOrdendeCompra.Visible = False - LkDevolucion.Visible = False - LBAplicaDevolucion.Visible = False - 'LkNotaCredito.Visible = False - LkEliminarFactura.Visible = False - ImgDownCancelacion.Visible = False - LkRefacturacion.Visible = False - HLOrdenServicio.Visible = False - LkCotizacionAutorizar.Visible = False - LnkFacturarRemision.Visible = False - LnkRemisiones.Visible = False - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - LnkOCs.Visible = False - LbCancelarDocumento.Visible = False - LBCancelarPedido.Visible = False - LiDevolucionAlmacen.Visible = False - HLPagar.Visible = False - HlAgregarExcel.Visible = False - HplDownXML.Visible = False - HplDownPDF.Visible = False - HLSaldarVenta.Visible = False - LBNotaCredito.Visible = False - LiComplementoPago.Visible = False - HlCuentaTerminal.Visible = False - LiLnkGuias.Visible = False - LiDocumentoCliente.Visible = False - - 'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION - GvPS.Columns(6).Visible = False - ThCantidadFacturadaRem.Visible = False - ThCantidadFacturadaRem2.Visible = False - GvPS.Columns(7).Visible = False - ThCantidadFacturada.Visible = False - ThCantidadFacturada2.Visible = False - - 'LIMPIA DETALLES - TmpDT.Clear() - GvPS.DataSource = Nothing - GvPS.DataBind() - - LblFolioFiscal.Text = "" - TxtFecha.Text = Now.ToShortDateString - - 'DESACTIVA/ACTIVA BOTONES - TrVistaPrevia.Visible = True - BtnEmitir.Visible = False - BtnCrearApartirDe.Visible = False - BtnGenerarRemision.Visible = False - BtnPermisoEditarCotizacion.Visible = False - BtnEditarCotizacion.Visible = False - BtnGenerarOS.Visible = False - - 'ACTIVA CONDICIONES DE PAGO - DdlUsoCFDI.Enabled = True - DdlUsoCFDI.SelectedValueExist("2") - DdlMetodoPago33.Enabled = True - DdlMetodoPago33.SelectedValueExist("1") ' PUE - CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) - DdlFormaPago33.Enabled = True - DdlFormaPago33.SelectedValueExist("11") ' condonación por default - - UpEstatus.Update() - UpnTools.Update() - UpCliente.Update() - UpParametros.Update() - UpPS.Update() - UpFacturar.Update() - UPObservaciones.Update() - UPPDescuento.Update() - UPCondicionesPago.Update() - UpDetalle.Update() - - - End Sub - - Private Sub InicializaDTVentasNC() - DtVentasNC = New DataTable - DtVentasNC.Columns.Add("CveVenta", GetType(Integer)) - DtVentasNC.Columns.Add("Importe", GetType(Decimal)) - DtVentasNC.Columns.Add("FolioFiscal", GetType(String)) - DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TC", .DataType = GetType(Decimal), .DefaultValue = 1}) - DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TCCambioValuacion", .DataType = GetType(Decimal), .DefaultValue = 1}) - DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "CveEstatusFactura", .DataType = GetType(Integer), .DefaultValue = -1}) - End Sub - - Private Sub CargaNCDT(pCveVenta As Integer, Importe As Decimal, Optional FolioFiscal As String = "", Optional NuevaFactura As Integer = -1, Optional ByRef ObjVentas As ClsVentas = Nothing, Optional TC As Decimal = 1) - If (pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs")) OrElse (pCveVenta > 0 AndAlso NuevaFactura = 1) Then - Dim CveEstatusFacturaNC As Integer = -1 - Dim TCCambioValuacion As Decimal = 1 - If FolioFiscal = "" Then - Dim ObjVentasAplicar As ClsVentas - If ObjVentas IsNot Nothing Then - ObjVentasAplicar = ObjVentas - Else - ObjVentasAplicar = New ClsVentas - End If - If ObjVentasAplicar.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentasAplicar.DtResultados.Rows.Count > 0 Then - FolioFiscal = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("FolioFiscal").ToString() - TC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambio").ToString.ToDecimal() - TCCambioValuacion = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambioValuacion").ToString.ToDecimal() - CveEstatusFacturaNC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("CveEstatusFactura").ToString.ToEntero() - End If - - If ObjVentas Is Nothing Then - ObjVentasAplicar.Dispose() - End If - - End If - - Dim Dr = DtVentasNC.NewRow - - Dr("CveVenta") = pCveVenta - Dr("Importe") = Importe - Dr("FolioFiscal") = FolioFiscal - Dr("TC") = TC - Dr("TCCambioValuacion") = TCCambioValuacion - Dr("CveEstatusFactura") = CveEstatusFacturaNC - - DtVentasNC.Rows.Add(Dr) - End If + Protected Sub LnkDocCliente_Click(sender As Object, e As EventArgs) + RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });") End Sub -#End Region + Private Sub CargaDocumentacionCliente() + LiDocumentoCliente.Visible = False + Dim objRH As New ClsEdocumentacion + + Dim TempCliente As Integer = If(CveVenta <= 0, CveCliente, -1) + Dim TipoDocumento As Integer = If(CveVenta <= 0, 14, -1) + + If objRH.DocumentacionElectronicaGet(-1, TempCliente, -1, UsuarioActual.CveEmpresa, TipoDocumento, CveVenta) Then + DtDocumentacionCliente = objRH.DtResultados.FiltraParametros("CveDocumentacionElectronica > 0") + DtDocumentacionCliente.Columns.Add("Accion", Type.GetType("System.String")) + DtDocumentacionCliente.Columns.Add("RutaArchivo", Type.GetType("System.String")) + DtDocumentacionCliente.Columns.Add("UpArchivo", Type.GetType("System.String")) + DtDocumentacionCliente.AcceptChanges() + GvDocumentosCliente.DataSource = DtDocumentacionCliente + LiDocumentoCliente.Visible = True + Else + DtDocumentacionCliente = Nothing + GvDocumentosCliente.DataSource = Nothing + End If + + objRH.Dispose() + GvDocumentosCliente.DataBind() + UpDocsCliente.Update() -#Region " APLICA DEVOLUCION " - Private Sub InicializaAplicaDevolucion() - If Not UsuarioActual.CveUsuario = 100 Then - If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then - Exit Sub - End If - End If - - 'sino tiene el permiso no puede generar Devolucion - If Not UsuarioActual.TienePermisoProceso(264) Then - Exit Sub - End If - - LkDevolucion.Visible = False - LBAplicaDevolucion.Visible = True - Dim SeEsconde As Boolean = False - Dim ObjVenta As New ClsVentas - If ObjVenta.GetVentaDetalle(CveVenta) Then - If Not ObjVenta.DtResultados.SUM("CantSur").ToString.ToDecimal > 0 Then SeEsconde = True - GvAplicaDevolucion.DataSource = ObjVenta.DtResultados.FiltraParametros("CantRes > 0") - End If - ObjVenta.Dispose() - - 'activo el permiso para registrar el importe diferente a la devolución - GvAplicaDevolucion.Columns(9).Visible = UsuarioActual.TienePermisoProceso(253) - - 'MODALIDAD CENTRO COSTOS - If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then - GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal" - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then - GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto" - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then - GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal/Proyecto" - ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then - GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto/Sucursal" - End If - - If SeEsconde Then GvAplicaDevolucion.Columns(1).Visible = False : GvAplicaDevolucion.Columns(2).Visible = False : GvAplicaDevolucion.Columns(3).Visible = False - - GvAplicaDevolucion.DataBind() - - UpDevolucion.Update() - - End Sub - Protected Sub BtnAplicaDevolucion_Click(sender As Object, e As EventArgs) - - 'VALIDACIONES - Dim Selecciono As Boolean = False - For Each Gv As GridViewRow In GvAplicaDevolucion.Rows - If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDouble > 0 Then - Selecciono = True - Exit For - End If - Next - - If Not Selecciono Then - Alert("Tiene que seleccionar al menos un concepto y este dege tener una cantidad mayor a 0. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - AplicaDevolucion = True - SaldoVentaDevolucion = HplSaldoAuxiliar.Text.ToDecimal - CveVentaDevolucion = CveVenta - DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) - DdlTipoComprobante.SelectedValue = "Dev" - - Dim AplicaPUEditado As Boolean = UsuarioActual.TienePermisoProceso(253) - - TmpDT.Clear() - For Each Gv As GridViewRow In GvAplicaDevolucion.Rows - If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal > 0 Then - Dim Cantidad As Decimal = Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal - Dim Descuento As Decimal = Cantidad * Gv.DataKey("Descuento").ToString.ToDecimal / Gv.DataKey("Cantidad").ToString.ToDecimal - Dim PU As Decimal = If(AplicaPUEditado, Gv.FCTextBox("TxtPrecioEditado").Text.ToDecimal, Gv.DataKey("PU").ToDecimal) - Dim Total As Decimal = (Cantidad * PU) - Dim TotalImpuestos As Decimal = (Cantidad * PU) - Descuento - Dim ImporteIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIVA").ToString.ToDecimal - Dim ImporteRetIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetIVA").ToString.ToDecimal - Dim ImporteRetISR As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetISR").ToString.ToDecimal - Dim ImporteIEPS As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIEPS").ToString.ToDecimal - - AgregaTempDT(Gv.DataKey("CvePS").ToString.ToEntero, Gv.DataKey("PS").ToString, Gv.DataKey("Codigo").ToString, Gv.DataKey("CodigoPS").ToString, - Gv.DataKey("CveTipoPS").ToString.ToEntero, Gv.DataKey("CveTipoInvPS").ToString.ToEntero, - Gv.DataKey("CveUM").ToString.ToEntero, Gv.DataKey("UM").ToString, Gv.DataKey("CveClasificacion").ToString.ToEntero, - Gv.DataKey("Clasificacion").ToString, Gv.DataKey("CveProyecto").ToString.ToEntero, Gv.DataKey("Proyecto").ToString, - Gv.DataKey("CveSubProyecto").ToString.ToEntero, Gv.DataKey("SubProyecto").ToString, - Gv.DataKey("Obs").ToString, Cantidad, PU, Gv.DataKey("PorcentajeIVA").ToString.ToDecimal, ImporteIVA, - Gv.DataKey("PorcentajeRetIVA").ToString.ToDecimal, ImporteRetIVA, - Gv.DataKey("PorcentajeRetISR").ToString.ToDecimal, ImporteRetISR, Gv.DataKey("PorcentajeIEPS").ToString.ToDecimal, - ImporteIEPS, -1, Descuento, Total, "", "", -1, -1, - Gv.DataKey("SATClaveProdServ").ToString, Gv.DataKey("SATClaveUM").ToString, -1, Gv.DataKey("CveVentaDetalle").ToString.ToEntero, -1, -1, -1, -1) - End If - Next - - LimpiaDocumentoDEV() - - CambiaTipoDocto() - CargaNC(CveVenta) - CalculaTotalesVenta() - - RegistraScript("$('#DivAplicaDevolucion').modal('hide')") - - End Sub - Protected Sub GvAplicaDevolucion_RowDataBound(sender As Object, e As GridViewRowEventArgs) - If e.Row.RowType = DataControlRowType.DataRow Then - e.Row.FCTextBox("TxtCantidadAplicaDevolucion").Attributes.Add("onkeyup", $"LimitaCantidadAplicaDev({e.Row.DBCampo("CantRes").ToDecimal}, this);") - If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Or UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then - e.Row.FCLabel("LblProyecto").Text = e.Row.FCLabel("LblSubProyecto").Text - e.Row.FCLabel("LblProyecto").Style.Clear() - e.Row.FCLabel("LblSubProyecto").Text = "" - End If - End If - End Sub - Private Sub LimpiaDocumentoDEV() - - 'REINICIALIZA PORLET CLIENTES - ChkEnviarFactura.Enabled = True - 'ACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto") - TxtCodigo.ReadOnly = False - - - 'REINICIALIZA PORLET DATOS DE EMIISION - trNCFactura.Visible = True - DdlSubProyectoDatos.Enabled = True - TrFolioFiscal.Visible = False - TxtFecha.Text = Now.ToShortDateString() - TipoCambioFactura = TxtTipoCambio.Text.ToDecimal - TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString - DivEstatusFac.Visible = False - - 'REINICIALIZA TABS - TabAlmacen.Enabled = False - TabE.Enabled = False - - 'REINICIALIZA GENERALES PS - LbAgregar.Visible = False - GvPS.Columns(17).Visible = False - GvPS.Columns(18).Visible = False - GvPS.Columns(19).Visible = False - GvPS.Columns(20).Visible = False - DivRemisionesFacturadas.Visible = False - DivAnticiposVinculados.Visible = False - - 'REINICIALIZA TOTALES - TrConversionDolares.Visible = False - - 'ACTIVA CONDICIONES DE PAGO - DdlUsoCFDI.Enabled = True - DdlUsoCFDI.SelectedValueExist("2") - DdlMetodoPago33.Enabled = True - DdlMetodoPago33.SelectedValueExist("1") - CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) - DdlFormaPago33.Enabled = True - DdlFormaPago33.SelectedValueExist("11") - - 'REINICIALIZA OBSERVACIONES - TxtObsFact.Enabled = True - TxtOrdenCompra.Enabled = True - TxtPedidoContrato.Enabled = True - TxtObsAlmacen.Enabled = True - - 'DESACTIVA/ACTIVA BOTONES - BtnCrearApartirDe.Visible = False - BtnEmitirImprimir.Visible = True - BtnVistaPrevia.Visible = True - BtnEmitir.Visible = False - - 'REINICIALIZA ACCIONES - LkDevolucion.Visible = False - 'LkNotaCredito.Visible = False - LkEliminarFactura.Visible = False - ImgDownCancelacion.Visible = False - LkRefacturacion.Visible = False - HLOrdenServicio.Visible = False - LkCotizacionAutorizar.Visible = False - LnkFacturarRemision.Visible = False - LnkRemisiones.Visible = False - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - LnkOCs.Visible = False - LbCancelarDocumento.Visible = False - LBCancelarPedido.Visible = False - LiDevolucionAlmacen.Visible = False - HLPagar.Visible = False - HlAgregarExcel.Visible = False - HplDownXML.Visible = False - HplDownPDF.Visible = False - HLSaldarVenta.Visible = False - LBNotaCredito.Visible = False - LiComplementoPago.Visible = False - HlCuentaTerminal.Visible = False - LiLnkGuias.Visible = False - LiDocumentoCliente.Visible = False - LBAplicaDevolucion.Visible = False - HplFolioFiscalModal.Visible = False - - 'Limpia Anticipos Seleccionados - For Each row2 As GridViewRow In GVAnticipos.Rows - If row2.RowType = DataControlRowType.DataRow Then - row2.FCCheckBox("Chk" & row2.RowIndex).Checked = False - End If - Next - - UpAnticipos.Update() - UpParametros.Update() - UpPS.Update() - UpEstatus.Update() - UpCliente.Update() - UpRemisiones.Update() - Updatetabs.Update() - UpFacturar.Update() - UPCondicionesPago.Update() - UpnTools.Update() - UPObservaciones.Update() - UpAntNC.Update() End Sub -#End Region -#Region "COMERCIO EXTERIOR" + Protected Sub LnkUploadDocumentacionCliente_Click(sender As Object, e As EventArgs) + + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + IndexDocumentoCliente = GvRow.RowIndex + + Dim Documentacion As String = GvRow.DataKey("Documentacion").ToString + AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString + + LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion + BtnModalClienteDocumentoCancelar.Visible = True + UpModalTitleUploadDocumentoCliente.Update() + UpModalButtonUploadDocumentoCliente.Update() + RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});") + + + End Sub + + Protected Sub BtnModalClienteDocumentoUpload_Click(sender As Object, e As EventArgs) Handles BtnModalClienteDocumentoUpload.Click + + If Not TxtFileCliente.getfiles().Archivos.Count > 0 Then + Alert("Tiene que cargar un archivo", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + Dim FileExtension As String = "-1" + Dim Filesgral As List(Of Archivo) = TxtFileCliente.getfiles().Archivos + Dim Filename As String = "" + + For Each fileItem As Archivo In Filesgral + Try + + FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "") + Dim tempArray() As String + tempArray = fileItem.filename.ToString().Split("-".ToCharArray()) + If RequiereOC And Not BtnModalClienteDocumentoCancelar.Visible Then + Dim Count = 0 + For Each GvRow As GridViewRow In GvDocumentosCliente.Rows + If GvRow.DataKey("Orden").ToEntero = 1 Then + IndexDocumentoCliente = Count + CargaDocumentoOC = True + Exit For + End If + Count = +1 + Next + End If + DtDocumentacionCliente(IndexDocumentoCliente)("RutaArchivo") = fileItem.FileUrl + DtDocumentacionCliente(IndexDocumentoCliente)("UpArchivo") = "1" + + TxtFileCliente.Text = "" + UpModalUploadClienteDocumento.Update() + Alert("Documento cargado", TipoMensaje.MsgInformacion) + Catch ex As Exception + OnError("Error al cargar archivo", ex) + End Try + + Next + + GvDocumentosCliente.DataSource = DtDocumentacionCliente + GvDocumentosCliente.DataBind() + + DtDocumentacionCliente.AcceptChanges() + UpDocsCliente.Update() + RegistraScript("$('#DivDocsClienteUpload').modal('hide')", "hidemodal3") + End Sub + + Private Sub GvDocumentosCliente_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDocumentosCliente.RowDataBound + + If e.Row.RowType = DataControlRowType.DataRow Then + + Dim ArchivoRuta As String = e.Row.DataKey("RutaArchivo") + Dim Adjunto As String = e.Row.DBCampo("Adjunto").ToString + Dim ImgDownLoad As Literal = e.Row.FCLiteral("ImgDownLoad") + Dim Chk As CheckBox = e.Row.FCCheckBox("chkEstatus") + Chk.Checked = If(e.Row.DataKey("Estatus").ToString = "1", True, False) + + If ArchivoRuta.Trim.Length > 0 Then + + Dim fi As New FileInfo(ArchivoRuta) + Dim linkDescarga As String = "" + If fi.Exists Then + linkDescarga = $"/Temp/{fi.Name}" + ImgDownLoad.Text = String.Format(" ", linkDescarga) + ImgDownLoad.Visible = True + End If + + Else + + If Adjunto.Trim.Length > 0 Then + ArchivoRuta = UsuarioActual.Empresa.Ruta & "Documentacion\Ventas\" & Adjunto + Dim fi As New FileInfo(ArchivoRuta) + Dim linkDescarga As String = "" + If fi.Exists() Then + linkDescarga = $"/Empresas/{UsuarioActual.CveEmpresa}/Documentacion/ventas/{fi.Name}" + ImgDownLoad.Text = String.Format(" ", linkDescarga) + ImgDownLoad.Visible = True + End If + + End If + End If + 'Else + + ' If ArchivoRuta.Trim.Length > 0 Then + + ' Dim fi As New FileInfo(ArchivoRuta) + ' Dim linkDescarga As String = "" + ' If fi.Exists Then + ' linkDescarga = $"/Temp/{fi.Name}" + ' ImgDownLoad.Visible = True + ' ImgDownLoad.Text = String.Format(" ", linkDescarga) + ' Else + ' ImgDownLoad.Visible = False + ' End If + + ' Else + ' ImgDownLoad.Visible = False + ' End If + + 'End If + End If + + End Sub + + Private Sub GuardaVentaDocumentosCliente(tCveVenta As Integer, ByRef objDocumentacion As ClsEdocumentacion) + + If tCveVenta > 0 Then + + For Each DRow As DataRow In DtDocumentacionCliente.FiltraParametros("RutaArchivo <> '' ").Rows + Dim CveDocumentacion As Integer = DRow("CveDocumentacion").ToString.ToEntero + Dim Estatus As Integer = DRow("Estatus").ToString.ToEntero + Dim Adjunto As String = DRow("Adjunto").ToString + Dim NombreArchivo As String = "" + Dim ArchivoRuta As String = DRow("RutaArchivo").ToString + If ArchivoRuta.Length > 0 Then Adjunto = ArchivoRuta + Dim Extension As String = Path.GetExtension(Adjunto) + + Dim CveDocumentacionElectronica As Integer = objDocumentacion.DocumentacionElectronicaAdd(CveDocumentacion, -1, -1, -1, 1, DRow("Observacion").ToString, Extension, UsuarioActual.CveUsuario, New Date(1900, 1, 1), CveVenta:=tCveVenta) + + If CveDocumentacionElectronica <= 0 Then ErrorList.Add("No se pudo registrar el documento ") + NombreArchivo = $"{CveDocumentacionElectronica}{Extension}" + + If ArchivoRuta.Length > 0 And NombreArchivo.Length > 0 Then + If Not Directory.Exists($"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\") Then + Directory.CreateDirectory($"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\") + End If + + Dim ArchivoExistenteRuta As String = $"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\{NombreArchivo}" + + If File.Exists(ArchivoExistenteRuta) Then File.Delete(ArchivoExistenteRuta) + + Try + + File.Move(ArchivoRuta, ArchivoExistenteRuta) + Catch ex As Exception + ErrorList.Add("No se pudo guardar el documento de la venta") + Exit For + End Try + + End If + Next + + End If + + End Sub + + Protected Sub chkEstatus_CheckedChanged(sender As Object, e As EventArgs) + + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, CheckBox).NamingContainer, GridViewRow) + Dim chk As CheckBox = GvRow.FCCheckBox("chkEstatus") + + + IndexDocumentoCliente = GvRow.RowIndex + + + If chk.Checked Then + DtDocumentacionCliente(IndexDocumentoCliente)("Estatus") = True + Else + DtDocumentacionCliente(IndexDocumentoCliente)("Estatus") = False + End If + + DtDocumentacionCliente.AcceptChanges() + + + End Sub + + Protected Sub CargarArchivosOC(sender As Object, e As EventArgs) + Dim Documentacion As String = "" + RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });", "ModalArchivos") + Dim Count = 0 + For Each GvRow As GridViewRow In GvDocumentosCliente.Rows + If GvRow.DataKey("Orden").ToEntero = 1 Then + IndexDocumentoCliente = Count + Documentacion = GvRow.DataKey("Documentacion").ToString + AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString + Exit For + End If + Count = +1 + Next + LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion + BtnModalClienteDocumentoCancelar.Visible = False + UpModalTitleUploadDocumentoCliente.Update() + UpModalButtonUploadDocumentoCliente.Update() + RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});", "modalOC") + End Sub +#End Region + +#Region " SALDAR VENTA " + Protected Sub BtnSaldarVenta_Click(sender As Object, e As EventArgs) + SaldarVenta() + End Sub + Private Sub SaldarVenta() + 'Dim ObjVenta As New ClsVentas + + 'If ObjVenta.VentasSaldar(CveVenta, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 0, -1, -1, TxtFechaSaldarVenta.Text.ToDate) Then + ' Alert("Documento Saldado") + 'End If + + 'ObjVenta.Dispose() + + 'RegistraScript("$('#ModalSaldarVenta').modal('hide')", "ModalSaldarVentaHidde") + + Dim ObjConta As New ClsContabilidad + ObjConta.IniciaTransacSQL() + Dim CvePrePoliza As Integer = 0 + Dim MsgError As String = "" + + Dim ObjIE As New ClsBancos + Dim FechaUltimaFluctuacion As Date = MinFecha + Dim TipoCambioFluctuacion As Decimal = 1 + If ObjIE.GetFluctuacionesBitacora(UsuarioActual.CveEmpresa) Then + If ObjIE.DtResultados.Rows.Count > 0 Then + Dim tFecha As Date = TxtFechaSaldarVenta.Text.ToDate + Dim Fecha As String = String.Format("{0}/{1}/{2}", tFecha.Year, tFecha.Month, tFecha.Day) + Dim drr As DataRow = ObjIE.DtResultados.FiltroPrimero("Fecha < #" & Fecha & "#", "Fecha DESC") + + If drr IsNot Nothing Then + FechaUltimaFluctuacion = drr("Fecha").ToString.ToDate + TipoCambioFluctuacion = drr("TipoCambio").ToString.ToDecimal + End If + + End If + End If + + ObjIE.Dispose() + + + Dim IdCtaContable As Integer = IdCtaContClientes + Dim CveCuenta As Integer = 0 + Dim PorcentajePago As Decimal = SaldoVenta / TxtTotal.Text.ToDecimal + Dim Saldo As Decimal = SaldoVenta + Dim SubTotal As Decimal = PorcentajePago * TxtSubTotal.Text.ToDecimal + Dim IVA As Decimal = PorcentajePago * TxtIVA.Text.ToDecimal + Dim IEPS As Decimal = PorcentajePago * TxtIEPS.Text.ToDecimal + Dim TCVenta As Decimal = TxtTipoCambio.Text.ToDecimal + Dim FechaVenta As Date = TxtFecha.Text.ToDate + Dim FechaPago As Date = TxtFechaSaldarVenta.Text.ToDate + Dim tCveMoneda As Integer = DdlMoneda.SelectedValue.ToEntero + Dim TCPago As Decimal = GlobalTipoCambio(TxtFechaSaldarVenta.Text.ToDate).FormatoNumero(4).ToDecimal + Dim CveConceptoDeduccion As Integer = 211 + + + 'si la fecha del documento es anterior a su ultima fluctuación. toma el Tc de la fluctuacion + If tCveMoneda = 2 Then + If FechaVenta < FechaUltimaFluctuacion Then + TCVenta = TipoCambioFluctuacion + End If + End If + + + 'condicionante + Dim ClienteMovto As Boolean = True + Dim SubtotalMovto As Boolean = False + Dim CveConceptoCliente As Integer = 2 + Dim ImpuestosMovto As Boolean = False + Dim IdCuentaContableNoDeducible As Integer = 0 + Dim SerieFolio As String = LblSerie.Text & "-" & TxtFolio.Text + Dim ConceptoPartida As String = "saldado " & SerieFolio + ' Dim CveSubProyecto As Integer = gr.DataKey("CveSubProyecto").ToEntero + + If CveConceptoDeduccion = 255 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(266).ToEntero + If CveConceptoDeduccion = 211 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(559).ToEntero + If CveConceptoDeduccion = 263 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(537).ToEntero + If CveConceptoDeduccion = 252 Then IdCuentaContableNoDeducible = 0 + If CveConceptoDeduccion = 78 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.IdCuentaOtrosIngresos + + If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122) Then + ClienteMovto = False : Saldo = Saldo * -1 + ImpuestosMovto = True : IVA = IVA * -1 + CveConceptoCliente = 1 + 'falta cuenta incobrable + IdCuentaContableNoDeducible = 3114 + End If + + Dim UsaComplementaria As Boolean = False + + If UsuarioActual.CveEmpresa = 119 Then + UsaComplementaria = True + End If + + If MsgError = "" Then + CvePrePoliza = ObjConta.AddPrePolizas("Ventas/Saldarr", 47, SaldoVenta, SaldoVenta, tCveMoneda, TxtFechaSaldarVenta.Text.ToDate, ConceptoPartida, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + + If tCveMoneda = 2 Then + IdCtaContable = IdCtaContMonedaExtranjera + Else + IdCtaContable = IdCtaContClientes + End If + + If UsaComplementaria AndAlso tCveMoneda = 2 Then + 'normal + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, Saldo, SerieFolio, CveConceptoCliente, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContable, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, Saldo), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + 'complementaria + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, 0, SerieFolio, 207, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContComplementaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, (Saldo * TCVenta) - Saldo), ImporteME:=Saldo, CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + + Else + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, Saldo, SerieFolio, CveConceptoCliente, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContable, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, Saldo * TCVenta), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + + End If + + 'fluctuación. + If tCveMoneda = 2 Then + Dim ImporteFluctuacion As Decimal = 0 + ImporteFluctuacion = Saldo * (TCPago - TCVenta) + If TCPago > TCVenta Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Math.Abs(ImporteFluctuacion), SerieFolio, 64, ConceptoPartida, FechaPago, IdCtaContable:=UsuarioActual.Empresa.IdCuentaGananciaCambiaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=Math.Abs(ImporteFluctuacion), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + Else + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Math.Abs(ImporteFluctuacion), SerieFolio, 65, ConceptoPartida, FechaPago, IdCtaContable:=UsuarioActual.Empresa.IdCuentaPerdidaCambiaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=Math.Abs(ImporteFluctuacion), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + End If + + 'cuando hay pago en dólares, se ajusta el concepto de subtotal, + SubTotal = (Saldo * TCVenta) + ImporteFluctuacion - (IVA * TCVenta) - (IEPS * TCVenta) + + End If + + + ' iva + Dim PorcentajeImpuesto As Decimal = DdlIVA.SelectedValue.ToEntero + + Dim IdCtaIVATrasladado As Integer = 0 + Dim CveCuentaIVATrasladado As Integer = 0 + + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then + IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero + CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero + End If + + IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) + CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) + If IVA > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ImpuestosMovto, IVA, SerieFolio, 61, ConceptoPartida, FechaPago, IdCtaContable, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, IVA, IVA * TCVenta), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + + IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSTrasladado + CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSTrasladado + If IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ImpuestosMovto, IEPS, SerieFolio, 39, ConceptoPartida, FechaPago, IdCtaContable, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, IEPS, IEPS * TCVenta), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + + 'al gasto,Subtotal + If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, SubtotalMovto, SubTotal, SerieFolio, CveConceptoDeduccion, ConceptoPartida, FechaPago, IdCuentaContableNoDeducible, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=SubTotal, CveCuenta:=-1, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then + MsgError = "Ocurrio un error al saldar el movimiento" + End If + + If ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 5) Then + If ObjConta.ValorPolizaDescuadre > 0 Then + MsgError = ObjConta.MensajePolizaDescuadre + " " + ObjConta.ValorDiferencia + GuardaLogAD($"Ventas/ClientesAbonar | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas") + + End If + End If + End If + + + If MsgError = "" Then + 'ObjConta.RollBack() + ObjConta.Commit() + + RegistraScript("$('#ModalSaldarVenta').modal('hide')", "ModalSaldarVentaHidde") + Alert("Documento Saldado") + Else + ObjConta.RollBack() + Alert(MsgError, TipoMensaje.MsgError) + End If + + + ObjConta.Dispose() + + End Sub +#End Region + +#Region "PAQUETERIA GUIAS" + + Protected Sub LnkAgregarGuia_Click(sender As Object, e As EventArgs) + ''DivModalGuias + 'DdlPaqueteria.Items.Clear() + 'DdlPaqueteria.DataSource = GlobalDTPaqueterias + 'DdlPaqueteria.DataBind() + 'DdlPaqueteria.Items.Insert(0, New ListItem("Seleccione ", "-1")) + 'UpModalGuias.Update() + 'CargaGvPaqueteria() + + 'RegistraScript("$('#DivModalGuias').modal({ backdrop: 'static', keyboard: false });") + + '' 21/Marzo/2018 - Se agrego Link a Modulo Paqueterias Guias + RegistraScript(String.Format("AbrirVentana('/General/PopUpPaqueteriasGuias.aspx?CveVenta={0}',800,620);", CveVenta)) + + End Sub + Protected Sub BtnAgregarGuia_Click(sender As Object, e As EventArgs) + + Dim objInventario As New ClsInventarios + Dim CvePaqueteriaGuia As Integer + + If objInventario.AddPaqueteriaGuia(DdlPaqueteria.SelectedValue.ToEntero, -1, TxtPaqueteriaGuia.Text.Trim, TxtPaqueteriaNumcajas.Text.ToEntero, TxtPaqueteriaPeso.Text.ToDecimal, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, + TxtRastreo.Text.Trim, TxtDimensiones.Text.Trim, TxtFechaEst.Text.Trim, CveVenta:=CveVenta) Then + + CvePaqueteriaGuia = objInventario.DtResultados.Rows(0)(0).ToString.ToEntero + CargaGvPaqueteria() + LimpiacontrolesPaqueteria() + + 'Envia notificacion se agrego guia vacia eliminada + If TxtPaqueteriaGuia.Text.Trim.Length = 0 Then + EnviarCorreoNotificacionGuias(2, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CvePaqueteriaGuia:=CvePaqueteriaGuia) + End If + + End If + + objInventario.Dispose() + + End Sub + Protected Sub LnkRemovePaqueteriaGuia_Click(sender As Object, e As EventArgs) + + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + Dim CvePaqueteriaGuia As Integer = GvRow.DataKey("CvePaqueteriaGuia").ToString.ToEntero + Dim Guia As String = GvRow.DataKey("Guia").ToString + + Dim objInventario As New ClsInventarios + + If objInventario.RemovePaqueteriaGuia(CvePaqueteriaGuia, UsuarioActual.CveEmpresa) Then + CargaGvPaqueteria() + + If Guia.Trim.Length = 0 Then + 'Envia notificacion se elimino guia vacia eliminada + EnviarCorreoNotificacionGuias(3, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CvePaqueteriaGuia:=CvePaqueteriaGuia) + + End If + + End If + + objInventario.Dispose() + + End Sub + Private Sub CargaGvPaqueteria() + + Dim objInventario As New ClsInventarios + + If objInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + + GvPaqueriaGuias.DataSource = objInventario.DtResultados + + If objInventario.DtResultados.Rows.Count > 0 Then + BtnAgregarGuia.Attributes.Add("data-toggle", "confirmation") + BtnAgregarGuia.Attributes.Add("data-popout", "true") + BtnAgregarGuia.Attributes.Add("data-original-title", "¿Está seguro de registrar una nueva guia a la factura?") + BtnAgregarGuia.Attributes.Add("data-btn-ok-label", "si") + Else + BtnAgregarGuia.Attributes.Remove("data-toggle") + BtnAgregarGuia.Attributes.Remove("data-popout") + BtnAgregarGuia.Attributes.Remove("data-original-title") + BtnAgregarGuia.Attributes.Remove("data-btn-ok-label") + End If + + If objInventario.DtResultados.Rows.Count > 1 Then + EnviarCorreoNotificacionGuias(4, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CountPaqueteria:=objInventario.DtResultados.Rows.Count) + End If + Else + GvPaqueriaGuias.DataSource = Nothing + End If + + objInventario.Dispose() + GvPaqueriaGuias.DataBind() + UpModalGuias.Update() + + End Sub + Private Sub LimpiacontrolesPaqueteria() + + DdlPaqueteria.SelectedIndex = 0 + TxtPaqueteriaGuia.Text = "" + TxtPaqueteriaNumcajas.Text = "" + TxtPaqueteriaPeso.Text = "" + + TxtRastreo.Text = "" + TxtDimensiones.Text = "" + TxtFechaEst.Text = "" + + End Sub + Protected Sub LnkGuiaPaqueteriaGuia_Click(sender As Object, e As EventArgs) + + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + Dim CveMovimiento As Integer = -1 + Dim CvePaqueteriaGuia As Integer = GvRow.DataKey("CvePaqueteriaGuia").ToString.ToEntero + Dim NumCajas As String = GvRow.DataKey("NumCajas").ToString + Dim Guia As String = GvRow.DataKey("Guia").ToString + Dim Peso As String = GvRow.DataKey("Peso").ToString.ToDecimal.ToString("####.00") + Dim DTDatosClienteGuia As New DataTable + Dim DTMovimientosDetalle As New DataTable + Dim CvePaqueteria As Integer = GvRow.DataKey("CvePaqueteria").ToString.ToEntero + Dim RutaRdlc As String = Server.MapPath("~") & "\Empresas\Grales\Formatos\GuiasFormato" & CvePaqueteria & ".rdlc" + + Dim Rastreo As String = GvRow.DataKey("Rastreo") + Dim Dimensiones As String = GvRow.DataKey("Dimensiones") + Dim FechaEstimada As String = GvRow.DataKey("FechaEstimada") + Dim ValorStimado As Double = 0 + + If Not File.Exists(RutaRdlc) Then + RutaRdlc = Server.MapPath("~") & "\Empresas\Grales\Formatos\GuiasFormato0.rdlc" + End If + + RutaRdlc = RutaRdlc.Replace(Server.MapPath("~") & "\", "") + + Dim params As New List(Of ReportParameter) + Dim ObjInventario As New ClsInventarios + + If ObjInventario.GetPaqueteriaGuiasInfoFormato(CveMovimiento, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + DTDatosClienteGuia = ObjInventario.DtResultados + Else + ObjInventario.Dispose() + Exit Sub + End If + + If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then + + DTMovimientosDetalle = ObjInventario.DtResultados + DTMovimientosDetalle.Columns.Add("Peso") + DTMovimientosDetalle.Columns.Add("Dimensiones") + DTMovimientosDetalle.AcceptChanges() + + For Each Drow As DataRow In DTMovimientosDetalle.Rows + Drow("Peso") = Peso + Drow("Dimensiones") = Dimensiones + DTMovimientosDetalle.AcceptChanges() + Next + + ValorStimado = DTMovimientosDetalle.SUM("PU") + ObjInventario.Dispose() + Else + ObjInventario.Dispose() + Exit Sub + End If + + If DTDatosClienteGuia.Rows.Count > 0 Then + params.Add(New ReportParameter("NombreComercial", DTDatosClienteGuia.Rows(0)("NombreComercial").ToString)) + params.Add(New ReportParameter("Direccion", DTDatosClienteGuia.Rows(0)("Direccion").ToString)) + params.Add(New ReportParameter("Colonia", DTDatosClienteGuia.Rows(0)("Colonia").ToString)) + params.Add(New ReportParameter("NoExt", DTDatosClienteGuia.Rows(0)("NoExt").ToString)) + params.Add(New ReportParameter("NoInt", DTDatosClienteGuia.Rows(0)("NoInt").ToString)) + params.Add(New ReportParameter("Localidad", DTDatosClienteGuia.Rows(0)("Localidad").ToString)) + params.Add(New ReportParameter("Telefono", DTDatosClienteGuia.Rows(0)("Telefono").ToString)) + params.Add(New ReportParameter("RFCCliente", DTDatosClienteGuia.Rows(0)("RFC").ToString)) + params.Add(New ReportParameter("CiudadCliente", DTDatosClienteGuia.Rows(0)("Ciudad").ToString)) + Else + Exit Sub + End If + + Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) + Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) + + params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) + params.Add(New ReportParameter("EmpresaDireccion", UsuarioActual.Empresa.Direccion)) + params.Add(New ReportParameter("EmpresaTelefono", UsuarioActual.Empresa.Telefono)) + params.Add(New ReportParameter("EmpresaColonia", UsuarioActual.Empresa.Colonia)) + params.Add(New ReportParameter("EmpresaLocalidad", UsuarioActual.Empresa.Localidad)) + params.Add(New ReportParameter("RFCEmpresa", UsuarioActual.Empresa.RFC)) + params.Add(New ReportParameter("CiudadEmpresa", UsuarioActual.Empresa.Ciudad)) + + params.Add(New ReportParameter("EmpresaTelefono", UsuarioActual.Empresa.Telefono)) + params.Add(New ReportParameter("NumCajas", NumCajas)) + params.Add(New ReportParameter("Peso", Peso)) + params.Add(New ReportParameter("Guia", Guia)) + + params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) + params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) + + params.Add(New ReportParameter("Anio", Now.Year.ToString)) + params.Add(New ReportParameter("Mes", Now.Month.ToString("00"))) + params.Add(New ReportParameter("Dia", Now.Day.ToString("00"))) + + params.Add(New ReportParameter("Rastreo", Rastreo)) + params.Add(New ReportParameter("Dimensiones", Dimensiones)) + params.Add(New ReportParameter("FechaEstimada", FechaEstimada)) + + If Imagen.Exists Then + params.Add(New ReportParameter("LogoPath", logouri)) + Else + params.Add(New ReportParameter("LogoPath", "")) + End If + + ImprimirPDF(RutaRdlc, DTMovimientosDetalle, params, $"ReporteGuia_{Now.ToString("yyyyMMddhhmmss")}") + + End Sub + Private Sub GvPaqueriaGuias_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvPaqueriaGuias.RowDataBound + + If e.Row.RowType = DataControlRowType.DataRow Then + Dim Lnk As LinkButton = e.Row.FCLinkButton("LnkGuiaPaqueteriaGuia") + Dim Destinatario As String = e.Row.DataKey("Mail").ToString + + If Destinatario.Length = 0 Then + e.Row.FCLinkButton("LnkGuiaPaqueteriaMail").Visible = False + Else + e.Row.FCLinkButton("LnkGuiaPaqueteriaMail").Attributes.Add("title", "Enviar correo a: " & Destinatario) + End If + + ScriptManager.GetCurrent(Me).RegisterPostBackControl(Lnk) + End If + + End Sub + Private Sub GvPaqueteriaCreaEnlaces() + + For Each GvRow As GridViewRow In GvPaqueriaGuias.Rows + + If GvRow.RowType = DataControlRowType.DataRow Then + Dim Lnk As LinkButton = GvRow.FCLinkButton("LnkGuiaPaqueteriaGuia") + ScriptManager.GetCurrent(Me).RegisterPostBackControl(Lnk) + End If + + Next + End Sub + Protected Sub LnkGuiaPaqueteriaMail_Click(sender As Object, e As EventArgs) + + Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + + Dim SerieFolio As String = GvRow.DataKey("SerieFolio").ToString + Dim NombreComercial As String = GvRow.DataKey("NombreComercial").ToString + Dim Destinatario As String = GvRow.DataKey("Mail").ToString + Dim Paqueteria As String = GvRow.DataKey("Paqueteria").ToString + Dim Guia As String = GvRow.DataKey("Guia").ToString + Dim Rastreo As String = GvRow.DataKey("Rastreo").ToString + Dim CveVenta As Integer = GvRow.DataKey("CveVenta").ToEntero + + EnviarCorreoNotificacionGuias(1, SerieFolio, NombreComercial, Destinatario, Paqueteria, Guia, Rastreo, CveVenta, New DataTable) + + End Sub + Private Sub EnviarCorreoNotificacionGuias(Tipo As Integer, SerieFolio As String, NombreComercial As String, Destinatario As String, Paqueteria As String, Guia As String, Rastreo As String, CveVenta As Integer, tDtMovimientos As DataTable, Optional CountPaqueteria As Integer = Nothing, Optional CvePaqueteriaGuia As Integer = -1) + + Dim Correo As New ClsSisMail() + Dim Asunto As String = UsuarioActual.Empresa.NombreCorto & " Envio de pedido: " & SerieFolio + Dim Cuerpo As New StringBuilder + + + Select Case Tipo + Case 1 'Notificacion Normal + + ' Dim ObjCliente As New ClsClientes() + + + + 'Dim FolioOC As String = "" + 'Dim FolioPedido As String = "" + 'Dim CorreoDestino = "" + 'Dim CveVendedor As Integer = DdlVendedor.SelectedValue.ToEntero + 'Dim CorreoVendedor As String = "" + 'Dim CorreoVendedorUsuarioActual As String = "" + + + 'If CveVendedor > 0 Then + ' Dim DtTemp As New DataTable + ' DtTemp = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros($"CveVendedor={CveVendedor}") + + ' If DtTemp.Rows.Count > 0 Then + ' CorreoVendedor = DtTemp.Rows(0)("Correo").ToString + ' End If + + 'End If + + 'Try + ' If UsuarioActual.CveVendedor > 0 Then + ' Dim DtTemp As New DataTable + ' DtTemp = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros($"CveVendedor={ UsuarioActual.CveVendedor}") + + ' If DtTemp.Rows.Count > 0 Then + ' CorreoVendedorUsuarioActual = DtTemp.Rows(0)("Correo").ToString + ' End If + + ' End If + + 'Catch ex As Exception + + 'End Try + + + 'If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, -1, TipoCliente:=-1) Then + + ' If ObjCliente.CobranzaCorreo <> ObjCliente.Mail Then + ' CorreoDestino = $"{ObjCliente.CobranzaCorreo};{ObjCliente.Mail }" + ' Else + ' CorreoDestino = $"{ObjCliente.Mail}" + ' End If + + 'End If + 'ObjCliente.Dispose() + + + 'If CorreoVendedor.Trim.Length > 0 Then + ' CorreoDestino = $"{CorreoDestino};{CorreoVendedor}" + 'End If + + 'If CorreoVendedorUsuarioActual.Trim.Length > 0 Then + ' CorreoDestino = $"{CorreoDestino};{CorreoVendedorUsuarioActual}" + 'End If + + 'If CveOC > 0 Then + ' Dim ObjOC As New ClsOC + ' If ObjOC.GetOC(CveOC, UsuarioActual.CveEmpresa) Then + ' FolioOC = ObjOC.Folio.ToString + ' End If + ' ObjOC.Dispose() + 'End If + + + 'If CvePedido > 0 Then + ' Dim ObjVenta As New ClsVentas + ' If ObjVenta.GetVenta(CvePedido, UsuarioActual.CveEmpresa) Then + ' FolioPedido = ObjVenta.Folio.ToString + ' End If + ' ObjVenta.Dispose() + 'End If + + + Cuerpo.AppendLine($"Estimado {NombreComercial} le informamos que los productos de la factura {SerieFolio} han sido enviados mediante la paquetería {Paqueteria} con Guia {Guia} , Rastreo {Rastreo} .

    ") + + If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then + Cuerpo.AppendLine("") + Cuerpo.AppendLine("") + + For Each Drow As DataRow In tDtMovimientos.Rows + Cuerpo.AppendLine($"") + Next + Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") + End If + + Cuerpo.AppendLine("

    Dudas y aclaraciones con su coordinador empresarial.") + + + ' Destinatario = "sig.buzon@gmail.com" + + + If Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) Then + GuardarBitacora(CveVenta, "", "Notificación de envío de productos al cliente") + Alert("Correo envíado exitosamente a " & Destinatario) + Else + Alert("Ocurrió un error al envíar el correo a " & Destinatario) + End If + + Exit Select + Case 2 'Notificacion Guia vacia + + 'Cuerpo.AppendLine($"Se informa que en la venta {SerieFolio} se agrego la paqueteria {Paqueteria} con guia vacia por el usuario { UsuarioActual.Nombre }.

    ") + + 'If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then + ' Cuerpo.AppendLine("") + ' Cuerpo.AppendLine("") + + ' For Each Drow As DataRow In tDtMovimientos.Rows + ' Cuerpo.AppendLine($"") + ' Next + ' Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") + 'End If + 'Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) + + 'Exit Select + + Case 3 'Notificacion Gui Vacia Eliminada + 'Cuerpo.AppendLine($"Se informa que en la venta {SerieFolio} se elimino la paqueteria {Paqueteria} con guia vacia por el usuario { UsuarioActual.Nombre }.

    ") + + 'If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then + ' Cuerpo.AppendLine("") + ' Cuerpo.AppendLine("") + + ' For Each Drow As DataRow In tDtMovimientos.Rows + ' Cuerpo.AppendLine($"") + ' Next + ' Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") + ' Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) + 'End If + + Exit Select + Case 4 'mas de una guia + Cuerpo.AppendLine($"Se informa que en la venta {SerieFolio} cuenta con { CountPaqueteria } paqueterias, se agrego la paqueteria {Paqueteria}, usuario { UsuarioActual.Nombre }.

    ") + Destinatario = "" + If UsuarioActual.CveEmpresa.Contiene(72, 80) Then + Destinatario = "luzdelmarcoeto@compuproveedores.com;ramonmartinez@compuproveedores.com" + End If + 'correo a ramón y a luz + + If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then + Cuerpo.AppendLine("") + Cuerpo.AppendLine("") + + For Each Drow As DataRow In tDtMovimientos.Rows + Cuerpo.AppendLine($"") + Next + Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString.ToEntero }{Drow("PS").ToString}
    ") + End If + Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString) + Exit Select + + End Select + + + + + End Sub + Private Sub GuardarBitacora(CveVenta As Integer, RutaAdjunto As String, Obser As String) + Dim ObjEventos As New ClsOIEventos() + + Try + If ObjEventos.AddEventoBitacora(Obser, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + + End If + Catch ex As Exception + OnError("Se presento un Error al guardar la Bitacora", ex) + End Try + + ObjEventos.Dispose() + End Sub +#End Region + +#Region " APLICAR NOTA DE CREDITO " + Private Sub InicializaAplicarNC() + 'If Not UsuarioActual.CveUsuario = 100 Then + ' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then + ' Exit Sub + ' End If + 'End If + + If CveVenta <= 0 Or Not DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Or Not HplSaldoAuxiliar.Text.ToDouble > 0 Then + ''If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then LkNotaCredito.Visible = False + Exit Sub + End If + + 'sino tiene el permiso de peude generar NC + If Not UsuarioActual.TienePermisoProceso(175) Then + Exit Sub + End If + + + AplicaNCMasiva = False + AplicaNC = False + LBNotaCredito.Visible = True + 'LkNotaCredito.Visible = False + + TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNC();") + TxtNCImporte.Attributes.Add("onkeyup", "CalculaPorcentajeNC();") + + Dim PorcentajeMaximo = 0.0 + If TxtTotal.Text.ToDouble > 0 Then + PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.ToDouble + Else + RVNCPorcentaje.MinimumValue = "0" + RVTxtNCImporte.MinimumValue = "0" + End If + + TxtNCPorcentaje.Text = PorcentajeMaximo.FormatoNumero(4) + If PorcentajeMaximo < RVNCPorcentaje.MinimumValue.ToDouble Then + RVNCPorcentaje.MinimumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString + End If + RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString + + TxtNCImporte.Text = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero + If ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble < RVTxtNCImporte.MinimumValue.ToDouble Then + RVTxtNCImporte.MinimumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString + End If + RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString + + UpAplicarNC.Update() + End Sub + + Private Sub InicializaAplicarNCMasiva() + + 'If Not UsuarioActual.CveUsuario = 100 Then + ' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then + ' Exit Sub + ' End If + 'End If + + 'sino tiene el permiso de peude generar NC + If Not UsuarioActual.TienePermisoProceso(175) Then + Exit Sub + End If + + AplicaNCMasiva = True + LBNotaCredito.Visible = True + 'LkNotaCredito.Visible = False + DivGvCxC.Visible = True + CargaCxC() + TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNCMasivo();") + TxtNCImporte.Text = "0.00" + TxtNCImporte.Enabled = False + RVTxtNCImporte.Enabled = False + + UpAplicarNC.Update() + + End Sub + + Private Sub CargaCxC() + Dim ObjMovtos As New ClsMovimientos() + If ObjMovtos.GetCxCClienteDetalle(ViewState("CveCliente").ToString.ToEntero, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa, DdlSucursalCliente.SelectedValue.ToEntero) Then + Dim DtTemporal As DataTable = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act' AND CveVenta > 0", "Moneda, OrdenVencimiento, FechaVencimiento") + GvCxC.DataSource = DtTemporal + End If + ObjMovtos.Dispose() + GvCxC.DataBind() + End Sub + + Protected Sub GvCxC_RowDataBound(sender As Object, e As GridViewRowEventArgs) + If e.Row.RowType = DataControlRowType.DataRow Then + e.Row.FCCheckBox("ChkCxC").Attributes.Add("onclick", $"CalculaTotalChk({e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble},{TxtNCPorcentaje.Text.ToDouble}, this);") + e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaCantidadNCMasivo({TxtNCPorcentaje.Text.ToDouble()},{e.Row.DBCampo("Saldo").ToDouble},{e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{TxtNCImporte.ClientID},{e.Row.FCCheckBox("ChkCxC").ClientID}, this);") + End If + End Sub + + Protected Sub DdlNCNivelImporte_SelectedIndexChanged(sender As Object, e As EventArgs) + Dim ImporteReferencia As Double = 0, PorcentajeMaximo As Double = 0 + If Not AplicaNCMasiva Then + ImporteReferencia = If(DdlNCNivelImporte.SelectedValue.ToEntero = 1, TxtTotal.Text.Trim.ToDouble, TxtSubTotal.Text.Trim.ToDouble) + PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.Trim.ToDouble + RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString + RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * ImporteReferencia) / 100).FormatoNumero().ToDouble.ToString + End If + + If AplicaNCMasiva Then RegistraScript($"CalculaImporteNCMasivo()", "CalculaImporteNCMasivo") Else RegistraScript("CalculaImporteNC();", "CalculaImporteNC") + UpAplicarNC.Update() + End Sub + + Protected Sub BtnAplicarNC_Click(sender As Object, e As EventArgs) + + Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlNCPS.SelectedValue.ToEntero).FiltroPrimero("") + If DrPS Is Nothing Then + Alert("Ocurrió un error al cargar la información del producto. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError) + Exit Sub + Else + 'VALIDA CLAVES SAT + If DrPS("SATClavePS").ToString = "" Then + Alert($"El concepto {DrPS("Codigo").ToString}-{DrPS("PS").ToString} no cuenta con producto SAT. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + If DrPS("SATClaveUnidadMedida").ToString = "" Then + Alert($"El concepto {DrPS("Codigo").ToString}-{DrPS("PS").ToString} no cuenta con Unidad Medida SAT. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + End If + + If DdlTipoComprobante.SelectedValue = "Ant" Then CveAnticipo = CveVenta + + DdlTipoComprobante.SelectedValueExist("Egs") + + 'CREAMOS DT PARA UTILIZAR AL TIMBRAR + InicializaDTVentasNC() + + Dim DtImpuestos As New DataTable + DtImpuestos.Columns.Add("ImportePU", GetType(Double)) + DtImpuestos.Columns.Add("ImporteTotal", GetType(Double)) + DtImpuestos.Columns.Add("PorcentajeIVA", GetType(Double)) + DtImpuestos.Columns.Add("ImporteIVA", GetType(Double)) + DtImpuestos.Columns.Add("PorcentajeRetIVA", GetType(Double)) + DtImpuestos.Columns.Add("ImporteRetIVA", GetType(Double)) + DtImpuestos.Columns.Add("PorcentajeRetISR", GetType(Double)) + DtImpuestos.Columns.Add("ImporteRetISR", GetType(Double)) + DtImpuestos.Columns.Add("PorcentajeIEPS", GetType(Double)) + DtImpuestos.Columns.Add("ImporteIEPS", GetType(Double)) + DtImpuestos.Columns.Add("CveSubProyecto", GetType(Integer)) + DtImpuestos.AcceptChanges() + + If AplicaNCMasiva Then + For Each Gvr As GridViewRow In GvCxC.Rows + If Gvr.FCCheckBox("ChkCxC").Checked Then + DtImpuestos.Merge(CargaDtImpuestosNC(Gvr.DataKey("CveVenta").ToString.ToEntero, Gvr.FCTextBox("TxtImporte").Text.ToString.ToDecimal), True, MissingSchemaAction.Ignore) + 'CARGA FACTURA A LA CUAL SE APLICA LA NC + CargaNCDT(Gvr.DataKey("CveVenta").ToString.ToEntero, Gvr.FCTextBox("TxtImporte").Text.ToString.ToDecimal) + End If + Next + Else + DtImpuestos = CargaDtImpuestosNC(CveVenta, TxtNCImporte.Text.Trim.ToDecimal) + End If + + Dim query = From dr In DtImpuestos + Group By PorcentajeIVA = dr("PorcentajeIVA").ToString.ToDecimal, + PorcentajeRetIVA = dr("PorcentajeRetIVA").ToString.ToDecimal, + PorcentajeRetISR = dr("PorcentajeRetISR").ToString.ToDecimal, + PorcentajeIEPS = dr("PorcentajeIEPS").ToString.ToDecimal + Into x = Group + Select ImportePU = x.Sum(Function(s) s("ImportePU").ToString.ToDecimal), + ImporteTotal = x.Sum(Function(s) s("ImporteTotal").ToString.ToDecimal), + ImporteIVA = x.Sum(Function(s) s("ImporteIVA").ToString.ToDecimal), + ImporteRetIVA = x.Sum(Function(s) s("ImporteRetIVA").ToString.ToDecimal), + ImporteRetISR = x.Sum(Function(s) s("ImporteRetISR").ToString.ToDecimal), + ImporteIEPS = x.Sum(Function(s) s("ImporteIEPS").ToString.ToDecimal), + PorcentajeIVA = PorcentajeIVA, + PorcentajeRetIVA = PorcentajeRetIVA, + PorcentajeRetISR = PorcentajeRetISR, + PorcentajeIEPS = PorcentajeIEPS + + Dim DrSubProyecto = GlobalDTSubProyectos(-1, TmpDT.FiltroPrimeroValor("CveSubProyecto", "", "ImporteTotal DESC").ToEntero, UsuarioActual.CveEmpresa, -1).FiltroPrimero("") + If DrSubProyecto Is Nothing Then + Alert("Ocurrió un error al cargar la información de centro de costos. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError) + Exit Sub + End If + + + DtImpuestos = query.QueryToDataTable(False) + + LimpiaDocumentoNC() + + Dim CveSubProyecto = DrSubProyecto("CveSubProyecto").ToString.ToEntero + Dim SubProyecto = DrSubProyecto("SubProyecto").ToString + Dim CveProyecto = DrSubProyecto("CveProyecto").ToString.ToEntero + Dim Proyecto = DrSubProyecto("Proyecto").ToString + + For Each Dr As DataRow In DtImpuestos.Rows + AgregaTempDT(DrPS("CvePS").ToString.ToEntero, DrPS("PS").ToString, DrPS("Codigo").ToString, DrPS("PSCodigo").ToString, DrPS("CveTipoPS").ToString.ToEntero, DrPS("Inv_CveMetodoInventario").ToString.ToEntero, + DrPS("CveUM").ToString.ToEntero, DrPS("UnidadMedida").ToString, DrPS("CveClasificacion").ToString.ToEntero, DrPS("Clasificacion").ToString, CveProyecto, Proyecto, CveSubProyecto, SubProyecto, + TxtNCObservaciones.Text.Trim, 1, Dr("ImportePU").ToString.ToDecimal, Dr("PorcentajeIVA").ToString.ToDecimal, Dr("ImporteIVA").ToString.ToDecimal, Dr("PorcentajeRetIVA").ToString.ToDecimal, Dr("ImporteRetIVA").ToString.ToDecimal, + Dr("PorcentajeRetISR").ToString.ToDecimal, Dr("ImporteRetISR").ToString.ToDecimal, Dr("PorcentajeIEPS").ToString.ToDecimal, Dr("ImporteIEPS").ToString.ToDecimal, -1, 0.0, Dr("ImporteTotal").ToString.ToDecimal, "", "", -1, -1, + DrPS("SATClavePS").ToString, DrPS("SATClaveUnidadMedida").ToString, -1, -1, -1, -1, -1, -1) + Next + + TrTipoRelacion.Visible = True + DdlTiposRelacion.SelectedValueExist("1") + + GvPS.DataSource = TmpDT + GvPS.DataBind() + + CalculaTotalesVenta(True) + + + 'condicióon, en la que se verifica que el importe total de aplicación de la nota de crédito sea igual al del total de la nota de crédito, ej. saldo de la factura 1000.01 y la nota de crédito se generó po 1000.00 + If Not AplicaNCMasiva Then + Dim TT As Decimal = TxtNCImporte.Text.ToDecimal + If TT > TxtTotal.Text.ToDecimal Then TT = TxtTotal.Text.ToDecimal + CargaNCDT(CveVenta, TT) + End If + + UpPS.Update() + + LBNotaCredito.Visible = False + RegistraScript("$('#ModalAplicarNC').modal('hide');", "EscondeModalNC") + AplicaNC = True + + CambiaTipoDocto() + + End Sub + + Private Function CargaDtImpuestosNC(CveVentaNC As Integer, Importe As Decimal) As DataTable + Dim Total As Decimal = 0, SubTotal As Decimal = 0, Saldo As Decimal = 0 + + Dim ObjVentas As New ClsVentas + + If ObjVentas.GetVentaDetalle(CveVentaNC) Then + TmpDT = ObjVentas.DtResultados + TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) + TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) + End If + + If AplicaNCMasiva Then + If ObjVentas.GetVenta(CveVentaNC, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + Total = ObjVentas.DtResultados()(0)("Total").ToString.ToDecimal + SubTotal = ObjVentas.DtResultados()(0)("SubTotal").ToString.ToDecimal + End If + End If + Else + Total = TxtTotal.Text.ToDecimal + SubTotal = TxtSubTotal.Text.ToDecimal + + + End If + ObjVentas.Dispose() + + Dim DtImpuestosLocal = TmpDT.FiltraParametros("", "", {"PorcentajeIVA", "PorcentajeRetIVA", "PorcentajeRetISR", "PorcentajeIEPS", "CveSubProyecto"}).Copy + DtImpuestosLocal.Columns.Add("ImportePU", GetType(Double)) + DtImpuestosLocal.Columns.Add("ImporteTotal", GetType(Double)) + DtImpuestosLocal.Columns.Add("ImporteIVA", GetType(Double)) + DtImpuestosLocal.Columns.Add("ImporteRetIVA", GetType(Double)) + DtImpuestosLocal.Columns.Add("ImporteRetISR", GetType(Double)) + DtImpuestosLocal.Columns.Add("ImporteIEPS", GetType(Double)) + + Dim ImporteReferencia As Decimal = If(DdlNCNivelImporte.SelectedValue.ToEntero = 1, Total, SubTotal) + Dim Porcentaje As Decimal = ((Importe * 100) / ImporteReferencia) / 100 + + For Each Dr As DataRow In DtImpuestosLocal.Rows + Dr("ImporteTotal") = Math.Round(Porcentaje * (TmpDT.SUM("TotalImporte", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ") - TmpDT.SUM("Descuento", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ")), 2) + ' COMENTANDO POR JESUS MURUA ALIAS EL CHOLO, LO HIZO EL RAUL ARRIBA ALV ! 28/02/2018 + 'Dr("ImporteTotal") = Porcentaje * TmpDT.SUM("TotalImporte", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ") + Dr("ImporteIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIVA", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' "), 2) + Dr("ImporteRetIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetIVA", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' "), 2) + Dr("ImporteRetISR") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetISR", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}'"), 2) + Dr("ImporteIEPS") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIEPS", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}'"), 2) + Dr("ImportePU") = Dr("ImporteTotal").ToString.ToDecimal '(Dr("ImporteTotal").ToString.ToDecimal - Dr("ImporteIVA").ToString.ToDecimal - Dr("ImporteRetIVA").ToString.ToDecimal - Dr("ImporteRetISR").ToString.ToDecimal - Dr("ImporteIEPS").ToString.ToDecimal) + Next + 'codigo para ajuste de centavo, si el importe total no cuadra con los totales + Dim difTmp As Decimal = Importe - (DtImpuestosLocal.SUMD("ImporteTotal") + DtImpuestosLocal.SUMD("ImporteIVA") + DtImpuestosLocal.SUMD("ImporteIEPS") - DtImpuestosLocal.SUMD("ImporteRetIVA") - DtImpuestosLocal.SUMD("ImporteRetISR")) + If Math.Abs(difTmp) >= 0.01 Then + 'asusto la diferencia en el último concepto + DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal") = DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal").ToString.ToDecimal + difTmp + End If + + 'CARGA FACTURA A LA CUAL SE APLICA LA NC + 'CargaNCDT(CveVentaNC, Importe.ToDecimal) + Return DtImpuestosLocal + End Function + + Private Sub AgregaTempDT(CvePS As Integer, PS As String, Codigo As String, CodigoPS As String, CveTipoPS As Integer, CveTipoInvPS As Integer, CveUM As Integer, UM As String, + CveClasificacion As Integer, Clasificacion As String, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, + Obs As String, Cantidad As Double, PU As Double, PorcentajeIVA As Double, ImporteIVA As Double, PorcentajeRetIVA As Double, ImporteRetIVA As Double, + PorcentajeRetISR As Double, ImporteRetISR As Double, PorcentajeIEPS As Double, ImporteIEPS As Double, TipoDescuento As Integer, Descuento As Double, + Total As Double, SerieLote As String, TiempoEntrega As String, CvePresupuestoIngreso As Integer, EntregaDirecta As Integer, SATClaveProdServ As String, + SATClaveUM As String, CveContratoDetalle As Integer, CveVentaDetalle As Integer, CveMovimientoDetallePedido As Integer, CveOrdenCompraDetalle As Integer, + CveVentaDetalleRemision As Integer, CveVentaDetalleCotizacion As Integer) + + Dim Row As DataRow = Nothing + Row = TmpDT.NewRow() + + Row("Consec") = TmpDT.Rows.Count + 1 + Row("Orden") = TmpDT.Rows.Count + 1 + + Row("CvePS") = CvePS + Row("PS") = PS + Row("Codigo") = Codigo + Row("CodigoPS") = CodigoPS + Row("CveTipoPS") = CveTipoPS + Row("CveTipoInvPS") = CveTipoInvPS + + Row("CveUM") = CveUM + Row("UM") = UM + + Row("CveClasificacion") = CveClasificacion + Row("Clasificacion") = Clasificacion + Row("CveProyecto") = CveProyecto + Row("Proyecto") = Proyecto + Row("CveSubProyecto") = CveSubProyecto + Row("SubProyecto") = SubProyecto + + Row("Obs") = Obs + Row("Cantidad") = Cantidad + Row("PU") = Math.Round(PU, 6) + Row("PorcentajeIVA") = PorcentajeIVA + Row("IVA") = PorcentajeIVA + Row("ImporteIVA") = Math.Round(ImporteIVA, NumeroDecimales) + Row("PorcentajeRetIVA") = PorcentajeRetIVA + Row("ImporteRetIVA") = Math.Round(ImporteRetIVA, NumeroDecimales) + Row("PorcentajeRetISR") = PorcentajeRetISR + Row("ImporteRetISR") = Math.Round(ImporteRetISR, NumeroDecimales) + Row("PorcentajeIEPS") = PorcentajeIEPS + Row("ImporteIEPS") = Math.Round(ImporteIEPS, NumeroDecimales) + Row("IEPS") = Math.Round(ImporteIEPS, NumeroDecimales) + Row("TipoDescuento") = TipoDescuento + Row("Descuento") = Math.Round(Descuento, NumeroDecimales) + Row("Total") = Math.Round(Total, NumeroDecimales) + Row("TotalImporte") = Math.Round(Total, NumeroDecimales) + + + Row("SerieLote") = SerieLote + Row("TiempoEntrega") = TiempoEntrega + Row("CvePresupuestoIngreso") = CvePresupuestoIngreso + Row("EntregaDirecta") = EntregaDirecta + Row("SATClaveProdServ") = SATClaveProdServ + Row("SATClaveUM") = SATClaveUM + + 'Contratos + Row("CveContratoDetalle") = CveContratoDetalle + Row("CveVentaDetalle") = CveVentaDetalle + Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido + Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle + Row("CveVentaDetalleRemision") = CveVentaDetalleRemision + Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion + + TmpDT.Rows.Add(Row) + End Sub + + Private Sub LimpiaDocumentoNC() + + EsCreaApartirDe = True + DivEstatusFac.Visible = False + TabAlmacen.Visible = False + + 'LIMPIA ACCIONES + HLOrdendeCompra.Visible = False + LkDevolucion.Visible = False + LBAplicaDevolucion.Visible = False + 'LkNotaCredito.Visible = False + LkEliminarFactura.Visible = False + ImgDownCancelacion.Visible = False + LkRefacturacion.Visible = False + HLOrdenServicio.Visible = False + LkCotizacionAutorizar.Visible = False + LnkFacturarRemision.Visible = False + LnkRemisiones.Visible = False + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + LnkOCs.Visible = False + LbCancelarDocumento.Visible = False + LBCancelarPedido.Visible = False + LiDevolucionAlmacen.Visible = False + HLPagar.Visible = False + HlAgregarExcel.Visible = False + HplDownXML.Visible = False + HplDownPDF.Visible = False + HLSaldarVenta.Visible = False + LBNotaCredito.Visible = False + LiComplementoPago.Visible = False + HlCuentaTerminal.Visible = False + LiLnkGuias.Visible = False + LiDocumentoCliente.Visible = False + + 'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION + GvPS.Columns(6).Visible = False + ThCantidadFacturadaRem.Visible = False + ThCantidadFacturadaRem2.Visible = False + GvPS.Columns(7).Visible = False + ThCantidadFacturada.Visible = False + ThCantidadFacturada2.Visible = False + + 'LIMPIA DETALLES + TmpDT.Clear() + GvPS.DataSource = Nothing + GvPS.DataBind() + + LblFolioFiscal.Text = "" + TxtFecha.Text = Now.ToShortDateString + + 'DESACTIVA/ACTIVA BOTONES + TrVistaPrevia.Visible = True + BtnEmitir.Visible = False + BtnCrearApartirDe.Visible = False + BtnGenerarRemision.Visible = False + BtnPermisoEditarCotizacion.Visible = False + BtnEditarCotizacion.Visible = False + BtnGenerarOS.Visible = False + + 'ACTIVA CONDICIONES DE PAGO + DdlUsoCFDI.Enabled = True + DdlUsoCFDI.SelectedValueExist("2") + DdlMetodoPago33.Enabled = True + DdlMetodoPago33.SelectedValueExist("1") ' PUE + CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) + DdlFormaPago33.Enabled = True + DdlFormaPago33.SelectedValueExist("11") ' condonación por default + + UpEstatus.Update() + UpnTools.Update() + UpCliente.Update() + UpParametros.Update() + UpPS.Update() + UpFacturar.Update() + UPObservaciones.Update() + UPPDescuento.Update() + UPCondicionesPago.Update() + UpDetalle.Update() + + + End Sub + + Private Sub InicializaDTVentasNC() + DtVentasNC = New DataTable + DtVentasNC.Columns.Add("CveVenta", GetType(Integer)) + DtVentasNC.Columns.Add("Importe", GetType(Decimal)) + DtVentasNC.Columns.Add("FolioFiscal", GetType(String)) + DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TC", .DataType = GetType(Decimal), .DefaultValue = 1}) + DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TCCambioValuacion", .DataType = GetType(Decimal), .DefaultValue = 1}) + DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "CveEstatusFactura", .DataType = GetType(Integer), .DefaultValue = -1}) + End Sub + + Private Sub CargaNCDT(pCveVenta As Integer, Importe As Decimal, Optional FolioFiscal As String = "", Optional NuevaFactura As Integer = -1, Optional ByRef ObjVentas As ClsVentas = Nothing, Optional TC As Decimal = 1) + If (pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs")) OrElse (pCveVenta > 0 AndAlso NuevaFactura = 1) Then + Dim CveEstatusFacturaNC As Integer = -1 + Dim TCCambioValuacion As Decimal = 1 + If FolioFiscal = "" Then + Dim ObjVentasAplicar As ClsVentas + If ObjVentas IsNot Nothing Then + ObjVentasAplicar = ObjVentas + Else + ObjVentasAplicar = New ClsVentas + End If + If ObjVentasAplicar.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentasAplicar.DtResultados.Rows.Count > 0 Then + FolioFiscal = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("FolioFiscal").ToString() + TC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambio").ToString.ToDecimal() + TCCambioValuacion = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambioValuacion").ToString.ToDecimal() + CveEstatusFacturaNC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("CveEstatusFactura").ToString.ToEntero() + End If + + If ObjVentas Is Nothing Then + ObjVentasAplicar.Dispose() + End If + + End If + + Dim Dr = DtVentasNC.NewRow + + Dr("CveVenta") = pCveVenta + Dr("Importe") = Importe + Dr("FolioFiscal") = FolioFiscal + Dr("TC") = TC + Dr("TCCambioValuacion") = TCCambioValuacion + Dr("CveEstatusFactura") = CveEstatusFacturaNC + + DtVentasNC.Rows.Add(Dr) + End If + End Sub + +#End Region + +#Region " APLICA DEVOLUCION " + Private Sub InicializaAplicaDevolucion() + If Not UsuarioActual.CveUsuario = 100 Then + If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then + Exit Sub + End If + End If + + 'sino tiene el permiso no puede generar Devolucion + If Not UsuarioActual.TienePermisoProceso(264) Then + Exit Sub + End If + + LkDevolucion.Visible = False + LBAplicaDevolucion.Visible = True + Dim SeEsconde As Boolean = False + Dim ObjVenta As New ClsVentas + If ObjVenta.GetVentaDetalle(CveVenta) Then + If Not ObjVenta.DtResultados.SUM("CantSur").ToString.ToDecimal > 0 Then SeEsconde = True + GvAplicaDevolucion.DataSource = ObjVenta.DtResultados.FiltraParametros("CantRes > 0") + End If + ObjVenta.Dispose() + + 'activo el permiso para registrar el importe diferente a la devolución + GvAplicaDevolucion.Columns(9).Visible = UsuarioActual.TienePermisoProceso(253) + + 'MODALIDAD CENTRO COSTOS + If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then + GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal" + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then + GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto" + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then + GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal/Proyecto" + ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then + GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto/Sucursal" + End If + + If SeEsconde Then GvAplicaDevolucion.Columns(1).Visible = False : GvAplicaDevolucion.Columns(2).Visible = False : GvAplicaDevolucion.Columns(3).Visible = False + + GvAplicaDevolucion.DataBind() + + UpDevolucion.Update() + + End Sub + Protected Sub BtnAplicaDevolucion_Click(sender As Object, e As EventArgs) + + 'VALIDACIONES + Dim Selecciono As Boolean = False + For Each Gv As GridViewRow In GvAplicaDevolucion.Rows + If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDouble > 0 Then + Selecciono = True + Exit For + End If + Next + + If Not Selecciono Then + Alert("Tiene que seleccionar al menos un concepto y este dege tener una cantidad mayor a 0. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + AplicaDevolucion = True + SaldoVentaDevolucion = HplSaldoAuxiliar.Text.ToDecimal + CveVentaDevolucion = CveVenta + DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) + DdlTipoComprobante.SelectedValue = "Dev" + + Dim AplicaPUEditado As Boolean = UsuarioActual.TienePermisoProceso(253) + + TmpDT.Clear() + For Each Gv As GridViewRow In GvAplicaDevolucion.Rows + If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal > 0 Then + Dim Cantidad As Decimal = Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal + Dim Descuento As Decimal = Cantidad * Gv.DataKey("Descuento").ToString.ToDecimal / Gv.DataKey("Cantidad").ToString.ToDecimal + Dim PU As Decimal = If(AplicaPUEditado, Gv.FCTextBox("TxtPrecioEditado").Text.ToDecimal, Gv.DataKey("PU").ToDecimal) + Dim Total As Decimal = (Cantidad * PU) + Dim TotalImpuestos As Decimal = (Cantidad * PU) - Descuento + Dim ImporteIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIVA").ToString.ToDecimal + Dim ImporteRetIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetIVA").ToString.ToDecimal + Dim ImporteRetISR As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetISR").ToString.ToDecimal + Dim ImporteIEPS As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIEPS").ToString.ToDecimal + + AgregaTempDT(Gv.DataKey("CvePS").ToString.ToEntero, Gv.DataKey("PS").ToString, Gv.DataKey("Codigo").ToString, Gv.DataKey("CodigoPS").ToString, + Gv.DataKey("CveTipoPS").ToString.ToEntero, Gv.DataKey("CveTipoInvPS").ToString.ToEntero, + Gv.DataKey("CveUM").ToString.ToEntero, Gv.DataKey("UM").ToString, Gv.DataKey("CveClasificacion").ToString.ToEntero, + Gv.DataKey("Clasificacion").ToString, Gv.DataKey("CveProyecto").ToString.ToEntero, Gv.DataKey("Proyecto").ToString, + Gv.DataKey("CveSubProyecto").ToString.ToEntero, Gv.DataKey("SubProyecto").ToString, + Gv.DataKey("Obs").ToString, Cantidad, PU, Gv.DataKey("PorcentajeIVA").ToString.ToDecimal, ImporteIVA, + Gv.DataKey("PorcentajeRetIVA").ToString.ToDecimal, ImporteRetIVA, + Gv.DataKey("PorcentajeRetISR").ToString.ToDecimal, ImporteRetISR, Gv.DataKey("PorcentajeIEPS").ToString.ToDecimal, + ImporteIEPS, -1, Descuento, Total, "", "", -1, -1, + Gv.DataKey("SATClaveProdServ").ToString, Gv.DataKey("SATClaveUM").ToString, -1, Gv.DataKey("CveVentaDetalle").ToString.ToEntero, -1, -1, -1, -1) + End If + Next + + LimpiaDocumentoDEV() + + CambiaTipoDocto() + CargaNC(CveVenta) + CalculaTotalesVenta() + + RegistraScript("$('#DivAplicaDevolucion').modal('hide')") + + End Sub + Protected Sub GvAplicaDevolucion_RowDataBound(sender As Object, e As GridViewRowEventArgs) + If e.Row.RowType = DataControlRowType.DataRow Then + e.Row.FCTextBox("TxtCantidadAplicaDevolucion").Attributes.Add("onkeyup", $"LimitaCantidadAplicaDev({e.Row.DBCampo("CantRes").ToDecimal}, this);") + If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Or UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then + e.Row.FCLabel("LblProyecto").Text = e.Row.FCLabel("LblSubProyecto").Text + e.Row.FCLabel("LblProyecto").Style.Clear() + e.Row.FCLabel("LblSubProyecto").Text = "" + End If + End If + End Sub + Private Sub LimpiaDocumentoDEV() + + 'REINICIALIZA PORLET CLIENTES + ChkEnviarFactura.Enabled = True + 'ACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto") + TxtCodigo.ReadOnly = False + + + 'REINICIALIZA PORLET DATOS DE EMIISION + trNCFactura.Visible = True + DdlSubProyectoDatos.Enabled = True + TrFolioFiscal.Visible = False + TxtFecha.Text = Now.ToShortDateString() + TipoCambioFactura = TxtTipoCambio.Text.ToDecimal + TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString + DivEstatusFac.Visible = False + + 'REINICIALIZA TABS + TabAlmacen.Enabled = False + TabE.Enabled = False + + 'REINICIALIZA GENERALES PS + LbAgregar.Visible = False + GvPS.Columns(17).Visible = False + GvPS.Columns(18).Visible = False + GvPS.Columns(19).Visible = False + GvPS.Columns(20).Visible = False + DivRemisionesFacturadas.Visible = False + DivAnticiposVinculados.Visible = False + + 'REINICIALIZA TOTALES + TrConversionDolares.Visible = False + + 'ACTIVA CONDICIONES DE PAGO + DdlUsoCFDI.Enabled = True + DdlUsoCFDI.SelectedValueExist("2") + DdlMetodoPago33.Enabled = True + DdlMetodoPago33.SelectedValueExist("1") + CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) + DdlFormaPago33.Enabled = True + DdlFormaPago33.SelectedValueExist("11") + + 'REINICIALIZA OBSERVACIONES + TxtObsFact.Enabled = True + TxtOrdenCompra.Enabled = True + TxtPedidoContrato.Enabled = True + TxtObsAlmacen.Enabled = True + + 'DESACTIVA/ACTIVA BOTONES + BtnCrearApartirDe.Visible = False + BtnEmitirImprimir.Visible = True + BtnVistaPrevia.Visible = True + BtnEmitir.Visible = False + + 'REINICIALIZA ACCIONES + LkDevolucion.Visible = False + 'LkNotaCredito.Visible = False + LkEliminarFactura.Visible = False + ImgDownCancelacion.Visible = False + LkRefacturacion.Visible = False + HLOrdenServicio.Visible = False + LkCotizacionAutorizar.Visible = False + LnkFacturarRemision.Visible = False + LnkRemisiones.Visible = False + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + LnkOCs.Visible = False + LbCancelarDocumento.Visible = False + LBCancelarPedido.Visible = False + LiDevolucionAlmacen.Visible = False + HLPagar.Visible = False + HlAgregarExcel.Visible = False + HplDownXML.Visible = False + HplDownPDF.Visible = False + HLSaldarVenta.Visible = False + LBNotaCredito.Visible = False + LiComplementoPago.Visible = False + HlCuentaTerminal.Visible = False + LiLnkGuias.Visible = False + LiDocumentoCliente.Visible = False + LBAplicaDevolucion.Visible = False + HplFolioFiscalModal.Visible = False + + 'Limpia Anticipos Seleccionados + For Each row2 As GridViewRow In GVAnticipos.Rows + If row2.RowType = DataControlRowType.DataRow Then + row2.FCCheckBox("Chk" & row2.RowIndex).Checked = False + End If + Next + + UpAnticipos.Update() + UpParametros.Update() + UpPS.Update() + UpEstatus.Update() + UpCliente.Update() + UpRemisiones.Update() + Updatetabs.Update() + UpFacturar.Update() + UPCondicionesPago.Update() + UpnTools.Update() + UPObservaciones.Update() + UpAntNC.Update() + End Sub +#End Region + +#Region "COMERCIO EXTERIOR" 'Public Sub InicializaComercioExterior() ' 'CargoComercioExterior = True @@ -21246,477 +21253,477 @@ Partial Class Ventas ' CargaGvComercioExterior() 'End Sub - Public Sub CargaGvComercioExterior() - GvComercioExterior.DataSource = TmpDT - GvComercioExterior.DataBind() - UpComercioExterior.Update() - End Sub - - 'Public Sub CargaCombos() - - ' 'DdlTipoOperacion.DataSource = GlobalDTTipoOperacion() - ' 'DdlTipoOperacion.Items.Insert(0, New ListItem("Seleccione", "-1")) - ' 'DdlTipoOperacion.DataBind() - - ' 'DdlIncoterm.DataSource = GlobalDTIncoterm() - ' 'DdlIncoterm.Items.Insert(0, New ListItem("Seleccione", "-1")) - ' 'DdlIncoterm.DataBind() - - ' 'DdlClavePedimento.DataSource = GlobalDTClavePedimento() - ' 'DdlClavePedimento.Items.Insert(0, New ListItem("Seleccione", "-1")) - ' 'DdlClavePedimento.DataBind() - - 'End Sub - - Protected Sub GvComercioExterior_RowDataBound(sender As Object, e As GridViewRowEventArgs) - If e.Row.RowType = DataControlRowType.DataRow Then - e.Row.FCTextBox("TxtValorUnitario").Attributes.Add("onkeyup", $"CalculaTotalUSD({e.Row.FCLabel("LblTotalUSD").ClientID}, this,{e.Row.FCTextBox("TxtCantidad").ClientID});") - End If - End Sub - - - 'Protected Sub BtnCargaComercioExterior_Click(sender As Object, e As EventArgs) - ' If Not CargoComercioExterior Then - ' InicializaComercioExterior() - ' End If - 'End Sub - - Public Function ValidaComercioExterior() As Boolean - If Not CveTipoOperacion > 0 Then - Alert("Tiene que seleccionar un tipo de operación", TipoMensaje.MsgAdvertencia) - Return False - End If - - If Not CvePedimento > 0 Then - Alert("Tiene que seleccionar una clave de pedimento", TipoMensaje.MsgAdvertencia) - Return False - End If - - If Not CveIncoterm > 0 Then - Alert("Tiene que seleccionar un incoterm", TipoMensaje.MsgAdvertencia) - Return False - End If - - If Not GvComercioExterior.Rows.Count > 0 Then - Alert("Tiene que seleccionar fraccion arancelaria,unidad aduana y valor unitario", TipoMensaje.MsgAdvertencia) - End If - - For Each Gvr As GridViewRow In GvComercioExterior.Rows - - If Not Gvr.DataKey("Codigo").ToString <> "" Then - Alert("Todos los conceptos tienen que tener un codigo asignado", TipoMensaje.MsgAdvertencia) - Return False - End If - - If Not Gvr.DataKey("ClaveSATFraccionArancelaria").ToEntero > 0 Then - Alert("Todos los productos tienen que tener una fraccion arancelaria", TipoMensaje.MsgAdvertencia) - Return False - End If - - If Not Gvr.DataKey("ClaveSATUnidadAduana").ToEntero > 0 Then - Alert("Todos los productos tienen que tener una unidad aduana", TipoMensaje.MsgAdvertencia) - Return False - End If - - If Not Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal > 0 Then - Alert("Todos los conceptos tienen que tener un valor unitario mayor a 0", TipoMensaje.MsgAdvertencia) - Return False - End If - Next - - Return True + Public Sub CargaGvComercioExterior() + GvComercioExterior.DataSource = TmpDT + GvComercioExterior.DataBind() + UpComercioExterior.Update() + End Sub + + 'Public Sub CargaCombos() + + ' 'DdlTipoOperacion.DataSource = GlobalDTTipoOperacion() + ' 'DdlTipoOperacion.Items.Insert(0, New ListItem("Seleccione", "-1")) + ' 'DdlTipoOperacion.DataBind() + + ' 'DdlIncoterm.DataSource = GlobalDTIncoterm() + ' 'DdlIncoterm.Items.Insert(0, New ListItem("Seleccione", "-1")) + ' 'DdlIncoterm.DataBind() + + ' 'DdlClavePedimento.DataSource = GlobalDTClavePedimento() + ' 'DdlClavePedimento.Items.Insert(0, New ListItem("Seleccione", "-1")) + ' 'DdlClavePedimento.DataBind() + + 'End Sub + + Protected Sub GvComercioExterior_RowDataBound(sender As Object, e As GridViewRowEventArgs) + If e.Row.RowType = DataControlRowType.DataRow Then + e.Row.FCTextBox("TxtValorUnitario").Attributes.Add("onkeyup", $"CalculaTotalUSD({e.Row.FCLabel("LblTotalUSD").ClientID}, this,{e.Row.FCTextBox("TxtCantidad").ClientID});") + End If + End Sub + + + 'Protected Sub BtnCargaComercioExterior_Click(sender As Object, e As EventArgs) + ' If Not CargoComercioExterior Then + ' InicializaComercioExterior() + ' End If + 'End Sub + + Public Function ValidaComercioExterior() As Boolean + If Not CveTipoOperacion > 0 Then + Alert("Tiene que seleccionar un tipo de operación", TipoMensaje.MsgAdvertencia) + Return False + End If + + If Not CvePedimento > 0 Then + Alert("Tiene que seleccionar una clave de pedimento", TipoMensaje.MsgAdvertencia) + Return False + End If + + If Not CveIncoterm > 0 Then + Alert("Tiene que seleccionar un incoterm", TipoMensaje.MsgAdvertencia) + Return False + End If + + If Not GvComercioExterior.Rows.Count > 0 Then + Alert("Tiene que seleccionar fraccion arancelaria,unidad aduana y valor unitario", TipoMensaje.MsgAdvertencia) + End If + + For Each Gvr As GridViewRow In GvComercioExterior.Rows + + If Not Gvr.DataKey("Codigo").ToString <> "" Then + Alert("Todos los conceptos tienen que tener un codigo asignado", TipoMensaje.MsgAdvertencia) + Return False + End If + + If Not Gvr.DataKey("ClaveSATFraccionArancelaria").ToEntero > 0 Then + Alert("Todos los productos tienen que tener una fraccion arancelaria", TipoMensaje.MsgAdvertencia) + Return False + End If + + If Not Gvr.DataKey("ClaveSATUnidadAduana").ToEntero > 0 Then + Alert("Todos los productos tienen que tener una unidad aduana", TipoMensaje.MsgAdvertencia) + Return False + End If + + If Not Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal > 0 Then + Alert("Todos los conceptos tienen que tener un valor unitario mayor a 0", TipoMensaje.MsgAdvertencia) + Return False + End If + Next + + Return True End Function -#End Region +#End Region + +#Region "NOTIFICACIONES AVACE" + Private Sub EnviarNotificacionAvance(NumeroContrato As String, DescripcionContrato As String, ContratoTipo As String, Cliente As String, CorreoVendedor As String, Optional MontoMaximo As Double = 0) + + Dim ObjMail As New ClsSisMail() + + Dim CorreoLicitacion As String = "" + + Dim Para As String = String.Format("{0};{1}", CorreoVendedor, CorreoLicitacion) + Dim Asunto As String = "NOTIFICACION DE 100% DE AVANCE DE CONTRATO" + Dim Cuerpo As String = "" + + If MontoMaximo > 0 Then + Cuerpo = String.Format("El Contrato {0} - {1} ({2}) con cliente {4} ha alcanzado el monto máximo de {3}.", NumeroContrato, DescripcionContrato, ContratoTipo, MontoMaximo.ToString("C2"), Cliente) + Else + Cuerpo = String.Format("El Contrato {0} - {1} ({2}) con cliente {3} ha llegado al 100% de Avance.", NumeroContrato, DescripcionContrato, ContratoTipo, Cliente) + End If + + ObjMail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Cuerpo) -#Region "NOTIFICACIONES AVACE" - Private Sub EnviarNotificacionAvance(NumeroContrato As String, DescripcionContrato As String, ContratoTipo As String, Cliente As String, CorreoVendedor As String, Optional MontoMaximo As Double = 0) - - Dim ObjMail As New ClsSisMail() - - Dim CorreoLicitacion As String = "" - - Dim Para As String = String.Format("{0};{1}", CorreoVendedor, CorreoLicitacion) - Dim Asunto As String = "NOTIFICACION DE 100% DE AVANCE DE CONTRATO" - Dim Cuerpo As String = "" - - If MontoMaximo > 0 Then - Cuerpo = String.Format("El Contrato {0} - {1} ({2}) con cliente {4} ha alcanzado el monto máximo de {3}.", NumeroContrato, DescripcionContrato, ContratoTipo, MontoMaximo.ToString("C2"), Cliente) - Else - Cuerpo = String.Format("El Contrato {0} - {1} ({2}) con cliente {3} ha llegado al 100% de Avance.", NumeroContrato, DescripcionContrato, ContratoTipo, Cliente) - End If - - ObjMail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Cuerpo) - End Sub -#End Region +#End Region -#Region "Comercio Exterior" - Private Sub CargaPais() - DdlComExtPais.Items.Clear() - DdlComExtPais.DataSource = GlobalDTPais() - DdlComExtPais.DataBind() - DdlComExtPais.SelectedValueExist("151") - End Sub - - Private Sub CargaEstado() - DdlComExtEstado.Items.Clear() - If DdlComExtPais.SelectedValue.ToEntero > 0 Then - DdlComExtEstado.DataSource = GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString) - End If - DdlComExtEstado.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlComExtEstado.DataBind() - End Sub - - Private Sub CargaMunicipio() - DdlComExtMunicipio.Items.Clear() - If DdlComExtEstado.SelectedValue.ToEntero > 0 Then - DdlComExtMunicipio.DataSource = GlobalDTMunicipio(GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString).FiltraParametros($"CveEstado = {DdlComExtEstado.SelectedValue.ToEntero}")(0)("ClaveSATEstado").ToString) - End If - DdlComExtMunicipio.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlComExtMunicipio.DataBind() - DdlComExtMunicipio.Visible = True - End Sub - - Private Sub CargaColonia() - DdlComExtColonia.Items.Clear() - If DdlComExtMunicipio.SelectedValue.ToEntero > 0 Then - DdlComExtColonia.DataSource = GlobalDTColonia(GlobalDTMunicipio(GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString).FiltraParametros($"CveEstado = {DdlComExtEstado.SelectedValue.ToEntero}")(0)("ClaveSATEstado").ToString).FiltraParametros($"CveMunicipio = {DdlComExtMunicipio.SelectedValue.ToEntero}")(0)("ClaveSATMunicipio").ToString) - End If - DdlComExtColonia.Items.Insert(0, New ListItem("Seleccione", "-1")) - DdlComExtColonia.DataBind() - DdlComExtColonia.Visible = True - End Sub - - Protected Sub DdlPais_SelectedIndexChanged(sender As Object, e As EventArgs) - 'si contiene MX, USA o CANADA carga ddls, si no carga txt - If DdlComExtPais.SelectedValue.Contiene("151", "66", "40") Then - DdlComExtEstado.Visible = True - DdlComExtMunicipio.Visible = True - DdlComExtColonia.Visible = True - - TxtComExtEstado.Visible = False - TxtComExtMunicipio.Visible = False - TxtComExtColonia.Visible = False - - CargaEstado() - CargaMunicipio() - CargaColonia() - Else - DdlComExtEstado.Visible = False - DdlComExtMunicipio.Visible = False - DdlComExtColonia.Visible = False - - TxtComExtEstado.Visible = True - TxtComExtMunicipio.Visible = True - TxtComExtColonia.Visible = True - End If - - End Sub - Protected Sub DdlEstado_SelectedIndexChanged(sender As Object, e As EventArgs) - 'si contiene USA o CANADA carga txt - If DdlComExtPais.SelectedValue.Contiene("151") Then - CargaMunicipio() - CargaColonia() - Else - If DdlComExtPais.SelectedValue.Contiene("66", "40") Then - DdlComExtMunicipio.Visible = False - DdlComExtColonia.Visible = False - - TxtComExtMunicipio.Visible = True - TxtComExtColonia.Visible = True - End If - End If - - End Sub - Protected Sub DdlMunicipio_SelectedIndexChanged(sender As Object, e As EventArgs) - CargaColonia() - End Sub - Private Sub BtnComExtConvertirUnidad_Click(sender As Object, e As EventArgs) Handles BtnComExtConvertirUnidad.Click - For Each gvr As GridViewRow In GvComercioExterior.Rows - gvr.FCTextBox("TxtCantidad").Text = (gvr.FCTextBox("TxtCantidad").Text.ToDecimal * TxtComExtConvertir.Text.ToDecimal).ToString - gvr.FCTextBox("TxtValorUnitario").Text = (gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal / TxtComExtConvertir.Text.ToDecimal).ToString - Next - End Sub -#End Region - - Private Sub BtnFolioFiscalAsignar_Click(sender As Object, e As EventArgs) Handles BtnFolioFiscalAsignar.Click - Dim ObjVentas As New ClsVentas() - If ObjVentas.UpdateVentaFolioFiscal(TxtModalFolioFiscal.Text.Trim, CveVenta, UsuarioActual.CveEmpresa) Then - Alert("Folio asignado", TipoMensaje.MsgInformacion) - RegistraScript("$('#ModalFolioFiscal').modal('hide')") - End If - ObjVentas.Dispose() +#Region "Comercio Exterior" + Private Sub CargaPais() + DdlComExtPais.Items.Clear() + DdlComExtPais.DataSource = GlobalDTPais() + DdlComExtPais.DataBind() + DdlComExtPais.SelectedValueExist("151") End Sub -#Region "FORMATO CICOVISA" - Protected Sub LnkImprimirFormatoCicovisa_Click(sender As Object, e As EventArgs) - Dim ObjVentas As New ClsVentas - Dim ObjInventario As New ClsInventarios - Dim SerieFolio As String = "" - Dim PedidoContrato As String = "" - Dim EnvioContacto As String = "" - Dim EnvioDireccion As String = "" - Dim Guia As String = "" - If ObjInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - If ObjInventario.DtResultados.Rows.Count > 0 Then - Guia = ObjInventario.DtResultados.Rows(0)("Guia").ToString - End If - End If - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - SerieFolio = ObjVentas.DtResultados.Rows(0)("SerieFolio").ToString - PedidoContrato = ObjVentas.DtResultados.Rows(0)("PedidoContrato").ToString - EnvioContacto = ObjVentas.DtResultados.Rows(0)("EnvioContacto").ToString - EnvioDireccion = $"{ObjVentas.DtResultados.Rows(0)("EnvioDireccion").ToString}, NO. EXT: {ObjVentas.DtResultados.Rows(0)("EnvioNoExt").ToString}, COLONIA: {ObjVentas.DtResultados.Rows(0)("EnvioColonia").ToString}, CP: {ObjVentas.DtResultados.Rows(0)("EnvioCP").ToString}" - End If - End If - Dim Dt As DataTable = Nothing - If ObjVentas.GetVentaDetalle(CveVenta) Then - Dt = ObjVentas.DtResultados - End If - ObjVentas.Dispose() - ObjInventario.Dispose() - If Dt.Rows.Count > 0 Then - Dim params As New List(Of ReportParameter) - params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) - params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) - params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) - params.Add(New ReportParameter("EnvioContacto", EnvioContacto)) - params.Add(New ReportParameter("SerieFolio", SerieFolio)) - params.Add(New ReportParameter("PedidoContrato", PedidoContrato)) - params.Add(New ReportParameter("EnvioDireccion", EnvioDireccion)) - params.Add(New ReportParameter("Guia", Guia)) - ImprimirPDF("Empresas/Grales/Formatos/Cicovisa.rdlc", Dt, params, String.Format("Formato Cicovisa -{0}", Now.ToDateTime.ToShortDateString)) - End If - End Sub -#End Region - -#Region "REQUIERE OC" - Protected Sub btnBuscarOCRegistrada_Click(sender As Object, e As EventArgs) - Dim ObjVentas As New ClsVentas - - If CveCliente > 0 AndAlso TxtOrdenCompra.Text.Trim <> "" AndAlso CveVenta <= 0 Then - If ObjVentas.GetOCVentas(CveCliente, TxtOrdenCompra.Text) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - Alert("Ya existen ventas con el mismo folio de orden de compra registrado", TipoMensaje.MsgAdvertencia) - End If - End If - End If - ObjVentas.Dispose() - End Sub -#End Region - -#Region "CLASIFICACIONES DETALLES" - Protected Sub DdlClasificacionPS_SelectedIndexChanged(sender As Object, e As EventArgs) - CargaClasificacionesDetalles() - End Sub - Protected Sub BtnAddClasificacionDetalle_Click(sender As Object, e As EventArgs) - TxtClasificacionDetalle.Text = "" - DdlClasificacionModal.SelectedValueExist(DdlClasificacionPS.SelectedValue) - UpModal.Update() - RegistraScript(String.Format("$('#{0}').modal('show');", "DModalClasificacion")) - End Sub - Protected Sub BtnAddClasificacionDetalleModal_Click(sender As Object, e As EventArgs) - Dim ObjVentas As New ClsVentas - If ObjVentas.AddClasificacionDetalle(TxtClasificacionDetalle.Text, DdlClasificacionModal.SelectedValue.ToEntero, - UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then - CargaClasificacionesDetalles() - DdlTipo.SelectedValueExist(ObjVentas.CveClasificacionDetalle) - UpAddPS.Update() - RegistraScript(String.Format("$('#{0}').modal('hide');", "DModalClasificacion"), "1") - RegistraScript("CreaDescripcionPS();", "2") - End If - ObjVentas.Dispose() - End Sub - - Private Sub GVAnticipos_PageIndexChanged(sender As Object, e As EventArgs) Handles GVAnticipos.PageIndexChanged - - End Sub - - Private Sub DdlTipoAmortizacionAnticipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoAmortizacionAnticipo.SelectedIndexChanged - divAnticipoMsg.Visible = False - If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("1", "2") Then - 'cuando es amortización por descuento, debe tener seleccionado descuentos previamente registrados - If DdlTipoAmortizacionAnticipo.SelectedValue = "1" AndAlso LblDescuentos.Text.ToDecimal <= 0 Then - divAnticipoMsg.Visible = True - - End If - - If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then DivConceptoNC.Visible = True Else DivConceptoNC.Visible = False - - DdlTipoRelacion.SelectedValueExist("7") - Else - DivConceptoNC.Visible = False - DdlTipoRelacion.SelectedValueExist("-1") - End If - - End Sub - - Private Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMetodoPago33.SelectedIndexChanged - CambiaMetodoPago33() - End Sub - Private Sub CambiaMetodoPago33() - CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) - + Private Sub CargaEstado() + DdlComExtEstado.Items.Clear() + If DdlComExtPais.SelectedValue.ToEntero > 0 Then + DdlComExtEstado.DataSource = GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString) + End If + DdlComExtEstado.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlComExtEstado.DataBind() End Sub -#End Region + Private Sub CargaMunicipio() + DdlComExtMunicipio.Items.Clear() + If DdlComExtEstado.SelectedValue.ToEntero > 0 Then + DdlComExtMunicipio.DataSource = GlobalDTMunicipio(GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString).FiltraParametros($"CveEstado = {DdlComExtEstado.SelectedValue.ToEntero}")(0)("ClaveSATEstado").ToString) + End If + DdlComExtMunicipio.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlComExtMunicipio.DataBind() + DdlComExtMunicipio.Visible = True + End Sub + + Private Sub CargaColonia() + DdlComExtColonia.Items.Clear() + If DdlComExtMunicipio.SelectedValue.ToEntero > 0 Then + DdlComExtColonia.DataSource = GlobalDTColonia(GlobalDTMunicipio(GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString).FiltraParametros($"CveEstado = {DdlComExtEstado.SelectedValue.ToEntero}")(0)("ClaveSATEstado").ToString).FiltraParametros($"CveMunicipio = {DdlComExtMunicipio.SelectedValue.ToEntero}")(0)("ClaveSATMunicipio").ToString) + End If + DdlComExtColonia.Items.Insert(0, New ListItem("Seleccione", "-1")) + DdlComExtColonia.DataBind() + DdlComExtColonia.Visible = True + End Sub + + Protected Sub DdlPais_SelectedIndexChanged(sender As Object, e As EventArgs) + 'si contiene MX, USA o CANADA carga ddls, si no carga txt + If DdlComExtPais.SelectedValue.Contiene("151", "66", "40") Then + DdlComExtEstado.Visible = True + DdlComExtMunicipio.Visible = True + DdlComExtColonia.Visible = True + + TxtComExtEstado.Visible = False + TxtComExtMunicipio.Visible = False + TxtComExtColonia.Visible = False + + CargaEstado() + CargaMunicipio() + CargaColonia() + Else + DdlComExtEstado.Visible = False + DdlComExtMunicipio.Visible = False + DdlComExtColonia.Visible = False + + TxtComExtEstado.Visible = True + TxtComExtMunicipio.Visible = True + TxtComExtColonia.Visible = True + End If + + End Sub + Protected Sub DdlEstado_SelectedIndexChanged(sender As Object, e As EventArgs) + 'si contiene USA o CANADA carga txt + If DdlComExtPais.SelectedValue.Contiene("151") Then + CargaMunicipio() + CargaColonia() + Else + If DdlComExtPais.SelectedValue.Contiene("66", "40") Then + DdlComExtMunicipio.Visible = False + DdlComExtColonia.Visible = False + + TxtComExtMunicipio.Visible = True + TxtComExtColonia.Visible = True + End If + End If + + End Sub + Protected Sub DdlMunicipio_SelectedIndexChanged(sender As Object, e As EventArgs) + CargaColonia() + End Sub + Private Sub BtnComExtConvertirUnidad_Click(sender As Object, e As EventArgs) Handles BtnComExtConvertirUnidad.Click + For Each gvr As GridViewRow In GvComercioExterior.Rows + gvr.FCTextBox("TxtCantidad").Text = (gvr.FCTextBox("TxtCantidad").Text.ToDecimal * TxtComExtConvertir.Text.ToDecimal).ToString + gvr.FCTextBox("TxtValorUnitario").Text = (gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal / TxtComExtConvertir.Text.ToDecimal).ToString + Next + End Sub +#End Region + + Private Sub BtnFolioFiscalAsignar_Click(sender As Object, e As EventArgs) Handles BtnFolioFiscalAsignar.Click + Dim ObjVentas As New ClsVentas() + If ObjVentas.UpdateVentaFolioFiscal(TxtModalFolioFiscal.Text.Trim, CveVenta, UsuarioActual.CveEmpresa) Then + Alert("Folio asignado", TipoMensaje.MsgInformacion) + RegistraScript("$('#ModalFolioFiscal').modal('hide')") + End If + ObjVentas.Dispose() + End Sub + +#Region "FORMATO CICOVISA" + Protected Sub LnkImprimirFormatoCicovisa_Click(sender As Object, e As EventArgs) + Dim ObjVentas As New ClsVentas + Dim ObjInventario As New ClsInventarios + Dim SerieFolio As String = "" + Dim PedidoContrato As String = "" + Dim EnvioContacto As String = "" + Dim EnvioDireccion As String = "" + Dim Guia As String = "" + If ObjInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + If ObjInventario.DtResultados.Rows.Count > 0 Then + Guia = ObjInventario.DtResultados.Rows(0)("Guia").ToString + End If + End If + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + SerieFolio = ObjVentas.DtResultados.Rows(0)("SerieFolio").ToString + PedidoContrato = ObjVentas.DtResultados.Rows(0)("PedidoContrato").ToString + EnvioContacto = ObjVentas.DtResultados.Rows(0)("EnvioContacto").ToString + EnvioDireccion = $"{ObjVentas.DtResultados.Rows(0)("EnvioDireccion").ToString}, NO. EXT: {ObjVentas.DtResultados.Rows(0)("EnvioNoExt").ToString}, COLONIA: {ObjVentas.DtResultados.Rows(0)("EnvioColonia").ToString}, CP: {ObjVentas.DtResultados.Rows(0)("EnvioCP").ToString}" + End If + End If + Dim Dt As DataTable = Nothing + If ObjVentas.GetVentaDetalle(CveVenta) Then + Dt = ObjVentas.DtResultados + End If + ObjVentas.Dispose() + ObjInventario.Dispose() + If Dt.Rows.Count > 0 Then + Dim params As New List(Of ReportParameter) + params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) + params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) + params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) + params.Add(New ReportParameter("EnvioContacto", EnvioContacto)) + params.Add(New ReportParameter("SerieFolio", SerieFolio)) + params.Add(New ReportParameter("PedidoContrato", PedidoContrato)) + params.Add(New ReportParameter("EnvioDireccion", EnvioDireccion)) + params.Add(New ReportParameter("Guia", Guia)) + ImprimirPDF("Empresas/Grales/Formatos/Cicovisa.rdlc", Dt, params, String.Format("Formato Cicovisa -{0}", Now.ToDateTime.ToShortDateString)) + End If + End Sub +#End Region + +#Region "REQUIERE OC" + Protected Sub btnBuscarOCRegistrada_Click(sender As Object, e As EventArgs) + Dim ObjVentas As New ClsVentas + + If CveCliente > 0 AndAlso TxtOrdenCompra.Text.Trim <> "" AndAlso CveVenta <= 0 Then + If ObjVentas.GetOCVentas(CveCliente, TxtOrdenCompra.Text) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + Alert("Ya existen ventas con el mismo folio de orden de compra registrado", TipoMensaje.MsgAdvertencia) + End If + End If + End If + ObjVentas.Dispose() + End Sub +#End Region + +#Region "CLASIFICACIONES DETALLES" + Protected Sub DdlClasificacionPS_SelectedIndexChanged(sender As Object, e As EventArgs) + CargaClasificacionesDetalles() + End Sub + Protected Sub BtnAddClasificacionDetalle_Click(sender As Object, e As EventArgs) + TxtClasificacionDetalle.Text = "" + DdlClasificacionModal.SelectedValueExist(DdlClasificacionPS.SelectedValue) + UpModal.Update() + RegistraScript(String.Format("$('#{0}').modal('show');", "DModalClasificacion")) + End Sub + Protected Sub BtnAddClasificacionDetalleModal_Click(sender As Object, e As EventArgs) + Dim ObjVentas As New ClsVentas + If ObjVentas.AddClasificacionDetalle(TxtClasificacionDetalle.Text, DdlClasificacionModal.SelectedValue.ToEntero, + UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then + CargaClasificacionesDetalles() + DdlTipo.SelectedValueExist(ObjVentas.CveClasificacionDetalle) + UpAddPS.Update() + RegistraScript(String.Format("$('#{0}').modal('hide');", "DModalClasificacion"), "1") + RegistraScript("CreaDescripcionPS();", "2") + End If + ObjVentas.Dispose() + End Sub + + Private Sub GVAnticipos_PageIndexChanged(sender As Object, e As EventArgs) Handles GVAnticipos.PageIndexChanged + + End Sub + + Private Sub DdlTipoAmortizacionAnticipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoAmortizacionAnticipo.SelectedIndexChanged + divAnticipoMsg.Visible = False + If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("1", "2") Then + 'cuando es amortización por descuento, debe tener seleccionado descuentos previamente registrados + If DdlTipoAmortizacionAnticipo.SelectedValue = "1" AndAlso LblDescuentos.Text.ToDecimal <= 0 Then + divAnticipoMsg.Visible = True + + End If + + If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then DivConceptoNC.Visible = True Else DivConceptoNC.Visible = False + + DdlTipoRelacion.SelectedValueExist("7") + Else + DivConceptoNC.Visible = False + DdlTipoRelacion.SelectedValueExist("-1") + End If + + End Sub + + Private Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMetodoPago33.SelectedIndexChanged + CambiaMetodoPago33() + End Sub + Private Sub CambiaMetodoPago33() + CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) + + End Sub + +#End Region -#Region " COTIZACIONES - EDITAR " - Private Sub BtnPermisoEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarCotizacion.Click - ModalidadEdicion = True - - 'ACTIVA BOTONES PARA EDITAR - For Each Row As GridViewRow In GvPS.Rows - Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString() - Next - GvPS.Columns(ColumnaEditar).HeaderText = "Editar" - GvPS.Columns(ColumnaEliminar).HeaderText = "Eliminar" - GvPS.DataSource = TmpDT - GvPS.DataBind() - - 'PORLET CLIENTE - 'ACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto") - TxtCodigo.ReadOnly = False - ChkEnviarFactura.Enabled = True - DdlSucursalCliente.Enabled = True - ChkDireccionEnvio.Enabled = True - DdlDireccionEnvio.Enabled = True - TxtAtencionA.Enabled = True - TxtFechaVencimientoCotizacion.Enabled = True - - 'BOTONERA - BtnGenerarRemision.Visible = False - BtnCrearApartirDe.Visible = False - BtnEmitirImprimir.Visible = False - BtnGenerarOS.Visible = False - - TxtCantidad.Enabled = True - DdlClasificacion.Enabled = True - DdlPS.Enabled = True - TxtObsPS.Enabled = True - DdlProyecto.Enabled = True - DdlSubProyecto.Enabled = True - TxtPrecio.Enabled = True - LbAgregar.Enabled = True - LnkAgregarPyME.Enabled = True - ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") - LblSubTotal1.Text = TxtSubTotal.Text - LblAmort.Text = TxtSubTotal.Text - TxtTiempoEntrega.Enabled = True - DdlVendedor.Enabled = True - - TxtObsFact.Enabled = True - TxtMotivoDescuento.Enabled = True - BtnEditarCotizacion.Visible = True - BtnPermisoEditarCotizacion.Visible = False - - DdlFormaPago33.Enabled = True - DdlUsoCFDI.Enabled = True - - DdlMetodoPago33.Enabled = True - 'TxtNumCtaPago.Enabled = True - DdlMoneda.Enabled = True - TxtPedidoContrato.Enabled = True - TxtOrdenCompra.Enabled = True - - If DdlMoneda.SelectedValue = "2" Then - TrConversionTipoCambio.Visible = True - End If - ChkConvertirDoctoPesos.Enabled = True - TxtTipoCambio.Enabled = True - TxtTotal.ReadOnly = False - TxtTotal.Attributes("readonly") = "readonly" - - RBLPago.Enabled = True - RBLPago.Items(0).Enabled = True - - GvImpuestosLocales2.Enabled = True - - - UpPS.Update() - UPPDescuento.Update() - UPObservaciones.Update() - UPCondicionesPago.Update() - UpCliente.Update() - - End Sub - Private Sub BtnEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnEditarCotizacion.Click - - 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 - - Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero - Dim TipoCambio As Double = TxtTipoCambio.Text.Trim.ToDecimal - If DdlMoneda.SelectedValue.ToEntero <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then - TipoCambio = 1 - Moneda = 1 - End If - - Dim ObjVentas As New ClsVentas - Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) - Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) - Dim OcurrioError = False - Dim MensajeError = "" - - - 'ACTUALIZA VENTA - If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), LblDescuentos.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtIVA.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtIEPS.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtTotal.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), - Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, - UsuarioActual.CveEmpresa, CveVenta, 0, 0, - Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1), - PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero, - CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal, - TipoDocto:=DdlTipoComprobante.SelectedValue) Then - MensajeError = "Ocurrió un error al actualizar la información de la cotización" - OcurrioError = True - End If - - 'ELIMINA DETALLES - If Not ObjVentas.RemoveVentasDetalle(CveVenta) Then - MensajeError = "Ocurrió un error al actualizar las partidas de la cotización" - OcurrioError = True - End If - - 'RE-INSERTA DETALLES - For Each Row As DataRow In TmpDT.Rows - If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, - Row("PU").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)))), 6), - Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, - PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, IEPS:=Row("IEPS").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString) Then - MensajeError = "Ocurrió un error al guardar las partidas de la cotización" - OcurrioError = True - Exit For - End If - Next - - For Each gvr As GridViewRow In GvImpuestosLocales2.Rows - If gvr.RowType = DataControlRowType.DataRow Then - If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble) Then - MensajeError = "Ocurrió un error al actualizar los impuestos locales" - OcurrioError = True - End If - End If - Next - - 'ORDEN PRODUCCION - If UsuarioActual.CveEmpresa.Contiene(126) Then - If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then - If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then - MensajeError = "Ocurrió un error al actualizar la orden de producción" - OcurrioError = True - End If - End If - End If - +#Region " COTIZACIONES - EDITAR " + Private Sub BtnPermisoEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarCotizacion.Click + ModalidadEdicion = True + + 'ACTIVA BOTONES PARA EDITAR + For Each Row As GridViewRow In GvPS.Rows + Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString() + Next + GvPS.Columns(ColumnaEditar).HeaderText = "Editar" + GvPS.Columns(ColumnaEliminar).HeaderText = "Eliminar" + GvPS.DataSource = TmpDT + GvPS.DataBind() + + 'PORLET CLIENTE + 'ACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto") + TxtCodigo.ReadOnly = False + ChkEnviarFactura.Enabled = True + DdlSucursalCliente.Enabled = True + ChkDireccionEnvio.Enabled = True + DdlDireccionEnvio.Enabled = True + TxtAtencionA.Enabled = True + TxtFechaVencimientoCotizacion.Enabled = True + + 'BOTONERA + BtnGenerarRemision.Visible = False + BtnCrearApartirDe.Visible = False + BtnEmitirImprimir.Visible = False + BtnGenerarOS.Visible = False + + TxtCantidad.Enabled = True + DdlClasificacion.Enabled = True + DdlPS.Enabled = True + TxtObsPS.Enabled = True + DdlProyecto.Enabled = True + DdlSubProyecto.Enabled = True + TxtPrecio.Enabled = True + LbAgregar.Enabled = True + LnkAgregarPyME.Enabled = True + ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") + LblSubTotal1.Text = TxtSubTotal.Text + LblAmort.Text = TxtSubTotal.Text + TxtTiempoEntrega.Enabled = True + DdlVendedor.Enabled = True + + TxtObsFact.Enabled = True + TxtMotivoDescuento.Enabled = True + BtnEditarCotizacion.Visible = True + BtnPermisoEditarCotizacion.Visible = False + + DdlFormaPago33.Enabled = True + DdlUsoCFDI.Enabled = True + + DdlMetodoPago33.Enabled = True + 'TxtNumCtaPago.Enabled = True + DdlMoneda.Enabled = True + TxtPedidoContrato.Enabled = True + TxtOrdenCompra.Enabled = True + + If DdlMoneda.SelectedValue = "2" Then + TrConversionTipoCambio.Visible = True + End If + ChkConvertirDoctoPesos.Enabled = True + TxtTipoCambio.Enabled = True + TxtTotal.ReadOnly = False + TxtTotal.Attributes("readonly") = "readonly" + + RBLPago.Enabled = True + RBLPago.Items(0).Enabled = True + + GvImpuestosLocales2.Enabled = True + + + UpPS.Update() + UPPDescuento.Update() + UPObservaciones.Update() + UPCondicionesPago.Update() + UpCliente.Update() + + End Sub + Private Sub BtnEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnEditarCotizacion.Click + + 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 + + Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero + Dim TipoCambio As Double = TxtTipoCambio.Text.Trim.ToDecimal + If DdlMoneda.SelectedValue.ToEntero <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then + TipoCambio = 1 + Moneda = 1 + End If + + Dim ObjVentas As New ClsVentas + Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) + Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) + Dim OcurrioError = False + Dim MensajeError = "" + + + 'ACTUALIZA VENTA + If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), LblDescuentos.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtIVA.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtIEPS.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtTotal.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), + Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, + UsuarioActual.CveEmpresa, CveVenta, 0, 0, + Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1), + PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero, + CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal, + TipoDocto:=DdlTipoComprobante.SelectedValue) Then + MensajeError = "Ocurrió un error al actualizar la información de la cotización" + OcurrioError = True + End If + + 'ELIMINA DETALLES + If Not ObjVentas.RemoveVentasDetalle(CveVenta) Then + MensajeError = "Ocurrió un error al actualizar las partidas de la cotización" + OcurrioError = True + End If + + 'RE-INSERTA DETALLES + For Each Row As DataRow In TmpDT.Rows + If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, + Row("PU").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)))), 6), + Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, + PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, IEPS:=Row("IEPS").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString) Then + MensajeError = "Ocurrió un error al guardar las partidas de la cotización" + OcurrioError = True + Exit For + End If + Next + + For Each gvr As GridViewRow In GvImpuestosLocales2.Rows + If gvr.RowType = DataControlRowType.DataRow Then + If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble) Then + MensajeError = "Ocurrió un error al actualizar los impuestos locales" + OcurrioError = True + End If + End If + Next + + 'ORDEN PRODUCCION + If UsuarioActual.CveEmpresa.Contiene(126) Then + If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then + If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then + MensajeError = "Ocurrió un error al actualizar la orden de producción" + OcurrioError = True + End If + End If + End If + If ObjConta.ValidacionPrePolizaCuadre(-1, 2, CveVenta) Then If ObjConta.ValorPolizaDescuadre > 0 Then If ObjConta.ValorPolizaDescuadre = 2 Then @@ -21724,1577 +21731,1577 @@ Partial Class Ventas MensajeError = ObjConta.MensajePolizaDescuadre End If End If - End If - - If OcurrioError Then - ObjVentas.RollBack() - Alert($"{MensajeError}. Por favor vuelva a intentar.", TipoMensaje.MsgError) - Else - ObjVentas.Commit() - - 'ELIMINA PDF VIEJO - Dim ArchivoPDF = New System.IO.FileInfo(String.Format("{0}PDF\{1}\{2}-{3}.pdf", UsuarioActual.Empresa.Ruta, DdlTipoComprobante.SelectedValue, Serie, Folio)) - If ArchivoPDF.Exists Then - ArchivoPDF.Delete() - End If - 'GENERA PDF NUEVO - GeneraPDFCotizacion(ChkEnviarFactura.Checked) - - Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta & "&&Tipo=Cot"";") - End If - - ObjVentas.Dispose() - ObjConta.Dispose() - ObjCGame.Dispose() + End If + + If OcurrioError Then + ObjVentas.RollBack() + Alert($"{MensajeError}. Por favor vuelva a intentar.", TipoMensaje.MsgError) + Else + ObjVentas.Commit() + + 'ELIMINA PDF VIEJO + Dim ArchivoPDF = New System.IO.FileInfo(String.Format("{0}PDF\{1}\{2}-{3}.pdf", UsuarioActual.Empresa.Ruta, DdlTipoComprobante.SelectedValue, Serie, Folio)) + If ArchivoPDF.Exists Then + ArchivoPDF.Delete() + End If + 'GENERA PDF NUEVO + GeneraPDFCotizacion(ChkEnviarFactura.Checked) + + Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta & "&&Tipo=Cot"";") + End If + + ObjVentas.Dispose() + ObjConta.Dispose() + ObjCGame.Dispose() End Sub -#End Region +#End Region -#Region " COTIZACIONES - SIN FACTURAR " - Private Sub LnkCotizaciones_Click(sender As Object, e As EventArgs) Handles LnkCotizaciones.Click - If ChkCotProductos.Checked Then - CargaCotizacionesxProducto() - Else - CargaCotizaciones() - End If - RegistraScript("$('#DivCotizaciones').modal('show');") - End Sub - Private Sub BtnConsultarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnConsultarCotizaciones.Click - If ChkCotProductos.Checked Then - CargaCotizacionesxProducto() - Else - CargaCotizaciones() - End If - End Sub - Private Sub ChkCotProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkCotProductos.CheckedChanged - If ChkCotProductos.Checked Then - GvCotPS.Visible = True - GvCot.Visible = False - DivFiltroCotPS.Visible = True - DivFiltroCot.Visible = False - GvCot.DataSource = Nothing - GvCot.DataBind() - CargaCotizacionesxProducto() - Else - GvCotPS.Visible = False - GvCot.Visible = True - DivFiltroCotPS.Visible = False - DivFiltroCot.Visible = True - GvCotPS.DataSource = Nothing - GvCotPS.DataBind() - CargaCotizaciones() - End If - End Sub - Private Sub CargaCotizaciones() - Dim ObjVentas As New ClsVentas - - If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 1) Then - DtCotizaciones = ObjVentas.DtResultados - - If Not DtCotizaciones.Columns.Contains("Aplicado") Then - DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) - End If - - GvCot.DataSource = DtCotizaciones - End If - ObjVentas.Dispose() - GvCot.DataBind() - UpCotizacionesFacturas.Update() - End Sub - - Private Sub CargaCotizacionesxProducto() - Dim ObjVentas As New ClsVentas - If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 2) Then - DtCotizaciones = ObjVentas.DtResultados - - If Not DtCotizaciones.Columns.Contains("Aplicado") Then - DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) - End If - - GvCotPS.DataSource = DtCotizaciones.FiltraParametros("Cantidad > 0") - End If - ObjVentas.Dispose() - GvCotPS.DataBind() - UpCotizacionesFacturas.Update() - End Sub - - Protected Sub BtnGuardarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnGuardarCotizaciones.Click - - If GvCot.Rows.Count = 0 And GvCotPS.Rows.Count = 0 Then - Alert("Debe existir por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'MARCA LAS SELECCIONADAS - VerificaCotizaciones(DtCotizaciones) - Dim DTSeleccionadas = DtCotizaciones.FiltraParametros("Aplicado = True") - - If DTSeleccionadas.Rows.Count = 0 Then - Alert("Debe seleccionar por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - - If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then - Alert("Solo debe seleccionar cotizaciones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") - DdlMoneda.Enabled = False - CambiaMoneda() - - 'LIMPIA LAS PARTIDAS ACTUALES - If GvPS.Rows.Count > 0 Then - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtIEPS.Text = "0.00" - TxtRetISR.Text = "0.00" - TxtRetIVA.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = "0.00" - End If - - Dim Cves As New StringBuilder - Dim CveMetodoPago As Integer = -1 - Dim MetodoPagoDif As Boolean = False - If ChkCotProductos.Checked Then - For Each row As DataRow In DTSeleccionadas.Rows - If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then - MetodoPagoDif = True - End If - CveMetodoPago = row("CveMetodoPago33").ToString.ToEntero - Cves.Append($"{row("CveVentaDetalle").ToString},") - Next - For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows - CotizacionesLista.Add(row("CveVenta").ToString.ToEntero) - Next - Else - For Each row As DataRow In DTSeleccionadas.Rows - If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then - MetodoPagoDif = True - End If - Cves.Append($"{row("CveVenta").ToString},") - CotizacionesLista.Add(row("CveVenta").ToString.ToEntero) - CveMetodoPago = row("CveMetodoPago33").ToString.ToEntero - Next - End If - - If MetodoPagoDif Then - Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia) - End If - - Cves.Remove(Cves.Length - 1, 1) - Dim ObjClientes As New ClsClientes - If ObjClientes.GetVentasCotizacionesTotales(CveCliente, Cves.ToString, If(ChkCotProductos.Checked, 2, 1)) Then - DtCotizacionesPS = ObjClientes.DtResultados - End If - ObjClientes.Dispose() - - If Not AgregaPSCotizacion() Then - Alert("Ocurrió un error validar las partidas de las cotizaciones seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'BtnEmitirImprimir.Text = "Facturar" - Dim CveTipoDocto = DdlTipoComprobante.SelectedValue - DdlTipoComprobante.Items.Clear() - DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) - DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) - DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem")) - DdlTipoComprobante.SelectedIndex = 0 - DdlTipoComprobante.SelectedValueExist(CveTipoDocto) - CambiaTipoComprobante() - 'DdlTipoComprobante.Enabled = False - - UpRemisionesFacturas.Update() - UpFacturar.Update() - UpPS.Update() - UpParametros.Update() - - RegistraScript("$('#DivCotizaciones').modal('hide');") - - End Sub - Private Sub VerificaCotizaciones(ByRef dt As DataTable) - If ChkCotProductos.Checked Then - For Each Gvr As GridViewRow In GvCotPS.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero - Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - Next - Else - For Each Gvr As GridViewRow In GvCot.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero - Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - Next - End If - End Sub - Private Function IndiceGVCotDataKey(GridView As GridView, DataKeyValue As String) As Integer - For Each row As GridViewRow In GridView.Rows - If row.DataKey("CveVentaDetalle") = DataKeyValue Then - Return row.RowIndex - End If - Next - Return Nothing - End Function - Private Function AgregaPSCotizacion() As Boolean - If DtCotizacionesPS IsNot Nothing Then - Dim tCantidad As Decimal = 0 - For Each Dr As DataRow In DtCotizacionesPS.Select() - tCantidad = If(ChkCotProductos.Checked, GvCotPS.Rows(IndiceGVCotDataKey(GvCotPS, Dr("CveVentaDetalle").ToString)).FCTextBox("TxtCantidadCot").Text.ToDecimal, Dr("Cantidad")).ToString.ToDecimal - AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, - Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, - Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, - CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveVentaDetalleCotizacion:=Dr("CveVentaDetalle").ToString.ToEntero) - Next - CalculaTotalesVenta() - Return True - Else - Return False - End If +#Region " COTIZACIONES - SIN FACTURAR " + Private Sub LnkCotizaciones_Click(sender As Object, e As EventArgs) Handles LnkCotizaciones.Click + If ChkCotProductos.Checked Then + CargaCotizacionesxProducto() + Else + CargaCotizaciones() + End If + RegistraScript("$('#DivCotizaciones').modal('show');") + End Sub + Private Sub BtnConsultarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnConsultarCotizaciones.Click + If ChkCotProductos.Checked Then + CargaCotizacionesxProducto() + Else + CargaCotizaciones() + End If + End Sub + Private Sub ChkCotProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkCotProductos.CheckedChanged + If ChkCotProductos.Checked Then + GvCotPS.Visible = True + GvCot.Visible = False + DivFiltroCotPS.Visible = True + DivFiltroCot.Visible = False + GvCot.DataSource = Nothing + GvCot.DataBind() + CargaCotizacionesxProducto() + Else + GvCotPS.Visible = False + GvCot.Visible = True + DivFiltroCotPS.Visible = False + DivFiltroCot.Visible = True + GvCotPS.DataSource = Nothing + GvCotPS.DataBind() + CargaCotizaciones() + End If + End Sub + Private Sub CargaCotizaciones() + Dim ObjVentas As New ClsVentas + + If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 1) Then + DtCotizaciones = ObjVentas.DtResultados + + If Not DtCotizaciones.Columns.Contains("Aplicado") Then + DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) + End If + + GvCot.DataSource = DtCotizaciones + End If + ObjVentas.Dispose() + GvCot.DataBind() + UpCotizacionesFacturas.Update() + End Sub + + Private Sub CargaCotizacionesxProducto() + Dim ObjVentas As New ClsVentas + If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 2) Then + DtCotizaciones = ObjVentas.DtResultados + + If Not DtCotizaciones.Columns.Contains("Aplicado") Then + DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) + End If + + GvCotPS.DataSource = DtCotizaciones.FiltraParametros("Cantidad > 0") + End If + ObjVentas.Dispose() + GvCotPS.DataBind() + UpCotizacionesFacturas.Update() + End Sub + + Protected Sub BtnGuardarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnGuardarCotizaciones.Click + + If GvCot.Rows.Count = 0 And GvCotPS.Rows.Count = 0 Then + Alert("Debe existir por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'MARCA LAS SELECCIONADAS + VerificaCotizaciones(DtCotizaciones) + Dim DTSeleccionadas = DtCotizaciones.FiltraParametros("Aplicado = True") + + If DTSeleccionadas.Rows.Count = 0 Then + Alert("Debe seleccionar por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + + If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then + Alert("Solo debe seleccionar cotizaciones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") + DdlMoneda.Enabled = False + CambiaMoneda() + + 'LIMPIA LAS PARTIDAS ACTUALES + If GvPS.Rows.Count > 0 Then + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtIEPS.Text = "0.00" + TxtRetISR.Text = "0.00" + TxtRetIVA.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = "0.00" + End If + + Dim Cves As New StringBuilder + Dim CveMetodoPago As Integer = -1 + Dim MetodoPagoDif As Boolean = False + If ChkCotProductos.Checked Then + For Each row As DataRow In DTSeleccionadas.Rows + If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then + MetodoPagoDif = True + End If + CveMetodoPago = row("CveMetodoPago33").ToString.ToEntero + Cves.Append($"{row("CveVentaDetalle").ToString},") + Next + For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows + CotizacionesLista.Add(row("CveVenta").ToString.ToEntero) + Next + Else + For Each row As DataRow In DTSeleccionadas.Rows + If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then + MetodoPagoDif = True + End If + Cves.Append($"{row("CveVenta").ToString},") + CotizacionesLista.Add(row("CveVenta").ToString.ToEntero) + CveMetodoPago = row("CveMetodoPago33").ToString.ToEntero + Next + End If + + If MetodoPagoDif Then + Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia) + End If + + Cves.Remove(Cves.Length - 1, 1) + Dim ObjClientes As New ClsClientes + If ObjClientes.GetVentasCotizacionesTotales(CveCliente, Cves.ToString, If(ChkCotProductos.Checked, 2, 1)) Then + DtCotizacionesPS = ObjClientes.DtResultados + End If + ObjClientes.Dispose() + + If Not AgregaPSCotizacion() Then + Alert("Ocurrió un error validar las partidas de las cotizaciones seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'BtnEmitirImprimir.Text = "Facturar" + Dim CveTipoDocto = DdlTipoComprobante.SelectedValue + DdlTipoComprobante.Items.Clear() + DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) + DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) + DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem")) + DdlTipoComprobante.SelectedIndex = 0 + DdlTipoComprobante.SelectedValueExist(CveTipoDocto) + CambiaTipoComprobante() + 'DdlTipoComprobante.Enabled = False + + UpRemisionesFacturas.Update() + UpFacturar.Update() + UpPS.Update() + UpParametros.Update() + + RegistraScript("$('#DivCotizaciones').modal('hide');") + + End Sub + Private Sub VerificaCotizaciones(ByRef dt As DataTable) + If ChkCotProductos.Checked Then + For Each Gvr As GridViewRow In GvCotPS.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero + Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + Next + Else + For Each Gvr As GridViewRow In GvCot.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero + Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + Next + End If + End Sub + Private Function IndiceGVCotDataKey(GridView As GridView, DataKeyValue As String) As Integer + For Each row As GridViewRow In GridView.Rows + If row.DataKey("CveVentaDetalle") = DataKeyValue Then + Return row.RowIndex + End If + Next + Return Nothing + End Function + Private Function AgregaPSCotizacion() As Boolean + If DtCotizacionesPS IsNot Nothing Then + Dim tCantidad As Decimal = 0 + For Each Dr As DataRow In DtCotizacionesPS.Select() + tCantidad = If(ChkCotProductos.Checked, GvCotPS.Rows(IndiceGVCotDataKey(GvCotPS, Dr("CveVentaDetalle").ToString)).FCTextBox("TxtCantidadCot").Text.ToDecimal, Dr("Cantidad")).ToString.ToDecimal + AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, + Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, + Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, + CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveVentaDetalleCotizacion:=Dr("CveVentaDetalle").ToString.ToEntero) + Next + CalculaTotalesVenta() + Return True + Else + Return False + End If End Function -#End Region +#End Region -#Region " COTIZACIONES - FACTURAR " - Private Function PreparaFacturarCotizacion() As Boolean - 'LIMPIAMOS - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtIEPS.Text = "0.00" - TxtRetIVA.Text = "0.00" - TxtRetISR.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = TxtIVA.Text - CreaDTVentas() - - If CveEmpresaCRM > 0 And CveAcercamientoCRM > 0 And Not CveCliente > 0 Then - Alert(String.Format("La Empresa CRM no tiene un Cliente vinculado. Por favor verifique y vuelva a intentar.

    - Crear Cliente
    ", CveEmpresaCRM), TipoMensaje.MsgAdvertencia) - Return False - End If - - Dim ObjClientes As New ClsClientes - If ObjClientes.GetVentasCotizacionesTotales(CveCliente, CveVenta.ToString, 1) Then - DtCotizacionesPS = ObjClientes.DtResultados - End If - ObjClientes.Dispose() - - If Not AgregaPSCotizacion() Then - Alert("Ocurrió un error al agregar los conceptos de la cotización. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Return False - End If - - If TmpDT.Rows.Count = 0 Then - Alert("No hay conceptos por facturar de esta cotización o ha sido cambiada su información. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Return False - End If - - Return True +#Region " COTIZACIONES - FACTURAR " + Private Function PreparaFacturarCotizacion() As Boolean + 'LIMPIAMOS + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtIEPS.Text = "0.00" + TxtRetIVA.Text = "0.00" + TxtRetISR.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = TxtIVA.Text + CreaDTVentas() + + If CveEmpresaCRM > 0 And CveAcercamientoCRM > 0 And Not CveCliente > 0 Then + Alert(String.Format("La Empresa CRM no tiene un Cliente vinculado. Por favor verifique y vuelva a intentar.

    + Crear Cliente
    ", CveEmpresaCRM), TipoMensaje.MsgAdvertencia) + Return False + End If + + Dim ObjClientes As New ClsClientes + If ObjClientes.GetVentasCotizacionesTotales(CveCliente, CveVenta.ToString, 1) Then + DtCotizacionesPS = ObjClientes.DtResultados + End If + ObjClientes.Dispose() + + If Not AgregaPSCotizacion() Then + Alert("Ocurrió un error al agregar los conceptos de la cotización. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Return False + End If + + If TmpDT.Rows.Count = 0 Then + Alert("No hay conceptos por facturar de esta cotización o ha sido cambiada su información. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Return False + End If + + Return True End Function -#End Region +#End Region -#Region " REMISIONES - SIN FACTURAR " - Protected Sub ChkCanRem_CheckedChanged(sender As Object, e As EventArgs) - If ChkCanRem.Checked Then - DivGvCancelarRemision.Visible = True - Else - DivGvCancelarRemision.Visible = False - End If - UpCancelarDocumento.Update() - End Sub - Private Sub LnkRemisiones_Click(sender As Object, e As EventArgs) Handles LnkRemisiones.Click - Dim ObjContratos As New ClsContratos - - If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1) Then - DdlFiltroContrato.DataSource = ObjContratos.DtResultados - DdlFiltroContrato.DataBind() - DdlFiltroContrato.Items.Insert(0, New ListItem("Remisiones sin Contrato", "-1")) - End If - - DdlFiltroRemMoneda.Items.Clear() - DdlFiltroRemMoneda.DataSource = GlobalDTMonedas - DdlFiltroRemMoneda.DataBind() - DdlFiltroRemMoneda.Items.Insert(0, New ListItem("Todas", "-1")) - - GvContratoDetalles.DataSource = Nothing - GvContratoDetalles.DataBind() - UpContratos.Update() - - DivEstimaciones.Visible = True - ContratoDetalles.Visible = False - UPEstimaciones.Update() - - Tab.ActiveTab = TabGenerales - TabGenerales.Enabled = True - Updatetabs.Update() - - If ChkRemProductos.Checked Then - CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - Else - CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - End If - RegistraScript("$('#DivRemisiones').modal('show');") - End Sub - Private Sub BtnConsultarRem_Click(sender As Object, e As EventArgs) Handles BtnConsultarRem.Click - If ChkRemProductos.Checked Then - CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - Else - CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - End If - End Sub - Private Sub ChkRemProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkRemProductos.CheckedChanged - If ChkRemProductos.Checked Then - GvRemPS.Visible = True - GvRem.Visible = False - DivFiltroRemPS.Visible = True - DivFiltroRem.Visible = False - GvRem.DataSource = Nothing - GvRem.DataBind() - CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - Else - GvRemPS.Visible = False - GvRem.Visible = True - DivFiltroRemPS.Visible = False - DivFiltroRem.Visible = True - GvRemPS.DataSource = Nothing - GvRemPS.DataBind() - CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - End If - End Sub - Private Sub DdlFiltroContrato_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroContrato.SelectedIndexChanged - If ChkRemProductos.Checked Then - CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - Else - CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - End If - End Sub - Private Sub DdlFiltroRemMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroRemMoneda.SelectedIndexChanged - If ChkRemProductos.Checked Then - CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - Else - CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) - End If - End Sub - Private Sub CargaRemisiones(CveContrato As Integer, CveMoneda As Integer) - Dim ObjVentas As New ClsVentas - If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 1, CveMoneda) Then - If CveContrato = -1 Then - DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0") - Else - DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}") - End If - If Not DTRemisiones.Columns.Contains("Aplicado") Then - DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) - End If - GvRem.DataSource = DTRemisiones - End If - ObjVentas.Dispose() - - GvRem.DataBind() - UpRemisionesFacturas.Update() - End Sub - Private Sub CargaRemisionesxProducto(CveContrato As Integer, CveMoneda As Integer) - Dim ObjVentas As New ClsVentas - If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 2, CveMoneda) Then - If CveContrato = -1 Then - DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0") - Else - DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}") - End If - If Not DTRemisiones.Columns.Contains("Aplicado") Then - DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) - End If - GvRemPS.DataSource = DTRemisiones - End If - ObjVentas.Dispose() - - GvRemPS.DataBind() - UpRemisionesFacturas.Update() - End Sub - Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblTipo.SelectedIndexChanged - HuboCambioRemi = Not HuboCambioRemi - End Sub - Protected Sub BtnGuardarRemisiones_Click(sender As Object, e As EventArgs) Handles BtnGuardarRemisiones.Click - If GvRem.Rows.Count > 0 Or GvRemPS.Rows.Count > 0 Then - 'Checa las facturas selecionadas - VerificaRemisiones(DTRemisiones) - - Dim dtSeleccionadas As DataTable = DTRemisiones.FiltraParametros("Aplicado = True") - Dim CveContrato = DTRemisiones.FiltroPrimeroValor("CveContrato", "Aplicado = True").ToEntero - - If dtSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then - Alert("Solo debe seleccionar remisiones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{dtSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") - DdlMoneda.Enabled = False - CambiaMoneda() - DdlUsoCFDI.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) - DdlMetodoPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) - CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) - DdlFormaPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveFormaPago")) - - 'validación, cuando las remisiones sean de una sucursal y el usuario solo tenga acceso a otra, deberá tener priodidad la sucursal de la que solo se factura - If DdlSubProyectoDatos.Enabled = True Then - DdlSubProyectoDatos.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveSubProyecto")) - End If - DdlSucursalCliente.SelectedValueExist(If(dtSeleccionadas.FiltroPrimeroValor("CveClienteSucursal").ToEntero > 0, dtSeleccionadas.FiltroPrimeroValor("CveClienteSucursal"), "-1")) - DdlVendedor.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveVendedor")) - - CambiaSucursalGeneral() - CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero) - - DdlUsoCFDI.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) - DdlMetodoPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) - CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) - DdlFormaPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveFormaPago")) - - If GvPS.Rows.Count > 0 Then - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = TxtIVA.Text - End If - - RBLPago.Items(0).Enabled = True 'sino está activo lo activamos porque las remisiones pueden ser a crédito - RBLPago.SelectedValue = "1" - - RemisionesLista.Clear() - - If dtSeleccionadas.Rows.Count > 0 Then - Select Case RblTipo.SelectedValue - Case "1" 'T O T A L G E N E R A L - - For Each row As DataRow In dtSeleccionadas.Rows - RemisionesLista.Add(row("CveVenta").ToString.ToEntero) - Next - - IsTotalxConcepto = False - Dim PU As Decimal = dtSeleccionadas.SUM("SubTotal").ToDecimal - Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa)(0) - Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16) - Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa)(0) - - AgregarProductoServicio(1, PS("CveUM").ToString.ToEntero, PS("UnidadMedida").ToString, PS("CveClasificacion").ToString.ToEntero, - PS("Clasificacion").ToString, PS("CvePS").ToString.ToEntero, PS("PS").ToString, "", PU, 0, - rowSP("CveProyecto").ToString.ToEntero, rowSP("Proyecto").ToString, rowSP("CveSubProyecto").ToString.ToEntero, rowSP("SubProyecto").ToString, RegeneraIEPS:=True) - - Case "2" 'T O T A L X R E M I S I O N - - For Each row As DataRow In dtSeleccionadas.Rows - RemisionesLista.Add(row("CveVenta").ToString.ToEntero) - Next - - Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa)(0) - Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa)(0) - Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16) - For Each gvr As GridViewRow In GvRem.Rows - If gvr.FCCheckBox("Chk").Checked Then - AgregarProductoServicio(1, PS("CveUM").ToString.ToEntero, PS("UnidadMedida").ToString, PS("CveClasificacion").ToString.ToEntero, - PS("Clasificacion").ToString, PS("CvePS").ToString.ToEntero, PS("PS").ToString, "", gvr.DataKey("SubTotal").ToString.ToDecimal, 0, - rowSP("CveProyecto").ToString.ToEntero, rowSP("Proyecto").ToString, rowSP("CveSubProyecto").ToString.ToEntero, rowSP("SubProyecto").ToString, RegeneraIEPS:=True) - End If - Next - - Case "3" 'T O T A L X C O N C E P T O - - IsTotalxConcepto = True - Dim sb As New StringBuilder - If ChkRemProductos.Checked Then - For Each row As DataRow In dtSeleccionadas.Rows - sb.Append($"{row("CveVentaDetalle").ToString},") - Next - For Each row As DataRow In dtSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows - RemisionesLista.Add(row("CveVenta").ToString.ToEntero) - Next - Else - For Each row As DataRow In dtSeleccionadas.Rows - sb.Append($"{row("CveVenta").ToString},") - RemisionesLista.Add(row("CveVenta").ToString.ToEntero) - Next - End If - - sb.Remove(sb.Length - 1, 1) - - CargaConceptosRemisionPorFacturar(sb.ToString, If(ChkRemProductos.Checked, 2, 1)) - End Select - - Dim CveTipoDocto = DdlTipoComprobante.SelectedValue - DdlTipoComprobante.Items.Clear() - DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) - DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) - DdlTipoComprobante.SelectedIndex = 0 - DdlTipoComprobante.SelectedValueExist(CveTipoDocto) - CambiaTipoComprobante() - - Dim MensajeRemisiones As New StringBuilder - Dim ObsOC As New StringBuilder - Dim ObsPedido As New StringBuilder - Dim ObsInv As New StringBuilder - MensajeRemisiones.Append("Remisiones: ") - - Dim CveMetodoPago As Integer = -1 - Dim MetodoPagoDif As Boolean = False - - For Each Dr As DataRow In dtSeleccionadas.Rows - MensajeRemisiones.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString.Length > 0, $"({Dr("ObsFact")})", "")) - ObsOC.AppendFormat("{0}, ", Dr("ObsOC")) - ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido")) - ObsInv.AppendFormat("{0}, ", Dr("ObsInv")) - - If CveMetodoPago <> -1 And Dr("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then - MetodoPagoDif = True - End If - CveMetodoPago = Dr("CveMetodoPago33").ToString.ToEntero - Next - TxtObsFact.Text = If(MensajeRemisiones.ToString.Length > 0, MensajeRemisiones.ToString.Substring(0, MensajeRemisiones.ToString.Length - 2), "") - TxtOrdenCompra.Text = If(ObsOC.ToString.Length > 0, ObsOC.ToString.Substring(0, ObsOC.ToString.Length - 2), "") - TxtPedidoContrato.Text = If(ObsPedido.ToString.Length > 0, ObsPedido.ToString.Substring(0, ObsPedido.ToString.Length - 2), "") - TxtObsAlmacen.Text = If(ObsInv.ToString.Length > 0, ObsInv.ToString.Substring(0, ObsInv.ToString.Length - 2), "") - UPObservaciones.Update() - - If MetodoPagoDif Then - Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia) - End If - - If CveContrato > 0 Then - DdlContrato.DataSource = DtContratos.FiltraParametros($"CveContrato = {CveContrato}") - DdlContrato.DataBind() - End If - - End If - End If - - UpRemisionesFacturas.Update() - UpFacturar.Update() - UpPS.Update() - UpParametros.Update() - UPEstimaciones.Update() - HuboCambioRemi = Not HuboCambioRemi - RegistraScript("$('#DivRemisiones').modal('hide');", "DivRemisionesHide") - End Sub - Private Sub VerificaRemisiones(ByRef dt As DataTable) - If ChkRemProductos.Checked Then - For Each Gvr As GridViewRow In GvRemPS.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero - Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - Next - Else - For Each Gvr As GridViewRow In GvRem.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero - Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - Next - End If - End Sub - Private Sub CargaConceptosRemisionPorFacturar(CveRemisiones As String, TipoCargas As Integer) - Dim ObjClientes As New ClsClientes - If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveRemisiones, TipoCargas) Then - DtRemisionesPS = ObjClientes.DtResultados - End If - ObjClientes.Dispose() - - If DtRemisionesPS IsNot Nothing Then - Dim tCantidad As Decimal = 0 - For Each Dr As DataRow In DtRemisionesPS.Select() - tCantidad = If(ChkRemProductos.Checked, GvRemPS.Rows(IndiceGVDataKey(GvRemPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadRem").Text, Dr("Cantidad")).ToString.ToDecimal - AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, - Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, - Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, - CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, - CveVentaDetalleRemision:=Dr("CveVentaDetalle").ToString.ToEntero, RegeneraIEPS:=True) - Next - - If DdlFiltroContrato.SelectedValue.ToEntero > 0 Then - CveContrato = DdlFiltroContrato.SelectedValue.ToEntero - End If - - End If - - CalculaTotalesVenta() - End Sub - Private Function IndiceGVDataKey(GridView As GridView, DataKey As String, DataKeyValue As String) As Integer - For Each row As GridViewRow In GridView.Rows - If row.DataKey(DataKey) = DataKeyValue Then - Return row.RowIndex - End If - Next - Return Nothing +#Region " REMISIONES - SIN FACTURAR " + Protected Sub ChkCanRem_CheckedChanged(sender As Object, e As EventArgs) + If ChkCanRem.Checked Then + DivGvCancelarRemision.Visible = True + Else + DivGvCancelarRemision.Visible = False + End If + UpCancelarDocumento.Update() + End Sub + Private Sub LnkRemisiones_Click(sender As Object, e As EventArgs) Handles LnkRemisiones.Click + Dim ObjContratos As New ClsContratos + + If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1) Then + DdlFiltroContrato.DataSource = ObjContratos.DtResultados + DdlFiltroContrato.DataBind() + DdlFiltroContrato.Items.Insert(0, New ListItem("Remisiones sin Contrato", "-1")) + End If + + DdlFiltroRemMoneda.Items.Clear() + DdlFiltroRemMoneda.DataSource = GlobalDTMonedas + DdlFiltroRemMoneda.DataBind() + DdlFiltroRemMoneda.Items.Insert(0, New ListItem("Todas", "-1")) + + GvContratoDetalles.DataSource = Nothing + GvContratoDetalles.DataBind() + UpContratos.Update() + + DivEstimaciones.Visible = True + ContratoDetalles.Visible = False + UPEstimaciones.Update() + + Tab.ActiveTab = TabGenerales + TabGenerales.Enabled = True + Updatetabs.Update() + + If ChkRemProductos.Checked Then + CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + Else + CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + End If + RegistraScript("$('#DivRemisiones').modal('show');") + End Sub + Private Sub BtnConsultarRem_Click(sender As Object, e As EventArgs) Handles BtnConsultarRem.Click + If ChkRemProductos.Checked Then + CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + Else + CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + End If + End Sub + Private Sub ChkRemProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkRemProductos.CheckedChanged + If ChkRemProductos.Checked Then + GvRemPS.Visible = True + GvRem.Visible = False + DivFiltroRemPS.Visible = True + DivFiltroRem.Visible = False + GvRem.DataSource = Nothing + GvRem.DataBind() + CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + Else + GvRemPS.Visible = False + GvRem.Visible = True + DivFiltroRemPS.Visible = False + DivFiltroRem.Visible = True + GvRemPS.DataSource = Nothing + GvRemPS.DataBind() + CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + End If + End Sub + Private Sub DdlFiltroContrato_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroContrato.SelectedIndexChanged + If ChkRemProductos.Checked Then + CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + Else + CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + End If + End Sub + Private Sub DdlFiltroRemMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroRemMoneda.SelectedIndexChanged + If ChkRemProductos.Checked Then + CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + Else + CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero) + End If + End Sub + Private Sub CargaRemisiones(CveContrato As Integer, CveMoneda As Integer) + Dim ObjVentas As New ClsVentas + If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 1, CveMoneda) Then + If CveContrato = -1 Then + DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0") + Else + DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}") + End If + If Not DTRemisiones.Columns.Contains("Aplicado") Then + DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) + End If + GvRem.DataSource = DTRemisiones + End If + ObjVentas.Dispose() + + GvRem.DataBind() + UpRemisionesFacturas.Update() + End Sub + Private Sub CargaRemisionesxProducto(CveContrato As Integer, CveMoneda As Integer) + Dim ObjVentas As New ClsVentas + If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 2, CveMoneda) Then + If CveContrato = -1 Then + DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0") + Else + DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}") + End If + If Not DTRemisiones.Columns.Contains("Aplicado") Then + DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) + End If + GvRemPS.DataSource = DTRemisiones + End If + ObjVentas.Dispose() + + GvRemPS.DataBind() + UpRemisionesFacturas.Update() + End Sub + Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblTipo.SelectedIndexChanged + HuboCambioRemi = Not HuboCambioRemi + End Sub + Protected Sub BtnGuardarRemisiones_Click(sender As Object, e As EventArgs) Handles BtnGuardarRemisiones.Click + If GvRem.Rows.Count > 0 Or GvRemPS.Rows.Count > 0 Then + 'Checa las facturas selecionadas + VerificaRemisiones(DTRemisiones) + + Dim dtSeleccionadas As DataTable = DTRemisiones.FiltraParametros("Aplicado = True") + Dim CveContrato = DTRemisiones.FiltroPrimeroValor("CveContrato", "Aplicado = True").ToEntero + + If dtSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then + Alert("Solo debe seleccionar remisiones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{dtSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") + DdlMoneda.Enabled = False + CambiaMoneda() + DdlUsoCFDI.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) + DdlMetodoPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) + CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) + DdlFormaPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveFormaPago")) + + 'validación, cuando las remisiones sean de una sucursal y el usuario solo tenga acceso a otra, deberá tener priodidad la sucursal de la que solo se factura + If DdlSubProyectoDatos.Enabled = True Then + DdlSubProyectoDatos.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveSubProyecto")) + End If + DdlSucursalCliente.SelectedValueExist(If(dtSeleccionadas.FiltroPrimeroValor("CveClienteSucursal").ToEntero > 0, dtSeleccionadas.FiltroPrimeroValor("CveClienteSucursal"), "-1")) + DdlVendedor.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveVendedor")) + + CambiaSucursalGeneral() + CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero) + + DdlUsoCFDI.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) + DdlMetodoPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) + CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) + DdlFormaPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveFormaPago")) + + If GvPS.Rows.Count > 0 Then + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = TxtIVA.Text + End If + + RBLPago.Items(0).Enabled = True 'sino está activo lo activamos porque las remisiones pueden ser a crédito + RBLPago.SelectedValue = "1" + + RemisionesLista.Clear() + + If dtSeleccionadas.Rows.Count > 0 Then + Select Case RblTipo.SelectedValue + Case "1" 'T O T A L G E N E R A L + + For Each row As DataRow In dtSeleccionadas.Rows + RemisionesLista.Add(row("CveVenta").ToString.ToEntero) + Next + + IsTotalxConcepto = False + Dim PU As Decimal = dtSeleccionadas.SUM("SubTotal").ToDecimal + Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa)(0) + Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16) + Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa)(0) + + AgregarProductoServicio(1, PS("CveUM").ToString.ToEntero, PS("UnidadMedida").ToString, PS("CveClasificacion").ToString.ToEntero, + PS("Clasificacion").ToString, PS("CvePS").ToString.ToEntero, PS("PS").ToString, "", PU, 0, + rowSP("CveProyecto").ToString.ToEntero, rowSP("Proyecto").ToString, rowSP("CveSubProyecto").ToString.ToEntero, rowSP("SubProyecto").ToString, RegeneraIEPS:=True) + + Case "2" 'T O T A L X R E M I S I O N + + For Each row As DataRow In dtSeleccionadas.Rows + RemisionesLista.Add(row("CveVenta").ToString.ToEntero) + Next + + Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa)(0) + Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa)(0) + Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16) + For Each gvr As GridViewRow In GvRem.Rows + If gvr.FCCheckBox("Chk").Checked Then + AgregarProductoServicio(1, PS("CveUM").ToString.ToEntero, PS("UnidadMedida").ToString, PS("CveClasificacion").ToString.ToEntero, + PS("Clasificacion").ToString, PS("CvePS").ToString.ToEntero, PS("PS").ToString, "", gvr.DataKey("SubTotal").ToString.ToDecimal, 0, + rowSP("CveProyecto").ToString.ToEntero, rowSP("Proyecto").ToString, rowSP("CveSubProyecto").ToString.ToEntero, rowSP("SubProyecto").ToString, RegeneraIEPS:=True) + End If + Next + + Case "3" 'T O T A L X C O N C E P T O + + IsTotalxConcepto = True + Dim sb As New StringBuilder + If ChkRemProductos.Checked Then + For Each row As DataRow In dtSeleccionadas.Rows + sb.Append($"{row("CveVentaDetalle").ToString},") + Next + For Each row As DataRow In dtSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows + RemisionesLista.Add(row("CveVenta").ToString.ToEntero) + Next + Else + For Each row As DataRow In dtSeleccionadas.Rows + sb.Append($"{row("CveVenta").ToString},") + RemisionesLista.Add(row("CveVenta").ToString.ToEntero) + Next + End If + + sb.Remove(sb.Length - 1, 1) + + CargaConceptosRemisionPorFacturar(sb.ToString, If(ChkRemProductos.Checked, 2, 1)) + End Select + + Dim CveTipoDocto = DdlTipoComprobante.SelectedValue + DdlTipoComprobante.Items.Clear() + DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) + DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) + DdlTipoComprobante.SelectedIndex = 0 + DdlTipoComprobante.SelectedValueExist(CveTipoDocto) + CambiaTipoComprobante() + + Dim MensajeRemisiones As New StringBuilder + Dim ObsOC As New StringBuilder + Dim ObsPedido As New StringBuilder + Dim ObsInv As New StringBuilder + MensajeRemisiones.Append("Remisiones: ") + + Dim CveMetodoPago As Integer = -1 + Dim MetodoPagoDif As Boolean = False + + For Each Dr As DataRow In dtSeleccionadas.Rows + MensajeRemisiones.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString.Length > 0, $"({Dr("ObsFact")})", "")) + ObsOC.AppendFormat("{0}, ", Dr("ObsOC")) + ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido")) + ObsInv.AppendFormat("{0}, ", Dr("ObsInv")) + + If CveMetodoPago <> -1 And Dr("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then + MetodoPagoDif = True + End If + CveMetodoPago = Dr("CveMetodoPago33").ToString.ToEntero + Next + TxtObsFact.Text = If(MensajeRemisiones.ToString.Length > 0, MensajeRemisiones.ToString.Substring(0, MensajeRemisiones.ToString.Length - 2), "") + TxtOrdenCompra.Text = If(ObsOC.ToString.Length > 0, ObsOC.ToString.Substring(0, ObsOC.ToString.Length - 2), "") + TxtPedidoContrato.Text = If(ObsPedido.ToString.Length > 0, ObsPedido.ToString.Substring(0, ObsPedido.ToString.Length - 2), "") + TxtObsAlmacen.Text = If(ObsInv.ToString.Length > 0, ObsInv.ToString.Substring(0, ObsInv.ToString.Length - 2), "") + UPObservaciones.Update() + + If MetodoPagoDif Then + Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia) + End If + + If CveContrato > 0 Then + DdlContrato.DataSource = DtContratos.FiltraParametros($"CveContrato = {CveContrato}") + DdlContrato.DataBind() + End If + + End If + End If + + UpRemisionesFacturas.Update() + UpFacturar.Update() + UpPS.Update() + UpParametros.Update() + UPEstimaciones.Update() + HuboCambioRemi = Not HuboCambioRemi + RegistraScript("$('#DivRemisiones').modal('hide');", "DivRemisionesHide") + End Sub + Private Sub VerificaRemisiones(ByRef dt As DataTable) + If ChkRemProductos.Checked Then + For Each Gvr As GridViewRow In GvRemPS.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero + Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + Next + Else + For Each Gvr As GridViewRow In GvRem.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero + Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + Next + End If + End Sub + Private Sub CargaConceptosRemisionPorFacturar(CveRemisiones As String, TipoCargas As Integer) + Dim ObjClientes As New ClsClientes + If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveRemisiones, TipoCargas) Then + DtRemisionesPS = ObjClientes.DtResultados + End If + ObjClientes.Dispose() + + If DtRemisionesPS IsNot Nothing Then + Dim tCantidad As Decimal = 0 + For Each Dr As DataRow In DtRemisionesPS.Select() + tCantidad = If(ChkRemProductos.Checked, GvRemPS.Rows(IndiceGVDataKey(GvRemPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadRem").Text, Dr("Cantidad")).ToString.ToDecimal + AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, + Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, + Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, + CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, + CveVentaDetalleRemision:=Dr("CveVentaDetalle").ToString.ToEntero, RegeneraIEPS:=True) + Next + + If DdlFiltroContrato.SelectedValue.ToEntero > 0 Then + CveContrato = DdlFiltroContrato.SelectedValue.ToEntero + End If + + End If + + CalculaTotalesVenta() + End Sub + Private Function IndiceGVDataKey(GridView As GridView, DataKey As String, DataKeyValue As String) As Integer + For Each row As GridViewRow In GridView.Rows + If row.DataKey(DataKey) = DataKeyValue Then + Return row.RowIndex + End If + Next + Return Nothing End Function -#End Region +#End Region -#Region " REMISIONES - FACTURAR " - Private Sub ActivaFacturarRemision() - 'If UsuarioActual.CveUsuario <> 100 Then - ' Exit Sub - 'End If - - Dim ObjClientes As New ClsClientes - If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveVenta.ToString, 1) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then - LnkFacturarRemision.Visible = True - If ThCantidadFacturadaRem.Visible Then - LnkFacturarRemision.ToolTip = "¿Seguro que desea facturar lo pendiente por facturar de la remisión?" - End If - - If DdlMoneda.SelectedValue.ToEntero = 1 Then - TrConversionDolares.Visible = True - ChkConvertirDolares.Enabled = True - TxtTipoCambioDlls.Enabled = True - Else - TrConversionTipoCambio.Visible = True - ChkConvertirDoctoPesos.Enabled = True - TxtTipoCambio.Enabled = True - End If - - UpPS.Update() - End If - - ObjClientes.Dispose() - End Sub - Private Sub LnkFacturarRemision_Click(sender As Object, e As EventArgs) Handles LnkFacturarRemision.Click - - 'LIMPIAMOS - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtIEPS.Text = "0.00" - TxtRetIVA.Text = "0.00" - TxtRetISR.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = TxtIVA.Text - CreaDTVentas() - - CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero > 0, DdlContrato.SelectedValue.ToEntero, -1), DdlMoneda.SelectedValue.ToEntero) - Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}") - If DrRemision.Count > 0 Then - DrRemision(0)("Aplicado") = "True" - End If - DTRemisiones.AcceptChanges() - RemisionesLista.Add(CveVenta) - CargaConceptosRemisionPorFacturar(CveVenta.ToString, 1) - - BtnEmitirImprimir.Text = "Facturar" - DdlTipoComprobante.SelectedValue = "Ing" - TxtFecha.Text = Now.ToShortDateString() - UpPS.Update() - UpFacturar.Update() - - If TmpDT.Rows.Count = 0 Then - Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - BtnEmitirImprimir_Click(BtnEmitirImprimir, EventArgs.Empty) - - End Sub - - Private Function PreparaFacturarRemision() As Boolean - 'LIMPIAMOS - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtIEPS.Text = "0.00" - TxtRetIVA.Text = "0.00" - TxtRetISR.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = TxtIVA.Text - CreaDTVentas() - - CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero > 0, DdlContrato.SelectedValue.ToEntero, -1), DdlMoneda.SelectedValue.ToEntero) - Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}") - If DrRemision.Count > 0 Then - DrRemision(0)("Aplicado") = "True" - End If - DTRemisiones.AcceptChanges() - RemisionesLista.Add(CveVenta) - CargaConceptosRemisionPorFacturar(CveVenta.ToString, 1) - - If TmpDT.Rows.Count = 0 Then - Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Return False - End If - - Return True +#Region " REMISIONES - FACTURAR " + Private Sub ActivaFacturarRemision() + 'If UsuarioActual.CveUsuario <> 100 Then + ' Exit Sub + 'End If + + Dim ObjClientes As New ClsClientes + If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveVenta.ToString, 1) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then + LnkFacturarRemision.Visible = True + If ThCantidadFacturadaRem.Visible Then + LnkFacturarRemision.ToolTip = "¿Seguro que desea facturar lo pendiente por facturar de la remisión?" + End If + + If DdlMoneda.SelectedValue.ToEntero = 1 Then + TrConversionDolares.Visible = True + ChkConvertirDolares.Enabled = True + TxtTipoCambioDlls.Enabled = True + Else + TrConversionTipoCambio.Visible = True + ChkConvertirDoctoPesos.Enabled = True + TxtTipoCambio.Enabled = True + End If + + UpPS.Update() + End If + + ObjClientes.Dispose() + End Sub + Private Sub LnkFacturarRemision_Click(sender As Object, e As EventArgs) Handles LnkFacturarRemision.Click + + 'LIMPIAMOS + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtIEPS.Text = "0.00" + TxtRetIVA.Text = "0.00" + TxtRetISR.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = TxtIVA.Text + CreaDTVentas() + + CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero > 0, DdlContrato.SelectedValue.ToEntero, -1), DdlMoneda.SelectedValue.ToEntero) + Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}") + If DrRemision.Count > 0 Then + DrRemision(0)("Aplicado") = "True" + End If + DTRemisiones.AcceptChanges() + RemisionesLista.Add(CveVenta) + CargaConceptosRemisionPorFacturar(CveVenta.ToString, 1) + + BtnEmitirImprimir.Text = "Facturar" + DdlTipoComprobante.SelectedValue = "Ing" + TxtFecha.Text = Now.ToShortDateString() + UpPS.Update() + UpFacturar.Update() + + If TmpDT.Rows.Count = 0 Then + Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + BtnEmitirImprimir_Click(BtnEmitirImprimir, EventArgs.Empty) + + End Sub + + Private Function PreparaFacturarRemision() As Boolean + 'LIMPIAMOS + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtIEPS.Text = "0.00" + TxtRetIVA.Text = "0.00" + TxtRetISR.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = TxtIVA.Text + CreaDTVentas() + + CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero > 0, DdlContrato.SelectedValue.ToEntero, -1), DdlMoneda.SelectedValue.ToEntero) + Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}") + If DrRemision.Count > 0 Then + DrRemision(0)("Aplicado") = "True" + End If + DTRemisiones.AcceptChanges() + RemisionesLista.Add(CveVenta) + CargaConceptosRemisionPorFacturar(CveVenta.ToString, 1) + + If TmpDT.Rows.Count = 0 Then + Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Return False + End If + + Return True End Function -#End Region +#End Region -#Region " PEDIDOS2 - SIN FACTURAR " - Protected Sub LnkPedido2SinFacturar_Click(sender As Object, e As EventArgs) - - DdlMonedaModalPedido2.Items.Clear() - DdlMonedaModalPedido2.DataSource = GlobalDTMonedas - DdlMonedaModalPedido2.DataBind() - DdlMonedaModalPedido2.Items.Insert(0, New ListItem("Todas", "-1")) - - Tab.ActiveTab = TabGenerales - TabGenerales.Enabled = True - Updatetabs.Update() - - CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1)) - RegistraScript("$('#DivPedidos2').modal('show');") - End Sub - - Private Sub BtnConsultaPedido_Click(sender As Object, e As EventArgs) Handles BtnConsultaPedido.Click - CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1)) - End Sub - Protected Sub ChkMostrarProductosPedido2_CheckedChanged(sender As Object, e As EventArgs) - MostrarProductoPedido2() - CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1)) - End Sub - Private Sub MostrarProductoPedido2() - If ChkMostrarProductosPedido2.Checked Then - GvPedidos2SinFacturarPS.Visible = True - GvPedidos2SinFacturar.Visible = False - DivBuscadorPedido2PS.Visible = True - DivBuscadorPedido2.Visible = False - GvPedidos2SinFacturar.DataSource = Nothing - GvPedidos2SinFacturar.DataBind() - Else - GvPedidos2SinFacturarPS.Visible = False - GvPedidos2SinFacturar.Visible = True - DivBuscadorPedido2PS.Visible = False - DivBuscadorPedido2.Visible = True - GvPedidos2SinFacturarPS.DataSource = Nothing - GvPedidos2SinFacturarPS.DataBind() - End If - End Sub - Private Sub CargaPedidos2(CveMoneda As Integer, Tipo As Integer) - Dim ObjVentas As New ClsVentas - If ObjVentas.GetVentaDetallePedido2SinFacturar(TxtFechaIPed.Text, TxtFechaFPedido.Text, CveCliente, CveMoneda, Tipo) Then - DtPedidos2 = ObjVentas.DtResultados - If Not DtPedidos2.Columns.Contains("Aplicado") Then - DtPedidos2.Columns.Add("Aplicado", Type.GetType("System.Boolean")) - End If - If Tipo = 1 Then - GvPedidos2SinFacturar.DataSource = DtPedidos2 - Else - GvPedidos2SinFacturarPS.DataSource = DtPedidos2 - End If - End If - - ObjVentas.Dispose() - If Tipo = 1 Then - GvPedidos2SinFacturar.DataBind() - Else - GvPedidos2SinFacturarPS.DataBind() - End If - UpModalPedidos2.Update() - End Sub - Protected Sub BtnGuardarPedido2_Click(sender As Object, e As EventArgs) - If GvPedidos2SinFacturar.Rows.Count = 0 And GvPedidos2SinFacturarPS.Rows.Count = 0 Then - Alert("Debe existir por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'MARCA LAS SELECCIONADAS - VerificaPedidos2(DtPedidos2) - Dim DTSeleccionadas As DataTable = DtPedidos2.FiltraParametros("Aplicado = True") - - If DTSeleccionadas.Rows.Count = 0 Then - Alert("Debe seleccionar por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'SOLO PUEDE SELECCIONAR DE LA MISMA MONEDA - If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then - Alert("Solo debe seleccionar pedidos de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'LIMPIA LAS PARTIDAS ACTUALES - If GvPS.Rows.Count > 0 Then - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtIEPS.Text = "0.00" - TxtRetISR.Text = "0.00" - TxtRetIVA.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = "0.00" - End If - Pedidos2Lista.Clear() - - 'CARGAMOS LOS VALORES DEL PEDIDO - DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") - DdlMoneda.Enabled = False - CambiaMoneda() - DdlMetodoPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) - DdlFormaPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveFormaPago")) - DdlUsoCFDI.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) - If DdlSubProyectoDatos.Enabled Then 'validación, cuando los pedido2 sean de una sucursal y el usuario solo tenga acceso a otra, deberá tener priodidad la sucursal de la que solo se factura - DdlSubProyectoDatos.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveSubProyecto")) - End If - DdlSucursalCliente.SelectedValueExist(If(DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal").ToEntero > 0, DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal"), "-1")) - DdlVendedor.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveVendedor")) - CambiaSucursalGeneral() - CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero) - - Dim Cves As New StringBuilder - If ChkMostrarProductosPedido2.Checked Then - For Each row As DataRow In DTSeleccionadas.Rows - Cves.Append($"{row("CveVentaDetalle").ToString},") - Next - For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows - Pedidos2Lista.Add(row("CveVenta").ToString.ToEntero) - Next - Else - For Each row As DataRow In DTSeleccionadas.Rows - Cves.Append($"{row("CveVenta").ToString},") - Pedidos2Lista.Add(row("CveVenta").ToString.ToEntero) - Next - End If - Cves.Remove(Cves.Length - 1, 1) - - Dim ObjVentas As New ClsVentas - If ObjVentas.GetVentasPedidos2Totales(CveCliente, Cves.ToString, If(ChkMostrarProductosPedido2.Checked, 2, 1)) Then - DtPedidos2PS = ObjVentas.DtResultados - End If - ObjVentas.Dispose() - - If Not AgregaPSPedido2() Then - Alert("Ocurrió un error validar las partidas de los pedidos seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - Dim CveTipoDocto = DdlTipoComprobante.SelectedValue - DdlTipoComprobante.Items.Clear() - DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) - DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) - DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem")) - DdlTipoComprobante.SelectedIndex = 0 - DdlTipoComprobante.SelectedValueExist(CveTipoDocto) - CambiaTipoComprobante() - - 'CARGA OBSERVACIONES DE LOS PEDIDOS - Dim MensajePedidos2 As New StringBuilder - Dim ObsOC As New StringBuilder - Dim ObsPedido As New StringBuilder - Dim ObsInv As New StringBuilder - MensajePedidos2.Append("Pedidos: ") - For Each Dr As DataRow In DTSeleccionadas.Rows - MensajePedidos2.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString.Length > 0, $"({Dr("ObsFact")})", "")) - ObsOC.AppendFormat("{0}, ", Dr("ObsOC")) - ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido")) - ObsInv.AppendFormat("{0}, ", Dr("ObsInv")) - Next - TxtObsFact.Text = If(MensajePedidos2.ToString.Length > 0, MensajePedidos2.ToString.Substring(0, MensajePedidos2.ToString.Length - 2), "") - TxtOrdenCompra.Text = If(ObsOC.ToString.Length > 0, ObsOC.ToString.Substring(0, ObsOC.ToString.Length - 2), "") - TxtPedidoContrato.Text = If(ObsPedido.ToString.Length > 0, ObsPedido.ToString.Substring(0, ObsPedido.ToString.Length - 2), "") - TxtObsAlmacen.Text = If(ObsInv.ToString.Length > 0, ObsInv.ToString.Substring(0, ObsInv.ToString.Length - 2), "") - - - UpModalPedidos2.Update() - UpFacturar.Update() - UpPS.Update() - UpParametros.Update() - UPEstimaciones.Update() - UPObservaciones.Update() - - RegistraScript("$('#DivPedidos2').modal('hide');", "DivPedidos2Hide") - End Sub - Private Sub VerificaPedidos2(ByRef dt As DataTable) - If ChkMostrarProductosPedido2.Checked Then - For Each Gvr As GridViewRow In GvPedidos2SinFacturarPS.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero - Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - Next - Else - For Each Gvr As GridViewRow In GvPedidos2SinFacturar.Rows - If Gvr.RowType = DataControlRowType.DataRow Then - Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") - Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero - Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") - If Drs.Count > 0 Then - Drs(0)("Aplicado") = ChkAplicar.Checked - End If - dt.AcceptChanges() - End If - Next - End If - End Sub - Private Function AgregaPSPedido2() As Boolean - If DtPedidos2PS IsNot Nothing Then - Dim tCantidad As Decimal = 0 - For Each Dr As DataRow In DtPedidos2PS.Select() - tCantidad = If(ChkMostrarProductosPedido2.Checked, GvPedidos2SinFacturarPS.Rows(IndiceGVDataKey(GvPedidos2SinFacturarPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadPedido2").Text, Dr("Cantidad")).ToString.ToDecimal - AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, - Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, - Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, - CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, - CveVentaDetallePedido2:=Dr("CveVentaDetalle").ToString.ToEntero, RegeneraIEPS:=True) - Next - CalculaTotalesVenta() - Return True - Else - Return False - End If +#Region " PEDIDOS2 - SIN FACTURAR " + Protected Sub LnkPedido2SinFacturar_Click(sender As Object, e As EventArgs) + + DdlMonedaModalPedido2.Items.Clear() + DdlMonedaModalPedido2.DataSource = GlobalDTMonedas + DdlMonedaModalPedido2.DataBind() + DdlMonedaModalPedido2.Items.Insert(0, New ListItem("Todas", "-1")) + + Tab.ActiveTab = TabGenerales + TabGenerales.Enabled = True + Updatetabs.Update() + + CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1)) + RegistraScript("$('#DivPedidos2').modal('show');") + End Sub + + Private Sub BtnConsultaPedido_Click(sender As Object, e As EventArgs) Handles BtnConsultaPedido.Click + CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1)) + End Sub + Protected Sub ChkMostrarProductosPedido2_CheckedChanged(sender As Object, e As EventArgs) + MostrarProductoPedido2() + CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1)) + End Sub + Private Sub MostrarProductoPedido2() + If ChkMostrarProductosPedido2.Checked Then + GvPedidos2SinFacturarPS.Visible = True + GvPedidos2SinFacturar.Visible = False + DivBuscadorPedido2PS.Visible = True + DivBuscadorPedido2.Visible = False + GvPedidos2SinFacturar.DataSource = Nothing + GvPedidos2SinFacturar.DataBind() + Else + GvPedidos2SinFacturarPS.Visible = False + GvPedidos2SinFacturar.Visible = True + DivBuscadorPedido2PS.Visible = False + DivBuscadorPedido2.Visible = True + GvPedidos2SinFacturarPS.DataSource = Nothing + GvPedidos2SinFacturarPS.DataBind() + End If + End Sub + Private Sub CargaPedidos2(CveMoneda As Integer, Tipo As Integer) + Dim ObjVentas As New ClsVentas + If ObjVentas.GetVentaDetallePedido2SinFacturar(TxtFechaIPed.Text, TxtFechaFPedido.Text, CveCliente, CveMoneda, Tipo) Then + DtPedidos2 = ObjVentas.DtResultados + If Not DtPedidos2.Columns.Contains("Aplicado") Then + DtPedidos2.Columns.Add("Aplicado", Type.GetType("System.Boolean")) + End If + If Tipo = 1 Then + GvPedidos2SinFacturar.DataSource = DtPedidos2 + Else + GvPedidos2SinFacturarPS.DataSource = DtPedidos2 + End If + End If + + ObjVentas.Dispose() + If Tipo = 1 Then + GvPedidos2SinFacturar.DataBind() + Else + GvPedidos2SinFacturarPS.DataBind() + End If + UpModalPedidos2.Update() + End Sub + Protected Sub BtnGuardarPedido2_Click(sender As Object, e As EventArgs) + If GvPedidos2SinFacturar.Rows.Count = 0 And GvPedidos2SinFacturarPS.Rows.Count = 0 Then + Alert("Debe existir por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'MARCA LAS SELECCIONADAS + VerificaPedidos2(DtPedidos2) + Dim DTSeleccionadas As DataTable = DtPedidos2.FiltraParametros("Aplicado = True") + + If DTSeleccionadas.Rows.Count = 0 Then + Alert("Debe seleccionar por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'SOLO PUEDE SELECCIONAR DE LA MISMA MONEDA + If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then + Alert("Solo debe seleccionar pedidos de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + 'LIMPIA LAS PARTIDAS ACTUALES + If GvPS.Rows.Count > 0 Then + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtIEPS.Text = "0.00" + TxtRetISR.Text = "0.00" + TxtRetIVA.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = "0.00" + End If + Pedidos2Lista.Clear() + + 'CARGAMOS LOS VALORES DEL PEDIDO + DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") + DdlMoneda.Enabled = False + CambiaMoneda() + DdlMetodoPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) + DdlFormaPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveFormaPago")) + DdlUsoCFDI.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) + If DdlSubProyectoDatos.Enabled Then 'validación, cuando los pedido2 sean de una sucursal y el usuario solo tenga acceso a otra, deberá tener priodidad la sucursal de la que solo se factura + DdlSubProyectoDatos.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveSubProyecto")) + End If + DdlSucursalCliente.SelectedValueExist(If(DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal").ToEntero > 0, DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal"), "-1")) + DdlVendedor.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveVendedor")) + CambiaSucursalGeneral() + CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero) + + Dim Cves As New StringBuilder + If ChkMostrarProductosPedido2.Checked Then + For Each row As DataRow In DTSeleccionadas.Rows + Cves.Append($"{row("CveVentaDetalle").ToString},") + Next + For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows + Pedidos2Lista.Add(row("CveVenta").ToString.ToEntero) + Next + Else + For Each row As DataRow In DTSeleccionadas.Rows + Cves.Append($"{row("CveVenta").ToString},") + Pedidos2Lista.Add(row("CveVenta").ToString.ToEntero) + Next + End If + Cves.Remove(Cves.Length - 1, 1) + + Dim ObjVentas As New ClsVentas + If ObjVentas.GetVentasPedidos2Totales(CveCliente, Cves.ToString, If(ChkMostrarProductosPedido2.Checked, 2, 1)) Then + DtPedidos2PS = ObjVentas.DtResultados + End If + ObjVentas.Dispose() + + If Not AgregaPSPedido2() Then + Alert("Ocurrió un error validar las partidas de los pedidos seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + Dim CveTipoDocto = DdlTipoComprobante.SelectedValue + DdlTipoComprobante.Items.Clear() + DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) + DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) + DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem")) + DdlTipoComprobante.SelectedIndex = 0 + DdlTipoComprobante.SelectedValueExist(CveTipoDocto) + CambiaTipoComprobante() + + 'CARGA OBSERVACIONES DE LOS PEDIDOS + Dim MensajePedidos2 As New StringBuilder + Dim ObsOC As New StringBuilder + Dim ObsPedido As New StringBuilder + Dim ObsInv As New StringBuilder + MensajePedidos2.Append("Pedidos: ") + For Each Dr As DataRow In DTSeleccionadas.Rows + MensajePedidos2.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString.Length > 0, $"({Dr("ObsFact")})", "")) + ObsOC.AppendFormat("{0}, ", Dr("ObsOC")) + ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido")) + ObsInv.AppendFormat("{0}, ", Dr("ObsInv")) + Next + TxtObsFact.Text = If(MensajePedidos2.ToString.Length > 0, MensajePedidos2.ToString.Substring(0, MensajePedidos2.ToString.Length - 2), "") + TxtOrdenCompra.Text = If(ObsOC.ToString.Length > 0, ObsOC.ToString.Substring(0, ObsOC.ToString.Length - 2), "") + TxtPedidoContrato.Text = If(ObsPedido.ToString.Length > 0, ObsPedido.ToString.Substring(0, ObsPedido.ToString.Length - 2), "") + TxtObsAlmacen.Text = If(ObsInv.ToString.Length > 0, ObsInv.ToString.Substring(0, ObsInv.ToString.Length - 2), "") + + + UpModalPedidos2.Update() + UpFacturar.Update() + UpPS.Update() + UpParametros.Update() + UPEstimaciones.Update() + UPObservaciones.Update() + + RegistraScript("$('#DivPedidos2').modal('hide');", "DivPedidos2Hide") + End Sub + Private Sub VerificaPedidos2(ByRef dt As DataTable) + If ChkMostrarProductosPedido2.Checked Then + For Each Gvr As GridViewRow In GvPedidos2SinFacturarPS.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero + Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + Next + Else + For Each Gvr As GridViewRow In GvPedidos2SinFacturar.Rows + If Gvr.RowType = DataControlRowType.DataRow Then + Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") + Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero + Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") + If Drs.Count > 0 Then + Drs(0)("Aplicado") = ChkAplicar.Checked + End If + dt.AcceptChanges() + End If + Next + End If + End Sub + Private Function AgregaPSPedido2() As Boolean + If DtPedidos2PS IsNot Nothing Then + Dim tCantidad As Decimal = 0 + For Each Dr As DataRow In DtPedidos2PS.Select() + tCantidad = If(ChkMostrarProductosPedido2.Checked, GvPedidos2SinFacturarPS.Rows(IndiceGVDataKey(GvPedidos2SinFacturarPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadPedido2").Text, Dr("Cantidad")).ToString.ToDecimal + AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString, + Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal, + Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString, + CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, + CveVentaDetallePedido2:=Dr("CveVentaDetalle").ToString.ToEntero, RegeneraIEPS:=True) + Next + CalculaTotalesVenta() + Return True + Else + Return False + End If End Function -#End Region +#End Region -#Region " PEDIDOS2 - FACTURAR " - Private Function PreparaFacturarPedido() As Boolean - 'LIMPIAMOS - TmpDT.Rows.Clear() - TxtSubTotal.Text = "0.00" - TxtSubTotal2.Text = "0.00" - TxtIVA.Text = "0.00" - TxtIEPS.Text = "0.00" - TxtRetIVA.Text = "0.00" - TxtRetISR.Text = "0.00" - TxtTotal.Text = "0.00" - HdnIVAOriginal.Value = TxtIVA.Text - CreaDTVentas() - - Dim ObjVentas As New ClsVentas - If ObjVentas.GetVentasPedidos2Totales(CveCliente, CveVenta.ToString, 1) Then - DtPedidos2PS = ObjVentas.DtResultados - End If - ObjVentas.Dispose() - - If Not AgregaPSPedido2() Then - Alert("Ocurrió un error validar las partidas de los pedidos seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Return False - End If - - If TmpDT.Rows.Count = 0 Then - Alert("No hay conceptos por facturar de esta cotización o ha sido cambiada su información. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) - Return False - End If - - TxtObsFact.Text = String.Format("Pedido: {0}-{1} {2}", LblSerie.Text, TxtFolio.Text, If(TxtObsFact.Text.Length > 0, $"({TxtObsFact.Text})", "")) - - Return True +#Region " PEDIDOS2 - FACTURAR " + Private Function PreparaFacturarPedido() As Boolean + 'LIMPIAMOS + TmpDT.Rows.Clear() + TxtSubTotal.Text = "0.00" + TxtSubTotal2.Text = "0.00" + TxtIVA.Text = "0.00" + TxtIEPS.Text = "0.00" + TxtRetIVA.Text = "0.00" + TxtRetISR.Text = "0.00" + TxtTotal.Text = "0.00" + HdnIVAOriginal.Value = TxtIVA.Text + CreaDTVentas() + + Dim ObjVentas As New ClsVentas + If ObjVentas.GetVentasPedidos2Totales(CveCliente, CveVenta.ToString, 1) Then + DtPedidos2PS = ObjVentas.DtResultados + End If + ObjVentas.Dispose() + + If Not AgregaPSPedido2() Then + Alert("Ocurrió un error validar las partidas de los pedidos seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Return False + End If + + If TmpDT.Rows.Count = 0 Then + Alert("No hay conceptos por facturar de esta cotización o ha sido cambiada su información. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) + Return False + End If + + TxtObsFact.Text = String.Format("Pedido: {0}-{1} {2}", LblSerie.Text, TxtFolio.Text, If(TxtObsFact.Text.Length > 0, $"({TxtObsFact.Text})", "")) + + Return True End Function -#End Region +#End Region -#Region " BOTONERA - ACCIONES DE ABAJO " +#Region " BOTONERA - ACCIONES DE ABAJO " + +#Region " CREAR APARTIR DE " + Protected Sub BtnCrearApartirDe_Click(sender As Object, e As System.EventArgs) Handles BtnCrearApartirDe.Click + ''[IPP-2Novimebre2018] COMENTADO POR SER UNA FUNCIONALIDAD SUPER RARA! LA REEMPLAZA EL EDITAR COTIZACION + ''Cuando es Cotizacion, actualiza la original + 'If DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnCrearApartirDe.Text = "Guardar Cambios" Then + ' Dim OcurrioError As Boolean = False + ' Dim ObjVentas As New ClsVentas + ' ObjVentas.IniciaTransacSQL() + + ' 'Elimino los movimientos del detalle de Ventas (Conceptos) + ' If Not ObjVentas.RemoveVentasDetalle(CveVenta) Then OcurrioError = True + + ' 'Actualizo los parametros de la venta + ' If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.Replace(",", "").ToDouble, LblDescuentos.Text.ToDouble, TxtIVA.Text.ToDouble, TxtIEPS.Text.ToDouble, TxtTotal.Text.ToDouble, + ' DdlMoneda.SelectedValue.ToEntero, TxtTipoCambio.Text.Trim.ToDouble, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, UsuarioActual.CveEmpresa, CveVenta, DdlMetodoPago.SelectedValue.ToEntero, + ' DdlFormaPago.SelectedValue.ToEntero, TxtNumCtaPago.Text.Trim, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero) Then + ' OcurrioError = True + ' End If + + ' 'Cargo de nueva cuenta el detalle de Ventas (Conceptos) + ' For Each Row As DataRow In TmpDT.Rows + ' If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, + ' Row("PU").ToString.ToDouble, Row("IVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble * (1 + Row("IVA").ToString.ToDouble)), 6), + ' Row("Obs").ToString, Row("Descuento").ToString.ToDouble, Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, IEPS:=Row("IEPS").ToString.ToDouble) Then + ' OcurrioError = True + ' Exit For + ' End If + ' Next + + ' If OcurrioError Then + ' ObjVentas.RollBack() + ' Alert("Ocurrió un error al guardar los cambios. Por favor intente de nuevo.", TipoMensaje.MsgError) + ' Else + ' '/Ventas/Ventas.aspx?CveVenta={0}&Tipo=Cot + ' Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta & "&&Tipo=Cot"";") + + ' BtnCrearApartirDe.Text = "Editar" + ' ObjVentas.Commit() + + ' ' GeneraPDFCot(TxtFecha.Text.Trim.ToDate, DTPS, VentaFolio, False, False) + ' End If + + ' ObjVentas.Dispose() + ' Exit Sub + 'End If + + ''[IPP-2Novimebre2018] COMENTADO POR SER UNA FUNCIONALIDAD SUPER RARA! LA REEMPLAZA EL EDITAR COTIZACION + 'If DdlTipoComprobante.SelectedValue = "Cot" Then + ' BtnCrearApartirDe.Text = "Guardar Cambios" + ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) + ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) + ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2")) + 'Else + ' BtnCrearApartirDe.Visible = False + 'End If + + BtnCrearApartirDe.Visible = False '[IPP-2Novimebre2018] REEMPLAZA LO COMENTADO ARRIBA + EsCreaApartirDe = True + ModalidadEdicion = True + DivEstatusFac.Visible = False + TabAlmacen.Visible = False + + 'CUANDO ES CREAR APARTIR DE SE LIMPIAN FUNCIONALIDADES DE DOCUMENTOS YA REGISTRADOS + BtnGenerarRemision.Visible = False + BtnPermisoEditarCotizacion.Visible = False + BtnEditarCotizacion.Visible = False + BtnGenerarOS.Visible = False + BtnsFacturar.Visible = False + HLOrdendeCompra.Visible = False + LkDevolucion.Visible = False + LBAplicaDevolucion.Visible = False + 'LkNotaCredito.Visible = False + LkEliminarFactura.Visible = False + ImgDownCancelacion.Visible = False + LkRefacturacion.Visible = False + HLOrdenServicio.Visible = False + LkCotizacionAutorizar.Visible = False + LnkFacturarRemision.Visible = False + LnkRemisiones.Visible = False + LnkPedido2SinFacturar.Visible = False + LnkCotizaciones.Visible = False + LnkOCs.Visible = False + LbCancelarDocumento.Visible = False + LBCancelarPedido.Visible = False + LiDevolucionAlmacen.Visible = False + HLPagar.Visible = False + HlAgregarExcel.Visible = False + + + 'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION/COTIZACIÓN + GvPS.Columns(6).Visible = False + ThCantidadFacturadaRem.Visible = False + ThCantidadFacturadaRem2.Visible = False + + GvPS.Columns(7).Visible = False + ThCantidadFacturada.Visible = False + ThCantidadFacturada2.Visible = False + + 'Cuando es cotización, Genera nueva cotizacion + If DdlTipoComprobante.SelectedValue = "Cot" Then + BtnEmitirImprimir.Text = "Cotizar" + 'TdReferencia.Style.Add("display", "none") + End If + + HplDownXML.Visible = False + HplDownPDF.Visible = False + + LblFolioFiscal.Text = "" + DdlTipoComprobante.Enabled = True + TxtFecha.Text = Now.ToShortDateString() + LblUsuario.Text = UsuarioActual.Usuario + LblFechaRegistro.Text = Now.ToShortDateString() + LblSeTimbro.Text = "No" + LblMail.Text = "No" + + 'PORLET CLIENTE + 'ACTIVA CAMBIO DE CLIENTE + HlCliente.Attributes.Remove("class") + HlCliente.Attributes.Add("class", "Texto") + TxtCodigo.ReadOnly = False + ChkEnviarFactura.Enabled = True + DdlSucursalCliente.Enabled = True + ChkDireccionEnvio.Enabled = True + DdlDireccionEnvio.Enabled = True + LnkOtraDireccion.Visible = True + TxtAtencionA.Enabled = True + TxtFechaVencimientoCotizacion.Enabled = True + + TxtCantidad.Enabled = True + DdlClasificacion.Enabled = True + DdlPS.Enabled = True + TxtObsPS.Enabled = True + DdlProyecto.Enabled = True + DdlSubProyecto.Enabled = True + TxtPrecio.Enabled = True + LbAgregar.Enabled = True + LnkAgregarPyME.Enabled = True + + ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") + + TxtMotivoDescuento.Enabled = True + LblSubTotal1.Text = TxtSubTotal.Text + TxtObsFact.Enabled = True + TxtMotivoDescuento.Enabled = True + TxtSubTotal.ReadOnly = False + TxtIVA.ReadOnly = False + TxtRetIVA.ReadOnly = False + TxtRetISR.ReadOnly = False + TxtTotal.ReadOnly = False + CalculaTotalesVenta() + BtnEmitirImprimir.Visible = True + GvImpuestosLocales2.Enabled = True + + 'Sección Detalle + DdlMoneda.Enabled = True + ChkConvertirDoctoPesos.Enabled = True + TxtTipoCambio.Enabled = True + TxtFechaEjecucion.ReadOnly = False + TxtFechaEjecucion.Text = Now.ToShortDateString + ImgCalendarFechaEje.Enabled = True + DdlVendedor.Enabled = True + DdlSubProyectoDatos.Enabled = True + DdlSubProyectoEjecucion.Enabled = True + DdlSubProyectoCobranza.Enabled = True + TxtTiempoEntrega.Enabled = True + TxtAlfa1.ReadOnly = False + TxtAlfa2.ReadOnly = False + TxtAlfa3.ReadOnly = False + TxtNum1.ReadOnly = False + TxtNum2.ReadOnly = False + TxtNum3.ReadOnly = False + TxtFech1.ReadOnly = False : ImgFech1.Enabled = True + TxtFech2.ReadOnly = False : ImgFech2.Enabled = True + TxtFech3.ReadOnly = False : ImgFech3.Enabled = True + + 'Condiciones de Pago + RBLPago.Enabled = True + RBLPago.Items(0).Enabled = True + + DdlFormaPago33.Enabled = True + DdlUsoCFDI.Enabled = True + + DdlMetodoPago33.Enabled = True + 'TxtNumCtaPago.Enabled = True + TxtFechaPago.ReadOnly = False + imgCalendario.Enabled = True + + TxtPedidoContrato.Enabled = True + TxtOrdenCompra.Enabled = True + + + Dim ObjCliente As New ClsClientes() + If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then + If ObjCliente.DtResultados.Rows.Count > 0 Then + PlazoCobranza = ObjCliente.PlazoCobranza + PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision + 'TxtNumCtaPago.Text = ObjCliente.NumCtaPago + TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString + End If + End If + ObjCliente.Dispose() + + TrVistaPrevia.Visible = True + TxtFechaVencimientoCotizacion.Text = Now.ToShortDateString + + 'HABILITA EDITAR Y ELIMINAR DEL GV + GvPS.Columns(17).Visible = True + GvPS.Columns(18).Visible = True + + UpnTools.Update() + UpCliente.Update() + UpParametros.Update() + UpPS.Update() + UpFacturar.Update() + UPObservaciones.Update() + UPPDescuento.Update() + UPCondicionesPago.Update() + UpDetalle.Update() + UpEstatus.Update() + + CambiaTipoDocto() + CambiaSucursalGeneral() + CargaAnticipos(CveCliente) + CargaRestriccionesCreditoCliente() + UpParametros.Update() -#Region " CREAR APARTIR DE " - Protected Sub BtnCrearApartirDe_Click(sender As Object, e As System.EventArgs) Handles BtnCrearApartirDe.Click - ''[IPP-2Novimebre2018] COMENTADO POR SER UNA FUNCIONALIDAD SUPER RARA! LA REEMPLAZA EL EDITAR COTIZACION - ''Cuando es Cotizacion, actualiza la original - 'If DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnCrearApartirDe.Text = "Guardar Cambios" Then - ' Dim OcurrioError As Boolean = False - ' Dim ObjVentas As New ClsVentas - ' ObjVentas.IniciaTransacSQL() - - ' 'Elimino los movimientos del detalle de Ventas (Conceptos) - ' If Not ObjVentas.RemoveVentasDetalle(CveVenta) Then OcurrioError = True - - ' 'Actualizo los parametros de la venta - ' If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.Replace(",", "").ToDouble, LblDescuentos.Text.ToDouble, TxtIVA.Text.ToDouble, TxtIEPS.Text.ToDouble, TxtTotal.Text.ToDouble, - ' DdlMoneda.SelectedValue.ToEntero, TxtTipoCambio.Text.Trim.ToDouble, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, UsuarioActual.CveEmpresa, CveVenta, DdlMetodoPago.SelectedValue.ToEntero, - ' DdlFormaPago.SelectedValue.ToEntero, TxtNumCtaPago.Text.Trim, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero) Then - ' OcurrioError = True - ' End If - - ' 'Cargo de nueva cuenta el detalle de Ventas (Conceptos) - ' For Each Row As DataRow In TmpDT.Rows - ' If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, - ' Row("PU").ToString.ToDouble, Row("IVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble * (1 + Row("IVA").ToString.ToDouble)), 6), - ' Row("Obs").ToString, Row("Descuento").ToString.ToDouble, Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, IEPS:=Row("IEPS").ToString.ToDouble) Then - ' OcurrioError = True - ' Exit For - ' End If - ' Next - - ' If OcurrioError Then - ' ObjVentas.RollBack() - ' Alert("Ocurrió un error al guardar los cambios. Por favor intente de nuevo.", TipoMensaje.MsgError) - ' Else - ' '/Ventas/Ventas.aspx?CveVenta={0}&Tipo=Cot - ' Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta & "&&Tipo=Cot"";") - - ' BtnCrearApartirDe.Text = "Editar" - ' ObjVentas.Commit() - - ' ' GeneraPDFCot(TxtFecha.Text.Trim.ToDate, DTPS, VentaFolio, False, False) - ' End If - - ' ObjVentas.Dispose() - ' Exit Sub - 'End If - - ''[IPP-2Novimebre2018] COMENTADO POR SER UNA FUNCIONALIDAD SUPER RARA! LA REEMPLAZA EL EDITAR COTIZACION - 'If DdlTipoComprobante.SelectedValue = "Cot" Then - ' BtnCrearApartirDe.Text = "Guardar Cambios" - ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) - ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) - ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2")) - 'Else - ' BtnCrearApartirDe.Visible = False - 'End If - - BtnCrearApartirDe.Visible = False '[IPP-2Novimebre2018] REEMPLAZA LO COMENTADO ARRIBA - EsCreaApartirDe = True - ModalidadEdicion = True - DivEstatusFac.Visible = False - TabAlmacen.Visible = False - - 'CUANDO ES CREAR APARTIR DE SE LIMPIAN FUNCIONALIDADES DE DOCUMENTOS YA REGISTRADOS - BtnGenerarRemision.Visible = False - BtnPermisoEditarCotizacion.Visible = False - BtnEditarCotizacion.Visible = False - BtnGenerarOS.Visible = False - BtnsFacturar.Visible = False - HLOrdendeCompra.Visible = False - LkDevolucion.Visible = False - LBAplicaDevolucion.Visible = False - 'LkNotaCredito.Visible = False - LkEliminarFactura.Visible = False - ImgDownCancelacion.Visible = False - LkRefacturacion.Visible = False - HLOrdenServicio.Visible = False - LkCotizacionAutorizar.Visible = False - LnkFacturarRemision.Visible = False - LnkRemisiones.Visible = False - LnkPedido2SinFacturar.Visible = False - LnkCotizaciones.Visible = False - LnkOCs.Visible = False - LbCancelarDocumento.Visible = False - LBCancelarPedido.Visible = False - LiDevolucionAlmacen.Visible = False - HLPagar.Visible = False - HlAgregarExcel.Visible = False - - - 'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION/COTIZACIÓN - GvPS.Columns(6).Visible = False - ThCantidadFacturadaRem.Visible = False - ThCantidadFacturadaRem2.Visible = False - - GvPS.Columns(7).Visible = False - ThCantidadFacturada.Visible = False - ThCantidadFacturada2.Visible = False - - 'Cuando es cotización, Genera nueva cotizacion - If DdlTipoComprobante.SelectedValue = "Cot" Then - BtnEmitirImprimir.Text = "Cotizar" - 'TdReferencia.Style.Add("display", "none") - End If - - HplDownXML.Visible = False - HplDownPDF.Visible = False - - LblFolioFiscal.Text = "" - DdlTipoComprobante.Enabled = True - TxtFecha.Text = Now.ToShortDateString() - LblUsuario.Text = UsuarioActual.Usuario - LblFechaRegistro.Text = Now.ToShortDateString() - LblSeTimbro.Text = "No" - LblMail.Text = "No" - - 'PORLET CLIENTE - 'ACTIVA CAMBIO DE CLIENTE - HlCliente.Attributes.Remove("class") - HlCliente.Attributes.Add("class", "Texto") - TxtCodigo.ReadOnly = False - ChkEnviarFactura.Enabled = True - DdlSucursalCliente.Enabled = True - ChkDireccionEnvio.Enabled = True - DdlDireccionEnvio.Enabled = True - LnkOtraDireccion.Visible = True - TxtAtencionA.Enabled = True - TxtFechaVencimientoCotizacion.Enabled = True - - TxtCantidad.Enabled = True - DdlClasificacion.Enabled = True - DdlPS.Enabled = True - TxtObsPS.Enabled = True - DdlProyecto.Enabled = True - DdlSubProyecto.Enabled = True - TxtPrecio.Enabled = True - LbAgregar.Enabled = True - LnkAgregarPyME.Enabled = True - - ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") - - TxtMotivoDescuento.Enabled = True - LblSubTotal1.Text = TxtSubTotal.Text - TxtObsFact.Enabled = True - TxtMotivoDescuento.Enabled = True - TxtSubTotal.ReadOnly = False - TxtIVA.ReadOnly = False - TxtRetIVA.ReadOnly = False - TxtRetISR.ReadOnly = False - TxtTotal.ReadOnly = False - CalculaTotalesVenta() - BtnEmitirImprimir.Visible = True - GvImpuestosLocales2.Enabled = True - - 'Sección Detalle - DdlMoneda.Enabled = True - ChkConvertirDoctoPesos.Enabled = True - TxtTipoCambio.Enabled = True - TxtFechaEjecucion.ReadOnly = False - TxtFechaEjecucion.Text = Now.ToShortDateString - ImgCalendarFechaEje.Enabled = True - DdlVendedor.Enabled = True - DdlSubProyectoDatos.Enabled = True - DdlSubProyectoEjecucion.Enabled = True - DdlSubProyectoCobranza.Enabled = True - TxtTiempoEntrega.Enabled = True - TxtAlfa1.ReadOnly = False - TxtAlfa2.ReadOnly = False - TxtAlfa3.ReadOnly = False - TxtNum1.ReadOnly = False - TxtNum2.ReadOnly = False - TxtNum3.ReadOnly = False - TxtFech1.ReadOnly = False : ImgFech1.Enabled = True - TxtFech2.ReadOnly = False : ImgFech2.Enabled = True - TxtFech3.ReadOnly = False : ImgFech3.Enabled = True - - 'Condiciones de Pago - RBLPago.Enabled = True - RBLPago.Items(0).Enabled = True - - DdlFormaPago33.Enabled = True - DdlUsoCFDI.Enabled = True - - DdlMetodoPago33.Enabled = True - 'TxtNumCtaPago.Enabled = True - TxtFechaPago.ReadOnly = False - imgCalendario.Enabled = True - - TxtPedidoContrato.Enabled = True - TxtOrdenCompra.Enabled = True - - - Dim ObjCliente As New ClsClientes() - If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then - If ObjCliente.DtResultados.Rows.Count > 0 Then - PlazoCobranza = ObjCliente.PlazoCobranza - PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision - 'TxtNumCtaPago.Text = ObjCliente.NumCtaPago - TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString - End If - End If - ObjCliente.Dispose() - - TrVistaPrevia.Visible = True - TxtFechaVencimientoCotizacion.Text = Now.ToShortDateString - - 'HABILITA EDITAR Y ELIMINAR DEL GV - GvPS.Columns(17).Visible = True - GvPS.Columns(18).Visible = True - - UpnTools.Update() - UpCliente.Update() - UpParametros.Update() - UpPS.Update() - UpFacturar.Update() - UPObservaciones.Update() - UPPDescuento.Update() - UPCondicionesPago.Update() - UpDetalle.Update() - UpEstatus.Update() - - CambiaTipoDocto() - CambiaSucursalGeneral() - CargaAnticipos(CveCliente) - CargaRestriccionesCreditoCliente() - UpParametros.Update() - End Sub -#End Region +#End Region -#Region " GENERAR FACTURA " - Protected Sub LBFacturarIngreso_Click(sender As Object, e As EventArgs) - EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) - 'DdlTipoComprobante.SelectedValue = "Ing" - EmitirDocumentoNuevo("Ing") - End Sub - Protected Sub LBFacturarAnticipo_Click(sender As Object, e As EventArgs) - EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) - 'DdlTipoComprobante.SelectedValue = "Ant" - EmitirDocumentoNuevo("Ant") +#Region " GENERAR FACTURA " + Protected Sub LBFacturarIngreso_Click(sender As Object, e As EventArgs) + EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) + 'DdlTipoComprobante.SelectedValue = "Ing" + EmitirDocumentoNuevo("Ing") End Sub -#End Region - -#Region " GENERAR REMISION " - Private Sub BtnGenerarRemision_Click(sender As Object, e As EventArgs) Handles BtnGenerarRemision.Click - If DdlTipoComprobante.SelectedValue.Contiene("Cot", "PA", "Pd2") Then 'CUANDO ES COTIZACION O PEDIDOA O PEDIDO2 SE HARA REMISION - EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) - 'DdlTipoComprobante.SelectedValue = "Rem" - EmitirDocumentoNuevo("Rem") - End If + Protected Sub LBFacturarAnticipo_Click(sender As Object, e As EventArgs) + EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) + 'DdlTipoComprobante.SelectedValue = "Ant" + EmitirDocumentoNuevo("Ant") End Sub -#End Region +#End Region -#Region "GENERAR AUTORIZACIÓN" +#Region " GENERAR REMISION " + Private Sub BtnGenerarRemision_Click(sender As Object, e As EventArgs) Handles BtnGenerarRemision.Click + If DdlTipoComprobante.SelectedValue.Contiene("Cot", "PA", "Pd2") Then 'CUANDO ES COTIZACION O PEDIDOA O PEDIDO2 SE HARA REMISION + EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) + 'DdlTipoComprobante.SelectedValue = "Rem" + EmitirDocumentoNuevo("Rem") + End If + End Sub +#End Region - Protected Sub BtnGeneraAutorizacion_Click(sender As Object, e As EventArgs) - If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then - - EmitirDocumentoNuevo("PA") - End If +#Region "GENERAR AUTORIZACIÓN" + + Protected Sub BtnGeneraAutorizacion_Click(sender As Object, e As EventArgs) + If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then + + EmitirDocumentoNuevo("PA") + End If End Sub -#End Region +#End Region + +#Region " EMITIR DOCUMENTO NUEVO " + Private Sub EmitirDocumentoNuevo(TipoDoctoNuevo As String) + Dim FolioFijo As Integer = 0 + 'CARGA LO PENDIENTE POR FACTURAR DE COTIZACION + If EraCotizacion = 1 Then + If Not PreparaFacturarCotizacion() Then + EraCotizacion = 0 + DdlTipoComprobante.SelectedValue = "Cot" + Exit Sub + End If + End If + + 'CARGA LO PENDIENTE POR FACTURAR DE REMISION + If DdlTipoComprobante.SelectedValue = "Rem" Then + If Not PreparaFacturarRemision() Then + DdlTipoComprobante.SelectedValue = "Rem" + Exit Sub + End If + End If + + 'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO2 + If DdlTipoComprobante.SelectedValue = "Pd2" Then + If Not PreparaFacturarPedido() Then + DdlTipoComprobante.SelectedValue = "Pd2" + Exit Sub + End If + End If + + 'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO AUTORIZACION + If DdlTipoComprobante.SelectedValue = "PA" Then ' que tome el folio fijo de la autorización + FolioFijo = TxtFolio.Text.ToEntero + ViewState("FolioActual") = FolioFijo + ViewState("EstablecioFolio") = True + TxtFolio.Text = FolioFijo.ToString + End If + + Dim TipoDoctoViejo As String = DdlTipoComprobante.SelectedValue + DdlTipoComprobante.SelectedValue = TipoDoctoNuevo + TxtFecha.Text = Now.ToString + TxtFechaPago.Text = If(TipoDoctoViejo = "Rem" AndAlso EsDiasCreditoFijo, Now.AddDays(DiasCredito), If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza))).ToShortDateString + TxtFechaEjecucion.Text = Now.ToString + + + If FolioFijo = 0 Then CargaFolios() 'RECARGA FOLIOS CON EL NUEVO TIPO DOCTO + EmitirImprimir() 'MANDA A EMITIR - PROCESO VIEJO -#Region " EMITIR DOCUMENTO NUEVO " - Private Sub EmitirDocumentoNuevo(TipoDoctoNuevo As String) - Dim FolioFijo As Integer = 0 - 'CARGA LO PENDIENTE POR FACTURAR DE COTIZACION - If EraCotizacion = 1 Then - If Not PreparaFacturarCotizacion() Then - EraCotizacion = 0 - DdlTipoComprobante.SelectedValue = "Cot" - Exit Sub - End If - End If - - 'CARGA LO PENDIENTE POR FACTURAR DE REMISION - If DdlTipoComprobante.SelectedValue = "Rem" Then - If Not PreparaFacturarRemision() Then - DdlTipoComprobante.SelectedValue = "Rem" - Exit Sub - End If - End If - - 'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO2 - If DdlTipoComprobante.SelectedValue = "Pd2" Then - If Not PreparaFacturarPedido() Then - DdlTipoComprobante.SelectedValue = "Pd2" - Exit Sub - End If - End If - - 'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO AUTORIZACION - If DdlTipoComprobante.SelectedValue = "PA" Then ' que tome el folio fijo de la autorización - FolioFijo = TxtFolio.Text.ToEntero - ViewState("FolioActual") = FolioFijo - ViewState("EstablecioFolio") = True - TxtFolio.Text = FolioFijo.ToString - End If - - Dim TipoDoctoViejo As String = DdlTipoComprobante.SelectedValue - DdlTipoComprobante.SelectedValue = TipoDoctoNuevo - TxtFecha.Text = Now.ToString - TxtFechaPago.Text = If(TipoDoctoViejo = "Rem" AndAlso EsDiasCreditoFijo, Now.AddDays(DiasCredito), If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza))).ToShortDateString - TxtFechaEjecucion.Text = Now.ToString - - - If FolioFijo = 0 Then CargaFolios() 'RECARGA FOLIOS CON EL NUEVO TIPO DOCTO - EmitirImprimir() 'MANDA A EMITIR - PROCESO VIEJO - End Sub -#End Region +#End Region -#End Region +#End Region -#Region "ACTUALIZAR FECHA DE VENCIMIENTO" +#Region "ACTUALIZAR FECHA DE VENCIMIENTO" - Protected Sub LnkUpdateFechaVencimiento_Click(sender As Object, e As EventArgs) - Dim ObjVentas As New ClsVentas - Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) - Dim ErrorTrans As Boolean = False - Dim FechaVencimientoAnterior As String = "" - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - If ObjVentas.DtResultados.Rows.Count > 0 Then - FechaVencimientoAnterior = ObjVentas.DtResultados.Rows(0)("FechaVencimiento").ToString.ToDate.ToShortDateString - Else - ErrorTrans = True - End If - End If - - If FechaVencimientoAnterior = TxtFechaPago.Text Then - Alert("La fecha de pago seleccionada es igual que la anterior.", TipoMensaje.MsgAdvertencia) - ObjVentas.RollBack() - ObjVentas.Dispose() - ObjEventos.Dispose() - Exit Sub - End If - - If Not ObjVentas.UpdateFechaVencimientoVenta(CveVenta, TxtFechaPago.Text.ToDate) Then - ErrorTrans = True - End If - - If Not ObjEventos.AddEventoBitacora($"Se actualizo la fecha de pago. Anterior:{FechaVencimientoAnterior} Actual:{TxtFechaPago.Text}.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - ErrorTrans = True - End If - - If Not ErrorTrans Then - ObjVentas.Commit() - Alert("Fecha de pago actualizada correctamente.") - Else - ObjVentas.RollBack() - End If - ObjVentas.Dispose() - ObjEventos.Dispose() - End Sub - Private Sub BtnRefrescarPagina_Click(sender As Object, e As EventArgs) Handles BtnRefrescarPagina.Click - Response.Redirect($"~/Ventas/Ventas.aspx?CveVenta={Me.CveVenta}") + Protected Sub LnkUpdateFechaVencimiento_Click(sender As Object, e As EventArgs) + Dim ObjVentas As New ClsVentas + Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) + Dim ErrorTrans As Boolean = False + Dim FechaVencimientoAnterior As String = "" + + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + FechaVencimientoAnterior = ObjVentas.DtResultados.Rows(0)("FechaVencimiento").ToString.ToDate.ToShortDateString + Else + ErrorTrans = True + End If + End If + + If FechaVencimientoAnterior = TxtFechaPago.Text Then + Alert("La fecha de pago seleccionada es igual que la anterior.", TipoMensaje.MsgAdvertencia) + ObjVentas.RollBack() + ObjVentas.Dispose() + ObjEventos.Dispose() + Exit Sub + End If + + If Not ObjVentas.UpdateFechaVencimientoVenta(CveVenta, TxtFechaPago.Text.ToDate) Then + ErrorTrans = True + End If + + If Not ObjEventos.AddEventoBitacora($"Se actualizo la fecha de pago. Anterior:{FechaVencimientoAnterior} Actual:{TxtFechaPago.Text}.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + ErrorTrans = True + End If + + If Not ErrorTrans Then + ObjVentas.Commit() + Alert("Fecha de pago actualizada correctamente.") + Else + ObjVentas.RollBack() + End If + ObjVentas.Dispose() + ObjEventos.Dispose() + End Sub + Private Sub BtnRefrescarPagina_Click(sender As Object, e As EventArgs) Handles BtnRefrescarPagina.Click + Response.Redirect($"~/Ventas/Ventas.aspx?CveVenta={Me.CveVenta}") End Sub -#End Region +#End Region -#Region "U S A D O S" +#Region "U S A D O S" - Private Sub CalculaUsados() - - - If ClienteEsDistribuidor Then - - Dim DTTamanios As New DataTable - Dim ObjAcum As New ClsAcumuladores - - If ObjAcum.TamañoGet(-1, UsuarioActual.CveEmpresa) Then - - DTTamanios = ObjAcum.DtResultados - - Dim DTCvePSCostos As New DataTable - DTCvePSCostos = ObjAcum.DtResultados.FiltraParametros("", "", {"CvePSCargo"}) - - If Not TmpDT.Columns.Contains("Eliminar") Then - TmpDT.Columns.Add("Eliminar", GetType(Integer)) - End If - - For Each drow As DataRow In TmpDT.Rows - For Each drow2 As DataRow In DTCvePSCostos.Rows - If drow("CvePS").ToString.ToEntero = drow2("CvePSCargo").ToString.ToEntero Then - drow("Eliminar") = 1 - Exit For - End If - Next - Next - - Dim TmpDTView As New DataView(TmpDT) - TmpDTView.RowFilter = "Eliminar = 1" - - For Each dRowEliminar As DataRowView In TmpDTView - dRowEliminar.Delete() - - Next - - - TmpDT.AcceptChanges() - - Dim ObjProductosServicios As New ClsProductosServicios() - - Dim CveUnidadMedidaPSA As Integer = -1 - Dim UnidadMedidaPSA As String = "Unidad" - Dim CveClacificacionPSA As Integer = -1 - - Dim ClacificacionPSA As String = "" - - Dim CveSubProyectoPSA As Integer = -1 - Dim SubProyectoPSA As String = "" - - Dim PSPSA As String = "" - - Dim DTPSTemp As New DataTable '= TmpDT.Clone - 'AgregarProductoServicio(1, CveUnidadMedidaPSA, UnidadMedidaPSA, CveClacificacionPSA, ClacificacionPSA, CvePSPSA, PSPSA, "", ImporteCargo, 0, -1, "", CveSubProyectoPSA, SubProyectoPSA) - DTPSTemp.Columns.Add("Cantidad", GetType(Integer)) - DTPSTemp.Columns.Add("CveUnidadMedida", GetType(Integer)) - DTPSTemp.Columns.Add("UnidadMedida", GetType(String)) - DTPSTemp.Columns.Add("CveClacificacion", GetType(Integer)) - DTPSTemp.Columns.Add("Clacificacion", GetType(String)) - DTPSTemp.Columns.Add("CvePS", GetType(Integer)) - DTPSTemp.Columns.Add("PS", GetType(String)) - DTPSTemp.Columns.Add("PU", GetType(Decimal)) - DTPSTemp.Columns.Add("CveSubProyecto", GetType(Integer)) - DTPSTemp.Columns.Add("SubProyecto", GetType(String)) - - For Each DrowPartidas As DataRow In TmpDT.Rows - Dim CveTamanioTemp As Integer = DrowPartidas("CveTamaño").ToString.ToEntero - - If CveTamanioTemp > 0 Then - - Dim DTTamanioTemp As New DataTable - Dim CvePsTemp As Integer = DTTamanios.FiltraParametros($"CveTamaño = { CveTamanioTemp } ").Rows(0)("CvePSCargo").ToString.ToEntero - - - CveSubProyectoPSA = DrowPartidas("CveSubProyecto").ToString.ToEntero - SubProyectoPSA = DrowPartidas("SubProyecto").ToString - - If ObjProductosServicios.GetPS(CvePsTemp, -1, UsuarioActual.CveEmpresa) Then - CveUnidadMedidaPSA = ObjProductosServicios.CveUnidadMedida - CveClacificacionPSA = ObjProductosServicios.CveClasificacion - UnidadMedidaPSA = ObjProductosServicios.DtResultados.FiltroPrimeroValor("UnidadMedida") - PSPSA = ObjProductosServicios.PS - End If - - - If UsuarioActual.Empresa.UsaAC Then - ClacificacionPSA = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, CveClacificacionPSA, -1)).FiltroPrimeroValor("Clasificacion", " Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") - Else - ClacificacionPSA = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, CveClacificacionPSA, -1)).FiltroPrimeroValor("Clasificacion", Orderby:="Clasificacion") - End If - - Dim Cargo As Decimal = DTTamanios.FiltroPrimeroValor("Cargo", $" CveTamaño = { CveTamanioTemp }").ToDecimal - - - If DTPSTemp.FiltraParametros($"CvePs = { CvePsTemp }").Rows.Count > 0 Then - - For Each dRowUpdate As DataRow In DTPSTemp.Rows - - If (dRowUpdate("CvePS").ToString.ToEntero = CvePsTemp) Then - dRowUpdate("Cantidad") = dRowUpdate("Cantidad").ToString.ToDecimal + DrowPartidas("Cantidad").ToString.ToDecimal - dRowUpdate("PU") = Cargo ' dRowUpdate("Total").ToString.ToDecimal + ImporteCargo - End If - Next - - DTPSTemp.AcceptChanges() - - Else - Dim dRowNuevo As DataRow = DTPSTemp.NewRow - - dRowNuevo("Cantidad") = DrowPartidas("Cantidad").ToString.ToDecimal - dRowNuevo("PU") = Cargo - dRowNuevo("CveUnidadMedida") = CveUnidadMedidaPSA - dRowNuevo("UnidadMedida") = UnidadMedidaPSA - dRowNuevo("CveClacificacion") = CveClacificacionPSA - dRowNuevo("Clacificacion") = ClacificacionPSA - dRowNuevo("CvePS") = CvePsTemp - dRowNuevo("PS") = PSPSA - - dRowNuevo("CveSubProyecto") = DrowPartidas("CveSubProyecto").ToString.ToEntero - dRowNuevo("SubProyecto") = DrowPartidas("SubProyecto").ToString - - DTPSTemp.Rows.Add(dRowNuevo) - DTPSTemp.AcceptChanges() - End If - - End If - Next - - - For Each drowPsTamaños As DataRow In DTPSTemp.Rows - Modalidad = "A" - If drowPsTamaños("PU").ToString.ToDecimal > 0 Then - AgregarProductoServicio(drowPsTamaños("Cantidad").ToString.ToEntero, drowPsTamaños("CveUnidadMedida").ToString.ToEntero, drowPsTamaños("UnidadMedida").ToString, - drowPsTamaños("CveClacificacion").ToString.ToEntero, drowPsTamaños("Clacificacion").ToString, drowPsTamaños("CvePS").ToString.ToEntero, - drowPsTamaños("PS").ToString, "", drowPsTamaños("PU").ToString.ToDecimal, 0, -1, "", drowPsTamaños("CveSubProyecto").ToString.ToEntero, - drowPsTamaños("SubProyecto").ToString) - End If - Next - - ObjProductosServicios.Dispose() - End If - - ObjAcum.Dispose() - End If - - - End Sub - - Private Function GuardarUsados(SqlTransaccion As SqlClient.SqlTransaction, CveVenta As Integer) As Boolean - Dim Resultado As Boolean = True - - If ClienteEsDistribuidor Then - 'If UsuarioActual.Empresa.Funcionalidad(533).ToEntero > 0 Then - ' Dim CvePSPSA As Integer = UsuarioActual.Empresa.Funcionalidad(533).ToEntero - - Dim ObjAcum As New ClsAcumuladores(SqlTransaccion) - - - For Each drow As DataRow In TmpDT.Rows - If drow("CveTamaño").ToString.ToEntero > 0 Then - Dim TempDTAcums = GlobalDTAcumTamaños.FiltraParametros("CvePSCargo = " & drow("CvePS").ToString) - If TempDTAcums IsNot Nothing AndAlso TempDTAcums.Rows.Count > 0 Then - If Not ObjAcum.DistribuidorMovtosAdd(CveCliente, drow("Cantidad").ToString.ToEntero, drow("CveTamaño").ToString.ToEntero, 2, CveVenta, UsuarioActual.CveUsuario, - UsuarioActual.CveEmpresa, 0D, "") Then - Resultado = False - Exit For - End If - Else - Resultado = True - End If - TempDTAcums.Dispose() - End If - Next - Else - Resultado = True - End If - - Return Resultado - + Private Sub CalculaUsados() + + + If ClienteEsDistribuidor Then + + Dim DTTamanios As New DataTable + Dim ObjAcum As New ClsAcumuladores + + If ObjAcum.TamañoGet(-1, UsuarioActual.CveEmpresa) Then + + DTTamanios = ObjAcum.DtResultados + + Dim DTCvePSCostos As New DataTable + DTCvePSCostos = ObjAcum.DtResultados.FiltraParametros("", "", {"CvePSCargo"}) + + If Not TmpDT.Columns.Contains("Eliminar") Then + TmpDT.Columns.Add("Eliminar", GetType(Integer)) + End If + + For Each drow As DataRow In TmpDT.Rows + For Each drow2 As DataRow In DTCvePSCostos.Rows + If drow("CvePS").ToString.ToEntero = drow2("CvePSCargo").ToString.ToEntero Then + drow("Eliminar") = 1 + Exit For + End If + Next + Next + + Dim TmpDTView As New DataView(TmpDT) + TmpDTView.RowFilter = "Eliminar = 1" + + For Each dRowEliminar As DataRowView In TmpDTView + dRowEliminar.Delete() + + Next + + + TmpDT.AcceptChanges() + + Dim ObjProductosServicios As New ClsProductosServicios() + + Dim CveUnidadMedidaPSA As Integer = -1 + Dim UnidadMedidaPSA As String = "Unidad" + Dim CveClacificacionPSA As Integer = -1 + + Dim ClacificacionPSA As String = "" + + Dim CveSubProyectoPSA As Integer = -1 + Dim SubProyectoPSA As String = "" + + Dim PSPSA As String = "" + + Dim DTPSTemp As New DataTable '= TmpDT.Clone + 'AgregarProductoServicio(1, CveUnidadMedidaPSA, UnidadMedidaPSA, CveClacificacionPSA, ClacificacionPSA, CvePSPSA, PSPSA, "", ImporteCargo, 0, -1, "", CveSubProyectoPSA, SubProyectoPSA) + DTPSTemp.Columns.Add("Cantidad", GetType(Integer)) + DTPSTemp.Columns.Add("CveUnidadMedida", GetType(Integer)) + DTPSTemp.Columns.Add("UnidadMedida", GetType(String)) + DTPSTemp.Columns.Add("CveClacificacion", GetType(Integer)) + DTPSTemp.Columns.Add("Clacificacion", GetType(String)) + DTPSTemp.Columns.Add("CvePS", GetType(Integer)) + DTPSTemp.Columns.Add("PS", GetType(String)) + DTPSTemp.Columns.Add("PU", GetType(Decimal)) + DTPSTemp.Columns.Add("CveSubProyecto", GetType(Integer)) + DTPSTemp.Columns.Add("SubProyecto", GetType(String)) + + For Each DrowPartidas As DataRow In TmpDT.Rows + Dim CveTamanioTemp As Integer = DrowPartidas("CveTamaño").ToString.ToEntero + + If CveTamanioTemp > 0 Then + + Dim DTTamanioTemp As New DataTable + Dim CvePsTemp As Integer = DTTamanios.FiltraParametros($"CveTamaño = { CveTamanioTemp } ").Rows(0)("CvePSCargo").ToString.ToEntero + + + CveSubProyectoPSA = DrowPartidas("CveSubProyecto").ToString.ToEntero + SubProyectoPSA = DrowPartidas("SubProyecto").ToString + + If ObjProductosServicios.GetPS(CvePsTemp, -1, UsuarioActual.CveEmpresa) Then + CveUnidadMedidaPSA = ObjProductosServicios.CveUnidadMedida + CveClacificacionPSA = ObjProductosServicios.CveClasificacion + UnidadMedidaPSA = ObjProductosServicios.DtResultados.FiltroPrimeroValor("UnidadMedida") + PSPSA = ObjProductosServicios.PS + End If + + + If UsuarioActual.Empresa.UsaAC Then + ClacificacionPSA = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, CveClacificacionPSA, -1)).FiltroPrimeroValor("Clasificacion", " Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") + Else + ClacificacionPSA = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, CveClacificacionPSA, -1)).FiltroPrimeroValor("Clasificacion", Orderby:="Clasificacion") + End If + + Dim Cargo As Decimal = DTTamanios.FiltroPrimeroValor("Cargo", $" CveTamaño = { CveTamanioTemp }").ToDecimal + + + If DTPSTemp.FiltraParametros($"CvePs = { CvePsTemp }").Rows.Count > 0 Then + + For Each dRowUpdate As DataRow In DTPSTemp.Rows + + If (dRowUpdate("CvePS").ToString.ToEntero = CvePsTemp) Then + dRowUpdate("Cantidad") = dRowUpdate("Cantidad").ToString.ToDecimal + DrowPartidas("Cantidad").ToString.ToDecimal + dRowUpdate("PU") = Cargo ' dRowUpdate("Total").ToString.ToDecimal + ImporteCargo + End If + Next + + DTPSTemp.AcceptChanges() + + Else + Dim dRowNuevo As DataRow = DTPSTemp.NewRow + + dRowNuevo("Cantidad") = DrowPartidas("Cantidad").ToString.ToDecimal + dRowNuevo("PU") = Cargo + dRowNuevo("CveUnidadMedida") = CveUnidadMedidaPSA + dRowNuevo("UnidadMedida") = UnidadMedidaPSA + dRowNuevo("CveClacificacion") = CveClacificacionPSA + dRowNuevo("Clacificacion") = ClacificacionPSA + dRowNuevo("CvePS") = CvePsTemp + dRowNuevo("PS") = PSPSA + + dRowNuevo("CveSubProyecto") = DrowPartidas("CveSubProyecto").ToString.ToEntero + dRowNuevo("SubProyecto") = DrowPartidas("SubProyecto").ToString + + DTPSTemp.Rows.Add(dRowNuevo) + DTPSTemp.AcceptChanges() + End If + + End If + Next + + + For Each drowPsTamaños As DataRow In DTPSTemp.Rows + Modalidad = "A" + If drowPsTamaños("PU").ToString.ToDecimal > 0 Then + AgregarProductoServicio(drowPsTamaños("Cantidad").ToString.ToEntero, drowPsTamaños("CveUnidadMedida").ToString.ToEntero, drowPsTamaños("UnidadMedida").ToString, + drowPsTamaños("CveClacificacion").ToString.ToEntero, drowPsTamaños("Clacificacion").ToString, drowPsTamaños("CvePS").ToString.ToEntero, + drowPsTamaños("PS").ToString, "", drowPsTamaños("PU").ToString.ToDecimal, 0, -1, "", drowPsTamaños("CveSubProyecto").ToString.ToEntero, + drowPsTamaños("SubProyecto").ToString) + End If + Next + + ObjProductosServicios.Dispose() + End If + + ObjAcum.Dispose() + End If + + + End Sub + + Private Function GuardarUsados(SqlTransaccion As SqlClient.SqlTransaction, CveVenta As Integer) As Boolean + Dim Resultado As Boolean = True + + If ClienteEsDistribuidor Then + 'If UsuarioActual.Empresa.Funcionalidad(533).ToEntero > 0 Then + ' Dim CvePSPSA As Integer = UsuarioActual.Empresa.Funcionalidad(533).ToEntero + + Dim ObjAcum As New ClsAcumuladores(SqlTransaccion) + + + For Each drow As DataRow In TmpDT.Rows + If drow("CveTamaño").ToString.ToEntero > 0 Then + Dim TempDTAcums = GlobalDTAcumTamaños.FiltraParametros("CvePSCargo = " & drow("CvePS").ToString) + If TempDTAcums IsNot Nothing AndAlso TempDTAcums.Rows.Count > 0 Then + If Not ObjAcum.DistribuidorMovtosAdd(CveCliente, drow("Cantidad").ToString.ToEntero, drow("CveTamaño").ToString.ToEntero, 2, CveVenta, UsuarioActual.CveUsuario, + UsuarioActual.CveEmpresa, 0D, "") Then + Resultado = False + Exit For + End If + Else + Resultado = True + End If + TempDTAcums.Dispose() + End If + Next + Else + Resultado = True + End If + + Return Resultado + End Function -#End Region +#End Region -#Region "PORCENTAJE IVA" - Protected Sub DdlIVA_SelectedIndexChanged(sender As Object, e As EventArgs) - If Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0 Then RecalculaIVA() - End Sub - - Private Sub RecalculaIVA() - PorcentajeIVA = Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2).ToDecimal - For Each Row As DataRow In TmpDT.Rows - If PorcentajeIVA > 0 Then - Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=Row("CvePS").ToString.ToEntero).FiltroPrimero("") - If DrPS IsNot Nothing Then - If DrPS("IVA").ToString.Contiene("-1", "") Then - Row("PorcentajeIVA") = PorcentajeIVA - Else - Row("PorcentajeIVA") = DrPS("IVA") - End If - Dim TotalCalculableImpuestos = (Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble) - Row("Descuento").ToString.ToDouble - Row("IVA") = Row("PorcentajeIVA").ToString.ToDouble - Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDouble * TotalCalculableImpuestos, NumeroDecimales) - End If - Else - Row("IVA") = 0 - Row("PorcentajeIVA") = 0 - Row("ImporteIVA") = 0 - End If - Next - CalculaTotalesVenta() +#Region "PORCENTAJE IVA" + Protected Sub DdlIVA_SelectedIndexChanged(sender As Object, e As EventArgs) + If Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0 Then RecalculaIVA() End Sub -#End Region + Private Sub RecalculaIVA() + PorcentajeIVA = Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2).ToDecimal + For Each Row As DataRow In TmpDT.Rows + If PorcentajeIVA > 0 Then + Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=Row("CvePS").ToString.ToEntero).FiltroPrimero("") + If DrPS IsNot Nothing Then + If DrPS("IVA").ToString.Contiene("-1", "") Then + Row("PorcentajeIVA") = PorcentajeIVA + Else + Row("PorcentajeIVA") = DrPS("IVA") + End If + Dim TotalCalculableImpuestos = (Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble) - Row("Descuento").ToString.ToDouble + Row("IVA") = Row("PorcentajeIVA").ToString.ToDouble + Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDouble * TotalCalculableImpuestos, NumeroDecimales) + End If + Else + Row("IVA") = 0 + Row("PorcentajeIVA") = 0 + Row("ImporteIVA") = 0 + End If + Next + CalculaTotalesVenta() + End Sub + +#End Region End Class \ No newline at end of file