Option Explicit On Option Strict On Imports Extensiones Imports System.Data Imports System.IO Imports System.Linq Imports System.Security.Cryptography.X509Certificates Imports System.Globalization Imports System.Net.Http Imports Microsoft.Reporting.WebForms Partial Class PV Inherits ClsPaginas #Region "PROPIEDADES" Private Const NumeroDecimales As Integer = 2 Dim ColumnaDescuento As Integer = 6 Dim ColumnaIVA As Integer = 7 Dim ColumnaIEPS As Integer = 8 Dim ColumnaRetIVA As Integer = 9 Dim ColumnaRetISR As Integer = 10 Dim ColumnaEditar As Integer = 12 Dim ColumnaEliminar As Integer = 13 '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 EsSupervisor As Boolean = False Private Property MandarCorreoSupervisor As Boolean = False Public Property EstablecioFolio As Boolean Get Return CBool(ViewState("EstablecioFolio").ToString) End Get Set(value As Boolean) ViewState("EstablecioFolio") = value End Set End Property 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 IdPoliza As Integer Get Return ViewState("IdPoliza").ToString.ToEntero End Get Set(value As Integer) ViewState("IdPoliza") = 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 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 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 EmpresaActual As Empresa Get Return CType(ViewState("EmpresaActual"), Empresa) End Get Set(value As Empresa) ViewState("EmpresaActual") = value End Set End Property Private ReadOnly Property CveCliente As Integer Get Return ViewState("CveCliente").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 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 ReadOnly Property CveDevolucion As Integer Get Return ViewState("CveDevolucion").ToString.ToEntero End Get 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 FolioFiscal As String Get Return ViewState("FolioFiscal").ToString End Get End Property Private ReadOnly Property Ruta As String Get Return ModExtensiones.DirectorioBaseEmpresas & "Empresas\" & UsuarioActual.CveEmpresa & "\" End Get End Property Private ReadOnly Property RutaPruebas As String Get Return ModExtensiones.DirectorioBaseEmpresas & "Empresas\1\" End Get End Property Private ReadOnly Property TipoCambio As Double Get Return ViewState("TipoCambio").ToString.ToDouble End Get End Property Private ReadOnly Property ProcesoCorrecto As Boolean Get Return CBool(ViewState("ProcesoCorrecto")) End Get 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 Double Get Return ViewState("IVA").ToString.ToDouble 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 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 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 IdCtaContDSV As Integer Get Return ViewState("IdCtaContDSV").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 ReadOnly Property AplicaFEMSA As Boolean Get Return CBool(ViewState("AplicaFEMSA")) 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 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 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 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 CveVentaDetalle As Integer Get Return If(ViewState("CveVentaDetalle") Is Nothing, -1, ViewState("CveVentaDetalle").ToString.ToEntero) End Get Set(value As Integer) ViewState("CveVentaDetalle") = 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 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 '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 DevolucionAlmacen As Integer Get Return ViewState("DevolucionAlmacen").ToString.ToEntero End Get Set(value As Integer) ViewState("DevolucionAlmacen") = 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 PlazoCobranza As Integer Get Return ViewState("PlazoCobranza").ToString.ToEntero End Get Set(value As Integer) ViewState("PlazoCobranza") = value End Set End Property Private ReadOnly Property SubProyectoPorcentajeIVA As Decimal Get Return ViewState("SubProyectoPorcentajeIVA").ToString.ToDecimal End Get 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 EnviarCorreoCliente As Boolean Get Return CBool(ViewState("EnviarCorreoCliente").ToString) End Get Set(value As Boolean) ViewState("EnviarCorreoCliente") = value End Set End Property Private ReadOnly Property ClasificacionesDescuentos As Dictionary(Of Integer, Decimal) Get Return New Dictionary(Of Integer, Decimal) From { {20516, 0.23D}, 'Descuento para lubricantes LTH {20515, 0.24D} 'Descuento para filtros LTH } End Get End Property #End Region #Region "PROPIEDADES DE PUNTO DE VENTA" 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 Property TmpDTMetodosPago As DataTable Get Return If(IsNothing(ViewState("TmpDTMetodosPago")), Nothing, CType(ViewState("TmpDTMetodosPago"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTMetodosPago") = value End Set End Property Private Property DTBCIUsados As DataTable Get Return If(IsNothing(ViewState("DTBCIUsados")), Nothing, CType(ViewState("DTBCIUsados"), DataTable)) End Get Set(value As DataTable) ViewState("DTBCIUsados") = 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 #End Region #Region " PROPIEDADES NUEVAS | GUARDAR - IMPRESION | IPP " 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 #End Region #Region " PROPIEDADES OC " Private Property CveOC As Integer Get Return ViewState("CveOC").ToString.ToEntero End Get Set(value As Integer) ViewState("CveOC") = value End Set End Property #End Region #Region "PROPIEDADES DATATABLE" 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 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 DTPresupuestoIngresos As DataTable Get Return CType(ViewState("DTPresupuestoIngresos"), DataTable) End Get Set(value As DataTable) ViewState("DTPresupuestoIngresos") = value End Set End Property 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 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 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 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 TmpDTAjustes As DataTable Get Return If(IsNothing(ViewState("TmpDTAjustes")), Nothing, CType(ViewState("TmpDTAjustes"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTAjustes") = value End Set End Property Private Property TmpDTRecepcionUsados As DataTable Get Return If(IsNothing(ViewState("TmpDTRecepcionUsados")), Nothing, CType(ViewState("TmpDTRecepcionUsados"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTRecepcionUsados") = value End Set End Property Private Property TmpDTPolizaVirtual As DataTable Get Return If(IsNothing(ViewState("TmpDTPolizaVirtual")), Nothing, CType(ViewState("TmpDTPolizaVirtual"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTPolizaVirtual") = 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 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 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 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 DtPagos As DataTable Get Return CType(ViewState("DtPagos"), DataTable) End Get Set(value As DataTable) ViewState("DtPagos") = value End Set End Property Private Property DtPUFacturas As DataTable Get Return CType(ViewState("DtPUFacturas"), DataTable) End Get Set(value As DataTable) ViewState("DtPUFacturas") = value End Set End Property Private Property DtModelosAuto As DataTable Get Return CType(ViewState("DtModelosAuto"), DataTable) End Get Set(value As DataTable) ViewState("DtModelosAuto") = value End Set End Property #End Region #Region "PROPIEDADES ACUMULADORES" Private Property ConsecutivoVenta As Integer Get Return ViewState("ConsecutivoVenta").ToString.ToEntero End Get Set(value As Integer) ViewState("ConsecutivoVenta") = value End Set End Property Private Property ModalidadAjuste As String Get Return ViewState("ModalidadAjuste").ToString End Get Set(value As String) ViewState("ModalidadAjuste") = value End Set End Property Private Property IndexAjuste As Integer Get Return ViewState("IndexAjuste").ToString.ToEntero End Get Set(value As Integer) ViewState("IndexAjuste") = value End Set End Property #End Region Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not IsPostBack Then DdlBPPS.setEsWebService(True) DdlBPPS.ddlWS.Attributes.Add("data-clear", "1") ViewState("ProcesoCorrecto") = True ViewState("NuevaFactura") = -1 ViewState("CveDevolucion") = -1 ViewState("CvePedido") = -1 ViewState("TipoContrato") = -1 ViewState("CveVenta") = -1 ViewState("CveOS") = -1 ViewState("CveFactura") = -1 ViewState("CveMetodoPagoCliente") = -1 ViewState("Entrega") = "" ViewState("Vigencia") = "" ViewState("AplicarVentaFacturada") = False ViewState("SeGuardoPrePoliza") = False ViewState("SubProyectoPorcentajeIVA") = 0 ViewState("ClienteDesglosaIEPS") = False ViewState("ClienteRetIVA") = 0 ViewState("ClienteRetISR") = 0 ViewState("EnviarCorreoCliente") = False CveVentaDetalle = -1 EstablecioFolio = False EstatusCliente = False RemisionesLista = New List(Of Integer) CvePrePoliza = 0 TotalOtrosConceptos = 0 CveUsuarioActual = UsuarioActual.CveUsuario EmpresaActual = UsuarioActual.Empresa IdPoliza = 0 CveCorte = -1 CveContrato = -1 DevolucionAlmacen = 0 CvePSAmortizacion = 0 PlazoCobranza = 0 IndexAjuste = 0 ConsecutivoVenta = 0 ModalidadAjuste = "" EsCreaApartirDe = False RequiereAlmacenDestino = False TmpDTComplementos = New DataTable DtPUFacturas = New DataTable Modalidad = "" Index = -1 If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ChkAjuste.Visible = True Else ChkAjuste.Visible = False End If If UsuarioActual.CveEmpresa = 72 Then TabAlmacen.Visible = False End If SetValues() CvePresupuesto = 0 'MODALIDADES If Request("Op") IsNot Nothing AndAlso Request("Op").ToString <> "" Then Opcion = Request("Op").ToString Else Opcion = "Ing" End If 'proceso 163, que activa al edicion de folios. TxtFecha.Text = Now.ToShortDateString() LblUsuario.Text = UsuarioActual.Usuario TxtCantidad.Attributes.Add("onKeyUp ", "Recalcula();") TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();") 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.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 = '';") 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();") 'ImgCerrarEstadoCaja.Attributes.Add("OnClick", "$('#DivEstadoCaja').hide();") TxtPorDescP.Attributes.Add("onKeyUp", "CalculaDescuento();") TxtDescP.Attributes.Add("onKeyUp", "CalculaDescuentoMonto();") 'TxtFechaAjuste.Attributes.Add("onchange", "CalculaMesesUso();") CreaDTmpC() CreaDTmpF() CargaDdlSubProyectos() CargaSucursales() CargaClasificaciones() CargaPS(-1, DdlPS) CargaPS(-1, DdlPSAjuste, AplicaAlmacen:=False) CargaEmpresa() CreaDTVentas() CargaMetodosPago() CargaUsoCFDI() CargaMonedas() CargaVendedores() CambiaTipoDocto() CargarAlmacenes() CargaFormaEntrega() CargaCuentasTerminal() If UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then CargaAjuste() RVPorDesc.MaximumValue = UsuarioActual.DescuentoAutorizado.ToString RVPorDesc.ErrorMessage = $"El rango para el % de descuento debe de estar entre 0 y {UsuarioActual.DescuentoAutorizado.ToString}." End If LimpiaEscondeContado() '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) 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 CargaCliente(CveCliente) Else ViewState("CveCliente") = -1 HdnCveCliente.Value = "-1" End If 'CARGA VENTA If Request("CveVenta") IsNot Nothing Then ViewState("CveVenta") = Request("CveVenta").ToString().ToEntero() CargaVenta() 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 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() '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 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() If Not UsuarioActual.CveEmpresa.Contiene(1, 119) Then 'PAGO CON TERMINAL PARA JAM RBLPago.Items.RemoveAt(2) End If 'CARGA VALORES INICIALES PARA AGREGAR PS DESDE MODAL CargaMetodosPSModal() If UsuarioActual.CveEmpresa.Contiene(72, 80, 1, 119) Then 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 If UsuarioActual.Empresa.Funcionalidad(569) = "1" Then DdlTipoComprobante.Items.Add(New ListItem("Remisión", "Rem")) DdlTipoComprobante.SelectedValueExist("Rem") End If DdlTipoDefecto.Width = New Unit(260%) 'Le quitamos el tamaño extra 'RegistraScript("window.onload = function AjustarVentana() { $('.page-content').css('min-height','100%'); }") 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 SerieFolioPadre As String Dim ObjVentas As New ClsVentas() Try 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 Dim ObjUsados As New ClsVentas Dim DtUsados As DataTable = Nothing If ObjUsados.GetVentasUsados(CveVenta, DdlSubProyectoDatos.SelectedValue.ToEntero(), DbRowVenta("Fecha").ToString.ToDateTime, UsuarioActual.CveEmpresa) Then DtUsados = ObjUsados.DtResultados End If ObjUsados.Dispose() 'Me.CveEstatusFacturaPadre = DbRowVenta("CveEstatusFacturaPadre").ToString.ToEntero 'CargaEncabezado DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString '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.Copy() TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) TmpDT.Columns.Add("ConsecPSPadre", GetType(Integer)) GvPS.DataSource = TmpDT GvPS.DataBind() End If 'ESCONDE ACCIONES UpnTools.Update() 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 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 DdlMoneda.SelectedValue = DbRowVenta("CveMoneda").ToString CambiaMoneda() If CveCliente > 0 Then 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 DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then TrTipoRelacion.Visible = True DdlTiposRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion").ToString.ToEntero) HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString End If 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 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) If TxtRetIVA.Text.ToDecimal() > 0 Then TrRetIVA.Style.Add("display", "") UsuarioActual.Empresa.MostrarRetIVA = True If TmpDT IsNot Nothing Then Dim PorcentajeRetIVA = (TmpDT.MAX("PorcentajeRetIVA").ToDecimal() * 100) LblRetIVA.Text = PorcentajeRetIVA.FormatoNumero(2) End If End If 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 LblSeTimbro.Text = DbRowVenta("SeTimbro").ToString LblMail.Text = DbRowVenta("EnvioMail").ToString TxtFechaPago.Text = DbRowVenta("FechaVencimiento").ToString TxtFechaVencimientoCotizacion.Text = Vigencia HdnIVAOriginal.Value = TxtIVA.Text DdlTiposRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion")) If DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then TrTipoRelacion2.Visible = True LblTipoRelacion.Text = DbRowVenta("TipoRelacion").ToString HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString 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 TxtTipoCambio.Text = DbRowVenta("TipoCambio").ToString 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 DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").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) CargarAlmacenes() CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString.ToEntero) If DbRowVenta("CveContrato").ToString.ToEntero > 0 Then CveContrato = DbRowVenta("CveContrato").ToString.ToEntero 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 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 '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 DeshabilitarEdicion() 'CargaLeyendasFiscales ViewState("VentaFolio") = If(LblSerie.Text.Trim.Length = 0, TxtFolio.Text.Trim, LblSerie.Text.Trim & "-" & TxtFolio.Text.Trim) CalculaTotalesVenta(False) tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") If DbRowVenta("TipoDocto").ToString = "Rem" Then For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = False Gvr.FCLinkButton("imgD").Visible = False Next 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR If TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then TrEmitir.Visible = False BtnPermisoEditarRemision.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 UsuarioActual.CveEmpresa = 48 Then TxtFecha.AutoPostBack = True End If UpPS.Update() UpContado.Update() UpEstatus.Update() Retorno = True Else ViewState("CveVenta") = -1 Alert("El documento solicitado no existe, favor de revisar su búsqueda.", TipoMensaje.MsgAdvertencia) End If End If Catch ex As Exception OnError("Ocurrió un error al cargar la venta", ex) End Try ObjVentas.Dispose() Return Retorno End Function #Region "E D I T A R - R E M I S I O N" Private Sub DeshabilitarEdicion() '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 TxtPrecio.Enabled = False ImgDescPU.Attributes.Clear() ImgDescTotal.Attributes.Clear() LbAgregar.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 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 'DdlSucursalEjecucion.Enabled = False 'DdlSucursalCobranza.Enabled = False DdlVendedor.Enabled = False DdlSucursalCliente.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) Else TxtFechaPago.ReadOnly = False End If imgCalendario.Enabled = False BtnEmitirImprimir.Visible = False End Sub Private Sub HabilitarEdicion() TxtCodigo.ReadOnly = False ChkEnviarFactura.Enabled = True ChkDireccionEnvio.Enabled = True TxtAtencionA.Enabled = True TxtFechaVencimientoCotizacion.Enabled = True TxtCantidad.Enabled = True DdlClasificacion.Enabled = True DdlPS.Enabled = True TxtObsPS.Enabled = True TxtPrecio.Enabled = True ImgDescPU.Attributes.Clear() ImgDescTotal.Attributes.Clear() LbAgregar.Enabled = True DdlCuentasTerminal.Enabled = True 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 = "" TxtObsFact.Enabled = True TxtMotivoDescuento.Enabled = True TxtSubTotal.ReadOnly = False TxtIVA.ReadOnly = False TxtRetIVA.ReadOnly = False TxtRetISR.ReadOnly = False TxtIEPS.ReadOnly = False TxtTotal.ReadOnly = False 'Sección Detalle DdlMoneda.Enabled = True DdlVendedor.Enabled = True DdlSucursalCliente.Enabled = True ChkConvertirDoctoPesos.Enabled = True ChkConvertirDolares.Enabled = True TxtTipoCambio.Enabled = True TxtTipoCambioDlls.Enabled = True 'Condiciones de Pago RBLPago.Enabled = True DdlFormaPago33.Enabled = True DdlUsoCFDI.Enabled = True DdlMetodoPago33.Enabled = True If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then TxtFechaPago.ReadOnly = Not UsuarioActual.TienePermisoProceso(260) Else TxtFechaPago.ReadOnly = False End If imgCalendario.Enabled = True End Sub Private Sub BtnPermisoEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarRemision.Click HabilitarEdicion() BtnPermisoEditarRemision.Visible = False BtnEditarRemision.Visible = True TxtObsFact.Enabled = True DdlUsoCFDI.Enabled = True DdlMetodoPago33.Enabled = True DdlFormaPago33.Enabled = True UPCondicionesPago.Update() RBLPago.Enabled = 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 AndAlso Gvr.DataKey("EsCargo") = "False" Gvr.FCLinkButton("imgD").Visible = Not Gvr.DataKey("CantidadInventario").ToString.ToDouble > 0 AndAlso Gvr.DataKey("EsCargo") = "False" CantidadFacturadaRemision += Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble Next 'ACTIVA CAMBIO DE CLIENTE - SI NO TIENE NADA FACTURADO If Not CantidadFacturadaRemision > 0 AndAlso UsuarioActual.TienePermisoProceso(284) 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 TxtPrecio.Enabled = True LbAgregar.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 CreaObjetosVenta() Dim ObjVentas As New ClsVentas ObjVentas.IniciaTransacSQL() Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) Dim ObjAcum As New ClsAcumuladores(ObjVentas.IniciaTransacSQL()) Dim ObjAC As ClsContPAQi = Nothing Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero Dim TipoCambio As Double = TxtTipoCambio.Text.ToDouble Try 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS If DdlMoneda.SelectedValue.ToEntero <> 2 AndAlso ChkConvertirDolares.Checked Then Dim TmpDTTotales As DataTable = TmpDT.FiltraParametros("EliminarDB = False") For Each Row As DataRow In TmpDTTotales.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 = TmpDTTotales.SUM("Total").ToDecimal.FormatoNumero LblDescuentos.Text = TmpDTTotales.SUM("Descuento").ToDecimal.FormatoNumero LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero TxtIVA.Text = TmpDTTotales.SUM("ImporteIVA").ToDecimal.FormatoNumero TxtRetIVA.Text = TmpDTTotales.SUM("ImporteRetIVA").ToDecimal.FormatoNumero TxtRetISR.Text = TmpDTTotales.SUM("ImporteRetISR").ToDecimal.FormatoNumero TxtIEPS.Text = TmpDTTotales.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 Dim TmpDTTotales As DataTable = TmpDT.FiltraParametros("EliminarDB = False") Dim Importe As Decimal Dim TCC As Decimal = TxtTipoCambio.Text.Trim.ToDecimal For Each Row As DataRow In TmpDTTotales.Rows Row("PU") = Math.Round(Row("PU").ToString.ToDecimal * TCC, 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 * TCC, NumeroDecimales) Importe = Row("Total").ToString.ToDecimal - Row("Descuento").ToString.ToDecimal Row("ImporteIEPS") = Math.Round(Importe * Row("PorcentajeIEPS").ToString.ToDecimal, NumeroDecimales) Row("ImporteIVA") = Math.Round(Importe * Row("PorcentajeIVA").ToString.ToDecimal, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Importe * Row("PorcentajeRetIVA").ToString.ToDecimal, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Importe * Row("PorcentajeRetISR").ToString.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 = TmpDTTotales.SUM("Total").ToDecimal.FormatoNumero LblDescuentos.Text = TmpDTTotales.SUM("Descuento").ToDecimal.FormatoNumero LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero TxtIVA.Text = TmpDTTotales.SUM("ImporteIVA").ToDecimal.FormatoNumero TxtRetIVA.Text = TmpDTTotales.SUM("ImporteRetIVA").ToDecimal.FormatoNumero TxtRetISR.Text = TmpDTTotales.SUM("ImporteRetISR").ToDecimal.FormatoNumero TxtIEPS.Text = TmpDTTotales.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 'ELIMINA LOS DETALLES If Not OcurrioError Then Dim DtEliminados As DataTable = TmpDT.FiltraParametros("EliminarDB = True AND CveVentaDetalle > 0", "", {"CveVentaDetalle"}) For Each Dr1 As DataRow In DtEliminados.Rows If Not ObjVentas.RemoveVentasDetalle(CveVenta, Dr1("CveVentaDetalle").ToString.ToEntero) Then OcurrioError = True End If Next 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:="", AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero, TipoDocto:="Rem", CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:="", RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal, Kilometraje:=0) 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.FiltraParametros("EliminarDB = False").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("PorcentajeIEPS").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("ImporteIEPS").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 If TmpDTRecepcionUsados IsNot Nothing Then If TmpDTRecepcionUsados.Select($"CvePS={Row("CvePS").ToString.ToEntero}").Length > 0 Then Dim rowInv As DataRow = TmpDTRecepcionUsados.Select($"CvePS={Row("CvePS").ToString.ToEntero}")(0) rowInv("CveVentaDetalle") = ObjVentas.CveVentaDetalle End If End If If TmpDTAjustes IsNot Nothing AndAlso TmpDTAjustes.Rows.Count > 0 Then If TmpDTAjustes.Select($"ConsecutivoVenta={Row("Consec").ToString.ToEntero}").Length > 0 Then Dim DrAju As DataRow = TmpDTAjustes.Select($"ConsecutivoVenta={Row("Consec").ToString.ToEntero}")(0) DrAju("CveVentaDetalle") = ObjVentas.CveVentaDetalle End If End If If TmpDTPolizaVirtual IsNot Nothing Then If TmpDTPolizaVirtual.Select($"CvePS={Row("CvePS").ToString.ToEntero}").Length > 0 Then Dim RowPoliza As DataRow = TmpDTPolizaVirtual.Select($"CvePS={Row("CvePS").ToString.ToEntero}")(0) RowPoliza("CveVentaDetalle") = ObjVentas.CveVentaDetalle End If End If End If End If index = index + 1 Next End If 'RECARGA LOS DATOS ObjFactura.Dispose() ObjFactura = Nothing ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa) If ObjFactura Is Nothing Then OcurrioError = True Else TmpDT = ObjFactura.DtDetalle TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) Dim NumRowsPS As Integer = 0 Dim CantidadPS As Decimal = 0 For Each GvRow As GridViewRow In GvPS.Rows If GvRow.RowType = DataControlRowType.DataRow Then NumRowsPS += 1 CantidadPS += GvRow.DataKey("Cantidad").ToDecimal() End If Next 'VALIDA NUMERO DE REGISTROS If TmpDT.Rows.Count <> NumRowsPS Then OcurrioError = True End If 'VALIDA CANTIDAD DE REGISTROS If TmpDT.SUM("Cantidad") <> CantidadPS Then OcurrioError = True End If End If 'GUARDA USADOS If Not OcurrioError AndAlso Not ObjVentas.EliminarUsados(CveVenta) Then OcurrioError = True End If If Not OcurrioError AndAlso TmpDTRecepcionUsados IsNot Nothing Then For Each drow As DataRow In TmpDTRecepcionUsados.Rows If Not ObjVentas.AddVentaUsado(CveVenta, drow("CvePS").ToString.ToEntero, drow("Cantidad").ToString.ToDecimal, drow("PU").ToString.ToDecimal, drow("CveBCIUsado").ToString.ToEntero, drow("CveModeloAuto").ToString.ToEntero) Then OcurrioError = True Exit For End If Next End If 'GUARDAR AJUSTES' If Not OcurrioError AndAlso Not ObjAcum.EliminarGarantiasDetalle(CveVenta) Then OcurrioError = True End If If Not OcurrioError AndAlso TmpDTAjustes IsNot Nothing AndAlso TmpDTAjustes.Rows.Count > 0 Then For Each Dr As DataRow In TmpDTAjustes.Rows If Not ObjAcum.AddGarantiasDetalle(Dr("CveVentaDetalle").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("CveFolioGarantia").ToString.ToEntero, Dr("CveTipoUso").ToString.ToEntero, Dr("CodigoEnsamble").ToString, Dr("CodigoLinea").ToString, Dr("CodigoInspeccion").ToString, Dr("CveTipoDefecto").ToString.ToEntero, Dr("NumPoliza").ToString, Dr("Importe").ToString.ToDouble, Dr("Consecutivo").ToString, Dr("FechaAjuste").ToString.ToDateTime(), Dr("PorcentajeAjuste").ToString.ToDecimal()) Then ErrorList.Add("Ocurrió un error al agregar la garantia detalle.") End If Next End If 'GUARDAR POLIZA VIRTUAL If Not OcurrioError AndAlso Not ObjAcum.EliminarPolizaVirtual(CveVenta) Then OcurrioError = True End If If Not OcurrioError AndAlso TmpDTPolizaVirtual IsNot Nothing Then For Each drow As DataRow In TmpDTPolizaVirtual.Rows If ObjAcum.AddPolizaVirtual(CveVenta, drow("CveVentaDetalle").ToString().ToEntero(), drow("CvePS").ToString.ToEntero, drow("Cantidad").ToString.ToDecimal, drow("PU").ToString.ToDecimal, drow("Descuento").ToString.ToDecimal, drow("Total").ToString.ToDecimal, drow("TipoServicio").ToString.ToEntero, drow("TipoPoliza").ToString.ToEntero, drow("CveModeloAuto").ToString.ToEntero, drow("AnioVehiculo").ToString.ToEntero, CBool(drow("TieneUsado").ToString), drow("FechaUsado").ToString().ToDateTime, drow("CvePSUsado").ToString.ToEntero, drow("CveBCIUsado").ToString.ToEntero) Then Else OcurrioError = True Exit For End If Next End If '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 'REGENERAR LOS SALDOS If Not OcurrioError Then OcurrioError = Not ObjFactura.RegenerarPrePolizas(ObjVentas.IniciaTransacSQL(), ObjAC) End If Catch ex As Exception OcurrioError = True OnError("Ocurrió un error al actualizar la remisión", ex) End Try 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:="document.location.href=""/Ventas/PV.aspx"";") End If ObjVentas.Dispose() ObjConta.Dispose() ObjBancos.Dispose() If ObjAC IsNot Nothing Then ObjAC.Dispose() End Sub #End Region #Region "PUNTO DE 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 realizo 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/PV.aspx"";" 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()", "divingresoegreso") 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 "CARGAS" Private Sub ConfiguraTipoDocto() 'Esconde Todo TdOrdenPago.Visible = False Tr33.Visible = False Tr32.Visible = False 'si tiene la funcionalidad que se active independiente del tipo de documento RMF 15-10-2017 Tr33.Visible = True Tr32.Visible = False '' NO CONOCEN EL SWTICH (SELECT EN .NET) ?? O COMO ?? - IPP If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then BtnEmitirImprimir.Text = "Emitir e Imprimir" 'TdReferencia.Style.Add("display", "none") End If UpFacturar.Update() End Sub Private Sub CargaMetodosPago() DdlMetodoPago.DataSource = GlobalDTMetodosPago.FiltraParametros("Estatus = 'Activo'", "ClaveSAT") '.FiltraParametros("CveMetodoPago > 0 ") DdlMetodoPago.DataBind() 'FACTURACION 3.3 DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago DdlMetodoPago33.DataBind() DdlMetodoPago33.SelectedValue = "3" If UsuarioActual.CveEmpresa = 119 Then CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) Else CargaFormaPago(-1) End If '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.DataBind() DdlFormaCliente.DataSource = dtt DdlFormaCliente.DataBind() DdlMetodoCliente.DataSource = GlobalDTVtaMetodoPago DdlMetodoCliente.DataBind() 'End If End Sub Private Sub CargaUsoCFDI() DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica) DdlUsoCFDI.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 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) 'Carga Detalle Sucursal DdlSucursalCliente.SelectedValueExist(drv("CveClienteSucursal").ToString) DdlSubProyectoDatos.SelectedValueExist(drv("CveSubProyecto").ToString) CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero) 'CargaDetalle If ObjVentas.GetVentaDetalle(CveVenta) Then TmpDT = ObjVentas.DtResultados.Copy() TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) GvPS.DataSource = TmpDT GvPS.DataBind() For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = False Gvr.FCLinkButton("imgD").Visible = False Next End If 'Carga Totales 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) HdnVentaSaldo.Value = drv("Total").ToString TxtMotivoDescuento.Text = drv("MotivoDescuento").ToString TxtObsFact.Text = drv("Observaciones").ToString DdlMoneda.SelectedValue = drv("CveMoneda").ToString TxtTipoCambio.Text = drv("TipoCambio").ToString DdlVendedor.SelectedValue = drv("CveVendedor").ToString DdlMetodoPago.SelectedValueExist(drv("CveMetodoPago").ToString) HdnIVAOriginal.Value = TxtIVA.Text '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 UpPS.Update() UpContado.Update() 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 End Sub Private Sub CargaEstados(Optional ClaveSATPais As String = "MEX") DdlEstadoSAT.Items.Clear() DdlEstadoSAT.DataSource = GlobalDTEstado(ClaveSATPais) DdlEstadoSAT.DataBind() DdlEstadoSAT.Items.Insert(0, New ListItem("Seleccione", "-1")) If UsuarioActual.CveEmpresa = 140 AndAlso ClaveSATPais = "MEX" Then DdlEstadoSAT.SelectedValueExist("26") End If End Sub Protected Sub DdlSATPais_SelectedIndexChanged(sender As Object, e As EventArgs) CargaEstados(DdlSATPais.SelectedValue) End Sub Private Sub CargaEmpresa() If UsuarioActual.Empresa.UsaContabilidad Then Dim ObjFisConfiguracion As New ClsFISConfiguracion If ObjFisConfiguracion.GetConfiguracion(UsuarioActual.CveEmpresa) Then ViewState("IdCtaContDSV") = ObjFisConfiguracion.ERDSV Else ViewState("IdCtaContDSV") = 0 End If ObjFisConfiguracion.Dispose() Else ViewState("IdCtaContDSV") = 0 End If End Sub Private Sub CargaMonedas() DdlMoneda.DataSource = GlobalDTMonedas DdlMoneda.DataBind() End Sub 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.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 CargaFormaEntrega() 'TrFormaEntrega.Visible = True DdlFormaEntrega.DataSource = GlobalDTVtaCondicionesEntrega(UsuarioActual.CveEmpresa) DdlFormaEntrega.DataBind() DdlFormaEntrega.Items.Insert(0, New ListItem("Seleccione", "-1")) End Sub Private Sub CargaCliente(CveCliente As Integer, Optional Estatus As Integer = 1) Dim ObjCliente As New ClsClientes() Try 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 LblCliente.Text = String.Format("{1}", CveCliente, ObjCliente.Nombre) ViewState("NombreCliente") = ObjCliente.Nombre LtlCliente.Text = ObjCliente.Nombre ChkEnviarFactura.Checked = ObjCliente.EnviarFactura 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("IdCtaContMonedaExtranjera") = ObjCliente.IdCtaContMonedaExtranjera ViewState("IdCtaContComplementaria") = ObjCliente.IdCtaContComplementaria ViewState("IdCtaContAnticipos") = ObjCliente.IdCtaContAnticipos ViewState("IdCtaContRetIVA") = ObjCliente.IdCtaContRetIVA ViewState("IdCtaContRetISR") = ObjCliente.IdCtaContRetISR ViewState("CodCliente") = ObjCliente.Codigo ViewState("ClienteDesglosaIEPS") = ObjCliente.DesglosaIEPS If (Boolean.Parse(ObjCliente.DtResultados(0)("EsDistribuidor").ToString)) Then TrEsDistribuidor.Visible = True If Not String.IsNullOrEmpty(ObjCliente.Vendedor) Then LbVendedor.Text = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Vendedor", $"CveVendedor = {ObjCliente.Vendedor}") End If Else TrEsDistribuidor.Visible = False End If 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 'ViewState("NumCtaPago") = ObjCliente.NumCtaPago EnviarCorreoCliente = ObjCliente.EnviarFactura ChkEnviarFactura.Visible = True ChkEnviarFactura.Checked = EnviarCorreoCliente LblEnviarMail.Visible = True Dim dr As DataRow = Nothing dr = GlobalDTSubProyectos(-1).FiltroPrimero("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 If CveVenta <= 0 Then CveMetodoPagoCliente = ObjCliente.DtResultados.Rows(0)("CveMetodoPago").ToString.ToEntero DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI.ToString) DdlMetodoPago.SelectedValueExist(ObjCliente.CveMetodoPago.ToString) DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33.ToString) 'DdlMetodoPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago33").ToString) DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty) DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33.ToString) 'DdlFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString) DdlUsoCFDI.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveUsoCFDI").ToString) End If TxtFechaPago.Text = (Now.AddDays(ObjCliente.PlazoCobranza)).ToShortDateString If ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero > 0 Then DdlVendedor.SelectedValueExist(ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero) End If If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If EstatusCliente = ObjCliente.Estatus If Not EstatusCliente Then BtnEmitirImprimir.Enabled = False Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) Else BtnEmitirImprimir.Enabled = True End If UpFacturar.Update() If UsuarioActual.Empresa.UsaInventarios Then RblTipo.Items.Remove(RblTipo.Items.FindByValue("1")) RblTipo.Items.Remove(RblTipo.Items.FindByValue("2")) End If UpnTools.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 Else CargaFormatoSucursal() UpParametros.Update() End If 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.DataBind() LbAgregar.Enabled = True UpEstatus.Update() UpPS.Update() UpParametros.Update() UPCondicionesPago.Update() UpComplementos.Update() CargarAlmacenes() CargaFacturasAjuste() Else Alert("El cliente solicitado no existe, por favor intente de nuevo.", TipoMensaje.MsgError) End If End If Catch ex As Exception OnError("Ocurrió un error al asignar el cliente", ex) End Try ObjCliente.Dispose() UPCondicionesPago.Update() 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 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") ViewState("SubProyectoPorcentajeIVA") = dr("IVA") ViewState("TipoFormato") = dr("TipoFormato") ViewState("Serie") = dr("Serie") LblSerie.Text = dr("Serie").ToString If SerieXML <> "" Then LblSerie.Text = SerieXML If dr("TipoVenta").ToString = "1" Then UpnTools.Update() 'activa el modo de pago efectivo directamente, y es venta nueva If ViewState("CveVenta").ToString.ToEntero < 0 Then InicializaCondicionesPago() DdlFormaPago.SelectedValueExist("0") DdlMetodoPago.SelectedValueExist("1") RBLPago.SelectedValue = "2" LimpiaEscondeContado() If DdlCuentaEfectivo.Items.Count = 2 Then DdlCuentaEfectivo.SelectedIndex = 0 End If End If End If DdlMetodoPago.SelectedValueExist(CveMetodoPagoCliente.ToString) UpFacturar.Update() UpParametros.Update() 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") End If If CveVenta <= 0 Then CveMetodoPagoCliente = ObjCliente.DtResultados.Rows(0)("CveMetodoPago").ToString.ToEntero DdlMetodoPago.SelectedValueExist(CveMetodoPagoCliente.ToString) DdlFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString) DdlMetodoPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago33").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 DdlMetodoPago.SelectedValueExist(CveMetodoPagoCliente.ToString) DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33) 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 Sub SetValues() ViewState("TipoCambio") = 1 If UsuarioActual.Empresa.MostrarRetIVA Then TrRetIVA.Style.Add("display", "") If UsuarioActual.Empresa.MostrarRetISR Then TrRetISR.Style.Add("display", "") 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") Else DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("Estado = 1", Orderby:="Clasificacion") End If DdlClasificacion.DataBind() End Sub Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost, Optional AplicaAlmacen As Boolean = True) Objeto.setEsWebService(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1") If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then Objeto.ddl.Items.Clear() 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-cveclasificacion", "-1") Objeto.ddlWS.Attributes.Add("data-aplicaparaventa", "1") If AplicaAlmacen Then Objeto.ddlWS.Attributes.Add("data-pagina", "ventas/ventas") Else Objeto.ddlWS.Attributes.Add("data-pagina", "-1") End If Objeto.ddlWS.Attributes.Add("data-aplicaparaventa", "1") Objeto.ddlWS.Attributes.Add("data-Estatus", "1") End If 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 BtnEmitirImprimir.Visible = True UpFacturar.Update() Else Alert("No tiene registrados Folios para " & DdlTipoComprobante.SelectedItem.Text & " en esta sucursal.", TipoMensaje.MsgAdvertencia) BtnEmitirImprimir.Visible = False UpFacturar.Update() End If DT.Dispose() End If ObjFolios.Dispose() 'End If End Sub Private Sub CargaDdlSubProyectos() DdlSubProyectoDatos.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ") DdlSubProyectoDatos.DataBind() 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 '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 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 BtnEmitirImprimir.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.ToastError) End Try End Sub #End Region #Region "GVPS" 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) Me.CveVentaDetalle = DbRow("CveVentaDetalle").ToString().ToEntero() If Me.CveVentaDetalle <= 0 Then EliminarUsados(DbRow("Consec").ToString().ToEntero()) TmpDT.Rows.Remove(DbRow) Else EliminarUsados() DbRow("EliminarDB") = True End If GvPS.DataSource = TmpDT.FiltraParametros("EliminarDB = False") DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() CargaGVInv(DtInv) CalculaTotalesVenta() Alert("Eliminado Correctamente.", TipoMensaje.MsgInformacion) Me.CveVentaDetalle = -1 UpContado.Update() End Sub 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 '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 'PUEDE EDTIRAR EL PU DEL PRODUCTO If UsuarioActual.TienePermisoProceso(222) Then ' e.Row.FCTextBox("TxtPrecio").Enabled = True e.Row.FCLinkButton("imgD").Visible = True e.Row.FCLinkButton("imgD").Visible = False Else e.Row.FCLinkButton("imgD").Visible = False e.Row.FCLinkButton("imgE").Visible = False End If End If If UsuarioActual.Empresa.CvePlataforma = 2 Then e.Row.FCLinkButton("imgE").Visible = False e.Row.FCLinkButton("imgEPyME").Visible = True End If 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.FiltraParametros("EliminarDB = False") GvPS.DataBind() UpPS.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 'If UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then ' e.Row.FCCheckBox("cbInv").Checked = True 'End If End If If CveVenta > 0 Then 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 #Region " INVENTARIO POR ENTREGA" 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("FechaCaducidad") Then DtTemporal.Columns.Add("FechaCaducidad", Type.GetType("System.DateTime")) End If GvInv.Columns(4).Visible = DtTemporal.MAX("Serie", "Serie <> ''") <> "" Or CveVenta <= 0 GvInv.Columns(5).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> "" GvInv.Columns(6).Visible = DtTemporal.MAX("FechaCaducidad", "FechaCaducidad <> ''") <> "" GvInv.DataSource = DtTemporal.FiltraParametros("EliminarDB = False") GvInv.DataBind() UpINV.Update() End Sub #End Region #Region " EMITIR IMPRIMIR - GUARDAR " Protected Sub BtnEmitirImprimir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitirImprimir.Click If Not CveCliente > 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 es obligatorio, favor de seleccionarlo", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VALIDA PRECIO AL AGREGAR A ALMACEN If Not UsuarioActual.TienePermisoProceso(169) Then If Not CveContrato > 0 Then If DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") 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 '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 For Each dr As DataRow In TmpDT.Rows 'SI ES SERVICIO NO VALIDA If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=dr("CvePS").ToString.ToEntero).FiltroPrimeroValor("CveTipoPS").ToString.ToEntero = 1 Then Continue For End If EsValido = False PU = dr("PU").ToString.ToDecimal * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) 'COSTO ALMACEN If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString.ToEntero, dr("Cantidad").ToString.ToDouble, -1, dr("Serie").ToString, TxtFecha.Text.ToDate, -1) CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA If PU >= CostoMenor Then EsValido = True End If Else EsValido = True End If If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString.ToEntero, dr("Cantidad").ToString.ToDouble, -1, dr("Serie").ToString, TxtFecha.Text.ToDate) 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 Then If DtPromociones.FiltraParametros($"CvePS = {dr("CvePS").ToString.ToEntero}").Rows.Count > 0 Then If PU >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {dr("CvePS").ToString.ToEntero}").ToDecimal Then EsValido = True End If End If End If 'NO DEJA REGISTRAR CON VALIDACION DE COSTO ALMACEN O PROMOCION 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) 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) End If Next ObjInventarios.Dispose() If MensajeCosto.ToString.Length > 1 Then Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If End If If UsuarioActual.Empresa.Funcionalidad(135) = "1" And DdlTipoComprobante.SelectedValue = "Cot" Then Alert("Se mando autorización al supervisor.") 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 Objeto.Dispose() If MandarCorreoSupervisor = True And CorreoSupervisor <> "" Then ViewState("Mail") = CorreoSupervisor End If MandarCorreoSupervisor = False End If 'If TmpDTAjustes IsNot Nothing AndAlso Not TmpDTAjustes.Rows.Count > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then ' RegistraScript("$('#DModalRecepcionUsados').modal('show');") 'Else ' EmitirImprimirNew() 'End If EmitirImprimirNew() End Sub #End Region #Region "E M I T I R - F A C T U R A" Protected Sub EmitirImprimirNew() If ValidaPagosContado() Then Exit Sub End If CreaObjetosVenta() If ObjFactura Is Nothing Or ObjFactura.Cliente Is Nothing Then Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError) ObjFactura = Nothing Exit Sub End If If ObjFactura.CveCliente > 0 Then If TmpDT.Rows.Count > 0 Then Dim Retorno = ObjFactura.EmitirFactura() If Retorno.CveVenta > 0 Then Dim SbAlert As New StringBuilder SbAlert.AppendFormat("{0}
", Retorno.Mensajes(Retorno.Mensajes.Count - 1)) SbAlert.AppendFormat("
", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta))) Retorno.Mensajes(Retorno.Mensajes.Count - 1) = SbAlert.ToString() End If For Each Mensaje In Retorno.Mensajes Alert(Mensaje, If(Retorno.TieneError, TipoMensaje.MsgError, TipoMensaje.MsgInformacion), If(Retorno.TieneError, "", Retorno.LigaPV)) Next 'Dim facBytes = DescargarFactura(Retorno.CveVenta, UsuarioActual.CveEmpresa) 'ImprimirbytesPDF(facBytes, ObjFactura.SerieFolio) End If End If End Sub Private Function DescargarFactura(CveVenta As Integer, CveEmpresa As Integer, Optional GetBytes As Boolean = True) As Byte() Dim Url = New Uri(String.Format("{0}://{1}:{2}/Compras/PopUpVerFactura.aspx?P={3}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta)))) Dim File As Byte() = Nothing Try Using httpClient = New HttpClient() httpClient.Timeout = New TimeSpan(0, 15, 0) Using request = New HttpRequestMessage(HttpMethod.Get, Url) request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CveUsuario=100", CveEmpresa, DateTime.UtcNow.Ticks))) Dim response = httpClient.SendAsync(request).Result If GetBytes AndAlso response.StatusCode = Net.HttpStatusCode.OK Then File = response.Content.ReadAsByteArrayAsync().Result End If End Using End Using Catch ex As Exception File = Nothing OnError("Ocurrió un error al descargar la factura", ex) End Try Return File End Function #End Region #Region "OBJETO VENTA" Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False) If Me.CveVenta > 0 Then ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=False) Else ObjFactura = New Modelos.Factura(UsuarioActual) ObjFactura.CvePrePoliza = -1 End If ObjFactura.CveUsuario = UsuarioActual.CveUsuario ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa ObjFactura.TipoCambio = 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.CveMetodoPago = DdlMetodoPago.SelectedValue.ToEntero ObjFactura.MetodoPago = DdlMetodoPago.SelectedItem.Text ObjFactura.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago.SelectedValue}") ObjFactura.FechaVencimiento = TxtFechaPago.Text.ToDate 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}") 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.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, If(RBLPago.SelectedValue = "1", 1, 2)) ' 0 - Contado, 1 - Credito, 2 - termianl ObjFactura.FormaPago = DdlFormaPago.SelectedValue.ToEntero 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 Else ObjFactura.TipoDocumento = "" End Select ObjFactura.Fech1 = Now ObjFactura.Fech2 = Now ObjFactura.Fech3 = Now ObjFactura.Alfa1 = "" ObjFactura.Alfa2 = "" ObjFactura.Alfa3 = "" ObjFactura.Num1 = 0 ObjFactura.Num2 = 0 ObjFactura.Num3 = DdlOrdenPago.SelectedValue.ToDouble ObjFactura.FechaPago = TxtFechaPago.Text.ToDate 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 = Now ObjFactura.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, CvePedido) ObjFactura.CveVendedor = DdlVendedor.SelectedValue.ToEntero If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If ObjFactura.FechaEjecucion = Now ObjFactura.CveSucursalEjecucion = DdlSubProyectoDatos.SelectedValue.ToEntero ObjFactura.CveSucursalCobranza = -1 ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero ObjFactura.CveSubProyectoEjecucion = DdlSubProyectoDatos.SelectedValue.ToEntero ObjFactura.CveSubProyectoCobranza = -1 ObjFactura.AtencionA = If(ObjFactura.TipoDocto = "Cot", TxtAtencionA.Text, "-1") ObjFactura.MotivoDescuento = TxtMotivoDescuento.Text.Trim ObjFactura.Observaciones = TxtObsFact.Text.Trim ObjFactura.Det_OrdenCompra = "" ObjFactura.Det_FechaOrdenCompra = MinFecha.ToShortDateString ObjFactura.MonedaAbreviatura = "" '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 ObjFactura.DtDeduccion = New DataTable 'OTROS ObjFactura.Det_FechaOrdenCompra = "" ObjFactura.Det_OrdenCompra = "" ObjFactura.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero If ObjFactura.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then ObjFactura.TipoCambio = TxtTipoCambio.Text.Trim.ToDecimal 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 ObjFactura.DtFirmas = DTmpF 'CLIENTE ObjFactura.CveCliente = CveCliente ObjFactura.SetCliente() 'SUCURSAL ObjFactura.CveSucursal = DdlSubProyectoDatos.SelectedValue.ToEntero ObjFactura.SetSubProyectoMatriz(Me) ObjFactura.SetSubProyecto(Me) ObjFactura.ClienteSucursal = New Modelos.SucursalModel 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 = DdlSucursalCliente.SelectedItem.Text ObjFactura.DtDetalle = TmpDT ObjFactura.DtPagos = DtPagos ObjFactura.DtPromociones = DtPromociones Dim FM As New Modelos.FemsaFactura Dim TmpDT7Eleven As New DataTable Dim TmpDTComplementosTimbrado As New DataTable PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) ObjFactura.FemsaFactura = FM ObjFactura.Timbre = PreParaTimbre(ObjFactura) ObjFactura.DtAjustes = TmpDTAjustes ObjFactura.DtRecepcionUsados = TmpDTRecepcionUsados ObjFactura.DtPolizasVirtuales = TmpDTPolizaVirtual ObjFactura.GenerarPDFFactura = False Dim CveTipoAlmacen As Integer = If(TmpDTAjustes IsNot Nothing AndAlso TmpDTAjustes.Rows.Count > 0, 6, 22) If GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltraParametros($"CveTipoAlmacen = {CveTipoAlmacen} AND CveSubProyecto= {DdlSubProyectoDatos.SelectedValue}").Rows.Count > 0 Then ObjFactura.CveAlmacenRecepcionUsados = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltraParametros($"CveTipoAlmacen = {CveTipoAlmacen} AND CveSubProyecto= {DdlSubProyectoDatos.SelectedValue}").Rows(0)("CveAlmacen").ToString.ToEntero End If 'If Not ddlAlmacen.SelectedValue.ToEntero > 0 AndAlso ddlAlmacen.Items.Count > 1 AndAlso UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then ' ddlAlmacen.SelectedIndex = 1 'End If If ddlAlmacen.SelectedValue.ToEntero > 0 Then ObjFactura.CveAlmacen = ddlAlmacen.SelectedValue.ToEntero If Not DtInv.Columns.Contains("Seleccionado") Then DtInv.Columns.Add("Seleccionado", GetType(Integer)) End If For Each Gvr As GridViewRow In GvInv.Rows Dim Dr As DataRow = DtInv.Select($"CvePS={Gvr.DataKey("CvePS")}")(0) If Gvr.FCCheckBox("cbInv").Checked AndAlso ddlAlmacen.SelectedValue.ToEntero > 0 Then Dr("Seleccionado") = 1 Else Dr("Seleccionado") = 0 End If Next DtInv.AcceptChanges() ObjFactura.DtInventario = DtInv.FiltraParametros("Seleccionado = 1") End If 'VALIDA ENTREGA POR ADELANTADO If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then 'INCRUSTAMOS ALMACEN ENTREGA POR ADELANTADO CUANDO SEA REMISION Y NO TRAIGA ASIGNADO POR EL USUARIO If ObjFactura.CveAlmacenTraspasoDestino <= 0 And ObjFactura.TipoDocto = "Rem" Then ObjFactura.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 ObjFactura.CveAlmacenTraspasoDestino <= 0 And ObjFactura.TipoDocto = "Rem" Then ErrorList.Add("Ocurrió un error al seleccionar el almacen de entrega por adelantado de la sucursal.") End If End If End Sub #End Region #Region "TIMBRADO" 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 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 Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) 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 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 = "" FM.FEMSA_NumProveedor = "" FM.FEMSA_Mail = "" FM.FEMSA_Version = "".ToEntero FM.FEMSA_NumPedido = "".ToEntero FM.FEMSA_NumEntrada = "" FM.FEMSA_NumRemision = "" FM.FEMSA_NumSocio = "" FM.FEMSA_CentroCosto = "" FM.FEMSA_IPeriodoLiquidacion = "" FM.FEMSA_FPeriodoLiquidacion = "" FM.FEMSA_CodRetencion1 = "" FM.FEMSA_CodRetencion2 = "" TmpDT7Eleven.Columns.Add("sevenElevenNumProveedor") TmpDT7Eleven.Columns.Add("sevenElevenFolio") TmpDT7Eleven.Columns.Add("sevenElevenTienda") TmpDT7Eleven.Columns.Add("sevenElevenFecha") Dim Row As DataRow = TmpDT7Eleven.NewRow Row("sevenElevenNumProveedor") = "" Row("sevenElevenFolio") = "" Row("sevenElevenTienda") = "" Row("sevenElevenFecha") = "" 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 Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero Row2("IdContabilidad") = TxtIdConta.Text.ToEntero Row2("TipoProceso") = DdlTipoCampaña.SelectedValue Row2("TipoAmbito") = DdlAmbitoComplemento.SelectedValue Row2("Entidad") = DdlINEEntidad.SelectedValue TmpDTComplementosTimbrado.Rows.Add(Row2) End Sub #End Region #Region "SELECTED INDEX CHANGE" Protected Sub DdlFacturas_SelectedIndexChanged(sender As Object, e As EventArgs) CargaPSAjuste() End Sub Private Sub DdlPSIndexChange(CvePSParametro As Integer, Ddl As ADServerControl.Dropdownlost) If Not CveCliente > 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 TxtDescuento.Text = FormatoNumero(0, 2) TxtPrecio.Text = "" Try 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 'Muestra la tabla de tamaños If drPS("CveTamaño").ToString().ToEntero() > 0 Then DivRecepcionUsados.Visible = True If DdlTipoComprobante.SelectedValue <> "Rem" Then GvRecepcionUsados.Columns(2).Visible = False Else GvRecepcionUsados.Columns(2).Visible = True End If End If DdlUnidadMedida.Items.Clear() If UsuarioActual.Empresa.UsaInventarios Then DdlUnidadMedida.DataSource = GlobalDTProductosServiciosEquivalencias(CvePSParametro, -1, UsuarioActual.CveEmpresa) 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) 'SUGIERE PRECIO Dim PrecioSugerido = 0.0 PrecioSugerido = drPS("Precio").ToString.ToDouble If UsuarioActual.CveEmpresa.Contiene(80, 119) Then 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:=CvePSParametro) Then PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble 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) ObjInventarios.Dispose() Dim PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDouble If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If ObjPS.Dispose() End If End If End If 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).ToEntero > 0 Then 'cuando el valor es 10.- secuencia Cliente/Sucursal, 20 - sucursal/cliente Dim TipoPrecioLista As Integer = UsuarioActual.Empresa.Funcionalidad(404).ToEntero ' si es 10. primero el cliente Dim CvePrecioListaPS As Integer Dim PorcentajePrecio As Double = 0 If TipoPrecioLista = 10 Then CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, Estatus:=-1, CveCliente:=CveCliente).FiltroPrimeroValor("CvePrecioLista").ToEntero() If CvePrecioListaPS <= 0 Then CvePrecioListaPS = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePrecioLista", "").ToEntero() End If Else CvePrecioListaPS = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePrecioLista", "").ToEntero() If CvePrecioListaPS <= 0 Then CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, Estatus:=-1, CveCliente:=CveCliente).FiltroPrimeroValor("CvePrecioLista").ToEntero() End If End If 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 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(), CveTipoAlmacen:=1) '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, CveTipoAlmacen:=1) ObjInventarios.Dispose() If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If 'CvePrecioLista = CvePrecioListaPS End If 'Dim ObjClasificaciones As New ClsClasificaciones 'If ObjClasificaciones.GetClasificaciones() Then ' PrecioBaseCosto = ObjClasificaciones.DtResultados.FiltroPrimeroValor("PrecioBaseCosto", $"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveClasificacion = {drPS("CveClasificacion")}").ToDecimal 'End If If PrecioSugerido > 0 Then Dim PrecioBaseCosto As Decimal = 0 PrecioBaseCosto = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, CveClasificacion:=drPS("CveClasificacion").ToString().ToEntero()).FiltroPrimeroValor("PrecioBaseCosto", "").ToDecimal If PrecioBaseCosto > 0 Then PrecioSugerido = PrecioSugerido * ((PrecioBaseCosto / 100) + 1) End If End If If PrecioSugerido > 0 Then TxtPrecio.Text = PrecioSugerido.FormatoNumero() RegistraScript("$get('LblPrecio1').innerText = formato_numero(" + PrecioSugerido.ToString + ", 2, '.', ',');") 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", SubProyectoPorcentajeIVA.ToString(), 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.") End If End If 'Descuento por clasificación If drPS("CveClasificacion").ToString.ToEntero.Contiene(20516, 20515) Then TxtDescuento.Text = (PrecioSugerido * ClasificacionesDescuentos(drPS("CveClasificacion").ToString.ToEntero)).ToString("F2") End If If ChkAjuste.Checked Then CalculaMesesUso() UpAjuste.Update() End If End If ElseIf CvePSParametro = -2 Then CargaPS(DdlClasificacion.SelectedValue.ToEntero, Ddl) Else DdlUnidadMedida.Items.Clear() DdlUnidadMedida.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlUnidadMedida.SelectedValue = "-1" DdlUnidadMedida.DataBind() End If Catch ex As Exception OnError("Ocurrió un error al cambiar el producto", ex) End Try UpClasificacion.Update() UpPS.Update() UpUnidadMedida.Update() UpAddVenta.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 DdlTipoDefecto_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlTipoDefecto.SelectedIndexChanged If DdlTipoDefecto.SelectedValue.ToEntero = 17 Then DivCodigoTD.Visible = True DdlTipoDefecto.Width = New Unit(140%) Else DivCodigoTD.Visible = False DdlTipoDefecto.Width = New Unit(200%) End If End Sub Protected Sub DdlSucursalCliente_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSucursalCliente.SelectedIndexChanged CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero) End Sub Private Sub DdlSubProyectoDatos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSubProyectoDatos.SelectedIndexChanged CambiaSucursalGeneral() End Sub Private Sub CambiaSucursalGeneral() Dim ObjSubProyectos As New ClsSubProyectos If ObjSubProyectos.GetSubProyectos() Then DTSucursal = ObjSubProyectos.DtResultados.FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue.ToEntero)) CambiaSucursal() End If ObjSubProyectos.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() ConfiguraTipoDocto() CargaFolios() UpEstatus.Update() 'REINICIALIZA VALORES DE ENTREGA POR ADELANTADO RequiereAlmacenDestino = False TrAlmacenAsignado.Visible = False TrDireccion.Visible = True TrCiudad.Visible = True TrRFC.Visible = True RBLPago.Enabled = True If DdlTipoComprobante.SelectedValue.Contiene("Ing") Then ChkEnviarFactura.Checked = EnviarCorreoCliente ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True ObtenerFechaVencimientoCER() End If If DdlTipoComprobante.SelectedValue.Contiene("Ing") 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 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 LblCliente.Text <> "Cliente" And Not EstatusCliente Then Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) End If BtnEmitirImprimir.Visible = EstatusCliente If DdlTipoComprobante.SelectedValue = "Cot" Then 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 DdlClasificacion_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlClasificacion.SelectedIndexChanged CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS) UpPS.Update() End Sub Private Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMetodoPago33.SelectedIndexChanged CambiaMetodoPago33() End Sub Private Sub CambiaMetodoPago33() If UsuarioActual.CveEmpresa = 119 Then CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero) Else CargaFormaPago(-1) End If End Sub #End Region #Region "DATATABLES" 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("Serie", 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)) TmpDT.Columns.Add("EsCargo", GetType(Boolean)) TmpDT.Columns.Add("PUOriginal", GetType(Decimal)) TmpDT.Columns.Add("ConsecPSPadre", GetType(Integer)) TmpDT.Columns.Add("EliminarDB", GetType(Boolean)) TmpDT.Columns("EliminarDB").DefaultValue = False 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 #End Region #Region "ADD PS" Private Sub AddPS(Cantidad As Double, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String, PU As Double, IVA As Double, RetIVA As Double, Descuento As Double, AsientoContableVentas As Integer, IdCtaContable As Integer, AplicaParaConcepto As Boolean, Codigo As String, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, Optional CveTipoPS As Integer = -1, Optional Serie As String = "", Optional CveContratoDetalle As Integer = -1, Optional TiempoEntrega As String = "", Optional CodigoPS As String = "") If Not CvePS > 0 Then Alert("Uno de los productos no existe. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError) Exit Sub End If Dim CveTipoInv = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimeroValor("Inv_CveMetodoInventario").ToEntero If Cantidad <> 1 And CveTipoInv = 5 AndAlso UsuarioActual.CveEmpresa <> 72 Then Alert("El producto se tiene que dar salida por serie y producto por producto (Cantidad = 1).", TipoMensaje.MsgAdvertencia) Exit Sub End If If TmpDT.FiltraParametros("AsientoContableVentas <> '" & AsientoContableVentas.ToString & "'").Rows.Count = 0 Then Dim Row As DataRow = Nothing Row = TmpDT.NewRow() Row("Codigo") = Codigo Row("Consec") = TmpDT.Rows.Count + 1 ConsecutivoVenta = TmpDT.Rows.Count + 1 Row("Cantidad") = Cantidad Row("CveUM") = CveUM Row("UM") = UM Row("CveClasificacion") = CveClasificacion Row("Clasificacion") = Clasificacion Row("CvePS") = CvePS Row("PS") = PS Row("CodigoPS") = CodigoPS Row("CveTipoPS") = CveTipoPS Row("CveTipoInvPS") = CveTipoInv Row("Obs") = Obs Row("PU") = PU Row("IVA") = IVA Row("RetIVA") = RetIVA Row("IEPS") = If(HdnAplicaIEPS.Value = "True", (Cantidad * PU) * HdnPorcentajeIEPS.Value.ToDecimal, 0) Row("Descuento") = Descuento Row("TipoDescuento") = HdnTipoDescuento.Value Row("Total") = (Cantidad * PU) Row("AsientoContableVentas") = AsientoContableVentas Row("IdCtaContVentas") = IdCtaContable Row("AplicaParaConcepto") = AplicaParaConcepto Row("CveProyecto") = CveProyecto Row("Proyecto") = Proyecto Row("CveSubProyecto") = CveSubProyecto Row("SubProyecto") = SubProyecto Row("Serie") = Serie Row("TiempoEntrega") = TiempoEntrega TmpDT.Rows.Add(Row) GvPS.DataSource = TmpDT.FiltraParametros("EliminarDB = False") GvPS.DataBind() DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvInv.DataSource = TmpDT.FiltraParametros("CveTipoPS=2") GvInv.DataBind() UpINV.Update() TxtSubTotal.Text = (TxtSubTotal.Text.Replace(",", "").ToDouble + (Cantidad * PU)).FormatoNumero(2) TxtIEPS.Text = (TxtIEPS.Text.Replace(",", "").ToDouble + (Cantidad * PU) * If(HdnPorcentajeIEPS.Value.ToDecimal = -1, 0.0D, HdnPorcentajeIEPS.Value.ToDecimal)).FormatoNumero(2) If TxtIEPS.Text.ToDouble > 0 Then : TrIEPS.Visible = True : End If If HdnTipoDescuento.Value = "0" Then LblDescuentos.Text = (LblDescuentos.Text.Trim.Replace(",", "").ToDouble + (Descuento * Cantidad)).FormatoNumero(2) TxtIVA.Text = (Math.Round(TxtIVA.Text.Replace(",", "").ToDouble, 2) + Math.Round(((Cantidad * (PU - Descuento)) * IVA), 2)).FormatoNumero(2) HdnIVAOriginal.Value = TxtIVA.Text ElseIf HdnTipoDescuento.Value = "1" Then LblDescuentos.Text = (LblDescuentos.Text.Trim.Replace(",", "").ToDouble + Descuento).FormatoNumero(2) TxtIVA.Text = (Math.Round(TxtIVA.Text.Replace(",", "").ToDouble, 2) + Math.Round(((Cantidad * PU - Descuento) * IVA), 2)).FormatoNumero(2) HdnIVAOriginal.Value = TxtIVA.Text ElseIf HdnTipoDescuento.Value = "-1" Then LblDescuentos.Text = (LblDescuentos.Text.Trim.Replace(",", "").ToDouble).FormatoNumero(2) TxtIVA.Text = (Math.Round(TxtIVA.Text.Replace(",", "").ToDouble, 2) + Math.Round(((Cantidad * PU) * IVA), 2)).FormatoNumero(2) HdnIVAOriginal.Value = TxtIVA.Text End If If CBool(ViewState("RetIVAFletes")) AndAlso RetIVA > 0 Then TxtRetIVA.Text = (TxtRetIVA.Text.Replace(",", "").ToDouble + ((Cantidad * PU)) * RetIVA).FormatoNumero(2) UpPS.Update() CalculaTotalesVenta(False) Else CalculaTotalesVenta(True) End If 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") UpContado.Update() Else Alert("No se puede hacer una factura que contenga conceptos de Venta y Anticipo.
Por favor separa una Factura de Venta de una Factura de Anticipos.", TipoMensaje.MsgAdvertencia) End If End Sub Private Sub LimpiaAgregar() TxtCantidad.Text = "1" 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 = "-1" DdlPS.SelectedText = "Seleccione" End If DdlUnidadMedida.Items.Clear() DdlUnidadMedida.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlUnidadMedida.SelectedValue = "-1" DdlUnidadMedida.DataBind() TxtObsPS.Text = "" TxtPrecio.Text = "" TxtDescuento.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" ' 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 ChkAgregar.Checked = True For Each Gvr As GridViewRow In GvRecepcionUsados.Rows If Gvr.RowType = DataControlRowType.DataRow Then Gvr.FCTextBox("TxtCantidad").Text = "" End If Next DivRecepcionUsados.Visible = False LimpiaAjuste() UPPDescuento.Update() UpINV.Update() UpClasificacion.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 Serie 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 EsCargo As Boolean = False, Optional ConsecPSPadre As Integer = -1, Optional EliminarDB As Boolean = False) As Integer Dim Retorno As Integer = -1 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.MsgAdvertencia) Retorno = -1 Return Retorno End If If (Obs.Length + PS.Length > 1000) 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) Retorno = -1 Return Retorno 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 rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Retorno = -1 Return Retorno End If End If End If End If Dim Row As DataRow = Nothing If Modalidad = "A" Then Row = TmpDT.NewRow() ElseIf Modalidad = "U" Then Dim Contador As Integer = 0 If CveVentaDetalle <= 0 Then For Each Dr As DataRow In TmpDT.Rows If Dr("Consec").ToString.ToEntero = Index Then Exit For End If Contador = Contador + 1 Next Row = TmpDT.Rows(Contador) Else Row = TmpDT.Select($"CveVentaDetalle={CveVentaDetalle}")(0) End If End If Dim TotalCalculableImpuestos As Decimal = 0 PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos Row("CveProyecto") = CveProyecto Row("Proyecto") = Proyecto Row("CveSubProyecto") = CveSubProyecto Row("SubProyecto") = SubProyecto Row("Serie") = Serie 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 = 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.MsgAdvertencia) Retorno = -1 Return Retorno 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)) Retorno = -1 Return Retorno End If End If TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento If Modalidad = "A" Then If Not TmpDT.Columns.Contains("PUOriginal") Then TmpDT.Columns.Add("PUOriginal", GetType(Decimal)) End If Row("PUOriginal") = PU End If 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 = "A" Then Row("Consec") = TmpDT.Rows.Count + 1 If Not EsCargo Then ConsecutivoVenta = TmpDT.Rows.Count + 1 End If ElseIf Modalidad = "U" Then If Not EsCargo Then ConsecutivoVenta = Row("Consec").ToString.ToEntero End If 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") = SubProyectoPorcentajeIVA 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") Row("EntregaDirecta") = EntregaDirecta 'Contratos Row("CveContratoDetalle") = CveContratoDetalle Row("CveVentaDetalle") = CveVentaDetalle Row("CveMovimientoDetallePedido") = CveVentaDetalle Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle Row("CveVentaDetalleRemision") = CveVentaDetalleRemision Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion Row("CveVentaDetallePedido2") = CveVentaDetallePedido2 Row("CuentaPredial") = CuentaPredial Row("EsCargo") = EsCargo If EsCargo AndAlso ConsecPSPadre >= 0 Then Row("ConsecPSPadre") = ConsecPSPadre End If Row("EliminarDB") = EliminarDB 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) Retorno = -1 Return Retorno 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 If Modalidad = "A" Then TmpDT.Rows.Add(Row) End If Retorno = Row("Consec").ToString().ToEntero() TmpDT.AcceptChanges() Return Retorno End Function Private Function ValidaAgregarPS(CvePS As Integer, CveUM As Integer, PU As Double, CveTipoPS As Integer, Cantidad As Decimal) 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 If CveCliente <= 0 Then Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact&TipoCliente=-1', 800, 547, 'N', 'PopUpBuscar')") Return False End If 'Validacion de Recepción de Usados Dim Vendido As Decimal = 0 Dim Entregado As Decimal = 0 Dim UltimoEntregado As Decimal = 0 For Each Gvr As GridViewRow In GvRecepcionUsados.Rows If Gvr.RowType = DataControlRowType.DataRow Then If Gvr.FCTextBox("TxtCantidad").Text.ToEntero() > 0 Then Entregado += (Gvr.FCTextBox("TxtCantidad").Text.ToEntero * Gvr.DataKey("Cargo").ToDecimal) UltimoEntregado = Gvr.DataKey("Cargo").ToDecimal End If End If Next If Entregado > 0 Then 'Calcular Vendido Dim DTTamanios As New DataTable Dim ObjAcum As New ClsAcumuladores If ObjAcum.TamañoGet(-1, UsuarioActual.CveEmpresa) Then DTTamanios = ObjAcum.DtResultados End If ObjAcum.Dispose() Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If DTTamanios.Rows.Count > 0 And DTTamanios IsNot Nothing And DrPS("CveTamaño").ToString.ToEntero > 0 Then Vendido = DTTamanios.FiltroPrimeroValor("Cargo", $" CveTamaño = { DrPS("CveTamaño") }").ToDecimal * Cantidad End If If Entregado > Vendido Then If (Entregado - Vendido) >= UltimoEntregado Then Alert("No puede entregar un cargo mayor a lo Vendido", TipoMensaje.MsgAdvertencia) Return False End If End If End If 'Dim CantidadUsados As Decimal = 0 'For Each Gvr As GridViewRow In GvRecepcionUsados.Rows ' If Gvr.RowType = DataControlRowType.DataRow Then ' CantidadUsados = CantidadUsados + Gvr.FCTextBox("TxtCantidad").Text.ToEntero() ' End If 'Next 'If CantidadUsados > TxtCantidad.Text.ToEntero() Then ' Alert("No puede tener una cantidad mayor a la de los cargos", TipoMensaje.MsgAdvertencia) ' 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, 140))) 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) 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" Then 'VALIDA EXISTENCIA If UsuarioActual.CveEmpresa.Contiene({1, 72, 80, 119, 140}) 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 If ChkAjuste.Checked Then If TxtFechaAjuste.Text.ToDate > Now Then Alert("La fecha de compra no puede ser mayor a la de hoy.", TipoMensaje.MsgAdvertencia) Return False End If End If Return True End Function Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click If Not CveCliente > 0 Then RegistraScript("javascript:AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact&TipoCliente=-1', 800, 547, 'N', 'PopUpBuscar')") : Exit Sub CargaAgregar() End Sub Private Sub CargaAgregar() Modalidad = "A" LnkAgregarPS.Text = "Agregar" CargaBCI() LimpiaAgregar() LimpiaAjuste() ModalidadAjuste = "A" ChkAgregar.Checked = True divagregrarotrops.Visible = True UpVenta.Update() RegistraScript("$('#DivAddVenta').modal({backdrop: 'static', keyboard: false});") End Sub Private Sub CargaBCI() 'Dim ObjGral As New ClsGenerales 'If ObjGral.BCIUsadoGet(UsuarioActual.CveEmpresa) Then ' DdlBCIUsado.DataSource = ObjGral.DtResultados 'End If 'DdlBCIUsado.Items.Insert(0, New ListItem("Seleccione", "-1")) 'DdlBCIUsado.SelectedValueExist(-1) 'DdlBCIUsado.DataBind() 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 ConsecutivoVenta = GvRow.DataKey("Consec").ToEntero CveVentaDetalle = GvRow.DataKey("CveVentaDetalle").ToEntero LnkAgregarPS.Text = "Actualizar" DdlClasificacion.SelectedValueExist(GvRow.DataKey("CveClasificacion")) CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS) UpClasificacion.Update() If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then DdlPS.SelectedValue = GvRow.DataKey("CvePS") Else DdlPS.SelectedValue = GvRow.DataKey("CvePS") DdlPS.SelectedText = GvRow.DataKey("PS") End If DdlPSIndexChange(DdlPS.SelectedValue.ToEntero, DdlPS) DdlUnidadMedida.SelectedValueExist(GvRow.DataKey("CveUM")) TxtCantidad.Text = GvRow.DataKey("Cantidad") 'Dim TotalCargos As Decimal = 0 'Dim StrTamanios As New StringBuilder() 'StrTamanios.Append("Se recibierón los siguientes usados:") 'For Each Gvr As GridViewRow In GvRecepcionUsados.Rows ' If Gvr.RowType = DataControlRowType.DataRow Then ' If Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal > 0 Then ' TotalCargos += Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal * Gvr.DataKey("Cargo").ToDecimal ' StrTamanios.AppendFormat("{0},", Gvr.DataKey("CodigoPS")) ' End If ' End If 'Next 'If TotalCargos > 0 Then ' StrTamanios.Remove(StrTamanios.Length - 1, 1) 'Else ' StrTamanios.Clear() 'End If TxtObsPS.Text = GvRow.DataKey("Obs") '.Replace(StrTamanios.ToString(), "") TxtPrecio.Text = GvRow.DataKey("PU") TxtDescuento.Text = GvRow.DataKey("Descuento") LblTotalPS.Text = GvRow.DataKey("Total") ChkAgregar.Checked = False divagregrarotrops.Visible = False If CveVenta <= 0 Then Ajuste() End If AddPolizaVirtual(DdlPS.SelectedValue.ToEntero()) UpVenta.Update() RegistraScript("$('#DivAddVenta').modal({backdrop: 'static', keyboard: false});", "EdicionVenta") End Sub Protected Sub LnkAgregarPS_Click(sender As Object, e As EventArgs) If ChkAjuste.Checked Then Dim FolioGarantia As MFolioGarantiaMensaje = ValidaFolioGarantia(DdlPSAjuste.SelectedValue.ToEntero(), DdlFolioGarantia.SelectedValue.ToEntero()) If Not FolioGarantia.Valido Then Alert($"El folio de garantía no es valido.
Clasificacion del Producto:{FolioGarantia.ClasificacionPS}.
Tipo Folio:{FolioGarantia.TipoFolio}", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If AgregarPS() Then If ChkAjuste.Checked Then GuardaAjuste() AddPolizaVirtual(DdlPS.SelectedValue.ToEntero()) CalculaTotalesVenta() If ChkAgregar.Checked = True And Modalidad = "A" Then LimpiaAgregar() UpVenta.Update() Else If Me.CveVentaDetalle > 0 Then For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = Not Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble > 0 AndAlso Gvr.DataKey("EsCargo") = "False" Gvr.FCLinkButton("imgD").Visible = Not Gvr.DataKey("CantidadInventario").ToString.ToDouble > 0 AndAlso Gvr.DataKey("EsCargo") = "False" Next End If UpVenta.Update() RegistraScript("$('#DivAddVenta').modal('hide');") End If End If Me.CveVentaDetalle = -1 End Sub Private Function AgregarPS() As Boolean Dim CveVentaDetalle As Integer = Me.CveVentaDetalle Dim EsCargo As Boolean = False If CveVentaDetalle > 0 Then EsCargo = CBool(TmpDT.FiltroPrimeroValor("EsCargo", $"CveVentaDetalle={CveVentaDetalle}")) End If 'SELECCIONA EL PS DEPENDIENDO LA MODALIDAD (CODIGO BARRAS - DDL) Dim CvePS = DdlPS.SelectedValue.ToEntero Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If ValidaAgregarPS(CvePS, DdlUnidadMedida.SelectedValue.ToEntero, TxtPrecio.Text.Trim.ToDouble, HdnTipoPS.Value.ToEntero, TxtCantidad.Text.ToDecimal) Then Dim Cantidad As Decimal = TxtCantidad.Text.ToDecimal Dim PU As Decimal = If(CvePSAmortizacion > 0, TxtPrecio.Text.Trim.ToDecimal * -1, TxtPrecio.Text.Trim.ToDecimal).RoundSQL(6) 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 If DrPS("CveClasificacion").ToString.ToEntero.Contiene(20516, 20515) Then Descuento = ((Cantidad * PU) * ClasificacionesDescuentos(DrPS("CveClasificacion").ToString.ToEntero)) End If Dim CveProyecto As Integer = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0)("CveProyecto").ToString.ToEntero Dim Proyecto As String = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0)("Proyecto").ToString Dim Consec = AgregarProductoServicio(Cantidad, DdlUnidadMedida.SelectedValue.ToEntero, DdlUnidadMedida.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero, DdlClasificacion.SelectedItem.Text, CvePS, "", TxtObsPS.Text.Trim, PU, Descuento, CveProyecto, Proyecto, DdlSubProyectoDatos.SelectedValue.ToEntero, DdlSubProyectoDatos.SelectedItem.Text, Serie:="", TiempoEntrega:="", CuentaPredial:="", RegeneraIEPS:=ClienteDesglosaIEPS, CveVentaDetalle:=CveVentaDetalle, EsCargo:=EsCargo) If CveVentaDetalle <= 0 AndAlso Not EsCargo Then Dim ListaPSCargo = CalculaUsados(Consec) If ListaPSCargo.Count > 0 Then CalculaRecepcionUsados(GvRecepcionUsados, CvePS, ListaPSCargo) End If ElseIf CveVentaDetalle > 0 AndAlso Not EsCargo Then EliminarUsados() Dim ListaPSCargo = CalculaUsados(Consec, LimpiarUsados:=False) If ListaPSCargo.Count > 0 Then CalculaRecepcionUsados(GvRecepcionUsados, CvePS, ListaPSCargo) End If End If Return True Else Return False End If End Function #End Region #Region " DESCUENTOS " Private Sub AplicarDescuentos() If TxtSubTotal.Text.ToDecimal <= 0 Then Alert("Para aplicar un descuento, el SubTotal debe ser mayor a cero.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim Total = 0.0D Dim Descuento As Decimal = HdnDescuento.Value.ToDecimal Dim Porcentaje As Decimal = Descuento / TmpDT.SUMD("Total") Dim LastDr As DataRow = Nothing For Each Dr As DataRow In TmpDT.Rows Descuento = Dr("Total").ToString.ToDecimal * Porcentaje Dr("Descuento") = Math.Round(Descuento, NumeroDecimales) Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (Dr("PU").ToString.ToDecimal)) - Dr("Descuento").ToString.ToDecimal 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("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) Dr("IEPS") = Dr("ImporteIEPS") LastDr = Dr Next If Not IsNothing(LastDr) Then Dim Fdes As Decimal = Descuento - TmpDT.SUMD("Descuento").ToString.ToDecimal If Fdes > 0 Then LastDr("Descuento") = LastDr("Descuento").ToString.ToDecimal + Fdes End If End If TmpDT.AcceptChanges() End Sub 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 AplicarDescuentos() '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 UpPS.Update() 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 AplicarDescuentos() '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();") End If End If UpPS.Update() End If RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal") 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 #End Region #Region "CALCULA TOTALES" Private Sub CalculaTotalesVenta(Optional RecalculaImpuestosLocales As Boolean = True) Dim TmpDT = Me.TmpDT.FiltraParametros("EliminarDB = False", Orderby:="Consec") 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 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 Else TrIEPS.Visible = False : GvPS.Columns(ColumnaIEPS).Visible = False : thEncIEPS1.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 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 GvPS.DataSource = TmpDT GvPS.DataBind() 'RECARGA GV INVENTARIO DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") CargaGVInv(DtInv) UpContado.Update() UpPS.Update() RegistraScript("BorraDescuentos();", "BorraDescuentos") End Sub #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 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).FiltroPrimero(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue)) ' If drSucursal IsNot Nothing Then TipoVenta = drSucursal("TipoVenta").ToString.ToEntero ' ChkClasificacion.Checked = True ' DIVClasif.Visible = False ' DIVClasificacion.Visible = False ' DIVCodBarras.Visible = True ' DIVCod.Visible = True ' RegistraScript(String.Format("$( document ).ready(function() {{$('#{0}').focus()}});", TxtCodigoBarras.ClientID), "cb") '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("Producto no encontrado ") ' 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("No se encontró el producto.", TipoMensaje.MsgAdvertencia) ' 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, Codigo:=Codigo, CodigoBarras:=CodigoBarras, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then GVBuscarPrecio.DataSource = ObjPS.DtResultados Else GVBuscarPrecio.DataSource = Nothing End If ObjPS.Dispose() GVBuscarPrecio.DataBind() UpBuscarPrecio.Update() End Sub #End Region #Region "MONEDA" 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() End Sub #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" TxtCambio.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 = 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 = 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, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) DdlCuentaTarjetaCredito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) DdlCuentaTarjetaDebito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) DdlCuentaCheque.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero))) DdlCuentaTransferencia.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).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 TxtCambio.Text.ToDecimal > 0 And TxtImporteEfectivo.Text.ToDecimal < TxtCambio.Text.ToDecimal Then Alert("Debe haber un pago en efectivo y ser mayor que el cambio. Si no, ser pago exacto.", TipoMensaje.MsgAdvertencia) Exit Sub End If If (DtPagos.SUM("Importe").ToString.ToDecimal + total - TxtCambio.Text.ToDecimal) > 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.ToDecimal - TxtCambio.Text.ToDecimal 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 Credito", 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 Debito", 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 Private Sub CargaCuentasTerminal() DdlCuentasTerminal.Items.Clear() DdlCuentasTerminal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"}) DdlCuentasTerminal.DataBind() DdlCuentasTerminal.Items.Insert(0, New ListItem("Seleccione", "-1")) UPTarjetaTermminal.Update() End Sub #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("", ddlAlmacen.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("Serie = '{0}'", Row.FCTextBox("TxtSerie").Text.ToString)) 'Valida Existencia If Existencia - ExistenciaActual <= 0 Then Alert(String.Format("Not 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)("Serie") = "" Else Row.FCHiddenField("HdnSerie").Value = Row.FCTextBox("TxtSerie").Text TmpDT.Rows(Index)("Serie") = Row.FCTextBox("TxtSerie").Text End If TmpDT.AcceptChanges() DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") ObjInventarios.Dispose() 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 rectifique.", 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.GetExistenciasPSSerie(Gvr.FCTextBox("TxtSerie").Text.ToString, ddlAlmacen.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) ExistenciaActual = DtInv.SUM("Cantidad", String.Format("Serie = '{0}'", Gvr.FCTextBox("TxtSerie").Text.Trim)) 'Valida Existencia If Existencia - ExistenciaActual < 0 Or Existencia = 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 #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 If ViewState("CveCliente").ToString.ToEntero > 0 Then CargaAgregar() End Sub Private Sub LnkAgregarCliente_Click(sender As Object, e As EventArgs) Handles LnkAgregarCliente.Click DivNombreCliente.Visible = False DivDireccionCliente.Visible = False DivNumeroCPCliente.Visible = False DivColoniaTelefonoCliente.Visible = False DivCiudadLocalidadCliente.Visible = False DivEstadoPaisCliente.Visible = False DivCorreoCuentaCliente.Visible = False DivBotonesAgregarCliente.Visible = False DivFormaCliente.Visible = False TxtRFCCliente.Text = "XAXX010101000" UpAgregarCliente.Update() CargaEstados() RegistraScript("showDivEC();") End Sub Private Sub BtnValidarRFC_Click(sender As Object, e As EventArgs) Handles BtnValidarRFC.Click If TxtRFCCliente.Text.ToUpper = "XAXX010101000" Then DivNombreCliente.Visible = True DivDireccionCliente.Visible = True DivNumeroCPCliente.Visible = True DivColoniaTelefonoCliente.Visible = True DivCiudadLocalidadCliente.Visible = True DivEstadoPaisCliente.Visible = True DivCorreoCuentaCliente.Visible = True DivBotonesAgregarCliente.Visible = True DivFormaCliente.Visible = True RFVDireccionC.Visible = False RFVNoEC.Visible = False RFVColoniaC.Visible = False RFVCiudadC.Visible = False RFVLocalidadC.Visible = False TxtNombreCliente.Focus() DdlMetodoCliente.SelectedValueExist(1) DdlFormaCliente.SelectedValueExist(1) 'carga datos particulares de la sucursal Dim dr As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero).FiltroPrimero("") If dr IsNot Nothing Then TxtCPCliente.Text = dr("CP").ToString 'TxtEstadoCliente.Text = dr("Estado").ToString RMf FAlta TxtCiudadCliente.Text = dr("Municipio").ToString TxtLocalidadCliente.Text = dr("Localidad").ToString End If Else Dim ObjCliente As New ClsClientes If ObjCliente.ValidaClienteRFC(TxtRFCCliente.Text, UsuarioActual.CveEmpresa) Then If ObjCliente.DtResultados.Rows.Count > 0 Then RegistraScript("hideDivEC();") ViewState("CveCliente") = ObjCliente.DtResultados(0)("CveCliente").ToString.ToEntero HdnCveCliente.Value = ObjCliente.DtResultados(0)("CveCliente").ToString CargaCliente(CveCliente) UpCliente.Update() Else DivNombreCliente.Visible = True DivDireccionCliente.Visible = True DivNumeroCPCliente.Visible = True DivColoniaTelefonoCliente.Visible = True DivCiudadLocalidadCliente.Visible = True DivEstadoPaisCliente.Visible = True DivCorreoCuentaCliente.Visible = True DivBotonesAgregarCliente.Visible = True DivFormaCliente.Visible = True End If End If ObjCliente.Dispose() RFVDireccionC.Visible = True RFVNoEC.Visible = True RFVColoniaC.Visible = True RFVCiudadC.Visible = True RFVLocalidadC.Visible = True DdlMetodoCliente.SelectedValueExist(-1) DdlFormaCliente.SelectedValueExist(-1) End If End Sub Private Sub BtnAgregarCliente_Click(sender As Object, e As EventArgs) Handles BtnAgregarCliente.Click Dim CvePrecioLista As Integer = -1 If DdlSubProyectoDatos.SelectedValue.ToEntero > 0 Then Dim Dr As DataRow = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero, UsuarioActual.CveEmpresa).Rows(0) If Dr IsNot Nothing Then If Dr("CvePrecioLista").ToString.ToEntero > 0 Then CvePrecioLista = Dr("CvePrecioLista").ToString.ToEntero End If End If End If Dim ObjCliente As New ClsClientes If ObjCliente.AgregarClienteNoFrecuente(TxtNombreCliente.Text.Trim, TxtDireccionCliente.Text.Trim, TxtNumExtCliente.Text.Trim, TxtNumIntCliente.Text.Trim, TxtColoniaCliente.Text.Trim, TxtLocalidadCliente.Text.Trim, TxtCiudadCliente.Text.Trim, DdlEstadoSAT.SelectedValue.ToEntero, TxtRFCCliente.Text.Trim, TxtCPCliente.Text.Trim, TxtTelefonoCliente.Text.Trim, TxtCorreoCliente.Text.Trim, DdlSubProyectoDatos.SelectedValue.ToEntero, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "", DdlMetodoCliente.SelectedValue.ToEntero, DdlFormaCliente.SelectedValue.ToEntero) Then If ObjCliente.DtResultados.Rows.Count > 0 Then RegistraScript("hideDivEC();") ViewState("CveCliente") = ObjCliente.DtResultados(0)("CveCliente").ToString.ToEntero HdnCveCliente.Value = ObjCliente.DtResultados(0)("CveCliente").ToString CargaCliente(CveCliente) UpCliente.Update() End If End If ObjCliente.Dispose() RecargaGlobalCliente() End Sub #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) 'If DdlClasificacionPS.SelectedValue.ToEntero > 0 Then 'Dim ObjVenta As New ClsVentas 'If ObjVenta.GetClasificacionDetalle(UsuarioActual.CveEmpresa, CveClasificacion:=DdlClasificacionPS.SelectedValue.ToEntero) Then ' DdlTipo.DataSource = ObjVenta.DtResultados 'End If 'ObjVenta.Dispose() ' End If 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 codigo es requerido.", TipoMensaje.MsgAdvertencia) Return End If If TxtCodigoPS.Text <> "" AndAlso Not TxtCodigoPS.Text.Length >= 3 Then Alert("El codigo 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() GlobalDTProductosServiciosEquivalencias(-1, -1, UsuarioActual.CveEmpresa) = Nothing GlobalDTPSSimplificado(UsuarioActual.CveEmpresa) = Nothing '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 Private Sub RecargaGlobalCliente() 'Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDTCliente) 'Hilo.Start() GeneraGlobalDTCliente() End Sub Private Sub GeneraGlobalDTCliente() GlobalDTCliente(UsuarioActual.CveEmpresa) = Nothing 'Dim Objclientes As New ClsClientes 'If Objclientes.GetClientes(-1, "-1", "-1", "-1", "-1", "-1", "-1", -1, -1, Estatus:=-1, TipoCliente:=-1) Then ' Application("GlobalDTCliente") = Objclientes.DtResultados 'End If 'Objclientes.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 #End Region #Region "AJUSTE" Private Sub CreaDTmpDTAjustes() TmpDTAjustes = New DataTable TmpDTAjustes.Columns.Add("CveFolioGarantia", GetType(Integer)) TmpDTAjustes.Columns.Add("CveTipoUso", GetType(Integer)) TmpDTAjustes.Columns.Add("CveTipoDefecto", GetType(Integer)) TmpDTAjustes.Columns.Add("CodigoEnsamble", GetType(String)) TmpDTAjustes.Columns.Add("CodigoLinea", GetType(String)) TmpDTAjustes.Columns.Add("CodigoInspeccion", GetType(String)) TmpDTAjustes.Columns.Add("Consecutivo", GetType(String)) TmpDTAjustes.Columns.Add("ConsecutivoVenta", GetType(Integer)) TmpDTAjustes.Columns.Add("FechaAjuste", GetType(Date)) TmpDTAjustes.Columns.Add("Meses", GetType(String)) TmpDTAjustes.Columns.Add("PorcentajeAjuste", GetType(Double)) TmpDTAjustes.Columns.Add("NumPoliza", GetType(String)) TmpDTAjustes.Columns.Add("Importe", GetType(Double)) TmpDTAjustes.Columns.Add("CvePS", GetType(Integer)) TmpDTAjustes.Columns.Add("PS", GetType(String)) TmpDTAjustes.Columns.Add("Cantidad", GetType(Decimal)) TmpDTAjustes.Columns.Add("CveUM", GetType(Integer)) TmpDTAjustes.Columns.Add("CveVentaDetalle", GetType(Integer)) TmpDTAjustes.Columns.Add("CveVenta", GetType(Integer)) TmpDTAjustes.Columns.Add("PUFactura", GetType(Double)) End Sub Private Sub CargaFacturasAjuste() DdlFacturas.Items.Clear() Dim ObjVenta As New ClsVentas If ObjVenta.GetVentas(UsuarioActual.CveEmpresa, "Ing", "-1", -1, "-1", CveCliente, -1, -1, -1, "-1", "-1", "-1", CveUsuarioConsulta:=UsuarioActual.CveUsuario) Then DdlFacturas.DataSource = ObjVenta.DtResultados DdlFacturas.Items.Insert(0, New ListItem("Sin Factura", "-1")) End If ObjVenta.Dispose() DdlFacturas.DataBind() UpAjuste.Update() End Sub Private Sub CargaBCIAjuste() Dim ObjGral As New ClsGenerales If ObjGral.BCIUsadoGet(UsuarioActual.CveEmpresa) Then DTBCIUsados = ObjGral.DtResultados.Copy() DdlBCIAjuste.DataSource = DTBCIUsados End If ObjGral.Dispose() DdlBCIAjuste.DataBind() End Sub Private Sub CargaAjuste() Dim ObjAcum As New ClsAcumuladores If ObjAcum.FoliosGarantiaGet(-1, UsuarioActual.CveEmpresa, Estatus:=1, Area:=1) Then DdlFolioGarantia.DataSource = ObjAcum.DtResultados DdlFolioGarantia.Items.Insert(0, New ListItem("Seleccione", "-1")) End If ObjAcum.Dispose() DdlFacturas.Items.Insert(0, New ListItem("Sin Factura", "-1")) DdlTipoUso.DataSource = GlobalDTAcumTiposUso.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa}") DdlTipoUso.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlTipoDefecto.DataSource = GlobalDTAcumTiposDefecto.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa}") DdlTipoDefecto.Items.Insert(0, New ListItem("Seleccione", "-1")) Dim DtTamanios = GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CvePSCargo > 0") CargaModelos() CargaBCIAjuste() GvRecepcionUsados.DataSource = DtTamanios GvRecepcionUsadosModal.DataSource = DtTamanios DdlFolioGarantia.DataBind() DdlTipoUso.DataBind() DdlTipoDefecto.DataBind() DdlFacturas.DataBind() GvRecepcionUsados.DataBind() GvRecepcionUsadosModal.DataBind() CreaDTmpDTAjustes() CreaDTmpDTRecepcionUsados() CreaDTmpDTPolizaVirtual() DdlDistribuidor.setEsWebService(True) DivChkAjuste.Visible = True End Sub Private Sub CargaModelos() Dim ObjGral As New ClsGenerales If ObjGral.ModelosAutosGet(UsuarioActual.CveEmpresa) Then DtModelosAuto = ObjGral.DtResultados DdlModeloAuto.DataSource = DtModelosAuto End If DdlModeloAuto.DataBind() End Sub Protected Sub GvRecepcionUsados_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvRecepcionUsados.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCDropDownList("DdlBCIUsado").DataSource = DTBCIUsados.FiltraParametros(String.Format("CveTamaño = {0}", e.Row.DataKey("CveTamaño"))) e.Row.FCDropDownList("DdlBCIUsado").DataBind() End If End Sub Private Sub CargaPSAjuste() 'DdlPSAjuste.Items.Clear() DtPUFacturas.Rows.Clear() If DdlFacturas.SelectedValue.ToEntero > 0 Then 'TxtPUFactura.Enabled = False Dim ObjVenta As New ClsVentas If ObjVenta.GetVentaDetalle(DdlFacturas.SelectedValue.ToEntero) Then DdlPSAjuste.DataSource = ObjVenta.DtResultados DtPUFacturas = ObjVenta.DtResultados TxtFechaAjuste.Text = ObjVenta.DtResultados.Rows(0)("Fecha").ToString.ToDate.ToShortDateString End If ObjVenta.Dispose() Else 'TxtPUFactura.Enabled = True 'TxtPUFactura.Text = "" DdlPSAjuste.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa) End If DdlPSAjuste.DataBind() ' DdlPSAjuste.Items.Insert(0, New ListItem("Seleccione", "-1")) DtPUFacturas.AcceptChanges() UpAjuste.Update() CalculaPorcentajeAjuste() End Sub Private Sub Ajuste() LimpiaAjuste() If TmpDTAjustes IsNot Nothing AndAlso TmpDTAjustes.FiltraParametros($"ConsecutivoVenta = {ConsecutivoVenta}").Rows.Count > 0 Then ModalidadAjuste = "U" TxtPrecio.Attributes.Add("onKeyUp", $"CambiaAjuste(this,{TxtPrecio.ClientID});") ChkAjuste.Checked = True DivAjuste.Visible = True CargaAjusteDetalle() Else ModalidadAjuste = "A" TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();") End If End Sub Private Sub LimpiaAjuste() DdlFolioGarantia.SelectedIndex = -1 TxtConsecutivoAjuste.Text = "" TxtCodEnsamble.Text = "" DdlTipoUso.SelectedIndex = -1 TxtCodLinea.Text = "" 'TxtPrecio.Text = "" TxtFechaAjuste.Text = Now.ToShortDateString CEEFechaAjuste.EndDate = Now TxtCodInspeccion.Text = "" TxtMesesUso.Text = "" DdlTipoDefecto.SelectedIndex = -1 TxtPorcentajeAjuste.Text = "" TxtPoliza.Text = "" TxtImporteAjuste.Text = "" DdlPSAjuste.SelectedValue = "-1" ChkAjuste.Checked = False DivAjuste.Visible = False End Sub Private Sub CargaAjusteDetalle() Dim Dr As DataRow = Nothing IndexAjuste = 0 For Each Dr2 As DataRow In TmpDTAjustes.Rows If Dr2("ConsecutivoVenta").ToString.ToEntero = ConsecutivoVenta Then Dr = Dr2 Exit For End If IndexAjuste += 1 Next If Dr IsNot Nothing Then IndexAjuste = TmpDTAjustes.Rows.IndexOf(Dr) DdlFolioGarantia.SelectedValueExist(Dr("CveFolioGarantia").ToString) TxtConsecutivoAjuste.Text = Dr("Consecutivo").ToString TxtCodEnsamble.Text = Dr("CodigoEnsamble").ToString DdlTipoUso.SelectedValueExist(Dr("CveTipoUso").ToString) TxtCodLinea.Text = Dr("CodigoLinea").ToString TxtCodInspeccion.Text = Dr("CodigoInspeccion").ToString TxtMesesUso.Text = Dr("Meses").ToString DdlTipoDefecto.SelectedValueExist(Dr("CveTipoDefecto").ToString) TxtPorcentajeAjuste.Text = Dr("PorcentajeAjuste").ToString TxtPoliza.Text = Dr("NumPoliza").ToString TxtImporteAjuste.Text = Dr("Importe").ToString DdlFacturas.SelectedValueExist(Dr("CveVenta").ToString) CargaPSAjuste() DdlPSAjuste.SelectedValue = (Dr("CvePS").ToString) TxtFechaAjuste.Text = Dr("FechaAjuste").ToString.ToDate.ToShortDateString TxtPrecio.Text = Dr("PUFactura").ToString.ToDecimal.FormatoNumero(2) TxtPrecio.Enabled = Not Dr("CveVenta").ToString.ToEntero > 0 End If End Sub 'Protected Sub BtnCalculaMesesUso_Click(sender As Object, e As EventArgs) ' CalculaMesesUso() 'End Sub Private Function CalculaMesesUso() As Boolean Dim FechaI As Date = TxtFechaAjuste.Text.ToDate.AddDays(1) Dim FechaF As Date = Now If FechaI.AddDays(-1) > FechaF Then TxtFechaAjuste.Text = FechaF.ToString("dd/MM/yyyy") Alert("La fecha de ajuste debe ser menor a la fecha actual", TipoMensaje.ToastAdventencia) Return False End If Dim Dia As Integer = FechaI.Day Try 'validación adicional, para saber si el mes tiene 31 días y el actua es menor. If FechaI.Day > Today.LastDayOfMonth.Day Then Dia = Today.LastDayOfMonth.Day Dim FechaT As Date = String.Format("{0}/{1}/{2}", Dia, FechaF.Month, FechaF.Year).ToDate 'armo la fecha con el día del mes actual Dim MesesTrascurridos As Integer = Math.Round(DateDiff(DateInterval.Day, FechaI, FechaT) / 30.4, 2).ToEntero 'saco los meses y lo redondeo If FechaT > FechaF Then 'todavía está en el mes actual. MesesTrascurridos = MesesTrascurridos Else MesesTrascurridos = MesesTrascurridos + 1 End If TxtMesesUso.Text = MesesTrascurridos.ToString Catch ex As Exception OnError("Ocurrió un error al calcular los meses de uso", ex) End Try Return True End Function Protected Sub DdlPSAjuste_selectedindexchange(sender As Object, e As EventArgs) If DdlPSAjuste.SelectedValue.ToEntero > 0 AndAlso DdlFacturas.SelectedValue.ToEntero > 0 Then Dim Contador As Integer = 1 Dim PUFactura As Decimal = 0 For Each Dr As DataRow In DtPUFacturas.Rows If Index = Contador Then PUFactura = Dr("PU").ToString.ToDecimal End If Contador += 1 Next TxtPUFactura.Text = PUFactura.FormatoNumero(2) End If If DdlPSAjuste.SelectedValue.ToEntero > 0 AndAlso DdlFacturas.SelectedValue.ToEntero <= 0 Then Dim CvePSParametro As Integer = DdlPSAjuste.SelectedValue.ToEntero Dim PrecioSugerido As Decimal = 0 Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSParametro).FiltroPrimero("") Dim CveMarca As Integer = -1 Dim CveClasificacion As Integer = -1 Dim CveTamanio As Integer = -1 If drPS IsNot Nothing Then PrecioSugerido = drPS("Precio").ToString.ToDecimal CveMarca = drPS("CveMarca").ToString.ToEntero CveClasificacion = drPS("CveClasificacion").ToString.ToEntero CveTamanio = drPS("CveTamaño").ToString.ToEntero End If If UsuarioActual.Empresa.Funcionalidad(404).ToEntero > 0 Then 'cuando el valor es 10.- secuencia Cliente/Sucursal, 20 - sucursal/cliente Dim TipoPrecioLista As Integer = UsuarioActual.Empresa.Funcionalidad(404).ToEntero ' si es 10. primero el cliente Dim CvePrecioListaPS As Integer Dim PorcentajePrecio As Decimal = 0 If TipoPrecioLista = 10 Then CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, Estatus:=-1, CveCliente:=CveCliente).FiltroPrimeroValor("CvePrecioLista").ToEntero() If CvePrecioListaPS <= 0 Then CvePrecioListaPS = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePrecioLista", "").ToEntero() End If Else CvePrecioListaPS = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePrecioLista", "").ToEntero() If CvePrecioListaPS <= 0 Then CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, Estatus:=-1, CveCliente:=CveCliente).FiltroPrimeroValor("CvePrecioLista").ToEntero() End If End If If CvePrecioListaPS > 0 Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDecimal PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal End If ObjPS.Dispose() 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(), CveTipoAlmacen:=1) '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, CveTipoAlmacen:=1) ObjInventarios.Dispose() If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If 'CvePrecioLista = CvePrecioListaPS End If TxtPUFactura.Text = PrecioSugerido.FormatoNumero(2) If DTBCIUsados IsNot Nothing AndAlso CveTamanio > 0 Then DdlBCIAjuste.Items.Clear() DdlBCIAjuste.DataSource = DTBCIUsados.FiltraParametros($"CveTamaño={CveTamanio}") DdlBCIAjuste.DataBind() End If DdlTipoUso.Items.Clear() DdlTipoUso.DataSource = GlobalDTAcumGarantiasMesesTipoUso(UsuarioActual.CveEmpresa, CveMarca) DdlTipoUso.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlTipoUso.DataBind() HdnPSAjusteMarca.Value = CveMarca.ToString() HdnPSAjusteClasificacion.Value = CveClasificacion.ToString() End If If Not DdlPSAjuste.SelectedValue.ToEntero > 0 AndAlso DdlFacturas.SelectedValue.ToEntero > 0 Then TxtPUFactura.Text = "" End If If DdlPSAjuste.SelectedValue.ToEntero() > 0 Then CalculaPorcentajeAjuste() End If End Sub Protected Sub DdlTipoUso_SelectedIndexChanged(sender As Object, e As EventArgs) CalculaPorcentajeAjuste() End Sub Protected Sub BtnCalcularImporteAjuste_Click(sender As Object, e As EventArgs) CalculaPorcentajeAjuste() End Sub Private Sub CalculaPorcentajeAjuste() If DdlPS.SelectedValue.ToEntero <= 0 Then Alert("No se ha especificado producto a entregar") Exit Sub End If If DdlPSAjuste.SelectedValue.ToEntero <= 0 Then Alert("No se ha especificado producto de ajuste a entregar") Exit Sub End If If Not CalculaMesesUso() Then Exit Sub End If Try TxtImporteAjuste.Text = "0.00" If DdlTipoUso.SelectedValue.ToEntero > 0 AndAlso DdlPSAjuste.SelectedValue.ToEntero > 0 AndAlso TxtMesesUso.Text <> "" AndAlso DdlPS.SelectedValue.ToEntero > 0 Then Dim CveMarca As Integer = -1 CveMarca = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).FiltroPrimeroValor("CveMarca", "").ToEntero Dim ImportePagarCliente As Decimal = 0 Dim ObjAcum As New ClsAcumuladores If ObjAcum.GarantiasMesesGet(-1, UsuarioActual.CveEmpresa, CveMarca, DdlTipoUso.SelectedValue.ToEntero, TxtMesesUso.Text.ToEntero) Then If ObjAcum.DtResultados.Rows.Count > 0 Then TxtPorcentajeAjuste.Text = (ObjAcum.DtResultados.Rows(0)("Valor").ToString.ToDouble / 100).ToString TxtImporteAjuste.Text = (TxtPorcentajeAjuste.Text.ToDecimal * TxtPUFactura.Text.ToDecimal).FormatoNumero ImportePagarCliente = TxtImporteAjuste.Text.ToDecimal Dim CargoVendido As Decimal = 0 Dim CargoGarantia As Decimal = 0 Dim CveTamaño As Integer = 0 If DdlPSAjuste.SelectedValue.ToEntero > 0 Then Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).FiltroPrimero("") If Dr IsNot Nothing Then CargoGarantia = Dr("Cargo").ToString.ToDecimal End If End If If DdlPS.SelectedValue.ToEntero > 0 Then Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPS.SelectedValue.ToEntero).FiltroPrimero("") If Dr IsNot Nothing Then CveTamaño = Dr("CveTamaño").ToString.ToEntero End If End If Dim DrCargo As DataRow = GlobalDTAcumTamaños.FiltroPrimero($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {CveTamaño}") If DrCargo IsNot Nothing Then CargoVendido = DrCargo("Cargo").ToString.ToDecimal End If 'el ajuste no puede ser mayor al precio de lo vendido de nuevo If (TxtPrecio.Text.ToDouble - ((TxtPUFactura.Text.ToDouble - TxtImporteAjuste.Text.ToDouble) - (CargoVendido - CargoGarantia))) < 0 Then TxtImporteAjuste.Text = "0.00" CargoGarantia = CargoVendido ImportePagarCliente = 0 End If ImportePagarCliente = (TxtPrecio.Text.ToDouble - ((TxtPUFactura.Text.ToDouble - TxtImporteAjuste.Text.ToDouble) - (CargoVendido - CargoGarantia))).ToDecimal TxtImporteAjuste.ToolTip = $"La diferencia de ajuste fue: {(TxtPrecio.Text.ToDouble - TxtImporteAjuste.Text.ToDouble).FormatoNumero()}. La diferencia de tamaños fue: {(CargoVendido - CargoGarantia).FormatoNumero}." TxtImporteAjuste.Text = ((TxtPUFactura.Text.ToDouble - TxtImporteAjuste.Text.ToDouble) - (CargoVendido - CargoGarantia)).FormatoNumero 'TxtPagarCliente.Text = ImportePagarCliente.FormatoNumero Else Alert("El producto no tiene ajuste en ese periodo", TipoMensaje.MsgAdvertencia) 'cuando no está registrada, no da ajuste TxtImporteAjuste.ToolTip = "El producto no tiene ajuste en ese periodo" TxtImporteAjuste.Text = "0.00" End If Else Alert("No se tiene especificado tabla de garantía") End If ObjAcum.Dispose() Else If DdlPSAjuste.SelectedValue.ToEntero <= 0 Then Alert("Especificar el producto a recibir") End If End If Catch ex As Exception OnError("Ocurrió un error al recalcular el costo", ex) End Try UpAjuste.Update() End Sub Private Sub GuardaAjuste() TxtPrecio.Text = TxtPrecio.Text UpAjuste.Update() Dim CargoAnterior As Double = 0 Dim CargoActual As Double = 0 If ModalidadAjuste = "A" Then Dim Row As DataRow = Nothing Row = TmpDTAjustes.NewRow Row("CveFolioGarantia") = DdlFolioGarantia.SelectedValue.ToEntero Row("CveTipoUso") = DdlTipoUso.SelectedValue.ToEntero Row("CveTipoDefecto") = DdlTipoDefecto.SelectedValue.ToEntero Row("CodigoEnsamble") = TxtCodEnsamble.Text Row("CodigoLinea") = TxtCodLinea.Text Row("CodigoInspeccion") = TxtCodInspeccion.Text Row("Consecutivo") = TxtConsecutivoAjuste.Text Row("FechaAjuste") = TxtFechaAjuste.Text.ToDate Row("Meses") = TxtMesesUso.Text.ToEntero Row("PorcentajeAjuste") = TxtPorcentajeAjuste.Text.ToDouble Row("NumPoliza") = TxtPoliza.Text Row("Importe") = TxtImporteAjuste.Text.ToDouble Row("ConsecutivoVenta") = ConsecutivoVenta Row("CvePS") = DdlPSAjuste.SelectedValue Row("PS") = DdlPSAjuste.SelectedText Row("CveVenta") = DdlFacturas.SelectedValue Row("PUFactura") = TxtPrecio.Text.ToDouble Row("Cantidad") = 1 Dim CveUM As Integer = -1 If DdlPSAjuste.SelectedValue.ToEntero > 0 Then Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).Rows(0) If Dr IsNot Nothing Then CveUM = Dr("CveUnidadMedida").ToString.ToEntero CargoAnterior = Dr("Cargo").ToString.ToDouble End If End If Row("CveUM") = CveUM Row("CveVentaDetalle") = -1 TmpDTAjustes.Rows.Add(Row) ElseIf ModalidadAjuste = "U" Then TmpDTAjustes.Rows(IndexAjuste)("CveFolioGarantia") = DdlFolioGarantia.SelectedValue.ToEntero TmpDTAjustes.Rows(IndexAjuste)("CveTipoUso") = DdlTipoUso.SelectedValue.ToEntero TmpDTAjustes.Rows(IndexAjuste)("CveTipoDefecto") = DdlTipoDefecto.SelectedValue.ToEntero TmpDTAjustes.Rows(IndexAjuste)("CodigoEnsamble") = TxtCodEnsamble.Text TmpDTAjustes.Rows(IndexAjuste)("CodigoLinea") = TxtCodLinea.Text TmpDTAjustes.Rows(IndexAjuste)("CodigoInspeccion") = TxtCodInspeccion.Text TmpDTAjustes.Rows(IndexAjuste)("Consecutivo") = TxtConsecutivoAjuste.Text TmpDTAjustes.Rows(IndexAjuste)("FechaAjuste") = TxtFechaAjuste.Text.ToDate TmpDTAjustes.Rows(IndexAjuste)("Meses") = TxtMesesUso.Text.ToDouble TmpDTAjustes.Rows(IndexAjuste)("PorcentajeAjuste") = TxtPorcentajeAjuste.Text.ToDecimal TmpDTAjustes.Rows(IndexAjuste)("NumPoliza") = TxtPoliza.Text.ToDouble TmpDTAjustes.Rows(IndexAjuste)("Importe") = TxtImporteAjuste.Text.ToDouble TmpDTAjustes.Rows(IndexAjuste)("ConsecutivoVenta") = ConsecutivoVenta TmpDTAjustes.Rows(IndexAjuste)("CvePS") = DdlPSAjuste.SelectedValue TmpDTAjustes.Rows(IndexAjuste)("PS") = DdlPSAjuste.SelectedText TmpDTAjustes.Rows(IndexAjuste)("CveVenta") = DdlFacturas.SelectedValue TmpDTAjustes.Rows(IndexAjuste)("PUFactura") = TxtPrecio.Text.ToDouble TmpDTAjustes.Rows(IndexAjuste)("Cantidad") = 1 Dim CveUM As Integer = -1 If DdlPSAjuste.SelectedValue.ToEntero > 0 Then Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).Rows(0) If Dr IsNot Nothing Then CveUM = Dr("CveUnidadMedida").ToString.ToEntero CargoAnterior = Dr("Cargo").ToString.ToDouble End If End If TmpDTAjustes.Rows(IndexAjuste)("CveUM") = CveUM TmpDTAjustes.Rows(IndexAjuste)("CveVentaDetalle") = -1 End If TmpDTAjustes.AcceptChanges() If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then If TmpDT.Select($"Consec={ConsecutivoVenta}").Length > 0 Then Dim Dr As DataRow = TmpDT.Select($"Consec={ConsecutivoVenta}")(0) Dim CvePSCargo As Integer = -1 Dim DrCargo As DataRow = GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {Dr("CveTamaño").ToString.ToEntero}").FiltroPrimero("") If DrCargo IsNot Nothing Then CvePSCargo = DrCargo("CvePSCargo").ToString.ToEntero CargoActual = DrCargo("Cargo").ToString.ToDouble End If Dr("Descuento") = Math.Round(TxtImporteAjuste.Text.ToDouble, NumeroDecimales) 'Dr("Descuento") = Math.Round((TxtPrecio.Text.ToDouble - TxtImporteAjuste.Text.ToDouble) + (CargoActual - CargoAnterior), NumeroDecimales) If Dr("Descuento").ToString.ToDouble > TxtPrecio.Text.ToDouble Then Dr("Descuento") = TxtPrecio.Text.ToDouble Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (Dr("PU").ToString.ToDecimal)) - Dr("Descuento").ToString.ToDecimal 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("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) Dr("IEPS") = Dr("ImporteIEPS") If CvePSCargo > 0 AndAlso TmpDT.Select($"CvePS={CvePSCargo}").Length > 0 Then Dim Dr2 As DataRow = TmpDT.Select($"CvePS={CvePSCargo}")(0) TmpDT.Rows.Remove(Dr2) End If End If End If TmpDT.AcceptChanges() End Sub Protected Sub ChkAjuste_CheckedChanged(sender As Object, e As EventArgs) If ChkAjuste.Checked Then For Each Gvr As GridViewRow In GvRecepcionUsados.Rows If Gvr.RowType = DataControlRowType.DataRow Then Gvr.FCTextBox("TxtCantidad").Text = "" Gvr.FCTextBox("TxtCantidad").Enabled = False End If Next DivAjuste.Visible = True TxtCantidad.Text = "1" TxtCantidad.Enabled = False DivModalVenta.Attributes.Remove("class") DivModalVenta.Attributes.Add("class", "modal-dialog modal-lg") DivAjuste.Attributes.Remove("class") DivAjuste.Attributes.Add("class", "col-md-6") DivDatosVenta.Attributes.Remove("class") DivDatosVenta.Attributes.Add("class", "col-md-6") TxtPrecio.Attributes.Add("onKeyUp", $"CambiaAjuste(this,{TxtPrecio.ClientID});") TxtPrecio.Text = TxtPrecio.Text TxtObsPS.Text = "Descuento por garantía" Else For Each Gvr As GridViewRow In GvRecepcionUsados.Rows If Gvr.RowType = DataControlRowType.DataRow Then Gvr.FCTextBox("TxtCantidad").Text = "" Gvr.FCTextBox("TxtCantidad").Enabled = True End If Next DivAjuste.Visible = False TxtCantidad.Enabled = True TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();") DivModalVenta.Attributes.Remove("class") DivModalVenta.Attributes.Add("class", "modal-dialog") DivAjuste.Attributes.Remove("class") DivAjuste.Attributes.Add("class", "col-md-1") DivDatosVenta.Attributes.Remove("class") DivDatosVenta.Attributes.Add("class", "col-md-12") End If UpModalVenta.Update() RegistraScript("$('#DivAddVenta').modal({backdrop: 'static', keyboard: false});") RegistraScript("Recalcula();", "Recalcula") End Sub Protected Sub DdlFolioGarantia_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFolioGarantia.SelectedIndexChanged Dim ObjAcumuladores As New ClsAcumuladores If ObjAcumuladores.GetNuevoConsecutivoFolio(DdlFolioGarantia.SelectedValue.ToEntero) Then Dim resultado As Integer = ObjAcumuladores.DtResultados.FiltroPrimeroValor("NuevoConsecutivo").ToEntero If ObjAcumuladores.FoliosGarantiaGet(DdlFolioGarantia.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then Dim Limite As Integer = If(ObjAcumuladores.DtResultados.FiltroPrimeroValor("Limite") IsNot Nothing, ObjAcumuladores.DtResultados.FiltroPrimeroValor("Limite").ToEntero, 0) 'ObjAcumuladores.DtResultados.FiltroPrimeroValor("Limite").ToEntero If resultado < Limite Or Limite = 0 Then TxtConsecutivoAjuste.Text = resultado.ToString Else Alert("limite de folios alcanzado") End If End If UpAjuste.Update() End If ObjAcumuladores.Dispose() Dim FolioGarantia As MFolioGarantiaMensaje = ValidaFolioGarantia(DdlPSAjuste.SelectedValue.ToEntero(), DdlFolioGarantia.SelectedValue.ToEntero()) If Not FolioGarantia.Valido Then Alert($"El folio de garantía no es valido.
Clasificacion del Producto:{FolioGarantia.ClasificacionPS}.
Tipo Folio:{FolioGarantia.TipoFolio}", TipoMensaje.MsgAdvertencia) End If End Sub #End Region #Region "P O L I Z A - V I R T U A L" Private Sub CreaDTmpDTPolizaVirtual() TmpDTPolizaVirtual = New DataTable TmpDTPolizaVirtual.Columns.Add("CvePS", GetType(Integer)) TmpDTPolizaVirtual.Columns.Add("Cantidad", GetType(Decimal)) TmpDTPolizaVirtual.Columns.Add("PU", GetType(Decimal)) TmpDTPolizaVirtual.Columns.Add("Descuento", GetType(Decimal)) TmpDTPolizaVirtual.Columns.Add("Total", GetType(Decimal)) TmpDTPolizaVirtual.Columns.Add("CveVentaDetalle", GetType(Integer)) TmpDTPolizaVirtual.Columns.Add("TipoServicio", GetType(Integer)) TmpDTPolizaVirtual.Columns.Add("TipoPoliza", GetType(Integer)) TmpDTPolizaVirtual.Columns.Add("CveModeloAuto", GetType(Integer)) TmpDTPolizaVirtual.Columns.Add("AnioVehiculo", GetType(Integer)) TmpDTPolizaVirtual.Columns.Add("TieneUsado", GetType(Boolean)) TmpDTPolizaVirtual.Columns.Add("FechaUsado", GetType(DateTime)) TmpDTPolizaVirtual.Columns.Add("CvePSUsado", GetType(Integer)) TmpDTPolizaVirtual.Columns.Add("CveBCIUsado", GetType(Integer)) End Sub Private Function AddPolizaVirtual(CvePS As Integer) As Boolean Dim Retorno As Boolean = True If Modalidad = "U" Then If TmpDTPolizaVirtual.Rows.Count > 0 Then Dim Elimino As Boolean = False For Each RowPoliza As DataRow In TmpDTPolizaVirtual.Rows If RowPoliza("CvePS").ToString().ToEntero() = CvePS Then RowPoliza.Delete() Elimino = True Exit For End If Next If Elimino Then TmpDTRecepcionUsados.AcceptChanges() End If End If End If Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If DrPS IsNot Nothing Then 'SOLO DEBE AGREGAR POLIZA VIRTUAL SI ES ACUMULADOR If Not DrPS("CveClasificacion").ToString().ToEntero().Contiene(20520, 20522, 20513, 20511, 20521, 20512, 20514, 20229) Then Return Retorno End If Else Retorno = False Return Retorno End If Dim Cantidad As Decimal = TxtCantidad.Text.ToDecimal() Dim PU As Decimal = TxtPrecio.Text.ToDecimal() Dim Descuento As Decimal = TxtDescuento.Text.ToDecimal() Dim ImporteAjuste As Decimal = TxtImporteAjuste.Text.ToDecimal().RoundSQL(2) Dim Total As Decimal = ((Cantidad * PU) - Descuento).RoundSQL(2) Dim TipoServicio As Integer = DdlTipoServicio.SelectedValue.ToEntero() Dim FechaUsado As DateTime = If(TxtFechaAjuste.Text.ToDateTime() < MinFecha, Now, TxtFechaAjuste.Text.ToDateTime()) Dim CveModeloAuto As Integer = DdlModeloAuto.SelectedValue.ToEntero() Dim AnioVehiculo As Integer = TxtAnioVehiculo.Text.ToEntero() Dim TipoPoliza As Integer = 1 'VENTA If ChkAjuste.Checked Then If Total = ImporteAjuste Then TipoPoliza = 3 'GARANTIA Else TipoPoliza = 2 'AJUSTE End If End If Dim TieneUsado As Boolean = GvRecepcionUsados.Rows.Cast(Of GridViewRow).Any(Function(GvRow) GvRow.RowType = DataControlRowType.DataRow AndAlso GvRow.FCTextBox("TxtCantidad").Text.ToDecimal() > 0) Dim CvePSUsado As Integer = -1 Dim CveBCIUsado As Integer = -1 If TieneUsado Then For Each GvRow As GridViewRow In GvRecepcionUsados.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCTextBox("TxtCantidad").Text.ToDecimal() > 0 Then CvePSUsado = GvRow.DataKey("CvePSCargo").ToEntero() CveBCIUsado = GvRow.FCDropDownList("DdlBCIUsado").SelectedValue.ToEntero() Exit For End If End If Next End If Dim Row As DataRow = TmpDTPolizaVirtual.NewRow() Row("CvePS") = CvePS Row("Cantidad") = Cantidad Row("PU") = PU Row("Descuento") = Descuento Row("Total") = Total Row("CveVentaDetalle") = -1 Row("TipoServicio") = TipoServicio Row("TipoPoliza") = TipoPoliza Row("CveModeloAuto") = CveModeloAuto Row("AnioVehiculo") = AnioVehiculo Row("TieneUsado") = TieneUsado Row("FechaUsado") = FechaUsado Row("CvePSUsado") = CvePSUsado Row("CveBCIUsado") = CveBCIUsado TmpDTPolizaVirtual.Rows.Add(Row) Return Retorno End Function #End Region #Region "U S A D O S" Private Sub CreaDTmpDTRecepcionUsados() TmpDTRecepcionUsados = New DataTable TmpDTRecepcionUsados.Columns.Add("CvePS", GetType(Integer)) TmpDTRecepcionUsados.Columns.Add("CvePSRelacionado", GetType(Integer)) TmpDTRecepcionUsados.Columns.Add("Cantidad", GetType(Decimal)) TmpDTRecepcionUsados.Columns.Add("CveUM", GetType(Integer)) TmpDTRecepcionUsados.Columns.Add("CveVentaDetalle", GetType(Integer)) TmpDTRecepcionUsados.Columns.Add("PU", GetType(Double)) TmpDTRecepcionUsados.Columns.Add("CveBCIUsado", GetType(Integer)) TmpDTRecepcionUsados.Columns.Add("CveModeloAuto", GetType(Integer)) TmpDTRecepcionUsados.Columns.Add("EliminarDB", GetType(Boolean)) TmpDTRecepcionUsados.Columns("EliminarDB").DefaultValue = False End Sub Protected Sub BtnRecepcionUsados_Click(sender As Object, e As EventArgs) 'CalculaRecepcionUsados(GvRecepcionUsadosModal) RegistraScript("$('#DModalRecepcionUsados').modal('hide');") EmitirImprimirNew() End Sub Private Sub CalculaRecepcionUsados(Gv As GridView, CvePS As Integer, ListaPSCargo As List(Of Integer)) If Modalidad = "U" Then If TmpDTRecepcionUsados.Rows.Count > 0 Then Dim Elimino As Boolean = False For Each Row As DataRow In TmpDTRecepcionUsados.Rows If Row("CvePSRelacionado").ToString().ToEntero() = CvePS Then Row.Delete() Elimino = True End If Next If Elimino Then TmpDTRecepcionUsados.AcceptChanges() End If End If End If Dim TotalCargos As Decimal = 0 Dim TotalCantidad As Decimal = 0 Dim StrTamanios As New StringBuilder() StrTamanios.Append("Se recibierón los siguientes usados:") For Each Gvr As GridViewRow In Gv.Rows If Gvr.RowType = DataControlRowType.DataRow Then If Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal > 0 Then TotalCargos += Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal * Gvr.DataKey("Cargo").ToDecimal TotalCantidad += Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal StrTamanios.AppendFormat("{0},", Gvr.DataKey("CodigoPS")) Dim Row As DataRow = TmpDTRecepcionUsados.NewRow() Row("CvePS") = Gvr.DataKey("CvePSCargo").ToEntero Row("CvePSRelacionado") = CvePS Row("Cantidad") = Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal Row("CveUM") = Gvr.DataKey("CveUM").ToEntero Row("CveVentaDetalle") = -1 Row("PU") = Gvr.DataKey("Cargo").ToDouble Row("CveBCIUsado") = Gvr.FCDropDownList("DdlBCIUsado").SelectedValue.ToEntero Row("CveModeloAuto") = DdlModeloAuto.SelectedValue.ToEntero TmpDTRecepcionUsados.Rows.Add(Row) End If End If Next If TotalCargos > 0 Then StrTamanios.Remove(StrTamanios.Length - 1, 1) Else StrTamanios.Clear() End If Dim StrCargos As New StringBuilder For Each CvePSCargo As Integer In ListaPSCargo StrCargos.AppendFormat(" {0},", CvePSCargo) Next StrCargos.Remove(StrCargos.Length - 1, 1) 'If TotalCantidad > TmpDT.FiltraParametros($"EsCargo = True AND CvePS IN ({StrCargos})").SUMD("Cantidad") Then ' Dim drt As DataRow() = TmpDT.Select("CvePS = " & CvePS) ' TmpDT.Rows.Remove(drt(0)) ' Alert("No puede tener una cantidad mayor a la de los cargos", TipoMensaje.MsgAdvertencia) ' Exit Sub 'End If For Each Dr As DataRow In TmpDT.FiltraParametros($"EsCargo = True AND EliminarDB = False AND CvePS IN ({StrCargos})").Rows Dim TotalAnterior As Decimal = Dr("Cantidad").ToString.ToDecimal * Dr("PU").ToString.ToDecimal 'Dim PUActual As Decimal = (TotalAnterior - TotalCargos) / Dr("Cantidad").ToString.ToDecimal Dim DescuentoCargo As Decimal = (TotalCargos / Dr("Cantidad").ToString.ToDecimal) If DescuentoCargo > (TotalAnterior - Dr("Descuento").ToString.ToDecimal()) Then DescuentoCargo = (TotalAnterior - Dr("Descuento").ToString.ToDecimal()) End If Dim Descuento As Decimal = Dr("Descuento").ToString.ToDecimal + DescuentoCargo Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (Dr("PU").ToString.ToDecimal)) - Descuento TotalCargos -= DescuentoCargo 'If PUActual <= 0 Then ' Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString) ' TmpDT.Rows.Remove(drt(0)) 'Else 'End If Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString) Dim drr As DataRow = drt(0) 'drr("PU") = PUActual drr("ImporteIVA") = Math.Round(Dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) drr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) drr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) drr("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) drr("IEPS") = Dr("ImporteIEPS") drr("Descuento") = Descuento drr("Obs") = StrTamanios.ToString() + Dr("Obs").ToString() 'drr("Total") = (Dr("Cantidad").ToString.ToDecimal * PUActual) 'drr("TotalImporte") = Math.Round(Dr("Cantidad").ToString.ToDecimal * PUActual, NumeroDecimales) If TotalCargos <= 0 Then Exit For End If Next TmpDT.AcceptChanges() If TotalCargos > 0 Then ' cuando se entrega más valor de usados, que los cargos hechos, se descuenta sobre el PU del producto de venta For Each Dr As DataRow In TmpDT.FiltraParametros($"EsCargo = False AND EliminarDB = False AND CvePS={CvePS}").Rows Dim PUAnterior As Decimal = Dr("Cantidad").ToString.ToDecimal * Dr("PU").ToString.ToDecimal Dim DescuentoCargo As Decimal = (TotalCargos / Dr("Cantidad").ToString.ToDecimal) If DescuentoCargo > (PUAnterior - Dr("Descuento").ToString.ToDecimal()) Then DescuentoCargo = (PUAnterior - Dr("Descuento").ToString.ToDecimal()) End If 'Dim PUActual As Decimal = PUAnterior - DescuentoCargo Dim Descuento As Decimal = Dr("Descuento").ToString.ToDecimal + DescuentoCargo Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (PUAnterior)) - Descuento TotalCargos += -DescuentoCargo Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString) Dim drr As DataRow = drt(0) drr("ImporteIVA") = Math.Round(Dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) drr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) drr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) drr("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) drr("IEPS") = Dr("ImporteIEPS") drr("Descuento") = Descuento 'drr("Obs") = StrTamanios.ToString() + Dr("Obs").ToString() 'drr("Total") = (Dr("Cantidad").ToString.ToDecimal * PUActual) 'drr("TotalImporte") = Math.Round(Dr("Cantidad").ToString.ToDecimal * PUActual, NumeroDecimales) 'If PUActual <= 0 Then ' Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString) ' TmpDT.Rows.Remove(drt(0)) 'Else ' Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString) ' Dim drr As DataRow = drt(0) ' 'drr("PU") = PUActual ' drr("ImporteIVA") = Math.Round(Dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) ' drr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) ' drr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) ' drr("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales) ' drr("IEPS") = Dr("ImporteIEPS") ' 'drr("Total") = (Dr("Cantidad").ToString.ToDecimal * PUActual) ' 'drr("TotalImporte") = Math.Round(Dr("Cantidad").ToString.ToDecimal * PUActual, NumeroDecimales) 'End If If TotalCargos <= 0 Then Exit For End If Next End If TmpDT.AcceptChanges() TmpDTRecepcionUsados.AcceptChanges() CalculaTotalesVenta() End Sub Private Function CalculaUsados(Consec As Integer, Optional LimpiarUsados As Boolean = True) As List(Of Integer) If Modalidad = "U" AndAlso LimpiarUsados Then EliminarUsados(Consec) End If Dim ListaPScargo As New List(Of Integer) Dim DTTamanios As DataTable = GlobalDTAcumTamaños() Dim DTCvePSCostos = DTTamanios.FiltraParametros("", "", {"CvePSCargo"}) Dim CveUnidadMedidaPSA As Integer = -1 Dim UnidadMedidaPSA As String = "Unidad" Dim CveClasificacionPSA As Integer = -1 Dim ClasificacionPSA As String = "" Dim CveSubProyectoPSA As Integer = -1 Dim SubProyectoPSA As String = "" Dim PSPSA As String = "" Dim DTPSTemp As New DataTable '= TmpDT.Clone DTPSTemp.Columns.Add("Cantidad", GetType(Integer)) DTPSTemp.Columns.Add("CveUnidadMedida", GetType(Integer)) DTPSTemp.Columns.Add("UnidadMedida", GetType(String)) DTPSTemp.Columns.Add("CveClasificacion", GetType(Integer)) DTPSTemp.Columns.Add("Clasificacion", 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)) DTPSTemp.Columns.Add("ConsecPSPadre", GetType(Integer)) DTPSTemp.Columns.Add("EliminarDB", GetType(Boolean)) DTPSTemp.Columns("EliminarDB").DefaultValue = False Dim ObjProductosServicios As New ClsProductosServicios() For Each DrowPartidas As DataRow In TmpDT.Select($"Consec = {Consec}") 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 CveClasificacionPSA = ObjProductosServicios.CveClasificacion ClasificacionPSA = ObjProductosServicios.Clasificacion UnidadMedidaPSA = ObjProductosServicios.DtResultados.FiltroPrimeroValor("UnidadMedida") PSPSA = ObjProductosServicios.PS 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("CveClasificacion") = CveClasificacionPSA dRowNuevo("Clasificacion") = ClasificacionPSA dRowNuevo("CvePS") = CvePsTemp dRowNuevo("PS") = PSPSA dRowNuevo("CveSubProyecto") = DrowPartidas("CveSubProyecto").ToString.ToEntero dRowNuevo("SubProyecto") = DrowPartidas("SubProyecto").ToString dRowNuevo("ConsecPSPadre") = Consec DTPSTemp.Rows.Add(dRowNuevo) DTPSTemp.AcceptChanges() End If End If Next ObjProductosServicios.Dispose() Dim ModalidadBack = Modalidad 'CAMBIA LA MODALIDAD PARA AGREGAR LOS PS CARGO If Modalidad = "U" Then Modalidad = "A" End If For Each drowPsTamaños As DataRow In DTPSTemp.Rows If drowPsTamaños("PU").ToString.ToDecimal > 0 Then Dim Concec = AgregarProductoServicio(drowPsTamaños("Cantidad").ToString.ToEntero, drowPsTamaños("CveUnidadMedida").ToString.ToEntero, drowPsTamaños("UnidadMedida").ToString, drowPsTamaños("CveClasificacion").ToString.ToEntero, drowPsTamaños("Clasificacion").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, EsCargo:=True, ConsecPSPadre:=drowPsTamaños("ConsecPSPadre").ToString.ToEntero, EliminarDB:=CBool(drowPsTamaños("EliminarDB").ToString())) If Consec > 0 Then ListaPScargo.Add(drowPsTamaños("CvePS").ToString.ToEntero) End If End If Next Modalidad = ModalidadBack Return ListaPScargo End Function Private Sub EliminarUsados(Consec As Integer) 'ELIMINAR EL USADO EXTRAS For Each drow As DataRow In TmpDT.Select($"ConsecPSPadre ={Consec}") drow.Delete() Next 'ELIMINAR LOS USADOS QUE SE MANDAN A RECEPCION For Each drow As DataRow In TmpDT.Select($"Consec ={Consec}") For Each RowRecepcionUsados As DataRow In TmpDTRecepcionUsados.Rows If (RowRecepcionUsados("CvePSRelacionado").ToString() = drow("CvePS").ToString()) Then RowRecepcionUsados.Delete() End If Next Next TmpDT.AcceptChanges() TmpDTRecepcionUsados.AcceptChanges() End Sub Private Sub EliminarUsados() 'ELIMINAR EL USADO EXTRAS For Each drow As DataRow In TmpDT.Select("EsCargo = True") drow("EliminarDB") = True Next 'ELIMINAR LOS USADOS QUE SE MANDAN A RECEPCION For Each drow As DataRow In TmpDT.Select("EsCargo = True") For Each RowRecepcionUsados As DataRow In TmpDTRecepcionUsados.Rows If (RowRecepcionUsados("CvePSRelacionado").ToString() = drow("CvePS").ToString()) Then RowRecepcionUsados.Delete() End If Next Next TmpDT.AcceptChanges() TmpDTRecepcionUsados.AcceptChanges() End Sub #End Region Protected Sub BtnPDFHistorial_Click(sender As Object, e As EventArgs) Dim ObjPS As New ClsProductosServicios Dim MarcaPS As String = "" If ObjPS.GetPS(DdlPSAjuste.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa) Then MarcaPS = ObjPS.DtResultados.FiltroPrimeroValor("Marca", String.Format("CvePS = {0}", DdlPSAjuste.SelectedValue.ToEntero)) 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) Dim DtDatos As New DataTable Dim params As New List(Of ReportParameter) 'Informacion Distribuidor If (DdlDistribuidor.SelectedValue.ToEntero > 0) Then Dim DatosClienteSeleccionado As DataRow = GlobalDTCliente(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveCliente = {0}", DdlDistribuidor.SelectedValue.ToEntero)) Dim Ciudad As String = DatosClienteSeleccionado.Item("Ciudad").ToString Dim Estado As String = DatosClienteSeleccionado.Item("Estado").ToString params.Add(New ReportParameter("NombreDistribuidor", DdlDistribuidor.SelectedText)) params.Add(New ReportParameter("CiudadEstado", String.Format("{0}, {1}", Ciudad.Trim, Estado))) params.Add(New ReportParameter("TelCliente", DatosClienteSeleccionado.Item("Telefono").ToString)) End If params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("Consec", TxtConsecutivoAjuste.Text.Trim)) params.Add(New ReportParameter("FolioAcuse", If(DdlFolioGarantia.SelectedValue.ToEntero = -1, "", DdlFolioGarantia.SelectedItem.Text))) 'Informacion de Garantia o ajuste params.Add(New ReportParameter("FechaInst", TxtFechaAjuste.Text.Trim)) params.Add(New ReportParameter("Fecha", Now.ToShortDateString)) params.Add(New ReportParameter("Defecto", If(DdlTipoDefecto.SelectedValue.ToEntero = -1, "", DdlTipoDefecto.SelectedItem.Text))) params.Add(New ReportParameter("MesesUso", TxtMesesUso.Text.Trim)) params.Add(New ReportParameter("PorcentajeAjuste", TxtPorcentajeAjuste.Text.Trim)) 'Informacion Acumulador params.Add(New ReportParameter("CodEnsamble", TxtCodEnsamble.Text.Trim)) params.Add(New ReportParameter("CodLinea", TxtCodLinea.Text.Trim)) params.Add(New ReportParameter("CodInspeccion", TxtCodInspeccion.Text.Trim)) params.Add(New ReportParameter("Tipo", DdlBCIAjuste.SelectedItem.Text)) params.Add(New ReportParameter("Marca", MarcaPS)) 'Informacion Vehiculo params.Add(New ReportParameter("MarcaAuto", If(DdlPS.SelectedValue.ToEntero > 0, DtModelosAuto.FiltroPrimeroValor("Marca", $"CveModeloAuto ={DdlModeloAuto.SelectedValue}"), ""))) params.Add(New ReportParameter("TipoAuto", If(DdlPS.SelectedValue.ToEntero > 0, DtModelosAuto.FiltroPrimeroValor("Modelo", $"CveModeloAuto ={DdlModeloAuto.SelectedValue}"), ""))) 'Informacion Consumidor params.Add(New ReportParameter("NombreCliente", LtlCliente.Text)) params.Add(New ReportParameter("Direccion", LblDireccion.Text)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If ImprimirPDF("Empresas/Grales/Formatos/Ajuste.rdlc", DtDatos, params, "Reporte de Ajuste", "PDF") End Sub Private Function ValidaFolioGarantia(CvePS As Integer, CveFolioGarantia As Integer) As MFolioGarantiaMensaje Dim Retorno As New MFolioGarantiaMensaje Dim Valido As Boolean = False Dim TipoFolio As String = "" Dim ListaClasificacionesPermitidas As New List(Of Integer) Dim ObjAcumuladores As New ClsAcumuladores If ObjAcumuladores.FoliosGarantiaGet(CveFolioGarantia, UsuarioActual.CveEmpresa, Area:=-1) AndAlso ObjAcumuladores.DtResultados.Rows.Count > 0 Then Dim Row As DataRow = ObjAcumuladores.DtResultados.Rows(0) TipoFolio = Row("tipoFolio").ToString().ToUpper() End If ObjAcumuladores.Dispose() Dim CveClasificacionPS As Integer = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimeroValor("CveClasificacion").ToEntero() Dim ClasificacionPS As String = GlobalDTClasificaciones(CveEmpresa:=UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacionPS).FiltroPrimeroValor("Clasificacion").ToString() Select Case TipoFolio Case "GENERAL" '20520 ACUM. AUTOMOTRIZ '20522 ACUM. ESPECIALES '20513 ACUM. ESTANDAR '20521 ACUM. PESADO '20512 ACUM. PREMIUM '20514 ACUM. VALUE '20229 Acumulador ListaClasificacionesPermitidas.Add(20520) 'ACUM. AUTOMOTRIZ ListaClasificacionesPermitidas.Add(20522) 'ACUM. ESPECIALES ListaClasificacionesPermitidas.Add(20513) 'ACUM. ESTANDAR ListaClasificacionesPermitidas.Add(20521) 'ACUM. PESADO ListaClasificacionesPermitidas.Add(20512) 'ACUM. PREMIUM ListaClasificacionesPermitidas.Add(20514) 'ACUM. VALUE ListaClasificacionesPermitidas.Add(20229) 'Acumulador Case "OPTIMA" '20511 ACUM. OPTIMA ListaClasificacionesPermitidas.Add(20511) 'ACUM. OPTIMA Case "MOTOBATERIA" '20517 MOTOBATERIAS ListaClasificacionesPermitidas.Add(20517) 'MOTOBATERIAS End Select If ListaClasificacionesPermitidas.Contains(CveClasificacionPS) Then Valido = True End If Retorno.CvePS = CvePS Retorno.CveFolioGarantia = CveFolioGarantia Retorno.CveClasificacionPS = CveClasificacionPS Retorno.ClasificacionPS = ClasificacionPS Retorno.TipoFolio = TipoFolio Retorno.Valido = Valido Return Retorno End Function Partial Class MFolioGarantiaMensaje Public Property CvePS As Integer Public Property CveClasificacionPS As Integer Public Property ClasificacionPS As String Public Property CveFolioGarantia As Integer Public Property TipoFolio As String Public Property Valido As Boolean End Class End Class