Option Explicit On Option Strict On Option Infer On Imports System.Data Imports System.Data.SqlClient Imports System.Diagnostics Imports System.IO Imports System.Net.Http Imports System.Security.Cryptography.X509Certificates Imports ADSNetLibrary.SIGAPI.Models.CRM.Request Imports ADSNetLibrary.SIGAPI.Services.CRM Imports ADSTimbrado Imports Extensiones Imports Microsoft.Reporting.WebForms Imports Newtonsoft.Json.Linq Partial Class VentasMedicas Inherits ClsPaginas #Region "Propiedades" Private Const NumeroDecimales As Integer = 2 Dim ColumnaDescuento As Integer = 10 Dim ColumnaPredial As Integer = 11 Dim ColumnaIVA As Integer = 12 Dim ColumnaIEPS As Integer = 13 Dim ColumnaRetIVA As Integer = 14 Dim ColumnaRetISR As Integer = 15 Dim ColumnaEditar As Integer = 17 Dim ColumnaEliminar As Integer = 18 'Factura de ventas Dim DTConceptos As DataTable Private Property Version As String Private Property Fecha As String Private Property SerieXML As String Private Property FolioXML As String Private Property SubTotal As Decimal Private Property Total As Decimal = 0 ' Private Property Descuentos As Decimal = 0 Private Property EmisorRFC As String Private Property ReceptorRFC As String Private Property TrasladoIVA As Decimal = 0 Private Property RetencionIVA As Decimal = 0 Private Property RetencionISR As Decimal = 0 Private Property TrasladoIEPS As Decimal = 0 Private Property TFDUUID As String = "" Private Property Moneda As String = "" Private Property TipoComprobante As String = "" Private Property OtrosImpuestos As Decimal = 0 Private Property TotalRetenciones As Decimal = 0 Private Property SumaTotalRetenciones As Decimal = 0 Private Property TotalTraslados As Decimal = 0 Private Property SumaTotalTraslados As Decimal = 0 Private Property SubTotalConceptos As Decimal = 0 Private Property Redondeo As Decimal = 0 Private Property NumRow As Integer Private Property EsSupervisor As Boolean = False Private Property MandarCorreoSupervisor As Boolean = False Private ReadOnly Property ExFolioFactura As Boolean Get Return CBool(ViewState("ExFolioFactura")) End Get End Property Private Property CveFactura As Integer Get Return ViewState("CveFactura").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveFactura") = value End Set End Property Private Property CuentasContablesInvalidas As StringBuilder Get Return CType(ViewState("CuentasContablesInvalidas"), StringBuilder) End Get Set(value As StringBuilder) ViewState("CuentasContablesInvalidas") = value End Set End Property 'Local Private Property DtPorcentajeMarcas As DataTable Get Return If(IsNothing(ViewState("DtPorcentajeMarcas")), Nothing, CType(ViewState("DtPorcentajeMarcas"), DataTable)) End Get Set(value As DataTable) ViewState("DtPorcentajeMarcas") = 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 TmpDTDescNC As DataTable Get Return If(IsNothing(ViewState("TmpDTDescNC")), Nothing, CType(ViewState("TmpDTDescNC"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTDescNC") = value End Set End Property Private Property TmpDTDescNCBonificacion As DataTable Get Return If(IsNothing(ViewState("TmpDTDescNCBonificacion")), Nothing, CType(ViewState("TmpDTDescNCBonificacion"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTDescNCBonificacion") = value End Set End Property Private Property TmpDTBonificacion As DataTable Get Return If(IsNothing(ViewState("TmpDTBonificacion")), Nothing, CType(ViewState("TmpDTBonificacion"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTBonificacion") = value End Set End Property Private Property TmpDTRNCBonificacionesCliente As DataTable Get Return If(IsNothing(ViewState("TmpDTRNCBonificacionesCliente")), Nothing, CType(ViewState("TmpDTRNCBonificacionesCliente"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTRNCBonificacionesCliente") = value End Set End Property Private Property TmpDTRNCBonificacionesSeleccionadas As DataTable Get Return If(IsNothing(ViewState("TmpDTRNCBonificacionesSeleccionadas")), Nothing, CType(ViewState("TmpDTRNCBonificacionesSeleccionadas"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTRNCBonificacionesSeleccionadas") = value End Set End Property Private Property TmpDTRNCDetalle As DataTable Get Return If(IsNothing(ViewState("TmpDTRNCDetalle")), Nothing, CType(ViewState("TmpDTRNCDetalle"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTRNCDetalle") = value End Set End Property Private Property TmpDTRNCDetalleSelecciondas As DataTable Get Return If(IsNothing(ViewState("TmpDTRNCDetalleSelecciondas")), Nothing, CType(ViewState("TmpDTRNCDetalleSelecciondas"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTRNCDetalleSelecciondas") = value End Set End Property Private Property TmpDTRNCBonificacionDetalle As DataTable Get Return If(IsNothing(ViewState("TmpDTRNCBonificacionDetalle")), Nothing, CType(ViewState("TmpDTRNCBonificacionDetalle"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTRNCBonificacionDetalle") = value End Set End Property Private Property TmpDTRNCBonificacionDetalleSeleccionadas As DataTable Get Return If(IsNothing(ViewState("TmpDTRNCBonificacionDetalleSeleccionadas")), Nothing, CType(ViewState("TmpDTRNCBonificacionDetalleSeleccionadas"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTRNCBonificacionDetalleSeleccionadas") = value End Set End Property Private Property TmpDTError As DataTable Get Return If(IsNothing(ViewState("TmpDTError")), Nothing, CType(ViewState("TmpDTError"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTError") = value End Set End Property Private Property TmpDTImpuestos As DataTable Get Return If(IsNothing(ViewState("TmpDTImpuestos")), Nothing, CType(ViewState("TmpDTImpuestos"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTImpuestos") = value End Set End Property Private Property TmpDTImpuestosIVAIEPS As DataTable Get Return If(IsNothing(ViewState("TmpDTImpuestosIVAIEPS")), Nothing, CType(ViewState("TmpDTImpuestosIVAIEPS"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTImpuestosIVAIEPS") = value End Set End Property Private Property TmpDTDocumentosRelacionados As DataTable Get Return If(IsNothing(ViewState("TmpDTDocumentosRelacionados")), Nothing, CType(ViewState("TmpDTDocumentosRelacionados"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTDocumentosRelacionados") = value End Set End Property Private Property TmpDTNCVinculadas As DataTable Get Return If(IsNothing(ViewState("TmpDTNCVinculadas")), Nothing, CType(ViewState("TmpDTNCVinculadas"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTNCVinculadas") = value End Set End Property Private Property TmpDTEnvioDireccion As DataTable Get Return If(IsNothing(ViewState("TmpDTEnvioDireccion")), Nothing, CType(ViewState("TmpDTEnvioDireccion"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTEnvioDireccion") = value End Set End Property Private Property TmpDTDireccionCP As DataTable Get Return If(IsNothing(ViewState("TmpDTDireccionCP")), Nothing, CType(ViewState("TmpDTDireccionCP"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTDireccionCP") = value End Set End Property Private Property IdPoliza As Integer Get Return ViewState("IdPoliza").ToString().ToEntero() End Get Set(value As Integer) ViewState("IdPoliza") = value End Set End Property Private Property CveAlmacenDevolucion As Integer Get Return ViewState("CveAlmacenDevolucion").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveAlmacenDevolucion") = value End Set End Property Private Property EraCotizacion As Integer Get Return ViewState("EraCotizacion").ToString().ToEntero() End Get Set(value As Integer) ViewState("EraCotizacion") = value End Set End Property Private Property FacturaMateriales As Integer Get Return ViewState("FacturaMateriales").ToString().ToEntero() End Get Set(value As Integer) ViewState("FacturaMateriales") = value End Set End Property Private Property TmpDTDeducciones As DataTable Get Return If(IsNothing(ViewState("TmpDTDeducciones")), Nothing, CType(ViewState("TmpDTDeducciones"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTDeducciones") = value End Set End Property Private Property TmpDTComplementos As DataTable Get Return If(IsNothing(ViewState("TmpDTComplementos")), Nothing, CType(ViewState("TmpDTComplementos"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTComplementos") = value End Set End Property Private Property DTmpC As DataTable Get Return If(IsNothing(ViewState("DTmpC")), Nothing, CType(ViewState("DTmpC"), DataTable)) End Get Set(value As DataTable) ViewState("DTmpC") = value End Set End Property Private Property DTmpF As DataTable Get Return If(IsNothing(ViewState("DTmpF")), Nothing, CType(ViewState("DTmpF"), DataTable)) End Get Set(value As DataTable) ViewState("DTmpF") = value End Set End Property Private Property DTSucursal As DataTable Get Return If(IsNothing(ViewState("DTSucursal")), Nothing, CType(ViewState("DTSucursal"), DataTable)) End Get Set(value As DataTable) ViewState("DTSucursal") = value End Set End Property Private Property DTOrdenesCompra As DataTable Get Return If(IsNothing(ViewState("DTOrdenesCompra")), Nothing, CType(ViewState("DTOrdenesCompra"), DataTable)) End Get Set(value As DataTable) ViewState("DTOrdenesCompra") = value End Set End Property Private Property DTOrdenesCompraPS As DataTable Get Return If(IsNothing(ViewState("DTOrdenesCompraPS")), Nothing, CType(ViewState("DTOrdenesCompraPS"), DataTable)) End Get Set(value As DataTable) ViewState("DTOrdenesCompraPS") = value End Set End Property Private Property DtOCTmpDT As DataTable Get Return If(IsNothing(ViewState("DtOCTmpDT")), Nothing, CType(ViewState("DtOCTmpDT"), DataTable)) End Get Set(value As DataTable) ViewState("DtOCTmpDT") = value End Set End Property Private Property DTRemisiones As DataTable Get Return If(IsNothing(ViewState("DTRemisiones")), Nothing, CType(ViewState("DTRemisiones"), DataTable)) End Get Set(value As DataTable) ViewState("DTRemisiones") = value End Set End Property Private Property ListaDescuentos As List(Of Modelos.VentaDescuentos) Get Return If(IsNothing(ViewState("ListaDescuentos")), Nothing, CType(ViewState("ListaDescuentos"), List(Of Modelos.VentaDescuentos))) End Get Set(value As List(Of Modelos.VentaDescuentos)) ViewState("ListaDescuentos") = 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 ListaRemisionesNC As List(Of Modelos.Factura) Get Return If(IsNothing(ViewState("ListaRemisionesNC")), Nothing, CType(ViewState("ListaRemisionesNC"), List(Of Modelos.Factura))) End Get Set(value As List(Of Modelos.Factura)) ViewState("ListaRemisionesNC") = value End Set End Property Private Property ListaNCDesc As List(Of Modelos.Factura) Get Return If(IsNothing(ViewState("ListaNCDesc")), Nothing, CType(ViewState("ListaNCDesc"), List(Of Modelos.Factura))) End Get Set(value As List(Of Modelos.Factura)) ViewState("ListaNCDesc") = value End Set End Property Private Property ListaNCBonificacion As List(Of Modelos.Factura) Get Return If(IsNothing(ViewState("ListaNCBonificacion")), Nothing, CType(ViewState("ListaNCBonificacion"), List(Of Modelos.Factura))) End Get Set(value As List(Of Modelos.Factura)) ViewState("ListaNCBonificacion") = value End Set End Property Private Property Pedidos2Lista As List(Of Integer) Get Return If(IsNothing(ViewState("Pedidos2Lista")), Nothing, CType(ViewState("Pedidos2Lista"), List(Of Integer))) End Get Set(value As List(Of Integer)) ViewState("Pedidos2Lista") = value End Set End Property Private Property DtRemisionesPS As DataTable Get Return If(IsNothing(ViewState("DtRemisionesPS")), Nothing, CType(ViewState("DtRemisionesPS"), DataTable)) End Get Set(value As DataTable) ViewState("DtRemisionesPS") = value End Set End Property Private Property DtCotizaciones As DataTable Get Return If(IsNothing(ViewState("DtCotizaciones")), Nothing, CType(ViewState("DtCotizaciones"), DataTable)) End Get Set(value As DataTable) ViewState("DtCotizaciones") = value End Set End Property Private Property CotizacionesLista As List(Of Integer) Get Return If(IsNothing(ViewState("CotizacionesLista")), Nothing, CType(ViewState("CotizacionesLista"), List(Of Integer))) End Get Set(value As List(Of Integer)) ViewState("CotizacionesLista") = value End Set End Property Private Property DtCotizacionesPS As DataTable Get Return If(IsNothing(ViewState("DtCotizacionesPS")), Nothing, CType(ViewState("DtCotizacionesPS"), DataTable)) End Get Set(value As DataTable) ViewState("DtCotizacionesPS") = value End Set End Property Private Property DtCotizacionTmpDT As DataTable Get Return If(IsNothing(ViewState("DtCotizacionTmpDT")), Nothing, CType(ViewState("DtCotizacionTmpDT"), DataTable)) End Get Set(value As DataTable) ViewState("DtCotizacionTmpDT") = value End Set End Property Private Property DtRemisionesTmpDT As DataTable Get Return If(IsNothing(ViewState("DtRemisionesTmpDT")), Nothing, CType(ViewState("DtRemisionesTmpDT"), DataTable)) End Get Set(value As DataTable) ViewState("DtRemisionesTmpDT") = value End Set End Property Private Property DtPedidos2TmpDT As DataTable Get Return If(IsNothing(ViewState("DtPedidos2TmpDT")), Nothing, CType(ViewState("DtPedidos2TmpDT"), DataTable)) End Get Set(value As DataTable) ViewState("DtPedidos2TmpDT") = value End Set End Property Private Property DtRemConceptosSurtidos As DataTable Get Return If(IsNothing(ViewState("DtRemConceptosSurtidos")), Nothing, CType(ViewState("DtRemConceptosSurtidos"), DataTable)) End Get Set(value As DataTable) ViewState("DtRemConceptosSurtidos") = value End Set End Property Private Property HuboCambioRemi As Boolean Get Return If(IsNothing(ViewState("HuboCambioRemi")), False, CType(ViewState("HuboCambioRemi"), Boolean)) End Get Set(value As Boolean) ViewState("HuboCambioRemi") = value End Set End Property Private Property AplicaGastoContrato As Boolean Get Return If(IsNothing(ViewState("AplicaGastoContrato")), False, CType(ViewState("AplicaGastoContrato"), Boolean)) End Get Set(value As Boolean) ViewState("AplicaGastoContrato") = value End Set End Property Private Property EsCreaApartirDe As Boolean Get Return If(IsNothing(ViewState("EsCreaApartirDe")), False, CType(ViewState("EsCreaApartirDe"), Boolean)) End Get Set(value As Boolean) ViewState("EsCreaApartirDe") = value End Set End Property Private Property RequiereAlmacenDestino As Boolean Get Return If(IsNothing(ViewState("RequiereAlmacenDestino")), False, CType(ViewState("RequiereAlmacenDestino"), Boolean)) End Get Set(value As Boolean) ViewState("RequiereAlmacenDestino") = value End Set End Property Private Property RequiereAlmacenOrigen As Boolean Get Return If(IsNothing(ViewState("RequiereAlmacenOrigen")), False, CType(ViewState("RequiereAlmacenOrigen"), Boolean)) End Get Set(value As Boolean) ViewState("RequiereAlmacenOrigen") = value End Set End Property Private Property AplicoNCFacturaActual As Boolean Get Return If(IsNothing(ViewState("AplicoNCFacturaActual")), False, CType(ViewState("AplicoNCFacturaActual"), Boolean)) End Get Set(value As Boolean) ViewState("AplicoNCFacturaActual") = value End Set End Property Private Property EmpresaActual As Empresa Get Return CType(ViewState("EmpresaActual"), Empresa) End Get Set(value As Empresa) ViewState("EmpresaActual") = value End Set End Property Property CargaDocumentoOC As Boolean Get If ViewState("CargaDocumentoOC") Is Nothing Then Return False Else Return DirectCast(ViewState("CargaDocumentoOC"), Boolean) End If End Get Set(value As Boolean) ViewState("CargaDocumentoOC") = value End Set End Property Private Property DTFacNC As DataTable Get Return If(IsNothing(ViewState("DTFacNC")), Nothing, CType(ViewState("DTFacNC"), DataTable)) End Get Set(value As DataTable) ViewState("DTFacNC") = value End Set End Property Private Property DtPromociones As DataTable Get Return If(IsNothing(ViewState("DtPromociones")), Nothing, CType(ViewState("DtPromociones"), DataTable)) End Get Set(value As DataTable) ViewState("DtPromociones") = value End Set End Property Private ReadOnly Property CveCliente As Integer Get Return ViewState("CveCliente").ToString().ToEntero() End Get End Property Private ReadOnly Property CveClienteAnterior As Integer Get Return ViewState("CveClienteAnterior").ToString().ToEntero() End Get End Property Private Property CveClienteSucursal As Integer Get If ViewState("CveClienteSucursal") Is Nothing Then Return -1 Else Return ViewState("CveClienteSucursal").ToString().ToEntero() End If End Get Set(value As Integer) ViewState("CveClienteSucursal") = value End Set End Property Private Property CveAnticipo As Integer Get If ViewState("CveAnticipo") Is Nothing Then Return -1 Else Return ViewState("CveAnticipo").ToString().ToEntero() End If End Get Set(value As Integer) ViewState("CveAnticipo") = value End Set End Property Private Property CveUsuarioActual As Integer Get Return ViewState("CveUsuarioActual").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveUsuarioActual") = value End Set End Property Private ReadOnly Property Mail As String Get Return IfNull(ViewState("Mail"), "").ToString() End Get End Property Private ReadOnly Property MailCC As String Get Return IfNull(ViewState("MailCC"), "").ToString() End Get End Property Public ReadOnly Property CveVenta As Integer Get Return ViewState("CveVenta").ToString().ToEntero() End Get End Property Private ReadOnly Property CveSubProyectoVenta As Integer Get Return If(IsNothing(ViewState("CveSubProyectoVenta")), -1, ViewState("CveSubProyectoVenta").ToString().ToEntero()) End Get End Property Private Property CveVentaPadre As Integer Get Return If(IsNothing(ViewState("CveVentaPadre")), -1, ViewState("CveVentaPadre").ToString().ToEntero()) End Get Set(value As Integer) ViewState("CveVentaPadre") = value End Set End Property Private Property CveEstatusFacturaPadre As Integer Get Return If(IsNothing(ViewState("CveEstatusFacturaPadre")), -1, ViewState("CveEstatusFacturaPadre").ToString().ToEntero()) End Get Set(value As Integer) ViewState("CveEstatusFacturaPadre") = value End Set End Property Private Property CveMovimientoDetalle As Integer Get Return If(IsNothing(ViewState("CveMovimientoDetalle")), -1, ViewState("CveMovimientoDetalle").ToString().ToEntero()) End Get Set(value As Integer) ViewState("CveMovimientoDetalle") = value End Set End Property Private ReadOnly Property CveDevolucion As Integer Get Return ViewState("CveDevolucion").ToString().ToEntero() End Get End Property Private Property CveVentaRelacion As Integer Get Return If(IsNothing(ViewState("CveVentaRelacion")), -1, ViewState("CveVentaRelacion").ToString().ToEntero()) End Get Set(value As Integer) ViewState("CveVentaRelacion") = value End Set End Property Private Property ImporteRelacion As Double Get Return If(IsNothing(ViewState("ImporteRelacion")), 0, ViewState("ImporteRelacion").ToString().ToDouble) End Get Set(value As Double) ViewState("ImporteRelacion") = value End Set End Property Private Property IsTotalxConcepto As Boolean Get Return If(IsNothing(ViewState("IsTotalxConcepto")), False, CBool(ViewState("IsTotalxConcepto").ToString())) End Get Set(value As Boolean) ViewState("IsTotalxConcepto") = value End Set End Property Private ReadOnly Property CveAlmacenTransitorio As Integer Get Return ViewState("CveAlmacenTransitorio").ToString().ToEntero() End Get End Property Private ReadOnly Property NuevaFactura As Integer Get Return ViewState("NuevaFactura").ToString().ToEntero() End Get End Property Private ReadOnly Property VentaFolio As String Get Return ViewState("VentaFolio").ToString() End Get End Property Private ReadOnly Property SelloCancelacion As String Get Return ViewState("SelloCancelacion").ToString() End Get End Property Private ReadOnly Property FechaCancelacion As DateTime Get Return ViewState("FechaCancelacion").ToString().ToDateTime End Get End Property Private ReadOnly Property EstablecioFolio As Boolean Get Return CBool(ViewState("EstablecioFolio")) End Get End Property Private ReadOnly Property FolioFiscal As String Get Return ViewState("FolioFiscal").ToString() End Get End Property Private ReadOnly Property Ruta As String Get Return UsuarioActual.Empresa.Ruta End Get End Property Private ReadOnly Property RutaPruebas As String Get Return String.Format("{0}Empresas/1/", ModExtensiones.DirectorioBaseEmpresas) End Get End Property Private ReadOnly Property TipoCambio As Decimal Get Return ViewState("TipoCambio").ToString().ToDecimal End Get End Property Private ReadOnly Property ProcesoCorrecto As Boolean Get Return CBool(ViewState("ProcesoCorrecto")) End Get End Property 'FUENTES RECAUDACIÓN Private Property DTPresupuestoIngresos As DataTable Get Return CType(ViewState("DTPresupuestoIngresos"), DataTable) End Get Set(value As DataTable) ViewState("DTPresupuestoIngresos") = value End Set End Property 'Folios Private ReadOnly Property CveFolio As Integer Get Return ViewState("CveFolio").ToString().ToEntero() End Get End Property Private ReadOnly Property NumAprobacion As Long Get Return CLng(ViewState("NumAprobacion").ToString()) End Get End Property Private ReadOnly Property FechaAprobacion As Date Get Return ViewState("FechaAprobacion").ToString().ToDate End Get End Property Private ReadOnly Property FolioActual As String Get Return ViewState("FolioActual").ToString() End Get End Property 'Sucursal Private ReadOnly Property Serie As String Get Return ViewState("Serie").ToString() End Get End Property Private ReadOnly Property Folio As Integer Get Return ViewState("Folio").ToString().ToEntero() End Get End Property Private ReadOnly Property FormatoFactura As String Get Return ViewState("FormatoFactura").ToString() End Get End Property Private ReadOnly Property TipoFormato As String Get Return ViewState("TipoFormato").ToString() End Get End Property Private ReadOnly Property IVA As Decimal Get Return ViewState("IVA").ToString().ToDecimal End Get End Property 'Private ReadOnly Property SubProyectoPorcentajeIVA As Decimal ' Get ' Return ViewState("SubProyectoPorcentajeIVA").ToString().ToDecimal ' End Get 'End Property Private ReadOnly Property ClienteRetIVA As Decimal Get Return ViewState("ClienteRetIVA").ToString().ToDecimal End Get End Property Private ReadOnly Property ClienteRetISR As Decimal Get Return ViewState("ClienteRetISR").ToString().ToDecimal End Get End Property Private ReadOnly Property ClienteDesglosaIEPS As Boolean Get Return CType(ViewState("ClienteDesglosaIEPS").ToString(), Boolean) End Get End Property Private ReadOnly Property ClienteNODesglosaIVA As Boolean Get Return CType(ViewState("ClienteNODesglosaIVA").ToString(), Boolean) End Get End Property 'Cliente Private ReadOnly Property NombreCliente As String Get Return ViewState("NombreCliente").ToString() End Get End Property Private ReadOnly Property Vendedor As String Get Return ViewState("Vendedor").ToString() End Get End Property Private ReadOnly Property CodCliente As String Get Return ViewState("CodCliente").ToString() End Get End Property Private ReadOnly Property CliNoExt As String Get Return ViewState("CliNoExt").ToString() End Get End Property Private ReadOnly Property CliNoInt As String Get Return ViewState("CliNoInt").ToString() End Get End Property Private ReadOnly Property CliLocalidad As String Get Return ViewState("CliLocalidad").ToString() End Get End Property Private ReadOnly Property CliPais As String Get Return ViewState("CliPais").ToString() End Get End Property Private ReadOnly Property SucCalle As String Get Return ViewState("SucCalle").ToString() End Get End Property Private ReadOnly Property CliCorreoCot As String Get If ViewState("CliCorreoCot") Is Nothing Then Return "" Else Return ViewState("CliCorreoCot").ToString() End If End Get End Property Private ReadOnly Property SucNoExt As String Get Return ViewState("SucNoExt").ToString() End Get End Property Private ReadOnly Property SucNoInt As String Get Return ViewState("SucNoInt").ToString() End Get End Property Private ReadOnly Property SucColonia As String Get Return ViewState("SucColonia").ToString() End Get End Property Private ReadOnly Property SucLocalidad As String Get Return ViewState("SucLocalidad").ToString() End Get End Property Private ReadOnly Property SucMunicipio As String Get Return ViewState("SucMunicipio").ToString() End Get End Property Private ReadOnly Property SucEstado As String Get Return ViewState("SucEstado").ToString() End Get End Property Private ReadOnly Property SucPais As String Get Return ViewState("SucPais").ToString() End Get End Property Private ReadOnly Property SucCP As String Get Return ViewState("SucCP").ToString() End Get End Property Private ReadOnly Property MatCalle As String Get Return ViewState("MatCalle").ToString() End Get End Property Private ReadOnly Property MatNoExt As String Get Return ViewState("MatNoExt").ToString() End Get End Property Private ReadOnly Property MatNoInt As String Get Return ViewState("MatNoInt").ToString() End Get End Property Private ReadOnly Property MatColonia As String Get Return ViewState("MatColonia").ToString() End Get End Property Private ReadOnly Property MatLocalidad As String Get Return ViewState("MatLocalidad").ToString() End Get End Property Private ReadOnly Property MatMunicipio As String Get Return ViewState("MatMunicipio").ToString() End Get End Property Private ReadOnly Property MatEstado As String Get Return ViewState("MatEstado").ToString() End Get End Property Private ReadOnly Property MatPais As String Get Return ViewState("MatPais").ToString() End Get End Property Private ReadOnly Property MatCP As String Get Return ViewState("MatCP").ToString() End Get End Property Private Property ImprimeNombreSucursal As Boolean Get Return CBool(ViewState("ImprimeNombreSucursal")) End Get Set(value As Boolean) ViewState("ImprimeNombreSucursal") = value End Set End Property Private ReadOnly Property AplicaFEMSA As Boolean Get Return CBool(ViewState("AplicaFEMSA")) End Get End Property Private ReadOnly Property AplicaComercioExterior As Boolean Get Return CBool(ViewState("AplicaComercioExterior")) End Get End Property Private ReadOnly Property CveTipoOperacion As Integer Get Return CInt(ViewState("CveTipoOperacion")) End Get End Property Private ReadOnly Property CvePedimento As Integer Get Return CInt(ViewState("CvePedimento")) End Get End Property Private ReadOnly Property CveIncoterm As Integer Get Return CInt(ViewState("CveIncoterm")) End Get End Property Private ReadOnly Property AplicaDetallista As Boolean Get Return CBool(ViewState("AplicaDetallista")) End Get End Property Private ReadOnly Property AplicaFord As Boolean Get Return CBool(ViewState("AplicaFord")) End Get End Property Private Property CveOS As Integer Get Return ViewState("CveOS").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveOS") = value End Set End Property Private ReadOnly Property SaldoVenta As Decimal Get Return If(IsNothing(ViewState("SaldoVenta")), 0, ViewState("SaldoVenta").ToString().ToDecimal) End Get End Property Private Property CvePSAmortizacion As Integer Get Return ViewState("CvePSAmortizacion").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePSAmortizacion") = value End Set End Property 'Inventarios Private Property DtInv As DataTable Get Return CType(ViewState("DtInv"), DataTable) End Get Set(value As DataTable) ViewState("DtInv") = value End Set End Property Private Property CvePrePoliza As Integer Get Return ViewState("CvePrePoliza").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePrePoliza") = value End Set End Property Private ReadOnly Property SeGuardoPrePoliza As Boolean Get Return CBool(ViewState("SeGuardoPrePoliza")) End Get End Property Private Property CveVentaFacturada As Integer Get Return ViewState("CveVentaFacturada").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveVentaFacturada") = value End Set End Property Private ReadOnly Property AplicarVentaFacturada As Boolean Get Return CBool(ViewState("AplicarVentaFacturada")) End Get End Property 'Estimaciones Private Property CveContrato As Integer Get Return ViewState("CveContrato").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveContrato") = value End Set End Property Private Property CvePedido As Integer Get Return ViewState("CvePedido").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePedido") = value End Set End Property Private Property CvePedido2 As Integer Get Return ViewState("CvePedido2").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePedido2") = value End Set End Property Private Property TipoContrato As Integer Get Return ViewState("TipoContrato").ToString().ToEntero() End Get Set(value As Integer) ViewState("TipoContrato") = value End Set End Property Private Property Opcion As String Get Return ViewState("Opcion").ToString() End Get Set(value As String) ViewState("Opcion") = value End Set End Property Private Property CorreoNotificacionPedDev As String Get Return If(IsNothing(ViewState("CorreoNotificacionDevPed")), "", ViewState("CorreoNotificacionDevPed").ToString()) End Get Set(value As String) ViewState("CorreoNotificacionDevPed") = value End Set End Property 'Presupuesto Private Property CvePresupuesto As Integer Get Return ViewState("CvePresupuesto").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePresupuesto") = value End Set End Property Private Property TotalOtrosConceptos As Decimal Get Return ViewState("TotalOtrosConceptos").ToString().ToDecimal End Get Set(value As Decimal) ViewState("TotalOtrosConceptos") = value End Set End Property Private Property TipoCambioFactura As Decimal Get Return ViewState("TipoCambioFactura").ToString().ToDecimal End Get Set(value As Decimal) ViewState("TipoCambioFactura") = value End Set End Property Private Property DtPagos As DataTable Get Return CType(ViewState("DtPagos"), DataTable) End Get Set(value As DataTable) ViewState("DtPagos") = value End Set End Property Private Property DevolucionAlmacen As Integer Get Return ViewState("DevolucionAlmacen").ToString().ToEntero() End Get Set(value As Integer) ViewState("DevolucionAlmacen") = value End Set End Property Private Property DevolucionAlmacenNC As Integer Get Return IfNull(ViewState("DevolucionAlmacenNC"), 2, ViewState("DevolucionAlmacenNC").ToString().ToString()).ToString().ToEntero() End Get Set(value As Integer) ViewState("DevolucionAlmacenNC") = value End Set End Property Private ReadOnly Property TipoDoctoDevolucion As String Get Return ViewState("TipoDoctoDevolucion").ToString() End Get End Property Private Property PlazoCobranza As Integer Get Return ViewState("PlazoCobranza").ToString().ToEntero() End Get Set(value As Integer) ViewState("PlazoCobranza") = value End Set End Property Private Property PlazoCobranzaRemision As Integer Get Return ViewState("PlazoCobranzaRemision").ToString().ToEntero() End Get Set(value As Integer) ViewState("PlazoCobranzaRemision") = value End Set End Property 'CvePAC Private Property CvePAC As Integer Get Return ViewState("CvePAC").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePAC") = value End Set End Property Private Property AplicaDevolucion As Boolean Get Return If(IsNothing(ViewState("AplicaDevolucion")), False, CType(ViewState("AplicaDevolucion"), Boolean)) End Get Set(value As Boolean) ViewState("AplicaDevolucion") = value End Set End Property Private Property CveVentaDevolucion As Integer Get Return If(IsNothing(ViewState("CveVentaDevolucion")), 0, CType(ViewState("CveVentaDevolucion"), Integer)) End Get Set(value As Integer) ViewState("CveVentaDevolucion") = value End Set End Property Private Property SaldoVentaDevolucion As Decimal Get Return ViewState("SaldoVentaDevolucion").ToString().ToDecimal End Get Set(value As Decimal) ViewState("SaldoVentaDevolucion") = value End Set End Property Private Property ContratoOC As Boolean Get Return If(IsNothing(ViewState("ContratoOC")), False, CType(ViewState("ContratoOC"), Boolean)) End Get Set(value As Boolean) ViewState("ContratoOC") = value End Set End Property Private Property TieneAlmacen As Boolean Get Return If(IsNothing(ViewState("TieneAlmacen")), False, CType(ViewState("TieneAlmacen"), Boolean)) End Get Set(value As Boolean) ViewState("TieneAlmacen") = value End Set End Property Private Property PorcentajeIVA As Decimal Get Return ViewState("PorcentajeIVA").ToString().ToDecimal End Get Set(value As Decimal) ViewState("PorcentajeIVA") = value End Set End Property Private Property CveEstatusRefacturacion As Integer Get Return If(IsNothing(ViewState("CveEstatusRefacturacion")), 0, CType(ViewState("CveEstatusRefacturacion"), Integer)) End Get Set(value As Integer) ViewState("CveEstatusRefacturacion") = value End Set End Property Private Property RefacturarCancelada As Boolean Get Return If(IsNothing(ViewState("RefacturarCancelada")), False, CBool(ViewState("RefacturarCancelada"))) End Get Set(value As Boolean) ViewState("RefacturarCancelada") = value End Set End Property Private Property CveEstadoCancelacion As Integer Get Return If(IsNothing(ViewState("CveEstadoCancelacion")), 0, CType(ViewState("CveEstadoCancelacion"), Integer)) End Get Set(value As Integer) ViewState("CveEstadoCancelacion") = value End Set End Property Private Property PermiteCredito As Boolean Get Return If(IsNothing(ViewState("PermiteCredito")), False, CBool(ViewState("PermiteCredito"))) End Get Set(value As Boolean) ViewState("PermiteCredito") = value End Set End Property Private Property DtAnticipoAmortizacion As DataTable Get Return CType(ViewState("DtAnticipoAmortizacion"), DataTable) End Get Set(value As DataTable) ViewState("DtAnticipoAmortizacion") = value End Set End Property Private Property SaldoAnticipo As Decimal Get Return If(IsNothing(ViewState("SaldoAnticipo")), 0, ViewState("SaldoAnticipo").ToString().ToDecimal()) End Get Set(value As Decimal) ViewState("SaldoAnticipo") = value End Set End Property Private Property CorreoEntregaAlmacen As String Get Return If(IsNothing(ViewState("CorreoEntregaAlmacen")), "", ViewState("CorreoEntregaAlmacen").ToString()) End Get Set(value As String) ViewState("CorreoEntregaAlmacen") = value End Set End Property Private Property CveVentaUsadoDevolucionEfectivo As Integer Get Return If(IsNothing(ViewState("CveVentaUsadoDevolucionEfectivo")), 0, CType(ViewState("CveVentaUsadoDevolucionEfectivo"), Integer)) End Get Set(value As Integer) ViewState("CveVentaUsadoDevolucionEfectivo") = value End Set End Property Private Property RFCReceptorVenta As String Get Return If(IsNothing(ViewState("RFCReceptorVenta")), "", ViewState("RFCReceptorVenta").ToString()) End Get Set(value As String) ViewState("RFCReceptorVenta") = value End Set End Property Private Property RegimenFiscalCliente As String Get Return IfNull(ViewState("RegimenFiscalCliente"), "").ToString() End Get Set(value As String) ViewState("RegimenFiscalCliente") = value End Set End Property Private Property RegimenSociedad As String Get Return IfNull(ViewState("RegimenSociedad"), "").ToString() End Get Set(value As String) ViewState("RegimenSociedad") = value End Set End Property Private Property TipoPersona As Boolean Get Return CBool(IfNull(ViewState("TipoPersona"), False)) End Get Set(value As Boolean) ViewState("TipoPersona") = value End Set End Property Private Property Adjunto As String Get Return If(IsNothing(ViewState("Adjunto")), "", ViewState("Adjunto").ToString()) End Get Set(value As String) ViewState("Adjunto") = value End Set End Property Private Property VentaActual As Venta Get Return DirectCast(ViewState("VentaActual"), Venta) End Get Set(value As Venta) ViewState("VentaActual") = value End Set End Property Private Property ListaAnticiposAplicados As List(Of Modelos.MAnticipoRelacionado) Get Return If(IsNothing(ViewState("ListaAnticiposAplicados")), Nothing, CType(ViewState("ListaAnticiposAplicados"), List(Of Modelos.MAnticipoRelacionado))) End Get Set(value As List(Of Modelos.MAnticipoRelacionado)) ViewState("ListaAnticiposAplicados") = value End Set End Property Private Property CveTimbreCartaPorteVenta As Integer Get Return If(IsNothing(ViewState("CveTimbreCartaPorteVenta")), -1, ViewState("CveTimbreCartaPorteVenta").ToString().ToEntero()) End Get Set(value As Integer) ViewState("CveTimbreCartaPorteVenta") = value End Set End Property #End Region #Region "Propiedades PuntoVenta" Private Property CveCorte As Integer Get Return ViewState("CveCorte").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveCorte") = value End Set End Property Private Property Entrega As String Get Return ViewState("Entrega").ToString() End Get Set(value As String) ViewState("Entrega") = value End Set End Property Private Property Vigencia As String Get Return ViewState("Vigencia").ToString() End Get Set(value As String) ViewState("Vigencia") = value End Set End Property Private Property DineroCaja As Double Get Return ViewState("DineroCaja").ToString().ToDouble End Get Set(value As Double) ViewState("DineroCaja") = value End Set End Property Private ReadOnly Property CveCicloComercial As Integer Get Return ViewState("CveCicloComercial").ToString().ToEntero() End Get End Property #End Region #Region "Propiedades Contratos" Private Property DtContratos As DataTable Get Return If(IsNothing(ViewState("DtContratos")), Nothing, CType(ViewState("DtContratos"), DataTable)) End Get Set(value As DataTable) ViewState("DtContratos") = value End Set End Property Private Property NumeroContrato As String Get Return ViewState("NumeroContrato").ToString() End Get Set(value As String) ViewState("NumeroContrato") = value End Set End Property Private Property DescripcionContrato As String Get Return ViewState("DescripcionContrato").ToString() End Get Set(value As String) ViewState("DescripcionContrato") = value End Set End Property Private Property NumeroLicitacion As String Get Return ViewState("NumeroLicitacion").ToString() End Get Set(value As String) ViewState("NumeroLicitacion") = value End Set End Property Private Property CveAlmacenExistenciasContrato As Integer Get Return ViewState("CveAlmacenExistenciasContrato").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveAlmacenExistenciasContrato") = value End Set End Property Private Property CveAlmacenOrigenContrato As Integer Get Return ViewState("CveAlmacenOrigenContrato").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveAlmacenOrigenContrato") = value End Set End Property Private Property DtContratosSerieDetalle As DataTable Get Return If(IsNothing(ViewState("DtContratosSerieDetalle")), Nothing, CType(ViewState("DtContratosSerieDetalle"), DataTable)) End Get Set(value As DataTable) ViewState("DtContratosSerieDetalle") = value End Set End Property Private Property CvePSSerie As Integer Get Return CType(ViewState("CvePSSerie"), Integer) End Get Set(value As Integer) ViewState("CvePSSerie") = value End Set End Property Private Property CveUMSerie As Integer Get Return CType(ViewState("CveUMSerie"), Integer) End Get Set(value As Integer) ViewState("CveUMSerie") = value End Set End Property Private Property CveConsecSerie As Integer Get Return CType(ViewState("CveConsecSerie"), Integer) End Get Set(value As Integer) ViewState("CveConsecSerie") = value End Set End Property Private Property LimitaCantidadSerie As Integer Get Return CType(ViewState("LimitaCantidadSerie"), Integer) End Get Set(value As Integer) ViewState("LimitaCantidadSerie") = value End Set End Property Private Property PorAmortizacionAnticipo As Integer Get If ViewState("PorAmortizacionAnticipo") Is Nothing Then Return 0 Else Return CType(ViewState("PorAmortizacionAnticipo"), Integer) End If End Get Set(value As Integer) ViewState("PorAmortizacionAnticipo") = value End Set End Property Private Property AmortizacionSujeridaContrato As Decimal Get If ViewState("AmortizacionSujeridaContrato") Is Nothing Then Return 0 Else Return ViewState("AmortizacionSujeridaContrato").ToString.ToDecimal End If End Get Set(value As Decimal) ViewState("AmortizacionSujeridaContrato") = value End Set End Property Private Property EscontratoObra As Boolean Get If ViewState("EscontratoObra") Is Nothing Then Return False Else Return Boolean.Parse(ViewState("EscontratoObra").ToString) End If End Get Set(value As Boolean) ViewState("EscontratoObra") = value End Set End Property #End Region #Region " PROPIEDADES NUEVAS | GUARDAR - IMPRESION " Private Property ErrorList As List(Of String) Get Return CType(ViewState("ErrorList"), List(Of String)) End Get Set(value As List(Of String)) ViewState("ErrorList") = value End Set End Property Private Property MensajeAlert As StringBuilder Get Return CType(ViewState("MensajeAlert"), StringBuilder) End Get Set(value As StringBuilder) ViewState("MensajeAlert") = value End Set End Property Private Property ObjFactura As Modelos.Factura Get Return CType(ViewState("ObjFactura"), Modelos.Factura) End Get Set(value As Modelos.Factura) ViewState("ObjFactura") = value End Set End Property Private Property ObjFacturaDevolucion As Modelos.Factura Get Return CType(ViewState("ObjFacturaDevolucion"), Modelos.Factura) End Get Set(value As Modelos.Factura) ViewState("ObjFacturaDevolucion") = value End Set End Property Private Property ObjFacturaBonificacion As Modelos.Factura Get Return CType(ViewState("ObjFacturaBonificacion"), Modelos.Factura) End Get Set(value As Modelos.Factura) ViewState("ObjFacturaBonificacion") = value End Set End Property Private Property ObjFacturaNC As Modelos.Factura Get Return CType(ViewState("ObjFacturaNC"), Modelos.Factura) End Get Set(value As Modelos.Factura) ViewState("ObjFacturaNC") = value End Set End Property #End Region #Region " PROPIEDADES NUEVAS " Private Property CveOC As Integer Get Return ViewState("CveOC").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveOC") = value End Set End Property Private Property RegistroxOC As Boolean Get Return CBool(IfNull(ViewState("RegistroxOC"), False)) End Get Set(value As Boolean) ViewState("RegistroxOC") = value End Set End Property Private Property EnviarCorreoCliente As Boolean Get Return CBool(IfNull(ViewState("EnviarCorreoCliente"), False)) End Get Set(value As Boolean) ViewState("EnviarCorreoCliente") = value End Set End Property Private Property EstatusCliente As Boolean Get Return CBool(ViewState("EstatusCliente").ToString()) End Get Set(value As Boolean) ViewState("EstatusCliente") = value End Set End Property 'Private Property CveMetodoPagoCliente As Integer ' Get ' Return ViewState("CveMetodoPagoCliente").ToString().ToEntero() ' End Get ' Set(value As Integer) ' ViewState("CveMetodoPagoCliente") = value ' End Set 'End Property Private Property Modalidad As String Get Return ViewState("Modalidad").ToString() End Get Set(value As String) ViewState("Modalidad") = value End Set End Property Private Property Index As Integer Get Return ViewState("Index").ToString().ToEntero() End Get Set(value As Integer) ViewState("Index") = value End Set End Property Private Property TotAnt As Decimal Get Return ViewState("TotAnt").ToString().ToDecimal End Get Set(value As Decimal) ViewState("TotAnt") = value End Set End Property Private Property TotalOriginal As Double Get Return ViewState("TotalOriginal").ToString().ToDouble End Get Set(value As Double) ViewState("TotalOriginal") = value End Set End Property Private Property AplicaCancelarRemision As Boolean Get Return CBool(ViewState("AplicaCancelarRemision").ToString()) End Get Set(value As Boolean) ViewState("AplicaCancelarRemision") = value End Set End Property Private Property TipoVentaSucursal As Integer Get Return ViewState("TipoVentaSucursal").ToString().ToEntero() End Get Set(value As Integer) ViewState("TipoVentaSucursal") = value End Set End Property Private Property MensajeCveSAT As StringBuilder Get If ViewState("MensajeCveSAT") Is Nothing Then ViewState("MensajeCveSAT") = New StringBuilder Return CType(ViewState("MensajeCveSAT"), StringBuilder) End Get Set(value As StringBuilder) ViewState("TipoVentaSucursal") = value End Set End Property Private Property EditoRemision As Boolean Get Return CBool(ViewState("EditoRemision").ToString()) End Get Set(value As Boolean) ViewState("EditoRemision") = value End Set End Property Private Property AplicaNC As Boolean Get Return CBool(ViewState("AplicaNC").ToString()) End Get Set(value As Boolean) ViewState("AplicaNC") = value End Set End Property Private Property DtVentasNC As DataTable Get Return CType(ViewState("DtVentasNC"), DataTable) End Get Set(value As DataTable) ViewState("DtVentasNC") = value End Set End Property Private Property AplicaNCMasiva As Boolean Get Return CBool(ViewState("AplicaNCMasiva").ToString()) End Get Set(value As Boolean) ViewState("AplicaNCMasiva") = value End Set End Property Private Property RefacturacionGeneroNC As Boolean Get Return CBool(ViewState("RefacturacionGeneroNC").ToString()) End Get Set(value As Boolean) ViewState("RefacturacionGeneroNC") = value End Set End Property Private Property ModalidadEdicion As Boolean Get Return CBool(ViewState("ModalidadEdicion").ToString()) End Get Set(value As Boolean) ViewState("ModalidadEdicion") = value End Set End Property Private Property ConversionRemision As String Get Return ViewState("ConversionRemision").ToString() End Get Set(value As String) ViewState("ConversionRemision") = value End Set End Property Private Property TipoCambioRemision As Decimal Get Return ViewState("TipoCambioRemision").ToString().ToDecimal End Get Set(value As Decimal) ViewState("TipoCambioRemision") = value End Set End Property Private Property TieneContrato As Boolean Get Return CBool(ViewState("TieneContrato").ToString()) End Get Set(value As Boolean) ViewState("TieneContrato") = value End Set End Property Private Property CveOrdenCompraContrato As Integer Get Return ViewState("CveOrdenCompraContrato").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveOrdenCompraContrato") = value End Set End Property Private Property ContratosConOC As StringBuilder Get If ViewState("ContratosConOC") Is Nothing Then ViewState("ContratosConOC") = New StringBuilder Return CType(ViewState("ContratosConOC"), StringBuilder) End Get Set(value As StringBuilder) ViewState("ContratosConOC") = value End Set End Property Private Property RequiereOC As Boolean Get Return CBool(ViewState("RequiereOC").ToString()) End Get Set(value As Boolean) ViewState("RequiereOC") = value End Set End Property Private Property PorcentajeCredito As Decimal Get Return ViewState("PorcentajeCredito").ToString().ToDecimal End Get Set(value As Decimal) ViewState("PorcentajeCredito") = value End Set End Property Private Property CvePedidoA As Integer Get Return ViewState("CvePedidoA").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePedidoA") = value End Set End Property Private Property CveAcercamiento As Integer Get If ViewState("CveAcercamiento") Is Nothing Then ViewState("CveAcercamiento") = -1 End If Return ViewState("CveAcercamiento").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveAcercamiento") = value End Set End Property Private Property CveEmpresaCRM As Integer Get Return ViewState("CveEmpresaCRM").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveEmpresaCRM") = value End Set End Property Private Property CveAcercamientoCRM As Integer Get Return ViewState("CveAcercamientoCRM").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveAcercamientoCRM") = value End Set End Property Private Property CorreoContactoCRM As String Get If ViewState("CorreoContactoCRM") Is Nothing Then ViewState("CorreoContactoCRM") = "" End If Return ViewState("CorreoContactoCRM").ToString() End Get Set(value As String) ViewState("CorreoContactoCRM") = value End Set End Property Private Property DtPedidos2 As DataTable Get Return CType(ViewState("DtPedidos2"), DataTable) End Get Set(value As DataTable) ViewState("DtPedidos2") = value End Set End Property Private Property DtPedidos2PS As DataTable Get Return CType(ViewState("DtPedidos2PS"), DataTable) End Get Set(value As DataTable) ViewState("DtPedidos2PS") = value End Set End Property Private Property CveEstatus As Integer Get Return ViewState("CveEstatus").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveEstatus") = value End Set End Property Private Property CveEstatusCotizacion As Integer Get Return (IfNull(ViewState("CveEstatusCotizacion"), "-1", ViewState("CveEstatusCotizacion"))).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveEstatusCotizacion") = value End Set End Property Private Property CveMetodoPago33Venta As Integer Get Return (IfNull(ViewState("CveMetodoPago33Venta"), "-1", ViewState("CveMetodoPago33Venta"))).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveMetodoPago33Venta") = value End Set End Property Private Property CveFormaPago33Venta As Integer Get Return (IfNull(ViewState("CveFormaPago33Venta"), "-1", ViewState("CveFormaPago33Venta"))).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveFormaPago33Venta") = value End Set End Property Private Property CveMetodoPago33Cliente As Integer Get Return If(IsNothing(ViewState("CveMetodoPago33Cliente")), -1, ViewState("CveMetodoPago33Cliente")).ToString().ToEntero End Get Set(value As Integer) ViewState("CveMetodoPago33Cliente") = value End Set End Property Private Property CveFormaPago33Cliente As Integer Get Return If(IsNothing(ViewState("CveFormaPago33Cliente")), -1, ViewState("CveFormaPago33Cliente")).ToString().ToEntero End Get Set(value As Integer) ViewState("CveFormaPago33Cliente") = value End Set End Property Private Property CveVendedorVenta As Integer Get Return (IfNull(ViewState("CveVendedorVenta"), "-1", ViewState("CveVendedorVenta"))).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveVendedorVenta") = value End Set End Property Private Property CveVendedorCliente As Integer Get Return If(IsNothing(ViewState("CveVendedorCliente")), -1, ViewState("CveVendedorCliente")).ToString().ToEntero End Get Set(value As Integer) ViewState("CveVendedorCliente") = value End Set End Property Private Property CveVendedorClienteSucursal As Integer Get Return If(IsNothing(ViewState("CveVendedorClienteSucursal")), -1, ViewState("CveVendedorClienteSucursal")).ToString().ToEntero End Get Set(value As Integer) ViewState("CveVendedorClienteSucursal") = value End Set End Property Private Property CveVendedorContrato As Integer Get Return If(IsNothing(ViewState("CveVendedorContrato")), -1, ViewState("CveVendedorContrato")).ToString().ToEntero End Get Set(value As Integer) ViewState("CveVendedorContrato") = value End Set End Property Private Property CveVendedorEmpresaCRM As Integer Get Return If(IsNothing(ViewState("CveVendedorEmpresaCRM")), -1, ViewState("CveVendedorEmpresaCRM")).ToString().ToEntero End Get Set(value As Integer) ViewState("CveVendedorEmpresaCRM") = value End Set End Property Private Property DiasCredito As Integer Get Return ViewState("DiasCredito").ToString().ToEntero() End Get Set(value As Integer) ViewState("DiasCredito") = value End Set End Property Private Property EsDiasCreditoFijo As Boolean Get Return CBool(ViewState("EsDiasCreditoFijo").ToString()) End Get Set(value As Boolean) ViewState("EsDiasCreditoFijo") = value End Set End Property Private Property TieneDiasVencidos As Boolean Get Return CBool(IfNull(ViewState("TieneDiasVencidos"), "False", ViewState("TieneDiasVencidos"))) End Get Set(value As Boolean) ViewState("TieneDiasVencidos") = value End Set End Property Private Property DiasVencidosCliente As Integer Get Return IfNull(ViewState("DiasVencidosCliente"), "0", ViewState("DiasVencidosCliente")).ToString().ToEntero() End Get Set(value As Integer) ViewState("DiasVencidosCliente") = value End Set End Property Private Property SeCancelaRemisionProceso As Boolean Get Return CBool(ViewState("SeCancelaRemisionProceso").ToString()) End Get Set(value As Boolean) ViewState("SeCancelaRemisionProceso") = value End Set End Property Private Property CvePrecioLista As Integer Get Return IfNull(ViewState("CvePrecioLista"), 0, ViewState("CvePrecioLista").ToString().ToEntero()).ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePrecioLista") = value End Set End Property Private Property CvePrecioListaCliente As Integer Get Return IfNull(ViewState("CvePrecioListaCliente"), 0, ViewState("CvePrecioListaCliente").ToString().ToEntero()).ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePrecioListaCliente") = value End Set End Property Private Property FacturarSucursal As Boolean Get Return CBool(IfNull(ViewState("FacturarSucursal"), "False", ViewState("FacturarSucursal"))) End Get Set(value As Boolean) ViewState("FacturarSucursal") = value End Set End Property Private Property ClienteSucursal As Modelos.SucursalModel Get Return CType(ViewState("ClienteSucursal"), Modelos.SucursalModel) End Get Set(value As Modelos.SucursalModel) ViewState("ClienteSucursal") = value End Set End Property Private Property VentaDesglosaIEPS As Boolean Get Return CBool(IfNull(ViewState("VentaDesglosaIEPS"), "False", ViewState("VentaDesglosaIEPS"))) End Get Set(value As Boolean) ViewState("VentaDesglosaIEPS") = value End Set End Property Private Property VentaNODesglosaIVA As Boolean Get Return CBool(IfNull(ViewState("VentaNODesglosaIVA"), "False", ViewState("VentaNODesglosaIVA"))) End Get Set(value As Boolean) ViewState("VentaNODesglosaIVA") = value End Set End Property Private Property SerieVenta As String Get Return IfNull(ViewState("SerieVenta"), "", ViewState("SerieVenta")).ToString() End Get Set(value As String) ViewState("SerieVenta") = value End Set End Property Private Property AplicaDocumentoNuevoNC As Boolean Get Return CBool(IfNull(ViewState("AplicaDocumentoNuevoNC"), "False", ViewState("AplicaDocumentoNuevoNC"))) End Get Set(value As Boolean) ViewState("AplicaDocumentoNuevoNC") = value End Set End Property Private Property AplicaRNCXDetalle As Boolean Get Return CBool(IfNull(ViewState("AplicaRNCXDetalle"), "False", ViewState("AplicaRNCXDetalle"))) End Get Set(value As Boolean) ViewState("AplicaRNCXDetalle") = value End Set End Property Private Property AplicaRNCBonificacionXDetalle As Boolean Get Return CBool(IfNull(ViewState("AplicaRNCBonificacionXDetalle"), "False", ViewState("AplicaRNCBonificacionXDetalle"))) End Get Set(value As Boolean) ViewState("AplicaRNCBonificacionXDetalle") = value End Set End Property Private Property AplicaRelacionManual As Boolean Get Return CBool(IfNull(ViewState("AplicaRelacionManual"), "False", ViewState("AplicaRelacionManual"))) End Get Set(value As Boolean) ViewState("AplicaRelacionManual") = value End Set End Property Private Property TmpDTFacturasRelacionadas As DataTable Get If ViewState("TmpDTFacturasRelacionadas") IsNot Nothing Then Return CType(ViewState("TmpDTFacturasRelacionadas"), DataTable) Else Return Nothing End If End Get Set(value As DataTable) ViewState("TmpDTFacturasRelacionadas") = value End Set End Property Private Property CveAutorizacion As Integer Get Return (IfNull(ViewState("CveAutorizacion"), "-1", ViewState("CveAutorizacion"))).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveAutorizacion") = value End Set End Property Private Property EsGarantia As Boolean Get Return CBool(IfNull(ViewState("EsGarantia"), False, ViewState("EsGarantia"))) End Get Set(value As Boolean) ViewState("EsGarantia") = value End Set End Property Private Property TipoCambioOriginal As Decimal Get Return (IfNull(ViewState("TipoCambioOriginal"), 0, ViewState("TipoCambioOriginal"))).ToString().ToDecimal() End Get Set(value As Decimal) ViewState("TipoCambioOriginal") = value End Set End Property Private Property DtMercancias As DataTable Get Return If(IsNothing(ViewState("DtMercancias")), Nothing, CType(ViewState("DtMercancias"), DataTable)) End Get Set(value As DataTable) ViewState("DtMercancias") = value End Set End Property Private Property ClienteCodigoRegimenFiscal As String Get If ViewState("ClienteCodigoRegimenFiscal") Is Nothing Then ViewState("ClienteCodigoRegimenFiscal") = "" End If Return ViewState("ClienteCodigoRegimenFiscal").ToString End Get Set(value As String) ViewState("ClienteCodigoRegimenFiscal") = value End Set End Property Private Property ClienteRegimenFiscal As String Get If ViewState("ClienteRegimenFiscal") Is Nothing Then ViewState("ClienteRegimenFiscal") = "" End If Return ViewState("ClienteRegimenFiscal").ToString End Get Set(value As String) ViewState("ClienteRegimenFiscal") = value End Set End Property Private Property CveLineaAdicionalVenta As Integer Get Return IfNull(ViewState("CveLineaAdicionalVenta"), "-1", ViewState("CveLineaAdicionalVenta")).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveLineaAdicionalVenta") = value End Set End Property Private Property SaldoLineaAdicional As Decimal Get Return (IfNull(ViewState("SaldoLineaAdicional"), "0", ViewState("SaldoLineaAdicional"))).ToString().ToDecimal() End Get Set(value As Decimal) ViewState("SaldoLineaAdicional") = value End Set End Property Private Property SaldoIngresosLineaAdicional As Decimal Get Return (IfNull(ViewState("SaldoIngresosLineaAdicional"), "0", ViewState("SaldoIngresosLineaAdicional"))).ToString().ToDecimal() End Get Set(value As Decimal) ViewState("SaldoIngresosLineaAdicional") = value End Set End Property Private Property CveCategoriaLineaAdicional As Integer Get Return IfNull(ViewState("CveCategoriaLineaAdicional"), "-1", ViewState("CveCategoriaLineaAdicional")).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveCategoriaLineaAdicional") = value End Set End Property Private Property CveMonedaLineaAdicional As Integer Get Return IfNull(ViewState("CveMonedaLineaAdicional"), "-1", ViewState("CveMonedaLineaAdicional")).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveMonedaLineaAdicional") = value End Set End Property Private Property HabilitoFacturacionIngresoLineaAdicional As Boolean Get Return If(IsNothing(ViewState("HabilitoFacturacionIngresoLineaAdicional")), False, CType(ViewState("HabilitoFacturacionIngresoLineaAdicional"), Boolean)) End Get Set(value As Boolean) ViewState("HabilitoFacturacionIngresoLineaAdicional") = value End Set End Property Private Property CveContratoTipo As Integer Get Return IfNull(ViewState("CveContratoTipo"), "-1", ViewState("CveContratoTipo")).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveContratoTipo") = value End Set End Property Private Property HabilitaRemisionPublicoGeneral As Integer Get Return IfNull(ViewState("HabilitaRemisionPublicoGeneral"), "0", ViewState("HabilitaRemisionPublicoGeneral")).ToString().ToEntero() End Get Set(value As Integer) ViewState("HabilitaRemisionPublicoGeneral") = value End Set End Property Private Property TieneBloqueoPorAutorizacion As Integer Get Return IfNull(ViewState("TieneBloqueoPorAutorizacion"), "0", ViewState("TieneBloqueoPorAutorizacion")).ToString().ToEntero() End Get Set(value As Integer) ViewState("TieneBloqueoPorAutorizacion") = value End Set End Property Public Property IndicePSActual As Integer Get Return IfNull(ViewState("IndicePSActual"), "-1", ViewState("IndicePSActual")).ToString().ToEntero() End Get Set(value As Integer) ViewState("IndicePSActual") = value End Set End Property Public Property CantidadOriginal As Decimal Get Return IfNull(ViewState("CantidadOriginal"), "-1", ViewState("CantidadOriginal")).ToString().ToDecimal() End Get Set(value As Decimal) ViewState("CantidadOriginal") = 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 Modalidad = "" Opcion = "" Index = 0 TotAnt = 0 'CargoComercioExterior = False ' DdlBPPS.setEsWebService(True) 'DdlBPPS.ddlWS.Attributes.Add("data-clear", "1") ViewState("ProcesoCorrecto") = True ViewState("CargoUsado") = True ViewState("NuevaFactura") = -1 ViewState("CveDevolucion") = -1 ViewState("CvePedido") = -1 ViewState("CvePedido2") = -1 ViewState("TipoContrato") = -1 ViewState("CveVenta") = -1 ViewState("CveCliente") = -1 ViewState("CveClienteAnterior") = -1 ViewState("CveOS") = -1 ViewState("CveOC") = -1 ViewState("CveAnticipo") = -1 ViewState("CveFactura") = -1 ViewState("CveCicloComercial") = -1 ViewState("Entrega") = "" ViewState("Vigencia") = "" ViewState("AplicarVentaFacturada") = False ViewState("SeGuardoPrePoliza") = False ViewState("TipoDoctoDevolucion") = "" ViewState("EditoRemision") = False ViewState("RequiereOC") = False ViewState("ClienteDesglosaIEPS") = False ViewState("ClienteNODesglosaIVA") = False ViewState("ClienteRetIVA") = 0 ViewState("ClienteRetISR") = 0 ViewState("CvePrecioLista") = 0 ViewState("CvePrecioListaCliente") = 0 HdnCargarInventario.Value = "True" Me.CveVendedorVenta = -1 Me.CveVendedorCliente = -1 Me.CveVendedorClienteSucursal = -1 Me.CveVendedorContrato = -1 Me.CveVendedorEmpresaCRM = -1 Me.EsGarantia = False CveEmpresaCRM = 0 CveAcercamientoCRM = 0 EstatusCliente = False RemisionesLista = New List(Of Integer) Pedidos2Lista = New List(Of Integer) CotizacionesLista = New List(Of Integer) ListaDescuentos = New List(Of Modelos.VentaDescuentos) CuentasContablesInvalidas = New StringBuilder CvePrePoliza = 0 TotalOtrosConceptos = 0 CveUsuarioActual = UsuarioActual.CveUsuario EmpresaActual = UsuarioActual.Empresa IdPoliza = 0 CveCorte = -1 CveContrato = -1 DevolucionAlmacen = 0 CvePSAmortizacion = 0 EraCotizacion = 0 FacturaMateriales = 0 CvePedidoA = 0 EsCreaApartirDe = False RequiereAlmacenDestino = False RequiereAlmacenOrigen = False TmpDTComplementos = New DataTable DtRemConceptosSurtidos = Nothing TipoVentaSucursal = 0 PlazoCobranza = 0 PlazoCobranzaRemision = 0 TipoCambioFactura = 1 NumeroContrato = "" DescripcionContrato = "" NumeroLicitacion = "" ImprimeNombreSucursal = False RegistraScript("SetDisabledTxtTotal(true);") TrVistaPrevia.Visible = False 'CveMetodoPagoCliente = 1 CveAlmacenExistenciasContrato = -1 UpFacturar.Update() 'CargaTiposDocumentos() TrEmitir.Visible = False ViewState("EstablecioFolio") = False 'ViewState("SubProyectoPorcentajeIVA") = 0 RefacturacionGeneroNC = False ModalidadEdicion = False ConversionRemision = "" TipoCambioRemision = 1 CveOrdenCompraContrato = -1 TieneContrato = False AplicaNC = False TieneAlmacen = False CveEstatus = -1 PorcentajeIVA = 0 EsDiasCreditoFijo = False DiasCredito = 0 AplicaCancelarRemision = False SeCancelaRemisionProceso = False TotalOriginal = 0 CveAlmacenDevolucion = 0 Me.CveEstadoCancelacion = 0 'TxtFechaOS.Text = NowADS().ToDateTime.ToString("yyyy-MM-dd HH:mm:ss").Replace(" ", "T") If UsuarioActual.TienePermisoProceso(177) Then DdlTipoComprobante.Items.Insert(4, New ListItem("Pedido de Contrato", "Ped")) End If If Not UsuarioActual.Empresa.Funcionalidad(558) = "1" Then LnkAgregarCliente.Visible = False End If DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Pedido", "Pd2")) If UsuarioActual.Empresa.Funcionalidad(344).ToString() = "1" Then DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("NC de Remisión", "RNC")) End If SetValues() CvePresupuesto = 0 'MODALIDADES If Request("Op") IsNot Nothing AndAlso Request("Op").ToString() <> "" Then Opcion = Request("Op").ToString() LblTitulo.Text = "Registro de Cotizaciones" TrTipo.Visible = False divcondicionespago.Visible = UsuarioActual.Empresa.CvePlataforma = 1 'SI ES PLATAFORMA ERP SIEMPRE VSIBLE ESTE PORLET ImgAntiPend.Visible = False TrOC.Visible = False DdlTipoComprobante.SelectedValue = "Op" Else Opcion = "Ing" DdlTipoComprobante.SelectedValue = "Ing" End If LblUsuario.Text = UsuarioActual.Usuario LblFechaRegistro.Text = NowADS().ToShortDateString() ImgDescTotal.Visible = False ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") ImgAntiPend.Attributes.Add("onclick", "$get('HdnTipoDescuento').value = '3'; MuestraAnticipos();") ImgOtrosConceptos.Attributes.Add("onclick", "javascript:$('#ModalOtrosConceptos').modal();") CreaDTmpC() CreaDTmpF() CreaDTDocumentosRelacionados() CargaDdlSubProyectos() 'CargaProyecto() 'CargaSucursales() CargaClasificaciones() CargaPS(-1, DdlPS) CreaDTVentas() CargaMetodosPago() CargaUsoCFDI() CargaMonedas() CargaAgentes() CargaProcedimientos() CargaTiposVenta() CargaDdlClientes() 'SI USUARIO USA AMORTIZACIÓN CONTABLE, se carga las tablas para usarlas mas adelante If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) DdlTipoComprobante.Items.Add(New ListItem("Compromisos", "Com")) DdlTipoComprobante.Items.Add(New ListItem("Orden Pago", "OP")) Dim AC As New ClsAC If AC.GetPresupuestoIngresos(-1, NowADS().Year, True, UsuarioActual.CveEmpresa) Then DdlFuenteRecaudacion.DataSource = AC.DtResultados() DTPresupuestoIngresos = AC.DtResultados() ViewState("DTFuenteRecaudacion") = AC.DtResultados() 'GenerarPolizasAC() End If AC.Dispose() 'columna de Fuente de recaudacion GvPS.Columns(21).Visible = True 'nomostrar.Visible = True 'nomostrar2.Visible = True 'GvPS.Width = 1250 DdlFuenteRecaudacion.DataBind() Else TFuenteRecaudacion.Visible = False End If 'Carga cliente If Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero() > 0 AndAlso Request("CveFactura") Is Nothing Then ViewState("CveCliente") = Request("CveCliente") HdnCveCliente.Value = Request("CveCliente") CargaCliente(CveCliente) Else ViewState("CveCliente") = -1 HdnCveCliente.Value = "-1" End If 'Carga empresa CRM If Request("CveEmpresaCRM") IsNot Nothing AndAlso IsNumeric(Request("CveEmpresaCRM")) AndAlso Request("CveEmpresaCRM").ToEntero() > 0 Then ViewState("CveEmpresaCRM") = Request("CveEmpresaCRM") CargaEmpresaCRM(CveEmpresaCRM) Else ViewState("CveEmpresaCRM") = -1 End If If Request("CveAcercamientoCRM") IsNot Nothing AndAlso IsNumeric(Request("CveAcercamientoCRM")) AndAlso Request("CveAcercamientoCRM").ToEntero() > 0 Then ViewState("CveAcercamientoCRM") = Request("CveAcercamientoCRM") Dim cRMService As ICRMService = New CRMService(System.Configuration.ConfigurationManager.ConnectionStrings("Conexion").ConnectionString) Dim AcercamientoModel As New RequestAcercamiento(UsuarioActual.CveEmpresa, CveAcercamientoCRM) Dim objAcercamiento = cRMService.GetAceracamientoCRM(AcercamientoModel) If objAcercamiento.Result.Count > 0 Then CorreoContactoCRM = objAcercamiento.Result(0).CorreoContacto End If Else ViewState("CveAcercamientoCRM") = -1 End If 'mensaje de confirmación al guardar BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)},0);" BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") BtnEmitirImprimir.Attributes.Add("data-popout", "true") BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") BtnEmitirImprimir.Attributes.Add("data-html", "true") If UsuarioActual.CveEmpresa.Contiene(126) Then ' cuando la empresa se relaciona a ua orden de producción, Citrus Game TrOP.Visible = True CargaOrdenProduccion() End If If Request("CveOrdenProduccion") IsNot Nothing AndAlso IsNumeric(Request("CveOrdenProduccion")) AndAlso Request("CveOrdenProduccion").ToEntero() > 0 Then DdlSubProyectoDatos.SelectedValueExist(11954) Using ObjVentas As New ClsNominas If ObjVentas.ManifiestoForVtaGet(UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario, "", -Request("CveOrdenProduccion").ToEntero()) Then TmpDT = ObjVentas.DtResultados TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) TmpDT.Columns.Add("CveVentaDetalleRNC", GetType(Integer)) TmpDT.Columns.Add("TieneProntoPago", GetType(String)) TmpDT.Columns.Add("ImporteProntoPago", GetType(Decimal)) TmpDT.Columns.Add("CveMarca", GetType(Integer)) TmpDT.Columns.Add("CvePrecioLista", GetType(Integer)) TmpDT.Columns.Add("PrecioLista", GetType(String)) TmpDT.Columns.Add("CveActivoFijo", GetType(Integer)) TmpDT.Columns.Add("AFDepreciacion", GetType(Decimal)) TmpDT.Columns.Add("AFValorInicial", GetType(Decimal)) TmpDT.Columns.Add("NumTurnos", GetType(Decimal)) TmpDT.Columns("NumTurnos").DefaultValue = 0D TmpDT.Columns.Add("NumeroPedimento", GetType(String)) GvPS.DataSource = ObjVentas.DtResultados GvPS.DataBind() 'IEPS A NIVEL DETALLE 'TxtIEPS.Text = If(TmpDT.SUM("IEPS") > 0, TmpDT.SUM("IEPS").FormatoNumero, TxtIEPS.Text) End If End Using End If If Request("CveEmbarqueManifiesto") IsNot Nothing AndAlso IsNumeric(Request("CveEmbarqueManifiesto")) AndAlso Request("CveEmbarqueManifiesto").ToEntero() > 0 Then DdlMoneda.SelectedValueExist(2) CambiaMoneda() Using ObjVentas As New ClsNominas If ObjVentas.EmbarqueManifiestoGet(-1, -1, -1, Request("CveEmbarqueManifiesto").ToString().ToEntero()) And ObjVentas.DtResultados.Rows.Count > 0 Then DdlSubProyectoDatos.SelectedValueExist(ObjVentas.DtResultados.Rows(0)("CveSubProyecto").ToString()) End If If ObjVentas.ManifiestoForVtaGet(UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario, "", Request("CveEmbarqueManifiesto").ToEntero()) Then TmpDT = ObjVentas.DtResultados TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) TmpDT.Columns.Add("CveVentaDetalleRNC", GetType(Integer)) TmpDT.Columns.Add("TieneProntoPago", GetType(String)) TmpDT.Columns.Add("ImporteProntoPago", GetType(Decimal)) TmpDT.Columns.Add("CveMarca", GetType(Integer)) TmpDT.Columns.Add("CvePrecioLista", GetType(Integer)) TmpDT.Columns.Add("PrecioLista", GetType(String)) TmpDT.Columns.Add("CveActivoFijo", GetType(Integer)) TmpDT.Columns.Add("AFDepreciacion", GetType(Decimal)) TmpDT.Columns.Add("AFValorInicial", GetType(Decimal)) TmpDT.Columns.Add("NumTurnos", GetType(Decimal)) TmpDT.Columns("NumTurnos").DefaultValue = 0D TmpDT.Columns.Add("NumeroPedimento", GetType(String)) GvPS.DataSource = ObjVentas.DtResultados GvPS.DataBind() 'IEPS A NIVEL DETALLE 'TxtIEPS.Text = If(TmpDT.SUM("IEPS") > 0, TmpDT.SUM("IEPS").FormatoNumero, TxtIEPS.Text) End If End Using End If 'SI ES VENTA NUEVA, NO RECARGAR TAB DE ALMACEN If CveVenta <= 0 Then 'REMOVER EVENTO PARA RECARGAR ALMACEN HdnCargarInventario.Value = "False" 'spanAlmacen.Attributes.Remove("onclick") UpParametros.Update() End If CargaEstatusFactura(Opcion) If Opcion = "Ing" Then 'DdlEstatus.Enabled = False If UsuarioActual.Empresa.TipoFacturacion = "CBB" Then 'DdlEstatus.SelectedValue = "3" CveEstatus = 3 ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then 'DdlEstatus.SelectedValue = "2" CveEstatus = 2 End If End If 'CARGA PARA FACTURAR ViewState("CveRemision") = IfNull(Request("CveRemision").ToEntero(), 0) ViewState("CveCotizacion") = IfNull(Request("CveCotizacion").ToEntero(), 0) 'If ViewState("CveCotizacion").ToString().ToEntero() > 0 Then ' EsCreaApartirDe = True 'End If If ViewState("CveRemision").ToString().ToEntero() > 0 Or ViewState("CveCotizacion").ToString().ToEntero() > 0 Then ImgAddObs.Visible = True CargaEventoBitacora() DdlTipoComprobante.Enabled = False DdlTipoComprobante.SelectedValue = "Ing" CargaEstatusFactura() 'DdlEstatus.SelectedValueExist("2") ConfiguraTipoDocto() BtnEmitirImprimir.Text = "Facturar" BtnEmitirImprimir.Visible = True UpnTools.Update() End If If Not ExFolioFactura Then SetPermisos() If CveVenta < 1 Then CargaFolios() If CveVenta <= 0 AndAlso UsuarioActual.CveEmpresa.Contiene(7, 122) Then TxtCantidad.Width = New Unit("100%") End If InicializaImprimirNew() 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()") CargaFormatoSucursal() 'SELECCIONA SUCURSAL DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE If Not (CveCliente > 0 Or CveVenta > 0) Then DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto) If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.Enabled = False End If CambiaSucursal() UpParametros.Update() End If 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE EnviarCorreoCliente = True If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then EnviarCorreoCliente = False End If 'MOSTRAR LA OPCION DE AGREGAR PS EN BDH If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso CveVenta <= 0 Then ImgOtrosConceptos.Visible = False GvPS.Columns(8).Visible = False For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = False Next End If If UsuarioActual.Empresa.CvePlataforma = 2 Then ImgOtrosConceptos.Visible = False GvPS.Columns(8).Visible = False For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = False Gvr.FCLinkButton("imgEPyME").Visible = True Next End If If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero() = -1 AndAlso UsuarioActual.CveTipoDocumento.Length = 3 Then CargaDdlSubProyectos() UpParametros.Update() DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento) CambiaTipoDocto() End If If Not CveVenta > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(403).ToString() = "1" Then If (DdlTipoComprobante.Items.FindByValue("Ing") IsNot Nothing) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) End If End If LtlTareaNueva.Text = String.Format(" Tarea", CveVenta) 'SI ESTA CARGANDO UNA REFACTURACION. VALIDAR QUE LA FACTURA ANTERIOR ESTE CANCELADA If Me.ObjFacturaNC IsNot Nothing Then If Me.CveDevolucion > 0 AndAlso Me.NuevaFactura = 1 Then Dim TipoEstatus As Integer = GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.ObjFacturaNC.CveEstatusFactura}").ToEntero() If TipoEstatus <> 5 Then 'ESTATUS DE CANCELACION PENDIENTE If Not Me.ObjFacturaNC.CveEstatusFactura = 23 Then Alert($"El documento de tipo '{Me.ObjFacturaNC.TipodeComprobante}' a refacturar no ha sido cancelado. Favor de verificar el documento", TipoMensaje.MsgAdvertencia) BtnEmitirImprimir.Visible = False UpFacturar.Update() End If End If End If End If 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO If Not CveVenta > 0 AndAlso Not BtnEmitirImprimir.Visible AndAlso Request("Op") IsNot Nothing AndAlso Request("Op").ToString() <> "" Then If DdlTipoComprobante.SelectedValue.Contiene("Cot") Then BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True End If End If If Request("CveCotizacion") IsNot Nothing AndAlso IfNull(Request("CveCotizacion"), 0).ToString().ToEntero() > 0 Then If UsuarioActual.Empresa.Funcionalidad(135).Contiene("1", "2") Then 'VERIFICA SI NO ESTA AUTORIZADA If CveEstatusCotizacion <> 8 Then BtnEmitirImprimir.Enabled = False BtnEmitirImprimir.Visible = False Alert("La cotización no esta autorizada", TipoMensaje.MsgAdvertencia) End If End If End If If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then ' IPP 15 Julio 2017 - ERA FALSE ImgAntiPend.Visible = False UpPS.Update() End If BloqueaCondiconesPago() End If End Sub Private Sub CargaDdlClientes() If UsuarioActual.Empresa.Funcionalidad(105) = "1" Then DdlClientesWS.setEsWebService(True) Else DdlClientesWS.setEsWebService(False) If Not UsuarioActual.Empresa.Funcionalidad(105) = "1" Then DdlClientesWS.ddl.Items.Clear() DdlClientesWS.DataSource = GlobalDTCliente(UsuarioActual.CveEmpresa, -1) DdlClientesWS.DataBind() DdlClientesWS.ddl.Items.Insert(0, New ListItem("Todos", "-1")) End If End If End Sub Private Sub BloqueaClasificaciones() If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then DdlClasificacion.Enabled = False DdlUnidadMedida.Enabled = False End If End Sub Private Sub BloqueaCondiconesPago() If UsuarioActual.TienePermisoProceso(289) Then DdlUsoCFDI.Enabled = False DdlMetodoPago33.Enabled = False DdlFormaPago33.Enabled = False DdlTiposRelacion.Enabled = False End If UPCondicionesPago.Update() End Sub Private Sub ConfiguraEmpresa() Select Case UsuarioActual.CveEmpresa Case 119 TxtObsPS.Attributes.Add("onkeypress", "setFocus(event,'TxtPrecio');") End Select End Sub #Region "C A R G A S" Private Sub CargaOrdenProduccion(Optional Opcion As Integer = 1, Optional CveVenta As Integer = -1) DdlOrdenProduccion.Items.Clear() Dim CveOrdenProduccion As String = "-1" Dim ObjCGame As New ClsCGame If ObjCGame.GetOrdenProduccion(-1, UsuarioActual.CveEmpresa, -1, "-1", MinFecha, MaxFecha, -1) Then If Opcion = 1 Then DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros(String.Format("CveVenta IS NULL ")) ElseIf Opcion = 2 Then LnkActualizarOrdenProduccion.Visible = True DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta} OR CveVenta IS NULL") If ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows.Count > 0 Then CveOrdenProduccion = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows(0)("CveOrdenProduccion").ToString() End If End If DdlOrdenProduccion.Items.Insert(0, New ListItem("Seleccione", "-1")) End If ObjCGame.Dispose() DdlOrdenProduccion.DataBind() DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion) End Sub Private Sub CargaEstatusFactura(Optional TipoDocto As String = "Ing") Dim FiltroCompromiso As String = If(TipoDocto = "Com", "And CveEstatusFactura In (2, 9)", "And CveEstatusFactura Not In (9)") If TipoDocto.ToUpper.Contiene("EGS", "COM", "ANT") Then TipoDocto = "Ing" End Sub Private Sub CargaOS(CveOS As Integer) Dim OS As New ClsOS Dim DtDetalle As DataTable = Nothing Dim DtDetalleMateriales As DataTable = Nothing If OS.GetOrdenesServicios(CveOS, -1, -1, -1, -1, UsuarioActual.CveEmpresa) Then HdnCveCliente.Value = OS.CveCliente.ToString() ViewState("CveCliente") = OS.CveCliente CargaCliente(CveCliente) If OS.GetOrdenesServiciosDetalleAFacturar(CveOS) Then Dim Cons As Integer = 1 For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows AgregarProductoServicio(dr("Cantidad").ToString().ToDecimal, dr("CveUM").ToString().ToEntero(), dr("UM").ToString(), -1, "", dr("CvePS").ToString().ToEntero(), "", dr("Obs").ToString(), dr("PU").ToString().ToDecimal, 0, -1, "", dr("CveSubProyecto").ToString().ToEntero(), dr("SubProyecto").ToString()) 'Dim drt As DataRow = TmpDT.NewRow 'drt("Consec") = Cons 'drt("CvePS") = dr("CvePS") 'drt("CveClasificacion") = dr("CveClasificacion") 'drt("Clasificacion") = dr("Clasificacion") 'drt("PS") = dr("PS") 'drt("CveOSDetalle") = dr("CveOSDetalle") 'drt("CodigoPS") = dr("CodigoPS") 'drt("Cantidad") = dr("Cantidad") 'drt("CveSubProyecto") = dr("CveSubProyecto") 'drt("SubProyecto") = dr("SubProyecto") 'drt("Obs") = dr("Obs") 'TmpDT.Rows.Add(drt) 'Cons = Cons + 1 Next TmpDT.AcceptChanges() DtDetalle = OS.DtResultados.FiltraParametros("SeFacturara = 1 ") End If For Each Row As DataRow In DtDetalle.Rows If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString().ToEntero(), CveOS) Then If OS.DtResultados.FiltraParametros("SeFacturara = 1").Rows.Count > 0 Then Alert("Hay materiales en la Orden de Servicio, ¿Desea facturar los materiales?", TipoMensaje.MsgConfirmacion, "BtnMateriales()") End If End If Next OS.Dispose() CalculaTotalesVenta(False) GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") UpPS.Update() End If End Sub Private Sub CargaTiposDocumentos() DdlTipoComprobante.DataSource = GlobalDTTiposDocumentos() DdlTipoComprobante.DataBind() End Sub Private Sub CargaNuevaFactura(OVenta As ClsVentas) Dim ObjVentas As ClsVentas If OVenta IsNot Nothing Then ObjVentas = OVenta Else ObjVentas = New ClsVentas() End If If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa, VerificaAlmacen:=False) Then If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) 'CargaCliente Dim CveCliente As Integer = drv("CveCliente").ToString().ToEntero() HdnCveCliente.Value = CveCliente.ToString() ViewState("CveCliente") = CveCliente CargaCliente(CveCliente) DdlSucursalCliente.SelectedValueExist(drv("CveClienteSucursal").ToString()) DdlSubProyectoDatos.SelectedValueExist(drv("CveSubProyecto").ToString()) If CveDevolucion > 0 Then CambiaSucursalGeneral() End If CargaClienteSucursal(drv("CveClienteSucursal").ToString().ToEntero()) 'CargaDetalle If ObjVentas.GetVentaDetalle(CveVenta) Then For Each dr As DataRow In ObjVentas.DtResultados.Rows AgregarProductoServicio(dr("Cantidad").ToString().ToDecimal, dr("CveUM").ToString().ToEntero(), dr("UM").ToString(), dr("CveClasificacion").ToString().ToEntero(), dr("Clasificacion").ToString(), dr("CvePS").ToString().ToEntero(), dr("PS").ToString(), dr("Obs").ToString(), dr("PU").ToString().ToDecimal, dr("Descuento").ToString().ToDecimal, dr("CveProyecto").ToString().ToEntero(), dr("Proyecto").ToString(), dr("CveSubProyecto").ToString().ToEntero(), dr("SubProyecto").ToString(), CveContratoDetalle:=dr("CveContratoDetalle").ToString().ToEntero(), CveVentaDetalleCotizacion:=dr("CveVentaDetalleCotizacion").ToString().ToEntero(), CveVentaDetalle:=dr("CveVentaDetalle").ToString().ToEntero(), RegeneraIEPS:=False, SeActualiza:=True) Next ObjVentas.DtResultados.Columns.Add("TieneProntoPago", GetType(String)) ObjVentas.DtResultados.Columns.Add("ImporteProntoPago", GetType(Decimal)) ObjVentas.DtResultados.Columns("TieneProntoPago").DefaultValue = "No" ObjVentas.DtResultados.Columns("ImporteProntoPago").DefaultValue = 0 GvPS.DataSource = ObjVentas.DtResultados GvPS.DataBind() End If 'CARGA IMPUESTOS LOCALES If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then If ObjVentas.DtResultados.Rows.Count > 0 Then TrOtros.Visible = True TmpDTImpuestos = ObjVentas.DtResultados GvImpuestosLocales2.DataSource = ObjVentas.DtResultados GvImpuestosLocales2.DataBind() If (NuevaFactura = 1) Then GvImpuestosLocales2.Enabled = True Else GvImpuestosLocales2.Enabled = False End If GvImpuestosLocales2.Visible = True End If End If 'Carga Totales ViewState("TipoDoctoDevolucion") = drv("TipoDocto").ToString() TxtSubTotal.Text = drv("SubTotal").ToString().FormatoNumero(2) LblDescuentos.Text = drv("Descuento").ToString().FormatoNumero(2) LblAmortizacion.Text = drv("Amortizacion").ToString().FormatoNumero(2) TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) TxtIVA.Text = drv("IVA").ToString().FormatoNumero(2) TxtRetIVA.Text = drv("RetIVA").ToString().FormatoNumero(2) If TxtRetIVA.Text.ToDecimal() > 0 Then TrRetIVA.Style.Add("display", "") UsuarioActual.Empresa.MostrarRetIVA = True End If TxtRetISR.Text = drv("RetISR").ToString().FormatoNumero(2) TxtTotal.Text = drv("Total").ToString().FormatoNumero(2) TotalOriginal = Math.Round(drv("Total").ToString().ToDouble, 2) HdnVentaSaldo.Value = drv("Total").ToString() TxtObsFact.Text = drv("Observaciones").ToString() DdlMoneda.SelectedValue = drv("CveMoneda").ToString() CambiaMoneda() TxtTipoCambio.Text = drv("TipoCambio").ToString() CvePAC = drv("CvePAC").ToString().ToEntero() DdlUsoCFDI.SelectedValueExist(drv("CveUsoCFDI").ToString()) DdlMetodoPago33.SelectedValueExist(drv("CveMetodoPago33").ToString()) CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) DdlFormaPago33.SelectedValueExist(drv("CveFormaPago33").ToString()) DdlTipoComprobante.SelectedValueExist(drv("TipoDocto").ToString()) DdlTipoComprobante.Enabled = False HdnIVAOriginal.Value = TxtIVA.Text HdnAmortizacion.Value = "0" 'LblAmort.Text.ToDouble.ToString() HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") CveContrato = drv("CveContrato").ToString().ToEntero() Updatetabs.Update() UpPS.Update() End If End If If OVenta Is Nothing Then ObjVentas.Dispose() End If End Sub Private Sub CargaMetodosPago() 'FACTURACION 3.3 DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago DdlMetodoPago33.DataBind() DdlMetodoPago33.SelectedValueExist("3") CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) 'End If End Sub Private Sub CargaFormaPago(CveMetodoPago As Integer) 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.DataSource = dtt DdlFormaPago33.SelectedValue = dtt.FiltroPrimeroValor("CveFormaPago", "") DdlFormaPago33.DataBind() If UsuarioActual.CveRol = 1 AndAlso CveMetodoPago = 1 AndAlso DdlTipoComprobante.SelectedValue = "Cot" AndAlso UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso TbDescuentosAdicionales.Visible Then If TmpDT.SUMD("Descuento") > 0 Then Dim TotalDescuento As Decimal = TmpDT.SUMD("Total", "Descuento > 0") * 0.05D Dim RowDescuentos As DataRow() = TmpDT.Select("Descuento > 0") If RowDescuentos IsNot Nothing Then LblDescuentoAdicional.Text = TotalDescuento.FormatoNumero(2) CalculaTotalesVenta() End If Else LblDescuentoAdicional.Text = "0.00" End If UpPS.Update() End If 'End If End Sub Private Sub CargaUsoCFDI() DdlUsoCFDI.Items.Clear() 'DdlSucursalUsoCFDI.Items.Clear() Dim EsPersonaMoral As Boolean = (TipoPersona = True) DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(If(Not EsPersonaMoral, 1, 0), RegimenFiscalReceptor:=RegimenFiscalCliente) 'DdlSucursalUsoCFDI.DataSource = GlobalDTSATUsosCFDI(If(Not EsPersonaMoral, 1, 0), RegimenFiscalReceptor:=RegimenFiscalCliente) DdlUsoCFDI.DataBind() 'DdlSucursalUsoCFDI.DataBind() If Not UsuarioActual.CveEmpresa.Contiene(76, 15) Then If DdlUsoCFDI.DataSource IsNot Nothing Then If DdlUsoCFDI.Items.FindByValue("25") IsNot Nothing Then DdlUsoCFDI.Items.Remove(DdlUsoCFDI.Items.FindByValue("25")) End If End If End If DdlUsoCFDI.Items.Insert(0, New ListItem("Seleccione", "-1")) ' DdlSucursalUsoCFDI.Items.Insert(0, New ListItem("Seleccione", "-1")) End Sub Private Sub CargaMonedas() DdlMoneda.DataSource = GlobalDTMonedas DdlMoneda.DataBind() End Sub 'Private Sub CargaProyecto() ' Dim CveSubProyecto As Integer = 0 ' Dim dtt As DataTable = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) ' DdlProyecto.DataSource = dtt ' DdlProyecto.DataBind() 'CveSubProyecto = GetSubProyectoSucursal() ' CargaSubProyecto(CveSubProyecto) 'End Sub Private Function GetSubProyectoSucursal() As Integer Dim Retorno As Integer = 0 'Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") ''Dim dr As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") ''si hay un proyecto relacionado con el subproyecto 'If dr IsNot Nothing AndAlso dr("CveSubProyecto").ToString().ToEntero() > 0 Then ' DdlProyecto.SelectedValueExist(dr("CveProyecto")) ' Retorno = dr("CveSubProyecto").ToString().ToEntero() 'End If Return Retorno End Function 'Private Sub CargarAlmacenes() ' If UsuarioActual.Empresa.UsaInventarios Then ' If (CveVenta > 0 And DdlTipoComprobante.SelectedValue <> "Cot") AndAlso Not (UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso EsCreaApartirDe) Then ' DivAlmacen.Visible = False ' Else ' Dim DTAlmacen As DataTable ' ddlAlmacen.Items.Clear() ' DTAlmacen = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}") ' ddlAlmacen.DataSource = DTAlmacen ' ddlAlmacen.Items.Insert(0, New ListItem("Seleccione ", "-1")) ' ddlAlmacen.SelectedValueExist("-1") ' ddlAlmacen.DataBind() ' If GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}").Rows.Count > 0 Then ' 'SI ES DEL MISMO SUB PROYECTO SUGIERE EL ALMACEN ASIGNADO AL USUARIO ' If UsuarioActual.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() Then ' ddlAlmacen.SelectedValueExist(UsuarioActual.CveAlmacen) ' Else ' Dim CveAlmacen As Integer = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}").ToEntero() ' ddlAlmacen.SelectedValueExist(CveAlmacen) ' End If ' 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 ' Else ' ddlAlmacen.DataSource = Nothing ' ddlAlmacen.DataBind() ' End If ' UpINV.Update() 'End Sub Private Sub CargaSubProyecto(Optional CveSubProyecto As Integer = -1, Optional FiltraPorProyecto As Boolean = False) 'DdlSubProyecto.Items.Clear() 'DdlSubProyecto.SelectedValue = Nothing 'If DdlProyecto.SelectedValue.ToEntero() > 0 Then ' DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) ' 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) 'End If 'DdlSubProyecto.DataBind() 'DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) 'If FiltraPorProyecto Then ' DdlSubProyecto.Items.Clear() ' Using ObjSubP As New ClsSubProyectos ' If ObjSubP.GetSubProyectos(UsuarioActual.CveEmpresa) Then ' DdlSubProyecto.DataSource = ObjSubP.DtResultados.FiltraParametros(String.Format("CveProyecto = {0}", DdlProyecto.SelectedValue)) ' End If ' End Using ' DdlSubProyecto.DataBind() ' DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) 'End If 'If CveSubProyecto > 0 Then DdlSubProyecto.SelectedValueExist(CveSubProyecto) End Sub Private Sub CargaEmpresaCRM(CveEmpresaCRM As Integer) Dim ObjCRM As New ClsCRM If ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa, CveEmpresaCRM) Then If ObjCRM.DtResultados.Rows.Count > 0 Then ViewState("CveCliente") = IIf(ObjCRM.DtResultados.Rows(0)("CveCliente").ToString().ToEntero() > 0, ObjCRM.DtResultados.Rows(0)("CveCliente"), -1) HdnCveCliente.Value = CveCliente.ToString() If (CveCliente > 0) Then CargaCliente(CveCliente) 'DESACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto disabled") TxtCodigo.ReadOnly = True UpCliente.Visible = True 'UpEmpresaCRM.Visible = False Else LblEmpresaCRM.Text = ObjCRM.DtResultados.Rows(0)("Empresa").ToString() LblRFCCRM.Text = ObjCRM.DtResultados.Rows(0)("RFC").ToString() LblMedioCaptacionCRM.Text = ObjCRM.DtResultados.Rows(0)("MedioCaptacion").ToString() UPCondicionesPago.Visible = True trNombreCliente.Visible = False trsucursalciente.Visible = False TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False TrOP.Visible = False 'trDireccionEnvio.Visible = False trCRM1.Visible = True trCRM2.Visible = True trCRM3.Visible = True LblTituloPorletCliente.Text = "EMPRESA CRM" End If Me.CveVendedorEmpresaCRM = ObjCRM.DtResultados.Rows(0)("CveVendedorAsignado").ToString().ToEntero() LbAgregar.Enabled = True 'TrAtencionA.Visible = True TrOC.Visible = True End If GvPS.Columns(5).Visible = True End If ObjCRM.Dispose() End Sub Private Sub CargaCliente(CveCliente As Integer, Optional Estatus As Integer = -1) If CveCliente <= 0 Then Exit Sub Dim ObjCliente As New ClsClientes() If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus, TipoCliente:=-1) Then If ObjCliente.DtResultados.Rows.Count > 0 Then TxtCodigo.Text = ObjCliente.Codigo LblCliente.Text = String.Format("{1}", CveCliente, ObjCliente.NombreComercial) ViewState("NombreCliente") = ObjCliente.Nombre ViewState("RequiereOC") = ObjCliente.RequiereOC EnviarCorreoCliente = ObjCliente.EnviarFactura EstatusCliente = ObjCliente.Estatus Me.PermiteCredito = ObjCliente.PermiteCredito LnkAgregarCliente.Visible = False 'ClienteEsDistribuidor = Boolean.Parse(ObjCliente.DtResultados.Rows(0)("EsDistribuidor").ToString()) TieneDiasVencidos = Boolean.Parse(ObjCliente.DtResultados.Rows(0)("TieneDiasVencidos").ToString()) DiasVencidosCliente = ObjCliente.DtResultados.Rows(0)("DiasVencidosCliente").ToString().ToEntero() ClienteCodigoRegimenFiscal = ObjCliente.DtResultados.Rows(0)("CodigoRegimenFiscal").ToString() ClienteRegimenFiscal = ObjCliente.DtResultados.Rows(0)("RegimenFiscal").ToString() If EstatusCliente = False And Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") And (CveVenta <= 0 Or EsCreaApartirDe) Then Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) BtnEmitirImprimir.Visible = EstatusCliente TrVistaPrevia.Visible = EstatusCliente End If If ViewState("CveDevolucion") IsNot Nothing AndAlso ViewState("NuevaFactura") IsNot Nothing Then If (CveDevolucion > 0 AndAlso NuevaFactura = 1) Then BtnEmitirImprimir.Visible = EstatusCliente TrVistaPrevia.Visible = EstatusCliente End If End If 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail) ViewState("MailCC") = ObjCliente.NotificarA CorreoEntregaAlmacen = ObjCliente.DtResultados(0)("CorreoEntregaAlmacen").ToString 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) If UsuarioActual.Empresa.MostrarRetISR AndAlso ObjCliente.RetISR > 0 Then ' TrRetISR.Style.Add("display", "none") TrRetISR.Visible = True Else TrRetISR.Visible = False End If ViewState("ClienteRetIVA") = ObjCliente.RetIVA / 100 ViewState("ClienteRetISR") = ObjCliente.RetISR / 100 If CveVenta <= 0 OrElse EsCreaApartirDe Then DdlTipoRetencion.SelectedValueExist(ObjCliente.DtResultados(0)("CveTipoRetencion").ToString()) DdlTipoRetencion_SelectedIndexChanged(DdlTipoRetencion, EventArgs.Empty) ViewState("RetIVAFletes") = ObjCliente.RetieneIVAFletes If ObjCliente.RetieneIVAFletes Then TrRetIVA.Style.Add("display", "") UsuarioActual.Empresa.MostrarRetIVA = True End If End If ViewState("Vendedor") = ObjCliente.Vendedor ViewState("CodCliente") = ObjCliente.Codigo ViewState("CvePrecioLista") = ObjCliente.CvePrecioLista ViewState("CvePrecioListaCliente") = ObjCliente.CvePrecioLista ViewState("CliNoExt") = ObjCliente.NoExt ViewState("CliNoInt") = ObjCliente.NoInt ViewState("CliLocalidad") = If(ObjCliente.Localidad.Trim.Length = 0, ObjCliente.Ciudad.Trim, ObjCliente.Localidad.Trim) ViewState("CliPais") = ObjCliente.Pais ImprimeNombreSucursal = ObjCliente.ImprimeNombreSucursal RegimenFiscalCliente = ObjCliente.DtResultados(0)("CodigoRegimenFiscal").ToString() RegimenSociedad = ObjCliente.DtResultados(0)("RegimenSociedad").ToString() TipoPersona = CBool(ObjCliente.DtResultados(0)("TipoPersona")) CargaUsoCFDI() 'ViewState("NumCtaPago") = ObjCliente.NumCtaPago ViewState("ClienteDesglosaIEPS") = ObjCliente.DesglosaIEPS ViewState("CargoUsado") = ObjCliente.CargoUsados Dim dr As DataRow = Nothing dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal = 1 And Estatus = 'Activo' AND CveEmpresa = " & UsuarioActual.CveEmpresa) If dr IsNot Nothing Then ViewState("MatCalle") = dr("Calle") ViewState("MatNoExt") = dr("NoExt") ViewState("MatNoInt") = dr("NoInt") ViewState("MatColonia") = dr("Colonia") ViewState("MatLocalidad") = dr("Localidad") ViewState("MatMunicipio") = dr("Municipio") ViewState("MatEstado") = dr("Estado") ViewState("MatPais") = dr("Pais") ViewState("MatCP") = dr("CP") End If If CveCliente = 239903 AndAlso UsuarioActual.CveEmpresa = 119 Then DdlMetodoPago33.Enabled = False 'ObjCliente.CveMetodoPago = 1 ' PUE, y que no se pueda modificar Else DdlMetodoPago33.Enabled = True End If Dim CveCotizacion As Integer = IfNull(ViewState("CveCotizacion"), 0).ToString().ToEntero() Me.CveMetodoPago33Cliente = ObjCliente.CveMetodoPago33 Me.CveFormaPago33Cliente = ObjCliente.CveFormaPago33 If (CveVenta <= 0 AndAlso CveCotizacion <= 0) Or EsCreaApartirDe Or NuevaFactura = 1 OrElse ModalidadEdicion Then DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33) CambiaMetodoPago33() DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI) 'SI ES RFC GENERICO NO TIENE OBLIGACIONES FISCALES If LblRFC.Text.Contiene("XAXX010101000", "XEXX010101000") Then 'S01 Sin efectos fiscales. DdlUsoCFDI.SelectedValueExist("23") DdlUsoCFDI.Enabled = False RegimenFiscalCliente = "616" ClienteCodigoRegimenFiscal = "616" End If End If PlazoCobranza = ObjCliente.PlazoCobranza PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision 'funcionalidad EnviarSMSTimbrado If CveVenta <= 0 And UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue = "Ing" Then If ObjCliente.CobranzaTelefono <> "" Then LblMensaje.Text = $"Se enviará mensaje SMS a {ObjCliente.CobranzaTelefono}" Else LblMensaje.Text = $"El Cliente no tiene teléfono para envío SMS " End If LblMensaje.Visible = True End If 'If Not ObjCliente.RFC = "XAXX010101000" Then ' TxtNumCtaPago.Text = ObjCliente.NumCtaPago 'End If 'Complementos 'COMERCIO EXTERIOR ViewState("AplicaComercioExterior") = ObjCliente.AplicaComercioExterior ViewState("CveTipoOperacion") = ObjCliente.CveTipoOperacion ViewState("CvePedimento") = ObjCliente.CvePedimento ViewState("CveIncoterm") = ObjCliente.CveIncoterm ViewState("AplicaFEMSA") = ObjCliente.AplicaFEMSA ViewState("AplicaDetallista") = ObjCliente.AplicaDetallista ViewState("AplicaFord") = ObjCliente.AplicaFord If ObjCliente.DtResultados(0)("CveVendedor").ToString().ToEntero() > 0 Then CveVendedorCliente = ObjCliente.DtResultados(0)("CveVendedor").ToString().ToEntero() End If UpFacturar.Update() 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(UsuarioActual.CveSubProyecto) ' DdlSubProyectoDatos.SelectedValueExist(ObjCliente.CveSubProyecto) End If 'RECARGA LOS VALORES DE LA SUCURSAL CambiaSucursal() UpParametros.Update() End If End If DdlSucursalCliente.Items.Clear() If ObjCliente.GetSucursales(CveCliente) Then DdlSucursalCliente.DataSource = ObjCliente.DtResultados If ObjCliente.DtResultados.Rows.Count > 0 Then trsucursalciente.Visible = True Else trsucursalciente.Visible = False End If Else trsucursalciente.Visible = False DdlSucursalCliente.DataSource = Nothing End If DdlSucursalCliente.Items.Insert(0, New ListItem("Matriz", "-1")) DdlSucursalCliente.DataBind() 'SI UTILIZA EL RFC GENERICO PERMITE FACTURAR SUCURSAL If (Not UsuarioActual.Empresa.Funcionalidad(558) = "1") AndAlso (CveVenta <= 0 OrElse NuevaFactura = 1) AndAlso LblRFC.Text.Trim() = "XAXX010101000" Then HabilitarFacturacionSucursal() End If 'CargaFolios() If ObjCliente.GetClienteImpuestosLocales(CveCliente) AndAlso CveVenta <= 0 Then 'se cargan impuestos locales Dim DtClienteImpuesto As DataTable = ObjCliente.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") If DtClienteImpuesto IsNot Nothing AndAlso DtClienteImpuesto.Rows.Count > 0 Then ' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear() TmpDTImpuestos = DtClienteImpuesto GvImpuestosLocales2.DataSource = TmpDTImpuestos GvImpuestosLocales2.DataBind() If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then TrOtros.Visible = True GvImpuestosLocales2.Visible = True TrOtros.Style.Add("display", "") Else TrOtros.Visible = False GvImpuestosLocales2.Visible = False End If DtClienteImpuesto.Dispose() End If UpImpuestos.Update() End If If DdlTipoComprobante.SelectedValue.Contiene("Cot") Then 'TrAtencionA.Visible = True TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False 'tdTelefonoGen.Visible = False 'tdTxtTelefonoGen.Visible = False ElseIf ObjCliente.RFC = "XAXX010101000" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ret") Then 'TrAtencionA.Visible = True TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False 'tdTelefonoGen.Visible = True 'tdTxtTelefonoGen.Visible = True Else 'TrAtencionA.Visible = False TrDireccion.Visible = True TrCiudad.Visible = True TrRFC.Visible = True 'tdTelefonoGen.Visible = False 'tdTxtTelefonoGen.Visible = False 'TxtAtencionA.Text = "" 'TxtTelefonoGenerico.Text = "" End If 'TrAtencionA.Visible = True 'tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") 'tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") LbAgregar.Enabled = True If UsuarioActual.CveEmpresa.Contiene(72, 80, 1, 119) Then BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)});" BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") BtnEmitirImprimir.Attributes.Add("data-popout", "true") BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") BtnEmitirImprimir.Attributes.Add("data-html", "true") End If 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True 'Else ' BtnEmitirImprimir.Visible = EstatusCliente ' TrVistaPrevia.Visible = EstatusCliente End If TrVistaPrevia.Visible = True ' si es empresa acumuladores If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then CargaPorcentajeMarcas() End If 'CargaFacturasARelacionar() UpFacturar.Update() UpEstatus.Update() UpPS.Update() UpParametros.Update() UPCondicionesPago.Update() UpCliente.Update() UpnTools.Update() Else Alert("Ocurrió un error al cargar los datos del cliente. Por favor vuelva a intentar.", TipoMensaje.MsgError) End If End If ObjCliente.Dispose() BloqueaCondiconesPago() DeshabilitarAplicarNotaDeCredito(LblRFC.Text) Dim CveVentaRef As Integer = -1 If Me.CveVenta > 0 AndAlso Not EsCreaApartirDe Then CveVentaRef = Me.CveVenta End If CargaRestriccionesCreditoCliente(True, CveVentaRef) If CveVenta <= 0 Then 'CalculaLineasAdicionales() HabilitaRemisionPublicoGeneral = 0 HabilitarRemisionesPublicoGeneral() End If 'If UsuarioActual.Empresa.Funcionalidad(705) = "1" Then ' Using ObjVentas As New ClsVentas ' If ObjVentas.GetLineasAdicionales(-1, CveCliente, -1, -1, DdlMoneda.SelectedValue.ToEntero(), MinFecha, MaxFecha, 0, UsuarioActual.CveEmpresa) Then ' If ObjVentas.DtResultados.Rows.Count > 0 Then ' TrLineaAdicional.Visible = True ' End If ' End If ' End Using 'End If End Sub Private Sub HabilitarRemisionesPublicoGeneral() If UsuarioActual.Empresa.Funcionalidad(381).Trim() <> "" Then 'SI ESTA BLOQUEADO POR AUTORIZACION, HABILITAR LA OPCION DE REMISION PARA PUBLICO EN GENERAL If UsuarioActual.Empresa.Funcionalidad(381).Trim() = CveCliente.ToString() Then Dim DeshabilitarAutorizacion As Boolean = CBool(GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("DeshabilitaAutorizacion")) 'SI ESTA BLOQUEADO POR AUTORZACION O QUE TENGA LA OPCION DE AUTORIZACIONES Y NO SEA DEL MODULO DE COTIZACIONES If (DdlTipoComprobante.SelectedValue.Contiene("PA") OrElse (DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso DdlTipoComprobante.Items.FindByValue("PA") IsNot Nothing AndAlso Not IfNull(Request("Op"), "").ToString() = "Cot")) AndAlso DeshabilitarAutorizacion Then If DdlTipoComprobante.Items.FindByValue("Rem") Is Nothing Then DdlTipoComprobante.Items.Insert(0, New ListItem("Remisión", "Rem")) End If DdlTipoComprobante.SelectedValueExist("Rem") HabilitaRemisionPublicoGeneral = 1 End If 'SI TUVO HABILITADO EL BLOQUEO POR AUTORIZACION PERO DESPUES SE CAMBIO MANUAL A REMISION If DdlTipoComprobante.SelectedValue.Contiene("Rem") AndAlso TieneBloqueoPorAutorizacion = 1 Then HabilitaRemisionPublicoGeneral = 1 End If 'SI TIENE LA HABILITACION DE REMISION ACTIVA Y LA SUCURSAL NO LO PERMITE If Not DeshabilitarAutorizacion AndAlso HabilitaRemisionPublicoGeneral = 1 Then HabilitaRemisionPublicoGeneral = 0 DdlTipoComprobante.SelectedValueExist("PA") If DdlTipoComprobante.Items.FindByValue("Rem") IsNot Nothing Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) End If End If UpParametros.Update() End If Else HabilitaRemisionPublicoGeneral = 0 End If End Sub Private Function ValidaImportePublicoGeneral() As Boolean Dim retorno As Boolean = False If DdlTipoComprobante.SelectedValue = "Rem" AndAlso HabilitaRemisionPublicoGeneral = 1 AndAlso UsuarioActual.Empresa.Funcionalidad(381).Trim() = CveCliente.ToString() Then Dim Total As Decimal = TxtTotal.Text.ToDecimal() If DdlMoneda.SelectedValue = "1" Then If Total <= 5000D Then retorno = True Else Alert("No puede generar una remisión con un valor mayor a 5,000 MXN. Debe cambiar el tipo de documento a 'Autorización'", TipoMensaje.MsgAdvertencia) End If End If If DdlMoneda.SelectedValue = "2" Then If TxtTipoCambio.Text.ToDecimal() > 0 Then Dim TotalPesos As Decimal = (Total * TxtTipoCambio.Text.ToDecimal()) If TotalPesos <= 5000D Then retorno = True Else Alert($"No puede generar una remisión con un valor mayor a {(5000 / TxtTipoCambio.Text.ToDecimal()).RoundSQL(2)} USD. Debe cambiar el tipo de documento a 'Autorización'", TipoMensaje.MsgAdvertencia) End If Else Alert("No se ha especificado un tipo de cambio", TipoMensaje.MsgAdvertencia) End If End If Else retorno = True End If Return retorno End Function Private Sub CargaRestriccionesCreditoCliente(Optional Alertas As Boolean = False, Optional CveVenta As Integer = -1) Dim ValorAutorizacion As String = UsuarioActual.Empresa.Funcionalidad(595) 'OBLIGAR PAGO DE CONTADO SI EL CLIENTE NO PERMITE CREDITO If (Not UsuarioActual.Empresa.Funcionalidad(702).Contiene("1", "2")) AndAlso Me.PermiteCredito = False AndAlso ((DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") AndAlso CveVenta < 1) OrElse (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "Cot", "PA") AndAlso EsCreaApartirDe) OrElse (DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso CveVenta > 0)) Then 'GENERAR UNA AUTORIZACIÓN SI EL CLIENTE NO PERMITE CREDITO If UsuarioActual.Empresa.Funcionalidad(595) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(268) Then 'SI LLEGÓ POR LA OPCIÓN DE COTIZACIÓN NO DEBE DE RESTRINGUIR If IfNull(Request("Op"), "").ToString() = "Cot" OrElse (DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0) Then DdlTipoComprobante.SelectedValue = "Cot" BtnGenerarRemision.Visible = False Else DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") DdlTipoComprobante.SelectedValue = "PA" TieneBloqueoPorAutorizacion = 1 End If DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) If Not UsuarioActual.TienePermisoProceso(325) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) End If DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) BtnsFacturar.Visible = False End If UPCondicionesPago.Update() 'CARGAR CREDITO DISPONIBLE AL GENERAR UNA FACTURA End If 'If ((DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "Cot", "PA") AndAlso CveVenta <= 0) OrElse (DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso CveVenta > 0)) AndAlso PermiteCredito Then ' 'FUNCIONALIDAD 702 - NO VERIFICAR LIMITE DE CRÉDITO Y CANDADOS DE VENTA ' If Not UsuarioActual.Empresa.Funcionalidad(702) = "1" Then ' Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero()) ' If CreditoDispo > 0 Then ' TrCreditoDisponible.Visible = True ' LblCreditoDisponible.Text = CreditoDispo.FormatoNumero ' If PorcentajeCredito > 80 Then TrPorcentajeCredito.Visible = True : LblPorcentajeCredito.Text = $"{PorcentajeCredito.FormatoNumero}%" ' If Not UsuarioActual.TienePermisoProceso(268) AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "PA") OrElse (DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso CveVenta > 0)) AndAlso (Not UsuarioActual.Empresa.Funcionalidad(702).Contiene("2")) Then ' Dim Vta As New ClsVentas ' Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) ' Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

{0}", Vta.SerieVenta) ' Vta.Dispose() ' If Opcion > 0 Then ' 'si la cotización no debe de existir este canddado ' If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) ' 'RBLPago.SelectedValue = "2" ' 'RBLPago.Items(0).Enabled = False ' UPCondicionesPago.Update() ' If Not EsCreaApartirDe AndAlso (DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0) Then ' DdlTipoComprobante.SelectedValueExist("Cot") ' Else ' If UsuarioActual.Empresa.Funcionalidad(531) <> "1" Then ' DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") ' DdlTipoComprobante.SelectedValue = "PA" ' TieneBloqueoPorAutorizacion = 1 ' End If ' End If ' 'si llegó por la opción de cotización no debe de restringuir ' If IfNull(Request("Op"), "").ToString() = "Cot" OrElse (DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0) Then DdlTipoComprobante.SelectedValue = "Cot" ' 'quito remisión y factura ' If UsuarioActual.Empresa.Funcionalidad(531) <> "1" Then ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) ' If Not UsuarioActual.TienePermisoProceso(325) Then ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) ' End If ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) ' End If ' 'SI ES AUTORIZACION DEBE PERMITIR GENERARLA ' If (Not DdlTipoComprobante.SelectedValue.Contiene("PA")) AndAlso UsuarioActual.Empresa.Funcionalidad(531) <> "1" Then ' BtnEmitirImprimir.Visible = False ' BtnsFacturar.Visible = False ' LBFacturarAnticipo.Visible = UsuarioActual.TienePermisoProceso(274) ' BtnGenerarRemision.Visible = False ' 'LnkPedido2SinFacturar.Visible = False ' LnkCotizaciones.Visible = False ' LnkOCs.Visible = False ' End If ' If DdlTipoComprobante.SelectedValue = "Cot" AndAlso UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ' Dim Autorizacion As Integer = 0 ' Dim ObjVentas As New ClsVentas ' If ObjVentas.GetAutorizacionLimite(UsuarioActual.CveEmpresa, CveCliente, DdlVendedor.SelectedValue.ToEntero, "Ing", CveEstatus:=1) Then ' Dim RowAutorizacion As DataRow = Nothing ' 'SI TIENE DIAS VENCIDOS BUSCAR POR TIPO VENCIMIENTO ' If TieneDiasVencidos Then ' RowAutorizacion = ObjVentas.DtResultados.FiltroPrimero($"TipoAutorizacion IN(1,2) AND CveVenta IS NULL AND CveTipoDocumento='Ing'", Orderby:="Importe DESC") ' Else ' RowAutorizacion = ObjVentas.DtResultados.FiltroPrimero($"TipoAutorizacion = 1 AND CveVenta IS NULL AND CveTipoDocumento='Ing'", Orderby:="Importe DESC") ' End If ' If RowAutorizacion IsNot Nothing Then ' Autorizacion = RowAutorizacion("CveAutorizacion").ToString().ToEntero() ' End If ' End If ' ObjVentas.Dispose() ' 'SI NO TIENE AUTORIZACION, MANTIENE EL BLOQUEO POR CONDICIONES DE CREDITO ' If Autorizacion > 0 Then ' BtnsFacturar.Visible = True ' End If ' End If ' Else ' ' el cliente tiene crédito disponible, no tiene bloqueo ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PA")) ' Dim EsCotizacion As Boolean = False ' If IfNull(Request("Op"), "").ToString() = "Cot" OrElse (DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0) Then ' EsCotizacion = True ' End If ' If UsuarioActual.TienePermisoProceso(199) Then DdlTipoComprobante.SelectedValueExistInsert("Rem", "Remisión") ' puede remisionar ' If UsuarioActual.TienePermisoProceso(60) Then DdlTipoComprobante.SelectedValueExistInsert("Ing", "Ingresos") 'puede facturar ' DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento) ' If EsCotizacion Then ' DdlTipoComprobante.SelectedValueExistInsert("Cot", "Cotización") ' End If ' If EsCotizacion AndAlso UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ' Dim Autorizacion As Integer = 0 ' Dim ObjVentas As New ClsVentas ' If ObjVentas.GetAutorizacionLimite(UsuarioActual.CveEmpresa, CveCliente, DdlVendedor.SelectedValue.ToEntero, "Ing", CveEstatus:=1) Then ' Dim RowAutorizacion As DataRow = Nothing ' 'SI TIENE DIAS VENCIDOS BUSCAR POR TIPO VENCIMIENTO ' If TieneDiasVencidos Then ' RowAutorizacion = ObjVentas.DtResultados.FiltroPrimero($"TipoAutorizacion IN(1,2) AND CveVenta IS NULL AND CveTipoDocumento='Ing'", Orderby:="Importe DESC") ' Else ' RowAutorizacion = ObjVentas.DtResultados.FiltroPrimero($"TipoAutorizacion = 1 AND CveVenta IS NULL AND CveTipoDocumento='Ing'", Orderby:="Importe DESC") ' End If ' If RowAutorizacion IsNot Nothing Then ' Autorizacion = RowAutorizacion("CveAutorizacion").ToString().ToEntero() ' End If ' End If ' ObjVentas.Dispose() ' 'SI NO TIENE AUTORIZACION, MANTIENE EL BLOQUEO POR CONDICIONES DE CREDITO ' If Autorizacion > 0 Then ' BtnsFacturar.Visible = True ' End If ' End If ' End If ' End If ' Else ' 'GENERAR AUTORIZACION SI TIENE EXCEDIO EL LIMITE DE CREDITO ' Select Case ValorAutorizacion ' Case "1" 'CREAR DOCUMENTO DE AUTORIZACION PA ' If Not UsuarioActual.TienePermisoProceso(268) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ant", "PA") AndAlso Not (UsuarioActual.Empresa.Funcionalidad(702).Contiene("2")) AndAlso UsuarioActual.Empresa.Funcionalidad(531) <> "1" Then ' 'VERIFICAR CANDADOS DE VENTA, REMISIONES SIN FACTURAR, FACTURAS QUE NO TENGAN VENCIDAS ' Dim Vta As New ClsVentas ' Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) ' Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

{0}", Vta.SerieVenta) ' Vta.Dispose() ' If Opcion > 0 Then ' 'If Opcion = 1 Then ' ' BtnEmitirImprimir.Visible = False ' ' BtnsFacturar.Visible = False ' 'End If ' If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) ' Else ' If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia) ' End If ' UPCondicionesPago.Update() ' DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") ' DdlTipoComprobante.SelectedValue = "PA" ' TieneBloqueoPorAutorizacion = 1 ' 'si llegó por la opción de cotización no debe de restringuir ' If IfNull(Request("Op"), "").ToString() = "Cot" OrElse (DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0) Then DdlTipoComprobante.SelectedValue = "Cot" ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) ' If Not UsuarioActual.TienePermisoProceso(325) Then ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) ' End If ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) ' BtnsFacturar.Visible = False ' LBFacturarAnticipo.Visible = UsuarioActual.TienePermisoProceso(274) ' BtnGenerarRemision.Visible = False ' 'LnkPedido2SinFacturar.Visible = False ' LnkCotizaciones.Visible = False ' LnkOCs.Visible = False ' Else ' If DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0 Then ' Dim Vta As New ClsVentas ' Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) ' Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

{0}", Vta.SerieVenta) ' Vta.Dispose() ' If Opcion > 0 Then ' BtnsFacturar.Visible = False ' BtnGenerarRemision.Visible = False ' Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) ' End If ' End If ' End If ' Case "2" 'Autorizacion desde una solicitud del catalogo de autorizaciones ' 'RMF. validacion temporal ' 'verifica si tiene autorizaciones de Nota de crédito autorizadas ' Dim ObjVentas As New ClsVentas ' If ObjVentas.GetAutorizacionLimite(UsuarioActual.CveEmpresa, CveCliente, -1, "Ing", CveEstatus:=1) Then ' Dim RowAutorizacion As DataRow = ObjVentas.DtResultados.FiltroPrimero($"CveVenta IS NULL AND CveTipoDocumento='Egs'", Orderby:="TipoAutorizacion") ' If RowAutorizacion IsNot Nothing Then ' DdlTipoComprobante.SelectedValueExistInsert("Egs", "Egresos") ' End If ' End If ' ObjVentas.Dispose() ' Case Else 'SI NO TIENE NINGUN TIPO DE AUTORIZACION CONFIGURADO ' 'RMF. codigo temporal para pruebas ' If Alertas AndAlso UsuarioActual.CveEmpresa = 140 Then ' Dim Vta As New ClsVentas ' Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) ' Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

{0}", Vta.SerieVenta) ' Vta.Dispose() ' If Opcion > 0 Then ' LnkSolicitarCredito.Visible = True ' Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) ' End If ' Else ' 'VERIFICAR CANDADOS DE VENTA ' If DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0 Then ' Dim Vta As New ClsVentas ' Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa) ' Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

{0}", Vta.SerieVenta) ' Vta.Dispose() ' If Opcion > 0 Then ' BtnsFacturar.Visible = False ' BtnGenerarRemision.Visible = False ' Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) ' End If ' End If ' End If ' End Select ' End If ' End If 'Else 'End If 'Puede hacer pedido If CveVenta <= 0 Then If Not UsuarioActual.TienePermisoProceso(177) Then If DdlTipoComprobante.Items.FindByValue("Pd2") IsNot Nothing Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2")) End If End If End If End Sub Private Sub CargaClienteSucursal(CveClienteSuc As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing) Me.ClienteSucursal = Nothing Me.FacturarSucursal = False LtlTitleRFCSucursal.Text = "" LtlRFCSucursal.Text = "" Dim ObjCliente As New ClsClientes If CveClienteSuc > 0 Then If ObjCliente.GetSucursales(CveCliente, CveClienteSuc) Then If ObjCliente.DtResultados.Rows.Count > 0 Then Dim Correo As String = 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() 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() Me.CveVendedorClienteSucursal = ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString().ToEntero() ViewState("CveClienteSucursal") = ObjCliente.DtResultados(0)("CveClienteSucursal").ToString() ViewState("CliCorreoCot") = ObjCliente.DtResultados.Rows(0)("CorreoCotizacion").ToString() 'If ObjCliente.DtResultados.Rows(0)("Estatus").ToString() <> "Activo" Then ' Alert("La Sucursal/Departamento del cliente se encuentra inactivo", TipoMensaje.MsgAdvertencia) 'Else ' Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero(), ObjVentas) ' TrCreditoDisponible.Visible = True ' LblCreditoDisponible.Text = CreditoDispo.FormatoNumero ' UPPCreditoDisponible.Update() ' UpParametros.Update() 'End If 'SI EL CLIENTE TIENE RFC GENERICO Y LA SUCURSAL TIENE RFC DEBE FACTURAR LA SUCURSAL If (Not UsuarioActual.Empresa.Funcionalidad(558) = "1") AndAlso LblRFC.Text.Trim() = "XAXX010101000" AndAlso Not String.IsNullOrEmpty(ObjCliente.DtResultados.Rows(0)("RFC").ToString()) Then Me.FacturarSucursal = True LtlTitleRFCSucursal.Text = "RFC:" LtlRFCSucursal.Text = ObjCliente.DtResultados.Rows(0)("RFC").ToString() Me.ClienteSucursal = New Modelos.SucursalModel Me.ClienteSucursal.Nombre = ObjCliente.DtResultados.Rows(0)("SucursalCliente").ToString() Me.ClienteSucursal.RFC = ObjCliente.DtResultados.Rows(0)("RFC").ToString() Me.ClienteSucursal.NoExt = CliNoExt Me.ClienteSucursal.NoInt = CliNoInt Me.ClienteSucursal.Localidad = CliLocalidad Me.ClienteSucursal.Direccion = LblDireccion.Text Me.ClienteSucursal.Colonia = LblColonia.Text Me.ClienteSucursal.Municipio = LblCiudad.Text Me.ClienteSucursal.Estado = LblEstado.Text Me.ClienteSucursal.CP = LblCP.Text Me.ClienteSucursal.Pais = CliPais Me.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString() Me.ClienteSucursal.TelefonoSucursal = LblTelefono.Text Me.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero() > 0, DdlSucursalCliente.SelectedItem.Text, "") Me.ClienteSucursal.ImprimeNombreSucursal = ImprimeNombreSucursal.ToString() End If If CveVenta <= 0 Then 'CveMetodoPagoCliente = ObjCliente.DtResultados.Rows(0)("CveMetodoPago").ToString().ToEntero() DdlMetodoPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago33").ToString()) DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty) DdlFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString()) DdlUsoCFDI.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveUsoCFDI").ToString()) 'SI ES RFC GENERICO NO TIENE OBLIGACIONES FISCALES If LblRFC.Text.Contiene("XAXX010101000", "XEXX010101000") Then 'S01 Sin efectos fiscales. DdlUsoCFDI.SelectedValueExist("23") DdlUsoCFDI.Enabled = False RegimenFiscalCliente = "616" ClienteCodigoRegimenFiscal = "616" End If End If 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 Me.CveVendedorClienteSucursal = -1 Me.CveVendedorCliente = ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString().ToEntero() ViewState("CliNoExt") = ObjCliente.NoExt ViewState("CliNoInt") = ObjCliente.NoInt PlazoCobranza = ObjCliente.PlazoCobranza Dim CveCotizacion As Integer = IfNull(ViewState("CveCotizacion"), 0).ToString().ToEntero() If CveVenta <= 0 AndAlso CveCotizacion <= 0 Then 'CveMetodoPagoCliente = ObjCliente.CveMetodoPago DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33) DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty) DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI) 'SI ES RFC GENERICO NO TIENE OBLIGACIONES FISCALES If LblRFC.Text.Contiene("XAXX010101000", "XEXX010101000") Then 'S01 Sin efectos fiscales. DdlUsoCFDI.SelectedValueExist("23") DdlUsoCFDI.Enabled = False RegimenFiscalCliente = "616" ClienteCodigoRegimenFiscal = "616" End If End If End If End If End If ''SI LA SUCURSAL DEL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO 'If Not -1 > 0 Then ' DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString()) 'End If ObjCliente.Dispose() UpEstatus.Update() UPCondicionesPago.Update() UpCliente.Update() 'UpEmitirTransitorio.Update() End Sub Private Function CargaCreditoDisponible(tCveCliente As Integer, tCveSucursalCliente As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing) As Decimal Dim Retorno As Decimal = 0 Dim ObjVentasAplciar As ClsVentas = Nothing If ObjVentas IsNot Nothing Then ObjVentasAplciar = ObjVentas Else ObjVentasAplciar = New ClsVentas End If If ObjVentasAplciar.ObtenerCreditoRestante(tCveCliente, tCveSucursalCliente) Then If ObjVentasAplciar.DtResultados.Rows.Count > 0 Then If tCveSucursalCliente > 0 Then Dim LimiteRestanteSucursal As Decimal = ObjVentasAplciar.DtResultados(0)("LimiteRestanteSucursal").ToString().ToDecimal Dim PorcentajeSaldoSucursal As Decimal = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoSucursal").ToString().ToDecimal Dim LimiteRestanteCliente As Decimal = ObjVentasAplciar.DtResultados(0)("LimiteRestanteCliente").ToString().ToDecimal Dim PorcentajeSaldoCliente As Decimal = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoCliente").ToString().ToDecimal 'SI EL LIMITE DE LA SUCURSAL ES MAYOR AL DEL CLIENTE DEBE LIMITAR AL DEL CLIENTE If LimiteRestanteSucursal > LimiteRestanteCliente Then Retorno = LimiteRestanteCliente PorcentajeCredito = PorcentajeSaldoCliente ElseIf LimiteRestanteSucursal < LimiteRestanteCliente Then Retorno = LimiteRestanteSucursal PorcentajeCredito = PorcentajeSaldoSucursal ElseIf LimiteRestanteSucursal = LimiteRestanteCliente Then Retorno = LimiteRestanteSucursal PorcentajeCredito = PorcentajeSaldoSucursal End If Else Retorno = ObjVentasAplciar.DtResultados(0)("LimiteRestanteCliente").ToString().ToDecimal PorcentajeCredito = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoCliente").ToString().ToDecimal End If End If End If If ObjVentas Is Nothing Then ObjVentasAplciar.Dispose() End If Return Retorno End Function Private Sub CargaDdlSubProyectos() Dim dtt As New DataTable dtt = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) DdlSubProyectoDatos.DataSource = dtt.FiltraParametros("EsSucursal = True ") DdlSubProyectoDatos.DataBind() 'DdlSubProyectoCobranza.DataSource = dtt.FiltraParametros("EsSucursal = True ") 'DdlSubProyectoCobranza.DataBind() 'DdlSubProyectoEjecucion.DataSource = dtt.FiltraParametros("EsSucursal = True ") 'DdlSubProyectoEjecucion.DataBind() 'DdlSubProyectoFiltroAF.DataSource = dtt 'DdlSubProyectoFiltroAF.DataBind() 'DdlSubProyectoFiltroAF.Items.Insert(0, New ListItem("Todos", "-1")) dtt.Dispose() End Sub Private Sub CargaClasificaciones() If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso 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).FiltraParametros("UsoClasificacion IN (1,3) and Estado = 1", Orderby:="Clasificacion") End If 'DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa) DdlClasificacion.DataBind() End Sub Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost, Optional AplicaParaVenta 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 = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, Estatus:=1, AplicaParaVenta:=If(AplicaParaVenta, 1, -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 If Me.CveVenta > 0 Then DdlSubProyectoDatos.SelectedValueExist(CveSubProyectoVenta) End If Dim cvesubproyecto As String = DdlSubProyectoDatos.SelectedValue If UsuarioActual.Empresa.Funcionalidad(558) = "1" OrElse UsuarioActual.Empresa.Funcionalidad(531) = "1" Then 'cuando es empresa llantera (558) o cuando es empresa acumuladores cvesubproyecto = "-1" End If Objeto.Attributes.Add("data-cvesubproyecto", cvesubproyecto) Objeto.ddlWS.Attributes.Add("data-cveclasificacion", CveClasificacion.ToString()) Objeto.ddlWS.Attributes.Add("data-Estatus", "1") If AplicaParaVenta Then Objeto.ddlWS.Attributes.Add("data-pagina", "ventas/ventas") Objeto.ddlWS.Attributes.Add("data-AplicaparaVenta", "1") End If End If End Sub Private Sub CargaTiposVenta() RBLTipoVenta.DataSource = GlobalDTTipoVenta().FiltraParametros("Estatus = 'True' ") RBLTipoVenta.DataBind() RegistraScript("$('#DvModalTipoVenta').modal({ backdrop: 'static', keyboard: false });") End Sub Private Sub CargaProcedimientos() DdlMedico.DataSource = GlobalDTMedicos(UsuarioActual.CveEmpresa).FiltraParametros("Estatus = 'True' ") DdlMedico.DataBind() DdlMedicoModal.DataSource = GlobalDTMedicos(UsuarioActual.CveEmpresa).FiltraParametros("Estatus = 'True' ") DdlMedicoModal.DataBind() End Sub Private Sub CargaAgentes() DdlProcedimiento.DataSource = GlobalDTProcedimientos(UsuarioActual.CveEmpresa).FiltraParametros("Estatus = 'True' ") DdlProcedimiento.DataBind() DdlProcedimientoModal.DataSource = GlobalDTProcedimientos(UsuarioActual.CveEmpresa).FiltraParametros("Estatus = 'True' ") DdlProcedimientoModal.DataBind() End Sub Private Sub CargaPSRemision(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost) Objeto.setEsWebService(UsuarioActual.Empresa.Funcionalidad(141).ToString() = "1") If Not UsuarioActual.Empresa.Funcionalidad(141).ToString() = "1" Then Objeto.ddl.Items.Clear() 'Objeto.ddl.DataSource = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, Estatus:=1, AplicaParaVenta:=1) Objeto.ddl.DataBind() Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2")) Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1")) Else Dim cvesubproyecto As String = "-1" Objeto.Attributes.Add("data-cvesubproyecto", cvesubproyecto) Objeto.ddlWS.Attributes.Add("data-cveclasificacion", CveClasificacion.ToString()) Objeto.ddlWS.Attributes.Add("data-pagina", "ventas/ventas") Objeto.ddlWS.Attributes.Add("data-Estatus", "1") Objeto.ddlWS.Attributes.Add("data-AplicaparaVenta", "1") End If End Sub #End Region #Region "G R I D V I E W S" Protected Sub GvPS_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvPS.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Attributes("id") = e.Row.RowIndex.ToString() If e.Row.RowIndex = 0 Then End If If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then 'MODO EDICION If UsuarioActual.Empresa.UsaInventarios Then e.Row.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToEntero(), -1, UsuarioActual.CveEmpresa) Else e.Row.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) End If e.Row.FCDropDownList("DdlUnidadMedida").DataBind() e.Row.FCDropDownList("DdlUnidadMedida").SelectedValueExist(e.Row.DBCampo("CveUM")) e.Row.FCDropDownList("DdlClasificacion").DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1) e.Row.FCDropDownList("DdlClasificacion").DataBind() e.Row.FCDropDownList("DdlClasificacion").SelectedValue = e.Row.DBCampo("CveClasificacion") CargaPS(e.Row.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero(), e.Row.FCDropDownLost("DdlPS")) e.Row.FCDropDownLost("DdlPS").SelectedText = e.Row.DBCampo("PS") e.Row.FCDropDownLost("DdlPS").SelectedValue = e.Row.DBCampo("CvePS") If e.Row.DBCampo("CveSubProyecto") = "-1" Then 'cargo todos las opciones para 'e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) 'e.Row.FCDropDownList("DdlProyecto").DataBind() 'e.Row.FCDropDownList("DdlProyecto").Items.Insert(0, New ListItem("Sin Proyecto Asignado", "-1")) 'e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) 'e.Row.FCDropDownList("DdlSubProyecto").DataBind() 'e.Row.FCDropDownList("DdlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) Else 'Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, e.Row.DBCampo("CveSubProyecto").ToEntero(), 1).FiltroPrimero("") 'If dr IsNot Nothing Then ' e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) ' e.Row.FCDropDownList("DdlProyecto").DataBind() ' e.Row.FCDropDownList("DdlProyecto").SelectedValue = dr("CveProyecto").ToString() ' e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, dr("CveProyecto").ToString().ToEntero(), UsuarioActual.CveEmpresa, -1, 1) ' e.Row.FCDropDownList("DdlSubProyecto").DataBind() ' e.Row.FCDropDownList("DdlSubProyecto").SelectedValueExist(e.Row.DBCampo("CveSubProyecto")) 'End If End If If UsuarioActual.TienePermisoProceso(68) Then e.Row.FCTextBox("TxtPrecio").Enabled = False e.Row.FCTextBox("TxtDescuento").Enabled = False End If If Not EsCreaApartirDe Then 'Si es una devolucion If NuevaFactura = 0 Then e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownLost("DdlPS").Enabled = False 'e.Row.FCDropDownList("DdlProyecto").Enabled = False 'e.Row.FCDropDownList("DdlSubProyecto").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = False ElseIf NuevaFactura = 1 Or CveContrato > 0 Then e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownLost("DdlPS").Enabled = False e.Row.FCTextBox("TxtCantidad").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = False e.Row.FCTextBox("TxtDescuento").Enabled = False If TieneAlmacen Then e.Row.FCLinkButton("imgD").Visible = False If UsuarioActual.TienePermisoProceso(222) Then e.Row.FCDropDownList("DdlUnidadMedida").Enabled = True e.Row.FCDropDownList("DdlClasificacion").Enabled = True e.Row.FCDropDownLost("DdlPS").Enabled = True e.Row.FCTextBox("TxtCantidad").Enabled = True e.Row.FCTextBox("TxtPrecio").Enabled = True e.Row.FCTextBox("TxtDescuento").Enabled = True End If End If End If 'Si es facturacion de OC o Contrato If CveContrato > 0 AndAlso Not CveVenta > 0 AndAlso Not CveCicloComercial > 0 Then e.Row.FCLinkButton("imgClone").Visible = False e.Row.FCTextBox("TxtOrden").Visible = True e.Row.FCTextBox("TxtCantidad").Enabled = False e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownLost("DdlPS").Enabled = False 'e.Row.FCDropDownList("DdlProyecto").Enabled = False 'e.Row.FCDropDownList("DdlSubProyecto").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = False End If If CveContrato > 0 AndAlso CveContratoTipo = 33 Then e.Row.FCTextBox("TxtCantidad").Enabled = True e.Row.FCTextBox("TxtPrecio").Enabled = True End If If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then e.Row.FCLinkButton("imgClone").Visible = False e.Row.FCTextBox("TxtOrden").Visible = True e.Row.FCTextBox("TxtCantidad").Enabled = False e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False ' e.Row.FCDropDownList("DdlProyecto").Enabled = False 'e.Row.FCDropDownList("DdlSubProyecto").Enabled = False e.Row.FCLiteral("LtlPSEdit").Visible = True e.Row.FCDropDownLost("DdlPS").Visible = False e.Row.FCDropDownLost("DdlPS").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = True End If If CveCicloComercial > 0 Then e.Row.FCTextBox("TxtPrecio").Enabled = True End If 'CUANDO SE QUIERE FACTURAR UNA REMISIÓN NO PERMITE EDITAR SU PRECIO If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso (e.Row.DBCampo("CveVentaDetalle").ToEntero() > 0 Or e.Row.DBCampo("CveVentaDetalleRemision").ToEntero() > 0) Then e.Row.FCTextBox("TxtPrecio").Enabled = False End If 'PERMISO EDITAR REM If e.Row.DBCampo("TipoDocto") = "Rem" And ModalidadEdicion Then 'LO PERMITIDO MODIFICAR e.Row.FCTextBox("TxtPrecio").Enabled = True e.Row.FCTextBox("TxtObsPS").Enabled = True e.Row.FCTextBox("TxtCantidad").Attributes.Add("onblur", $"ValidarCantidadMenor(this,{e.Row.DBCampo("CantidadInventario").ToDouble})") 'LO NO PERMITIDO MODIFICAR e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False If UsuarioActual.CveEmpresa = 119 Then e.Row.FCTextBox("TxtCantidad").Enabled = False End If 'cuando ya tiene una salida, no se puede cambiar el producto If e.Row.DBCampo("CantidadInventario").ToDouble > 0 Then e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownLost("DdlPS").Enabled = False e.Row.FCDropDownLost("DdlPS").ddlWS.Attributes.Add("disabled", "disabled") End If e.Row.FCTextBox("TxtTiempoEntrega").Enabled = False 'e.Row.FCDropDownList("DdlProyecto").Enabled = False 'e.Row.FCDropDownList("DdlSubProyecto").Enabled = False e.Row.FCLinkButton("imgD").Visible = False End If If UsuarioActual.CveEmpresa.Contiene(7, 122) Then e.Row.FCTextBox("TxtCantidad").Width = New Unit("100%") e.Row.FCLabel("LblTurnoEditar").Visible = True e.Row.FCTextBox("TxtNumTurnosEditar").Visible = True End If 'If UsuarioActual.CveEmpresa = 119 Then ' e.Row.FCTextBox("TxtDescuento").Enabled = False 'End If Else 'MODO NORMAL If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then e.Row.FCDropDownList("DdlFR").DataSource = DTPresupuestoIngresos e.Row.FCDropDownList("DdlFR").DataBind() e.Row.FCDropDownList("DdlFR").SelectedValue = e.Row.DBCampo("CvePresupuestoIngreso") 'e.Row.FCDropDownList("DdlFR").Enabled = False End If If e.Row.DataKey("IEPS").ToDouble > 0 Then : TrIEPS.Visible = True : End If If NuevaFactura = 1 Then If Not UsuarioActual.TienePermisoProceso(222) Then e.Row.FCLinkButton("imgD").Visible = False e.Row.FCLinkButton("imgE").Visible = False End If If TieneAlmacen Then e.Row.FCLinkButton("imgD").Visible = False End If End If If (CveContrato > 0 AndAlso Not CveVenta > 0) Then e.Row.FCLinkButton("imgD").Visible = False End If 'If DdlContratosModal.DataSource IsNot Nothing AndAlso CveCicloComercial <= 0 Then ' e.Row.FCLinkButton("imgE").Visible = False 'End If 'Si es facturacion de OC If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then e.Row.FCLinkButton("imgClone").Visible = False e.Row.FCTextBox("TxtOrden").Visible = True End If If UsuarioActual.Empresa.CvePlataforma = 2 Then e.Row.FCLinkButton("imgE").Visible = False e.Row.FCLinkButton("imgEPyME").Visible = True End If If UsuarioActual.Empresa.Tipo_CentroCosto = 2 Or UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then e.Row.FCLabel("LblProyecto").Visible = False End If If CveVenta > 0 Then 'And e.Row.DBCampo("TipoDocto") = "Rem" If ModalidadEdicion Then e.Row.FCLinkButton("imgE").Visible = Not e.Row.DBCampo("CantidadFacturadaRem").ToDouble > 0 e.Row.FCLinkButton("imgD").Visible = Not e.Row.DBCampo("CantidadInventario").ToDouble > 0 ElseIf Not CveDevolucion > 0 Then e.Row.FCLinkButton("imgE").Visible = False e.Row.FCLinkButton("imgD").Visible = False End If 'EN BDH NO DEBE PODER EDITAR LOS PS If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then If ModalidadEdicion Then e.Row.FCLinkButton("imgE").Visible = True e.Row.FCLinkButton("imgD").Visible = False Else e.Row.FCLinkButton("imgE").Visible = False e.Row.FCLinkButton("imgD").Visible = False End If End If End If If UsuarioActual.Empresa.Funcionalidad(360) = "1" AndAlso e.Row.DBCampo("CvePrecioLista").ToEntero() > 0 Then e.Row.FCLiteral("LtlPrecioLista").Visible = True End If If UsuarioActual.CveEmpresa.Contiene(7, 122) AndAlso e.Row.DBCampo("NumTurnos").ToDecimal() > 0 Then e.Row.FCLiteral("LtlNumTurnos").Visible = True End If 'CANTIDAD FACTURADA Select Case e.Row.DBCampo("TipoDocto") Case "Cot" e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaCot").ToDecimal.ToString("#,##0.##") Case "Pd2" e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaPed2").ToDecimal.ToString("#,##0.##") End Select If EsCreaApartirDe Then e.Row.FCLinkButton("imgD").Visible = True e.Row.FCLinkButton("imgE").Visible = True End If 'If GvInv.Rows.Count > 0 AndAlso ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem" AndAlso e.Row.DataKey("CveVentaDetalle").ToString().ToEntero() > 0 Then ' e.Row.FCLinkButton("imgE").Enabled = False ' e.Row.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen." 'End If End If End If End Sub Protected Sub GvPS_RowEditing(sender As Object, e As EventArgs) Handles GvPS.RowEditing 'ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs ' LimpiaAgregar() Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) IndicePSActual = GvRow.RowIndex CantidadOriginal = GvRow.DataKey("Cantidad").ToDecimal TxtCantidad.Text = GvRow.DataKey("Cantidad") DdlClasificacion.SelectedValueExist(GvRow.DataKey("CveClasificacion")) If UsuarioActual.Empresa.Funcionalidad(141).ToString() = "1" Then DdlPS.txtValue.Value = GvRow.DataKey("CvePS") DdlPS.txtText.Value = GvRow.DataKey("CodigoPS") Else DdlPS.ddl.SelectedValueExist(GvRow.DataKey("CvePS")) End If TxtObsPS.Text = GvRow.DataKey("Obs") TxtPrecio.Text = GvRow.DataKey("PU") TxtCantidad.Focus() UpDVAddPS.Update() RegistraScript("$('#DVAddPS').modal();") '''************ 'GvPS.EditIndex = e.NewEditIndex 'GvPS.DataSource = TmpDT 'DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") 'GvPS.DataBind() 'If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then ' GvPS.Rows(e.NewEditIndex).FCDropDownList("DdlUnidadMedida").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCDropDownList("DdlClasificacion").Enabled = False 'End If ''SI ES LLANTERA NO DEBE BLOQUEAR EL TEXTBOX 'If GvPS.Rows(e.NewEditIndex).DataKey("CvePromocionDetalle").ToString().ToEntero() > 0 AndAlso (Not UsuarioActual.Empresa.Funcionalidad(558) = "1") Then ' GvPS.Rows(e.NewEditIndex).FCTextBox("TxtDescuento").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCTextBox("TxtDescuento").ToolTip = "No se puede editar el descuento porque viene de una promoción" 'End If 'If Me.CveVenta > 0 AndAlso UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Cot") Then ' GvPS.Rows(e.NewEditIndex).FCTextBox("TxtDescuento").Enabled = False 'End If 'If CveVenta > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ' GvPS.Rows(e.NewEditIndex).FCTextBox("TxtCantidad").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCDropDownList("DdlUnidadMedida").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCDropDownLost("DdlPS").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCDropDownLost("DdlPS").ddlWS.Attributes.Add("disabled", "disabled") ' GvPS.Rows(e.NewEditIndex).FCDropDownList("DdlUnidadMedida").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCDropDownList("DdlClasificacion").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCDropDownList("DdlProyecto").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCDropDownList("DdlSubProyecto").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCTextBox("TxtObsPS").Enabled = True ' GvPS.Rows(e.NewEditIndex).FCTextBox("TxtPrecio").Enabled = False ' GvPS.Rows(e.NewEditIndex).FCTextBox("TxtDescuento").Enabled = False 'End If End Sub 'Protected Sub GvPS_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvPS.RowCancelingEdit ' GvPS.EditIndex = -1 ' GvPS.DataSource = TmpDT ' DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") ' GvPS.DataBind() 'End Sub 'Protected Sub GvPS_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvPS.RowUpdating ' 'Dim TipoDescuento As Integer ' Dim Cantidad, PU, CantidadInventario As Decimal ' Dim ObjDescuento As New Modelos.VentaDescuentos ' Dim CuentaPredial As String ' Cantidad = GvPS.Rows(e.RowIndex).FCTextBox("TxtCantidad").Text.ToDecimal ' PU = (GvPS.Rows(e.RowIndex).FCTextBox("TxtPrecio").Text.ToDecimal).RoundSQL(6) ' Dim DescuentoManual As Decimal = (GvPS.Rows(e.RowIndex).FCTextBox("TxtDescuento").Text.ToDecimal).RoundSQL(NumeroDecimales) ' ObjDescuento.ImporteDescuento = DescuentoManual ' CuentaPredial = GvPS.Rows(e.RowIndex).FCTextBox("TxtPredial").Text.Trim ' If PU <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(558) = "1" Then ' Alert("El precio debe ser mayor a 0", TipoMensaje.MsgAdvertencia) ' Exit Sub ' End If ' If UsuarioActual.CveEmpresa = 140 OrElse DtPromociones IsNot Nothing AndAlso DtPromociones.Rows.Count > 0 Then ' ObjDescuento = CalcularDescuentos(TmpDT.Rows(e.RowIndex)("CvePS").ToString().ToEntero(), Cantidad, PU) ' End If ' 'SI ESTA HABILITADO LA OPCION DE DESCUENTO, SE AGREGO UN DESCUENTO MANUAL Y NO TIENE PROMOCION ' If GvPS.Rows(e.RowIndex).FCTextBox("TxtDescuento").Enabled AndAlso (ObjDescuento.CvePromocionDetalle <= 0 AndAlso ObjDescuento.ImporteDescuento <= 0) AndAlso DescuentoManual > 0 Then ' ObjDescuento.ImporteDescuento = DescuentoManual ' End If ' 'VERIFICA SI EL DESCUENTO SUPERA EL SUBTOTAL ' If ObjDescuento.ImporteDescuento.RoundSQL(2) > (Cantidad * PU).RoundSQL(2) Then ' Alert("El descuento no puede ser mayor al subtotal", TipoMensaje.MsgAdvertencia) ' Exit Sub ' End If ' Dim CantidadOriginal As Decimal = GvPS.Rows(e.RowIndex).DataKey("Cantidad").ToDecimal() ' Dim DatarowPS As DataRow = Nothing ' DatarowPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString().ToEntero()).FiltroPrimero("") ' Estado = -1 ' 'verifica si tiene ventaminima ' If Cantidad > 0 AndAlso DatarowPS("VentaMinima").ToString().ToDecimal > 0 AndAlso (DdlTipoComprobante.SelectedValue = "Rem" Or DdlTipoComprobante.SelectedValue = "Ing") Then ' 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... ' If Cantidad Mod DatarowPS("VentaMinima").ToString().ToDecimal <> 0 Then ' Alert(String.Format("El producto se vende solo en cantidades de {0}", DatarowPS("VentaMinima").ToString())) ' Exit Sub ' End If ' End If ' 'si es remisión, ingreso, anticipo debe de considerar el preciominimo ' If Not UsuarioActual.TienePermisoProceso(169) Then ' NO VALIDA EXISTENCIAS NI COSTO - PERMISO PARA NO VALIDAR ' Dim CvePS As Integer = DatarowPS("CvePS").ToString().ToEntero() ' Dim CveUM As Integer = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedValue.ToEntero() 'DatarowPS("CveUM").ToString().ToEntero() ' Dim CveTipoPS As Integer = DatarowPS("CveTipoPS").ToString().ToEntero() ' CantidadInventario = GvPS.Rows(e.RowIndex).DataKey("CantidadInventario").ToDecimal ' Dim CveUMInicial As Integer = GvPS.Rows(e.RowIndex).DataKey("CveUM").ToEntero ' Dim ValidaExistencia As Boolean = True ' If (CantidadInventario > 0) OrElse (Cantidad <= CantidadOriginal) Then 'si ya hay algo surtido, que no valide existencia ' ValidaExistencia = False ' End If ' If CveUM <> CveUMInicial Then ValidaExistencia = True ' 'SOLO VALIDA EXISTENCIAS Y COSTO: SI USA INVENTARIOS, SOLO PRODUCTOS TIPO PRODUCTO, SOLO REMISIONES E INGRESOS ' If UsuarioActual.Empresa.UsaInventarios AndAlso CveTipoPS = 2 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119))) Then ' Dim ObjInventarios As New ClsInventarios ' Dim Existencia As Decimal ' If ValidaExistencia Then ' Existencia = ObjInventarios.GetExistenciasPS(CvePS, CveUM, UsuarioActual.CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveVendedor:=-1, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) ' End If ' Dim Costo As Decimal = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDecimal, -1, "-1", NowADS, 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 Costo <= 0 Then Costo = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDecimal, -1, "-1", NowADS, -1, CveTipoAlmacen:=1) ' ObjInventarios.Dispose() ' Dim PrecioMinimo As Decimal = 0 ' 'RMF. condicion temporal, para reubicación, precio mínimo ' If UsuarioActual.CveEmpresa = 119 Then ' 'Dim CvePrecioLista As Integer = 38 ' Dim objPS As New ClsProductosServicios ' If objPS.GetPSSucursalesALL(CvePS, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero()) Then ' PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal ' 'If PrecioMinimo > 0 Then ' ' Costo = PrecioMinimo ' 'End If ' End If ' objPS.Dispose() ' End If ' If ValidaExistencia AndAlso DdlTipoComprobante.SelectedValue <> "Cot" AndAlso Not RegistroxOC Then ' 'VALIDA EXISTENCIA ' If UsuarioActual.CveEmpresa.Contiene({72, 80, 119, 140, 153}) Then ' 'SI ES VENTA NUEVA TOMA EN CUENTA LO DEL TMPDT ' If CveVenta <= 0 Then ' If Existencia - TmpDT.SUM("Cantidad", $"CvePS = {CvePS} AND (EntregaDirecta IS NULL OR EntregaDirecta < 1)") < TxtCantidad.Text.ToDouble Then ' Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia) ' Exit Sub ' End If ' Else ' If DdlTipoComprobante.SelectedValue = "Rem" Then ' Dim CantidadVenta As Double = 0 ' Using ObjVentas As New ClsVentas ' If ObjVentas.GetVentaDetalle(CveVenta) Then ' CantidadVenta = ObjVentas.DtResultados.SUM("Cantidad", $"CvePS = {CvePS}") ' End If ' End Using ' 'SUMA LO YA RESTADO EN PENDIENTE POR SURTIR QUE PERTENESCA A LA VENTA. ' 'PARA QUE NO RESTE LA EXISTENCIA 2 VECES Y PUEDAS COMPARAR LO REAL ' If (Existencia + CantidadVenta) - TmpDT.SUM("Cantidad", $"CvePS = {CvePS} AND (EntregaDirecta IS NULL OR EntregaDirecta < 1)") < TxtCantidad.Text.ToDouble Then ' Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia) ' Exit Sub ' End If ' End If ' End If ' End If ' End If ' 'VALIDA COSTOS ' If Not CveContrato > 0 Then ' 'BANDERAS PARA VALIDACIONES ' Dim EsValido As Boolean = False ' Dim EsValidoMayor As Boolean = False ' Dim CostoMenor As Decimal = 0 ' Dim CostoMayor As Decimal = 0 ' 'PRECIO MINIMO ' If UsuarioActual.Empresa.Funcionalidad(129).ToEntero() > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then ' '' NOTA. si tiene preciominimo, debe de validarlos e ignorar el costo, pero se debe de considerar el TC, para el costo ' If PrecioMinimo > 0 Then ' 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA ' If PU >= PrecioMinimo Then ' aqui se comparar los importes directos, sin el TC ' EsValido = True ' End If ' Else ' CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) ' '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 ' 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 ' '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
", DatarowPS("PS").ToString()) ' If TienePermisoImportes Then ' MensajeCosto.AppendFormat("El costo del producto es: ${0:#,###.00}
", Costo) ' MensajeCosto.AppendFormat("El rango menor aceptado es: {0:#,###.00}% ${1}
", UsuarioActual.Empresa.Funcionalidad(129).ToEntero(), CostoMenor) ' MensajeCosto.AppendFormat("El precio indicado es: ${0:#,###.00} ({1}% de ganancia)
", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) ' End If ' Alert(String.Format(MensajeCosto.ToString()), TipoMensaje.MsgAdvertencia) ' MensajeCosto.Clear() ' e.Cancel = True ' Exit Sub ' 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:#,###.00}
", Costo) ' MensajeCosto.AppendFormat("El rango mayor aceptado es: {0}% ${1:#,###.00}
", UsuarioActual.Empresa.Funcionalidad(133).ToEntero(), CostoMayor) ' MensajeCosto.AppendFormat("El precio indicado es: ${0:#,###.00} ({1}% de ganancia)
", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) ' End If ' Alert(MensajeCosto.ToString(), TipoMensaje.MsgAdvertencia) ' MensajeCosto.Clear() ' e.Cancel = True ' Exit Sub ' End If ' End If ' End If ' End If ' If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ObjDescuento IsNot Nothing Then ' Dim ConsecEliminar As Integer = TmpDT.Rows(e.RowIndex)("Consec").ToString().ToEntero() ' If ConsecEliminar > 0 Then ' Dim descEliminar As Modelos.VentaDescuentos = ListaDescuentos.FirstOrDefault(Function(x) x.Consec = ConsecEliminar) ' If descEliminar IsNot Nothing Then ' ListaDescuentos.Remove(descEliminar) ' End If ' End If ' End If ' If TmpDT.Rows(e.RowIndex)("CvePS").ToString() <> GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue Then ' 'eliminar y cargar el ps *** ' Dim DdlUM As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida") ' Dim DdlCla As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlClasificacion") ' If DtPromociones IsNot Nothing AndAlso DtPromociones.Rows.Count > 0 Then ' ObjDescuento = CalcularDescuentos(GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue.ToEntero(), Cantidad, PU) ' End If ' Dim NumTurnos As Decimal = 0 ' If UsuarioActual.CveEmpresa.Contiene(7, 122) Then ' NumTurnos = GvPS.Rows(e.RowIndex).FCTextBox("TxtNumTurnosEditar").Text.ToDecimal() ' End If ' TmpDT.Rows.Remove(TmpDT.Rows(e.RowIndex)) ' 'CalculaUsados() ' AgregarProductoServicio(Cantidad, DdlUM.SelectedValue.ToEntero(), DdlUM.SelectedItem.Text, DdlCla.SelectedValue.ToEntero(), DdlCla.SelectedItem.Text, ' GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue.ToEntero(), GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedText, ' GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.Trim, PU, ObjDescuento.ImporteDescuento, ' GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedValue.ToEntero(), GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text, ' GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue.ToEntero(), GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text, ' CuentaPredial:=CuentaPredial, CveVentaDetalle:=GvPS.Rows(e.RowIndex).DataKey("CveVentaDetalle").ToString().ToEntero(), SeActualiza:=True, CvePromocionDetalle:=ObjDescuento.CvePromocionDetalle, ' ObjDescuento:=ObjDescuento, NumTurnos:=NumTurnos) ' ' TmpDT.Rows(e.RowIndex)("CveUM") = Ddl.SelectedValue ' ' TmpDT.Rows(e.RowIndex)("UM") = Ddl.SelectedItem.Text ' GvPS.EditIndex = -1 ' GvPS.DataSource = TmpDT ' DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") ' GvPS.DataBind() ' Else ' Dim DrPS As DataRow = Nothing ' DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString().ToEntero()).FiltroPrimero("") ' If Not ClienteDesglosaIEPS Then ' PU = PU * (1 + DrPS("IEPSPorcentaje").ToString().ToDecimal) ' TmpDT.Rows(e.RowIndex)("PorcentajeIEPS") = 0 ' End If ' Dim TotalCalculableImpuestos As Decimal = ((Cantidad * PU) - (ObjDescuento.ImporteDescuento)) ' Dim TotalCalculableImpuestosIVA As Decimal = 0 ' TotalCalculableImpuestosIVA = TotalCalculableImpuestos * (1 + TmpDT.Rows(e.RowIndex)("PorcentajeIEPS").ToString().ToDecimal) ' Dim ClienteRetIVA As Decimal = Me.ClienteRetIVA ' If ClienteRetIVA <= 0 Then ' If DdlTipoRetencion.SelectedValue.Contiene("1", "2") Then ' ClienteRetIVA = 0.106667D ' ElseIf DdlTipoRetencion.SelectedValue.Contiene("3") Then ' ClienteRetIVA = 0.04D ' End If ' End If ' If DrPS("IVA").ToString().Contiene("-1", "") Then ' TmpDT.Rows(e.RowIndex)("PorcentajeIVA") = PorcentajeIVA ' Else ' TmpDT.Rows(e.RowIndex)("PorcentajeIVA") = DrPS("IVA") ' End If ' If UsuarioActual.Empresa.Funcionalidad(373) = "1" AndAlso LblRFC.Text = "XEXX010101000" Then ' TmpDT.Rows(e.RowIndex)("PorcentajeIVA") = 0 ' TmpDT.Rows(e.RowIndex)("ImporteIVA") = 0 ' End If ' TmpDT.Rows(e.RowIndex)("CveUM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedValue.ToEntero() ' TmpDT.Rows(e.RowIndex)("UM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedItem.Text ' TmpDT.Rows(e.RowIndex)("Cantidad") = Cantidad ' TmpDT.Rows(e.RowIndex)("Obs") = GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.TrimEnd ' TmpDT.Rows(e.RowIndex)("TiempoEntrega") = GvPS.Rows(e.RowIndex).FCTextBox("TxtTiempoEntrega").Text.Trim ' TmpDT.Rows(e.RowIndex)("PU") = PU ' TmpDT.Rows(e.RowIndex)("Descuento") = ObjDescuento.ImporteDescuento ' TmpDT.Rows(e.RowIndex)("Total") = (Cantidad * PU) ' TmpDT.Rows(e.RowIndex)("TotalImporte") = (Cantidad * PU).RoundSQL(NumeroDecimales) ' TmpDT.Rows(e.RowIndex)("ImporteIVA") = (TmpDT.Rows(e.RowIndex)("PorcentajeIVA").ToString().ToDecimal * TotalCalculableImpuestosIVA).RoundSQL(NumeroDecimales) ' TmpDT.Rows(e.RowIndex)("ImporteIEPS") = (TmpDT.Rows(e.RowIndex)("PorcentajeIEPS").ToString().ToDecimal * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) ' TmpDT.Rows(e.RowIndex)("ImporteRetIVA") = (ClienteRetIVA * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) ' TmpDT.Rows(e.RowIndex)("RetIVA") = (ClienteRetIVA * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) ' TmpDT.Rows(e.RowIndex)("ImporteRetISR") = (ClienteRetISR * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) ' TmpDT.Rows(e.RowIndex)("PorcentajeRetIVA") = ClienteRetIVA ' TmpDT.Rows(e.RowIndex)("PorcentajeRetISR") = ClienteRetISR ' TmpDT.Rows(e.RowIndex)("CuentaPredial") = CuentaPredial ' Dim NumTurnos As Decimal = 0 ' If UsuarioActual.CveEmpresa.Contiene(7, 122) Then ' NumTurnos = GvPS.Rows(e.RowIndex).FCTextBox("TxtNumTurnosEditar").Text.ToDecimal() ' End If ' TmpDT.Rows(e.RowIndex)("NumTurnos") = NumTurnos ' If ObjDescuento IsNot Nothing Then ' TmpDT.Rows(e.RowIndex)("CvePromocionDetalle") = ObjDescuento.CvePromocionDetalle ' End If ' If GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").Items.Count = 0 Then ' TmpDT.Rows(e.RowIndex)("Proyecto") = "Sin Proyecto Asignado" ' TmpDT.Rows(e.RowIndex)("CveSubProyecto") = -1 ' Else ' TmpDT.Rows(e.RowIndex)("Proyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text ' End If ' If GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").Items.Count = 0 Then ' TmpDT.Rows(e.RowIndex)("SubProyecto") = "Sin SubProyecto Asignado" ' Else ' 'si está visible en el encabezado, si no esta visible que no actualice, porque generar error, selecciona el primer item ' TmpDT.Rows(e.RowIndex)("SubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text ' TmpDT.Rows(e.RowIndex)("CveSubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue ' End If ' 'RELACIONAL PS CON EL DESCUENTO ' If ObjDescuento IsNot Nothing Then ' ObjDescuento.Consec = TmpDT.Rows(e.RowIndex)("Consec").ToString().ToEntero() ' End If ' DrPS = Nothing ' GvPS.EditIndex = -1 ' GvPS.DataSource = TmpDT ' DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") ' GvPS.DataBind() ' End If ' If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ObjDescuento IsNot Nothing Then ' ListaDescuentos.Add(ObjDescuento) ' End If ' CalculaTotalesVenta() ' UpPS.Update() 'End Sub Protected Sub GvPS_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvPS.RowDeleting If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing Then Dim ConsecEliminar As Integer = TmpDT.Rows(e.RowIndex)("Consec").ToString().ToEntero() If ConsecEliminar > 0 Then Dim descEliminar As Modelos.VentaDescuentos = ListaDescuentos.FirstOrDefault(Function(x) x.Consec = ConsecEliminar) If descEliminar IsNot Nothing Then ListaDescuentos.Remove(descEliminar) End If End If End If Dim DbRow As DataRow = Nothing DbRow = TmpDT.Rows(e.RowIndex) TmpDT.Rows.Remove(DbRow) 'CalculaUsados() GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() 'CargaGVInv(DtInv) CalculaTotalesVenta() Alert("Eliminado Correctamente.", TipoMensaje.MsgInformacion) 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") End Sub #End Region #Region " EMITIR IMPRIMIR - GUARDAR " Protected Sub BtnEmitirImprimir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitirImprimir.Click Try EmitirImprimir() Catch ex As Exception OnError(ex.ToString(), ex) End Try End Sub Private Sub EmitirImprimir(Optional TipoDoctoViejo As String = "") DtRemisionesTmpDT = TmpDT.Copy DtPedidos2TmpDT = TmpDT.Copy DtCotizacionTmpDT = TmpDT.Copy DtOCTmpDT = TmpDT.Copy TmpDTError = TmpDT.Copy If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "Egs", "Dev") Then If RegimenFiscalCliente.Contiene("-1", "") Then Alert("El cliente no tiene asignado un régimen fiscal.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlUsoCFDI.SelectedValue.ToEntero() <= 0 Then Alert("No se ha seleccionado el Uso CFDI o el cliente no tiene asignado el correcto.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Egs", "Dev") Then If LblRFC.Text.Trim().ToUpper().Contiene("XAXX010101000", "XEXX010101000") AndAlso RegimenFiscalCliente <> "616" Then Alert("El Regimen fiscal del cliente debe ser '616 - Sin obligaciones fiscales' cuando se utiliza el RFC genérico.", TipoMensaje.MsgAdvertencia) Exit Sub End If If LblRFC.Text.Trim().ToUpper().Contiene("XAXX010101000", "XEXX010101000") AndAlso DdlUsoCFDI.SelectedValue <> "23" Then Alert("El uso cfdi del cliente debe ser 'S01 - Sin efectos fiscales' cuando se utiliza el RFC genérico.", TipoMensaje.MsgAdvertencia) Exit Sub End If If Not LblRFC.Text.Trim().ToUpper().Contiene("XAXX010101000", "XEXX010101000") AndAlso RegimenFiscalCliente = "616" Then Alert("El Regimen fiscal del cliente no puede ser '616 - Sin obligaciones fiscales' si no se utiliza el RFC genérico.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim EsPersonaMoral As Boolean = Me.TipoPersona Dim DtUsosCFDI As DataTable = GlobalDTSATUsosCFDI(If(Not EsPersonaMoral, 1, 0), RegimenFiscalReceptor:=RegimenFiscalCliente).FiltraParametros($"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") If DtUsosCFDI.Rows.Count = 0 Then Alert("El Uso CFDI no corresponde con el tipo de persona (fisca, moral) y el régimen fiscal.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If Not ValidaImportePublicoGeneral() Then Exit Sub End If If (Me.FacturarSucursal AndAlso DdlSucursalCliente.SelectedValue.ToEntero() > 0 AndAlso (Me.ClienteSucursal IsNot Nothing AndAlso String.IsNullOrEmpty(Me.ClienteSucursal.RFC))) Then Alert("La sucursal no tiene asignada un RFC.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VALIDACIONES If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia) Exit Sub End If If TmpDT Is Nothing OrElse TmpDT.Rows.Count = 0 Then Alert("Es necesario tener al menos un concepto registrado.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'Subproyecto Obligatorio If UsuarioActual.Empresa.Funcionalidad(120) = "1" AndAlso TmpDT.FiltraParametros("ISNULL(CveSubProyecto,0) <= 0").Rows.Count > 0 Then Alert("El Subproyecto de los conceptos es obligatorio, Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VENDEDOR OBLIGATORIO If -1 <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then Alert("Debe seleccionar un vendedor.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'SI TIENE ANTICIPOS Y ESTA AMORTIZADO AL 100% EL DOCUMENTO (SALDO = 0) | NO VALIDA PU DEL CONCEPTO If Not (LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0) Then If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then If UsuarioActual.CveEmpresa.Contiene(72, 80) Then If TmpDT.FiltraParametros($"TotalImporte = 0").Rows.Count > 0 Then Alert("El importe de cada concepto debe ser mayor a cero. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If End If Dim CveContratoTipo As Integer = 0 If CveContrato > 0 Then Dim ObjContrato As New ClsContratos If ObjContrato.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then If ObjContrato.DtResultados.Rows.Count > 0 Then CveContratoTipo = ObjContrato.DtResultados.Rows(0)("CveContratoTipo").ToString().ToEntero() End If End If ObjContrato.Dispose() End If Me.CveAutorizacion = -1 'SI ES A CREDITO DEBE VERIFICAR SI TIENE AUTORIZACIONES If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso CveCliente > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs") Then Dim TipoDocumentoAutorizacion As String = "" Dim ImporteAutorizacion As Decimal = 0 Dim TipoAutorizacion As Integer = 0 Dim DiasVencidosAutorizacion As Integer = 0 Dim CveVendedor As Integer = -1 Dim ObjVentas As New ClsVentas ObjVentas.Dispose() If TipoDocumentoAutorizacion = "Ing" Then If TipoAutorizacion = 1 Then If TieneDiasVencidos Then CveAutorizacion = -1 Alert($"El crédito no esta autorizado. El cliente tiene días vencidos", TipoMensaje.MsgAdvertencia) Exit Sub End If If ImporteAutorizacion < TxtTotal.Text.ToDecimal() Then Dim BloquearCredito As Boolean = True CveAutorizacion = -1 'VERIFICA SI TIENE CREDITO DISPONIBLE DENTRO DEL CLIENTE Dim ObjCred As New ClsVentas If ObjCred.ObtenerCreditoRestante(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero()) AndAlso ObjCred.DtResultados.Rows.Count > 0 Then 'SI TIENE CREDITO DISPONIBLE NO BLOQUEAR AUNQUE LA AUTORIZACION NO TENGA EL IMPORTE DEL DOCUMENTO If DdlSucursalCliente.SelectedValue.ToEntero() > 0 Then If (ObjCred.DtResultados(0)("LimiteRestanteSucursal").ToString().ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal)) > 0 Then BloquearCredito = False End If Else If (ObjCred.DtResultados(0)("LimiteRestanteCliente").ToString().ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal)) > 0 Then BloquearCredito = False End If End If End If ObjCred.Dispose() If BloquearCredito Then Alert($"El crédito autorizado es insuficiente. Crédito Disponible:{ImporteAutorizacion:N2}", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If 'If TipoAutorizacion = 2 Then ' If DiasVencidosCliente > DiasVencidosAutorizacion Then ' CveAutorizacion = -1 ' Alert($"El crédito no esta autorizado. Los días vencidos del cliente son mayores a lo autorizado", TipoMensaje.MsgAdvertencia) ' Exit Sub ' End If 'End If 'SI NO SE ENCONTRO NINGUA AUTORIZACION If TipoAutorizacion = 0 Then If TieneDiasVencidos Then CveAutorizacion = -1 Alert($"El crédito no esta autorizado. El cliente tiene días vencidos", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If If TieneDiasVencidos AndAlso DdlTipoComprobante.SelectedValue = "Egs" AndAlso CveAutorizacion <= 0 Then CveAutorizacion = -1 Alert($"El crédito no esta autorizado. No tiene autorización para generar notas de crédito. El cliente tiene días vencidos", TipoMensaje.MsgAdvertencia) Exit Sub End If If TipoDocumentoAutorizacion = "Egs" Then If TipoAutorizacion = 1 Then If ImporteAutorizacion < TxtTotal.Text.ToDecimal() Then CveAutorizacion = -1 Alert($"El crédito autorizado es insuficiente. Crédito Disponible:{ImporteAutorizacion:N2}", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If End If 'SI TIENE LINEA ADICIONAL NO VERIFICAR LIMITE DE CREDITO 'SI NO TIENE AUTORIZACION VERIFICAR LIMITE DE CREDITO Y CANDADOS DE VENTA 'No exceder el limite de credito, Si no tiene contrato limita el credito, si tiene no hace nada. Si no tiene remisiones tampoco hace nada. 'If DdlLineaAdicional.SelectedValue.ToEntero() <= 0 AndAlso Me.CveAutorizacion <= 0 AndAlso (Not CveContrato > 0 Or CveContratoTipo.Contiene(28)) AndAlso (Not NuevaFactura = 1) AndAlso RBLPago.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso RemisionesLista.Count <= 0 AndAlso TxtTotal.Text.ToDecimal > 0 AndAlso Not CvePedidoA > 0 Then ' 'If UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then ' If Not UsuarioActual.Empresa.Funcionalidad(702) = "1" Then ' Dim ObjVentas As New ClsVentas ' If ObjVentas.ObtenerCreditoRestante(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero()) Then ' If ObjVentas.DtResultados.Rows.Count > 0 Then ' If DdlSucursalCliente.SelectedValue.ToEntero() > 0 Then ' If ObjVentas.DtResultados(0)("LimiteRestanteSucursal").ToString().ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then ' ObjVentas.Dispose() ' Alert("Se está excediendo el límite de credito permitido de la Sucursal del Cliente.", TipoMensaje.MsgInformacion) ' Exit Sub ' End If ' Else ' If ObjVentas.DtResultados(0)("LimiteRestanteCliente").ToString().ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then ' ObjVentas.Dispose() ' Alert("Se está excediendo el límite de credito permitido del Cliente.", TipoMensaje.MsgInformacion) ' Exit Sub ' End If ' End If ' Else ' ObjVentas.Dispose() ' Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError) ' Exit Sub ' End If ' Else ' ObjVentas.Dispose() ' Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError) ' Exit Sub ' End If ' ObjVentas.Dispose() ' 'VERIFICA SI TIENE BLOQUEO POR DIAS VENCIDOS ' If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ' Dim Vta As New ClsVentas ' Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa, TipoVerificacion:=2) ' Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón:

{0}", Vta.SerieVenta) ' Vta.Dispose() ' If Opcion = 2 Then ' Alert(OpcionMsg, TipoMensaje.MsgError) ' Exit Sub ' End If ' End If ' End If ' 'End If 'End If 'VALIDA PRECIO AL AGREGAR A ALMACEN If Not UsuarioActual.TienePermisoProceso(169) Then If (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") AndAlso NuevaFactura <> 1) Or (DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119)) Then Dim MensajeCosto As New StringBuilder Dim CostoMenor As Decimal = 0.0D Dim CostoMayor As Decimal = 0.0D Dim Costo As Decimal = 0.0D Dim EsValido As Boolean = False 'BANDERA Dim EsValidoMayor As Boolean = False Dim EsValidoPU As Boolean = True 'SOLO SE VALIDA CUANDO EL TXTPU = 0 Y LO INVALIDA ALGUNA PROMOCION 'VALIDA PROMOCIONES Y EXISTENCIAS Dim ObjVentas As New ClsVentas If ObjVentas.GetPromocionesPS(-1, NowADS, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveCliente, -1, 1, UsuarioActual.CveEmpresa) Then DtPromociones = ObjVentas.DtResultados End If ObjVentas.Dispose() Dim ObjInventarios As New ClsInventarios Dim PU As Decimal = 0.0D Dim Cantidad As Double Dim CveUnidad As Integer Dim CveProducto As Integer Dim Existencia As Double ' Dim CveAlmacen As Integer = ddlAlmacen.SelectedValue.ToEntero() For Each dr As DataRow In TmpDT.FiltraParametros("CveTipoPS = 2").Rows If DdlTipoComprobante.SelectedValue <> "Cot" Then 'VALIDA EXISTENCIA CveProducto = dr("CvePS").ToString().ToEntero() CveUnidad = dr("CveUM").ToString().ToEntero() Cantidad = TmpDT.SUM("Cantidad", $"CvePS = {CveProducto} AND (EntregaDirecta IS NULL OR EntregaDirecta < 1)") 'VALIDA CONTRA LA SUMA DEL MISMO PS If UsuarioActual.Empresa.UsaInventarios AndAlso RemisionesLista.Count < 1 AndAlso dr("EntregaDirecta").ToString().ToEntero() < 1 Then Existencia = ObjInventarios.GetExistenciasPS(CveProducto, CveUnidad, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveVendedor:=-1, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) If Existencia < Cantidad Then MensajeCosto.AppendFormat("
El Producto {0}. No cuenta con la cantidad suficiente en inventario. Cuenta con {1}.", dr("CodigoPS").ToString(), Existencia.FormatoNumero(2)) Continue For End If End If End If EsValido = False EsValidoMayor = False EsValidoPU = True PU = dr("PU").ToString().ToDecimal * If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.ToDecimal) Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString().ToEntero(), dr("Cantidad").ToString().ToDecimal, -1, "-1", NowADS, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveTipoAlmacen:=1) Dim PrecioMinimo As Decimal = 0 'RMF. condicion temporal, para reubicación, precio mínimo If UsuarioActual.CveEmpresa = 119 Then 'Dim CvePrecioLista As Integer = 38 Dim objPS As New ClsProductosServicios If objPS.GetPSSucursalesALL(dr("CvePS").ToString().ToEntero(), UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero()) Then PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal 'If PrecioMinimo > 0 Then ' Costo = PrecioMinimo 'End If End If objPS.Dispose() End If 'PRECIO MINIMO If UsuarioActual.Empresa.Funcionalidad(129).ToEntero() > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then '' NOTA. si tiene preciominimo, debe de validarlos e ignorar el costo, pero se debe de considerar el TC, para el costo If PrecioMinimo > 0 Then 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA If PU >= PrecioMinimo Then ' aqui se comparar los importes directos, sin el TC EsValido = True End If Else CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) '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 End If Else EsValido = True End If If UsuarioActual.Empresa.Funcionalidad(133).ToEntero() > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo) 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA If PU <= CostoMayor Then EsValidoMayor = True End If Else EsValidoMayor = True End If 'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR If Not EsValido Or PU = 0 Then If DtPromociones.FiltraParametros($"CvePS = {dr("CvePS").ToString().ToEntero()}").Rows.Count > 0 Then If PU * If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {dr("CvePS").ToString().ToEntero()}").ToDecimal Then EsValido = True Else EsValidoPU = False ' SI NO ENTRA DENTRO DE LA PROMOCION NO SE PUEDE VENDER A 0 End If Else EsValidoPU = False ' SI NO TIENE PROMOCION NO SE PUEDE VENDER A 0 End If End If 'NO DEJA REGISTRAR CON VALIDACION DE COSTO ALMACEN O PROMOCION Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) If Not EsValido Then MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio menor de su Costo ni a un precio mayor de su rango aceptado
", dr("PS").ToString()) If TienePermisoImportes Then MensajeCosto.AppendFormat("El costo del producto es: {0:#,###.00}$
", Costo) MensajeCosto.AppendFormat("El rango menor aceptado es: {0} {1:#,###.00}$
", UsuarioActual.Empresa.Funcionalidad(129).ToEntero(), CostoMenor) MensajeCosto.AppendFormat("El precio indicado es: {0:#,###.00}$ ({1}% de ganancia)
", PU.FormatoNumero, If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)) End If End If If Not EsValidoMayor Then MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio mayor de su rango aceptado
", dr("PS").ToString()) If TienePermisoImportes Then MensajeCosto.AppendFormat("El costo del producto es: {0:#,###.00}$
", Costo) MensajeCosto.AppendFormat("El rango mayor aceptado es: {0} {1:#,###.00}$
", UsuarioActual.Empresa.Funcionalidad(133).ToEntero(), CostoMayor) MensajeCosto.AppendFormat("El precio indicado es: {0:#,###.00}$ ({1}% de ganancia)
", PU.FormatoNumero, If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)) End If End If ' SOLO SI TIENE LA FUNCIONALIDAD DE RESTRICCION VALIDA EL IMPORTE CERO If UsuarioActual.Empresa.Funcionalidad(139).ToString().ToEntero() > 0 Then If Not EsValidoPU Then MensajeCosto.AppendFormat($"El producto {dr("PS").ToString()}. No se puede vender a un importe de cero ($0)", TipoMensaje.MsgAdvertencia) End If End If Next ObjInventarios.Dispose() If MensajeCosto.ToString().Length > 1 Then Alert(MensajeCosto.ToString(), TipoMensaje.MsgAdvertencia) MensajeCosto.Clear() Exit Sub End If End If End If 'Valida si en caso de que el detalle tenga llantas o polizas se agreguén kilometraje/serie en la parte de observaciones(solo para el caso de empresas llanteras) If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then If TxtObsFact.Text = "" Then Dim FaltaObservacion As Integer = -1 FaltaObservacion = TmpDT.FiltroPrimeroValor("CveClasificacion", "CveClasificacion = 20345").ToEntero() 'cuando es la clasificacion de polizas If FaltaObservacion = 20345 Then Alert("No se ha especificado la serie para la poliza en la sección de Observaciones", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If If UsuarioActual.Empresa.Funcionalidad(135) = "1" And DdlTipoComprobante.SelectedValue = "Cot" Then Alert("Se mando autorización al supervisor.", TipoMensaje.MsgInformacion) MandarCorreoSupervisor = True Dim CorreoSupervisor As String = "" Dim Objeto As New ClsVtaVendedores Dim DTSupervisores As New DataTable If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then DTSupervisores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", -1)) 'Verifico si el supervisor tiene correo para proceder If DTSupervisores.Rows.Count > 0 Then CorreoSupervisor = DTSupervisores.Rows(0)("CorreoSupervisor").ToString() End If End If DTSupervisores.Dispose() Objeto.Dispose() If MandarCorreoSupervisor = True And CorreoSupervisor <> "" Then ViewState("Mail") = CorreoSupervisor End If MandarCorreoSupervisor = False End If If RequiereOC AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Ing") AndAlso Not CveDevolucion > 0 Then If Not CargaDocumentoOC Then Alert("Tiene que cargar un archivo de orden de compra", TipoMensaje.MsgAdvertencia) Exit Sub End If If TxtOrdenCompra.Text.Trim = "" Then Alert("Tiene que especificar un folio de orden de compra", TipoMensaje.MsgAdvertencia) Exit Sub End If End If 'If DivAlmacen.Visible AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Dev") AndAlso GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked) > 0 AndAlso ddlAlmacen.SelectedValue.ToEntero() <= 0 Then ' Alert("Tiene que seleccionar un almacén para la salida de almacén", TipoMensaje.MsgAdvertencia) ' Exit Sub 'End If EmitirImprimirNew(TipoDoctoViejo) End Sub #End Region #Region " NNNNEEEEEEEWWWWWW " Private Sub InicializaImprimirNew() Dim Archivo As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) Dim Archivo2 As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) Dim ArchivoSti As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.mrt", UsuarioActual.Empresa.Ruta)) Dim ArchivoSti2 As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.mrt", UsuarioActual.Empresa.Ruta)) Dim ArchivoSti3 As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.mrt", UsuarioActual.Empresa.Ruta)) UpnTools.Update() End Sub Protected Sub EmitirImprimirNew(Optional TipoDoctoViejo As String = "") 'If Not ValidaVentaContratoObra() Then ' Exit Sub 'End If 'If ValidaPagosContado(TipoDoctoViejo:=TipoDoctoViejo) Then ' Exit Sub 'End If 'validaciones, si es Anticipo solo permitir "servicios de facturación" y si es ingreso todos menos serv. factu If UsuarioActual.CveEmpresa = 119 Then If DdlTipoComprobante.SelectedValue = "Ing" Then Dim tCont As Integer = TmpDT.FiltraParametros("SATClaveProdServ='84111506'").Rows.Count If tCont > 0 Then Alert("Existen productos con código SAT '84111506' no permitido al facturar ingresos.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If DdlTipoComprobante.SelectedValue = "Ant" Then Dim tCont As Integer = TmpDT.FiltraParametros("SATClaveProdServ<>'84111506'").Rows.Count If tCont > 0 Then Alert("Al facturar 'Anticipos' solo son permitidos código SAT '84111506'.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If 'CREA UNA COPIA DE SEGURIDAD PARA LOS DATOS DEL TMPDT If TmpDTError Is Nothing OrElse TmpDTError.Rows.Count = 0 Then TmpDTError = TmpDT.Copy() End If If UsuarioActual.CveRol = 1 AndAlso UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso TbDescuentosAdicionales.Visible Then If LblDescuentoAdicional.Text.ToDecimal() > 0 Then Dim TotalDescuento As Decimal = LblDescuentoAdicional.Text.ToDecimal() / (1D + TmpDT.MAX("PorcentajeIVA").ToString().ToDecimal()) Dim RowDescuentos As DataRow() = TmpDT.Select("Descuento > 0") If RowDescuentos IsNot Nothing Then Dim Row As DataRow = RowDescuentos(0) Row("Descuento") = Row("Descuento").ToString().ToDecimal() + TotalDescuento Dim TotalCalculableImpuestos As Decimal = (Row("Cantidad").ToString().ToDecimal() * Row("PU").ToString().ToDecimal()) - Row("Descuento").ToString().ToDecimal() Row("ImporteIVA") = (TotalCalculableImpuestos * Row("PorcentajeIVA").ToString().ToDecimal()).RoundSQL(2) CalculaTotalesVenta(RecalcularTotalOriginal:=False) 'UpPS.Update() 'VALIDA EL CALCULO DE LOS DESCUENTOS If (LblTotalOriginal.Text.ToDecimal() - LblDescuentoAdicional.Text.ToDecimal()) <> TxtTotal.Text.ToDecimal() Then TmpDT = TmpDTError.Copy() CalculaTotalesVenta(RecalcularTotalOriginal:=False) Alert("Ocurrió un error al procesar los datos de la Venta. Los descuentos no coinciden con el importe final", TipoMensaje.MsgError) Exit Sub End If End If End If End If CreaObjetosVenta(TipoDoctoViejo:=TipoDoctoViejo) If ObjFactura Is Nothing OrElse (ObjFactura.Cliente Is Nothing And Not CveEmpresaCRM > 0) Then Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError) ObjFactura = Nothing Exit Sub End If If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then If UsuarioActual.CveEmpresa.Contiene(72, 80) Then If ObjFactura.SubTotal <= 0 Then Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If If ObjFactura.CveCliente > 0 Or CveEmpresaCRM > 0 Then If TmpDT.Rows.Count > 0 Then Dim ObjVentas As New ClsVentas() Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) Dim ObjContr As New ClsContratos(ObjVentas.IniciaTransacSQL()) Dim ObjOS As New ClsOS(ObjVentas.IniciaTransacSQL()) Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) Dim ObjClientes As New ClsClientes(ObjVentas.IniciaTransacSQL()) Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) Dim ObjDocCliente As New ClsEdocumentacion(ObjVentas.IniciaTransacSQL()) Dim ObjGeneral As New ClsGenerales(ObjVentas.IniciaTransacSQL()) Dim ObjAcum As New ClsAcumuladores(ObjVentas.IniciaTransacSQL()) 'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) ErrorList = New List(Of String) MensajeAlert = New StringBuilder 'GUARDA VENTA Dim TieneAnticipo As Boolean = False Dim CveAnticipoPadre As Integer = 0 ' vinculación con anticipo Dim FolioFiscalRelacionado As String = "" 'If GVAnticipos.Rows.Count > 0 Then ' Dim actualindex As Integer = 0 ' For Each row2 As GridViewRow In GVAnticipos.Rows ' If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then ' TieneAnticipo = True ' CveAnticipoPadre = row2.DataKey("CveVenta").ToEntero() ' CveAnticipo = CveAnticipoPadre ' 'CUANDO ES REFACTURACION DEBE RELACIONAR CON LA FACTURA REFACTURADA ' If NuevaFactura <> 1 Then ' ObjFactura.CveVentaRelacion = CveAnticipoPadre 'relaciona al anticipo ' ObjFactura.ImporteRelacion = row2.FCTextBox($"TxtAnticipo{actualindex}").Text.ToDecimal ' FolioFiscalRelacionado = row2.DataKey("FolioFiscal") ' ObjFactura.CveVentaPadre = row2.DataKey("CveVenta").ToEntero() ' Else ' ObjFactura.CveVentaRelacion = CveDevolucion ' End If ' End If ' actualindex = actualindex + 1 ' Next 'End If Dim EsNCAmortizacion As Boolean = False Dim CveVentaAnterior As Integer = Me.CveVenta Dim CveTimbreCartaPorte As Integer = -1 GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjAcum, ObjContr, ObjFactura, TmpDT, ObjFactura.CveNCaVincular, ObjBancos, ObjOS, ObjEventos, ObjCGame, ObjClientes, EsNCAmortizacion:=EsNCAmortizacion, CveAnticipoPadre:=CveAnticipoPadre) 'If ErrorList.Count = 0 AndAlso ChkEmitirCartaPorte.Checked AndAlso ObjFactura.TipoDocto = "Ing" Then ' CveTimbreCartaPorte = GuardarCartaPorte(ObjFactura, ObjGeneral, ObjClientes) ' If CveTimbreCartaPorte <= 0 Then ' ErrorList.Add("Ocurrió un error al registrar la carta porte") ' End If 'End If 'Agregamos las OCs a la tabla If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 AndAlso DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then Dim CveVentaDetalle As Integer = 0 Dim CveOrdenCompraDetalle As Integer = 0 Dim Cantidad As Decimal = 0 For Each row As DataRow In TmpDT.Rows Cantidad = row("Cantidad").ToString().ToDecimal CveVentaDetalle = row("CveVentaDetalle").ToString().ToEntero() CveOrdenCompraDetalle = row("CveOrdenCompraDetalle").ToString().ToEntero() If Not ObjVentas.AgregarVentaOCDetalle(CveVentaDetalle, CveOrdenCompraDetalle, Cantidad) Then ErrorList.Add("Ocurrió un Error al agregar el detalle de la Remision") Exit For End If Next End If If Not String.IsNullOrEmpty(TipoDoctoViejo) Then 'SI VIENE DE UNA AUTORIZACION If TipoDoctoViejo = "PA" Then If Not ObjEventos.AddEventoBitacora(String.Format("Se generó una remisión en Folio: {1}", ObjFactura.CveVenta, ObjFactura.SerieFolio), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVentaAnterior) Then ErrorList.Add("Ocurrió un error al agregar la bitacora de Póliza Virtual.") End If End If End If 'SI ES REFACTURACION Dim ObjNC As List(Of Object) = Nothing If ErrorList.Count = 0 Then If NuevaFactura = 1 Then 'SI YA ESTA MARCADA LA VENTA ANTERIOR If DevolucionAlmacenNC = 2 Then If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then ErrorList.Add("No se pudo Cancelar el movimiento de almacen de la Factura") End If 'MARCAR VENTA ANTERIOR If Not ObjInventario.ActualizarEsDevolucionVenta(CveDevolucion, 2) Then ErrorList.Add("No se pudo Cancelar el movimiento de almacen de la Factura") End If Else 'MARCA LO PENDIENTE A NIVEL DETALLE Dim DtMovDetalles As DataTable = Nothing If ObjInventario.GetSaldoVentaDetalle(CveDevolucion, UsuarioActual.CveEmpresa) Then DtMovDetalles = ObjInventario.DtResultados.Copy() Else ErrorList.Add("No se pudo verificar los movimientos de almacen de la factura") End If 'MARCAR VENTA ANTERIOR If Not ObjInventario.ActualizarEsDevolucionVenta(CveDevolucion, 2) Then ErrorList.Add("No se pudo Cancelar el movimiento de almacen de la Factura") End If If DtMovDetalles IsNot Nothing Then Dim CantidadTotal As Decimal = 0 Dim TotalSalida As Decimal = 0 For Each Row As DataRow In DtMovDetalles.Rows Dim Cantidad As Decimal = Row("Cantidad").ToString().ToDecimal() Dim SaldoAlmacen As Decimal = Row("SaldoAlmacen").ToString().ToDecimal() CantidadTotal += Cantidad If SaldoAlmacen < 0 AndAlso Cantidad = Math.Abs(SaldoAlmacen) Then TotalSalida += Math.Abs(SaldoAlmacen) If Not ObjInventario.UpdateEstatusAlmacen(Row("CveVentaDetalleNueva").ToString().ToEntero(), 1) Then ErrorList.Add("No se pudo actualizar el movimiento de almacen de la factura") End If End If Next 'SI SE VERIFICA QUE TODO ESTA SURTIDO, SE MARCA TODA LA FACTURA If CantidadTotal = TotalSalida Then If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then ErrorList.Add("No se pudo Cancelar el movimiento de almacen de la Factura") End If End If End If DtMovDetalles.Dispose() End If End If End If 'SI ES AMORTIZACION 3.3 'Dim ListaNotasCreditoGeneradas As New List(Of Modelos.Factura) Dim NCDescuento As Boolean = ((ListaNCDesc IsNot Nothing AndAlso ListaNCDesc.Count > 0) OrElse (ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0)) Dim SerieFolioNCProntoPago As String = "" Dim CveVentaNCProntoPago As Integer = -1 ''SOLO GENERAR NC POR DESCUENTO PRONTO PAGO SI EL PAGO ES DE CONTADO 'If ErrorList.Count = 0 AndAlso RBLPago.SelectedValue = "2" AndAlso ObjFactura.DescuentoProntoPago > 0 Then ' Dim ImportePagado As Decimal = DtPagos.SUMD("Importe") ' Dim ImporteRNC As Decimal = LblDescuentosRNC.Text.ToDecimal() ' If (ImportePagado + ImporteRNC + ObjFactura.DescuentoProntoPago) >= ObjFactura.Total Then ' Dim RespFacturaProntoPago As Modelos.MensajeProntoPago = GenerarNCProntoPago(ObjVentas.IniciaTransacSQL(), ObjClientes, ObjFactura) ' If RespFacturaProntoPago.ObjFacturaProntoPago Is Nothing OrElse RespFacturaProntoPago Is Nothing Then ' ErrorList.Add("No se pudo generar la nota de crédito de pronto pago") ' Else ' If RespFacturaProntoPago.Mensaje.CveVenta <= 0 OrElse RespFacturaProntoPago.Mensaje.TieneError Then ' ErrorList.Add("No se pudo generar la nota de crédito de pronto pago") ' Else ' CveVentaNCProntoPago = RespFacturaProntoPago.Mensaje.CveVenta ' SerieFolioNCProntoPago = RespFacturaProntoPago.Mensaje.SerieFolio ' ListaNotasCreditoGeneradas.Add(RespFacturaProntoPago.ObjFacturaProntoPago) ' End If ' End If ' Else ' ErrorList.Add("No se pudo generar la nota de crédito de pronto pago, no coiciden los pagos con el total a pagar de la factura") ' End If 'End If If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ErrorList.Count = 0 AndAlso ObjFactura.TipoDocto = "Ing" Then Dim RowVenta As DataRow = Nothing If ObjVentas.GetVenta(ObjFactura.CveVenta, UsuarioActual.CveEmpresa, VerificaAlmacen:=False) Then RowVenta = ObjVentas.DtResultados.Rows(0) Else ErrorList.Add("No se pudieron validar los datos de la venta") End If If RowVenta IsNot Nothing Then 'SI FUE VENTA DE CONTADO VALIDA QUE SE HAYA PAGADO EN SU TOTALIDAD If RowVenta("CondicionesPago").ToString().ToEntero() = 0 AndAlso RowVenta("Saldo").ToString().ToDecimal() > 0.01D Then ErrorList.Add("La venta no fue pagada en su totalidad") End If Else ErrorList.Add("No se pudieron validar los datos de la venta") End If End If 'MARCA PARA NO SURTIR VENTA DE COTNRATO DE CONSIGNACION DE VENTA | [IPP] : PARCHE If ErrorList.Count = 0 Then If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then ErrorList.Add("No se pudo cancelar el movimiento de almacen de la Factura de consignación") End If End If End If If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 Then 'ACTUALIZA VENTA COTIZACIÓN If EraCotizacion = 1 And BtnEmitirImprimir.Text = "Facturar" Then If Not ObjVentas.UpdateVentaCotizacion(ObjFactura.CveVenta, Request("CveVenta").ToEntero()) Then ErrorList.Add("Ocurrió un error al actualizar la cotización") End If End If 'ACTUALIZA VENTAPADRE PEDIDO If Request("DevPed").ToEntero() > 0 AndAlso ErrorList.Count = 0 Then If Not ObjVentas.UpdateVentaCotizacion(Request("DevPed").ToEntero(), ObjFactura.CveVenta) Then ErrorList.Add("Ocurrió un error al actualizar la devolución de pedido") End If End If 'ACTUALIZA LA COLUMNA CveVentaFacturada If (Request("CveRemision") IsNot Nothing AndAlso ViewState("CveRemision").ToString().ToEntero() > 0) AndAlso (Request("Op") IsNot Nothing AndAlso Request("Op") = "Rem") AndAlso ErrorList.Count = 0 Then If Not ObjVentas.UpdateVentaRemision(ViewState("CveRemision").ToString().ToEntero(), ObjFactura.CveVenta) Then ErrorList.Add("Ocurrió un error al actualizar la remision") End If End If 'Agregamos las Cotizaciones a la tabla If DtCotizacionesPS IsNot Nothing AndAlso DtCotizacionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then Dim CveVentaDetalle As Integer = 0 Dim CveVentaDetallePadre As Integer = 0 Dim Cantidad As Decimal = 0 Dim CvePS As Integer = 0 Dim PU As Decimal = 0 For Each row As DataRow In DtCotizacionesPS.Rows Cantidad = DtCotizacionTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal CvePS = DtCotizacionTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero() PU = DtCotizacionTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero() CveVentaDetallePadre = row("CveVentaDetalle").ToString().ToEntero() If Not ObjVentas.AgregaCotizacionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then ErrorList.Add("Ocurrió un Error al agregar el detalle de la Cotización.") End If Next End If 'Marcamos las ventas anteriores a febrero como surtidas - Ajuste Compu If ErrorList.Count = 0 Then If Not ObjVentas.MarcarRemisionesSinSurtir(ObjVentas.CveVenta) Then ErrorList.Add("Ocurrió un Error al marcar la factura") End If End If 'If CveFactura > 0 AndAlso ErrorList.Count = 0 Then ' If Not ObjVentas.UpdateVentaFacturas(CveFactura, ObjVentas.CveVenta, UsuarioActual.CveEmpresa) Then ' ErrorList.Add("No se pudo actualizar la Factura") ' End If 'End If 'If CveCicloComercial > 0 AndAlso ErrorList.Count = 0 Then ' If Not ObjContr.CicloComercialUpdate(CveCicloComercial, True, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then ' ErrorList.Add("No se pudo actualizar ") ' End If 'End If 'MARCAR LA FACTURA ANTERIOR If (Me.CveDevolucion > 0 AndAlso Me.NuevaFactura = 1) Then If Me.ObjFacturaNC IsNot Nothing Then If Me.ObjFacturaNC.CveEstatusRefacturacion = 4 AndAlso Not ObjVentas.UpdateEstatusVenta(ObjFacturaNC.CveVenta, ObjFacturaNC.CveEstatusFactura, UsuarioActual.CveEmpresa, CveEstatusRefacturacion:=5) Then ErrorList.Add("No se actualizó el estatus de la factura anterior.") End If End If End If 'ContPAQ El movimiento 1 es el de Venta Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" AutoConta = AutocontaMatriz(AutoConta) If DdlTipoComprobante.SelectedValue.Contiene("Rem", "RNC", "Cot", "Ped", "Pd2", "PA") Then AutoConta = False End If If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Rem", "RNC", "Cot", "Ped", "Pd2", "PA", "Egs", "Dev") Then AutoConta = False End If If UsuarioActual.CveEmpresa = 140 Then AutoConta = True End If Try If AutoConta Then If Not ObjConta.ContabilizarPrePoliza(ObjFactura.CvePrePoliza, ObjFactura.CveUsuario, UsuarioActual.Empresa) Then ErrorList.Add("Ocurrió un error al contabilizar, pongase en contacto con soporte técnico") End If End If Catch ex As Exception ErrorList.Add("Ocurrió un error al contabilizar, pongase en contacto con soporte técnico") OnError("Ocurrió un error al contabilizar la factura", ex) End Try If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 AndAlso (SeGuardoPrePoliza Or ObjFactura.TipoDocto.Contiene("Ped", "Cot", "DPe", "PeC", "PA", "Pd2")) Then ObjVentas.Commit() ObjFactura.DtDetalle = TmpDT 'actualiza por cambios de pedimentos. ObjFactura.Timbre = PreParaTimbre(ObjFactura) Try ViewState("CveVenta") = ObjFactura.CveVenta If Request("CveEmbarqueManifiesto") IsNot Nothing AndAlso IsNumeric(Request("CveEmbarqueManifiesto")) AndAlso Request("CveEmbarqueManifiesto").ToEntero() > 0 Then If ObjVentas.Embarque_ManifiestoUpvta(ObjFactura.CveVenta, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Request("CveEmbarqueManifiesto").ToEntero()) Then End If End If Catch ex As Exception OnError("Ocurrió un error al actualizar el embarque", ex) End Try Try ViewState("CveVenta") = ObjFactura.CveVenta If Request("CveOrdenProduccion") IsNot Nothing AndAlso IsNumeric(Request("CveOrdenProduccion")) AndAlso Request("CveOrdenProduccion").ToEntero() > 0 Then If ObjVentas.AgroOrdenProduccionUpvta(ObjFactura.CveVenta, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Request("CveOrdenProduccion").ToEntero()) Then End If End If Catch ex As Exception OnError("Ocurrió un error al actualizar la orden de producción", ex) End Try Try Dim DirectoriArchivoXML As String = String.Format("{0}{1}", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto) ' System.IO.Path.Combine() If Not Directory.Exists(DirectoriArchivoXML) Then Directory.CreateDirectory(DirectoriArchivoXML) End If Catch ex As Exception OnError("Ocurrió un error al generar el directorio de xml", ex) End Try Dim SeTimbro As Boolean = False Dim SeTimbroNC As Boolean = False Dim EstatusSMS As Integer = 0 Dim MsgCancelacionRefacturacion As Modelos.Factura.MCancelacionVentaMensaje = Nothing 'TIMBRADO Y CASO ESPECIAL NOTA DE CREDITO If (TipoDoctoDevolucion = "" OrElse Not TipoDoctoDevolucion.Contiene("Rem", "RNC", "Cot", "Ped", "DPe", "PA", "Pd2")) Then Dim DebeTimbrar As Boolean = True If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then 'si tiene anticipos seleccionados y el total es cero, que no se timbre(previo empresa72) If LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0 Then DebeTimbrar = False End If End If If UsuarioActual.TienePermisoProceso(335) Then DebeTimbrar = False End If DebeTimbrar = False If DebeTimbrar AndAlso ObjFactura.TipoDocto.Contiene("Ing", "Egs", "Ant", "Dev") Then If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso (UsuarioActual.Empresa.FacturaProduccion OrElse UsuarioActual.CveEmpresa = 1) Then 'FACTURA INGRESO/EGRESO Dim FM As New Modelos.FemsaFactura Dim TmpDT7Eleven As New DataTable Dim TmpDTComplementosTimbrado As New DataTable Dim ObjTimbrado As New Timbrado Try 'If AplicaFEMSA Then ' PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) 'End If If DebeTimbrar Then SeTimbro = ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) End If Catch ex As Exception OnError("Ocurrió un error al generar el timbrado", ex) End Try Dim FolioFiscalFactura As String = ObjTimbrado.UUID Dim MsgErrorTimbrado As String = ObjTimbrado.MensajeErrorCFDI ObjTimbrado = Nothing 'NOTA DE CREDITO - REFACTURADA - CASO ESPECIAL, TIMBRADO E IMPRESION 'If DebeTimbrar AndAlso SeTimbro AndAlso ListaNotasCreditoGeneradas IsNot Nothing AndAlso ListaNotasCreditoGeneradas.Count > 0 Then ' Try ' For Each NCGenerada As Modelos.Factura In ListaNotasCreditoGeneradas ' If NCGenerada.Timbre IsNot Nothing Then ' NCGenerada.Timbre.CFDIRelacionados.UUID.Clear() ' NCGenerada.Timbre.CFDIRelacionados.UUID.Add(FolioFiscalFactura) ' Dim ObjTimbradoNC As New Timbrado ' Dim TimbroNC As Boolean = ObjTimbradoNC.TimbrarFactura(UsuarioActual, NCGenerada) ' If Not TimbroNC Then ' Alert(ObjTimbradoNC.MensajeErrorCFDI, TipoMensaje.MsgError) ' End If ' ObjTimbradoNC = Nothing ' End If ' Next ' Catch ex As Exception ' OnError("Ocurrió un error al timbrar la NC.", ex) ' End Try 'End If If Not SeTimbro Then Alert(MsgErrorTimbrado, TipoMensaje.MsgError) End If 'CANCELAR FACTURA ANTERIOR Try If SeTimbro AndAlso (Me.CveDevolucion > 0 AndAlso Me.NuevaFactura = 1) Then If Me.ObjFacturaNC IsNot Nothing AndAlso Me.ObjFacturaNC.CveEstatusFactura <> 5 Then Me.ObjFacturaNC.CveEstatusRefacturacion = 2 'MARCAR COMO REFACTURADA MsgCancelacionRefacturacion = Me.ObjFacturaNC.CancelarPorRefacturacion(Me.ObjFacturaNC.CveMotivoCancelacion, Me.ObjFacturaNC.MotivoCancelacion, FolioFiscalFactura) End If End If Catch ex As Exception OnError("Ocurrió un error al cancelar la factura anterior.", ex) End Try End If End If End If 'MENSAJE PRINCIPAL MensajeAlert.AppendFormat(String.Format("
La {0}: {1} se generó correctamente.

", ObjFactura.TipoDocumento, ObjFactura.SerieFolio)) ' DESCARGA XML - SI SE TIMBRA MANDA CORREO CON FACTURA If SeTimbro Then Dim ArchivoXML As String = String.Format("{0}/XML/{1}/{2}.xml", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) If File.Exists(ArchivoXML) Then MensajeAlert.AppendFormat("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", ObjFactura.SerieFolio, ObjFactura.TipoDocto))) End If Try 'MANDA CORREO Dim strURLHOST As String = String.Format("{0}://{1}:{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port) Dim Factura As New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=False, CargaDTDetalle:=False, CargaDatosCliente:=False, CargaDatosRelacionados:=False, VerificaAlmacen:=False) Dim Hilo As New System.Threading.Thread(Sub() GeneraPDFFactura(False, Factura, UsuarioActual, strURLHOST)) Hilo.Start() Catch ex As Exception OnError("Ocurrió un error al enviar el PDF", ex) End Try End If 'DESCARGA PDF If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant", "Egs", "Dev", "Pd2") Then 'If Not ImprimeAlert Then Dim ArchivoIngPyMe As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.mrt", UsuarioActual.Empresa.Ruta)) Dim ArchivoIng As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta)) Dim ArchivoRem As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta)) Dim ArchivoEgs As New System.IO.FileInfo(String.Format("{0}Formatos/NotaCredito.rdlc", UsuarioActual.Empresa.Ruta)) If ArchivoIng.Exists Or ArchivoRem.Exists Or ArchivoIngPyMe.Exists Or ArchivoEgs.Exists Then MensajeAlert.AppendFormat("
", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta))) Else MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") End If End If 'CRM If DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso CveEmpresaCRM > 0 AndAlso CveAcercamientoCRM > 0 Then Dim ArchivoCotRdlc As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.rdlc", UsuarioActual.Empresa.Ruta)) Dim ArchivoCotMrt As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.mrt", UsuarioActual.Empresa.Ruta)) If ArchivoCotRdlc.Exists Or ArchivoCotMrt.Exists Then MensajeAlert.AppendFormat("
", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta))) If ChkEnviarFacturaCRM.Checked AndAlso CorreoContactoCRM.Trim.Length > 0 Then Try Dim pdfCRM As Byte() = Nothing 'If CveVenta > 0 Then ' ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=False) 'End If pdfCRM = PdfFactura(ObjFactura) If pdfCRM IsNot Nothing Then Dim SerieFolioCRM As String = ObjFactura.SerieFolio Dim TipoDoctoCRM As String = ObjFactura.TipoDocto GeneraPDFCotizacion(True, CorreoContactoCRM:=CorreoContactoCRM, pdfCRM:=pdfCRM, SerieFolioCRM:=SerieFolioCRM, TipoDoctoCRM:=TipoDoctoCRM) End If Catch ex As Exception OnError("Ocurrió un error al enviar el PDF", ex) End Try End If Else MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") End If End If If DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso CveEmpresaCRM > 0 AndAlso CveAcercamientoCRM > 0 Then Dim ArchivoCotRdlc As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.rdlc", UsuarioActual.Empresa.Ruta)) Dim ArchivoCotMrt As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.mrt", UsuarioActual.Empresa.Ruta)) If ArchivoCotRdlc.Exists Or ArchivoCotMrt.Exists Then MensajeAlert.AppendFormat("
", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta))) Else MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") End If End If 'ERROR DE NO TIMBRADO If Not SeTimbro And (DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue = "Ant") Then MensajeAlert.AppendFormat("La factura no se pudo timbrar. Por favor intentelo de nuevo a traves del boton Emitir.") End If 'ERROR DE NO TIMBRADO NC If Not IsNothing(ObjNC) AndAlso ObjNC.Count > 0 AndAlso Not SeTimbroNC Then MensajeAlert.AppendFormat("
La NC #{0} no se pudo timbrar. Por favor intentelo de nuevo a traves del boton Emitir.", CType(ObjNC(0), Modelos.Factura).SerieFolio) End If 'NOTIFICACION DE SMS Select Case EstatusSMS Case 1 MensajeAlert.AppendFormat("
Notificación SMS: enviado con éxito al cliente al celular: {0}", ObjFactura.Cliente.CobranzaTelefono) Case 2 MensajeAlert.AppendFormat("
Notificación SMS: sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.") Case 3 MensajeAlert.AppendFormat("
Notificación SMS: sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.") End Select If DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso CveEmpresaCRM > 0 AndAlso CveAcercamientoCRM > 0 Then RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))}'", "Imprimir") End If 'DESCARGAR PDF DE CICOVISA 'If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 Then ' If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then ' MensajeAlert.AppendFormat("
", Encripta(String.Format("OP=CIC&CVEVENTA={0}", CveVenta))) ' End If 'End If 'MOVIMIENTO DE ALMACEN If ObjFactura.Inv_CveMovimiento > 0 Then MensajeAlert.AppendFormat("

Movimiento de Almacén
", ObjFactura.Inv_CveMovimiento) End If If CveVentaNCProntoPago > 0 Then MensajeAlert.AppendFormat(String.Format("
La nota de crédito {0} por descuento pronto pago se generó correctamente.

", SerieFolioNCProntoPago)) End If If MsgCancelacionRefacturacion IsNot Nothing Then If Not MsgCancelacionRefacturacion.HuboError Then If MsgCancelacionRefacturacion.CveEstatus = 5 Then MensajeAlert.AppendFormat("
El folio {0} fue cancelado. Descargar Acuse", Me.ObjFacturaNC.SerieFolio, Encripta(String.Format("OP=CAN&CVEVTA={0}", Me.ObjFacturaNC.CveVenta))) MensajeAlert.AppendFormat(" Enviar Acuse.

", Me.ObjFacturaNC.CveVenta) ElseIf MsgCancelacionRefacturacion.CveEstatus = 20 Then MensajeAlert.AppendFormat("
El folio {0} esta en proceso de cancelación. Descargar Acuse", Me.ObjFacturaNC.SerieFolio, Encripta(String.Format("OP=CAN&CVEVTA={0}", Me.ObjFacturaNC.CveVenta))) MensajeAlert.AppendFormat(" Enviar Acuse.

", Me.ObjFacturaNC.CveVenta) Else MensajeAlert.AppendFormat("
El folio {0} no fue cancelado. Intente mas tarde cancelar el documento Ver en el reporte", Me.ObjFacturaNC.SerieFolio, Me.ObjFacturaNC.CveVenta) End If Else MensajeAlert.AppendFormat("
El folio {0} no fue cancelado. Intente mas tarde cancelar el documento Ver en el reporte", Me.ObjFacturaNC.SerieFolio, Me.ObjFacturaNC.CveVenta) End If End If 'MUESTA ALERT OK ' si es elrol 1165-Ventas,EMp:80, o la empresa 119, recarga ventas, para seguir registrando-. 'Dim Liga = If(UsuarioActual.CveRol = 1165 Or UsuarioActual.CveEmpresa = 119, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", If(CveEmpresaCRM > 0, $"document.location.href=""/CRM/EmpresaCRM.aspx?CveEmpresaCRM={CveEmpresaCRM}"";", $"document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";")) 'Alert(MensajeAlert.ToString(), TipoMensaje.MsgInformacion, Liga) Dim Liga As String = "" Dim Liga2 As String = "" If Request("CveCliente") IsNot Nothing AndAlso Request("CveCliente").ToEntero > 0 Then Liga = $"document.location.href=""/Ventas/Ventas.aspx?CveCliente={Request("CveCliente")}"";" Else Liga = "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";" End If If CveEmpresaCRM > 0 Then Liga2 = $"document.location.href=""/CRM/EmpresaCRM.aspx?CveEmpresaCRM={CveEmpresaCRM}"";" Else Liga2 = $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}"";" End If If DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso CveEmpresaCRM > 0 AndAlso CveAcercamientoCRM > 0 Then Liga = $"document.location.href=""/CRM/Acercamiento.aspx?CveAcercamiento={CveAcercamientoCRM}&OPTAB=COT"";" Alert(MensajeAlert.ToString(), TipoMensaje.MsgInformacion, Liga, TextoConfirmacion:="Aceptar", TextoSegundoBoton:=Nothing, JSBtn2:=Nothing, ShowCloseButton:=False) Else Alert(MensajeAlert.ToString(), TipoMensaje.MsgDosBotones, Liga, TextoConfirmacion:="Seguir Registrando", TextoSegundoBoton:="Ir al Cliente", JSBtn2:=Liga2, ShowCloseButton:=False) End If MensajeAlert.Clear() Try BtnEmitirImprimir.Visible = False ObjFactura = Nothing Catch ex As Exception OnError("Ocurrió un error al limpiar los datos", ex) End Try Else ObjVentas.RollBack() For Each ErrorItem As String In ErrorList Alert(ErrorItem, TipoMensaje.MsgAdvertencia) Next 'MUESTA ALERT ERROR Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) End If ObjVentas.Dispose() ObjConta.Dispose() ObjInventario.Dispose() ObjCGame.Dispose() ObjContr.Dispose() ObjDocCliente.Dispose() ObjAcum.Dispose() 'ObjFolios.Dispose() ErrorList.Clear() ErrorList = Nothing MensajeAlert = Nothing TmpDT = TmpDTError.Copy CalculaTotalesVenta(RecalcularTotalOriginal:=False) Else ObjVentas.RollBack() For Each ErrorItem As String In ErrorList Alert(ErrorItem, TipoMensaje.MsgAdvertencia) Next 'MUESTA ALERT ERROR Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) ObjVentas.Dispose() ObjConta.Dispose() ObjInventario.Dispose() ObjCGame.Dispose() ObjContr.Dispose() ObjDocCliente.Dispose() 'ObjFolios.Dispose() ErrorList.Clear() ErrorList = Nothing MensajeAlert = Nothing TmpDT = TmpDTError.Copy CalculaTotalesVenta(RecalcularTotalOriginal:=False) End If ObjFactura = Nothing 'ListaNotasCreditoGeneradas = Nothing End If End If End Sub Private Function AutocontaMatriz(AutoConta As Boolean) As Boolean Dim Respuesta As Boolean = False If UsuarioActual.CveEmpresa.Contiene(13, 83) Then Dim DTSubproyectoActual As DataTable = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero) If (DTSubproyectoActual.Rows(0)("TipoSucursal").ToString.ToEntero = 1) Then Respuesta = True Else Respuesta = False End If Else Respuesta = AutoConta End If Return Respuesta End Function Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False, Optional EsCancelacion As Boolean = False, Optional TipoDoctoViejo As String = "") If Me.CveVenta > 0 AndAlso NuevaFactura <> 1 Then ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=EsCancelacion) Else ObjFactura = New Modelos.Factura End If ObjFactura.Version = "4.0" If ObjFactura.Cliente Is Nothing Then ObjFactura.Cliente = New Modelos.ClienteModel ObjFactura.Cliente.CodigoRegimenFiscal = ClienteCodigoRegimenFiscal ObjFactura.Cliente.RegimenFiscal = ClienteRegimenFiscal ObjFactura.CveUsuario = UsuarioActual.CveUsuario ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa ObjFactura.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) ObjFactura.TipoCambioDolares = TxtTipoCambioDlls.Text.Trim.ToDecimal ObjFactura.ConvertirPesos = ChkConvertirDoctoPesos.Checked ObjFactura.ConvertirDolares = ChkConvertirDolares.Checked ObjFactura.CveMoneda = DdlMoneda.SelectedValue.ToEntero() ObjFactura.Moneda = DdlMoneda.SelectedItem.Text ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") ObjFactura.TipoDocto = If(IfNull(ViewState("CveRemision"), 0).ToString().ToEntero() > 0, "Ing", DdlTipoComprobante.SelectedValue) ObjFactura.FacturarSucursal = (Me.FacturarSucursal AndAlso DdlSucursalCliente.SelectedValue.ToEntero() > 0 AndAlso (Me.ClienteSucursal IsNot Nothing AndAlso Not String.IsNullOrEmpty(Me.ClienteSucursal.RFC))) ObjFactura.VentaDesglosaIEPS = Me.VentaDesglosaIEPS If EsCreaApartirDe Then ViewState("EstablecioFolio") = False End If 'si es cancelacion, debe de conservar el folio actual ''SI NO ESTABLECIO UN FOLIO FIJO Y SI ES FACTURACION DE REMISION O COTIZACION NO TOMAR EL FOLIO QUE SE MUESTRA 'If Not EstablecioFolio AndAlso (Not EsCancelacion AndAlso ObjFactura.Folio > 0 AndAlso TipoDoctoViejo.Contiene("Rem", "Cot")) Then ' ObjFactura.Folio = -1 'End If ObjFactura.Folio = Me.FolioActual.ToEntero ObjFactura.Serie = Me.Serie If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Dim ObjFolios As New ClsGralFolios() Dim TipoDoctoConsulta As String = If(ObjFactura.TipoDocto = "Ant", "Ing", If(ObjFactura.TipoDocto = "PA", "Rem", ObjFactura.TipoDocto)) 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 ObjFactura.Serie = DT.Rows(0)("Serie").ToString() End If DT.Dispose() End If ObjFolios.Dispose() End If ObjFactura.Fecha = New Date(NowADS.Year, NowADS.Month, NowADS.Day, NowADS().Hour, NowADS().Minute, NowADS().Second) ObjFactura.CvePrePoliza = -1 ObjFactura.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero() ObjFactura.MetodoPago = "" ' DdlMetodoPago.SelectedItem.Text ObjFactura.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFactura.FechaVencimiento = NowADS() ' If ObjFactura.TipoDocto = "Cot" Then ObjFactura.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero() ObjFactura.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero() > 0, DdlMetodoPago33.SelectedItem.Text, "") ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFactura.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero() ObjFactura.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero() > 0, DdlFormaPago33.SelectedItem.Text, "") ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}") ObjFactura.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero() ObjFactura.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero() > 0, DdlUsoCFDI.SelectedItem.Text, "") ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") ' End If ObjFactura.UsuarioCreo = LblUsuario.Text.Trim ObjFactura.CveCondicionEntrega = --1 ObjFactura.CondicionEntrega = "-1" ObjFactura.CondicionesPago = 2 ' 0 - Contado, 1 - Credito, 2 - termianl ObjFactura.FormaPago = 0 ObjFactura.AtencionA = "" ObjFactura.FordGSDB = "" ObjFactura.NumeroContrato = NumeroContrato ObjFactura.DescripcionContrato = DescripcionContrato ObjFactura.NumeroDescripcionContrato = If($"{NumeroContrato} - {NumeroLicitacion}" = " - ", "", $"{NumeroContrato} {If(NumeroLicitacion = "", "", $" - Licitación: {NumeroLicitacion}")}") ObjFactura.PedidoContrato = "" ObjFactura.OrdenCompra = TxtOrdenCompra.Text.Trim Select Case ObjFactura.TipoDocto Case "Ing" ObjFactura.TipoDocumento = "Factura" Case "Rem" ObjFactura.TipoDocumento = "Remision" Case "Cot" ObjFactura.TipoDocumento = "Cotizacion" Case "Egs" ObjFactura.TipoDocumento = "Nota de Crédito" Case "Dev" ObjFactura.TipoDocumento = "Nota de Devolución" Case "DPe" ObjFactura.TipoDocumento = "Devolución de pedido" Case "PeC" ObjFactura.TipoDocumento = "Consignación de Pedido" Case Else ObjFactura.TipoDocumento = "" End Select ObjFactura.Fech1 = NowADS() ObjFactura.Fech2 = NowADS() ObjFactura.Fech3 = NowADS() ObjFactura.Alfa1 = "" ObjFactura.Alfa2 = "" ObjFactura.Alfa3 = "" ObjFactura.Num1 = 0 ObjFactura.Num2 = 0 ObjFactura.Num3 = 0 If divcondicionespago.Visible Then ObjFactura.FechaPago = NowADS() Else ObjFactura.FechaPago = NowADS() End If ObjFactura.DiasCredito = DiasCredito ObjFactura.EsDiasCreditoFijo = EsDiasCreditoFijo ObjFactura.CveCorte = CveCorte 'ObjFactura.CveMesa = -1 ObjFactura.NumeroPersonas = 0 'If ObjFactura.TipoDocto = "Ant" And DdlContratosModal.SelectedValue.ToEntero > 0 Or ObjFactura.TipoDocto = "Ing" And DdlContratosModal.SelectedValue.ToEntero > 0 Or ObjFactura.TipoDocto = "Egs" And DdlContratosModal.SelectedValue.ToEntero > 0 Then ' CveContrato = DdlContratosModal.SelectedValue.ToEntero 'End If ObjFactura.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) ObjFactura.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero() ObjFactura.Entrega = Entrega ObjFactura.Vigencia = NowADS() ObjFactura.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, If(CvePedido2 > 0, CvePedido2, CvePedido)) If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then ObjFactura.CveVentaPadre = DtVentasNC.Rows(0)("CveVenta").ToString().ToEntero() ObjFactura.SerieFolioPadre = DtVentasNC.Rows(0)("FolioFiscal").ToString() End If If DdlTipoComprobante.SelectedValue = "Dev" AndAlso ListaRemisionesNC IsNot Nothing AndAlso ListaRemisionesNC.Count > 0 Then Dim ObjRNC As Modelos.Factura = ListaRemisionesNC.FirstOrDefault If ObjRNC IsNot Nothing Then ObjFactura.CveVentaPadre = ObjRNC.CveVentaPadre ObjFactura.SerieFolioPadre = ObjRNC.SerieFolioPadre End If End If ObjFactura.CveVendedor = -1 ObjFactura.FechaEjecucion = NowADS() ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() ObjFactura.CveSubProyectoCobranza = DdlSubProyectoDatos.SelectedValue.ToEntero() ObjFactura.CveSubProyectoEjecucion = DdlSubProyectoDatos.SelectedValue.ToEntero() ObjFactura.AtencionA = If(ObjFactura.TipoDocto = "Cot" Or (ObjFactura.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), "", "-1") ObjFactura.MotivoDescuento = "" ObjFactura.Observaciones = TxtObsFact.Text.Trim ObjFactura.Det_OrdenCompra = "" ObjFactura.Det_FechaOrdenCompra = "" ObjFactura.Det_ContraRecibo = "" ObjFactura.MonedaAbreviatura = "" 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS If (ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then Dim TotalCalculableImpuestos, TotalCalculableImpuestosIVA As Decimal For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDecimal * ObjFactura.TipoCambio, 6) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDouble * ObjFactura.TipoCambio, NumeroDecimales) TotalCalculableImpuestos = (Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal) - Row("Descuento").ToString().ToDecimal TotalCalculableImpuestosIVA = TotalCalculableImpuestos * (1 + Row("PorcentajeIEPS").ToString().ToDecimal) Row("IVA") = Row("PorcentajeIVA") Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString().ToDecimal * TotalCalculableImpuestosIVA, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("PorcentajeIEPS").ToString().ToDecimal * TotalCalculableImpuestos, NumeroDecimales) Row("IEPS") = Row("ImporteIEPS") Row("Total") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio).FormatoNumero If gvr.DataKey("TipoImpuesto").ToString() = "5" Then ImpuestosLocales -= Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) Else ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) End If End If Next ObjFactura.SubTotal = TmpDT.SUMD("Total") ObjFactura.Descuento = TmpDT.SUMD("Descuento") ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) ObjFactura.IVA = TmpDT.SUMD("ImporteIVA") ObjFactura.RetIVA = TmpDT.SUMD("ImporteRetIVA") ObjFactura.RetISR = TmpDT.SUMD("ImporteRetISR") ObjFactura.IEPS = TmpDT.SUMD("ImporteIEPS") ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal TipoCambioRemision = ObjFactura.TipoCambio ObjFactura.TipoCambio = 1 ObjFactura.ConvertirPesos = False ConversionRemision = "/" 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES ElseIf (ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDouble / ObjFactura.TipoCambioDolares, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Next Dim ImpuestosLocales As Decimal = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) End If Next ObjFactura.SubTotal = TmpDT.SUMD("Total") ObjFactura.Descuento = TmpDT.SUMD("Descuento") ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) ObjFactura.IVA = TmpDT.SUMD("ImporteIVA") ObjFactura.RetIVA = TmpDT.SUMD("ImporteRetIVA") ObjFactura.RetISR = TmpDT.SUMD("ImporteRetISR") ObjFactura.IEPS = TmpDT.SUMD("ImporteIEPS") ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales) TipoCambioRemision = ObjFactura.TipoCambioDolares ObjFactura.TipoCambioDolares = 1 ObjFactura.ConvertirDolares = False ConversionRemision = "*" 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS REGISTRO DIRECTO SIN VENTA ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True) Then Dim TotalCalculableImpuestos, TotalCalculableImpuestosIVA As Decimal For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDecimal * ObjFactura.TipoCambio, 6) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDouble * ObjFactura.TipoCambio, NumeroDecimales) TotalCalculableImpuestos = (Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal) - Row("Descuento").ToString().ToDecimal TotalCalculableImpuestosIVA = TotalCalculableImpuestos * (1 + Row("PorcentajeIEPS").ToString().ToDecimal) Row("IVA") = Row("PorcentajeIVA") Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString().ToDecimal * TotalCalculableImpuestosIVA, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales) Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("PorcentajeIEPS").ToString().ToDecimal * TotalCalculableImpuestos, NumeroDecimales) Row("IEPS") = Row("ImporteIEPS") Row("Total") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) 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.ToDecimal * ObjFactura.TipoCambio).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales) End If Next ObjFactura.SubTotal = TmpDT.SUM("Total") ObjFactura.Descuento = TmpDT.SUM("Descuento") ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) ObjFactura.IVA = TmpDT.SUM("ImporteIVA") ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA") ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR") ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS") ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal TipoCambioRemision = ObjFactura.TipoCambio ObjFactura.TipoCambio = 1 ObjFactura.ConvertirPesos = False ConversionRemision = "/" 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES REGISTRO DIRECTO SIN VENTA ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True) Then For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDouble / ObjFactura.TipoCambioDolares, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) End If Next ObjFactura.SubTotal = TmpDT.SUM("Total") ObjFactura.Descuento = TmpDT.SUM("Descuento") ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) ObjFactura.IVA = TmpDT.SUM("ImporteIVA") ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA") ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR") ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS") ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal TipoCambioRemision = ObjFactura.TipoCambioDolares ObjFactura.TipoCambioDolares = 1 ObjFactura.ConvertirDolares = False ConversionRemision = "*" Else 'Totales, Y se llena TmpDTImpuestos ObjFactura.SubTotal = TxtSubTotal.Text.ToDecimal ObjFactura.Descuento = LblDescuentos.Text.Trim.ToDecimal ObjFactura.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal ObjFactura.IVA = TxtIVA.Text.ToDecimal ObjFactura.RetIVA = TxtRetIVA.Text.ToDecimal ObjFactura.RetISR = TxtRetISR.Text.ToDecimal ObjFactura.IEPS = TxtIEPS.Text.ToDecimal ObjFactura.Total = TxtTotal.Text.ToDecimal End If Dim TmpSubtotal As Decimal = TxtSubTotal.Text.ToDecimal - ObjFactura.Descuento Dim TmpAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal ObjFactura.DtDetalle = TmpDT 'If AplicaFord Then ' ObjFactura.FordGSDB = TxtFordGSDB.Text ' Dim SB As New StringBuilder ' For Each li As ListItem In LstFordASN.Items ' SB.AppendFormat("{0}, ", li.Text) ' Next ' ObjFactura.FordASN = SB.ToString() 'End If If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone() Dim DR As DataRow = TmpDTImpuestosVista.NewRow() If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = ObjFactura.SubTotal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = ObjFactura.Descuento : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = ObjFactura.Amortizacion : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() 'If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = ObjFactura.IVA : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = ObjFactura.RetIVA : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = ObjFactura.RetISR : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtIEPS.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IEPS" : DR("Importe") = ObjFactura.IEPS : DR("Orden") = 80 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then Dim Orden As Integer = 80 If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString() : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString() : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString() : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() Orden = Orden + 1 End If End If Next If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = ObjFactura.Total : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) ObjFactura.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC") 'TmpDT DESGLOSE DE IMPUESTOS 3.3 If UsuarioActual.CveEmpresa.Contiene(119) Then If TmpDTDocumentosRelacionados IsNot Nothing Then ObjFactura.DtDocumentosRelacionados = TmpDTDocumentosRelacionados End If If TmpDTNCVinculadas IsNot Nothing Then ObjFactura.DtNCVinculadas = TmpDTNCVinculadas End If End If CreaDTImpuestosIVAIEPS() For Each DrImpuestos33 As DataRow In TmpDT.Rows Dim DrIVA As DataRow = Nothing Dim DrIEPS As DataRow = Nothing Try DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0) Catch ex As Exception DrIVA = Nothing End Try If DrIVA IsNot Nothing Then DrIVA("Importe") = DrIVA("Importe").ToString().ToDouble + DrImpuestos33("ImporteIVA").ToString().ToDouble TmpDTImpuestosIVAIEPS.AcceptChanges() Else Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() If DrImpuestos33("PorcentajeIVA").ToString().ToDecimal > 0 Then DR2("Impuesto") = "IVA" : DR2("tasa") = DdlIVA.SelectedItem.ToString() : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString().ToDecimal : DR2("Orden") = "1" TmpDTImpuestosIVAIEPS.Rows.Add(DR2) TmpDTImpuestosIVAIEPS.AcceptChanges() End If End If Try DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString().ToDecimal * 100} %'")(0) Catch ex As Exception DrIEPS = Nothing End Try If DrIEPS IsNot Nothing Then DrIEPS("Importe") = DrIEPS("Importe").ToString().ToDouble + DrImpuestos33("ImporteIEPS").ToString().ToDouble TmpDTImpuestosIVAIEPS.AcceptChanges() Else Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() If DrImpuestos33("PorcentajeIEPS").ToString().ToDouble > 0 Then DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString().ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString().ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.09", "5", "0")))) TmpDTImpuestosIVAIEPS.Rows.Add(DR2) TmpDTImpuestosIVAIEPS.AcceptChanges() End If End If Next ObjFactura.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC") 'otros 'ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim 'ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim 'ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim ObjFactura.Det_FechaOrdenCompra = "" ObjFactura.Det_OrdenCompra = "" ObjFactura.Det_ContraRecibo = "" ObjFactura.CveNCaVincular = -1 If ObjFactura.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then ObjFactura.TipoCambio = 1 ObjFactura.CveMoneda = 1 ObjFactura.Moneda = "Pesos" ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") End If If ObjFactura.CveMoneda <> 2 AndAlso ChkConvertirDolares.Checked Then ObjFactura.TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal ObjFactura.CveMoneda = 2 ObjFactura.Moneda = "Dólares" ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") End If 'Se agrega CveVenta -1 For Each Row As DataRow In TmpDT.Rows Row("CveVenta") = ObjFactura.CveVenta Next 'DETALLES ObjFactura.DtDetalle = TmpDT.Copy ObjFactura.DtFirmas = DTmpF.Copy 'CLIENTE ObjFactura.CveCliente = CveCliente ObjFactura.SetCliente() ObjFactura.CveEmpresaCRM = CveEmpresaCRM If CveCliente = -1 And CveEmpresaCRM > 0 Then ObjFactura.Cliente.Nombre = LblEmpresaCRM.Text ObjFactura.Cliente.RFC = LblRFCCRM.Text End If 'SUCURSAL 'ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() ObjFactura.SetSubProyectoMatriz(Me) ObjFactura.SetSubProyecto(Me) ObjFactura.ClienteSucursal = New Modelos.SucursalModel() If CveCliente > 0 Then If Me.ClienteSucursal IsNot Nothing Then ObjFactura.ClienteSucursal.RFC = Me.ClienteSucursal.RFC ObjFactura.ClienteSucursal.Nombre = Me.ClienteSucursal.Nombre End If ObjFactura.ClienteSucursal.NoExt = CliNoExt ObjFactura.ClienteSucursal.NoInt = CliNoInt ObjFactura.ClienteSucursal.Localidad = CliLocalidad ObjFactura.ClienteSucursal.Direccion = LblDireccion.Text ObjFactura.ClienteSucursal.Colonia = LblColonia.Text ObjFactura.ClienteSucursal.Municipio = LblCiudad.Text ObjFactura.ClienteSucursal.Estado = LblEstado.Text ObjFactura.ClienteSucursal.CP = LblCP.Text ObjFactura.ClienteSucursal.Pais = CliPais ObjFactura.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString() ObjFactura.ClienteSucursal.TelefonoSucursal = LblTelefono.Text ObjFactura.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero() > 0, DdlSucursalCliente.SelectedItem.Text, "") ObjFactura.ClienteSucursal.ImprimeNombreSucursal = ImprimeNombreSucursal.ToString() End If 'ENVIO DIRECCION ObjFactura.EnviarA = New Modelos.EnviarAModel 'If ChkDireccionEnvio.Checked Then ' If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())).Rows.Count > 0 Then ' For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())).Rows ' ObjFactura.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString().ToEntero() ' ObjFactura.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString() ' ObjFactura.EnviarA.EnvioNoExt = Row("EnvioNoExt").ToString() ' ObjFactura.EnviarA.EnvioNoInt = Row("EnvioNoInt").ToString() ' ObjFactura.EnviarA.EnvioColonia = Row("EnvioColonia").ToString() ' ObjFactura.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString() ' ObjFactura.EnviarA.EnvioEstado = Row("EnvioEstado").ToString() ' ObjFactura.EnviarA.EnvioCP = Row("EnvioCP").ToString() ' ObjFactura.EnviarA.EnvioTel = Row("EnvioTel").ToString() ' ObjFactura.EnviarA.EnvioContacto = Row("EnvioContacto").ToString() ' ObjFactura.EnviarA.EnvioDepartamento = Row("EnvioDepartamento").ToString() ' 'ObjFactura.EnviarA.EnvioPedidoContrato = Row("EnvioPedidoContrato").ToString() ' Next ' End If 'End If 'Amortizacion ObjFactura.CveTipoRelacion = -1 'If ObjFactura.CveTipoRelacion > 0 Then ' Select Case ObjFactura.CveTipoRelacion ' Case 7 ' ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" ' ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" ' If ListaAnticiposAplicados IsNot Nothing Then ' For Each Ant As Modelos.MAnticipoRelacionado In ListaAnticiposAplicados ' ObjFactura.Timbre.CFDIRelacionados.UUID.Add(Ant.FolioFiscal) ' Next ' End If ' 'ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) ' End Select 'End If ObjFactura.AplicaDevolucion = Me.AplicaDevolucion ObjFactura.CveTipoAmortizacionAnticipo = -1 If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso NuevaFactura = 1 Then ' refacturación ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero() End If ' If CveCliente > 0 Then ObjFactura.Timbre = PreParaTimbre(ObjFactura) 'SI SE ESTA EDITANDO ACTUALIZA LOS IMPORTES DEL DT If GvImpuestosLocales2.Visible AndAlso GvImpuestosLocales2.Enabled Then For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then Dim DrsImpuestos As DataRow() = TmpDTImpuestos.Select($"CveImpuestoLocal={gvr.DataKey("CveImpuestoLocal")}") If DrsImpuestos IsNot Nothing AndAlso DrsImpuestos.Length = 1 Then DrsImpuestos(0)("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble End If End If Next End If 'INE COMPLEMENTO 'If RblComplementos.SelectedValue.ToEntero() > 0 Then ' ObjFactura.CveComplementoTimbrado = RblComplementos.SelectedValue.ToEntero() ' Dim INE As New Modelos.ComplementoINE ' Select Case RblComplementos.SelectedValue.ToEntero() ' Case 5 ' INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() ' INE.INETipoProceso = "Ordinario" ' INE.INETipoComite = "Directivo Estatal" ' INE.INEEntidad = DdlINEEntidad.SelectedValue ' Case 6 ' INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() ' INE.INETipoProceso = "Ordinario" ' INE.INETipoComite = "Ejecutivo Estatal" ' INE.INEEntidad = DdlINEEntidad.SelectedValue ' Case 7 ' INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() ' INE.INETipoProceso = "Ordinario" ' INE.INETipoComite = "Ejecutivo Nacional" ' Case 8 ' INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() ' INE.INETipoProceso = DdlTipoCampaña.SelectedValue ' INE.INETipoComite = DdlAmbitoComplemento.SelectedValue ' INE.INEEntidad = DdlINEEntidad.SelectedValue ' Case Else ' INE.INEIdContabilidad = 0 ' INE.INETipoProceso = "" ' INE.INETipoComite = "" ' INE.INEEntidad = "" ' End Select ' ObjFactura.ComplementoINE = INE 'End If ObjFactura.CveTipoRetencion = DdlTipoRetencion.SelectedValue.ToEntero() ObjFactura.DescuentoProntoPago = HdnProntoPago.Value.ToDecimal() ObjFactura.NuevaFactura = Me.NuevaFactura ObjFactura.EsGarantia = Me.EsGarantia 'ASIGNAR RFC RECEPTOR If ObjFactura.Timbre IsNot Nothing Then If ObjFactura.Timbre.Receptor IsNot Nothing Then ObjFactura.RFCReceptor = ObjFactura.Timbre.Receptor.RFC End If End If ObjFactura.DtMercancias = DtMercancias End Sub Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre Dim Timbre As New CFDITimbre Timbre.Comprobante.Version = "4.0" 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.FechaCP Timbre.Comprobante.FormadePago = Obj.FormaPagoSAT33 Timbre.Comprobante.CondicionesdePago = If(UsuarioActual.CveEmpresa.Contiene(15, 76), "No Aplica", 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 Timbre.Comprobante.LugarExpedicion = Obj.SubProyecto.CP If Timbre.Comprobante.LugarExpedicion = "" Then Dim aa As String = "no se guardo lugar de expedicion" aa.GuardaLog() End If Timbre.Comprobante.Confirmacion = "" If Obj.FacturarSucursal Then Timbre.Receptor.RFC = Obj.ClienteSucursal.RFC Timbre.Receptor.Nombre = Obj.ClienteSucursal.Nombre Timbre.Receptor.DomicilioFiscalReceptor = Obj.ClienteSucursal.CP Else Timbre.Receptor.RFC = Obj.Cliente.RFC Timbre.Receptor.Nombre = Obj.Cliente.Nombre Timbre.Receptor.DomicilioFiscalReceptor = Obj.Cliente.CP End If Timbre.Receptor.RegimenFiscalReceptor = Obj.Cliente.CodigoRegimenFiscal Timbre.Receptor.ResidenciaFiscal = "" Timbre.Receptor.NumeroRegistroTributario = "" Timbre.Receptor.UsoCFDI = Obj.ClaveUsoCFDI Timbre.Comprobante.TipoComprobante = If(Obj.TipoDocto.Contiene("Ing", "Ant"), "I", If(Obj.TipoDocto.Contiene("Egs", "Dev"), "E", "")) If Timbre.Comprobante.TipoComprobante = "E" Then If Obj.TipoDocto = "Egs" Then Timbre.CFDIRelacionados.TipoRelacion = "01" Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso" End If If Obj.TipoDocto = "Dev" Then Timbre.CFDIRelacionados.TipoRelacion = "03" Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso" End If Obj.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero() 'If HdnFolioFiscalNC.Value <> "0" And HdnFolioFiscalNC.Value <> "" Then Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) End If ' cuando es refacturacoin es cfdirelacionado, con relacion 04 'If Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then ' Timbre.CFDIRelacionados.TipoRelacion = "04" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso" ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) 'End If 'If HdnTipoDescuento.Value = "3" And DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() > 0 Then ' Timbre.CFDIRelacionados.TipoRelacion = "07" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" 'Else ' 'SI LA FACTURA VIENE DE SER CANCELADA SISTEMA CUANDO SE REFACTURO NO HAY QUE RELACIONAR ' If (CveEstatusFacturaPadre > 0 AndAlso CveEstatusFacturaPadre <> 4) OrElse (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) OrElse HdnFolioFiscalNC.Value.ToString() <> "" Then ' If Obj.CveTipoRelacion > 0 Then ' Select Case Obj.CveTipoRelacion ' Case 1 ' Timbre.CFDIRelacionados.TipoRelacion = "01" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "01-Nota de Crédito aplicada a Ingreso" ' Case 2 ' Timbre.CFDIRelacionados.TipoRelacion = "02" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "02-Nota de débito de los documentos relacionados" ' Case 3 ' Timbre.CFDIRelacionados.TipoRelacion = "03" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "03-Devolución aplicada a Ingreso" ' Case 4 ' Timbre.CFDIRelacionados.TipoRelacion = "04" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "04-Sustitución de los CFDI Previos" ' Case 7 ' Timbre.CFDIRelacionados.TipoRelacion = "07" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" ' Case 8 ' Timbre.CFDIRelacionados.TipoRelacion = "08" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "08-Factura generada por pagos en parcialidades " ' Case 9 ' Timbre.CFDIRelacionados.TipoRelacion = "09" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "09-Factura generada por pagos diferidos" ' End Select ' If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then ' For Each Dr As DataRow In DtVentasNC.Rows ' Timbre.CFDIRelacionados.UUID.Add(Dr("FolioFiscal").ToString()) ' Next ' Else ' If ListaAnticiposAplicados IsNot Nothing AndAlso ListaAnticiposAplicados.Count > 0 Then ' For Each Ant As Modelos.MAnticipoRelacionado In ListaAnticiposAplicados ' Timbre.CFDIRelacionados.UUID.Add(Ant.FolioFiscal) ' Next ' Else ' If Not String.IsNullOrEmpty(HdnFolioFiscalNC.Value.Trim()) AndAlso HdnFolioFiscalNC.Value <> "0" Then ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) ' End If ' End If ' End If ' End If ' End If 'End If ''SI LAS FACTURAS SE RELACIONARAN MANUALMENTE SE AGREGAN 'If UsuarioActual.TienePermisoProceso(321) AndAlso Me.AplicaRelacionManual AndAlso DdlTipoRelacionARelacionar.SelectedValue.ToEntero() > 0 Then ' Dim CveTipoRelacion As Integer = DdlTipoRelacionARelacionar.SelectedValue.ToEntero() ' Obj.CveTipoRelacion = DdlTipoRelacionARelacionar.SelectedValue.ToEntero() ' Dim RowTipoRelacion As DataRow = GlobalDTVtaTiposRelacion().FiltroPrimero($"CveTipoRelacion = {CveTipoRelacion}") ' Timbre.CFDIRelacionados.TipoRelacion = RowTipoRelacion("SATClaveTipoRelacion").ToString() ' Timbre.CFDIRelacionados.TipoRelacionTexto = RowTipoRelacion("SATTipoRelacion").ToString() ' For Each GvRow As GridViewRow In GvFacturasRelacionadas.Rows ' If GvRow.RowType = DataControlRowType.DataRow Then ' Timbre.CFDIRelacionados.UUID.Add(GvRow.DataKey("FolioFiscal").Replace("test", "")) ' End If ' Next '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 i As Integer = 1 Dim tPS As String 'detalles 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 tPS = tPS.Replace("|", " ") If tPS.Length >= 1000 Then Dim tPSRecortado As String = tPS.Remove(999, tPS.Length - 999) tPS = tPSRecortado 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.RoundSQL(2), .Unidad = drr("UM").ToString(), .ClaveUnidad = drr("SATClaveUM").ToString(), .ClaveProdServ = drr("SATClaveProdServ").ToString(), .Noidentificacion = drr("Noidentificacion").ToString(), .CuentaPredial = drr("CuentaPredial").ToString(), .ImporteGravaIVAAdicional = drr("ImporteIEPS").ToString().ToDecimal, .ObjetoImpuesto = drr("CodigoObjetoImpuesto").ToString(), .NumeroPedimento = drr("NumeroPedimento").ToString} 'verifica suma subtotales If i = Obj.DtDetalle.Rows.Count AndAlso totSubTotal.RoundSQL(2) <> concepto.Importe.RoundSQL(2) AndAlso Math.Abs(totSubTotal.RoundSQL(2) - concepto.Importe.RoundSQL(2)) <= 0.01 Then 'proceso de ajusta de decimales concepto.Importe = totSubTotal 'concepto.ValorUnitario = totSubTotal / concepto.Cantidad 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, y si la BASE de calculo es mayor a cero ' si es objimp = 01, significa que no lleva desglose de impuesto, está exento If concepto.ObjetoImpuesto <> "01" AndAlso Timbre.Comprobante.Total > 0 AndAlso (concepto.Importe - concepto.Descuento + concepto.ImporteGravaIVAAdicional > 0) Then concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = (concepto.Importe - concepto.Descuento + concepto.ImporteGravaIVAAdicional).RoundSQL(6), .TasaOCuota = drr("PorcentajeIVA").ToString().ToDecimal, .Impuesto = "002", .Importe = drr("ImporteIVA").ToString().ToDecimal}) End If If concepto.ObjetoImpuesto <> "01" AndAlso drr("ImporteIEPS").ToString().ToDouble > 0 Then concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = (concepto.Importe - concepto.Descuento).RoundSQL(6), .TasaOCuota = drr("PorcentajeIEPS").ToString().ToDecimal, .Impuesto = "003", .Importe = drr("ImporteIEPS").ToString().ToDecimal}) End If If concepto.ObjetoImpuesto <> "01" AndAlso drr("ImporteRetIVA").ToString().ToDouble > 0 Then 'si hay retenciones concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = (concepto.Importe - concepto.Descuento).RoundSQL(6), .TasaOCuota = drr("PorcentajeRetIVA").ToString().ToDecimal, .Impuesto = "002", .Importe = drr("ImporteRetIVA").ToString().ToDecimal}) End If If concepto.ObjetoImpuesto <> "01" AndAlso drr("ImporteRetISR").ToString().ToDouble > 0 Then 'retención de ISR concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = (concepto.Importe - concepto.Descuento).RoundSQL(6), .TasaOCuota = drr("PorcentajeRetISR").ToString().ToDecimal, .Impuesto = "001", .Importe = drr("ImporteRetISR").ToString().ToDecimal}) End If 'si el codigo objeto impuesto es 02 y no tiene desglose de impuestos por el descuento, debe asignar el valor 04 - Si objeto de impuesto y no causa impuesto If concepto.Impuestos.Count = 0 AndAlso concepto.ObjetoImpuesto = "02" AndAlso (concepto.Importe - concepto.Descuento + concepto.ImporteGravaIVAAdicional).RoundSQL(2) = 0.00D Then concepto.ObjetoImpuesto = "04" End If Timbre.Conceptos.Add(concepto) i += 1 Next 'RMF. faltan impuestos locales If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto IN (1,3) ").Rows.Count > 0 Then For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto IN (1,3) ").Rows If DrImpuestosLocales("Importe").ToString().ToDecimal > 0 Then Dim ret As New CFDIRetencionesLocales With { .TasaRetencion = DrImpuestosLocales("Porcentaje").ToString().ToDecimal, .ImpuestoLocalRetenido = DrImpuestosLocales("ImpuestoLocal").ToString(), .Importe = DrImpuestosLocales("Importe").ToString().ToDecimal(If(Obj.ConvertirPesos, Obj.TipoCambio, 1)).RoundSQL(2) } Timbre.RetencionesLocales.Add(ret) End If Next End If If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows.Count > 0 Then For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows If DrImpuestosLocales("Importe").ToString().ToDecimal > 0 Then Dim ret As New CFDITrasladosLocales With {.TasaTraslado = DrImpuestosLocales("Porcentaje").ToString().ToDecimal, .ImpuestoLocalTraslado = DrImpuestosLocales("ImpuestoLocal").ToString(), .Importe = DrImpuestosLocales("Importe").ToString().ToDecimal(If(Obj.ConvertirPesos, Obj.TipoCambio, 1))} Timbre.TrasladosLocales.Add(ret) End If Next End If Dim AplicaComercioExteriorSubProyecto As Boolean = True 'If ChkEmitirComercioExterior.Checked Then ' 'AplicaComercioExteriorSubProyecto = If(GlobalDTSubProyectos(-1, Obj.CveSubProyecto, CveEmpresa:=UsuarioActual.CveEmpresa)(0)("AplicaComercioExterior").ToString() = "True", True, False) ' Timbre.Complementos.ComercioExterior11.AplicaComercioExteriorSubProyecto = AplicaComercioExteriorSubProyecto ' 'DATOS GENERALES ' Timbre.Comprobante.Exportacion = "02" ' Timbre.Complementos.ComercioExterior11.TipoOperacion = GlobalDTTipoOperacion().FiltraParametros($"CveTipoOperacion={CveTipoOperacion}")(0)("ClaveSATTipoOperacion").ToString() ' Timbre.Complementos.ComercioExterior11.ClavedePedimento = GlobalDTClavePedimento().FiltraParametros($"CvePedimento={CvePedimento}")(0)("ClaveSATPedimento").ToString() ' Timbre.Complementos.ComercioExterior11.CertificadoOrigen = "0" ' Timbre.Complementos.ComercioExterior11.Incoterm = GlobalDTIncoterm.FiltroPrimeroValor("ClaveSATIncoterm", $"CveIncoterm={DdlIncoterm.SelectedValue}") ' Timbre.Complementos.ComercioExterior11.Subdivision = "0" ' Timbre.Complementos.ComercioExterior11.TipoCambioUSD = If(Obj.CveMoneda = 1, 1, Obj.TipoCambio) ' Timbre.Complementos.ComercioExterior11.MotivoTraslado = "" ' 'If Timbre.Comprobante.TipoComprobante = "T" Then ' ' Timbre.Complementos.ComercioExterior11.MotivoTraslado = GlobalDTSATMotivoTraslado.FiltroPrimeroValor("ClaveSATMotivoTraslado", $"CveMotivoTraslado={DdlSATMotivoTraslado.SelectedValue}") ' 'Else ' ' Timbre.Complementos.ComercioExterior11.MotivoTraslado = "" ' 'End If ' 'EMISOR ' Dim Dr As DataRow ' Dr = Nothing ' If GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).Rows.Count > 0 Then ' Dr = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa)(0) ' End If ' Timbre.Complementos.ComercioExterior11.Emisor.CURP = UsuarioActual.Empresa.CURP ' Timbre.Complementos.ComercioExterior11.Emisor.Calle = Dr("Calle").ToString() ' Timbre.Complementos.ComercioExterior11.Emisor.NumeroExterior = Dr("NoExt").ToString() ' Timbre.Complementos.ComercioExterior11.Emisor.NumeroInterior = Dr("NoInt").ToString() ' Timbre.Complementos.ComercioExterior11.Emisor.Colonia = Dr("ClaveSATColonia").ToString() ' Timbre.Complementos.ComercioExterior11.Emisor.Localidad = "" ' Timbre.Complementos.ComercioExterior11.Emisor.Municipio = Dr("ClaveSATMunicipio").ToString() ' Timbre.Complementos.ComercioExterior11.Emisor.Estado = Dr("ClaveSATEstado").ToString() ' Timbre.Complementos.ComercioExterior11.Emisor.Pais = Dr("ClaveSATPais").ToString() ' Timbre.Complementos.ComercioExterior11.Emisor.CP = Dr("ClaveSATCP").ToString() ' Dim ComExtPais, ComExtEstado, ComExtMunicipio, ComExtColonia, ComExtCalle, ComExtNumero, ComExtCP As String ' ComExtColonia = "" : ComExtMunicipio = "" ' ComExtPais = GlobalDTGralPaises.FiltroPrimeroValor("ClaveSATPais", $"CvePais={DdlComExtPais.SelectedValue}") ' ComExtCalle = TxtComExtCalle.Text.Trim ' ComExtNumero = TxtComExtNumero.Text.Trim ' ComExtCP = TxtComExtCP.Text.Trim ' If ComExtPais = "MEX" Then ' ComExtEstado = GlobalDTGralEstados(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}") ' ComExtMunicipio = GlobalDTGralMunicipios(ComExtEstado).FiltroPrimeroValor("ClaveSATMunicipio", $"CveMunicipio={DdlComExtMunicipio.SelectedValue}") ' ComExtColonia = GlobalDTGralColonias("-1", "-1", "-1", CveColonia:=DdlComExtColonia.SelectedValue.ToEntero).FiltroPrimeroValor("ClaveSATColonia", "") ' Else ' If ComExtPais.Contiene("USA", "CAN") Then ' ComExtEstado = GlobalDTGralEstados(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}") ' Else ' ComExtEstado = TxtComExtEstado.Text.Trim ' End If ' ComExtMunicipio = TxtComExtMunicipio.Text.Trim ' ComExtColonia = TxtComExtColonia.Text.Trim ' End If ' 'RECEPTOR ' Timbre.Complementos.ComercioExterior11.Receptor.NumRegIdTrib = If(Timbre.Comprobante.Version = "4.0", Obj.Cliente.NumRegIdTrib, "") ' EN LA VERSION 3.3 NO DEBE DE REGISTRARSE ESTE VALOR ' Timbre.Complementos.ComercioExterior11.Receptor.Calle = ComExtCalle ' Timbre.Complementos.ComercioExterior11.Receptor.NumeroExterior = ComExtNumero ' Timbre.Complementos.ComercioExterior11.Receptor.NumeroInterior = "" ' Timbre.Complementos.ComercioExterior11.Receptor.Colonia = ComExtColonia ' Timbre.Complementos.ComercioExterior11.Receptor.Localidad = "" ' Timbre.Complementos.ComercioExterior11.Receptor.Referencia = Obj.Cliente.ReferenciaFiscal ' Timbre.Complementos.ComercioExterior11.Receptor.Municipio = ComExtMunicipio ' Timbre.Complementos.ComercioExterior11.Receptor.CP = ComExtCP ' Timbre.Complementos.ComercioExterior11.Receptor.Estado = ComExtEstado ' Timbre.Complementos.ComercioExterior11.Receptor.Pais = ComExtPais ' Timbre.Receptor.ResidenciaFiscal = Obj.Cliente.ClaveSATPais ' Timbre.Receptor.NumeroRegistroTributario = Obj.Cliente.NumRegIdTrib ' ''DESTINATARIO ' 'If ChkAplicaDestinatario.Checked AndAlso DdlDirecionDestinatario.SelectedValue.ToEntero() > 0 Then ' ' Dim RowDireccion As DataRow = Nothing ' ' Dim ObjClientes As New ClsClientes ' ' If ObjClientes.DireccionEnvioGet(DdlDirecionDestinatario.SelectedValue.ToEntero(), CveCliente, -1) Then ' ' RowDireccion = ObjClientes.DtResultados.Rows(0) ' ' End If ' ' ObjClientes.Dispose() ' ' If RowDireccion IsNot Nothing Then ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Nombre = RowDireccion("EnvioContacto").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Calle = RowDireccion("EnvioDireccion").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.NumeroExterior = RowDireccion("EnvioNoExt").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.NumeroInterior = "" ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Colonia = "" ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Localidad = RowDireccion("NombreLocalidad").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Referencia = "" ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Municipio = RowDireccion("NombreMunicipio").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.CP = RowDireccion("EnvioCP").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Estado = RowDireccion("NombreEstado").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.Pais = RowDireccion("ClaveSATPais").ToString() ' ' Timbre.Complementos.ComercioExterior11.Destinatario.NumRegIdTrib = RowDireccion("COM_NumRegIdTrib").ToString() ' ' End If ' 'Else ' ' Timbre.Complementos.ComercioExterior11.Destinatario = Nothing ' 'End If ' ''MERCANCIAS ' 'For Each Gvr As GridViewRow In GvComercioExterior.Rows ' ' Dim mercancia As New CFDIComercioExterior11Mercancias With {.CantidadAduana = Gvr.FCTextBox("TxtCantidad").Text.ToDecimal, ' ' .FraccionArancelaria = Gvr.DataKey("ClaveSATFraccionArancelaria").ToString(), ' ' .UnidadAduana = Gvr.DataKey("ClaveSATUnidadAduana").ToString(), ' ' .ValorDolares = Math.Round(Gvr.FCTextBox("TxtCantidad").Text.ToDecimal * Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, 2), ' ' .ValorUnitarioAduana = Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, ' ' .NoIdentificacion = Gvr.DataKey("Codigo")} ' ' If Gvr.FCTextBox("TxtMarca").Text <> "" Then ' ' mercancia.DescripcionesEspecificas.Marca = Gvr.FCTextBox("TxtMarca").Text ' ' End If ' ' Timbre.Complementos.ComercioExterior11.Mercancias.Add(mercancia) ' ' i += 1 ' 'Next 'Else ' Timbre.Complementos.ComercioExterior11.AplicaComercioExteriorSubProyecto = False 'End If Return Timbre End Function Private Sub PrepararTimbrado(ByRef FM As Modelos.FemsaFactura, ByRef TmpDT7Eleven As DataTable, ByRef TmpDTComplementosTimbrado As DataTable) 'FM.AplicaFEMSA = AplicaFEMSA 'FM.FEMSA_NumSociedad = TxtFEMSA_NumSociedad.Text.Trim 'FM.FEMSA_NumProveedor = TxtFEMSA_NumProveedor.Text.Trim 'FM.FEMSA_Mail = TxtFEMSA_Mail.Text.Trim 'FM.FEMSA_Version = TxtFEMSA_Version.Text.ToEntero() 'FM.FEMSA_NumPedido = TxtFEMSA_NumPedido.Text.Trim.ToLong 'FM.FEMSA_NumEntrada = TxtFEMSA_NumEntrada.Text.Trim 'FM.FEMSA_NumRemision = TxtFEMSA_NumRemision.Text.Trim 'FM.FEMSA_NumSocio = TxtFEMSA_NumSocio.Text.Trim 'FM.FEMSA_CentroCosto = TxtFEMSA_CentroCosto.Text.Trim 'FM.FEMSA_IPeriodoLiquidacion = TxtFEMSA_IPeriodoLiquidacion.Text.Trim 'FM.FEMSA_FPeriodoLiquidacion = TxtFEMSA_FPeriodoLiquidacion.Text.Trim 'FM.FEMSA_CodRetencion1 = TxtFEMSA_CodRetencion1.Text.Trim 'FM.FEMSA_CodRetencion2 = TxtFEMSA_CodRetencion2.Text.Trim FM.AplicaFEMSA = False FM.FEMSA_NumSociedad = "" FM.FEMSA_NumProveedor = "" FM.FEMSA_Mail = "" FM.FEMSA_Version = 0 FM.FEMSA_NumPedido = 0 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") = Txt7ElevenNumProveedor.Text.Trim() 'Row("sevenElevenFolio") = Txt7ElevenFolio.Text.Trim() 'Row("sevenElevenTienda") = Txt7ElevenTienda.Text.Trim() 'Row("sevenElevenFecha") = Txt7ElevenFecha.Text.Trim() 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 'If RblComplementos.SelectedValue.ToEntero() > 0 Then ' Select Case RblComplementos.SelectedValue.ToEntero() ' Case 5 ' Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() ' Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() ' Row2("TipoProceso") = "Ordinario" ' Row2("TipoAmbito") = "Directivo Estatal" ' Row2("Entidad") = DdlINEEntidad.SelectedValue ' Case 6 ' Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() ' Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() ' Row2("TipoProceso") = "Ordinario" ' Row2("TipoAmbito") = "Ejecutivo Estatal" ' Row2("Entidad") = DdlINEEntidad.SelectedValue ' Case 7 ' Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() ' Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() ' Row2("TipoProceso") = "Ordinario" ' Row2("TipoAmbito") = "Ejecutivo Nacional" ' Row2("Entidad") = "" ' Case 8 ' Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() ' Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() ' Row2("TipoProceso") = DdlTipoCampaña.SelectedValue ' Row2("TipoAmbito") = DdlAmbitoComplemento.SelectedValue ' Row2("Entidad") = DdlINEEntidad.SelectedValue ' End Select 'Else Row2("CveComplemento") = "" Row2("IdContabilidad") = "" Row2("TipoProceso") = "" Row2("TipoAmbito") = "" Row2("Entidad") = "" 'End If TmpDTComplementosTimbrado.Rows.Add(Row2) End Sub #End Region #Region " GUARDAR - VENTA, PREPOLIZAS, INV, ESTIMACIONES, AC, NOTA DE CRÉDITO " Private Sub GuardarVenta(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjAcum As ClsAcumuladores, ByRef ObjContr As ClsContratos, factura As Modelos.Factura, ByRef TmpDTDetalle As DataTable, CveNCaVincular As Integer, Optional ByRef ObjBancos As ClsBancos = Nothing, Optional ByRef ObjOS As ClsOS = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, ByRef Optional ObjCGame As ClsCGame = Nothing, ByRef Optional ObjCliente As ClsClientes = Nothing, Optional EsNCAmortizacion As Boolean = False, Optional NCDescuento As Boolean = False, Optional ListaNCDescuento As List(Of Modelos.Factura) = Nothing, Optional CveAnticipoPadre As Integer = -1) Dim Msgok As New StringBuilder Dim CveAlmacenTraspasoOrigen As Integer = -1 Dim CveAlmacenTraspasoDestino As Integer = -1 Dim EsDevolucionVenta As Integer = -1 Dim EsInterno As Integer = -1 'Si es devolucion revertimos los almacenes If CvePedido > 0 And TipoContrato = 2 Then EsDevolucionVenta = 1 CveAlmacenTraspasoOrigen = -1 CveAlmacenTraspasoDestino = -1 End If 'VALIDA ENTREGA POR ADELANTADO If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then 'INCRUSTAMOS ALMACEN ENTREGA POR ADELANTADO CUANDO SEA REMISION Y NO TRAIGA ASIGNADO POR EL USUARIO If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then CveAlmacenTraspasoDestino = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString().ToEntero() End If 'SI LA SUCURSAL NO TIENE ENTREGA POR ADELANTADO If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then ErrorList.Add("Ocurrió un error al seleccionar el almacen de entrega por adelantado de la sucursal.") End If End If Dim TotalImpuestoLocal As Double = 0 If GvImpuestosLocales2.Rows.Count > 0 Then For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then If gvr.DataKey("TipoImpuesto") = "5" Then ' cuando es traslado local TotalImpuestoLocal -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble Else ' cuando es retención TotalImpuestoLocal += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble End If End If End If Next End If 'SI LA FACTURA ESTA PAGADA DEBE MARCAR LA DEVOLUCION POR SI SE QUIERE AMORTIZAR If (ObjFacturaNC IsNot Nothing AndAlso ObjFacturaNC.PagadoBancos > 0) AndAlso factura.TipoDocto = "Dev" Then factura.Alfa3 = "DEV" factura.DevolucionImportePagado = ObjFacturaNC.Total / ObjFacturaNC.PagadoBancos 'falta tomar el dato End If Dim tCveTipoPoliza As Integer = -1 If UsuarioActual.CveEmpresa = 140 Then tCveTipoPoliza = 1 ' que sea siempre ingreso. End If Dim TipoContable As Integer = -1 factura.CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardarVenta", factura.CvePlantillaPoliza, factura.Total, factura.Total, factura.CveMoneda, factura.Fecha, If(CveEmpresaCRM > 0, LblEmpresaCRM.Text, factura.Cliente.Nombre), factura.CveUsuario, factura.CveEmpresa, CveTipoPoliza:=tCveTipoPoliza, TipoContable:=TipoContable) Dim RFCReceptor As String = "" If factura.Timbre IsNot Nothing AndAlso factura.Timbre.Receptor IsNot Nothing Then If Not String.IsNullOrEmpty(factura.Timbre.Receptor.RFC) Then RFCReceptor = factura.Timbre.Receptor.RFC.Trim End If End If 'SI NO SE VA TIMBRAR TOMA EL DEL CLIENTE If String.IsNullOrEmpty(RFCReceptor) Then If Not String.IsNullOrEmpty(LblRFC.Text) Then RFCReceptor = LblRFC.Text.Trim End If If factura.FacturarSucursal Then If factura.ClienteSucursal IsNot Nothing Then RFCReceptor = factura.ClienteSucursal.RFC End If End If End If Dim DescripcionVenta As String = "" 'If TxtDescripcionVenta.Text <> "" Then DescripcionVenta = TxtDescripcionVenta.Text If Not ObjVentas.AddVenta(factura.TipoDocto, factura.Folio, factura.CveCliente, factura.CveClienteSucursal, factura.SubTotalTC, factura.DescuentoTC, factura.AmortizacionTC, factura.IVATC, factura.RetIVATC, factura.RetISRTC, factura.TotalTC, factura.CveMoneda, factura.TipoCambio, factura.CveMetodoPago, factura.CondicionesPago, factura.FormaPago, factura.FechaPago, factura.Fecha, factura.MotivoDescuento, factura.Observaciones, factura.FechaEjecucion, factura.CveVendedor, factura.Alfa1, factura.Alfa2, factura.Alfa3, factura.Num1, factura.Num2, factura.Num3, factura.Fech1, factura.Fech2, factura.Fech3, factura.CveCorte, factura.NumeroPersonas, factura.CvePrePoliza, factura.CveUsuario, factura.CveEmpresa, AtencionA:=factura.AtencionA, TelefonoGenerico:="", CveContrato:=factura.CveContrato, CveVentaPadre:=If(AplicaDevolucion, CveVentaDevolucion, factura.CveVentaPadre), Det_FechaOrdenCompra:=factura.Det_FechaOrdenCompra, Det_OrdenCompra:=factura.Det_OrdenCompra, otros:=factura.Otros, Entrega:="-1", Vigencia:=If(DdlTipoComprobante.SelectedValue = "Cot", NowADS(), MinFecha), CveAlmacenTraspasoDestino:=CveAlmacenTraspasoDestino, CveAlmacenTraspasoOrigen:=CveAlmacenTraspasoOrigen, CveDireccionEnvio:=-1, CveOC:=CveOC, IEPS:=factura.IEPSTC, Serie:=factura.Serie, CveCondicionEntrega:=-1, PedidoContrato:="", ObservacionesAlmacen:="", CveSubProyecto:=factura.CveSubProyecto, CveSubProyectoCobranza:=factura.CveSubProyectoCobranza, CveSubProyectoEjecucion:=factura.CveSubProyectoEjecucion, CveFormaPago33:=factura.CveFormaPago33, CveMetodoPago33:=factura.CveMetodoPago33, CveUsoCFDI:=factura.CveUsoCFDI, OrdenCompra:=TxtOrdenCompra.Text, CveCuentaTerminal:=-1, CveTipoRelacion:=factura.CveTipoRelacion, ImpuestoLocal:=TotalImpuestoLocal, CveVentaRelacion:=(If(factura.CveVentaRelacion.ToEntero() > 0, factura.CveVentaRelacion, -1)), ImporteRelacion:=(If(factura.ImporteRelacion <> Nothing, factura.ImporteRelacion, -1)), CveTipoAmortizacionAnticipo:=factura.CveTipoAmortizacionAnticipo, CveEmpresaCRM:=CveEmpresaCRM, EsInterno:=EsInterno, CveAcercamientoCRM:=CveAcercamientoCRM, DiasCredito:=factura.DiasCredito, EsDiasCreditoFijo:=factura.EsDiasCreditoFijo, AnticipoEspecial:=False, Kilometraje:=0, EsAmortizacion:=EsNCAmortizacion, CveTipoRetencion:=factura.CveTipoRetencion, CorreoNotificacion:="", FormaPaqueteria:=1, FacturarSucursal:=factura.FacturarSucursal, VentaDesglosaIEPS:=factura.VentaDesglosaIEPS, RFCReceptor:=RFCReceptor, Adjunto:=Adjunto, DevolucionImportePagado:=factura.DevolucionImportePagado, EsGarantia:=factura.EsGarantia, ServicioDomicilio:=False, CveLineaAdicional:=-1, DescripcionVenta:=DescripcionVenta, CveMedico:=DdlMedico.SelectedValue.ToEntero, CveProcedimiento:=DdlProcedimiento.SelectedValue.ToEntero, CveTipoVenta:=RBLTipoVenta.SelectedValue.ToEntero) Then ErrorList.Add("Ocurrió un error al Generar la Venta.
Revise su factura y cualquier detalle comuníquese a Soporte Técnico") Else ViewState("Serie") = ObjVentas.Serie ViewState("Folio") = ObjVentas.Folio ViewState("FolioActual") = ObjVentas.Folio 'If factura.TipoDocto.Contiene("Dev", "Egs") OrElse DtVentasNC IsNot Nothing OrElse CveEstatusRefacturacion > 0 OrElse CveAnticipoPadre > 0 Then ' If DtVentasNC IsNot Nothing Then ' For Each row As DataRow In DtVentasNC.Rows ' If Not row("CveVenta").ToString().ToEntero() = -1 Then ' If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, row("CveVenta").ToString().ToEntero()) Then ' ErrorList.Add("Ocurrió un error al relacionar las ventas entre si comuníquese a Soporte Técnico") ' End If ' End If ' Next ' Else ' 'SI ES REFACTURACION DEBE AGREGAR LA VENTA ANTERIOR COMO RELACIONADA TAMBIEN ' If Not CveVenta = -1 Then ' If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, CveVenta) Then ' ErrorList.Add("Ocurrió un error al relacionar las ventas entre si comuníquese a Soporte Técnico") ' End If ' Else ' If CveEstatusRefacturacion > 0 AndAlso CveDevolucion > 0 Then ' If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, CveDevolucion) Then ' ErrorList.Add("Ocurrió un error al relacionar las ventas entre si comuníquese a Soporte Técnico") ' End If ' End If ' End If ' 'SI TIENE UN ANTICIPO TAMBIEN DEBE RELACIONARLO ' If CveAnticipoPadre > 0 Then ' If ListaAnticiposAplicados IsNot Nothing Then ' For Each Ant As Modelos.MAnticipoRelacionado In ListaAnticiposAplicados ' If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, Ant.CveVenta) Then ' ErrorList.Add("Ocurrió un error al relacionar las ventas entre si comuníquese a Soporte Técnico") ' End If ' Next ' End If ' 'If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, CveAnticipoPadre) Then ' ' ErrorList.Add("Ocurrió un error al relacionar las ventas entre si comuníquese a Soporte Técnico") ' 'End If ' End If ' End If 'End If 'If UsuarioActual.TienePermisoProceso(321) AndAlso Me.AplicaRelacionManual Then ' For Each GvRow As GridViewRow In GvFacturasRelacionadas.Rows ' If GvRow.RowType = DataControlRowType.DataRow Then ' If GvRow.DataKey("CveVenta").ToEntero() > 0 Then ' If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, GvRow.DataKey("CveVenta").ToEntero()) Then ' ErrorList.Add("Ocurrió un error al relacionar las ventas entre si comuníquese a Soporte Técnico") ' End If ' Else ' Dim FolioFiscalRelacionado As String = GvRow.DataKey("FolioFiscal") ' If Not String.IsNullOrEmpty(FolioFiscalRelacionado) Then ' If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, -1, FolioFiscal:=FolioFiscalRelacionado) Then ' ErrorList.Add("Ocurrió un error al relacionar las ventas entre si comuníquese a Soporte Técnico") ' End If ' End If ' End If ' End If ' Next 'End If ''SI SE SELECCIONO UNA FACTURA PARA DEVOLUCION DE EFECTIVO DEBE ASOCIARLA A LA NOTA DE CREDITO 'If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso factura.TipoDocto = "Egs" AndAlso Me.CveVentaUsadoDevolucionEfectivo > 0 Then ' If Not ObjVentas.AddVentasRelacionadas(ObjVentas.CveVenta, CveVentaUsadoDevolucionEfectivo) Then ' ErrorList.Add("Ocurrió un error al relacionar la venta de devolución de efectivo entre si.") ' End If 'End If End If If ErrorList.Count = 0 AndAlso ObjVentas.CveVenta > 0 Then factura.CveVenta = ObjVentas.CveVenta factura.Serie = ObjVentas.Serie factura.Folio = ObjVentas.Folio ViewState("VentaFolio") = ObjVentas.SerieFolio factura.Timbre.Comprobante.Serie = ObjVentas.Serie factura.Timbre.Comprobante.Folio = ObjVentas.Folio.ToString() If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso Me.CveAutorizacion > 0 Then If Not ObjVentas.UpdateAutorizacionLimite(Me.CveAutorizacion, factura.CveCliente, factura.CveVenta) Then ErrorList.Add("Error al guardar los limites de la autorizacion") End If End If 'Se agregan los PS For Each Row As DataRow In TmpDTDetalle.Rows If Not ObjVentas.AddVentaDetalle(ObjVentas.CveVenta, Row("CvePS").ToString().ToEntero(), Row("Cantidad").ToString().ToDecimal, Row("CveUM").ToString().ToEntero(), Row("PU").ToString().ToDecimal(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("ImporteIVA").ToString().ToDecimal, Math.Round((Row("Total").ToString().ToDecimal(If(factura.ConvertirPesos, factura.TipoCambio, 1)) * (1 + Row("PorcentajeIVA").ToString().ToDecimal(If(factura.ConvertirPesos, factura.TipoCambio, 1)))), 6), Row("Obs").ToString(), Row("Descuento").ToString().ToDecimal(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("TipoDescuento").ToString().ToEntero(), Row("CveSubProyecto").ToString().ToEntero(), Row("CvePresupuestoIngreso").ToString().ToEntero(), TiempoEntrega:=Row("TiempoEntrega").ToString(), CveVentaDetallePadre:=Row("CveVentaDetalle").ToString().ToEntero(), CveContratoDetalle:=Row("CveContratoDetalle").ToString().ToEntero(), CvePromocionDetalle:=Row("CvePromocionDetalle").ToString().ToEntero(), IEPS:=Row("ImporteIEPS").ToString().ToDecimal, CveMovimientoDetallePedido:=Row("CveMovimientoDetallePedido").ToString().ToEntero(), ImporteRetIVA:=Row("ImporteRetIVA").ToString().ToDecimal, ImporteRetISR:=Row("ImporteRetISR").ToString().ToDecimal, PorcentajeIVA:=Row("PorcentajeIVA").ToString().ToDecimal, PorcentajeIEPS:=Row("PorcentajeIEPS").ToString().ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString().ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString().ToDecimal, CuentaPredial:=Row("CuentaPredial").ToString(), CvePrecioLista:=Row("CvePrecioLista").ToString().ToEntero(), CveActivoFijo:=Row("CveActivoFijo").ToString().ToEntero(), NumTurnos:=Row("NumTurnos").ToString().ToDecimal()) Then ErrorList.Add("Ocurrió un error al agregar un Producto o Servicio a la Factura.
Revise su factura y cualquier detalle comuníquese a Soporte Técnico") Exit For Else If CveContrato > 0 AndAlso factura.TipoDocto = "Rem" AndAlso AplicaGastoContrato Then If Not ObjContr.AddContratoGasto(CveContrato, Row("PS").ToString(), Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, factura.Fecha, UsuarioActual.CveUsuario, CveVenta:=ObjVentas.CveVenta) Then ErrorList.Add("Ocurrió un error al agregar el gasto de la Factura.") Exit For End If End If ''Si es devolucion se agregan a la tabla de Vta_VentasDetalleDevolucion 'If factura.AplicaDevolucion Then ' Try ' Dim EsCargo As Integer = If(Row("EsCargo").ToString() = "True", 1, 0) ' If EsCargo = 1 Then ' If Me.ObjFacturaNC IsNot Nothing Then ' Dim CveVentaDetalleUsado As Integer = -1 ' For Each RowIng As DataRow In Me.ObjFacturaNC.DtDetalle.Rows ' If RowIng("Cantidad").ToString().ToDecimal() = Row("Cantidad").ToString().ToDecimal() AndAlso RowIng("CvePS").ToString().ToEntero() = Row("CvePS").ToString().ToEntero() Then ' CveVentaDetalleUsado = RowIng("CveVentaDetalle").ToString().ToEntero() ' Exit For ' End If ' Next ' If CveVentaDetalleUsado > 0 Then ' If Not ObjVentas.AddVentaDetalleDevolucion(CveVentaDetalleUsado, ObjVentas.CveVentaDetalle, Row("Cantidad").ToString().ToDouble) Then ' ErrorList.Add("Ocurrió un error al agregar la venta detalle devolución.") ' End If ' End If ' End If ' Else ' If Not ObjVentas.AddVentaDetalleDevolucion(Row("CveVentaDetalle").ToString().ToEntero(), ObjVentas.CveVentaDetalle, Row("Cantidad").ToString().ToDouble) Then ' ErrorList.Add("Ocurrió un error al agregar la venta detalle devolución.") ' End If ' End If ' Catch ex As Exception ' ErrorList.Add("Ocurrió un error al agregar la venta detalle devolución.") ' End Try ' If ErrorList.Count = 0 Then ' If Not ObjEventos.AddEventoBitacora(String.Format("Se aplicó una devolución en Folio: {1}", factura.CveVenta, factura.SerieFolio), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVentaDevolucion) Then ' ErrorList.Add("Ocurrió un error al agregar la bitacora de devolución.") ' End If ' End If 'End If 'Dim TmpDr As DataRow = TmpDTDetalle.Select($"Consec = {Row("Consec").ToString()}")(0) 'TmpDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle 'Try ' If DtInv IsNot Nothing AndAlso DtInv.Rows.Count > 0 Then ' Dim InvDr As DataRow = DtInv.Select($"Consec = {Row("Consec").ToString()}")(0) ' InvDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle ' End If 'Catch ex As Exception 'End Try 'SI SE FACTURA UNA RNC SE MUESTRA 'If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso factura.TipoDocto = "Egs" Then ' If Row("CveVentaDetalleRNC").ToString().ToEntero() > 0 Then ' If Not ObjVentas.AddVentaDetalleRNCFacturada(Row("CveVentaDetalleRNC").ToString().ToEntero(), ObjVentas.CveVentaDetalle, Row("Cantidad").ToString().ToDecimal()) Then ' ErrorList.Add("Ocurrió un error al agregar la venta detalle devolución.") ' End If ' Dim EsCargo As Boolean = False ' Dim ListaRNC As List(Of Modelos.Factura) = Nothing ' If NCDescuento Then ' ListaRNC = ListaNCDescuento ' Else ' ' EsCargo = RblRNCTipo.SelectedValue = "1" ' ListaRNC = ListaRemisionesNC ' End If ' End If 'End If End If Next ''Orden Produccion' 'If UsuarioActual.CveEmpresa.Contiene(126) Then ' If ObjVentas.CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero() > 0 Then ' If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), ObjVentas.CveVenta) Then ' ErrorList.Add("Ocurrió un error al actualizar la orden de producción") ' End If ' End If 'End If 'PedidoA' 'If ObjVentas.CveVenta > 0 And CvePedidoA > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem") Then ' If Not ObjCliente.UpdateEstatusPedido(CvePedidoA, 18, -1, UsuarioActual.CveUsuario, CveRemision:=factura.CveVenta) Then ' ErrorList.Add("Ocurrió un error al actualizar el estatus del pedidoA") ' Else ' 'Remision ' If Not ObjEventos.AddEventoBitacora($"Remisionado de autorización en: {ObjFactura.SerieFolio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CvePedidoA) Then ' ErrorList.Add("Ocurrió un error al agregar bitácora de Autorización") ' End If ' End If 'End If 'Contratos 'If factura.CveContrato > 0 AndAlso Me.CveContratoTipo <> 33 Then ' If factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing") Then ' GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, 1) ' 'CUANDO ES NOTA DE CRÉDITO, NO DEBE DE CONSIDERAR AVANCE, CUANDO ES NOTA DE CRÉDITO POR AMORTIZACIÓN ' ElseIf factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") AndAlso Not EsNCAmortizacion Then ' GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, -1) ' End If 'End If 'Impuestos Locales For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then If Not ObjVentas.AddVentaImpuestoLocales(factura.CveVenta, gvr.DataKey("CveImpuestoLocal").ToString().ToEntero(), gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1))) Then ErrorList.Add("Ocurrió un error al Guardar Impuestos Locales") End If End If End If Next If DTmpF.Rows.Count > 0 Then For Each Row As DataRow In DTmpF.Rows If Not ObjVentas.AddVentasFirmas(factura.CveVenta, Row("Titulo").ToString(), Row("Nombre").ToString(), Row("Puesto").ToString(), Row("Lado").ToString().ToEntero()) Then ErrorList.Add("Ocurrio un error al Guardar Firmas") End If Next End If If ErrorList.Count = 0 AndAlso ChkRequiereTecnico.Checked Then GeneraOS(ObjVentas.IniciaTransacSQL, ErrorList) End If 'Si viene de OS, Se guarda CveVenta en OS If CveOS > 0 Then If Not ObjOS.UpdateVentaOS(factura.CveVenta, CveOS) Then ErrorList.Add("Ocurrió un error al guardar la venta en Ordenes de Servicio") End If End If If ErrorList.Count = 0 Then 'prepoliza GuardarVentaPrePolizas(ObjConta, factura, TmpDTDetalle, CveNCaVincular, ObjBancos, ObjVentas, ObjEventos:=ObjEventos, EsNCAmortizacion:=EsNCAmortizacion, NCDescuento:=NCDescuento, ListaNCDescuento:=ListaNCDescuento, ObjInventario:=ObjInventario, TipoContable:=TipoContable) If ErrorList.Count = 0 Then If ErrorList.Count = 0 Then 'estimaciones 'If Me.CveContratoTipo <> 33 Then ' GuardarVentaEstimaciones(ObjContr, factura) 'End If If ErrorList.Count = 0 Then 'armonizaccionContable 'GuardarVentaAC(ObjVentas, factura, Msgok) If ErrorList.Count = 0 Then 'Impuestos Locales If GuardarVentaImpuestosLocales(ObjVentas, ObjConta, factura) Then ErrorList.Add("Ocurrio un error al Guardar Impuestos Locales") End If End If End If End If End If End If End If End Sub Private Function GeneraOS(ByRef TransacSQL As SqlTransaction, ByRef errorList As List(Of String)) As Boolean Dim Errores As Boolean = False Dim ObjOrdenServicio As New ClsOS(TransacSQL) Dim CveOSTipo As Integer = -1 If ObjOrdenServicio.GetTipoOrdenesServicios(UsuarioActual.CveEmpresa) Then CveOSTipo = ObjOrdenServicio.DtResultados.FiltroPrimeroValor("CveOrdenServicioTipo", " Estatus = 'Activo' ").ToEntero End If Dim EstatusOrdenServicio As Integer = GlobalDTEstatusOrdenServicios(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveEstatusOrdenServicio", "TipoEstatus = 1").ToEntero If ObjOrdenServicio.AddOrdenesServicios(CveCliente, DdlSubProyectoDatos.SelectedValue.ToEntero, UsuarioActual.Nombre, TxtFecha.Text.Replace(",", "").ToDateTime, $"Venta: {Serie}-{FolioActual}", UsuarioActual.CveUsuario, EstatusOrdenServicio, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, CveOSTipo, CveClienteSucursal:=DdlSubProyectoDatos.SelectedValue.ToEntero, Direccion:="", Telefono:="", CveModeloAuto:=-1, Año:="", CveMedico:=DdlMedico.SelectedValue.ToEntero, CveProcedimiento:=DdlProcedimiento.SelectedValue.ToEntero, CveTipoVenta:=RBLTipoVenta.SelectedValue.ToEntero, FechaCita:=TxtFecha.Text.Replace(",", "").ToDateTime) Then CveOS = ObjOrdenServicio.CveOS Else errorList.Add("Se presento un error al guardar la orden de servicio.") Errores = True End If Dim CvePSDetalle As Integer = UsuarioActual.Empresa.Funcionalidad(708).ToEntero If Not CvePSDetalle > 0 Then errorList.Add("No se tiene asignado un producto para la orden de servicio (FNC 708).") Errores = True End If If Not Errores Then Dim CveOsDetalle = ObjOrdenServicio.AddOrdenesServiciosDetalle(ObjOrdenServicio.CveOS, CvePSDetalle, 1, -1, -1, $"Venta: {Serie}-{FolioActual}", False, True, False, -1, "-1", "-1", "-1", "", UsuarioActual.CveUsuario, Archivo:="") If CveOsDetalle > 0 Then 'MENSAJE PRINCIPAL Dim MensajeAlertOS As New StringBuilder MensajeAlertOS.AppendFormat(String.Format("
La Orden de Servicio: {0} se generó correctamente.

", ObjOrdenServicio.Folio)) MensajeAlert.AppendFormat("
", Encripta(String.Format("OP=OS&CVEOS={0}", ObjOrdenServicio.CveOS))) Dim Liga = $"document.location.href=""/OS/RepOrdenesServicios.aspx"";" Alert(MensajeAlertOS.ToString, TipoMensaje.MsgInformacion, Liga) Else errorList.Add("Se presento un error al guardar la el detalle de la orden de servicio.") Errores = True End If End If Return If(Errores, False, True) End Function Private Sub GuardarVentaPrePolizas(ByRef ObjConta As ClsContabilidad, factura As Modelos.Factura, TmpDTDetalleMovimientos As DataTable, CveNCaVincular As Integer, Optional ByRef ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, Optional EsNCAmortizacion As Boolean = False, Optional NCDescuento As Boolean = False, Optional ValorMultiplicador As Integer = 1, Optional ListaNCDescuento As List(Of Modelos.Factura) = Nothing, Optional ObjInventario As ClsInventarios = Nothing, Optional TipoContable As Integer = -1) Dim CveIE As Integer = -1 Dim DT As DataTable = Nothing Dim CveConceptoAfectacion As Integer = 1 'Cliente Dim CveConceptoAntCli As Integer = 3 'Anticipo Cliente Dim CveConceptoVenta As Integer = 4 'Venta Dim CveConceptoCanAnt As Integer = 11 'Cancelacion Anticipos Dim CveConceptoDSV As Integer = 12 ' DSV Dim CveConceptoIVA As Integer = 13 'IVA Trasladado Dim CveConceptoRetIVA As Integer = 8 'Ret IVA Dim CveConceptoRetISR As Integer = 9 'Ret ISR 'P R E P O L I Z A S If DdlTipoComprobante.SelectedValue <> "Cot" Then If factura.CvePrePoliza > 0 Then If ProcesoPrepolizas(ObjConta, factura, CveIE, TmpDTDetalleMovimientos, ValorMultiplicador, ObjBancos, ObjVentas, ObjEventos:=ObjEventos, EsNCAmortizacion:=EsNCAmortizacion, NCDescuento:=NCDescuento, ListaNCDescuento:=ListaNCDescuento, ObjInventario:=ObjInventario, TipoContable:=TipoContable) Then ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If Else ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If End If End Sub Private Function ProcesoPrepolizas(ByRef ObjConta As ClsContabilidad, ObjFactura As Modelos.Factura, CveIE As Integer, TmpDTDetalle As DataTable, Optional ValorMultiplicador As Integer = 1, ByRef Optional ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, Optional EsNCAmortizacion As Boolean = False, Optional NCDescuento As Boolean = False, Optional ListaNCDescuento As List(Of Modelos.Factura) = Nothing, Optional ObjInventario As ClsInventarios = Nothing, Optional TipoContable As Integer = -1) As Boolean Try Dim DT As DataTable Dim CvePlantilaPoliza As Integer Dim PorcentajeAmortizacion As Decimal = 0 Dim sumaAmorticaciones As Decimal = 0 Dim ErrorPrepoliza As Boolean = False Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

" Dim CveCuentaContabilizacion As Integer = 1 Dim tipoCambio As Decimal Dim TCPago As Decimal = 1 Dim CuentasContablesInvalidasSIG As New StringBuilder If ObjFactura.TipoDocto = "Ing" Or ObjFactura.TipoDocto = "Ant" Or ObjFactura.TipoDocto = "Com" Then CvePlantilaPoliza = 4 ElseIf ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then CvePlantilaPoliza = 7 ElseIf ObjFactura.TipoDocto.Contiene("Rem", "RNC") Then CvePlantilaPoliza = 4 End If If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then tipoCambio = ObjFactura.TipoCambio TCPago = GlobalTipoCambio(ObjFactura.Fecha.AddDays(-1)).ToString().ToDecimal ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then If UsuarioActual.CveEmpresa.Contiene(13, 83) Then tipoCambio = GlobalTipoCambio(ObjFactura.Fecha.AddDays(-1)).ToString().ToDecimal Else 'If ChkEmitirComercioExterior.Checked Then ' tipoCambio = GlobalTipoCambio(ObjFactura.Fecha.AddDays(-1)).ToString().ToDecimal 'Else tipoCambio = GlobalTipoCambio(ObjFactura.Fecha).ToString().ToDecimal 'End If End If Else tipoCambio = 1 End If Dim ConceptoContable As Integer Dim TipoMovimiento As Boolean Dim importeMovimiento As Decimal Dim FechaMovimiento As Date = ObjFactura.Fecha Dim Concepto As String = ObjFactura.SerieFolio Dim Referencia As String = ObjFactura.SerieFolio Dim Fecha As Date = NowADS() Dim importeMX As Decimal Dim Multiplicador As Integer Dim CveIEPago As Integer Dim FolioIE As Long Dim CveIEAnticipo As Integer Dim CveSubProyectoVenta As Integer = DdlSubProyectoDatos.SelectedValue.ToEntero() Dim CveSubProyectoContabilizar As Integer Dim SeContabiliza As Boolean = True Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Rem", "RNC", "Cot", "Ped", "Pd2", "PA", "Egs", "Dev") Then AutoConta = False End If Dim UsaComplementariaClientes As Boolean = True If ObjConta.GetPlantillaConceptos(ObjFactura.CveEmpresa, CvePlantilaPoliza) Then Dim dtt As DataTable = ObjConta.DtResultados If ValorMultiplicador = -1 Then dtt = ObjConta.DtResultados.FiltraParametros("", "Orden DESC") ' se ordena contrario al registro para llevar los saldos correctos For Each Row As DataRow In dtt.Rows ConceptoContable = Row("CveConcepto").ToString().ToEntero() TipoMovimiento = If(Row("TipoMovto").ToString() = "True", True, False) importeMovimiento = 0 CveSubProyectoContabilizar = 0 Multiplicador = (Row("Multiplicador").ToString().ToEntero()) Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, ConceptoContable, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", "") Dim PorcentajeImpuesto As Decimal = 0 Select Case ConceptoContable Case 1 'Cliente If Not ObjFactura.TipoDocto.Contiene("Egs", "Rem", "RNC") Then If ObjFactura.CveMoneda > 1 Then ConceptoContable = 291 importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If tipoCambio > 1 Then If importeMovimiento <> 0 AndAlso (UsaComplementariaClientes) Then importeMX = importeMovimiento If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, (importeMovimiento * tipoCambio - importeMovimiento).RoundSQL, 203, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True End If End If End If Dim DtAF As DataTable = TmpDT.FiltraParametros("CveActivoFijo > 0") If DtAF.Rows.Count > 0 Then For Each RowAF As DataRow In DtAF.FiltraParametros("", "", {"CveActivoFijo", "Obs"}).Rows Dim ImporteDepreciado As Decimal = DtAF.SUMD("AFDepreciacion", $"CveActivoFijo = {RowAF("CveActivoFijo")}").RoundSQL(2) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, ImporteDepreciado, (ImporteDepreciado).RoundSQL, 271, Referencia, $"Depreciación {RowAF("Obs")}", CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True End If 'MARCAR EL ACTIVO FIJO COMO VENDEDIDO If Not ErrorPrepoliza AndAlso RowAF("CveActivoFijo").ToString().ToEntero() > 0 Then If Not ObjVentas.UpdateEstatusAFVendido(RowAF("CveActivoFijo").ToString().ToEntero(), UsuarioActual.CveEmpresa, 5) Then ErrorPrepoliza = True End If End If Next End If End If Case 3 'Cliente If ObjFactura.TipoDocto = "Ant" Then ConceptoContable = If(UsuarioActual.CveEmpresa.Contiene(119), 95, ConceptoContable) importeMovimiento = ObjFactura.SubTotal * ValorMultiplicador importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" End If Case 190 'Remisión del cliente If ObjFactura.TipoDocto = "Rem" Then importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" Dim ContabilizableRem As Boolean = False If TipoContable <> -1 Then ContabilizableRem = True End If If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, 190, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=ContabilizableRem, CveSubProyecto:=CveSubProyectoContabilizar) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, importeMX, 193, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=ContabilizableRem, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Else ErrorPrepoliza = True End If importeMovimiento = 0 ViewState("SeGuardoPrePoliza") = True End If Case 277 'Remisión de NC If ObjFactura.TipoDocto = "RNC" Then importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, 277, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, importeMX, 278, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Else ErrorPrepoliza = True End If importeMovimiento = 0 ViewState("SeGuardoPrePoliza") = True End If Case 12 'Nota de Credito If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then Dim ConPreP As ConceptosTipoSaldo = ObtenerCveConceptoPrePoliza(6, ObjFactura.CveMoneda, False, 2) importeMovimiento = ObjFactura.Total * ValorMultiplicador importeMX = (importeMovimiento * tipoCambio * Multiplicador).RoundSQL(2) FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = ObjFactura.CveSubProyecto If ObjFactura.CveMoneda = 2 Then importeMX = importeMovimiento Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, ConPreP.CveConcepto, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If If UsaComplementariaClientes AndAlso ObjFactura.CveMoneda = 2 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, (importeMovimiento * tipoCambio - importeMovimiento).RoundSQL(2), ConPreP.CveConceptoComplementario, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If End If Dim TipoCambioNC As Decimal = 1 If ObjFactura.CveMoneda = 2 Then If tipoCambio > 1 Then TipoCambioNC = tipoCambio Else If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TipoCambioNC = GlobalTipoCambio(ObjFactura.Fecha.AddDays(-1)).ToDecimal Else TipoCambioNC = GlobalTipoCambio(ObjFactura.Fecha).ToDecimal End If End If End If importeMovimiento = 0 importeMX = 0 'APLICA NC SALDOS DIRECTOS If Not ErrorPrepoliza AndAlso DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then For Each Dr As DataRow In DtVentasNC.Rows Dim ObjFacturaRef As New Modelos.Factura(UsuarioActual, Dr("CveVenta").ToString().ToEntero(), UsuarioActual.CveEmpresa, CargaDTDetalle:=False, VerificaAlmacen:=False, CargaDatosCliente:=False, CargaDatosRelacionados:=False) Dim ventaRef As New Venta(ObjFacturaRef, UsuarioActual) ObjFacturaRef.Dispose() Dim Pago As New VentaPago Pago.Fecha = ObjFactura.Fecha Pago.FechaDocumentoRelacionado = ObjFactura.Fecha Pago.ImportePagoVenta = Dr("Importe").ToString().ToDecimal() Pago.ImportePago = Dr("Importe").ToString().ToDecimal() Pago.CveMonedaPago = ObjFactura.CveMoneda Pago.TCPago = TipoCambioNC Pago.TipoPago = "NC" Pago.CveVentaAmortizacion = ObjFactura.CveVenta 'Dr("CveVenta").ToString().ToEntero() Pago.AplicaTraslado = False Pago.Referencia = Concepto 'Pago.CveConceptoPago = 251 ErrorPrepoliza = AplicaPrePolizaPagoVenta(ventaRef, Pago, ObjFactura.CvePrePoliza, ObjConta) If ErrorPrepoliza Then Exit For End If Next If Not ErrorPrepoliza AndAlso ObjConta.ValidacionesPrePoliza(ObjFactura.CvePrePoliza, UsuarioActual, Opcion:=5, AutoConta:=AutoConta) Then If ObjConta.ValorPolizaDescuadre > 0 Then 'ErrorPrepoliza = True GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") End If End If If ErrorPrepoliza Then Exit For End If End If 'APLICA DEVOLUCION SALDOS DIRECTOS If AplicaDevolucion Then Dim importeMovimientoDev As Decimal = TxtTotal.Text.ToDecimal importeMovimientoDev = If(SaldoVentaDevolucion < importeMovimientoDev, SaldoVentaDevolucion, importeMovimientoDev) If importeMovimientoDev > 0 Then Dim importeMXDev As Decimal = importeMovimientoDev * tipoCambio * Multiplicador If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimientoDev.FormatoNumero(2)}" If UsaComplementariaClientes AndAlso tipoCambio > 1 Then importeMXDev = importeMovimientoDev Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * tipoCambio) - importeMovimientoDev).RoundSQL If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, ImporteComplementaria, 203, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura) Then ErrorPrepoliza = True Exit For End If End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, importeMXDev, 91, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True Exit For End If If UsaComplementariaClientes AndAlso TipoCambioFactura > 1 Then importeMXDev = importeMovimientoDev Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * TipoCambioFactura) - importeMovimientoDev).RoundSQL If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, ImporteComplementaria, 207, Referencia, Concepto, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, ImporteME:=If(TipoCambioFactura = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=TipoCambioFactura) Then ErrorPrepoliza = True Exit For End If End If Dim CveConceptoPagoNC As Integer = 251 If ObjFactura.CveMoneda > 1 Then CveConceptoPagoNC = 301 End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, importeMXDev, CveConceptoPagoNC, Referencia, Concepto, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True Exit For End If If tipoCambio <> TipoCambioFactura Then Dim difFluctuacion As Decimal = tipoCambio - TipoCambioFactura Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida Dim TipoMovtoFluctua As Boolean = True If difFluctuacion < 0 Then CveConceptoFluctua = 65 TipoMovtoFluctua = False Else CveConceptoFluctua = 64 TipoMovtoFluctua = True End If Dim ImporteFluctuacion As Decimal = Math.Abs((importeMovimientoDev * difFluctuacion).RoundSQL) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, ImporteFluctuacion, CveConceptoFluctua, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura) Then ErrorPrepoliza = True Exit For End If End If If ObjConta.ValidacionesPrePoliza(ObjFactura.CvePrePoliza, UsuarioActual, Opcion:=2, AutoConta:=AutoConta) Then If ObjConta.ValorPolizaDescuadre > 0 Then GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") End If End If End If End If End If importeMovimiento = 0 Case 136 'Otros Conceptos Dinamicos 'For Each row2 As GridViewRow In GVOtrosConceptos.Rows ' If row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal > 0 Then ' importeMovimiento = row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal * ValorMultiplicador ' CveSubProyectoContabilizar = CveSubProyectoVenta ' If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" ' If importeMovimiento <> 0 Then ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, If(row2.DataKey("TipoMovto").ToString() = "True", True, False), importeMovimiento, importeMovimiento * tipoCambio, row2.DataKey("CveConceptoContable").ToEntero(), Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True ' End If ' End If ' End If 'Next importeMovimiento = 0 Case 11 'Anticipo '[IPP] SI ES REFACTURACION LOS ANTICIPOS NO LOS DEBE APLICAR EN EL INGRESO REFACTURADO (VIEJO) If NuevaFactura = 1 And ObjFactura.CveVenta = CveDevolucion Then Exit Select End If If ObjFactura.TipoDocto = "Ing" AndAlso ValorMultiplicador = -1 Then For Each row2 As GridViewRow In GvAntNC.Rows If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 11 Then importeMovimiento = row2.DataKey("Importe").ToString().ToDecimal * ValorMultiplicador '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMovimiento * tipoCambio, ConceptoContable, Referencia, Concepto, CveVenta:=row2.DataKey("CveVenta").ToEntero(), CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True Exit For Else ViewState("SeGuardoPrePoliza") = True End If End If End If Next End If 'CUANDO APLICAN UNA NOTA DE CREDITO SOBRE UN ANTICIPO If ObjFactura.TipoDocto = "Egs" AndAlso EsNCAmortizacion Then If DtAnticipoAmortizacion IsNot Nothing AndAlso DtAnticipoAmortizacion.Rows.Count > 0 Then For Each RowAnticipo As DataRow In DtAnticipoAmortizacion.Rows Dim CveVentaAnticipo As Integer = RowAnticipo("CveVenta").ToString().ToEntero() importeMovimiento = RowAnticipo("SaldoAnticipo").ToString().ToDecimal If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMovimiento, ConceptoContable, Referencia, Concepto, CveVenta:=CveVentaAnticipo, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True Exit For Else ViewState("SeGuardoPrePoliza") = True End If End If Next End If End If 'cuando es anticipo ' cuando es amortización de nota de crédito, y es la nc ' cuando es amortización por descuento, y es el ingreso ' cuando es amortización en cero 'DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() = 2 AndAlso ObjFactura.TipoDocto.Contiene("Egs") OrElse 'Cuando la funcionalidad de amortizacion en PS esta activa If Not ErrorPrepoliza Then DT = TmpDTDetalle.FiltraParametros($"CvePS = {CvePSAmortizacion}") If DT.Rows.Count > 0 Then For Each Row2 As DataRow In DT.Rows importeMovimiento = Math.Abs(Row2("PU").ToString().ToDecimal) CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMovimiento * tipoCambio, ConceptoContable, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If End If Next End If End If 'PorcentajeAmortizacion = sumaAmorticaciones / TxtTotal.Text.ToDecimal importeMovimiento = 0 Case 91 'Amortizacion Nota de Credito Dim Contabilizable As Boolean = If(UsuarioActual.CveEmpresa = 119, False, True) If ValorMultiplicador = -1 Then 'cuando es cancelación For Each row2 As GridViewRow In GvNC.Rows If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 91 Then importeMovimiento = row2.DataKey("Importe").ToDecimal * ValorMultiplicador sumaAmorticaciones += importeMovimiento If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then Dim CveConceptoPagoNC As Integer = 251 If ObjFactura.CveMoneda > 1 Then CveConceptoPagoNC = 301 End If If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimiento, importeMovimiento * tipoCambio, CveConceptoPagoNC, Referencia, Concepto, CveVenta:=row2.DataKey("CveVentaNC").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimiento, importeMovimiento * tipoCambio, 91, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString().ToEntero(), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then ErrorPrepoliza = True Exit For End If Else ErrorPrepoliza = True Exit For End If End If End If Next Else 'For Each row2 As GridViewRow In GVAnticipos.Rows ' If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 12 Then ' If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then ' importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal ' sumaAmorticaciones += importeMovimiento ' If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" ' CveSubProyectoContabilizar = CveSubProyectoVenta ' If importeMovimiento <> 0 Then ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMovimiento * tipoCambio, ConceptoContable, Referencia, Concepto, CveVenta:=row2.DataKey("CveVenta").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then ' ErrorPrepoliza = True ' End If ' End If ' End If ' End If 'Next If UsuarioActual.Empresa.Funcionalidad(344) = "1" AndAlso ObjFactura.TipoDocto = "Egs" Then Dim ListaNC As List(Of Modelos.Factura) = Nothing If NCDescuento Then ListaNC = ListaNCDescuento Else ListaNC = ListaRemisionesNC End If If ListaNC IsNot Nothing Then For Each ObjRNC As Modelos.Factura In ListaNC If ObjRNC.TipoDocto = "RNC" Then importeMovimiento = ObjRNC.TotalRemNCAplicado * -1 importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" 'ACTUALIZA SI LA VENTA FUE MARCADA CON OTRA PARA EL FILTRO DE USADOS If ObjRNC.Num3 > 0 Then If Not ObjVentas.UpdateVentaRNCUsado(ObjRNC.CveVenta, ObjRNC.Num3.ToEntero()) Then ErrorPrepoliza = True End If End If Dim CveMovimiento As Integer = -1 Dim CveAlmacen As Integer = -1 If ObjInventario IsNot Nothing AndAlso ObjInventario.GetInv_Mov(ObjRNC.CveVenta, UsuarioActual.CveEmpresa) Then CveMovimiento = ObjInventario.DtResultados.FiltroPrimeroValor("CveMovimiento", "CvePS IS NULL AND CveConcepto = 42").ToEntero() CveAlmacen = ObjInventario.DtResultados.FiltroPrimeroValor("CveAlmacen", "CvePS IS NULL AND CveConcepto = 42").ToEntero() End If 'VERIFICA SI TIENE MOVIMIENTO DE ENTRADA DE USADO If CveMovimiento > 0 AndAlso CveAlmacen > 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, 277, Referencia, Concepto, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Dim SubTotalCalculado As Decimal = (importeMovimiento / (1D + ObjRNC.PorcentajeIVA)).ToDecimal Dim Importe318 As Decimal = (SubTotalCalculado * ObjRNC.PorcentajeIVA).RoundSQL(2).ToDecimal() If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, Importe318, Importe318, 318, Referencia, Concepto, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, SubTotalCalculado, SubTotalCalculado, 150, Referencia, Concepto, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=ObjRNC.DtDetalle.MAX("CveClasificacion").ToEntero(), CveSubProyecto:=ObjRNC.CveSubProyecto, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, Contabilizable:=False) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If Else If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, 277, Referencia, Concepto, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, importeMX, 278, Referencia, Concepto, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Else ErrorPrepoliza = True End If End If importeMovimiento = 0 End If Next End If End If If sumaAmorticaciones <> 0 Then Dim CveConceptoPagoNC As Integer = 251 If ObjFactura.CveMoneda > 1 Then CveConceptoPagoNC = 301 End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, sumaAmorticaciones, sumaAmorticaciones * tipoCambio, CveConceptoPagoNC, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If End If End If importeMovimiento = 0 Case 4 'Venta Clasificacion If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC", "Ant", "Egs", "Dev") Then Dim ConceptoContableAplicar As Integer = 4 Dim CveVentaAplicar As Integer = ObjFactura.CveVenta Dim CveVentaAmortizacionAplicar As Integer = -1 If ObjFactura.TipoDocto.Contiene("Egs") And DdlTipoComprobante.SelectedValue = "Ant" And CveDevolucion > 0 And NuevaFactura = 1 Then ConceptoContableAplicar = 11 CveVentaAplicar = CveDevolucion CveVentaAmortizacionAplicar = ObjFactura.CveVenta End If DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto", "PorcentajeIVA", "CveActivoFijo"}) If DT.Rows.Count > 0 Then 'Se agrega movimiento separado por la cuenta de ventas (ER) For Each Row2 As DataRow In DT.Rows importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1} AND PorcentajeIVA = {2} AND ISNULL(CveActivoFijo,-1) = {3}", Row2("CveClasificacion"), Row2("CveSubProyecto"), Row2("PorcentajeIVA"), If(Row2("CveActivoFijo").ToString().ToEntero() > 0, Row2("CveActivoFijo").ToString().ToEntero(), -1))).ToString().ToDecimal()) * ValorMultiplicador importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago Concepto = $"{ObjFactura.SerieFolio} {If(Row2("CveClasificacion").ToString().ToEntero() > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString()}"), "")} - {If(Row2("CveSubProyecto").ToString().ToEntero() > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString()}"), "Sin SubProyecto Asignado")}" If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" 'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas If importeMovimiento <> 0 Then If Row2("CveActivoFijo").ToString().ToEntero() > 0 Then Dim DtAF As DataTable = TmpDT.FiltraParametros($"CveActivoFijo = {Row2("CveActivoFijo")}") If DtAF.Rows.Count > 0 Then For Each RowAF As DataRow In DtAF.FiltraParametros("", "", {"CveActivoFijo", "Obs"}).Rows Dim ImporteCosto As Decimal = DtAF.SUMD("AFValorInicial", $"CveActivoFijo = {RowAF("CveActivoFijo")}").RoundSQL(2) Dim ImporteDepreciacion As Decimal = DtAF.SUMD("AFDepreciacion", $"CveActivoFijo = {RowAF("CveActivoFijo")}").RoundSQL(2) Dim ImporteC4 As Decimal = importeMovimiento Dim ImporteC4MX As Decimal = importeMX importeMovimiento = ImporteC4 - ImporteCosto + ImporteDepreciacion importeMX = ImporteC4MX - ImporteCosto + ImporteDepreciacion If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, ImporteCosto, (ImporteCosto).RoundSQL, 49, Referencia, $"COSTO {RowAF("Obs")}", CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveActivoFijo:=Row2("CveActivoFijo").ToString().ToEntero(), Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True End If Next End If End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, ConceptoContableAplicar, Referencia, Concepto, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=Row2("CveSubProyecto").ToString().ToEntero(), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, PorcentajeImpuesto:=Row2("PorcentajeIVA").ToString().ToDecimal) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If End If Next End If End If importeMovimiento = 0 Case 150 'Descuento sobre ventas If (ObjFactura.TipoDocto.Contiene("Egs", "Dev") AndAlso Not EsNCAmortizacion) OrElse NCDescuento Then Dim ConceptoContableAplicar As Integer = 150 Dim CveVentaAplicar As Integer = ObjFactura.CveVenta Dim CveVentaAmortizacionAplicar As Integer = -1 DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto", "PorcentajeIVA"}) If DT.Rows.Count > 0 Then 'Se agrega movimiento separado por la cuenta de ventas (ER) For Each Row2 As DataRow In DT.Rows importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1} AND PorcentajeIVA = {2}", Row2("CveClasificacion"), Row2("CveSubProyecto"), Row2("PorcentajeIVA"))).ToString().ToDecimal) * ValorMultiplicador importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago Concepto = $"{ObjFactura.SerieFolio} {If(Row2("CveClasificacion").ToString().ToEntero() > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString()}"), "")} - {If(Row2("CveSubProyecto").ToString().ToEntero() > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString()}"), "Sin SubProyecto Asignado")}" If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" 'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, ConceptoContableAplicar, Referencia, Concepto, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=Row2("CveSubProyecto").ToString().ToEntero(), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, PorcentajeImpuesto:=Row2("PorcentajeIVA").ToString().ToDecimal) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If End If Next End If End If importeMovimiento = 0 Case 103 'Descuento importeMovimiento = 0 Case 8 'Ret IVA por Trasladar If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") AndAlso ObjFactura.CveTipoRetencion <> 4 Then 'SI NO ES RETENCION DE IVA DE SERVICIOS importeMovimiento = ObjFactura.RetIVA * ValorMultiplicador importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" 'SI LA FACTURA ESTA PAGADA EN SU TOTALIDAD DEBE REGRESAR EL IMPUESTO If (ObjFacturaNC IsNot Nothing AndAlso ObjFacturaNC.PagadoBancos > 0) AndAlso ObjFactura.TipoDocto = "Dev" Then TipoMovimiento = Not TipoMovimiento ConceptoContable = 62 importeMovimiento = importeMovimiento * -1 importeMX = importeMX * -1 End If End If Case 313 'Ret Iva Servicios If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") AndAlso ObjFactura.CveTipoRetencion = 4 Then 'SI TIENE RETENCION DE IVA DE SERVICIOS importeMovimiento = ObjFactura.RetIVA * ValorMultiplicador importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" 'SI LA FACTURA ESTA PAGADA EN SU TOTALIDAD DEBE REGRESAR EL IMPUESTO If (ObjFacturaNC IsNot Nothing AndAlso ObjFacturaNC.PagadoBancos > 0) AndAlso ObjFactura.TipoDocto = "Dev" Then TipoMovimiento = Not TipoMovimiento ConceptoContable = 314 importeMovimiento = importeMovimiento * -1 importeMX = importeMX * -1 End If End If Case 9 'Ret ISR por Trasladar If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") Then importeMovimiento = ObjFactura.RetISR * ValorMultiplicador importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta 'SI LA FACTURA ESTA PAGADA EN SU TOTALIDAD DEBE REGRESAR EL IMPUESTO If (ObjFacturaNC IsNot Nothing AndAlso ObjFacturaNC.PagadoBancos > 0) AndAlso ObjFactura.TipoDocto = "Dev" Then TipoMovimiento = Not TipoMovimiento ConceptoContable = 63 importeMovimiento = importeMovimiento * -1 importeMX = importeMX * -1 End If If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" End If Case 13 'Iva por Trasladar If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") And ObjFactura.IVA > 0 Then importeMovimiento = ObjFactura.IVA * ValorMultiplicador importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2) FechaMovimiento = ObjFactura.FechaPago PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal 'SI LA FACTURA ESTA PAGADA EN SU TOTALIDAD DEBE REGRESAR EL IMPUESTO If (ObjFacturaNC IsNot Nothing AndAlso ObjFacturaNC.PagadoBancos > 0) AndAlso ObjFactura.TipoDocto = "Dev" Then TipoMovimiento = Not TipoMovimiento ConceptoContable = 61 importeMovimiento = importeMovimiento * -1 importeMX = importeMX * -1 End If CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" End If Case 38 'IEPS por Trasladar If Not ObjFactura.TipoDocto.Contiene("Rem") Then importeMovimiento = ObjFactura.IEPS * ValorMultiplicador importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2) FechaMovimiento = ObjFactura.Fecha CveSubProyectoContabilizar = CveSubProyectoVenta 'SI LA FACTURA ESTA PAGADA EN SU TOTALIDAD DEBE REGRESAR EL IMPUESTO If (ObjFacturaNC IsNot Nothing AndAlso ObjFacturaNC.PagadoBancos > 0) AndAlso ObjFactura.TipoDocto = "Dev" Then TipoMovimiento = Not TipoMovimiento ConceptoContable = 39 importeMovimiento = importeMovimiento * -1 importeMX = importeMX * -1 CveIE = ObjFacturaNC.PagadoCveIE End If If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" End If Case 30 'PAGO - BANCOS 'If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 AndAlso ObjFactura.TipoDocto <> "Rem" Then ' For Each DrPago As DataRow In DtPagos.Rows ' CveIEPago = -1 ' FolioIE = -1 ' FolioIE = ObjBancos.GetNextFolio(DrPago("CveCuenta").ToString().ToEntero(), DrPago("CveTipoMovimiento").ToString().ToEntero()) ' If Not FolioIE > 0 Then ' ErrorPrepoliza = True ' Exit For ' End If ' 'If DrPago("CveTipoMovimiento").ToString().ToEntero() = 8 Then '13 ' ' DrPago("Importe") = DrPago("Importe").ToString().ToDecimal - TxtCambio.Text.ToDecimal ' 'End If ' CveIEPago = ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString().ToEntero(), DrPago("CveTipoMovimiento").ToString().ToEntero(), Fecha, FolioIE.ToString(), String.Format("PAGO: {0}", TxtFolio.Text), DrPago("Importe").ToString().ToDouble, DdlMoneda.SelectedValue.ToEntero(), tipoCambio, DrPago("Observaciones").ToString(), "", False, False, -1, ObjFactura.CvePrePoliza, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte, MesesSinIntereses:=DrPago("MesesSinIntereses").ToString().ToEntero(), Modulo:="Ventas/Guardar") ' If CveIEPago > 0 Then ' importeMovimiento = DrPago("Importe").ToString().ToDecimal * ValorMultiplicador ' importeMX = (importeMovimiento * tipoCambio * Multiplicador).RoundSQL ' CveSubProyectoContabilizar = CveSubProyectoVenta ' 'MONEDA EXTRANJERA ' If ObjFactura.CveMoneda > 1 Then ' 'BANCOS ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMovimiento, ConceptoContable, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True ' Exit For ' End If ' 'BANCOS COMPLEMENTARIA ' If UsaComplementariaClientes Then ' Dim ImporteComplementaria As Decimal = ((importeMovimiento * tipoCambio) - importeMovimiento).RoundSQL ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 204, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, ImporteComplementaria, 204, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, TipoCambioPago:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ' ErrorPrepoliza = True ' End If ' End If ' 'PAGO CLIENTES ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 2, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, importeMovimiento, 2, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True ' Exit For ' End If ' 'PAGO CLIENTES COMPLEMENTARIA ' If UsaComplementariaClientes Then ' Dim ImporteComplementaria As Decimal = ((importeMovimiento * tipoCambio) - importeMovimiento).RoundSQL ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 207, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, 0, ImporteComplementaria, 207, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, TipoCambioPago:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ' ErrorPrepoliza = True ' End If ' End If ' Else ' 'BANCOS ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, ConceptoContable, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True ' Exit For ' End If ' 'PAGO CLIENTES ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 2, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, importeMX, 2, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True ' Exit For ' End If ' End If ' If ObjFactura.IVA <> 0 Then ' Dim PorcentajeImpuestoPago As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal ' 'IVA X TRASLADAR ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, ((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, 13, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ' ErrorPrepoliza = True ' Exit For ' End If ' 'IVA PAGADO ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, ((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, 61, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ' ErrorPrepoliza = True ' Exit For ' End If ' End If ' If ObjFactura.IEPS <> 0 Then ' Dim PorcentajeImpuestoPago As Decimal = TmpDT.MAX("PorcentajeIEPS").ToDecimal ' 'IEPS X TRASLADAR ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, ((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, 38, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ' ErrorPrepoliza = True ' Exit For ' End If ' 'IEPS PAGADO ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, ((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, 39, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ' ErrorPrepoliza = True ' Exit For ' End If ' End If ' If ObjFactura.RetIVA <> 0 AndAlso ObjFactura.CveTipoRetencion = 4 Then ' Dim PorcentajeImpuestoPago As Decimal = TmpDT.MAX("PorcentajeRetIVA").ToDecimal ' 'RETIVA X TRASLADAR ' 'OBTENER CUENTAS ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 313, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.RetIVA) / ObjFactura.Total, ((importeMovimiento * ObjFactura.RetIVA) / ObjFactura.Total) * tipoCambio * Multiplicador, 313, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ' ErrorPrepoliza = True ' Exit For ' End If ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 314, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.RetIVA) / ObjFactura.Total, ((importeMovimiento * ObjFactura.RetIVA) / ObjFactura.Total) * tipoCambio * Multiplicador, 314, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ' ErrorPrepoliza = True ' Exit For ' End If ' End If ' Else ' ErrorPrepoliza = True ' Exit For ' End If ' Next ' importeMovimiento = 0 'End If importeMovimiento = 0 End Select If (importeMovimiento <> 0 OrElse (importeMovimiento = 0 AndAlso ObjFactura.Total = 0 AndAlso ConceptoContable = 1)) And Not ErrorPrepoliza Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, importeMX, ConceptoContable, Referencia, Concepto, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If End If If ErrorPrepoliza Then Exit For End If Next End If 'Si es Facturacion de una remision cancelamos, traspasamos saldos y agregamos evento a la bitacora If RemisionesLista.Count > 0 AndAlso ObjFactura.TipoDocto.Contiene("Ing", "Ant") Then 'se verifica que el documento que se está generando sea "Ing", "Ant" If Not ObjFactura.TipoDocto.Contiene("Ing", "Ant") Then ErrorPrepoliza = True ErrorList.Add("No se pueden facturar las remisiones, con ese tipo de comprobante seleccionado") Else For Each CveRemision As Integer In RemisionesLista If Not ObjConta.TraspasarSaldosRemision(CveRemision, ObjFactura.CvePrePoliza, ObjFactura.CveVenta) Then ErrorPrepoliza = True End If If CveRemision > 0 Then If ObjVentas.GetVenta(CveRemision, UsuarioActual.CveEmpresa, VerificaAlmacen:=False) Then Dim SerieFolioRem As String = ObjVentas.DtResultados.Rows(0)("SerieFolio").ToString() 'Factura If Not ObjEventos.AddEventoBitacora($"Venta facturada de Remisión: {SerieFolioRem}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then ErrorPrepoliza = True End If Else ErrorPrepoliza = True End If Else ErrorPrepoliza = True End If 'Remision If Not ObjEventos.AddEventoBitacora($"Remisión facturada en Venta: {ObjFactura.SerieFolio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveRemision) Then ErrorPrepoliza = True End If Next End If End If 'REGRESA SALDO A LAS REMISIONES QUE SE FACTURARON EN EL INGRESO QUE SE ESTA CANCELANDO If ObjFactura.TipoDocto = "Ing" And ValorMultiplicador = -1 AndAlso NuevaFactura <> 1 AndAlso Not SeCancelaRemisionProceso Then ' se debe de excluir cuando es refacturación If ObjVentas.GetRemisionesRelacionadas(ObjFactura.CveVenta, ObjFactura.TipoDocto) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then For Each Dr As DataRow In ObjVentas.DtResultados.Rows Dim Selecciono As Boolean = False If Not Selecciono Then If Not ObjConta.TraspasarSaldosRemision(Dr("CveVenta").ToString().ToEntero(), ObjFactura.CvePrePoliza, ObjFactura.CveVenta, 1) Then ErrorPrepoliza = True End If 'Remision If Not ObjEventos.AddEventoBitacora($"Facturación cancelada en: ", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Dr("CveVenta").ToString().ToEntero()) Then ErrorPrepoliza = True End If End If Next End If End If If NuevaFactura = 1 AndAlso TotalOriginal > TxtTotal.Text.ToDouble AndAlso ObjEventos IsNot Nothing Then If Not ObjEventos.AddEventoBitacora($"Factura a menor precio de la factura origen.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then ErrorPrepoliza = True Else Alert("Factura a menor precio de la factura origen.", TipoMensaje.MsgAdvertencia) End If End If 'Simplificacion de PrePolizas 'If ObjFactura.TipoDocto.Contiene("Egs", "Dev") OrElse SimplificarPrePoliza Then ' If Not ObjConta.PrePolizaSimplificacion(ObjFactura.CvePrePoliza, UsuarioActual.CveEmpresa) Then ' Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) ' End If 'End If Dim ModalidadRefacturacion As Integer = UsuarioActual.Empresa.Funcionalidad(586).ToEntero() 'REFACTURACION CON PAGOS, DEBE CANCELAR SALDOS DEL DOCUMENTO ANTERIOR Y TRASPASAR PAGOS AL NUEVO If ModalidadRefacturacion = 2 AndAlso ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso ObjFactura.NuevaFactura = 1 Then If Not ObjConta.TraspasarSaldosPrePolizasRefacturacion(ObjFacturaNC.CveVenta, ObjFactura.CveVenta, ObjFactura.CvePrePoliza, CvePlantilaPoliza, UsuarioActual.CveEmpresa) Then ErrorList.Add("Ocurrió un error al traspasos saldos en refacturación") End If Else 'EN CASO DE SER REFACTURACION DE ANTICIPO SE ACTUALIZAN LAS VENTAS APLICADAS HACIA EL NUEVO If NuevaFactura = 1 AndAlso CveDevolucion > 0 AndAlso ObjFactura.TipoDocto.Contiene("Ant") Then If Not ObjVentas.TraspasaVentasAplicadasAnt(ObjFactura.CveVenta, CveDevolucion, UsuarioActual.CveEmpresa, ObjFactura.CvePrePoliza) Then ErrorPrepoliza = True End If End If End If If ObjConta.ValidacionesPrePoliza(ObjFactura.CvePrePoliza, UsuarioActual, Opcion:=2, AutoConta:=AutoConta) Then If ObjConta.ValorPolizaDescuadre > 0 Then If ObjConta.ValorPolizaDescuadre = 2 Then ErrorPrepoliza = True Alert(ObjConta.MensajePolizaDescuadre, TipoMensaje.MsgError) End If 'ErrorPrepoliza = True GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then ' Dim DtTest = ObjConta.DtResultados 'End If End If Else ErrorPrepoliza = True End If Return ErrorPrepoliza Catch ex As Exception GuardaLog("GuardaPreP." & ex.ToString()) Return True End Try End Function Private Function GuardarVentaImpuestosLocales(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, Factura As Modelos.Factura, Optional ValorMultiplicador As Integer = 1) As Boolean Dim ErrorPrepoliza As Boolean = False If TmpDTImpuestos IsNot Nothing AndAlso Factura.CvePrePoliza > 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "Rem") Then Dim Importe As Decimal Dim Concepto As String Dim tipoCambio As Decimal Dim CveSubProyectoContabilizar As Integer = DdlSubProyectoDatos.SelectedValue.ToEntero() For Each RowIL As DataRow In TmpDTImpuestos.Rows If RowIL("TipoImpuesto").ToString().ToEntero() > 0 Then Importe = RowIL("Importe").ToString().ToDecimal * ValorMultiplicador Concepto = ViewState("VentaFolio").ToString() If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then tipoCambio = Factura.TipoCambio ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then If UsuarioActual.CveEmpresa.Contiene(13, 83) Then tipoCambio = GlobalTipoCambio(Factura.Fecha.AddDays(-1)).ToString().ToDecimal Else tipoCambio = GlobalTipoCambio(Factura.Fecha).ToString().ToDecimal End If Else tipoCambio = 1 End If Select Case RowIL("TipoImpuesto").ToString() Case "1" If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Importe * tipoCambio, 27, Concepto, Concepto, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Case "3" If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Importe * tipoCambio, 116, Concepto, Concepto, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Case "4" If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Importe * tipoCambio, 58, Concepto, Concepto, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Case "5" If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, True, Importe, Importe * tipoCambio, 27, Concepto, Concepto, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If End Select End If Next End If Return ErrorPrepoliza End Function #End Region #Region " VISTA PREVIA NEW " Private Sub VistaPreviaNew() If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") Exit Sub End If CreaObjetosVenta(True) If ObjFactura Is Nothing Or (ObjFactura.Cliente Is Nothing And Not CveEmpresaCRM > 0) Then Alert("Ocurrió un error al procesar los datos para la vista previa. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgError) ObjFactura = Nothing Exit Sub End If Dim CartaPorte As Modelos.MSubReportData = Nothing If UsuarioActual.CveEmpresa = 13 Then CartaPorte = New Modelos.MSubReportData() CartaPorte.Parametros.Add(New ReportParameter($"TieneCartaPorte", "False")) End If ImprimirbytesPDF(PdfFactura(ObjFactura, Guardar:=False, SubReportData:=CartaPorte), "Factura", "PDF") End Sub #End Region #Region "¡ P D F R E P O R T V I E W E R !" Private Sub GeneraPDFFactura(EnviaCorreo As Boolean, Factura As Modelos.Factura, UsuarioActual As Usuario, strURLHOST As String, Optional CorreoCRM As String = "") 'GUARDA PDF Dim LocalSerieFolio As String = String.Empty Dim LocalTipoDocto As String = String.Empty 'TIMBRADO NUEVO Try DescargarFactura(Factura.CveVenta, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario, Regenerar:=True, strURLHOST:=strURLHOST) Catch ex As Exception OnError("Ocurrió un error al generar el PDF", ex) End Try Dim ErrorCorreo As Boolean = False 'If EnviaCorreo Then ' If Factura IsNot Nothing Then ' 'MANDA CORREO ' If EnviaCorreo Then ' LocalSerieFolio = Factura.SerieFolio ' LocalTipoDocto = Factura.TipoDocto ' Dim ArchivoAdjunto As String = "" ' Dim ArchivoXML As String = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) ' Dim ArchivoPDF As String = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) ' If Adjunto <> "" Then ' ArchivoAdjunto = String.Format("{0}Ventas\{1}", UsuarioActual.Empresa.Ruta, Adjunto) ' End If ' Try ' Dim FIXML As New FileInfo(ArchivoXML) ' Dim FIPDF As New FileInfo(ArchivoPDF) ' If FIXML.Exists AndAlso FIPDF.Exists Then ' MandaMails(UsuarioActual, CveVenta, Factura.TipoDocto, LocalSerieFolio, EnviaCorreo, ArchivoXML, ArchivoPDF, ArchivoAdjunto, CorreoCRM) ' Else ' ErrorCorreo = True ' End If ' Catch ex As Exception ' ErrorCorreo = True ' End Try ' End If ' Else ' ErrorCorreo = True ' End If ' If ErrorCorreo Then ' Dim ObjVentas As New ClsVentas ' If EnviaCorreo Then ' ObjVentas.UpdateVentaMail(3, CveVenta) ' Else ' ObjVentas.UpdateVentaMail(0, CveVenta) ' End If ' ObjVentas.Dispose() ' End If 'End If End Sub Private Sub GeneraPDFCotizacion(EnviaCorreo As Boolean, Optional CorreoContactoCRM As String = "", Optional pdfCRM As Byte() = Nothing, Optional SerieFolioCRM As String = "", Optional TipoDoctoCRM As String = "") Dim pdf As Byte() = Nothing 'GUARDA PDF Dim LocalSerieFolio As String = String.Empty Dim LocalTipoDocto As String = String.Empty 'TIMBRADO NUEVO If CorreoContactoCRM.Trim.Length > 0 Then pdf = pdfCRM LocalSerieFolio = SerieFolioCRM LocalTipoDocto = TipoDoctoCRM Else Try If CveVenta > 0 Then ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=False) End If pdf = PdfFactura(ObjFactura) LocalSerieFolio = ObjFactura.SerieFolio LocalTipoDocto = ObjFactura.TipoDocto Catch ex As Exception OnError("Ocurrió un error al generar el PDF", ex) End Try End If 'MANDA CORREO If EnviaCorreo Then Dim ArchivoAdjunto As String = "" Dim ArchivoXML As String = "" Dim ArchivoPDF As String = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) If Adjunto <> "" Then ArchivoAdjunto = String.Format("{0}Ventas\{1}", UsuarioActual.Empresa.Ruta, Adjunto) End If 'Try ' ' BytesPdfCotizacion(CveVenta) ' Dim Hilo As New System.Threading.Thread(Sub() MandaMails(UsuarioActual, CveVenta, DdlTipoComprobante.SelectedValue.ToString(), LocalSerieFolio, False, ArchivoXML, ArchivoPDF, ArchivoAdjunto, CorreoContactoCRM:=CorreoContactoCRM)) ' Hilo.Start() 'Catch ex As Exception ' OnError("Ocurrió error al mandar Mail", ex) ' Dim ObjVentas As New ClsVentas ' ObjVentas.UpdateVentaMail(0, CveVenta) ' ObjVentas.Dispose() 'End Try End If End Sub #End Region #Region " VISTA PREVIA " Protected Sub BtnVistaPrevia_Click(sender As Object, e As System.EventArgs) Handles BtnVistaPrevia.Click VistaPreviaNew() End Sub #End Region #Region "D R O P - D O W N - L I S T" Private Sub DdlPSIndexChange(CvePSParametro As Integer, Ddl As ADServerControl.Dropdownlost) If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") Exit Sub End If If CvePSParametro > 0 Then Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSParametro).FiltroPrimero("") If drPS IsNot Nothing Then 'HdnUnidadMedida.Value = PS.Rows(0)("CveUnidadMedida").ToString() HdnPS.Value = drPS("PS").ToString() HdnCodigoPS.Value = drPS("PSCodigo").ToString() HdnTipoPS.Value = drPS("CveTipoPS").ToString() HdnTipoInv.Value = drPS("Inv_CveMetodoInventario").ToString() HdnAplicaIEPS.Value = drPS("AplicaIEPS").ToString() HdnPorcentajeIEPS.Value = drPS("IEPSPorcentaje").ToString() DdlUnidadMedida.Items.Clear() If UsuarioActual.Empresa.UsaInventarios Then DdlUnidadMedida.DataSource = GlobalDTProductosServiciosEquivalencias(CvePSParametro, -1, 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()) If drPS("CveTipoPS").ToString() = "1" Then 'Si es servicio If UsuarioActual.Empresa.Funcionalidad(558).ToString() = "1" Then 'Si es Empresa llantera TxtPrecio.Enabled = True Else 'TxtPrecio.Enabled = False End If Else TxtPrecio.Enabled = True End If Dim PSCodigoSAT As String = drPS("SATClavePS").ToString If UsuarioActual.TienePermisoProceso(68) AndAlso Not PSCodigoSAT.Contiene("84111506", "80141610") Then TxtPrecio.Enabled = False 'If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count = 0 AndAlso Not ChkEmitirComercioExterior.Checked Then ' DdlMoneda.SelectedValueExist(drPS("CveMoneda").ToString()) ' CambiaMoneda() 'End If 'If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count = 0 AndAlso Not ChkEmitirComercioExterior.Checked Then ' DdlMoneda.SelectedValueExist(drPS("CveMoneda").ToString()) ' CambiaMoneda() 'End If 'SUGIERE PRECIO Dim PrecioSugerido As Decimal = 0 Dim tPrecioSugerido As Decimal = 0 tPrecioSugerido = drPS("Precio").ToString().ToDecimal Dim ObjPrecioSugerido As Modelos.MPrecioSugerido = CalculaPrecioSugerido(CvePSParametro, drPS("CveClasificacion").ToString().ToEntero()) PrecioSugerido = ObjPrecioSugerido.PrecioSugerido If PrecioSugerido <= 0 Then PrecioSugerido = tPrecioSugerido TxtPrecio.Text = PrecioSugerido.ToString("#,###.####") ' que muestre hasta los 4 digitos si lo requiere HdnIVAPS.Value = If(drPS("IVA").ToString() = "-1", ViewState("IVA"), drPS("IVA").ToString()).ToString() HdnIVARetAPS.Value = drPS("RetIVA").ToString() HdnCodigo.Value = drPS("Codigo").ToString() If DdlClasificacion.SelectedIndex = 0 Then If drPS("CveClasificacion").ToString() IsNot Nothing Then DdlClasificacion.SelectedValueExist(drPS("CveClasificacion").ToString()) Else Alert("El Productos/Servicio no tiene asignada una Clasificación.", TipoMensaje.MsgInformacion) End If End If End If ElseIf CvePSParametro = -2 Then CargaPS(DdlClasificacion.SelectedValue.ToEntero(), Ddl) End If UPPPS.Update() UpPS.Update() UpDVAddPS.Update() End Sub Private Function CalculaPrecioSugerido(CvePSParametro As Integer, CveClasificacion As Integer, Optional CvePrecioListaSugerido As Integer = -1) As Modelos.MPrecioSugerido Dim Retorno As New Modelos.MPrecioSugerido Dim PrecioSugerido As Decimal = 0 If UsuarioActual.CveEmpresa.Contiene(1) Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPorcentajeProductos(CveCliente) Then Dim PrecioAplicado As Decimal = ObjPS.DtResultados.FiltraParametros($"CvePS = {CvePSParametro}").FiltroPrimeroValor("PrecioA").ToDecimal 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 Decimal = 0 If TipoPrecioLista = 10 Then CvePrecioListaPS = Me.CvePrecioListaCliente 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 = Me.CvePrecioListaCliente 'GlobalDTCliente(UsuarioActual.CveEmpresa, Estatus:=-1, CveCliente:=CveCliente).FiltroPrimeroValor("CvePrecioLista").ToEntero() End If If Me.CvePrecioListaCliente > 0 Then Dim ArrayClientes As String() = UsuarioActual.Empresa.Funcionalidad(711).Split(",".ToCharArray()) 'VERIFICA SI EL CLIENTE ACTUAL DEBE TENER PRIORIDAD SU LISTA DE PRECIOS If ArrayClientes.Length > 0 AndAlso ArrayClientes.Count(Function(cliente) cliente.Trim() = Me.CveCliente.ToString()) > 0 Then CvePrecioListaPS = Me.CvePrecioListaCliente End If 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 As Decimal = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDecimal, -1, "-1", NowADS, 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.ToDecimal, -1, "-1", NowADS, -1, CveTipoAlmacen:=1) ObjInventarios.Dispose() If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If Me.CvePrecioLista = CvePrecioListaPS Retorno.CvePrecioLista = CvePrecioListaPS End If If PrecioSugerido > 0 Then Dim PrecioBaseCosto As Decimal = 0 PrecioBaseCosto = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion).FiltroPrimeroValor("PrecioBaseCosto", "").ToDecimal If PrecioBaseCosto > 0 Then PrecioSugerido = PrecioSugerido * ((PrecioBaseCosto / 100) + 1) End If End If Retorno.PrecioSugerido = PrecioSugerido Return Retorno End Function Protected Sub DdlPS_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlPS.selectedindexchange DdlPSIndexChange(DdlPS.SelectedValue.ToEntero(), DdlPS) End Sub Protected Sub DdlClasificacion_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlClasificacion.SelectedIndexChanged CargaPS(DdlClasificacion.SelectedValue.ToEntero(), DdlPS) UpPS.Update() End Sub 'Protected Sub DdlNCFactura_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlNCFactura.SelectedIndexChanged ' Dim objcompras As New ClsCompras ' If objcompras.GetCompraDetallealmacen(0, DdlNCFactura.SelectedValue.ToEntero()) Then ' GvInvNC.DataSource = objcompras.DtResultados ' If objcompras.DtResultados.Rows.Count > 0 Then ' Tab.ActiveTabIndex = 1 ' Updatetabs.Update() ' End If ' Else ' GvInvNC.DataSource = Nothing ' End If ' GvInvNC.DataBind() ' UpINVNC.Update() ' objcompras.Dispose() 'End Sub Protected Sub DdlTipoComprobante_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlTipoComprobante.SelectedIndexChanged CambiaTipoComprobante() End Sub Private Sub CambiaTipoComprobante() CambiaTipoDocto() End Sub Private Sub CambiaTipoDocto() ConfiguraTipoDocto() CargaFolios() CargaEstatusFactura(DdlTipoComprobante.SelectedValue) UpEstatus.Update() 'REINICIALIZA VALORES DE ENTREGA POR ADELANTADO RequiereAlmacenDestino = False If DdlTipoComprobante.SelectedValue = "Cot" And UsuarioActual.Empresa.Funcionalidad(135).Contiene("1", "2") Then Alert("Se ocupa una autorización.", TipoMensaje.MsgAdvertencia) TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False 'RBLPago.Enabled = False 'TxtFechaVencimientoCotizacion.Text = NowADS().ToString() GvPS.Columns(5).Visible = True UpnTools.Update() 'tdTelefonoGen.Visible = False 'tdTxtTelefonoGen.Visible = False Else If DdlTipoComprobante.SelectedValue = "Cot" Then TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False 'RBLPago.Enabled = False 'RBLPago.SelectedValue = "2" 'TxtFechaVencimientoCotizacion.Text = NowADS().ToString() GvPS.Columns(5).Visible = True 'tdTelefonoGen.Visible = False 'tdTxtTelefonoGen.Visible = False Else TrDireccion.Visible = True TrCiudad.Visible = True TrRFC.Visible = True GvPS.Columns(5).Visible = False LblMensaje.Visible = UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue.Contiene("Ing") If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev") Then 'ObtenerFechaVencimientoCER() If DdlTipoComprobante.SelectedValue.Contiene("Egs") Then 'se cargan las facturas timbradas 'CargaFacturasRelacionar() 'RegistraScript("$('#DivRelacionarFacturasNC').modal('show');") End If End If 'If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then ' 'ENTREGA POR ADELANTADO ' If UsuarioActual.Empresa.Funcionalidad(145) = "1" And Not DdlTipoComprobante.SelectedValue.Contiene("PA") Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then ' RequiereAlmacenDestino = True ' 'If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then ' ' TrAlmacenAsignado.Visible = True ' 'End If ' Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero() ' If CveAlmacenDestino > 0 Then ' DdlAlmacenAsignado.Items.Clear() ' DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} And CveTipoAlmacen In (4,10)") ' DdlAlmacenAsignado.DataBind() ' DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString())) ' DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString() ' Else ' DdlAlmacenAsignado.Items.Clear() ' DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} AND CveTipoAlmacen IN (10)") ' DdlAlmacenAsignado.DataBind() ' End If ' Dim CveAlmacenOrigen As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenOrigen", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero() ' If CveAlmacenOrigen > 0 Then ' DdlAlmacenOrigen.Items.Clear() ' DdlAlmacenOrigen.DataSource = GlobalDTAlmacen(UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1, CveAlmacen:=CveAlmacenOrigen) '.FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}") ' DdlAlmacenOrigen.DataBind() ' DdlAlmacenOrigen.SelectedValueExist(CveAlmacenOrigen.ToString()) ' End If ' UpParametros.Update() ' Else ' RequiereAlmacenDestino = False ' TrAlmacenAsignado.Visible = False ' TrAlmacenOrigen.Visible = False ' End If ' 'ENVIO DE FACTURA ' ChkEnviarFactura.Checked = False ' ChkEnviarFactura.Visible = True ' LblEnviarMail.Visible = True ' If CveVenta > 0 AndAlso EnviarCorreoCliente Then ChkEnviarFactura.Checked = EnviarCorreoCliente 'End If If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "PA", "Pd2") AndAlso (ReceptorRFC = "XAXX010101000" Or LblRFC.Text = "XAXX010101000") Then TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False 'tdTelefonoGen.Visible = True 'tdTxtTelefonoGen.Visible = True Else 'TxtAtencionA.Text = "" 'TxtTelefonoGenerico.Text = "" End If End If End If If DdlTipoComprobante.SelectedValue.Contiene("Ing") Then ImgAntiPend.Visible = True Else ImgAntiPend.Visible = False End If 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO If EsCreaApartirDe OrElse ModalidadEdicion OrElse CveVenta <= 0 Then If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True Else If LblCliente.Text <> "Cliente" And Not EstatusCliente Then Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) End If If Not CveEmpresaCRM > 0 Then BtnEmitirImprimir.Visible = EstatusCliente TrVistaPrevia.Visible = EstatusCliente Else BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True End If End If End If If DdlTipoComprobante.SelectedValue = "Ing" Then ImgAntiPend.Visible = True End If 'TrAtencionA.Visible = True 'tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") 'tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") Updatetabs.Update() UPCondicionesPago.Update() UpCliente.Update() UpPS.Update() UPObservaciones.Update() End Sub Protected Sub DdlSucursalCliente_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSucursalCliente.SelectedIndexChanged CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero()) 'RECARGA LAS RESTRICCIONES DE CREDITO SI SE CAMBIO LA SUCURSAL DEL CLIENTE If DdlSucursalCliente.SelectedValue.ToEntero() > 0 Then CargaRestriccionesCreditoCliente(Alertas:=True, CveVenta:=Me.CveVenta) End If End Sub Protected Sub DdlCCEdit_SelectedIndexChanged(sender As Object, e As System.EventArgs) Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) Dim CveProyecto As String = DirectCast(sender, DropDownList).SelectedValue gvr.FCDropDownList("DDlSubProyecto").Items.Clear() gvr.FCDropDownList("DDlSubProyecto").DataSource = GlobalDTSubProyectos(CveProyecto.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa) gvr.FCDropDownList("DDlSubProyecto").DataBind() gvr.FCDropDownList("DDlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) End Sub Protected Sub DdlClasificacion_SelectedIndexChanged1(sender As Object, e As EventArgs) Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) CargaPS(gvr.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero(), gvr.FCDropDownLost("DdlPS")) End Sub 'Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlProyecto.SelectedIndexChanged ' CargaSubProyecto(FiltraPorProyecto:=True) 'End Sub #End Region #Region " SUCURSAL FACTURACION " Private Sub DdlSubProyectoDatos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSubProyectoDatos.SelectedIndexChanged CambiaSucursalGeneral() End Sub Private Sub CambiaSucursalGeneral(Optional RecargarPartidas As Boolean = True) Dim ObjSubProyectos As New ClsSubProyectos 'Dim ObjSucursal As New ClsSucursales If ObjSubProyectos.GetSubProyectos() Then DTSucursal = ObjSubProyectos.DtResultados.FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue.ToEntero())) 'Dim drc As DataRow 'drc = DTSucursal(0) 'DdlSubProyecto.Items.Clear() 'DdlSubProyecto.DataSource = DTSucursal ''DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) ''DdlSubProyecto.SelectedValue = "-1" 'DdlSubProyecto.DataBind() 'DdlSubProyecto.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) 'CambiaSucursal(RecargarPartidas) 'If ObjSucursal.GetSucursales(UsuarioActual.CveEmpresa) Then ' DTSucursal = ObjSucursal.DtResultados.FiltraParametros(String.Format("CveSucursal = {0}", drc("CveSucursal").ToString().ToEntero())) ' Dim dre As DataRow ' dre = DTSucursal(0) ' DdlSucursal.SelectedValue = dre("CveSucursal").ToString() ' CambiaSucursal() 'End If End If ObjSubProyectos.Dispose() HabilitarRemisionesPublicoGeneral() 'UpDetalle.Update() 'UpEmitirTransitorio.Update() End Sub Private Sub CambiaSucursal(Optional RecargarPartidas As Boolean = True) CargaFormatoSucursal() CargaFolios() 'CargarAlmacenes() If RecargarPartidas Then RecargaSucursalPartidas() End If DdlPS.Attributes.Remove("data-cvesubproyecto") DdlPS.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) UpPS.Update() End Sub Private Sub RecargaSucursalPartidas() Dim CveSubProyecto As Integer = DdlSubProyectoDatos.SelectedValue.ToEntero() Dim SubProyecto As String = "" If CveSubProyecto > 0 Then SubProyecto = DdlSubProyectoDatos.SelectedItem.Text End If If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then For Each Row As DataRow In TmpDT.Rows Row("CveSubProyecto") = CveSubProyecto Row("SubProyecto") = SubProyecto Next End If GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() UpPS.Update() End Sub Private Sub CargaFolios(Optional FacturarDocumentoNuevo As Boolean = False) If DdlSubProyectoDatos.SelectedValue.ToEntero() <= 0 Then Alert("No se tienen asignadas sucursales", TipoMensaje.MsgError) Exit Sub End If Dim ObjFolios As New ClsGralFolios() Dim TipoDoctoConsulta As String = "Ing" ' 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("FolioActual") = DT.Rows(0)("FActual").ToString() ViewState("Serie") = DT.Rows(0)("Serie").ToString() UpFacturar.Update() Else If DdlTipoComprobante.Items.Count > 0 Then Alert("No tiene registrados Folios para " & DdlTipoComprobante.SelectedItem.Text & " en esta sucursal.", TipoMensaje.MsgAdvertencia) Else Alert("No tiene permisos para generar ningun tipo de documento.", TipoMensaje.MsgAdvertencia) End If TrEmitir.Visible = False TrVistaPrevia.Visible = False BtnEmitirImprimir.Visible = False UpFacturar.Update() End If DT.Dispose() End If ObjFolios.Dispose() 'End If End Sub Private Sub CargaFormatoSucursal(Optional RecalcularIVA As Boolean = True) Dim dr As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue))) If dr IsNot Nothing Then ViewState("SucCalle") = dr("Calle") ViewState("SucNoExt") = dr("NoExt") ViewState("SucNoInt") = dr("NoInt") ViewState("SucColonia") = dr("Colonia") ViewState("SucLocalidad") = dr("Localidad") ViewState("SucMunicipio") = dr("Municipio") ViewState("SucEstado") = dr("Estado") ViewState("SucPais") = dr("Pais") ViewState("SucCP") = dr("CP") ViewState("FormatoFactura") = dr("FormatoFactura") ViewState("IVA") = dr("IVA") DdlIVA.Visible = False Select Case ViewState("IVA").ToString().ToDouble Case 0 DdlIVA.SelectedValue = "1" PorcentajeIVA = ViewState("IVA").ToString().ToDecimal Case 0.08 DdlIVA.SelectedValue = If(EsCreaApartirDe, $"{(TmpDT.MAX("PorcentajeIVA").ToDecimal() + 1).RoundSQL(2).ToString()}", "1.08") PorcentajeIVA = If(EsCreaApartirDe, TmpDT.MAX("PorcentajeIVA").ToDecimal, ViewState("IVA").ToString().ToDecimal).RoundSQL(2) DdlIVA.Visible = If(Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0, True, False) Case 0.16 DdlIVA.SelectedValue = "1.16" PorcentajeIVA = ViewState("IVA").ToString().ToDecimal End Select 'SI ES COTIZACION HABILITAR EL DDL DE IVA If CveVenta <= 0 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then DdlIVA.Visible = True End If If RecalcularIVA AndAlso TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 AndAlso (Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0) Then RecalculaIVA() 'ViewState("SubProyectoPorcentajeIVA") = dr("IVA") ViewState("TipoFormato") = dr("TipoFormato") Dim CveSubProyecto As Integer = GetSubProyectoSucursal() If CveSubProyecto > 0 Then CargaSubProyecto(CveSubProyecto) TipoVentaSucursal = dr("TipoVenta").ToString().ToEntero() End If UpFacturar.Update() UpPS.Update() UpParametros.Update() End Sub #End Region #Region " AGREGAR PS " Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click AgregarPS() End Sub Private Function ValidaAgregarPS(CvePS As Integer, CveUM As Integer, PU As Double, CveTipoPS As Integer) As Boolean 'NO TOCAR - IPP 'VALIDA PARAMETROS If CvePS <= 0 Or CveUM <= 0 Then Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) Return False End If If HdnPS.Value = "" Or HdnPS.Value = "-1" Then Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) Return False End If 'SI USA CONTABILIDAD LA CLASIFICACION ES OBLIGATORIA If DdlClasificacion.SelectedValue.ToEntero() <= 0 AndAlso UsuarioActual.Empresa.UsaContabilidad Then Alert("La Clasificación es obligatoria, favor de seleccionarla", TipoMensaje.MsgAdvertencia) Return False End If 'SUBPROYECTO OBLIGATORIO If DdlSubProyectoDatos.SelectedValue.ToEntero() <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(120) = "1" Then Alert("El Subproyecto es obligatorio, favor de seleccionarlo", TipoMensaje.MsgAdvertencia) Return False End If If CveCliente <= 0 And Not CveEmpresaCRM > 0 Then Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact', 800, 547, 'N', 'PopUpBuscar')") Return False End If If PU <= 0 Then Alert("No se puede vender a un importe de cero", TipoMensaje.MsgAdvertencia) Return False End If 'VALIDA PROMOCIONES Dim ObjVentas As New ClsVentas If ObjVentas.GetPromocionesPS(-1, NowADS, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveCliente, -1, 1, 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 'SI NO TIENE LA FUNCIONALIDAD VALIDARA LAS MONEDAS If UsuarioActual.Empresa.Funcionalidad(524) <> "" Then If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count >= 1 Then Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).Rows(0) If DrPS IsNot Nothing Then If DrPS("CveMoneda").ToString().ToEntero() <> DdlMoneda.SelectedValue.ToEntero() Then Alert("No puede agregar un producto de diferente moneda a la ya seleccionada", TipoMensaje.MsgAdvertencia) Return False End If End If End If End If ' NO VALIDA EXISTENCIAS NI COSTO - PERMISO PARA NO VALIDAR If Not UsuarioActual.TienePermisoProceso(169) Then 'SOLO VALIDA EXISTENCIAS Y COSTO: SI USA INVENTARIOS, SOLO PRODUCTOS TIPO PRODUCTO, SOLO REMISIONES E INGRESOS If UsuarioActual.Empresa.UsaInventarios AndAlso CveTipoPS = 2 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119))) Then Dim ObjInventarios As New ClsInventarios Dim Existencia As Decimal = ObjInventarios.GetExistenciasPS(CvePS, CveUM, UsuarioActual.CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveVendedor:=-1, 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.ToDecimal, -1, "-1", NowADS, 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 Costo <= 0 Then Costo = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDecimal, -1, "-1", NowADS, -1, CveTipoAlmacen:=1) ObjInventarios.Dispose() Dim PrecioMinimo As Decimal = 0 'RMF. condicion temporal, para reubicación, precio mínimo If UsuarioActual.CveEmpresa = 119 Then 'Dim CvePrecioLista As Integer = 38 Dim objPS As New ClsProductosServicios If objPS.GetPSSucursalesALL(CvePS, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero()) Then PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal 'If PrecioMinimo > 0 Then ' Costo = PrecioMinimo 'End If End If objPS.Dispose() End If If DdlTipoComprobante.SelectedValue <> "Cot" Then 'VALIDA EXISTENCIA If UsuarioActual.CveEmpresa.Contiene({72, 80, 119, 153, 140}) Then If CveVenta <= 0 OrElse Me.EsCreaApartirDe Then If Existencia - TmpDT.SUM("Cantidad", $"CvePS = {CvePS} AND (EntregaDirecta IS NULL OR EntregaDirecta < 1)") < TxtCantidad.Text.ToDouble Then Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia) Return False End If Else If DdlTipoComprobante.SelectedValue = "Rem" Then Dim CantidadVenta As Double = 0 Using ObjVentasE As New ClsVentas If ObjVentasE.GetVentaDetalle(CveVenta) Then CantidadVenta = ObjVentasE.DtResultados.SUM("Cantidad", $"CvePS = {CvePS}") End If End Using 'SUMA LO YA RESTADO EN PENDIENTE POR SURTIR QUE PERTENESCA A LA VENTA. 'PARA QUE NO RESTE LA EXISTENCIA 2 VECES Y PUEDAS COMPARAR LO REAL If (Existencia + CantidadVenta) - TmpDT.SUM("Cantidad", $"CvePS = {CvePS} And (EntregaDirecta Is NULL Or EntregaDirecta < 1)") < 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 End If End If 'VALIDA COSTOS If Not CveContrato > 0 Then 'BANDERAS PARA VALIDACIONES Dim EsValido As Boolean = False Dim EsValidoMayor As Boolean = False Dim CostoMenor As Decimal = 0.0D Dim CostoMayor As Decimal = 0.0D 'PRECIO MINIMO If UsuarioActual.Empresa.Funcionalidad(129).ToEntero() > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then '' NOTA. si tiene preciominimo, debe de validarlos e ignorar el costo, pero se debe de considerar el TC, para el costo If PrecioMinimo > 0 Then 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA If PU >= PrecioMinimo Then ' aqui se comparar los importes directos, sin el TC EsValido = True End If Else CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) '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 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 Else Dim DrPS As DataRow = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") 'valida sino tiene promocion la clasificacion If DrPS IsNot Nothing Then If DtPromociones.FiltraParametros(String.Format("CveClasificacion = {0}", DdlClasificacion.SelectedValue.ToEntero())).Rows.Count > 0 Then ''falta aplicar si tiene promocion Dim drPromo As DataRow = DtPromociones.FiltroPrimero(String.Format("CveClasificacion = {0}", DdlClasificacion.SelectedValue.ToEntero())) If drPromo IsNot Nothing Then If drPromo("CveMarca").ToString() = DrPS("CveMarca").ToString() Then End If End If End If 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}-{1}. No se puede vender a un precio menor de su Costo
", HdnCodigoPS.Value, HdnPS.Value) If TienePermisoImportes Then MensajeCosto.AppendFormat("El costo del producto es: ${0:#,###.00}
", Costo) MensajeCosto.AppendFormat("El rango menor aceptado es: {0}% ${1:#,###.00}
", UsuarioActual.Empresa.Funcionalidad(129).ToEntero(), CostoMenor) MensajeCosto.AppendFormat("El precio indicado es: ${0:#,###.00} ({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:#,###.00}
", Costo) MensajeCosto.AppendFormat("El rango mayor aceptado es: {0}% ${1:#,###.00}
", UsuarioActual.Empresa.Funcionalidad(133).ToEntero(), CostoMayor) MensajeCosto.AppendFormat("El precio indicado es: ${0:#,###.00} ({1}% de ganancia)
", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) End If Alert(MensajeCosto.ToString(), TipoMensaje.MsgAdvertencia) Return False End If End If End If End If Return True End Function Private Function CalcularDescuentos(CvePS As Integer, Cantidad As Decimal, PU As Decimal) As Modelos.VentaDescuentos Dim Descuento As Decimal = 0 Dim ValidaCondicionesComerciales As Boolean = True 'AGREGA PROMOCION EN EL DESCUENTO Dim TipoPromo As Integer = 0 Dim TotalPromocion As Decimal = 0 Dim PromocionPorcentaje As Decimal = 0 Dim PUModificado As Decimal = 0 Dim SeAjustoPU As Boolean = False Dim PUPromocion As Decimal = 0 Dim CantMinima As Integer = 0 Dim CveMarcaPS As Integer = 0 Dim CveClasifPS As Integer = 0 Dim CveRinTamañoPS As Integer = 0 Dim CvePromocionDetalle As Integer = 0 Dim IncluyeImpuestos As Boolean = False Dim TipoAplicacion As Integer = 1 ' 1 - descuento, 2 en PU Dim ObjDescuento As New Modelos.VentaDescuentos If DdlSubProyectoDatos.SelectedValue = "11842" Then '' E141, el subproyecto: Franquicia, no proceden las promociones Return ObjDescuento End If Dim DrPS As DataRow = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If DrPS IsNot Nothing Then CveMarcaPS = DrPS("CveMarca").ToString().ToEntero() CveClasifPS = DrPS("CveClasificacion").ToString().ToEntero() CveRinTamañoPS = DrPS("CveRinTamaño").ToString().ToEntero() If CveClasifPS = 20636 Then ValidaCondicionesComerciales = False End If 'CAMBIO DE VIGENCIA NO SE APLICAN DESCUENTOS If CveClasifPS = 20637 Then ObjDescuento.ImporteDescuento = 0 Return ObjDescuento End If If UsuarioActual.CveRol = 1 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Cot") AndAlso CveRinTamañoPS > 0 Then If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso Not TbDescuentosAdicionales.Visible Then TbDescuentosAdicionales.Visible = True End If End If End If Dim dr As DataRow = Nothing If DtPromociones IsNot Nothing AndAlso DtPromociones.Rows.Count > 0 Then dr = DtPromociones.FiltroPrimero(String.Format("CvePS = {0} AND (CveSubProyecto = {1} OR CveSubProyecto IS NULL) AND (CveRinTamaño = {2} OR CveRinTamaño IS NULL) AND ((TipoPromocion <> 3 AND (CantidadMinima <= {3} OR CantidadMinima IS NULL)) OR (TipoPromocion = 3 AND CantidadMinima <= {3} ))", CvePS, DdlSubProyectoDatos.SelectedValue, CveRinTamañoPS, Cantidad), Orderby:="CantidadMinima desc ") If dr Is Nothing Then 'verifica marca, si tiene asignada la promocion dr = DtPromociones.FiltroPrimero(String.Format("CvePS IS NULL AND CveClasificacion = {0} AND (CveMarca = {1} OR CveMarca IS NULL) AND (CveSubProyecto = {2} OR CveSubProyecto IS NULL) AND (CveRinTamaño = {3} OR CveRinTamaño IS NULL) AND ((TipoPromocion <> 3 AND (CantidadMinima <= {4} OR CantidadMinima IS NULL)) OR (TipoPromocion = 3 AND CantidadMinima <= {4} )) ", CveClasifPS, CveMarcaPS, DdlSubProyectoDatos.SelectedValue, CveRinTamañoPS, Cantidad), Orderby:="CantidadMinima desc") End If End If Dim Cant As Integer = 1 Dim CveMarcaPromocion As Integer = -1 If dr IsNot Nothing Then CveMarcaPromocion = dr("CveMarca").ToString().ToEntero() TipoPromo = dr("TipoPromocion").ToString().ToEntero() CantMinima = dr("CantidadMinima").ToString().ToEntero() IncluyeImpuestos = dr("IncluyeImpuestos").ToString() = "True" PromocionPorcentaje = dr("Promocion").ToString().ToDecimal PUPromocion = dr("PUPromocion").ToString().ToDecimal CvePromocionDetalle = dr("CvePromocionDetalle").ToString().ToEntero() TipoAplicacion = dr("TipoAplicacion").ToString().ToEntero() If CantMinima > 0 Then Cant = Math.Floor(Cantidad / CantMinima).ToEntero() End If End If TotalPromocion = Math.Round(PUPromocion * Cant / (1 + If(IncluyeImpuestos, PorcentajeIVA, 0)), 6) If TipoPromo = 1 Then 'Promocion por Importe $ If TipoAplicacion = 2 Then Descuento = 0 SeAjustoPU = True PUModificado = Math.Round(PUPromocion / (1 + If(IncluyeImpuestos, PorcentajeIVA, 0)), 6) Else Descuento = Descuento + PU - TotalPromocion End If ElseIf TipoPromo = 2 Then 'Promocion por % Descuento = Descuento + ((PU * PromocionPorcentaje / 100) * Cantidad) ElseIf TipoPromo = 3 Then 'Promocion por Cantidad If Cantidad >= CantMinima Then Descuento = Descuento + TotalPromocion Else CvePromocionDetalle = -1 End If End If 'VERIFICA SI APLICAN CONDICIONES COMERCIALES If ValidaCondicionesComerciales AndAlso DtPorcentajeMarcas IsNot Nothing AndAlso DtPorcentajeMarcas.Rows.Count > 0 Then 'VERIFICA SI EL PRODUCTO TIENE ESPECIFICADA UNA MARCA If Not String.IsNullOrEmpty(DrPS("CveMarca").ToString()) AndAlso DrPS("CveMarca").ToString().ToEntero() > 0 Then Dim RowPorcentaje As DataRow = DtPorcentajeMarcas.FiltroPrimero($"CveMarca={DrPS("CveMarca").ToString()}") 'REALIZA LOS DESCUENTOS DE ACUERDO AL PORCENTAJE POR MARCA If RowPorcentaje IsNot Nothing Then '(AHORA LOS DESCUENTOS SON ACUMULABLES) 'Descuento = 0 Dim PorcentajeProducto As Decimal = RowPorcentaje("PorcentajeProducto").ToString().ToDecimal() / 100D Dim PorcentajeProducto2 As Decimal = RowPorcentaje("PorcentajeProducto2").ToString().ToDecimal() / 100D Dim PorcentajeProducto3 As Decimal = RowPorcentaje("PorcentajeProducto3").ToString().ToDecimal() / 100D Dim TotalInicial As Decimal = (Cantidad * (PU)) '- Descuento Dim TotalFinal As Decimal = TotalInicial 'SI APLICA EL PRIMER DESCUENTO If PorcentajeProducto > 0 Then Dim Descuento1 As Decimal = (TotalInicial * PorcentajeProducto).RoundSQL(2) Dim Total2 As Decimal = (TotalInicial - Descuento1) 'SI APLICA EL SEGUNDO DESCUENTO If PorcentajeProducto2 > 0 Then Dim Descuento2 As Decimal = (Total2 * PorcentajeProducto2).RoundSQL(2) Dim Total3 As Decimal = (Total2 - Descuento2) 'SI APLICA EL TERCER DESCUENTO If PorcentajeProducto3 > 0 Then Dim Descuento3 As Decimal = (Total3 * PorcentajeProducto3).RoundSQL(2) TotalFinal = Total3 - Descuento3 Else TotalFinal = Total3 End If Else TotalFinal = Total2 End If Else TotalFinal = TotalInicial End If If PorcentajeProducto > 0 Then Descuento += ((Cantidad * PU) - TotalFinal) End If 'SI TIENE PRONTO PAGO CALCULA EL IMPORTE If DdlTipoComprobante.SelectedValue = "Ing" AndAlso RowPorcentaje("ProntoPago").ToString().ToDecimal() > 0 Then Dim SubTotalProntoPago As Decimal = (Cantidad * (PU)) - Descuento Dim TotalProntoPago As Decimal = SubTotalProntoPago * (1 + PorcentajeIVA) Dim PorcentajeProntoPago As Decimal = RowPorcentaje("ProntoPago").ToString().ToDecimal() / 100D ObjDescuento.ImporteProntoPago = (TotalProntoPago * PorcentajeProntoPago).RoundSQL(2) End If End If End If End If If Descuento < 0 Then Descuento = 0 Alert("No se calculó el descuento correctamente", TipoMensaje.MsgAdvertencia) End If If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then 'LTH AA Paq. 2 baterias, LTH AAA Paq. 02 baterias, LTH AA Paq. 4 baterias, LTH AAA Paq. 4 Baterias If CvePS.Contiene(521445, 521448, 402917, 402918) Then 'SI TIENE BATERIAS AGREGADAS CON LA MARCA LTH, APLICAR PROMOCION, LA CLASIFICACION DEBE SER ACUMULADORES If TmpDT.SUMD("Cantidad", "CveMarca IN (819,826,1085,1052) AND CveClasificacion IN (20520,20522,20513,20521,20512,20514,20229)") >= 1D Then Descuento = 0 SeAjustoPU = True 'Paq. 2 baterias If CvePS.Contiene(521445, 521448) Then PUPromocion = 25D End If 'Paq. 4 baterias If CvePS.Contiene(402917, 402918) Then PUPromocion = 40D End If PUModificado = Math.Round(PUPromocion / (1 + PorcentajeIVA), 6) End If End If End If 'YOKOHAMA If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso CveRinTamañoPS > 0 AndAlso CveMarcaPromocion.Contiene(800, 912, 1238, 1381, 1456, 1528, 1600, 1672, 1807) Then Dim DtRines As DataTable = Nothing Dim ObjGral As New ClsGenerales If ObjGral.GetRimTamanios(UsuarioActual.CveEmpresa) Then DtRines = ObjGral.DtResultados.Copy() End If ObjGral.Dispose() If CveMarcaPromocion > 0 Then ObjDescuento.NombrePromo = "YOKOHAMA VERANO" 'dr("NombrePromocion").ToString() ObjDescuento.CveMarca = CveMarcaPromocion Dim Rin As String = DtRines.FiltroPrimeroValor("RinTamaño", $"CveRinTamaño = {CveRinTamañoPS}") Dim PromoDescuento As Decimal = (Descuento * (1 + If(IncluyeImpuestos, PorcentajeIVA, 0))).RoundSQL(2) ObjDescuento.ObsDescuento = String.Format("RIN {0} BONO ${1:N2}", Rin, PromoDescuento) End If End If ObjDescuento.ImporteDescuento = Descuento.RoundSQL(2) ObjDescuento.CvePromocionDetalle = CvePromocionDetalle If SeAjustoPU Then ObjDescuento.PU = PUModificado ObjDescuento.EsPUModificado = True End If Return ObjDescuento End Function Private Sub AgregarPS() 'SELECCIONA EL PS DEPENDIENDO LA MODALIDAD (CODIGO BARRAS - DDL) Try If IndicePSActual = -1 Then Dim CvePS As Integer = -1 CvePS = DdlPS.SelectedValue.ToEntero() If ValidaAgregarPS(CvePS, DdlUnidadMedida.SelectedValue.ToEntero(), TxtPrecio.Text.Trim.ToDouble, HdnTipoPS.Value.ToEntero()) Then If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then CvePSAmortizacion = DdlPS.SelectedValue.ToEntero().ToEntero() End If Dim Cantidad As Decimal = TxtCantidad.Text.ToDecimal Dim PU As Decimal = If(CvePSAmortizacion > 0, TxtPrecio.Text.Trim.ToDecimal * -1, TxtPrecio.Text.Trim.ToDecimal) Dim ObjDescuento As Modelos.VentaDescuentos = CalcularDescuentos(CvePS, Cantidad, PU) If ObjDescuento.EsPUModificado Then PU = ObjDescuento.PU End If Dim CvePrecioListaPS As Integer = -1 Dim PrecioListaPS As String = "" If AgregarProductoServicio(Cantidad, DdlUnidadMedida.SelectedValue.ToEntero(), DdlUnidadMedida.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero(), DdlClasificacion.SelectedItem.Text, CvePS, "", TxtObsPS.Text.TrimEnd, PU, ObjDescuento.ImporteDescuento, -1, "", DdlSubProyectoDatos.SelectedValue.ToEntero(), DdlSubProyectoDatos.SelectedItem.Text, Serie:="", TiempoEntrega:="", CuentaPredial:="", RegeneraIEPS:=ClienteDesglosaIEPS, CvePromocionDetalle:=ObjDescuento.CvePromocionDetalle, ImporteProntoPago:=ObjDescuento.ImporteProntoPago, ObjDescuento:=ObjDescuento, CvePrecioLista:=CvePrecioListaPS, PrecioLista:=PrecioListaPS, NumTurnos:=0) Then If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ObjDescuento IsNot Nothing Then ListaDescuentos.Add(ObjDescuento) End If CalculaTotalesVenta() LimpiaAgregar() UpPS.Update() RegistraScript("$('#DVAddPS').modal('hide')") End If End If Else 'Dim TipoDescuento As Integer Dim Cantidad, PU, CantidadInventario As Decimal Dim CvePS As Integer = DdlPS.SelectedValue.ToEntero Dim ObjDescuento As New Modelos.VentaDescuentos Cantidad = TxtCantidad.Text.ToDecimal PU = TxtPrecio.Text.ToDecimal.RoundSQL(6) ObjDescuento.ImporteDescuento = 0 If PU <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(558) = "1" Then Alert("El precio debe ser mayor a 0", TipoMensaje.MsgAdvertencia) Exit Sub End If If UsuarioActual.CveEmpresa = 140 OrElse DtPromociones IsNot Nothing AndAlso DtPromociones.Rows.Count > 0 Then ObjDescuento = CalcularDescuentos(CvePS, Cantidad, PU) End If ''VERIFICA SI EL DESCUENTO SUPERA EL SUBTOTAL Dim DatarowPS As DataRow = Nothing DatarowPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") ' Estado = -1 'verifica si tiene ventaminima If Cantidad > 0 AndAlso DatarowPS("VentaMinima").ToString().ToDecimal > 0 AndAlso (DdlTipoComprobante.SelectedValue = "Rem" Or DdlTipoComprobante.SelectedValue = "Ing") Then 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... If Cantidad Mod DatarowPS("VentaMinima").ToString().ToDecimal <> 0 Then Alert(String.Format("El producto se vende solo en cantidades de {0}", DatarowPS("VentaMinima").ToString())) Exit Sub End If End If 'si es remisión, ingreso, anticipo debe de considerar el preciominimo If Not UsuarioActual.TienePermisoProceso(169) Then ' NO VALIDA EXISTENCIAS NI COSTO - PERMISO PARA NO VALIDAR Dim CveUM As Integer = DdlUnidadMedida.SelectedValue.ToEntero() 'DatarowPS("CveUM").ToString().ToEntero() Dim CveTipoPS As Integer = DatarowPS("CveTipoPS").ToString().ToEntero() CantidadInventario = TmpDT.Rows(IndicePSActual)("CantidadInventario").tostring.ToDecimal Dim CveUMInicial As Integer = TmpDT.Rows(IndicePSActual)("CveUM").tostring.ToEntero Dim ValidaExistencia As Boolean = True If (CantidadInventario > 0) OrElse (Cantidad <= CantidadOriginal) Then 'si ya hay algo surtido, que no valide existencia ValidaExistencia = False End If If CveUM <> CveUMInicial Then ValidaExistencia = True 'SOLO VALIDA EXISTENCIAS Y COSTO: SI USA INVENTARIOS, SOLO PRODUCTOS TIPO PRODUCTO, SOLO REMISIONES E INGRESOS If UsuarioActual.Empresa.UsaInventarios AndAlso CveTipoPS = 2 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119))) Then Dim ObjInventarios As New ClsInventarios Dim Existencia As Decimal If ValidaExistencia Then Existencia = ObjInventarios.GetExistenciasPS(CvePS, CveUM, UsuarioActual.CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveVendedor:=-1, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) End If Dim Costo As Decimal = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDecimal, -1, "-1", NowADS, 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 Costo <= 0 Then Costo = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDecimal, -1, "-1", NowADS, -1, CveTipoAlmacen:=1) ObjInventarios.Dispose() Dim PrecioMinimo As Decimal = 0 'RMF. condicion temporal, para reubicación, precio mínimo If UsuarioActual.CveEmpresa = 119 Then 'Dim CvePrecioLista As Integer = 38 Dim objPS As New ClsProductosServicios If objPS.GetPSSucursalesALL(CvePS, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero()) Then PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal End If objPS.Dispose() End If If ValidaExistencia AndAlso DdlTipoComprobante.SelectedValue <> "Cot" AndAlso Not RegistroxOC Then 'VALIDA EXISTENCIA If UsuarioActual.CveEmpresa.Contiene({72, 80, 119, 140, 153}) Then 'SI ES VENTA NUEVA TOMA EN CUENTA LO DEL TMPDT If CveVenta <= 0 Then If Existencia - TmpDT.SUM("Cantidad", $"CvePS = {CvePS} AND (EntregaDirecta IS NULL OR EntregaDirecta < 1)") < TxtCantidad.Text.ToDouble Then Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia) Exit Sub End If Else If DdlTipoComprobante.SelectedValue = "Rem" Then Dim CantidadVenta As Double = 0 Using ObjVentas As New ClsVentas If ObjVentas.GetVentaDetalle(CveVenta) Then CantidadVenta = ObjVentas.DtResultados.SUM("Cantidad", $"CvePS = {CvePS}") End If End Using 'SUMA LO YA RESTADO EN PENDIENTE POR SURTIR QUE PERTENESCA A LA VENTA. 'PARA QUE NO RESTE LA EXISTENCIA 2 VECES Y PUEDAS COMPARAR LO REAL If (Existencia + CantidadVenta) - TmpDT.SUM("Cantidad", $"CvePS = {CvePS} AND (EntregaDirecta IS NULL OR EntregaDirecta < 1)") < TxtCantidad.Text.ToDouble Then Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If End If End If 'VALIDA COSTOS If Not CveContrato > 0 Then 'BANDERAS PARA VALIDACIONES Dim EsValido As Boolean = False Dim EsValidoMayor As Boolean = False Dim CostoMenor As Decimal = 0 Dim CostoMayor As Decimal = 0 'PRECIO MINIMO If UsuarioActual.Empresa.Funcionalidad(129).ToEntero() > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then '' NOTA. si tiene preciominimo, debe de validarlos e ignorar el costo, pero se debe de considerar el TC, para el costo If PrecioMinimo > 0 Then 'SI EL PRECIO ES MAYOR AL COSTO, SI PASA If PU >= PrecioMinimo Then ' aqui se comparar los importes directos, sin el TC EsValido = True End If Else CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo) '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 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 '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
", DatarowPS("PS").ToString()) If TienePermisoImportes Then MensajeCosto.AppendFormat("El costo del producto es: ${0:#,###.00}
", Costo) MensajeCosto.AppendFormat("El rango menor aceptado es: {0:#,###.00}% ${1}
", UsuarioActual.Empresa.Funcionalidad(129).ToEntero(), CostoMenor) MensajeCosto.AppendFormat("El precio indicado es: ${0:#,###.00} ({1}% de ganancia)
", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) End If Alert(String.Format(MensajeCosto.ToString()), TipoMensaje.MsgAdvertencia) MensajeCosto.Clear() Exit Sub 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:#,###.00}
", Costo) MensajeCosto.AppendFormat("El rango mayor aceptado es: {0}% ${1:#,###.00}
", UsuarioActual.Empresa.Funcionalidad(133).ToEntero(), CostoMayor) MensajeCosto.AppendFormat("El precio indicado es: ${0:#,###.00} ({1}% de ganancia)
", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero) End If Alert(MensajeCosto.ToString(), TipoMensaje.MsgAdvertencia) MensajeCosto.Clear() Exit Sub End If End If End If End If If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ObjDescuento IsNot Nothing Then Dim ConsecEliminar As Integer = TmpDT.Rows(IndicePSActual)("Consec").ToString().ToEntero() If ConsecEliminar > 0 Then Dim descEliminar As Modelos.VentaDescuentos = ListaDescuentos.FirstOrDefault(Function(x) x.Consec = ConsecEliminar) If descEliminar IsNot Nothing Then ListaDescuentos.Remove(descEliminar) End If End If End If If TmpDT.Rows(IndicePSActual)("CvePS").ToString().ToEntero <> CvePS Then TmpDT.Rows.Remove(TmpDT.Rows(IndicePSActual)) AgregarProductoServicio(Cantidad, DdlUnidadMedida.SelectedValue.ToEntero(), DdlUnidadMedida.Text, DdlClasificacion.SelectedValue.ToEntero(), DdlClasificacion.SelectedItem.Text, DdlPS.SelectedValue.ToEntero(), DdlPS.SelectedText, TxtObsPS.Text.Trim, PU, ObjDescuento.ImporteDescuento, CveProyecto:=-1, Proyecto:="", CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), SubProyecto:=DdlSubProyectoDatos.SelectedItem.Text, CuentaPredial:="", CveVentaDetalle:=CvePS, SeActualiza:=True, CvePromocionDetalle:=ObjDescuento.CvePromocionDetalle, ObjDescuento:=ObjDescuento, NumTurnos:=0) GvPS.EditIndex = -1 GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() Else Dim DrPS As DataRow = Nothing DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(IndicePSActual)("CvePS").ToString().ToEntero()).FiltroPrimero("") If Not ClienteDesglosaIEPS Then PU = PU * (1 + DrPS("IEPSPorcentaje").ToString().ToDecimal) TmpDT.Rows(IndicePSActual)("PorcentajeIEPS") = 0 End If Dim TotalCalculableImpuestos As Decimal = ((Cantidad * PU) - (ObjDescuento.ImporteDescuento)) Dim TotalCalculableImpuestosIVA As Decimal = 0 TotalCalculableImpuestosIVA = TotalCalculableImpuestos * (1 + TmpDT.Rows(IndicePSActual)("PorcentajeIEPS").ToString().ToDecimal) Dim ClienteRetIVA As Decimal = Me.ClienteRetIVA If ClienteRetIVA <= 0 Then If DdlTipoRetencion.SelectedValue.Contiene("1", "2") Then ClienteRetIVA = 0.106667D ElseIf DdlTipoRetencion.SelectedValue.Contiene("3") Then ClienteRetIVA = 0.04D End If End If If DrPS("IVA").ToString().Contiene("-1", "") Then TmpDT.Rows(IndicePSActual)("PorcentajeIVA") = PorcentajeIVA Else TmpDT.Rows(IndicePSActual)("PorcentajeIVA") = DrPS("IVA") End If If UsuarioActual.Empresa.Funcionalidad(373) = "1" AndAlso LblRFC.Text = "XEXX010101000" Then TmpDT.Rows(IndicePSActual)("PorcentajeIVA") = 0 TmpDT.Rows(IndicePSActual)("ImporteIVA") = 0 End If TmpDT.Rows(IndicePSActual)("CveUM") = DdlUnidadMedida.SelectedValue.ToEntero() TmpDT.Rows(IndicePSActual)("UM") = DdlUnidadMedida.SelectedItem.Text TmpDT.Rows(IndicePSActual)("Cantidad") = Cantidad TmpDT.Rows(IndicePSActual)("Obs") = TxtObsPS.Text.TrimEnd TmpDT.Rows(IndicePSActual)("TiempoEntrega") = "" TmpDT.Rows(IndicePSActual)("PU") = PU TmpDT.Rows(IndicePSActual)("Descuento") = ObjDescuento.ImporteDescuento TmpDT.Rows(IndicePSActual)("Total") = (Cantidad * PU) TmpDT.Rows(IndicePSActual)("TotalImporte") = (Cantidad * PU).RoundSQL(NumeroDecimales) TmpDT.Rows(IndicePSActual)("ImporteIVA") = (TmpDT.Rows(IndicePSActual)("PorcentajeIVA").ToString().ToDecimal * TotalCalculableImpuestosIVA).RoundSQL(NumeroDecimales) TmpDT.Rows(IndicePSActual)("ImporteIEPS") = (TmpDT.Rows(IndicePSActual)("PorcentajeIEPS").ToString().ToDecimal * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) TmpDT.Rows(IndicePSActual)("ImporteRetIVA") = (ClienteRetIVA * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) TmpDT.Rows(IndicePSActual)("RetIVA") = (ClienteRetIVA * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) TmpDT.Rows(IndicePSActual)("ImporteRetISR") = (ClienteRetISR * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) TmpDT.Rows(IndicePSActual)("PorcentajeRetIVA") = ClienteRetIVA TmpDT.Rows(IndicePSActual)("PorcentajeRetISR") = ClienteRetISR TmpDT.Rows(IndicePSActual)("CuentaPredial") = "" TmpDT.Rows(IndicePSActual)("NumTurnos") = 0 If ObjDescuento IsNot Nothing Then TmpDT.Rows(IndicePSActual)("CvePromocionDetalle") = ObjDescuento.CvePromocionDetalle End If 'RELACIONAL PS CON EL DESCUENTO If ObjDescuento IsNot Nothing Then ObjDescuento.Consec = TmpDT.Rows(IndicePSActual)("Consec").ToString().ToEntero() End If DrPS = Nothing GvPS.EditIndex = -1 GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() End If If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ObjDescuento IsNot Nothing Then ListaDescuentos.Add(ObjDescuento) End If CalculaTotalesVenta() RegistraScript("$('#DVAddPS').modal('hide')") UpPS.Update() End If Catch ex As Exception OnError("Ocurrió un error al agregar el producto", ex) End Try End Sub Protected Sub LnkAgregarPS_Click(sender As Object, e As EventArgs) LimpiaAgregar() RegistraScript("$('#DVAddPS').modal();") End Sub Private Sub LimpiaAgregar() IndicePSActual = -1 CantidadOriginal = 0 TxtCantidad.Text = "" HdnPS.Value = "-1" HdnCodigoPS.Value = "-1" HdnTipoPS.Value = "-1" HdnTipoInv.Value = "-1" DdlClasificacion.SelectedIndex = 0 If Not UsuarioActual.Empresa.Funcionalidad(141).ToString() = "1" Then DdlPS.SelectedValue = "" DdlPS.SelectedText = "" Else DdlPS.SelectedValue = "-1" End If TxtObsPS.Text = "" TxtPrecio.Text = "" HdnIVAPS.Value = "-1" HdnIVARetAPS.Value = "-1" HdnAplicaIEPS.Value = "False" HdnPorcentajeIEPS.Value = "0" HdnCodigo.Value = "-1" TxtCantidad.Focus() UpDVAddPS.Update() End Sub Private Sub CargaPorcentajeMarcas() Dim ObjPS As New ClsProductosServicios If ObjPS.GetPorcentajeMarcas(CveCliente) Then DtPorcentajeMarcas = ObjPS.DtResultados.Copy() End If ObjPS.Dispose() 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 SeActualiza As Boolean = False, Optional CvePromocionDetalle As Integer = -1, Optional EsCargo As Boolean = False, Optional ImporteProntoPago As Decimal = 0, Optional ByRef ObjDescuento As Modelos.VentaDescuentos = Nothing, Optional CvePrecioLista As Integer = -1, Optional PrecioLista As String = "", Optional CveActivoFijo As Integer = -1, Optional AFDepreciacion As Decimal = 0D, Optional AFValorInicial As Decimal = 0D, Optional NumTurnos As Decimal = 0D) As Boolean Dim Retorno As Boolean = False Try If Not CvePS > 0 Then Alert("Ocurrió un error al cargar la información del producto a agregar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError) Return False End If 'VALIDA CONCEPTOS EN CERO - YA SE VALIDA ANTES CON FUNCIONALIDAD - A MIRAS DE ELIMINAR - IPP 28 AGOSTO 2017 If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant") Then If UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso CveOrdenCompraDetalle = 0 Then ' si viene de una oc, se permiten valores en cero If Cantidad * PU <= 0 Then If Not DdlTipoComprobante.SelectedValue = "DPe" Then Alert("El importe del concepto debe ser mayor a cero. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If End If End If End If Dim Row As DataRow = Nothing Dim TotalCalculableImpuestos As Decimal = 0 Dim TotalCalculableImpuestosIVA As Decimal = 0 PU = PU.RoundSQL(6) ' el precio unitario puede llevar hasta 6 decimales permitidos Descuento = Descuento.RoundSQL(NumeroDecimales) If Not TmpDT.Columns.Contains("RetIVA") Then TmpDT.Columns.Add("RetIVA", GetType(Decimal)) End If Row = TmpDT.NewRow() Row("CveProyecto") = CveProyecto Row("Proyecto") = Proyecto Row("CveSubProyecto") = CveSubProyecto Row("SubProyecto") = SubProyecto Row("Serie") = Serie Row("TiempoEntrega") = TiempoEntrega If Modalidad = "U" Then Row("Orden") = Index Else Dim ConsecutivoActual As Integer = TmpDT.MAX("Consec").ToEntero() If ConsecutivoActual < 0 Then ConsecutivoActual = 0 End If Row("Orden") = ConsecutivoActual + 1 End If Dim DrPS As DataRow = Nothing DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") ' Estado = -1 If DrPS Is Nothing Then Alert("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.", TipoMensaje.MsgError) Return False End If If (DrPS("SATClaveUnidadMedida").ToString() = "" Or DrPS("SATClavePS").ToString() = "") Then 'VALIDA CLAVESAT If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then 'DOCUMENTOS DONDE NO SE VALIDA If DrPS("SATClavePS").ToString() = "" Then MensajeCveSAT.AppendFormat("{0}-{1}: Sin producto SAT
", DrPS("Codigo").ToString(), DrPS("PS").ToString()) Return False ElseIf DrPS("SATClaveUnidadMedida").ToString() = "" Then MensajeCveSAT.AppendFormat("{0}-{1}: Sin Unidad Medida SAT
", DrPS("Codigo").ToString(), DrPS("PS").ToString()) Return False End If 'If UsuarioActual.CveEmpresa.Contiene(72, 80, 146) AndAlso DrPS("SATClavePS").ToString() = "01010101" Then ' MensajeCveSAT.AppendFormat("{0}-{1}: El producto/servicio no existe en el catálogo del SAT
", DrPS("Codigo").ToString(), DrPS("PS").ToString()) ' Return False 'End If End If Else If UsuarioActual.CveEmpresa.Contiene(72, 80, 146) AndAlso DrPS("SATClavePS").ToString() = "01010101" Then MensajeCveSAT.AppendFormat("{0}-{1}: El producto/servicio no existe en el catálogo del SAT
", DrPS("Codigo").ToString(), DrPS("PS").ToString()) Return False End If End If 'SI NO ES REFACTURACION verifica si tiene ventaminima If NuevaFactura <> 1 Then If Cantidad > 0 AndAlso DrPS("VentaMinima").ToString().ToDecimal > 0 Then 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... If Cantidad Mod DrPS("VentaMinima").ToString().ToDecimal <> 0 Then Alert(String.Format("El producto se vende solo en cantidades de {0}", DrPS("VentaMinima").ToString())) Return False End If End If End If If CveUM <= 0 Then CveUM = DrPS("CveUnidadMedida").ToString().ToEntero() End If Row("Cantidad") = Cantidad Row("CveUM") = CveUM Row("UM") = DrPS("UnidadMedida") Row("CveClasificacion") = DrPS("CveClasificacion") Row("Clasificacion") = DrPS("Clasificacion") Row("CvePS") = CvePS Row("Obs") = Obs 'VERIFICA SI EN LA FACTURA PADRE SE DESGLOSO EL IEPS Dim FacturaDesglosoIEPS As Boolean = ((CveDevolucion > 0 AndAlso NuevaFactura = 1) AndAlso (Me.ObjFacturaNC IsNot Nothing AndAlso Not Me.ObjFacturaNC.VentaDesglosaIEPS)) If Not ClienteDesglosaIEPS Then If Not RegeneraIEPS AndAlso Not FacturaDesglosoIEPS Then PU = PU * (1 + DrPS("IEPSPorcentaje").ToString().ToDecimal) VentaDesglosaIEPS = True End If DrPS("IEPSPorcentaje") = 0 End If 'SI YA SE DESGLOSO EL IEPS SE GUARDA LA BANDERA EN ESTA FACTURA If FacturaDesglosoIEPS Then VentaDesglosaIEPS = True End If If DrPS("IVA").ToString().Contiene("-1", "") Then Row("PorcentajeIVA") = PorcentajeIVA Else Row("PorcentajeIVA") = DrPS("IVA") End If If UsuarioActual.Empresa.Funcionalidad(373) = "1" AndAlso LblRFC.Text = "XEXX010101000" Then DrPS("IVA") = 0 Row("PorcentajeIVA") = 0 End If If ClienteNODesglosaIVA Then 'If Not RegeneraIEPS AndAlso Not FacturaDesglosoIEPS Then PU = PU * (1 + Row("PorcentajeIVA").ToString().ToDecimal) VentaNODesglosaIVA = True 'End If DrPS("IVA") = 0 Row("PorcentajeIVA") = 0 End If TotalCalculableImpuestos = ((Cantidad * (PU)) - Descuento) TotalCalculableImpuestosIVA = TotalCalculableImpuestos * (1 + DrPS("IEPSPorcentaje").ToString().ToDecimal) Row("PU") = PU Row("Codigo") = DrPS("Codigo") Row("NoIdentificacion") = DrPS("Codigo") Row("ClaveSATFraccionArancelaria") = DrPS("ClaveSATFraccionArancelaria") Row("ClaveSATUnidadAduana") = DrPS("ClaveSATUnidadAduana") Row("ClaveSATFraccionArancelariaDescripcion") = DrPS("ClaveSATFraccionArancelariaDescripcion") Row("ClaveSATUnidadAduanaDescripcion") = DrPS("ClaveSATUnidadAduanaDescripcion") If Modalidad = "U" Then Row("Consec") = Index Else Dim ConsecutivoActual As Integer = TmpDT.MAX("Consec").ToEntero() If ConsecutivoActual < 0 Then ConsecutivoActual = 0 End If Row("Consec") = ConsecutivoActual + 1 End If Row("PS") = DrPS("PS") Row("CodigoPS") = DrPS("PSCodigo").ToString() Row("CveTipoPS") = DrPS("CveTipoPS") Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario") Row("CveTamaño") = DrPS("CveTamaño") Row("CodigoObjetoImpuesto") = DrPS("CodigoObjetoImpuesto") If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion") If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion") Dim ClienteRetIVA As Decimal = Me.ClienteRetIVA If ClienteRetIVA <= 0 AndAlso DrPS("RetIVA").ToString.ToDecimal > 0 Then ClienteRetIVA = DrPS("RetIVA").ToString.ToDecimal DdlTipoRetencion.Enabled = True End If If ClienteRetIVA <= 0 Then If DdlTipoRetencion.SelectedValue.Contiene("1", "2") Then ClienteRetIVA = 0.106667D ElseIf DdlTipoRetencion.SelectedValue.Contiene("3") Then ClienteRetIVA = 0.04D End If End If LblRetIVA.Text = (ClienteRetIVA * 100).FormatoNumero If LblRetIVA.Text.ToDecimal() > 0 Then TrRetIVA.Style.Add("display", "") DdlTipoRetencion.Visible = True Else TrRetIVA.Style.Add("display", "none") End If Row("IVA") = Row("PorcentajeIVA") Row("ImporteIVA") = (Row("PorcentajeIVA").ToString().ToDecimal * TotalCalculableImpuestosIVA).RoundSQL(NumeroDecimales) Row("ImporteRetIVA") = (ClienteRetIVA * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) Row("RetIVA") = (ClienteRetIVA * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) Row("ImporteRetISR") = (ClienteRetISR * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) Row("PorcentajeRetIVA") = ClienteRetIVA Row("PorcentajeRetISR") = ClienteRetISR Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje") Row("ImporteIEPS") = (DrPS("IEPSPorcentaje").ToString().ToDecimal * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) Row("IEPS") = Row("ImporteIEPS") Row("Descuento") = (Descuento).RoundSQL(NumeroDecimales) Row("TipoDescuento") = "-1" Row("CvePromocionDetalle") = CvePromocionDetalle Row("Total") = (Cantidad * PU) Row("TotalImporte") = (Cantidad * PU).RoundSQL(NumeroDecimales) Row("SATClaveProdServ") = DrPS("SATClavePS") Row("SATClaveUM") = DrPS("SATClaveUnidadMedida") If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then Row("CvePresupuestoIngreso") = Me.DdlFuenteRecaudacion.SelectedValue End If Row("EntregaDirecta") = EntregaDirecta 'Contratos Row("CveContratoDetalle") = CveContratoDetalle Row("CveVentaDetalle") = CveVentaDetalle Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle Row("CveVentaDetalleRemision") = CveVentaDetalleRemision Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion Row("CveVentaDetallePedido2") = CveVentaDetallePedido2 Row("CuentaPredial") = CuentaPredial Row("EsCargo") = EsCargo If TmpDT.Columns.Contains("CveMarca") Then Row("CveMarca") = DrPS("CveMarca") End If If ImporteProntoPago > 0 Then Row("ImporteProntoPago") = ImporteProntoPago Row("TieneProntoPago") = "Si" End If Row("CvePrecioLista") = CvePrecioLista Row("PrecioLista") = PrecioLista Row("CveActivoFijo") = CveActivoFijo Row("AFDepreciacion") = AFDepreciacion Row("AFValorInicial") = AFValorInicial Row("NumTurnos") = NumTurnos If UsuarioActual.CveEmpresa.Contiene(119, 13, 83) Then If Not RemisionesLista.Count > 0 Then 'SI VIENE DE REMISION NO SE CONSIDERA 'MONEDA DIFERENTE DEL PS AL PRIMER PS AGREGADO If DdlMoneda.Enabled = False And CveVenta < 0 And TmpDT.Rows.Count > 0 Then If DdlMoneda.SelectedValue <> DrPS("CveMoneda").ToString() Then Alert($"La moneda base del producto: {DrPS("PSCodigo").ToString()} es diferente a la moneda del documento.", TipoMensaje.MsgAdvertencia) Return False End If End If 'ACTIVA PRODUCTOS DE LA MISMA MONEDA If TmpDT.Rows.Count = 0 And CveVenta < 0 Then DdlMoneda.SelectedValueExist(DrPS("CveMoneda").ToString()) CambiaMoneda() DdlMoneda.Enabled = False End If End If End If 'RELACIONAL PS CON EL DESCUENTO If ObjDescuento IsNot Nothing Then ObjDescuento.Consec = Row("Consec").ToString().ToEntero() End If 'RECARGAR GV TmpDT.Rows.Add(Row) 'AGREGA PS ADICIONAL If UsuarioActual.Empresa.Funcionalidad(561).ToString() = "1" AndAlso Not UsuarioActual.TienePermisoProceso(285) AndAlso GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows.Count > 0 AndAlso Not SeActualiza Then For Each Dr As DataRow In GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows Dim CvePSAdicional As Integer = Dr("CvePSAdicional").ToString().ToEntero() Dim DrPoliza As DataRow = TmpDT.NewRow() DrPoliza.ItemArray = Row.ItemArray Dim DrPSAdicional As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSAdicional).Rows(0) If DrPSAdicional IsNot Nothing Then DrPoliza("CvePS") = CvePSAdicional DrPoliza("PS") = DrPSAdicional("PS").ToString() DrPoliza("CveUM") = DrPSAdicional("CveUM").ToString().ToEntero() DrPoliza("UM") = DrPSAdicional("UnidadMedida").ToString() DrPoliza("CveClasificacion") = DrPSAdicional("CveClasificacion").ToString().ToEntero() DrPoliza("Clasificacion") = DrPSAdicional("Clasificacion").ToString() DrPoliza("CodigoPS") = DrPSAdicional("PSCodigo").ToString() DrPoliza("CveTipoPS") = DrPSAdicional("CveTipoPS") DrPoliza("CveTipoInvPS") = DrPSAdicional("Inv_CveMetodoInventario") DrPoliza("NoIdentificacion") = DrPSAdicional("Codigo") If Modalidad = "U" Then DrPoliza("Consec") = Index Else Dim ConsecutivoActual As Integer = TmpDT.MAX("Consec").ToEntero() If ConsecutivoActual < 0 Then ConsecutivoActual = 0 End If DrPoliza("Consec") = ConsecutivoActual + 1 End If Row("Orden") = TmpDT.Rows.Count + 1 DrPoliza("Cantidad") = If(Dr("Cantidad").ToString().ToDecimal > 0, Dr("Cantidad").ToString().ToDecimal, Cantidad) PU = 0 Dim PrecioSugerido As Decimal = 0 'Dim CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero() If CvePrecioLista > 0 Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioLista, CvePS:=CvePSAdicional) Then PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDecimal If PrecioSugerido = 0 Then Dim ObjInventarios As New ClsInventarios Dim CostoPS As Decimal = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString().ToDecimal, -1, "-1", NowADS, 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(CvePSAdicional, DrPoliza("Cantidad").ToString().ToDecimal, -1, "-1", NowADS, -1, CveTipoAlmacen:=1) ObjInventarios.Dispose() Dim PorcentajePrecio As Decimal = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If ObjPS.Dispose() End If End If If PrecioSugerido > 0 Then PU = PrecioSugerido End If PU = PU.RoundSQL(6) DrPoliza("PU") = PU TotalCalculableImpuestos = (DrPoliza("Cantidad").ToString().ToDecimal * (PU)) If DrPSAdicional("IVA").ToString().Contiene("-1", "") Then DrPoliza("PorcentajeIVA") = PorcentajeIVA Else DrPoliza("PorcentajeIVA") = DrPSAdicional("IVA") End If DrPoliza("IVA") = DrPoliza("PorcentajeIVA") DrPoliza("ImporteIVA") = (DrPoliza("PorcentajeIVA").ToString().ToDecimal * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) DrPoliza("ImporteRetIVA") = (ClienteRetIVA * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) DrPoliza("ImporteRetISR") = (ClienteRetISR * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) DrPoliza("PorcentajeRetIVA") = ClienteRetIVA DrPoliza("PorcentajeRetISR") = ClienteRetISR DrPoliza("PorcentajeIEPS") = DrPSAdicional("IEPSPorcentaje") DrPoliza("ImporteIEPS") = (DrPSAdicional("IEPSPorcentaje").ToString().ToDecimal * TotalCalculableImpuestos).RoundSQL(NumeroDecimales) DrPoliza("IEPS") = DrPoliza("ImporteIEPS") DrPoliza("Descuento") = 0 ' Descuento DrPoliza("TipoDescuento") = "" DrPoliza("Total") = (DrPoliza("Cantidad").ToString().ToDecimal * PU) DrPoliza("TotalImporte") = (DrPoliza("Cantidad").ToString().ToDecimal * PU).RoundSQL(NumeroDecimales) DrPoliza("SATClaveProdServ") = DrPSAdicional("SATClavePS") DrPoliza("SATClaveUM") = DrPSAdicional("SATClaveUnidadMedida") DrPoliza("CveActivoFijo") = -1 TmpDT.Rows.Add(DrPoliza) End If Next End If Retorno = True Catch ex As Exception Retorno = False OnError("Ocurrió un error al agregar el producto/servicio", ex) End Try Return Retorno End Function #End Region #Region "D A T A - T A B L E S" Private Sub CreaDTVentas() TmpDT = New DataTable TmpDT.Columns.Add("CveVenta", GetType(Integer)) TmpDT.Columns.Add("Consec", GetType(Integer)) TmpDT.Columns.Add("Cantidad", GetType(Decimal)) TmpDT.Columns.Add("Codigo", GetType(String)) TmpDT.Columns.Add("CveUM", GetType(Integer)) TmpDT.Columns.Add("UM", GetType(String)) TmpDT.Columns.Add("SATClaveUM", GetType(String)) TmpDT.Columns.Add("CveClasificacion", GetType(Integer)) TmpDT.Columns.Add("Clasificacion", GetType(String)) TmpDT.Columns.Add("CvePS", GetType(Integer)) TmpDT.Columns.Add("PS", GetType(String)) TmpDT.Columns.Add("CodigoPS", GetType(String)) TmpDT.Columns.Add("SATClaveProdServ", GetType(String)) TmpDT.Columns.Add("NoIdentificacion", GetType(String)) TmpDT.Columns.Add("CveTipoPS", GetType(Integer)) TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer)) TmpDT.Columns.Add("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)) TmpDT.Columns.Add("RetIVA", GetType(Decimal)) TmpDT.Columns.Add("RetISR", GetType(Decimal)) 'Para uso del módulo contable 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)) TmpDT.Columns.Add("CvePromocionDetalle", 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("CveConcepto", GetType(Integer)) TmpDT.Columns.Add("EsCargo", GetType(Boolean)) TmpDT.Columns.Add("CveVentaDetalleRNC", GetType(Integer)) TmpDT.Columns.Add("TieneProntoPago", GetType(String)) TmpDT.Columns.Add("ImporteProntoPago", GetType(Decimal)) TmpDT.Columns.Add("CodigoObjetoImpuesto", GetType(String)) TmpDT.Columns.Add("CveMarca", GetType(Integer)) TmpDT.Columns.Add("CvePrecioLista", GetType(Integer)) TmpDT.Columns.Add("PrecioLista", GetType(String)) TmpDT.Columns.Add("CveActivoFijo", GetType(Integer)) TmpDT.Columns.Add("AFDepreciacion", GetType(Decimal)) TmpDT.Columns.Add("AFValorInicial", GetType(Decimal)) TmpDT.Columns("EsCargo").DefaultValue = False TmpDT.Columns("TieneProntoPago").DefaultValue = "No" TmpDT.Columns("ImporteProntoPago").DefaultValue = 0 TmpDT.Columns.Add("NumTurnos", GetType(Decimal)) TmpDT.Columns("NumTurnos").DefaultValue = 0 TmpDT.Columns.Add("NumeroPedimento", GetType(String)) End Sub Private Sub CreaDTmpC() DTmpC = New DataTable DTmpC.Columns.Add("Descripcion", GetType(String)) End Sub Private Sub CreaDTmpF() DTmpF = New DataTable DTmpF.Columns.Add("CveVenta", GetType(Integer)) DTmpF.Columns.Add("Titulo", GetType(String)) DTmpF.Columns.Add("Nombre", GetType(String)) DTmpF.Columns.Add("Puesto", GetType(String)) DTmpF.Columns.Add("Lado", GetType(Integer)) End Sub Private Sub CreaDTImpuestos() TmpDTImpuestos = New DataTable TmpDTImpuestos.Columns.Add("CveImpuestoLocal", GetType(Integer)) TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String)) TmpDTImpuestos.Columns.Add("Porcentaje", GetType(Decimal)) TmpDTImpuestos.Columns.Add("Importe", GetType(Decimal)) TmpDTImpuestos.Columns.Add("TipoImpuesto", GetType(Integer)) TmpDTImpuestos.Columns.Add("CveCuenta", GetType(Integer)) TmpDTImpuestos.Columns.Add("Orden", GetType(Integer)) End Sub Private Sub CreaDTImpuestosIVAIEPS() TmpDTImpuestosIVAIEPS = New DataTable TmpDTImpuestosIVAIEPS.Columns.Add("Impuesto", GetType(String)) TmpDTImpuestosIVAIEPS.Columns.Add("tasa", GetType(String)) TmpDTImpuestosIVAIEPS.Columns.Add("Importe", GetType(Decimal)) TmpDTImpuestosIVAIEPS.Columns.Add("Orden", GetType(Integer)) End Sub Private Sub CreaDTDocumentosRelacionados() TmpDTDocumentosRelacionados = New DataTable TmpDTDocumentosRelacionados.Columns.Add("SerieFolio", GetType(String)) TmpDTDocumentosRelacionados.Columns.Add("Fecha", GetType(String)) TmpDTDocumentosRelacionados.Columns.Add("Importe", GetType(Decimal)) TmpDTDocumentosRelacionados.Columns.Add("FolioFiscal", GetType(Integer)) End Sub #End Region #Region "P D F" #End Region #Region "A C T U A L I Z A " #Region "New" 'Private Function ActualizaTimbrado(Timbro As Boolean, CveVenta As Integer) As Boolean ' Dim Retorno = False ' Dim ObjVentas As New ClsVentas() ' Retorno = ObjVentas.UpdateVentaTimbre(CBool(Timbro), CveVenta) ' ObjVentas.Dispose() ' Return Retorno 'End Function 'Private Sub ActualizaCadenaOriginal(CadenaOriginal As String, CveVenta As Integer) ' Dim ObjVentas As New ClsVentas() ' ObjVentas.UpdateVentaCadenaOriginal(CadenaOriginal.ToString(), CveVenta) ' ObjVentas.Dispose() 'End Sub 'Private Sub ActualizaEstatus(CveEstatus As Integer, FolioFiscal As String, CveVenta As Integer) ' Dim ObjVentas As New ClsVentas() ' ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", NowADS(), CveVenta) ' ObjVentas.Dispose() 'End Sub 'Private Sub ActualizaCliente(NumCtaPago As String, MetodoDePago As Integer, CveCliente As Integer) ' Dim ObjCliente As New ClsClientes ' ObjCliente.UpdateClienteFactura(NumCtaPago, MetodoDePago, CveCliente, UsuarioActual.CveUsuario) ' ObjCliente.Dispose() 'End Sub #End Region #End Region #Region "M E T O D O S" 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 SetPermisos() If CveVenta < 1 OrElse EsCreaApartirDe Then 'Puede cotizar If Not UsuarioActual.TienePermisoProceso(59) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) End If 'Puede Hacer NC If Not UsuarioActual.TienePermisoProceso(175) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) End If 'Puede Hacer Devolución If Not UsuarioActual.TienePermisoProceso(264) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) End If 'Puede facturar If Not UsuarioActual.TienePermisoProceso(60) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing")) DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant")) If Not UsuarioActual.TienePermisoProceso(175) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) End If If Not UsuarioActual.TienePermisoProceso(264) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) End If End If 'Puede remisionar If Not UsuarioActual.TienePermisoProceso(199) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) End If 'Puede hacer pedido If Me.CveVenta <= 0 Then If Not UsuarioActual.TienePermisoProceso(177) Then If DdlTipoComprobante.Items.FindByValue("Pd2") IsNot Nothing Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2")) End If End If End If '[IPP]: FALTA CONFIGURAR Y DAR PERMISO A TODOS LOS QUE TENGAN ACCESO A VENTAS ''Puede remisionar 'If Not UsuarioActual.TienePermisoProceso(199) Then ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) 'End If ''MODO SOLO LECTURA 'If DdlTipoComprobante.Items.Count = 0 Then ' DdlTipoComprobante.Items.Insert(0, New ListItem("Solo lectura", "-1")) ' TrBotones.Visible = False 'End If ConfiguraTipoDocto() End If End Sub Private Sub CalculaTotalesVenta(Optional RecalculaImpuestosLocales As Boolean = True, Optional NCDescuento As Boolean = False, Optional ValidarDescuentos As Boolean = False, Optional RecalcularTotalOriginal As Boolean = True) Dim TotalSubTotal As Decimal = TmpDT.SUMD("TotalImporte") Dim TotalSubTotalRef As Decimal = TotalSubTotal Dim TotalDescuentos As Decimal = TmpDT.SUMD("Descuento") Dim TotalAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal Dim TotalIVA As Decimal = TmpDT.SUMD("ImporteIVA") Dim TotalIEPS As Decimal = TmpDT.SUMD("ImporteIEPS") Dim TotalRetIVA As Decimal = TmpDT.SUMD("ImporteRetIVA") Dim TotalRetISR As Decimal = TmpDT.SUMD("ImporteRetISR") Dim Total As Decimal = 0 Dim TotalImpuestosLocales As Decimal = 0 Dim TotalProntoPago As Decimal = 0 If ValidarDescuentos Then TotalSubTotalRef = TotalSubTotal - TotalDescuentos End If 'If TotalAmortizacion > 0 AndAlso TotalSubTotalRef = TotalAmortizacion Then ' si se amortizó completa la factura, debe de limpiar los impuestos PorcentajeRetIVA ' If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("3") Then ' For Each dr As DataRow In TmpDT.Rows ' dr("ImporteIVA") = 0 : dr("ImporteIEPS") = 0 : dr("PorcentajeIEPS") = 0 : dr("ImporteRetIVA") = 0 : dr("PorcentajeRetIVA") = 0 : dr("ImporteRetISR") = 0 : dr("PorcentajeIVA") = 0 : dr("IVA") = 0 ' Next ' If TmpDTImpuestos IsNot Nothing Then ' For Each dr2 As DataRow In TmpDTImpuestos.Rows ' dr2("Importe") = 0 ' Next ' TmpDTImpuestos.AcceptChanges() ' End If ' TmpDT.AcceptChanges() ' TotalIVA = TmpDT.SUMD("ImporteIVA") ' TotalIEPS = TmpDT.SUMD("ImporteIEPS") ' TotalRetIVA = TmpDT.SUMD("ImporteRetIVA") ' TotalRetISR = TmpDT.SUMD("ImporteRetISR") ' TotalImpuestosLocales = TmpDTImpuestos.SUMD("Importe") ' End If 'End If If RecalculaImpuestosLocales AndAlso TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then If TotalSubTotal <> TotalAmortizacion Then For Each drt As DataRow In TmpDTImpuestos.Rows drt("Importe") = drt("Porcentaje").ToString().ToDecimal * TotalSubTotal / 100 Next End If GvImpuestosLocales2.DataSource = TmpDTImpuestos GvImpuestosLocales2.DataBind() End If For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal > 0 Then If gvr.DataKey("TipoImpuesto") = "5" Then ' traslado de imp local TotalImpuestosLocales -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal Else TotalImpuestosLocales += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal End If End If End If Next 'If TotalDescuentos > 0 Then GvPS.Columns(ColumnaDescuento).Visible = True : thEncDesc1.Visible = True : thEncDesc2.Visible = True Else GvPS.Columns(ColumnaDescuento).Visible = False : thEncDesc1.Visible = False : thEncDesc2.Visible = False If TotalIEPS > 0 Then TrIEPS.Visible = True : GvPS.Columns(ColumnaIEPS).Visible = True Else TrIEPS.Visible = False : GvPS.Columns(ColumnaIEPS).Visible = False If TotalRetIVA > 0 Then GvPS.Columns(ColumnaRetIVA).Visible = True Else GvPS.Columns(ColumnaRetIVA).Visible = False If TotalRetISR > 0 Then GvPS.Columns(ColumnaRetISR).Visible = True Else GvPS.Columns(ColumnaRetISR).Visible = False 'If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero().Contiene(2, 1) Then ' TotalAmortizacion = 0 'End If Dim TotalRemNCAplicado As Decimal = 0 If TbDescuentosRNC.Visible AndAlso ListaNCDesc IsNot Nothing Then TotalRemNCAplicado = ListaNCDesc.Sum(Function(RNC) RNC.TotalRemNCAplicado) If ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0 Then TotalRemNCAplicado += ListaNCBonificacion.Sum(Function(RNC) RNC.TotalRemNCAplicado) End If End If Total = (TotalSubTotal - TotalDescuentos - TotalAmortizacion + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) 'LblSubTotal1.Text = TotalSubTotal.FormatoNumero(2) TxtSubTotal.Text = TotalSubTotal.FormatoNumero(2) LblDescuentos.Text = TotalDescuentos.FormatoNumero TxtSubTotal2.Text = (TotalSubTotal - TotalDescuentos - TotalAmortizacion).FormatoNumero(2) TxtRetIVA.Text = TotalRetIVA.FormatoNumero(2) TxtRetISR.Text = TotalRetISR.FormatoNumero(2) TxtIVA.Text = TotalIVA.FormatoNumero TxtIEPS.Text = TotalIEPS.FormatoNumero TxtTotal.Text = Total.FormatoNumero HdnProntoPago.Value = TotalProntoPago.ToString() LblProntoPago.Text = TotalProntoPago.FormatoNumero(2) LblTotalAPagar.Text = (TxtTotal.Text.ToDecimal() - TotalRemNCAplicado - TotalProntoPago).FormatoNumero If RecalcularTotalOriginal Then LblTotalOriginal.Text = (TxtTotal.Text.ToDecimal()).FormatoNumero End If LblTotalAPagarAdicional.Text = (LblTotalOriginal.Text.ToDecimal() - LblDescuentoAdicional.Text.ToDecimal()).FormatoNumero 'LblAmort.Text = TxtSubTotal.Text If CveVenta <= 0 OrElse (CveDevolucion > 0 And NuevaFactura = 1) Then HdnVentaSaldo.Value = Total.ToString() Else HdnVentaSaldo.Value = SaldoVenta.ToString() End If HdnIVAOriginal.Value = TxtIVA.Text 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = Total.ToString() If MensajeCveSAT IsNot Nothing AndAlso MensajeCveSAT.ToString().Length > 0 Then Alert($"Los siguientes conceptos hace falta especificar clave SAT

{MensajeCveSAT.ToString()}", TipoMensaje.MsgAdvertencia) MensajeCveSAT.Clear() End If Dim view As DataView = New DataView(TmpDT) view.Sort = "Consec" GvPS.DataSource = view GvPS.DataBind() If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ListaDescuentos.Count > 0 Then Dim Titulo As String = ListaDescuentos.FirstOrDefault().NombrePromo Dim strPromos As New StringBuilder If Not String.IsNullOrEmpty(Titulo) Then For Each Promo As Modelos.VentaDescuentos In ListaDescuentos If Not String.IsNullOrEmpty(Promo.ObsDescuento) Then strPromos.AppendFormat("{0}, ", Promo.ObsDescuento) End If Next If strPromos.Length > 2 Then strPromos.Remove(strPromos.Length - 2, 2) End If If strPromos.Length > 0 Then TxtObsFact.Text = "" TxtObsFact.Text = String.Format("{0} {1}", Titulo, strPromos.ToString()) End If End If End If ValidaImportePublicoGeneral() UPObservaciones.Update() UpPS.Update() RegistraScript("BorraDescuentos();", "BorraDescuentos") End Sub Private Sub VinculaCotizacionVenta() Dim ObjVentas As New ClsVentas() ObjVentas.UpdateVentaCotizacion(CveVenta, Request("CveVenta").ToEntero()) ObjVentas.Dispose() End Sub Protected Sub DdlFuenteRecaudacion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFuenteRecaudacion.SelectedIndexChanged For Each dr As DataRow In TmpDT.Rows dr("CvePresupuestoIngreso") = DdlFuenteRecaudacion.SelectedValue Next GvPS.DataSource = TmpDT GvPS.DataBind() UpPS.Update() End Sub Protected Sub DdlFR_SelectedIndexChanged(sender As Object, e As EventArgs) Dim DdlFR_Gv As DropDownList = CType(sender, DropDownList) Dim index As Integer = CType(DdlFR_Gv.NamingContainer, GridViewRow).FCLiteral("LtlConsecutivo").Text.ToString().ToEntero() If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then TmpDT(index - 1)("CvePresupuestoIngreso") = DdlFR_Gv.SelectedValue End If TmpDT.AcceptChanges() End Sub Protected Sub TxtCodigo_TextChanged(sender As Object, e As System.EventArgs) Handles TxtCodigo.TextChanged Dim ObjClientes As New ClsClientes() Dim Nombre As String = "-1" Dim Codigo As String = "-1" Dim NombreCorto As String = "-1" Dim RFC As String = "-1" Dim Telefono As String = "-1" Dim Mail As String = "-1" If TxtCodigo.Text.Trim <> String.Empty Then Codigo = TxtCodigo.Text.Trim If Codigo <> "-1" Then If ObjClientes.GetClientes(-1, Nombre, Codigo, NombreCorto, RFC, Telefono, Mail, -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then If ObjClientes.DtResultados.Rows.Count > 0 Then If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not ObjClientes.CveCliente.Contiene(10450, 10460, 10458) Then TrEmitir.Visible = False : LbAgregar.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False UpFacturar.Update() Exit Sub ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not ObjClientes.CveCliente.Contiene(27448) Then TrEmitir.Visible = False : LbAgregar.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False UpFacturar.Update() Exit Sub Else HdnCveCliente.Value = ObjClientes.CveCliente.ToString() End If BtnBuscarCliente_Click(sender, e) Else Alert("No se encontró el cliente con el código: " & TxtCodigo.Text.Trim & ".", Extensiones.TipoMensaje.MsgAdvertencia) TxtCodigo.Text = "" LblCliente.Text = "Cliente" LblDireccion.Text = "Dirección" LblColonia.Text = "Colonia" LblCiudad.Text = "Ciudad" LblEstado.Text = "Estado" LblCP.Text = "00000" LblRFC.Text = "AAA010101AAA" LblTelefono.Text = "9999999999" trsucursalciente.Visible = False End If End If ObjClientes.Dispose() End If End Sub Private Sub HabilitarFacturacionSucursal() trsucursalciente.Visible = True 'LnkAgregarSucursal.Visible = True LblSucursal.Text = "Cliente" If (CveVenta <= 0 OrElse NuevaFactura = 1) Then DdlSucursalCliente.Enabled = True End If DdlSucursalCliente_SelectedIndexChanged(DdlSucursalCliente, EventArgs.Empty) UpCliente.Update() End Sub Protected Sub ChkFacturarSucursal_CheckedChanged(sender As Object, e As EventArgs) End Sub Private Sub ConfiguraTipoDocto() Tr33.Visible = False 'si tiene la funcionalidad que se active independiente del tipo de documento RMF 15-10-2017 Tr33.Visible = True If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then BtnEmitirImprimir.Text = "Emitir e Imprimir" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then BtnEmitirImprimir.Text = "Emitir e Imprimir" 'TdReferencia.Style.Remove("display") ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then BtnEmitirImprimir.Text = "Registrar" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC", "PA", "Pd2") Then BtnEmitirImprimir.Text = "Registrar" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue = "Cot" Then BtnEmitirImprimir.Text = "Cotizar" 'TdReferencia.Style.Add("display", "none") 'FACTURACION 3.3 Tr33.Visible = True ElseIf DdlTipoComprobante.SelectedValue = "Com" Then BtnEmitirImprimir.Text = "Registrar" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue.ToString() = "OP" Then BtnEmitirImprimir.Text = "Registrar" End If UpFacturar.Update() End Sub Private Sub EliminaPoliza() 'If UsuarioActual.Empresa.TipoContabilidad = 2 Then ' Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) ' ObjAC.IniciaTransacSQL() ' Dim ObjConta As New ClsContabilidad ' ObjConta.IniciaTransacSQL() ' Dim ErrorMovimiento = False ' 'Elimina la poliza ' If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 Then ' If Not ObjAC.RemovePoliza(IdPoliza) Then ' ErrorMovimiento = True ' End If ' End If ' 'Desasocia la poliza ' If Not ErrorMovimiento Then ' If Not ObjConta.DesasociarPoliza(IdPoliza, UsuarioActual.CveEmpresa) Then ' ErrorMovimiento = True ' End If ' End If ' If Not ErrorMovimiento Then ' If Not ObjConta.UpdatePrePolizasDetalleBloquear(CvePrePoliza, False) Then ' ErrorMovimiento = True ' End If ' End If ' If Not ErrorMovimiento Then ' Alert("La póliza ha sido desvinculada y eliminada con éxito.", TipoMensaje.MsgInformacion) ' ObjAC.Commit() ' ObjConta.Commit() ' BtnDescontabilizar.Visible = False ' Else ' Alert("Ocurrió un error al desvincular y/o eliminar la póliza. Por favor intente de nuevo ", TipoMensaje.MsgError) ' ObjAC.RollBack() ' ObjConta.RollBack() ' End If ' ObjAC.Dispose() ' ObjConta.Dispose() 'End If End Sub Protected Sub DdlPS_SelectedIndexChanged1(sender As Object, e As EventArgs) Dim Ddl As DropDownList = CType(sender, DropDownList) Dim gvr As GridViewRow = CType(Ddl.BindingContainer, GridViewRow) gvr.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(Ddl.SelectedValue.ToEntero(), -1, UsuarioActual.CveEmpresa) gvr.FCDropDownList("DdlUnidadMedida").DataBind() End Sub Private Function CuadrarFacturaMovimientos(ByRef ObjVentas As ClsVentas, CveRemision As Integer, MovDetalle As DataTable) As DataTable Dim MovDTCuadrados As New DataTable MovDTCuadrados = MovDetalle.Clone MovDTCuadrados.Clear() 'Llenamos el DT solo si es primera llamada If DtRemConceptosSurtidos Is Nothing Then Dim DtDetalleRemision As DataTable = Nothing Dim StrCveVentasDetalle As New StringBuilder() If ObjVentas.GetVentaDetalle(CveRemision) Then DtDetalleRemision = ObjVentas.DtResultados.FiltraParametros("", DistinctColumns:={"CveVenta", "CveVentaDetalle"}) End If For Each RowDetalle As DataRow In DtDetalleRemision.Rows StrCveVentasDetalle.AppendFormat("{0},", RowDetalle("CveVentaDetalle")) Next If StrCveVentasDetalle.Length > 0 Then StrCveVentasDetalle.Remove(StrCveVentasDetalle.Length - 1, 1) End If If DtDetalleRemision IsNot Nothing Then DtRemConceptosSurtidos = New DataTable DtRemConceptosSurtidos.Columns.Add("CveRemision", GetType(Integer)) DtRemConceptosSurtidos.Columns.Add("CveVentaDetalle", GetType(Integer)) DtRemConceptosSurtidos.Columns.Add("Cantidad", GetType(Decimal)) DtRemConceptosSurtidos.Columns.Add("Surtido", GetType(Decimal)) 'VERIFICA SOLO LOS QUE SON TIPO PRODUCTOS For Each dr As DataRow In DtRemisionesTmpDT.FiltraParametros($"CveTipoPS = 2 AND CveVentaDetalle IN ({StrCveVentasDetalle.ToString()})").Rows Dim dtr As DataRow = DtRemConceptosSurtidos.NewRow dtr("CveRemision") = CveRemision dtr("CveVentaDetalle") = dr("CveVentaDetalle") dtr("Cantidad") = dr("Cantidad") dtr("Surtido") = 0 DtRemConceptosSurtidos.Rows.Add(dtr) Next End If End If For Each dr As DataRow In MovDetalle.Rows Dim rowSurtidos As DataRow = DtRemConceptosSurtidos.FiltroPrimero($"CveVentaDetalle={dr("CveVentaDetalle")}") Dim rowSurtidosP As DataRow = DtRemConceptosSurtidos.Select($"CveVentaDetalle={dr("CveVentaDetalle")}").FirstOrDefault Dim Indice As Integer = DtRemConceptosSurtidos.Rows.IndexOf(rowSurtidosP) 'Si no se ha terminado de surtir agregamos el movimiento If Indice >= 0 Then ' rowSurtidos("Surtido").ToString().ToDouble < rowSurtidos("Cantidad").ToString().ToDouble AndAlso (dr("CantidadDisponible").ToString().ToDouble - rowSurtidos("Surtido").ToString().ToDouble > 0 Or dr("Serie").ToString() <> "") If rowSurtidos("Surtido").ToString().ToDecimal < rowSurtidos("Cantidad").ToString().ToDecimal Then Dim CantidadSurtida As Decimal = If(dr("CantidadDisponible").ToString().ToDecimal < rowSurtidos("Cantidad").ToString().ToDouble, dr("CantidadDisponible").ToString().ToDecimal, rowSurtidos("Cantidad").ToString().ToDecimal) 'SI LA CANTIDAD SURTIDA SUPERA LO REQUERIDO, TOMA SOLO LO NECESARIO PARA COMPLETAR If (rowSurtidos("Surtido").ToString().ToDecimal + CantidadSurtida) > rowSurtidos("Cantidad").ToString().ToDecimal Then CantidadSurtida = (rowSurtidos("Cantidad").ToString().ToDecimal - rowSurtidos("Surtido").ToString().ToDecimal) End If MovDTCuadrados.ImportRow(dr) MovDTCuadrados(MovDTCuadrados.Rows.Count - 1)("Cantidad") = CantidadSurtida DtRemConceptosSurtidos(Indice)("Surtido") = rowSurtidos("Surtido").ToString().ToDecimal + CantidadSurtida End If Else ErrorList.Add("Ocurrió un error al traspasar el inventario de la remisión") Exit For End If Next Return MovDTCuadrados End Function #End Region #Region "E V E N T O - B I T A C O R A" Protected Sub GvEB_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvEB.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex = 0 Then e.Row.Cells(0).Width = Unit.Pixel(200) e.Row.Cells(1).Width = Unit.Pixel(200) e.Row.Cells(2).Width = Unit.Pixel(100) e.Row.Cells(3).Width = Unit.Pixel(500) End If If e.Row.DBCampo("Archivo").ToString() <> "" Then e.Row.FCLinkButton("LinkArchivo").Visible = True e.Row.FCLinkButton("LinkArchivo").CommandArgument = String.Format("OI\{0}", e.Row.DBCampo("Archivo").ToString()) ScriptManager.GetCurrent(Me).RegisterPostBackControl(e.Row.FCLinkButton("LinkArchivo")) 'Registro un evento Postbacktrigger, que recargue toda la pagina para que funcione End If e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left End If End Sub Protected Sub BtnGuardarEventoBitacora_Click(sender As Object, e As EventArgs) Handles BtnGuardarEventoBitacora.Click Dim FileExtension As String = "-1" Dim filesgral As List(Of Archivo) = Anexo.getfiles().Archivos Dim Filename As String = "" For Each fileItem As Archivo In filesgral FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "") Filename = fileItem.filename Next Dim ObjEventos As New ClsOIEventos() If ObjEventos.AddEventoBitacora(TxtEventoDescripcion.Text.Trim, String.Format(".{0}", FileExtension), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then If Filename <> "" Then Filename.FilesMove(String.Format("OI{0}", ObjEventos.CveEvento.ToString()), String.Format("{0}OI", UsuarioActual.Empresa.Ruta), ConcatenarDirectorioBase:=False) End If End If ObjEventos.Dispose() CargaEventoBitacora() UPEventoBitacora.Update() End Sub Private Sub CargaEventoBitacora() If CveVenta <= 0 Then Exit Sub Dim ObjEventoBitacora As New ClsOIEventos() If ObjEventoBitacora.GetAgendaBitacora(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then GvEB.DataSource = ObjEventoBitacora.DtResultados.FiltraParametros("CveTipoEvento IN(6,2,1)") Else GvEB.DataSource = Nothing End If ObjEventoBitacora.Dispose() GvEB.DataBind() End Sub Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs) Dim filePath As String = String.Format("{0}{1}", UsuarioActual.Empresa.Ruta, CType(sender, LinkButton).CommandArgument) Dim Archivo As New System.IO.FileInfo(filePath) HttpContext.Current.Response.Clear() HttpContext.Current.Response.ClearContent() HttpContext.Current.Response.ContentType = "application/octet-stream" HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(filePath)) HttpContext.Current.Response.AddHeader("Content-Length", Archivo.Length.ToString()) HttpContext.Current.Response.TransmitFile(filePath) HttpContext.Current.Response.Flush() HttpContext.Current.Response.End() Archivo = Nothing End Sub #End Region #Region "BTN 'S" Protected Sub LnkActualizarOrdenProduccion_Click(sender As Object, e As EventArgs) If DdlOrdenProduccion.SelectedValue.ToEntero() > 0 Then Dim ObjCGame As New ClsCGame If ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then Alert("La orden de producción fue actualizada con exito.") End If ObjCGame.Dispose() Else Alert("Tiene que seleccionar una orden de producción.", TipoMensaje.MsgAdvertencia) End If End Sub 'BtnRefacturacionConfirmar Private Sub BtnRefacturacionConfirmar_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmar.Click ' DdlMotivoRefactura.SelectedValueExist(1) ' DdlMotivoCancelacion.Enabled = False 'UpRefac.Update() RegistraScript("$('#DivMotivoRefacturacion').modal({ backdrop: 'static', keyboard: false });", "R1") 'CancelarDocumento(True) End Sub Private Sub BtnRefacturacionConfirmarAceptacion_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmarAceptacion.Click 'DdlMotivoCancelacion.SelectedValueExist(1) 'DdlMotivoCancelacion.Enabled = False 'UpRefac.Update() RegistraScript("$('#DivMotivoRefacturacion').modal({ backdrop: 'static', keyboard: false });", "R1") 'CancelarDocumento(True) End Sub Protected Sub BtnDescontabilizar_Click(sender As Object, e As EventArgs) 'Alert("Hola entre", TipoMensaje.MsgError) 'Exit Sub Dim ObjConta As New ClsContabilidad Dim Movimientos As Integer = ObjConta.GetMovimientosPoliza(IdPoliza, UsuarioActual.CveEmpresa) 'Verifica que solo exista 1 compra asociada If Movimientos = 1 Then EliminaPoliza() Else RegistraScript("ConfirmEliminarPolizaMultiple();") End If ObjConta.Dispose() End Sub Private Sub BtnMateriales_Click(sender As Object, e As EventArgs) Handles BtnMateriales.Click Dim OS As New ClsOS Dim DtDetalle As DataTable = Nothing Dim DtDetalleMateriales As DataTable = Nothing DtDetalle = TmpDT.Copy For Each Row As DataRow In DtDetalle.Rows If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString().ToEntero(), CveOS) Then Dim Cons As Integer = TmpDT.Rows.Count + 1 For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows Dim drt As DataRow = TmpDT.NewRow FacturaMateriales = 1 drt("Consec") = Cons drt("CveClasificacion") = dr("CveClasificacion") drt("Clasificacion") = dr("Clasificacion") drt("CvePS") = dr("CvePS") drt("PS") = dr("PS") drt("CodigoPS") = dr("CodigoPS") drt("Cantidad") = dr("Cantidad") drt("CveOSDetalle") = dr("CveOSDetalle") drt("CveSubProyecto") = dr("CveSubProyecto") drt("SubProyecto") = dr("SubProyecto") drt("CveActivoFijo") = -1 TmpDT.Rows.Add(drt) Cons = Cons + 1 Next End If DtDetalleMateriales = OS.DtResultados.FiltraParametros("SeFacturara = 1 ") Next OS.Dispose() GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() UpPS.Update() End Sub Private Sub RegenerarPDF(CveVenta As Integer, CveEmpresa As Integer, CveUsuario As Integer, strURLHOST As String) Try DescargarFactura(CveVenta, CveEmpresa, CveUsuario, Regenerar:=True, strURLHOST:=strURLHOST) Catch ex As Exception OnError("Ocurrió error al regenerar el PDF", ex) End Try End Sub #End Region 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(NowADS).ToString() TrConversionDolares.Visible = True ChkConvertirDolares.Enabled = Not UsuarioActual.TienePermisoProceso(324) Case "2" TxtTipoCambioDlls.Text = "1" 'If UsuarioActual.CveEmpresa.Contiene(13, 83) OrElse ChkEmitirComercioExterior.Checked Then ' TxtTipoCambio.Text = GlobalTipoCambio(NowADS.AddDays(-1)).ToString() 'Else TxtTipoCambio.Text = GlobalTipoCambio(NowADS).ToString() 'End If TrConversionTipoCambio.Visible = True ChkConvertirDoctoPesos.Enabled = Not UsuarioActual.TienePermisoProceso(324) Case Else 'If UsuarioActual.CveEmpresa.Contiene(13, 83) OrElse ChkEmitirComercioExterior.Checked Then ' TxtTipoCambio.Text = GlobalTipoCambio(NowADS.AddDays(-1)).ToString() 'Else TxtTipoCambio.Text = GlobalTipoCambio(NowADS).ToString() 'End If TrConversionTipoCambio.Visible = True End Select If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TxtTipoCambio.Enabled = True TxtTipoCambioDlls.Enabled = True TxtTipoCambio.ReadOnly = False TxtTipoCambioDlls.ReadOnly = False End If UpPS.Update() End Sub #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 End Sub #End Region #Region "IMPUESTOS LOCALES" Private Sub GvImpuestosLocales2_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvImpuestosLocales2.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then 'e.Row.FCTextBox("TxtImpuestoLocalPS").Text = (TxtSubTotal.Text.ToDouble - (TxtSubTotal.Text.ToDouble * (e.Row.DBCampo("Porcentaje").ToString().ToDouble) / 100)).ToString() e.Row.FCTextBox("TxtImpuestoLocalPS").Attributes.Add("onKeyUp", String.Format("FnSuma();")) End If End Sub Private Function RegeneracionPolizas(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ObjBancos As ClsBancos) As Boolean Dim ErrorCancelar As Boolean = False Dim Mensaje As String = "" CreaObjetosVenta() 'If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then ' ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() 'End If 'REMOVEMOS LOS CONCEPTOS DE LA PREPOLIZA ErrorCancelar = Not ObjConta.RemovePrePolizasDetalle(CvePrePoliza, -1, CveVenta, 2) ObjFactura.CveVenta = CveVenta ObjFactura.CvePrePoliza = CvePrePoliza 'VUELVE A GENERAR LAS PREPOLIZAS If Not ErrorCancelar Then ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, 1, ObjBancos, ObjVentas) If Not ErrorCancelar Then ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, 1) Return ErrorCancelar End Function #End Region #Region " DEVOLUCION ALMACEN " Protected Sub LBDevolucionAlmacen_Click(sender As Object, e As EventArgs) Dim SaldoAlmacen As Decimal = 0 Dim ErrorVerificacion As Boolean = False Using ObjInv As New ClsInventarios If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then If ObjInv.DtResultados.Rows.Count > 0 Then TieneAlmacen = True End If Else ErrorVerificacion = True End If End Using If ErrorVerificacion Then Alert("No se pudieron verificar los movimientos de almacen del documento.", TipoMensaje.MsgError) Exit Sub End If If Not TieneAlmacen Then Alert("El documento no tiene movimientos de almacen.", TipoMensaje.MsgAdvertencia) Exit Sub End If Using ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa, VerificaAlmacen:=True) Then If ObjVentas.DtResultados.Rows.Count > 0 Then Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0) Me.DevolucionAlmacen = DbRowVenta("EsDevolucionVenta").ToString().ToEntero() SaldoAlmacen = DbRowVenta("SaldoAlmacen").ToString().ToDecimal() End If End If End Using If DdlTipoComprobante.SelectedValue.ToString() = "Rem" AndAlso SaldoAlmacen = 0 Then Alert("El documento ya fue devuelto.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlTipoComprobante.SelectedValue.ToString() = "Ing" AndAlso SaldoAlmacen = 0 Then Alert("El movimiento ya fue devuelto.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim EstatusDevolucion As Integer = If(Me.DevolucionAlmacen = 0, 1, 0) Dim ObjV As New ClsVentas If ObjV.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then Alert("La solicitud de Devolución de Almacén se guardó correctamente") End If ObjV.Dispose() Me.DevolucionAlmacen = EstatusDevolucion 'InicializaDevolucionAlmacen() 'UpnTools.Update() End Sub #End Region #Region "Metodos Viejos" Private Sub GvPS_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPS.RowCommand If e.CommandName = "Clonar" Then Dim RowNum As Integer = Convert.ToInt32(e.CommandArgument) Dim GvRow As GridViewRow = GvPS.Rows(RowNum) TxtCantidad.Text = GvPS.Rows(RowNum).FCLiteral("LtlCantidad").Text DdlClasificacion.SelectedValue = GvRow.DataKey("CveClasificacion") DdlPS.SelectedValue = GvRow.DataKey("CvePS") DdlPS_SelectedIndexChanged(Nothing, Nothing) DdlUnidadMedida.SelectedValue = GvRow.DataKey("CveUM") TxtObsPS.Text = GvRow.FCLiteral("LtlObsPS").Text 'DdlProyecto.SelectedValue = GvRow.DataKey("CveProyecto") 'DdlProyecto_SelectedIndexChanged(Nothing, Nothing) 'DdlSubProyecto.SelectedValue = GvRow.DataKey("CveSubProyecto") TxtPrecio.Text = GvRow.FCLiteral("LtlPU").Text RegistraScript("Recalcula();") LbAgregar_Click(Nothing, Nothing) Else DdlPS_SelectedIndexChanged(Nothing, Nothing) End If End Sub Protected Sub OrdenarGvPS(ByVal sender As Object, ByVal e As EventArgs) For Each row As GridViewRow In GvPS.Rows TmpDT.Rows(row.RowIndex)("Orden") = row.FCTextBox("TxtOrden").Text.ToEntero() Next Dim resultados = From OrdenDT In TmpDT Order By OrdenDT("Orden").ToString().ToEntero() Select OrdenDT TmpDT = resultados.CopyToDataTable CalculaTotalesVenta() GvPS.DataSource = TmpDT GvPS.DataBind() UpPS.Update() End Sub #End Region #Region "DESCARGAR E IMPRIMIR LISTADO" Public Sub DescargarFormato() Dim Directorio As String = ModExtensiones.DirectorioBaseEmpresas & "Empresas\Grales\Formatos\FormatoVentas.xlsx" Dim Archivo As New IO.FileInfo(Directorio) If Archivo.Exists Then Response.Clear() Response.ClearHeaders() Response.ClearContent() Response.AddHeader("Content-Disposition", "attachment; filename=" + Archivo.Name) Response.AddHeader("Content-Length", Archivo.Length.ToString()) Response.ContentType = "text/plain" Response.Flush() Response.TransmitFile(Archivo.FullName) Response.End() End If End Sub Private Sub CargarArchivo(Ruta As String, FileName As String, Tipo As String, FileUrl As String) Dim dt As New DataTable Dim ErrorArchivo As Boolean = False Dim n As Integer = 0 dt = ReadExcelFile(FileUrl, True) If Not ErrorArchivo Then If Not dt.Columns(0).ColumnName = "Cantidad" Then Alert("El nombre de la primera columna debe ser 'Cantidad'.Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(1).ColumnName = "Código" Then Alert("El nombre de la segunda columna debe ser 'Código'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(2).ColumnName = "Codigo Barras" Then Alert("El nombre de la tecera columna debe ser 'Codigo Barras'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(3).ColumnName = "Producto/Servicio" Then Alert("El nombre de la cuarta columna debe ser 'Producto/Servicio'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(4).ColumnName = "UM" Then Alert("El nombre de la quinta columna debe ser 'U.M'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(5).ColumnName = "Precio Unitario" Then Alert("El nombre de la sexta columna debe ser 'Precio Unitario'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(6).ColumnName = "Proyecto" Then Alert("El nombre de la séptima columna debe ser 'Proyecto'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(7).ColumnName = "Observaciones" Then Alert("El nombre de la octava columna debe ser 'Observaciones'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If If Not dt.Columns(8).ColumnName = "Tiempo Entrega" Then Alert("El nombre de la octava columna debe ser 'Tiempo Entrega'. Favor de corregirlo", TipoMensaje.MsgError) Exit Sub End If dt.TableName = "Datos" Dim DtSubProyecto As DataTable = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa) DtSubProyecto.CaseSensitive = False If Not ErrorArchivo Then NumRow = 1 Dim RowNoEncontrados As String = "" Dim NumAgregados As Integer = 0 For Each Row As DataRow In dt.Rows NumAgregados = NumAgregados + 1 Dim Cantidad As Decimal = Row("Cantidad").ToString().ToDecimal Dim UM As String = Row("UM").ToString() Dim Codigo As String = Row("Código").ToString().Trim.ToUpper Dim CodigoBarras As String = Row("Codigo Barras").ToString().Trim.ToUpper Dim ProductoServicio As String = Row("Producto/Servicio").ToString().Trim.ToUpper Dim PrecioUnitario As Decimal = Row("Precio Unitario").ToString().ToDecimal Dim Proyecto As String = Row("Proyecto").ToString().Trim.ToUpper Dim Observaciones As String = Row("Observaciones").ToString().Trim.ToUpper Dim TiempoEntrega As String = Row("Tiempo Entrega").ToString() Dim CvePS As Integer = 0 Dim CveClasificacion As Integer = 0 Dim CveUM As Integer = 0 Dim CodigoPS As Integer = 0 Dim DrProyecto As DataRow Dim SubProyecto As String = "" Dim CveProyecto As Integer = 0 Dim CveSubProyecto As Integer = 0 NumRow = NumRow + 1 If Proyecto <> "" Then DrProyecto = DtSubProyecto.FiltroPrimero($"(SubProyecto) = '{Proyecto}'") If DrProyecto IsNot Nothing Then CveSubProyecto = DrProyecto("CveSubProyecto").ToString().ToEntero() CveProyecto = DrProyecto("CveProyecto").ToString().ToEntero() SubProyecto = DrProyecto("SubProyecto").ToString() End If Else CveProyecto = -1 CveSubProyecto = -1 End If If Codigo <> "" Then Using ObjPS As New ClsProductosServicios If ObjPS.GetPS(-1, -1, UsuarioActual.CveEmpresa, Codigo:=Codigo) Then If ObjPS.CvePS > 0 Then CvePS = ObjPS.CvePS CveUM = ObjPS.CveUnidadMedida CveClasificacion = ObjPS.CveClasificacion Else RowNoEncontrados = String.Format("{3}    - No se encontró {0} en la fila {1}, columna {2}<\BR>", Codigo, NumRow, "Codigo", RowNoEncontrados) End If Else RowNoEncontrados = String.Format("{3}    - No se encontró {0} en la fila {1}, columna {2}<\BR>(NoBD)", Codigo, NumRow, "Codigo", RowNoEncontrados) End If End Using ElseIf CodigoBarras <> "" Then Using ObjPS As New ClsProductosServicios If ObjPS.GetPS(-1, -1, UsuarioActual.CveEmpresa, CodigoBarras:=CodigoBarras) Then If ObjPS.CvePS > 0 Then CvePS = ObjPS.CvePS CveUM = ObjPS.CveUnidadMedida CveClasificacion = ObjPS.CveClasificacion Else RowNoEncontrados = String.Format("{3}    - No se encontró {0} en la fila {1}, columna {2}<\BR>", Codigo, NumRow, "Codigo", RowNoEncontrados) End If Else RowNoEncontrados = String.Format("{3}    - No se encontró {0} en la fila {1}, columna {2}<\BR>(NoBD)", Codigo, NumRow, "Codigo", RowNoEncontrados) End If End Using ElseIf ProductoServicio <> "" Then Using ObjPS As New ClsProductosServicios If ObjPS.GetPS(-1, -1, UsuarioActual.CveEmpresa, CodigoBarras:=CodigoBarras) Then If ObjPS.CvePS > 0 Then CvePS = ObjPS.CvePS CveUM = ObjPS.CveUnidadMedida CveClasificacion = ObjPS.CveClasificacion Else RowNoEncontrados = String.Format("{3}    - No se encontró {0} en la fila {1}, columna {2}<\BR>", Codigo, NumRow, "Codigo", RowNoEncontrados) End If Else RowNoEncontrados = String.Format("{3}    - No se encontró {0} en la fila {1}, columna {2}<\BR>(NoBD)", Codigo, NumRow, "Codigo", RowNoEncontrados) End If End Using Else RowNoEncontrados &= "<\BR>    - En la fila " & NumRow & " no se especificó código, código de barras ó descripción." End If If CvePS > 0 Then If PrecioUnitario <= 0 Then Dim ObjPrecioSugerido As Modelos.MPrecioSugerido = CalculaPrecioSugerido(CvePS, CveClasificacion) PrecioUnitario = ObjPrecioSugerido.PrecioSugerido End If AgregarProductoServicio(Cantidad, CveUM, UM, -1, "", CvePS, HdnPS.Value, Observaciones, PrecioUnitario, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto, TiempoEntrega:=TiempoEntrega) End If Next CalculaTotalesVenta() If RowNoEncontrados.Length > 0 Then Alert("Los siguientes productos o servicios no se encontraron en la Base de Datos.<\BR>" & RowNoEncontrados, TipoMensaje.MsgAdvertencia) Else Alert("Se cargaron " & NumAgregados & " productos o servicios correctamente.") End If End If End If dt.Dispose() End Sub 'Private dtps As DataTable = Nothing 'Private Function GetPS(Opt As String, Valor As String) As String ' Dim StrReturn As String = String.Empty ' Dim CvePS As Integer = 0 ' If dtps Is Nothing Then dtps = GlobalDTPS(UsuarioActual.CveEmpresa) ' CvePS = dtps.FiltroPrimeroValor("CvePS", Opt & " = '" & Valor & "'").ToString().ToEntero() ' If CvePS > 0 Then ' StrReturn = "True|" & CvePS.ToString() ' Else ' StrReturn = "False|    - No se encontró " & Valor & " en la fila " & NumRow & ", columna " & Opt ' End If ' Return StrReturn 'End Function #End Region #Region " BOTONERA - ACCIONES DE ABAJO " #Region " GENERAR FACTURA " Protected Sub LBFacturarIngreso_Click(sender As Object, e As EventArgs) EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) 'DdlTipoComprobante.SelectedValue = "Ing" EmitirDocumentoNuevo("Ing") End Sub Protected Sub LBFacturarAnticipo_Click(sender As Object, e As EventArgs) EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) 'DdlTipoComprobante.SelectedValue = "Ant" EmitirDocumentoNuevo("Ant") End Sub #End Region #Region " GENERAR REMISION " Private Sub BtnGenerarRemision_Click(sender As Object, e As EventArgs) Handles BtnGenerarRemision.Click If DdlTipoComprobante.SelectedValue.Contiene("Cot", "PA", "Pd2") Then 'CUANDO ES COTIZACION O PEDIDOA O PEDIDO2 SE HARA REMISION EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) 'DdlTipoComprobante.SelectedValue = "Rem" EmitirDocumentoNuevo("Rem") End If End Sub #End Region #Region "GENERAR AUTORIZACIÓN" Protected Sub BtnGeneraAutorizacion_Click(sender As Object, e As EventArgs) If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then EmitirDocumentoNuevo("PA") End If End Sub #End Region #Region " EMITIR DOCUMENTO NUEVO " Private Function ValidaFacturarCotizacion() As Boolean Dim Retorno As Boolean = True If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then Dim Total As Decimal = TxtTotal.Text.ToDecimal() Dim AmortizacionNC As Decimal = 0 Dim TienePagos As Boolean = ((Not (DtPagos Is Nothing OrElse DtPagos.Rows.Count = 0)) AndAlso (DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0)) OrElse AmortizacionNC > 0 If Not PermiteCredito AndAlso Not TienePagos AndAlso Total > 0 Then Alert("Es necesario especificar un pago.", TipoMensaje.MsgAdvertencia) Retorno = False Return Retorno End If If Not PermiteCredito AndAlso TienePagos AndAlso Total > 0 Then Dim TotalPago As Decimal = DtPagos.SUM("Importe") + AmortizacionNC If TotalPago < Total Then Alert("La suma de los pagos debe ser igual al total de la venta.", TipoMensaje.MsgAdvertencia) Retorno = False Return Retorno End If End If End If Return Retorno End Function Private Sub EmitirDocumentoNuevo(TipoDoctoNuevo As String) If (FacturarSucursal AndAlso DdlSucursalCliente.SelectedValue.ToEntero() > 0 AndAlso (Me.ClienteSucursal IsNot Nothing AndAlso String.IsNullOrEmpty(Me.ClienteSucursal.RFC))) Then Alert("La sucursal no tiene asignada un RFC.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim TieneSoloServicios As Boolean = TmpDT.MAX("CveTipoPS") = "1" 'SI ES REMISION Y TIENE PRODUCTOS, DEBE VERIFICAR EL ALMACEN If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso Not TieneSoloServicios AndAlso DdlTipoComprobante.SelectedValue = "Rem" AndAlso TipoDoctoNuevo = "Ing" AndAlso Not TmpDT.MAX("CveTipoPS") = "1" Then Dim SaldoAlmacenExA As Decimal = 0 'Dim SaldoAlmacenUsados As Decimal = 0 Using ObjInventarios As New ClsInventarios 'VERIFICA SI HACE FALTA DEVOLVER PRODUCTOS Y USADOS EN ESPECIFICO If ObjInventarios.GetSaldoVentaDetalleAlmacen(CveVenta, UsuarioActual.CveEmpresa) Then SaldoAlmacenExA = ObjInventarios.DtResultados.SUMD("SaldoAlmacen", $"CveTipoAlmacen = 10") 'SaldoAlmacenUsados = ObjInventarios.DtResultados.SUMD("SaldoAlmacen", $"CveTipoAlmacen = 22") End If End Using 'Si ya se surtió y recibió If SaldoAlmacenExA <= 0 Then BtnsFacturar.Visible = False Alert("No se puede facturar hasta que se haya surtido la remisión", TipoMensaje.MsgAdvertencia) Exit Sub End If End If Dim FolioFijo As Integer = 0 If FolioFijo = 0 Then CargaFolios(FacturarDocumentoNuevo:=True) 'RECARGA FOLIOS CON EL NUEVO TIPO DOCTO EmitirImprimir("Ing") 'MANDA A EMITIR - PROCESO VIEJO End Sub #End Region #End Region #Region "PORCENTAJE IVA" Protected Sub DdlIVA_SelectedIndexChanged(sender As Object, e As EventArgs) If Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0 Then RecalculaIVA() If ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then RecalculaIVA() End If End Sub Private Sub RecalculaIVA() PorcentajeIVA = Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2).ToDecimal For Each Row As DataRow In TmpDT.Rows If PorcentajeIVA > 0 Then Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=Row("CvePS").ToString().ToEntero()).FiltroPrimero("") If DrPS IsNot Nothing Then If DrPS("IVA").ToString().Contiene("-1", "") Then Row("PorcentajeIVA") = PorcentajeIVA Else Row("PorcentajeIVA") = DrPS("IVA") End If Dim PU As Decimal = Row("PU").ToString().ToDecimal().RoundSQL(6) ' el precio unitario puede llevar hasta 6 decimales permitidos Dim TotalCalculableImpuestos As Decimal = (Row("Cantidad").ToString().ToDecimal * PU) - Row("Descuento").ToString().ToDecimal Dim TotalCalculableImpuestosIVA As Decimal = TotalCalculableImpuestos * (1 + Row("PorcentajeIEPS").ToString().ToDecimal) Row("IVA") = Row("PorcentajeIVA").ToString().ToDouble Row("ImporteIVA") = (Row("PorcentajeIVA").ToString().ToDouble * TotalCalculableImpuestosIVA).RoundSQL(NumeroDecimales) End If Else Row("IVA") = 0 Row("PorcentajeIVA") = 0 Row("ImporteIVA") = 0 End If Next CalculaTotalesVenta() End Sub #End Region Protected Sub DdlTipoRetencion_SelectedIndexChanged(sender As Object, e As EventArgs) If CveVenta <= 0 OrElse EsCreaApartirDe Then If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then For Each RowServicio As DataRow In TmpDT.Rows Dim tClienteRetIVA As Decimal = ClienteRetIVA If tClienteRetIVA <= 0 Then If DdlTipoRetencion.SelectedValue.Contiene("1", "2") Then tClienteRetIVA = 0.106667D ElseIf DdlTipoRetencion.SelectedValue.Contiene("3") Then tClienteRetIVA = 0.04D ElseIf DdlTipoRetencion.SelectedValue.Contiene("0") Then tClienteRetIVA = 0.00D End If ViewState("ClienteRetIVA") = tClienteRetIVA End If Dim TotalCalculableImpuestos As Decimal = (RowServicio("Cantidad").ToString().ToDecimal() * RowServicio("PU").ToString().ToDecimal()) - RowServicio("Descuento").ToString().ToDecimal() RowServicio("ImporteRetIVA") = (TotalCalculableImpuestos * ClienteRetIVA).RoundSQL() RowServicio("PorcentajeRetIVA") = ClienteRetIVA Next TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").FormatoNumero(2) Dim PorcentajeRetIVA As Decimal = (TmpDT.MAX("PorcentajeRetIVA").ToDecimal() * 100) LblRetIVA.Text = PorcentajeRetIVA.FormatoNumero(2) If PorcentajeRetIVA > 0 Then TrRetIVA.Style.Add("display", "") UsuarioActual.Empresa.MostrarRetIVA = True DdlTipoRetencion.Visible = True End If GvPS.DataSource = TmpDT GvPS.DataBind() End If End If UpPS.Update() End Sub Private Function DescargarFactura(CveVenta As Integer, CveEmpresa As Integer, CveUsuarioCreo As Integer, Optional GetBytes As Boolean = True, Optional Regenerar As Boolean = False, Optional strURLHOST As String = "") As Byte() If String.IsNullOrEmpty(strURLHOST) Then strURLHOST = String.Format("{0}://{1}:{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port) End If Dim Url As New Uri(String.Format("{0}/Compras/PopUpVerFactura.aspx?P={1}", strURLHOST, Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1®ENERAR={1}", CveVenta, If(Regenerar, "1", "0"))))) Dim File As Byte() = Nothing Try Using httpClient As New HttpClient() httpClient.Timeout = New TimeSpan(0, 2, 0) Using request As New HttpRequestMessage(HttpMethod.Get, Url) request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CveUsuario={2}", CveEmpresa, DateTime.UtcNow.Ticks, CveUsuarioCreo))) 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 Protected Sub btnupEventoBitacora_Click(sender As Object, e As EventArgs) CargaEventoBitacora() End Sub Protected Sub BtnEditar_Click() Handles BtnEditar.Click Dim Opcion As String = BtnEditar.Text If Opcion = "Editar" Then EditarHabilitarCampos() ElseIf Opcion = "Guardar" Then GuardarValoresEditados() End If End Sub Private Sub EditarHabilitarCampos() 'Datos de emisión 'Observaciones TxtObsFact.Enabled = True TxtOrdenCompra.Enabled = True BtnEditar.Text = "Guardar" If UsuarioActual.TienePermisoProceso(357) AndAlso LblSeTimbro.Text = "No" Then DdlUsoCFDI.Enabled = True End If If UsuarioActual.TienePermisoProceso(289) Then If LblSeTimbro.Text = "No" Then DdlUsoCFDI.Enabled = False DdlMetodoPago33.Enabled = False DdlFormaPago33.Enabled = False End If End If UpParametros.Update() UPObservaciones.Update() UpFacturar.Update() UPCondicionesPago.Update() End Sub Private Sub GuardarValoresEditados() Dim TieneError As Boolean = False Dim AplicaUpdateTC As Boolean = False If DdlMoneda.SelectedValue.ToEntero() = 2 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then AplicaUpdateTC = True End If Dim ObjVentas As New ClsVentas() ObjVentas.IniciaTransacSQL() If Not ObjVentas.UpdateObservacionesVenta(Me.CveVenta, UsuarioActual.CveEmpresa, -1, TxtObsFact.Text, -1, "", "", "", TxtOrdenCompra.Text, NowADS.ToString) Then TieneError = True End If If Not TieneError AndAlso AplicaUpdateTC Then If Not ObjVentas.UpdateVentaTC(Me.CveVenta, UsuarioActual.CveEmpresa, TxtTipoCambio.Text.ToDecimal()) Then TieneError = True End If End If If Not TieneError Then ObjVentas.Commit() BtnEditar.Text = "Editar" Dim Liga As String = $"document.location.href=""/Ventas/Ventas.aspx?CveVenta={Me.CveVenta}"";" Alert("La venta se actualizó correctamente", TipoMensaje.MsgInformacion, Liga, TextoConfirmacion:="Aceptar", TextoSegundoBoton:=Nothing, JSBtn2:=Nothing, ShowCloseButton:=False) UpParametros.Update() UPObservaciones.Update() UpFacturar.Update() Else ObjVentas.RollBack() End If ObjVentas.Dispose() 'REGENERAR EL PDF Try Dim CveEmpresaPDF As Integer = UsuarioActual.CveEmpresa Dim CveUsuarioPDF As Integer = UsuarioActual.CveUsuario Dim strURLHOST As String = String.Format("{0}://{1}:{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port) RegenerarPDF(CveVenta, CveEmpresaPDF, CveUsuarioPDF, strURLHOST) Catch ex As Exception OnError("Ocurrió un error al regenerar el PDF", ex) End Try End Sub Private Function DeshabilitarAplicarNotaDeCredito(RFC As String) As Boolean Dim Retorno As Boolean = False If UsuarioActual.CveEmpresa = 119 AndAlso RFC.Contiene("XAXX010101000", "XEXX010101000") AndAlso Not UsuarioActual.CveUsuario.Contiene(1719, 3761) Then UpnTools.Update() Retorno = True End If Return Retorno End Function Private Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMetodoPago33.SelectedIndexChanged CambiaMetodoPago33() End Sub Private Sub CambiaMetodoPago33() CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) End Sub Protected Sub ChkRequiereTecnico_CheckedChanged(sender As Object, e As EventArgs) TdFechaOS2.Visible = ChkRequiereTecnicoModal.Checked UpCliente.Update() End Sub Protected Sub RBLTipoVenta_SelectedIndexChanged(sender As Object, e As EventArgs) If RBLTipoVenta.SelectedValue.ToEntero > 0 Then DvModalTipoVentaPasoTipo.Visible = False DvModalTipoVentaPasoCliente.Visible = True 'DvModalTipoVentaPasoRequiereOS.Visible = False 'DvModalTipoVentaPasoMedicoProcedimiento.Visible = False End If UpDvModalTipoVenta.Update() End Sub Protected Sub DdlClientesWS_selectedindexchange(sender As Object, e As EventArgs) If DdlClientesWS.SelectedValue.ToEntero > 0 Then DvModalTipoVentaPasoCliente.Visible = False DvModalTipoVentaPasoRequiereOS.Visible = True TxtFechaModal.Text = NowADS.ToString("yyyy-MM-dd HH:mm:ss").Replace(" ", "T") 'si es A - Vista o ,Fuera De Linea requiere tecnico If RBLTipoVenta.SelectedValue.ToEntero.Contiene(1, 3) Then ChkRequiereTecnicoModal.Checked = True ChkRequiereTecnicoModal.Enabled = False DvModalRequiereOSFecha.Visible = True End If End If UpDvModalTipoVenta.Update() End Sub Protected Sub LnkDvModalTipoVentaSeuigenteRequiereTecnico_Click(sender As Object, e As EventArgs) If ChkRequiereTecnicoModal.Checked Then If Not IsDate(TxtFechaModal.Text.Replace(",", "")) Then Alert("El campo fecha no es valido.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If DvModalTipoVentaPasoRequiereOS.Visible = False DvModalTipoVentaPasoMedicoProcedimiento.Visible = True UpDvModalTipoVenta.Update() End Sub Protected Sub DdlMedicoModal_SelectedIndexChanged(sender As Object, e As EventArgs) ModalValidaMedicoProcedimiento() End Sub Protected Sub DdlProcedimientoModal_SelectedIndexChanged(sender As Object, e As EventArgs) ModalValidaMedicoProcedimiento() End Sub Protected Sub ModalValidaMedicoProcedimiento() If DdlMedicoModal.SelectedValue.ToEntero > 0 AndAlso DdlProcedimientoModal.SelectedValue.ToEntero > 0 Then LnkDvModalTipoVentaAceptar.Visible = True Else LnkDvModalTipoVentaAceptar.Visible = False End If UpDvModalTipoVenta.Update() End Sub Protected Sub LnkDvModalTipoVentaCancelar_Click(sender As Object, e As EventArgs) LnkDvModalTipoVentaAceptar.Visible = False DvModalTipoVentaPasoTipo.Visible = True DvModalTipoVentaPasoCliente.Visible = False DvModalTipoVentaPasoRequiereOS.Visible = False DvModalTipoVentaPasoMedicoProcedimiento.Visible = False DdlClientesWS.txtText.Value = "" DdlClientesWS.txtValue.Value = "" DdlClientesWS.ddl.SelectedValueExist(-1) DvModalRequiereOSFecha.Visible = False ChkRequiereTecnicoModal.Checked = False RBLTipoVenta.SelectedValue = Nothing DdlMedicoModal.SelectedValueExist(-1) DdlProcedimientoModal.SelectedValueExist(-1) UpDvModalTipoVenta.Update() End Sub Protected Sub LnkDvModalTipoVentaAceptar_Click(sender As Object, e As EventArgs) ChkRequiereTecnico.Checked = ChkRequiereTecnicoModal.Checked TxtFecha.Text = TxtFechaModal.Text If ChkRequiereTecnicoModal.Checked Then TdFechaOS1.Visible = True TdFechaOS2.Visible = True Else TdFechaOS1.Visible = False TdFechaOS2.Visible = False End If DdlMedico.SelectedValueExist(DdlMedicoModal.SelectedValue) DdlProcedimiento.SelectedValueExist(DdlProcedimientoModal.SelectedValue) 'si es A - Vista o ,Fuera De Linea requiere tecnico If RBLTipoVenta.SelectedValue.ToEntero.Contiene(1, 3) Then TdFechaOS1.Visible = True TdFechaOS2.Visible = True ChkRequiereTecnico.Checked = True ChkRequiereTecnico.Enabled = False End If TdRequiereTecnico1.Visible = True TdRequiereTecnico2.Visible = True CargaCliente(DdlClientesWS.SelectedValue.ToEntero) RegistraScript("$('#DvModalTipoVenta').modal('hide');") UpCliente.Update() End Sub Protected Sub ChkRequiereTecnicoModal_CheckedChanged(sender As Object, e As EventArgs) DvModalRequiereOSFecha.Visible = ChkRequiereTecnicoModal.Checked UpDvModalTipoVenta.Update() End Sub End Class