Option Explicit On Option Strict On Imports System.Data Imports System.Diagnostics Imports System.Globalization Imports System.IO Imports System.Net.Http Imports System.Security.Cryptography.X509Certificates Imports System.Xml Imports Extensiones Imports Microsoft.Reporting.WebForms Imports Newtonsoft.Json.Linq Partial Class Ventas Inherits ClsPaginas #Region "Propiedades" Private Const NumeroDecimales As Integer = 2 Dim ColumnaDescuento As Integer = 10 Dim ColumnaPredial As Integer = 11 Dim ColumnaIVA As Integer = 12 Dim ColumnaIEPS As Integer = 13 Dim ColumnaRetIVA As Integer = 14 Dim ColumnaRetISR As Integer = 15 Dim ColumnaEditar As Integer = 17 Dim ColumnaEliminar As Integer = 18 'Factura de ventas Dim DTConceptos As DataTable Private Property Version As String Private Property Fecha As String Private Property SerieXML As String Private Property FolioXML As String Private Property SubTotal As Decimal Private Property Total As Decimal = 0 ' Private Property Descuentos As Decimal = 0 Private Property EmisorRFC As String Private Property ReceptorRFC As String Private Property TrasladoIVA As Decimal = 0 Private Property RetencionIVA As Decimal = 0 Private Property RetencionISR As Decimal = 0 Private Property TrasladoIEPS As Decimal = 0 Private Property TFDUUID As String = "" Private Property Moneda As String = "" Private Property TipoComprobante As String = "" Private Property OtrosImpuestos As Decimal = 0 Private Property TotalRetenciones As Decimal = 0 Private Property SumaTotalRetenciones As Decimal = 0 Private Property TotalTraslados As Decimal = 0 Private Property SumaTotalTraslados As Decimal = 0 Private Property SubTotalConceptos As Decimal = 0 Private Property Redondeo As Decimal = 0 Private Property NumRow As Integer Private Property EsSupervisor As Boolean = False Private Property MandarCorreoSupervisor As Boolean = False Private ReadOnly Property ExFolioFactura As Boolean Get Return CBool(ViewState("ExFolioFactura")) End Get End Property Private Property CveFactura As Integer Get Return ViewState("CveFactura").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveFactura") = value End Set End Property Private Property idCuentaContabilizacion As Integer Get Return ViewState("idCuentaContabilizacion").ToString().ToEntero() End Get Set(value As Integer) ViewState("idCuentaContabilizacion") = value End Set End Property Private Property CuentasContablesInvalidas As StringBuilder Get Return CType(ViewState("CuentasContablesInvalidas"), StringBuilder) End Get Set(value As StringBuilder) ViewState("CuentasContablesInvalidas") = value End Set End Property 'Local Private Property 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 Descuentos) Get Return If(IsNothing(ViewState("ListaDescuentos")), Nothing, CType(ViewState("ListaDescuentos"), List(Of Descuentos))) End Get Set(value As List(Of Descuentos)) 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 ViewState("Mail").ToString() End Get End Property Private ReadOnly Property MailCC As String Get Return ViewState("MailCC").ToString() End Get End Property Private ReadOnly Property CveVenta As Integer Get Return ViewState("CveVenta").ToString().ToEntero() End Get End Property Private 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 CtaContable As String Get Return ViewState("CtaContable").ToString() End Get End Property Private ReadOnly Property IdCtaContClientes As Integer Get Return IfNull(ViewState("IdCtaContClientes"), "").ToString().ToEntero() End Get End Property Private ReadOnly Property IdCtaContMonedaExtranjera As Integer Get Return ViewState("IdCtaContMonedaExtranjera").ToString().ToEntero() End Get End Property Private ReadOnly Property IdCtaContComplementaria As Integer Get Return ViewState("IdCtaContComplementaria").ToString().ToEntero() End Get End Property Private ReadOnly Property IdCtaContAnticipos As Integer Get Return ViewState("IdCtaContAnticipos").ToString().ToEntero() End Get End Property Private ReadOnly Property IdCtaContAnticiposExtranjera As Integer Get Return ViewState("IdCtaContAnticiposExtranjera").ToString().ToEntero() End Get End Property Private ReadOnly Property IdCtaContAnticiposComplementaria As Integer Get Return ViewState("IdCtaContAnticiposComplementaria").ToString().ToEntero() End Get End Property Private ReadOnly Property IdCtaContRetIVA As Integer Get Return ViewState("IdCtaContRetIVA").ToString().ToEntero() End Get End Property Private ReadOnly Property IdCtaContRetISR As Integer Get Return ViewState("IdCtaContRetISR").ToString().ToEntero() End Get End Property Private ReadOnly Property CodCliente As String Get Return ViewState("CodCliente").ToString() End Get End Property Private ReadOnly Property CliNoExt As String Get Return ViewState("CliNoExt").ToString() End Get End Property Private ReadOnly Property CliNoInt As String Get Return ViewState("CliNoInt").ToString() End Get End Property Private ReadOnly Property CliLocalidad As String Get Return ViewState("CliLocalidad").ToString() End Get End Property Private ReadOnly Property CliPais As String Get Return ViewState("CliPais").ToString() End Get End Property Private ReadOnly Property SucCalle As String Get Return ViewState("SucCalle").ToString() End Get End Property Private ReadOnly Property CliCorreoCot As String Get If ViewState("CliCorreoCot") Is Nothing Then Return "" Else Return ViewState("CliCorreoCot").ToString() End If End Get End Property Private ReadOnly Property SucNoExt As String Get Return ViewState("SucNoExt").ToString() End Get End Property Private ReadOnly Property SucNoInt As String Get Return ViewState("SucNoInt").ToString() End Get End Property Private ReadOnly Property SucColonia As String Get Return ViewState("SucColonia").ToString() End Get End Property Private ReadOnly Property SucLocalidad As String Get Return ViewState("SucLocalidad").ToString() End Get End Property Private ReadOnly Property SucMunicipio As String Get Return ViewState("SucMunicipio").ToString() End Get End Property Private ReadOnly Property SucEstado As String Get Return ViewState("SucEstado").ToString() End Get End Property Private ReadOnly Property SucPais As String Get Return ViewState("SucPais").ToString() End Get End Property Private ReadOnly Property SucCP As String Get Return ViewState("SucCP").ToString() End Get End Property Private ReadOnly Property MatCalle As String Get Return ViewState("MatCalle").ToString() End Get End Property Private ReadOnly Property MatNoExt As String Get Return ViewState("MatNoExt").ToString() End Get End Property Private ReadOnly Property MatNoInt As String Get Return ViewState("MatNoInt").ToString() End Get End Property Private ReadOnly Property MatColonia As String Get Return ViewState("MatColonia").ToString() End Get End Property Private ReadOnly Property MatLocalidad As String Get Return ViewState("MatLocalidad").ToString() End Get End Property Private ReadOnly Property MatMunicipio As String Get Return ViewState("MatMunicipio").ToString() End Get End Property Private ReadOnly Property MatEstado As String Get Return ViewState("MatEstado").ToString() End Get End Property Private ReadOnly Property MatPais As String Get Return ViewState("MatPais").ToString() End Get End Property Private ReadOnly Property MatCP As String Get Return ViewState("MatCP").ToString() End Get End Property Private Property ImprimeNombreSucursal As Boolean Get Return CBool(ViewState("ImprimeNombreSucursal")) End Get Set(value As Boolean) ViewState("ImprimeNombreSucursal") = value End Set End Property Private ReadOnly Property AplicaFEMSA As Boolean Get Return CBool(ViewState("AplicaFEMSA")) End Get End Property Private ReadOnly Property AplicaComercioExterior As Boolean Get Return CBool(ViewState("AplicaComercioExterior")) End Get End Property Private ReadOnly Property CveTipoOperacion As Integer Get Return CInt(ViewState("CveTipoOperacion")) End Get End Property Private ReadOnly Property CvePedimento As Integer Get Return CInt(ViewState("CvePedimento")) End Get End Property Private ReadOnly Property CveIncoterm As Integer Get Return CInt(ViewState("CveIncoterm")) End Get End Property Private ReadOnly Property AplicaDetallista As Boolean Get Return CBool(ViewState("AplicaDetallista")) End Get End Property Private ReadOnly Property AplicaFord As Boolean Get Return CBool(ViewState("AplicaFord")) End Get End Property Private ReadOnly Property CveOS As Integer Get Return ViewState("CveOS").ToString().ToEntero() End Get End Property Private ReadOnly Property SaldoVenta As Decimal Get Return If(IsNothing(ViewState("SaldoVenta")), 0, ViewState("SaldoVenta").ToString().ToDecimal) End Get End Property Private Property CvePSAmortizacion As Integer Get Return ViewState("CvePSAmortizacion").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePSAmortizacion") = value End Set End Property 'Inventarios Private Property DtInv As DataTable Get Return CType(ViewState("DtInv"), DataTable) End Get Set(value As DataTable) ViewState("DtInv") = value End Set End Property Private Property CvePrePoliza As Integer Get Return ViewState("CvePrePoliza").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePrePoliza") = value End Set End Property Private ReadOnly Property SeGuardoPrePoliza As Boolean Get Return CBool(ViewState("SeGuardoPrePoliza")) End Get End Property Private Property CveVentaFacturada As Integer Get Return ViewState("CveVentaFacturada").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveVentaFacturada") = value End Set End Property Private ReadOnly Property AplicarVentaFacturada As Boolean Get Return CBool(ViewState("AplicarVentaFacturada")) End Get End Property 'Estimaciones Private Property CveContrato As Integer Get Return ViewState("CveContrato").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveContrato") = value End Set End Property Private Property CvePedido As Integer Get Return ViewState("CvePedido").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePedido") = value End Set End Property Private Property CvePedido2 As Integer Get Return ViewState("CvePedido2").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePedido2") = value End Set End Property Private Property TipoContrato As Integer Get Return ViewState("TipoContrato").ToString().ToEntero() End Get Set(value As Integer) ViewState("TipoContrato") = value End Set End Property Private Property Opcion As String Get Return ViewState("Opcion").ToString() End Get Set(value As String) ViewState("Opcion") = value End Set End Property Private Property CorreoNotificacionPedDev As String Get Return If(IsNothing(ViewState("CorreoNotificacionDevPed")), "", ViewState("CorreoNotificacionDevPed").ToString()) End Get Set(value As String) ViewState("CorreoNotificacionDevPed") = value End Set End Property 'Presupuesto Private Property CvePresupuesto As Integer Get Return ViewState("CvePresupuesto").ToString().ToEntero() End Get Set(value As Integer) ViewState("CvePresupuesto") = value End Set End Property Private Property TotalOtrosConceptos As Decimal Get Return ViewState("TotalOtrosConceptos").ToString().ToDecimal End Get Set(value As Decimal) ViewState("TotalOtrosConceptos") = value End Set End Property Private Property TipoCambioFactura As Decimal Get Return ViewState("TipoCambioFactura").ToString().ToDecimal End Get Set(value As Decimal) ViewState("TipoCambioFactura") = value End Set End Property Private Property DtPagos As DataTable Get Return CType(ViewState("DtPagos"), DataTable) End Get Set(value As DataTable) ViewState("DtPagos") = value End Set End Property Private Property DevolucionAlmacen As Integer Get Return ViewState("DevolucionAlmacen").ToString().ToEntero() End Get Set(value As Integer) ViewState("DevolucionAlmacen") = value End Set End Property Private 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 MAnticipoRelacionado) Get Return If(IsNothing(ViewState("ListaAnticiposAplicados")), Nothing, CType(ViewState("ListaAnticiposAplicados"), List(Of MAnticipoRelacionado))) End Get Set(value As List(Of 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 CveEmpresaCRM As Integer Get Return ViewState("CveEmpresaCRM").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveEmpresaCRM") = value End Set End Property Private Property CveAcercamientoCRM As Integer Get Return ViewState("CveAcercamientoCRM").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveAcercamientoCRM") = value End Set End Property Private Property DtPedidos2 As DataTable Get Return CType(ViewState("DtPedidos2"), DataTable) End Get Set(value As DataTable) ViewState("DtPedidos2") = value End Set End Property Private Property DtPedidos2PS As DataTable Get Return CType(ViewState("DtPedidos2PS"), DataTable) End Get Set(value As DataTable) ViewState("DtPedidos2PS") = value End Set End Property Private Property CveEstatus As Integer Get Return ViewState("CveEstatus").ToString().ToEntero() End Get Set(value As Integer) ViewState("CveEstatus") = value End Set End Property Private Property 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 VentaSaldoAlmacen As Decimal Get Return ViewState("VentaSaldoAlmacen").ToString().ToDecimal End Get Set(value As Decimal) ViewState("VentaSaldoAlmacen") = value End Set End Property Private Property VentaSaldoAlmacenNC As Decimal Get Return IfNull(ViewState("VentaSaldoAlmacenNC"), 0, ViewState("VentaSaldoAlmacenNC").ToString().ToDecimal()).ToString().ToDecimal() End Get Set(value As Decimal) ViewState("VentaSaldoAlmacenNC") = 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 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("ImporteLineaAdicional"), "0", ViewState("ImporteLineaAdicional"))).ToString().ToDecimal() End Get Set(value As Decimal) ViewState("ImporteLineaAdicional") = value End Set End Property Private Property CveClasificacionLineaAdicional As Integer Get Return IfNull(ViewState("CveClasificacionLineaAdicional"), "-1", ViewState("CveClasificacionLineaAdicional")).ToString().ToEntero() End Get Set(value As Integer) ViewState("CveClasificacionLineaAdicional") = 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 #End Region '#Region "AuxiliarConta" ' Property CvePrePolizaNegativa As Integer ' Get ' If ViewState("CvePrePolizaNegativa") Is Nothing Then ' Return -1 ' Else ' Return ViewState("CvePrePolizaNegativa").ToString.ToEntero ' End If ' End Get ' Set(value As Integer) ' ViewState("CvePrePolizaNegativa") = value ' End Set ' End Property ' Private Property DTDatos As DataTable ' Get ' Return CType(ViewState("DTDatos"), DataTable) ' End Get ' Set(value As DataTable) ' ViewState("DTDatos") = value ' End Set ' End Property '#End Region #Region " A C U M U L A D O R E S" Private Property ClienteEsDistribuidor As Boolean Get If ViewState("ClienteEsDistribuidor") Is Nothing Then Return False Else Return Boolean.Parse(ViewState("ClienteEsDistribuidor").ToString()) End If End Get Set(value As Boolean) ViewState("ClienteEsDistribuidor") = value End Set End Property #End Region Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not IsPostBack Then If IfNull(Request("Opcionx"), "").ToString = "Saldar" And UsuarioActual.CveUsuario = 100 Then TxtFechaSaldarVenta.Text = "2021/12/31" SaldarVenta() Exit Sub End If 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 Me.CveVendedorVenta = -1 Me.CveVendedorCliente = -1 Me.CveVendedorClienteSucursal = -1 Me.CveVendedorContrato = -1 Me.CveVendedorEmpresaCRM = -1 Me.EsGarantia = False idCuentaContabilizacion = 1 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 Descuentos) 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 If UsuarioActual.CveRol = 1 OrElse UsuarioActual.CveEmpresa.Contiene(13, 83) Then DivCartaPorte.Visible = True End If 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 txtFechaICot.Text = Now.AddMonths(-3).ToShortDateString TxtFechaIRem.Text = Now.AddMonths(-3).ToShortDateString TxtFechaIPed.Text = Now.AddMonths(-3).ToShortDateString TxtFechaIOC.Text = Now.AddMonths(-3).ToShortDateString txtFechaFCot.Text = Now.ToShortDateString TxtFechaFRem.Text = Now.ToShortDateString TxtFechaFPedido.Text = Now.ToShortDateString TxtFechaFOC.Text = Now.ToShortDateString If UsuarioActual.TienePermisoProceso(177) Then DdlTipoComprobante.Items.Insert(4, New ListItem("Pedido de Contrato", "Ped")) End If TrSinExistencia.Visible = UsuarioActual.TienePermisoProceso(276) If UsuarioActual.Empresa.Funcionalidad(595) = "1" Then ImgDescPU.Visible = False ImgDescConcepto.Visible = False DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Autorización", "PA")) 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")) DivBtnRemNC.Visible = True DivTxtRemNC.Visible = True LtlTitleImportesRem.Visible = True End If If UsuarioActual.Empresa.Funcionalidad(528) = "1" Then 'FUNCIONALIDAD. DE REGISTRO DE CUENTA PREDIAL. GvPS.Columns(ColumnaPredial).Visible = True thPredial1.Visible = True thPredial2.Visible = True End If If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then ' PARA BUSCAR FOLIO DE OC, YA FACTURADA EN EL CAMPO ORDEN DE COMPRA TxtOrdenCompra.Attributes.Add("onblur", "BuscarOCRegistrada();") trCorreoNotif1.Visible = True trCorreoNotif2.Visible = True End If If UsuarioActual.Empresa.Funcionalidad(561).ToString() = "1" Then thPoliza.Visible = True thPoliza2.Visible = True End If If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso UsuarioActual.CveUsuario = 100 Then DivPenalizacion.Visible = True End If If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then LnkSolicitarCredito.Visible = True End If DdlSATPS.setEsWebService(True) : DdlSATPS.Attributes.Add("data-metodo", "getpssat") DivPSSAT.Visible = True SetValues() CvePresupuesto = 0 'MODALIDADES If Request("Op") IsNot Nothing AndAlso Request("Op").ToString() <> "" Then Opcion = Request("Op").ToString() LblTitulo.Text = "Registro de Cotizaciones" TrTipo.Visible = False TabAlmacen.Visible = False TabDetalleVentas.Visible = False TabVentaAF.Visible = False TabE.Visible = False TabComplementos.Visible = False divcondicionespago.Visible = UsuarioActual.Empresa.CvePlataforma = 1 'SI ES PLATAFORMA ERP SIEMPRE VSIBLE ESTE PORLET ImgAntiPend.Visible = False TrObsAlmacen.Visible = False TrTxtObsAlmacen.Visible = False TrPedido.Visible = False TrOC.Visible = False DdlTipoComprobante.SelectedValue = "Op" Else Opcion = "Ing" DdlTipoComprobante.SelectedValue = "Ing" End If 'DdlTipoComprobante.Attributes.Add("onChange", "ActivaReferencia(this)") TxtFecha.Text = Now.ToShortDateString() TxtFechaEjecucion.Text = Now.ToShortDateString LblUsuario.Text = UsuarioActual.Usuario LblFechaRegistro.Text = Now.ToShortDateString() TxtPrecioPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();") TxtCantidadPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();") ImgDescPU.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '0'; $get('LblPrecio1').style.display = ''; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") ImgDescConcepto.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '1'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = ''; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") ImgDescTotal.Visible = False ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") ImgAntiPend.Attributes.Add("onclick", "$get('HdnTipoDescuento').value = '3'; MuestraAnticipos();") ImgOtrosConceptos.Attributes.Add("onclick", "javascript:$('#ModalOtrosConceptos').modal();") 'LkbAgregarComplementos.Attributes.Add("onclick", "javascript:$('#ModalComplementos').modal();") 'ImgCerrar.Attributes.Add("OnClick", "$('#DivAnticipos').hide();") 'LkbEstadodeCaja.Attributes.Add("OnClick", "MuestraEstadoCaja();") 'LkbIngreso.Attributes.Add("OnClick", "MuestraIngresoEgreso(1);") 'LkbRetiro.Attributes.Add("OnClick", "MuestraIngresoEgreso(0);") TxtImporteEfectivo.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteCredito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteDebito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteCheque.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteTransferencia.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteOtrosContado.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtEfectivoEnCaja.Attributes.Add("onKeyUp", "CalculaDiferencia();") TxtEfectivoCajaBloqueo.Attributes.Add("onKeyUp", "CalculaDiferenciaBloqueo();") 'ImgCerrarTerminoCorte.Attributes.Add("OnClick", "$('#DivTerminarCorte').hide();") 'ImgCerrarIE.Attributes.Add("OnClick", "$('#DivIngresoEgreso').hide();")DdlTipoComprobante 'ImgCerrarEstadoCaja.Attributes.Add("OnClick", "$('#DivEstadoCaja').hide();") TabAlmacen.Enabled = UsuarioActual.Empresa.UsaInventarios TxtPorDescP.Attributes.Add("onKeyUp", "CalculaDescuento();") TxtDescP.Attributes.Add("onKeyUp", "CalculaDescuento();") TxtCantidadPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')") TxtObsPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')") TxtPrecioPyME.Attributes.Add("onkeypress", "CallServerMethod(event)") CreaDTmpC() CreaDTmpF() CreaDTDocumentosRelacionados() CargaDdlSubProyectos() 'CargaProyecto() CargaSucursales() CargaClasificaciones() CargaPS(-1, DdlPS) CargaPS(-1, DdlPSMercancia) CargaPS(-1, DdlPSFlete) 'CargaPSRemision(-1, DdlPSRemision) CargaPSPyME(-1, DdlPSPyME) CreaDTVentas() CargaMetodosPago() 'CargaFormaPago(-1) CargaUsoCFDI() CargaMotivosCancelacion() CargaTiposRelacion() CargaMonedas() CargaVendedores() CargarAlmacenes() CargaFormaEntrega() CargaCuentasTerminal() CargaDdlNCPS() CargarCamiones() '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, Now.Year, True, UsuarioActual.CveEmpresa) Then DdlFuenteRecaudacion.DataSource = AC.DtResultados() DTPresupuestoIngresos = AC.DtResultados() ViewState("DTFuenteRecaudacion") = AC.DtResultados() 'GenerarPolizasAC() End If AC.Dispose() 'columna de Fuente de recaudacion GvPS.Columns(21).Visible = True nomostrar.Visible = True nomostrar2.Visible = True 'GvPS.Width = 1250 DdlFuenteRecaudacion.DataBind() Else TFuenteRecaudacion.Visible = False End If 'Carga cliente If Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero() > 0 AndAlso Request("CveFactura") Is Nothing Then ViewState("CveCliente") = Request("CveCliente") HdnCveCliente.Value = Request("CveCliente") CargaCliente(CveCliente) VerificarContrato(True) ElseIf Request("CveFactura") IsNot Nothing AndAlso IsNumeric(Request("CveFactura")) AndAlso Request("CveFactura").ToEntero() > 0 AndAlso Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero() > 0 Then ViewState("CveCliente") = Request("CveCliente") ViewState("CveFactura") = Request("CveFactura").ToEntero() Dim RFC As String = CargaFactura(CveFactura) CargaCliente(CveCliente) Else ViewState("CveCliente") = -1 HdnCveCliente.Value = "-1" End If 'Carga empresa CRM If Request("CveEmpresaCRM") IsNot Nothing AndAlso IsNumeric(Request("CveEmpresaCRM")) AndAlso Request("CveEmpresaCRM").ToEntero() > 0 Then ViewState("CveEmpresaCRM") = Request("CveEmpresaCRM") CargaEmpresaCRM(CveEmpresaCRM) Else ViewState("CveEmpresaCRM") = -1 End If If Request("CveAcercamientoCRM") IsNot Nothing AndAlso IsNumeric(Request("CveAcercamientoCRM")) AndAlso Request("CveAcercamientoCRM").ToEntero() > 0 Then ViewState("CveAcercamientoCRM") = Request("CveAcercamientoCRM") Else ViewState("CveAcercamientoCRM") = -1 End If 'mensaje de confirmación al guardar BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)},{If(HdnTieneAnticipos.Value = "1", 1, 0)});" BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") BtnEmitirImprimir.Attributes.Add("data-popout", "true") BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") BtnEmitirImprimir.Attributes.Add("data-html", "true") If UsuarioActual.CveEmpresa.Contiene(126) Then ' cuando la empresa se relaciona a ua orden de producción, Citrus Game TrOP.Visible = True CargaOrdenProduccion() End If 'MUESTRA EL MODAL PARA PODER RELACIONAR FACTURAS If UsuarioActual.TienePermisoProceso(321) Then HlFacturasRelaciondas.Visible = True 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)) 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)) 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 'Carga Venta If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero() > 0 Then ViewState("CveVenta") = Request("CveVenta") If CargaVenta() Then If UsuarioActual.TienePermisoProceso(321) Then CargaRelacionadasPendientes() End If 'DdlSucursal.Enabled = False DdlSubProyectoDatos.Enabled = False BtnEmitirImprimir.Visible = False BtnCrearApartirDe.Visible = True If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then BtnCrearApartirDe.Visible = False End If If UsuarioActual.TienePermisoProceso(302) AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then BtnEditar.Visible = True 'DdlEstatus.Enabled = True DivFechaAnticipoCliente.Visible = True TxtFechaAnticipoCliente.Text = Now.ToShortDateString ImgAddObs.Visible = True CargaEventoBitacora() ConfiguraTipoDocto() TrFolioFiscal.Visible = True ' Si esta cancelado el compromiso/Pedido no se puede editar el estatus 'If DdlEstatus.SelectedValue.Contiene({"9", "14", "17"}) Then ' DdlEstatus.Enabled = False 'End If 'CargaDetalle de Almacen If Not LblAlertRefacInv.Visible Then If CveVentaPadre > 0 Then InventarioMov(CveVentaPadre) Else InventarioMov() End If End If 'PERMISO PARA CANCELAR PEDIDO If GvInv.Rows.Count = 0 Then If DdlTipoComprobante.SelectedValue.Contiene("Ped") And Not CveEstatus = 14 Then If UsuarioActual.TienePermisoProceso(186) Then LBCancelarPedido.Visible = True End If End If End If 'CARGA GV DE COMERCIO EXTERIOR SI NO ESTA TIMBRADA If LblSeTimbro.Text = "No" Then CargaGvComercioExterior() End If 'HABILITA IMPRESION DE FORMATO CICOVISA If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then LnkImprimirFormatoCicovisa.Visible = True End If 'HABILITA IMPRESION DE FORMATO TELCEL If UsuarioActual.CveEmpresa = 72 And CveCliente = 70869 And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then LnkImprimirFormatoTelcel.Visible = True End If 'If UsuarioActual.TienePermisoProceso(269) AndAlso Not DevolucionAlmacen = 2 Then ' Dim ObjInventario As New ClsInventarios ' If ObjInventario.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then ' If ObjInventario.DtResultados.Rows.Count > 0 Then ' DivDevAlm.Visible = True ' End If ' End If ' ObjInventario.Dispose() 'End If If DdlTipoComprobante.SelectedValue = "Ing" Then CargaVentaCortePorte(Me.CveVenta) End If End If Else If Request("CveOS") IsNot Nothing AndAlso IsNumeric(Request("CveOS")) AndAlso Request("CveOS").ToEntero() > 0 Then ViewState("CveOS") = Request("CveOS") CargaOS(CveOS) Else 'Modalidad Devoluciones y Refacturacion If Request("CveDevolucion") IsNot Nothing AndAlso IsNumeric(Request("CveDevolucion")) AndAlso Request("CveDevolucion").ToEntero() > 0 Then ViewState("CveDevolucion") = Request("CveDevolucion") ViewState("CveVenta") = Request("CveDevolucion") ViewState("NuevaFactura") = Request("NuevaFactura") trNCFactura.Visible = True DdlNCFactura.DataSource = Nothing DdlNCFactura.DataBind() CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString().ToEntero()) DdlNCFactura.SelectedValueExist(CveDevolucion) If NuevaFactura = 0 Then LbAgregar.Visible = False If DdlTipoComprobante.SelectedValue = "Ing" Then DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) DdlTipoComprobante.SelectedValue = "Dev" ElseIf DdlTipoComprobante.SelectedValue = "Ant" Then DdlTipoComprobante.SelectedValueExist("Egs") End If DdlTipoComprobante.Enabled = False CargaFolios() DdlUsoCFDI.Enabled = True DdlUsoCFDI.SelectedValueExist("2") DdlMetodoPago33.Enabled = True DdlMetodoPago33.SelectedValueExist("1") DdlFormaPago33.Enabled = True DdlFormaPago33.SelectedValueExist("20") End If If NuevaFactura = 1 Then TrTipoRelacion.Visible = True DdlTiposRelacion.SelectedValueExist("4") Dim ObjInv As New ClsInventarios If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then If ObjInv.DtResultados.Rows.Count > 0 Then TieneAlmacen = True End If End If ObjInv.Dispose() End If 'regenrea el tipo de cambio CargaNuevaFactura(Nothing) CambiaMoneda() 'NOTA DE CREDITO If NuevaFactura = 2 Then DdlTipoComprobante.Items.Insert(0, New ListItem("Nota de Crédito", "Egs")) DdlTipoComprobante.SelectedValue = "Egs" DdlTipoComprobante.Enabled = False CargaFolios() DdlUsoCFDI.Enabled = True DdlUsoCFDI.SelectedValueExist("2") DdlMetodoPago33.Enabled = True DdlMetodoPago33.SelectedValueExist("1") DdlFormaPago33.Enabled = True DdlFormaPago33.SelectedValueExist("20") TrTipoRelacion.Visible = True DdlTiposRelacion.SelectedValueExist("1") End If End If 'ENTREGA POR ADELANTADO If DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ped", "PeC") Then If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then RequiereAlmacenDestino = True If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then TrAlmacenAsignado.Visible = True TrAlmacenOrigen.Visible = True End If Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero() If CveAlmacenDestino > 0 Then DdlAlmacenAsignado.Items.Clear() DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} And CveTipoAlmacen In (4,10)") DdlAlmacenAsignado.DataBind() DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString())) DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString() Else DdlAlmacenAsignado.Items.Clear() DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} AND CveTipoAlmacen IN (10)") DdlAlmacenAsignado.DataBind() End If UpParametros.Update() Else RequiereAlmacenDestino = False TrAlmacenAsignado.Visible = False TrAlmacenOrigen.Visible = False End If 'ENVIO DE FACTURA ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True End If 'Modalidad Contrato If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero() > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").Contiene("0", "1") Then If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then TrAlmacenAsignado.Visible = True TrAlmacenOrigen.Visible = True End If UPCondicionesPago.Visible = False RequiereAlmacenDestino = True CveContrato = Request("CveContrato").ToEntero() TipoContrato = Request("Tipo").ToEntero() 'DESACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto disabled") TxtCodigo.ReadOnly = True CargarContratoUrl() UpParametros.Update() End If 'Modalidad CveCicloComercial If Request("CveCicloComercial") IsNot Nothing AndAlso IsNumeric(Request("CveCicloComercial")) AndAlso Request("CveCicloComercial").ToEntero() > 0 Then ViewState("CveCicloComercial") = Request("CveCicloComercial").ToEntero() CargaCicloComercialURL() UpParametros.Update() End If 'Modalidad Devolucion Pedido **REVISAR SI SE USA If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero() > 0 AndAlso Request("CvePedido") IsNot Nothing AndAlso IsNumeric(Request("CvePedido")) AndAlso Request("CvePedido").ToEntero() > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").ToEntero() = 2 Then CveContrato = Request("CveContrato").ToEntero() CvePedido = Request("CvePedido").ToEntero() TipoContrato = Request("Tipo").ToEntero() ''REQUIERE DEVOLUCION 'DdlDevolucionAlmacen.SelectedValue = "1" 'DdlDevolucionAlmacen.Enabled = False 'UpInvDev.Update() CargarPedidoUrl() End If 'MODALIDAD DEVOLUCION PEDIDO NUEVO If Request("DevPed") IsNot Nothing AndAlso IsNumeric(Request("DevPed")) AndAlso Request("DevPed").ToEntero() > 0 AndAlso Request("MovInv") IsNot Nothing AndAlso IsNumeric(Request("MovInv")) AndAlso Request("MovInv").ToEntero() > 0 Then ViewState("CveVenta") = Request("DevPed") ViewState("MovInv") = Request("MovInv") ViewState("CveMovimientoDetalle") = IfNull(Request("CveMovimientoDetalle"), "-1").ToString().ToEntero() DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe")) DdlTipoComprobante.SelectedValue = "DPe" DdlTipoComprobante.Enabled = False CargaFacturaDevolucionPedido() CargaFolios() If CveContrato > 0 Then CargaNotificacionContrato() End If End If 'Modalidad Cotizacion If Opcion = "Cot" Then DdlTipoComprobante.SelectedValueExist(Opcion) DdlTipoComprobante.Enabled = False DdlTipoComprobante_SelectedIndexChanged(sender, Nothing) 'Carga CvePresupuesto If Request("CvePresupuesto") IsNot Nothing AndAlso IsNumeric(Request("CvePresupuesto")) AndAlso Request("CvePresupuesto").ToEntero() > 0 Then CvePresupuesto = Request("CvePresupuesto").ToEntero() 'DdlEstatus.Enabled = False End If If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then LnkAgregarCliente.Visible = True ChkEnviarFactura.Checked = False ChkEnviarFactura.Enabled = False End If End If CargaEstatusFactura(Opcion) If Opcion = "Ing" Then ObtenerFechaVencimientoCER() 'DdlEstatus.Enabled = False If UsuarioActual.Empresa.TipoFacturacion = "CBB" Then 'DdlEstatus.SelectedValue = "3" CveEstatus = 3 ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then 'DdlEstatus.SelectedValue = "2" CveEstatus = 2 End If End If End If End If 'CARGA PARA FACTURAR ViewState("CveRemision") = IfNull(Request("CveRemision").ToEntero(), 0) ViewState("CveCotizacion") = IfNull(Request("CveCotizacion").ToEntero(), 0) 'If ViewState("CveCotizacion").ToString().ToEntero() > 0 Then ' EsCreaApartirDe = True 'End If If ViewState("CveRemision").ToString().ToEntero() > 0 Or ViewState("CveCotizacion").ToString().ToEntero() > 0 Then 'ViewState("CveRemision") = Request("CveRemision") 'Dim CveRemision As Integer = ViewState("CveRemision").ToString().ToEntero() CargaVenta() 'DdlSucursal.Enabled = False BtnCrearApartirDe.Visible = True If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then BtnCrearApartirDe.Visible = False End If 'DdlEstatus.Enabled = True ImgAddObs.Visible = True CargaEventoBitacora() DdlTipoComprobante.Enabled = False DdlTipoComprobante.SelectedValue = "Ing" CargaEstatusFactura() 'DdlEstatus.SelectedValueExist("2") ConfiguraTipoDocto() BtnEmitirImprimir.Text = "Facturar" BtnEmitirImprimir.Visible = True UpnTools.Update() TxtFecha.Text = Now.ToShortDateString '' Si esta cancelado el compromiso no se puede editar el estatus 'If DdlEstatus.SelectedValue = "9" Then ' DdlEstatus.Enabled = False 'End If 'CargaDetalle de Almacen InventarioMov() If ViewState("CveCotizacion").ToString().ToEntero() > 0 Then CargaCotizaciones() If DtCotizaciones IsNot Nothing Then For Each Row As DataRow In DtCotizaciones.Select($"CveVenta={ViewState("CveCotizacion").ToString().ToEntero()}") Row("Aplicado") = True Next End If CargarCotizacionesAFacturar() End If End If If Not ExFolioFactura Then SetPermisos() If CveVenta < 1 Then CargaFolios() 'SELECCIONA VENDEDOR DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE 'If UsuarioActual.CveVendedor > 0 Then ' If CveVenta = -1 AndAlso Not DdlVendedor.SelectedValue.ToEntero() > 0 Then DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString()) ' If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then ' DdlVendedor.Enabled = False ' End If ' 'multiples vendedores visible ' If UsuarioActual.TienePermisoProceso(153) Then ' DdlVendedor.Enabled = True ' End If 'End If If UsuarioActual.Empresa.Funcionalidad(301).ToEntero() > 0 Then TxtFecha.Enabled = False ImgFecha.Visible = False End If CargarCodigo() InicializaImprimirNew() 'RegistraScript("FnSuma()") TxtSubTotal.Attributes.Add("onKeyUp", "FnSuma()") TxtIVA.Attributes.Add("onKeyUp", "FnSuma()") TxtIEPS.Attributes.Add("onKeyUp", "FnSuma()") TxtRetIVA.Attributes.Add("onKeyUp", "FnSuma()") TxtRetISR.Attributes.Add("onKeyUp", "FnSuma()") 'Permitir Edicion de Iva If UsuarioActual.Empresa.Funcionalidad(509) = "1" Then TxtIVA.Enabled = True 'TxtTotal.Enabled = True RegistraScript("SetDisabledTxtTotal(false);") TxtSubTotal.Enabled = True TxtSubTotal2.Enabled = True End If 'Cortes de Caja If UsuarioActual.TienePermisoProceso(160) Then CargaCorteCaja() End If '********************************** 'Complementos de Timbrado Dim ObjVenta As New ClsVentas If ObjVenta.GetVentaComplementos() Then RblComplementos.DataSource = ObjVenta.DtResultados RblComplementos.DataBind() UpComplementos.Update() End If ObjVenta.Dispose() CargaFormatoSucursal() InicializaDevolucionAlmacen() CargaOtrosConceptos() CargaFacturaOC() 'SELECCIONA SUCURSAL DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE If Not (CveCliente > 0 Or CveVenta > 0) Then DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto) DdlSubProyectoEjecucion.SelectedValueExist(UsuarioActual.CveSubProyecto) DdlSubProyectoCobranza.SelectedValueExist(UsuarioActual.CveSubProyecto) If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.Enabled = False End If CambiaSucursal() UpParametros.Update() UpDetalle.Update() End If 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE EnviarCorreoCliente = True If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then EnviarCorreoCliente = False ChkEnviarFactura.Enabled = False End If If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = False LblEnviarMail.Visible = False Else If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then 'ENVIO DE FACTURA ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True Else ChkEnviarFactura.Checked = EnviarCorreoCliente ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True End If End If CargaFletes() CargarCentrosDeCosto(DdlProyecto, DdlSubProyecto, LblProyectoHeader, LblSubProyecto, AplicaTodos:="") DdlSubProyecto.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) CargarCentrosDeCosto(DdlProyectoPyME, DdlSubProyectoPyME, LblProyectoPyME, LblSubProyectoPyME, AplicaTodos:="") DdlProyectoPyME.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) BrSubProyecto.Visible = DdlProyecto.Visible divProyectoPyME.Visible = DdlProyecto.Visible 'MOSTRAR LA OPCION DE AGREGAR PS EN BDH If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso CveVenta <= 0 Then ImgOtrosConceptos.Visible = False TrFormaEntrega.Visible = False TabDetalleVentas.Visible = False 'TabE.Visible = False LnkOCs.Visible = False GvPS.Columns(8).Visible = False TrEdit.Visible = True ThProyecto.Visible = False For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = False Gvr.FCLinkButton("imgEPyME").Visible = True Next LnkAddVenta.Visible = True divproyectos.Visible = False DivAddClasificacionPyME.Visible = False DivAddUMPyME.Visible = False End If If UsuarioActual.Empresa.CvePlataforma = 2 Then ImgOtrosConceptos.Visible = False TrFormaEntrega.Visible = False TabDetalleVentas.Visible = False TabE.Visible = False LnkOCs.Visible = False GvPS.Columns(8).Visible = False TrEdit.Visible = False ThProyecto.Visible = False For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = False Gvr.FCLinkButton("imgEPyME").Visible = True Next LnkAddVenta.Visible = True divproyectos.Visible = False DivAddClasificacionPyME.Visible = False DivAddUMPyME.Visible = False End If TabVentaAF.Visible = False 'CARGA VALORES INICIALES PARA AGREGAR PS DESDE MODAL CargaMetodosPSModal() 'CARGA VALORES DE ORDEN DE PRODUCCION Dim CveOrdenProduccion = IfNull(Request("CveOrdenProduccion"), "-1").ToString().ToEntero() If CveOrdenProduccion > 0 And Not CveVenta > 0 Then DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion) If DdlOrdenProduccion.SelectedValue.ToEntero() > 0 Then DdlTipoComprobante.SelectedValue = "Rem" DdlMoneda.SelectedValue = "2" Dim ObjCGame As New ClsCGame If ObjCGame.GetAvance(DdlOrdenProduccion.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) Then For Each dt As DataRow In ObjCGame.DtResultados.Rows If dt("Avance").ToString().ToEntero() > 0 Then AgregarProductoServicio(dt("Avance").ToString().ToDecimal, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString(), dt("PU").ToString().ToDecimal, 0, DdlProyecto.SelectedValue.ToEntero(), DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero(), DdlSubProyecto.SelectedItem.Text) 'AddPS(dt("Avance").ToString().ToDouble, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString(), dt("PU").ToString().ToDouble, 0, 0, 0, 1, 0, True, ' "", DdlProyecto.SelectedValue.ToEntero(), DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero(), DdlSubProyecto.SelectedItem.Text, 2, HdnTipoInv.Value.ToEntero()) End If Next GvPS.DataSource = TmpDT End If If ObjCGame.GetFlete(UsuarioActual.CveEmpresa) Then TxtObsFact.Text = String.Format("Chofer: {0}; Remolque: {1}; Scat: {2};", ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Chofer"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("CodigoDescripcionRemolque"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Scat")) End If ObjCGame.Dispose() GvPS.DataBind() UPObservaciones.Update() UpPS.Update() CargaFolios() End If End If If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero() = -1 AndAlso UsuarioActual.CveTipoDocumento.Length = 3 Then CargaDdlSubProyectos() UpParametros.Update() DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento) CambiaTipoDocto() LimpiaEscondeContado() End If InicializaAplicarNC() If CveCliente > 0 Then CargaRestriccionesCreditoCliente(CveVenta:=Me.CveVenta) 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 'rmf.2020.09.30, codigo de prueba If UsuarioActual.CveEmpresa = 1 Then DivMesesSinIntereses.Visible = True DivDdlCuentaTarjetaCredito.Attributes.Add("class", "col-md-4") DivContadoOtros.Visible = True End If If UsuarioActual.Empresa.Funcionalidad(558).ToEntero() = 1 Then DivMesesSinIntereses.Visible = True DivDdlCuentaTarjetaCredito.Attributes.Add("class", "col-md-4") DivContadoOtros.Visible = True TrKilometraje.Visible = True TrPedido.Visible = False ' TrKilometrajeTxt.Visible = True 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 'QUITAR ESTAS OPCIONES SI LA FACTURA VA SER CANCELADA O ESTA CANCELADA If CveEstatus.Contiene(4, 5, 12, 13, 20, 23) Then LBNotaCredito.Visible = False LnkAplicarRNCDevolucion.Visible = False HLPagar.Visible = False HLSaldarVenta.Visible = False HlFacturasRelaciondas.Visible = False End If ''EN REALIDAD SE OCUPAN ESTAS COSAS DENTRO DEL POSTABCK ??? If Not CveVenta > 0 Then 'LbDescargarExcel.Visible = True HlAgregarExcel.Visible = True End If If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then ' IPP 15 Julio 2017 - ERA FALSE ImgAntiPend.Visible = False UpPS.Update() End If If UsuarioActual.Empresa.Funcionalidad(517) <> "" Then TxtFolio.Enabled = False TxtFecha.Enabled = False If LblSeTimbro.Text = "No" And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev", "Ant") Then TxtFecha.Text = Now.ToShortDateString End If ImgFecha.Visible = False End If 'condición temporal por implementación JAM. usuario FernandaRomo If UsuarioActual.CveUsuario.Contiene(11703, 1719) Then TxtFecha.Enabled = True ImgFecha.Visible = True End If TxtFecha.Enabled = True BloqueaCondiconesPago() BloqueaClasificaciones() 'NO PERMITIR AGREGAR PS DESDE VENTAS EN ECONOLLANTAS If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then BtnModalAddPS.Enabled = False End If MostrarOpcionesPaqueteria() 'If ViewState("CveCotizacion").ToString().ToEntero() > 0 Then 'If Not AjustarTotalCotizacionFacturada(ViewState("CveCotizacion").ToString().ToEntero(), TxtTotal.Text.ToDecimal) Then ' BtnEmitirImprimir.Visible = True ' Alert("Ocurrió un error al ajustar el importe", TipoMensaje.MsgError) 'End If 'End If If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then trRotacion.Visible = True trRotacionlbl.Visible = True trAlineacion.Visible = True trAlineacionlbl.Visible = True Dim FechaRotaAlinea As Date = TxtFecha.Text.ToDate LblRotacion.Text = FechaRotaAlinea.AddMonths(6).ToShortDateString LblAlineacion.Text = FechaRotaAlinea.AddMonths(6).ToShortDateString UPObservaciones.Update() 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 DdlFormaEntrega.Enabled = False DdlUsoCFDI.Enabled = False DdlMetodoPago33.Enabled = False DdlFormaPago33.Enabled = False DdlTiposRelacion.Enabled = False TxtFechaPago.ReadOnly = True TxtFechaPago.Enabled = False RBLPago.Enabled = False imgCalendario.Visible = 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 "Punto Venta" Private Sub CargaCorteCaja() Dim DebeCerrarCorte As Boolean = False 'Checar si hay un Turno Abierto Dim ObjPVenta As New ClsPuntoVenta If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then If ObjPVenta.DtResultados.Rows.Count > 0 Then CveCorte = ObjPVenta.CveCorte Dim FechaICorte = ObjPVenta.FechaInicial.Date '.AddDays(-5) If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso FechaICorte < Now.Date Then DebeCerrarCorte = True LblMotivoBloqueo.Text = $"Existe un corte del día {FechaICorte.ToString("dd/MM/yyyy")}. Favor de cerrarlo para iniciar un nuevo corte." Else LblEstatusCaja.Text = ObjPVenta.FechaInicial.ToShortDateString LblTurno.Text = ObjPVenta.FechaInicial.ToShortDateString TrEstatusCaja.Visible = True BtnIniciarTurno.Visible = False LkbEstadodeCaja.Visible = True LkbIngreso.Visible = True LkbRetiro.Visible = True UpTurno.Visible = True End If Else UpTurno.Visible = False 'Ingresar un nuevo Turno RegistraScript("window.onload = function MuestraCorteCaja() { document.getElementById(""C_btnShow"").click(); }") End If End If ObjPVenta.Dispose() If DebeCerrarCorte Then CargaDatosCorte() BtnEmitirImprimir.Visible = False HlCliente.Visible = False DdlPS.Visible = False RegistraScript("window.onload = function MuestraPantallaBloqueo() { document.getElementById(""C_btnShowBloqueo"").click(); }") End If End Sub Private Sub BtnIniciarTurno_Click(sender As Object, e As EventArgs) Handles BtnIniciarTurno.Click Dim ObjPVenta As New ClsPuntoVenta ObjPVenta.AddVtaCortes(Now, TxtDineroCaja.Text.ToDecimal, UsuarioActual.CveUsuario, TxtDescripcionCaja.Text, UsuarioActual.CveEmpresa) CveCorte = ObjPVenta.CveCorte LblEstatusCaja.Text = Now.ToShortDateString TrEstatusCaja.Visible = True LkbEstadodeCaja.Visible = True LkbIngreso.Visible = True LkbRetiro.Visible = True BtnIniciarTurno.Visible = False ObjPVenta.Dispose() RegistraScript("$('#DivCorteDeCaja').hide();") End Sub Private Sub LkbEstadodeCaja_Click(sender As Object, e As EventArgs) Handles LkbEstadodeCaja.Click CargaDatosCorte() CargaVentasPago() CargaEntradasSalidas() RegistraScript("$('#DivEstadoCaja').modal()") End Sub Private Sub CargaDatosCorte() Dim ObjPVenta As New ClsPuntoVenta Dim Total As Double If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then If ObjPVenta.DtResultados.Rows.Count > 0 Then Total = ObjPVenta.DtResultados(0)("ImporteInicial").ToString().ToDouble + ObjPVenta.DtResultados(0)("VentasEfectivo").ToString().ToDouble + ObjPVenta.DtResultados(0)("Ingresado").ToString().ToDouble - ObjPVenta.DtResultados(0)("Retirado").ToString().ToDouble - ObjPVenta.DtResultados(0)("Devoluciones").ToString().ToDouble DineroCaja = Total LblEfectivoEsperado.Text = Total.FormatoNumero(2) LblEfectivoBloqueo.Text = Total.FormatoNumero(2) Dim Dt As New DataTable Dt.Columns.Add("Descripcion", GetType(String)) Dt.Columns.Add("Importe", GetType(Decimal)) Dim Dr1 = Dt.NewRow Dr1("Descripcion") = "Fondo de Caja" Dr1("Importe") = ObjPVenta.DtResultados(0)("ImporteInicial").ToString().ToDouble Dt.Rows.Add(Dr1) Dim Dr2 = Dt.NewRow Dr2("Descripcion") = "Ventas en Efectivo" Dr2("Importe") = ObjPVenta.DtResultados(0)("VentasEfectivo").ToString().ToDouble Dt.Rows.Add(Dr2) Dim Dr21 = Dt.NewRow Dr21("Descripcion") = "Devoluciones" Dr21("Importe") = ObjPVenta.DtResultados(0)("Devoluciones").ToString().ToDouble Dt.Rows.Add(Dr21) 'Dim Dr3 = Dt.NewRow 'Dr3("Descripcion") = "Propinas" 'Dr3("Importe") = ObjPVenta.DtResultados(0)("Propina").ToString().ToDouble 'Dt.Rows.Add(Dr3) Dim Dr4 = Dt.NewRow Dr4("Descripcion") = "Entradas" Dr4("Importe") = ObjPVenta.DtResultados(0)("Ingresado").ToString().ToDouble Dt.Rows.Add(Dr4) Dim Dr5 = Dt.NewRow Dr5("Descripcion") = "Salidas" Dr5("Importe") = ObjPVenta.DtResultados(0)("Retirado").ToString().ToDouble Dt.Rows.Add(Dr5) Dim Dr6 = Dt.NewRow Dr6("Descripcion") = "Total" Dr6("Importe") = Total Dt.Rows.Add(Dr6) GvDineroCaja.DataSource = Dt GvDineroCaja.DataBind() UpDineroCaja.Update() UpTerminarCorte.Update() End If End If ObjPVenta.Dispose() End Sub Private Sub CargaVentasPago() Dim ObjPVenta As New ClsPuntoVenta If ObjPVenta.GetVta_MetodosPago(CveCorte) Then If ObjPVenta.DtResultados.Rows.Count > 0 Then GvMetodosPago.DataSource = ObjPVenta.DtResultados GvMetodosPago.DataBind() UpMetodosPago.Update() End If End If ObjPVenta.Dispose() End Sub Private Sub CargaEntradasSalidas() Dim ObjPVenta As New ClsPuntoVenta 'Salida If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 0) Then If ObjPVenta.DtResultados.Rows.Count > 0 Then GvEgresos.DataSource = ObjPVenta.DtResultados GvEgresos.DataBind() UpEgresos.Update() End If End If 'Entrada If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 1) Then If ObjPVenta.DtResultados.Rows.Count > 0 Then GvIngresos.DataSource = ObjPVenta.DtResultados GvIngresos.DataBind() UpIngresos.Update() End If End If ObjPVenta.Dispose() End Sub Private Sub BtnAceptarIE_Click(sender As Object, e As EventArgs) Handles BtnAceptarIE.Click Dim ObjPVenta As New ClsPuntoVenta If TxtCantidadIE.Text.ToEntero() > 0 Then If ObjPVenta.AddVta_MovimientosCajas(CveCorte, UsuarioActual.CveUsuario, TxtCantidadIE.Text.ToDouble, TxtDescripcionIE.Text, HdnTipoMovimiento.Value.ToEntero(), Now) Then TxtCantidadIE.Text = "" TxtDescripcionIE.Text = "" RegistraScript("$('#DivIngresoEgreso').modal('hide')", "divingresoegreso") Alert("El movimiento se realizó correctamente") UpIngresoEgreso.Update() End If End If ObjPVenta.Dispose() End Sub Private Sub BtnCerrarTurno_Click(sender As Object, e As EventArgs) Handles BtnCerrarTurno.Click Dim ObjPVenta As New ClsPuntoVenta If TxtEfectivoEnCaja.Text.Trim <> "" Then If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoEnCaja.Text.ToDouble, LblDiferenciaCaja.Text.ToDouble, Now, UsuarioActual.CveEmpresa) Then RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=CORT&CVECORTE={0}&FORMATO={1}", CveCorte, "PDF"))}'", "Imprimir") Dim Liga = "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";" Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga) End If End If ObjPVenta.Dispose() End Sub Private Sub BtnCerrarBloqueo_Click(sender As Object, e As EventArgs) Handles BtnCerrarBloqueo.Click Dim ObjPVenta As New ClsPuntoVenta If TxtEfectivoCajaBloqueo.Text.Trim <> "" Then If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoCajaBloqueo.Text.ToDouble, LblDiferenciaCajaBloqueo.Text.ToDouble, Now, UsuarioActual.CveEmpresa) Then RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=CORT&CVECORTE={0}&FORMATO={1}", CveCorte, "PDF"))}'", "Imprimir") Dim Liga = "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";" Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga) End If Else Alert("Debe especificar el efectivo en caja", TipoMensaje.MsgAdvertencia) RegistraScript("window.onload = function MuestraPantallaBloqueo() { document.getElementById(""C_btnShowBloqueo"").click(); }") End If ObjPVenta.Dispose() End Sub Private Sub BtnCancelar_Click(sender As Object, e As EventArgs) Handles BtnCancelar.Click Response.Redirect("~/Inicio.aspx") End Sub Protected Sub BtnCerrarCaja_Click(sender As Object, e As EventArgs) RegistraScript("$('#DivEstadoCaja').modal('hide')") RegistraScript("$('#DivTerminarCorte').modal()", "divterminarcorte") End Sub Protected Sub LkbIngreso_Click(sender As Object, e As EventArgs) CargaIngresoEgreso(1) End Sub Public Sub CargaIngresoEgreso(Opcion As Integer) RegistraScript("$('#DivIngresoEgreso').modal()") If Opcion = 1 Then LblTituloIE.Text = "Ingreso de Efectivo: " HdnTipoMovimiento.Value = "1" ElseIf Opcion = 0 Then LblTituloIE.Text = "Retiro de Efectivo: " HdnTipoMovimiento.Value = "0" End If UpIngresoEgreso.Update() End Sub Protected Sub LkbRetiro_Click(sender As Object, e As EventArgs) CargaIngresoEgreso(0) End Sub #End Region #Region "Contratos" Private Sub PresionarBotonModal(Boton As String) Try Dim script As String = $"document.getElementById(""{Boton}"").click();" Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.Handler, Page) ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), Boton, script, True) Pag = Nothing Catch ex As Exception End Try End Sub Private Sub VerificarContrato(Optional AfterPageLoad As Boolean = False) Dim ObjContratos As New ClsContratos If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then If UsuarioActual.CveEmpresa.Contiene(72, 80) Then DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'") Else DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True ") End If If AfterPageLoad Then RegistraScript("window.onload = function MuestraContratos() { document.getElementById(""C_BtnMostrarContrato"").click(); }") Else PresionarBotonModal("C_BtnMostrarContrato") End If End If End If ObjContratos.Dispose() End Sub Private Sub BtnIniciarContrato_Click(sender As Object, e As EventArgs) Handles BtnIniciarContrato.Click DdlContratosModal.Items.Clear() If RblOpcionContrato.SelectedValue = "2" Then ContratoDetalles.Visible = True DivEstimaciones.Visible = False DdlContratosModal.DataSource = DtContratos DdlContratosModal.DataBind() DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) DdlContratosOC.Items.Clear() DdlContratosOC.DataSource = DtContratos DdlContratosOC.DataBind() 'DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) UPEstimaciones.Update() Tab.ActiveTab = TabE TabGenerales.Enabled = False Updatetabs.Update() 'ESCONDE ACCIONES LnkRemisiones.Visible = False LnkPedido2SinFacturar.Visible = False LnkCotizaciones.Visible = False HlAgregarExcel.Visible = False 'VINCULARA LAS OC QUE TENGAN CONTRATO SOLAMENTE TieneContrato = True LnkOCs.Visible = True UpnTools.Update() Else BtnEstimacion.Visible = True GvEst.Visible = True DdlContratosOC.Items.Clear() DdlContratosOC.DataSource = DtContratos DdlContratosOC.DataBind() DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) GvContratoDetalles.DataSource = Nothing GvContratoDetalles.DataBind() UpContratos.Update() DivEstimaciones.Visible = True ContratoDetalles.Visible = False UPEstimaciones.Update() Tab.ActiveTab = TabGenerales TabGenerales.Enabled = True Updatetabs.Update() TieneContrato = False End If PresionarBotonModal("C_BtnCerrarContrato") End Sub Private Sub BtnCancelarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCancelarContratoDetalles.Click DtContratos = Nothing PresionarBotonModal("C_BtnCerrarContrato") End Sub Private Sub DdlContratosModal_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosModal.SelectedIndexChanged DdlContratoModalSelectIndex() End Sub Protected Sub RBLTipoContrato_SelectedIndexChanged(sender As Object, e As EventArgs) CargaContratos() End Sub Private Sub CargaContratos() Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}") If DrContrato Is Nothing Then Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError) Exit Sub End If If DrContrato("CveContratoTipo").ToString.ToEntero.Contiene(30, 31) Then PorAmortizacionAnticipo = DrContrato("PorAmortizacionAnticipo").ToString.ToEntero EscontratoObra = True Else PorAmortizacionAnticipo = 0 EscontratoObra = False End If LbContratoImporteTotal.Text = DrContrato("ImporteTotal").ToString().FormatoNumero LbContratoImporteMinimo.Text = DrContrato("ImporteMin").ToString().FormatoNumero LbContratoImporteMaximo.Text = DrContrato("ImporteMax").ToString().FormatoNumero LtContratoImporteSaldo.Text = DrContrato("ImporteSaldo").ToString().FormatoNumero Dim ObjContrato As New ClsContratos Dim NoId As Integer = 0 If ObjContrato.GetContratosDetalle(DdlContratosModal.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) Then 'SI ES CONTRATO DE CONSIGNACION DE VENTA AGARRA LAS EXISTENCIAS DEL ALMACEN CreaConsignacionSerieDetalle() CveAlmacenExistenciasContrato = -1 CveAlmacenOrigenContrato = -1 GvContratoDetalles.Columns(8).Visible = False If DrContrato("CveContratoTipo").ToString().Contiene("27") Then CveAlmacenExistenciasContrato = If(DrContrato("CveAlmacenDestino").ToString().ToEntero() > 0, DrContrato("CveAlmacenDestino").ToString().ToEntero(), -1) CveAlmacenOrigenContrato = If(DrContrato("CveAlmacenOrigen").ToString().ToEntero() > 0, DrContrato("CveAlmacenOrigen").ToString().ToEntero(), -1) End If NoId = ObjContrato.DtResultados.FiltraParametros("NoIdentificacion <> ''").Rows.Count 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA Dim DtDetalle As DataTable = ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}") GvContratoDetalles.DataSource = DtDetalle 'ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}") GvContratoDetalles.DataBind() UpContratos.Update() NumeroContrato = DrContrato("NumeroContrato").ToString() DescripcionContrato = DrContrato("DescripcionContrato").ToString() NumeroLicitacion = DrContrato("NumeroLicitacion").ToString().Trim Me.CveVendedorContrato = DrContrato("CveVendedor").ToString().ToEntero() DdlVendedor.SelectedValueExist(DrContrato("CveVendedor")) If DrContrato("CveSucursalCliente").ToString().ToEntero() > 0 Then DdlSucursalCliente.SelectedValueExist(DrContrato("CveSucursalCliente")) DdlSucursalCliente_SelectedIndexChanged(DdlSucursalCliente, EventArgs.Empty) DdlSucursalCliente.Enabled = False DdlSucursalCliente.Attributes.Add("disabled", "") End If Dim CveAlmacenDestino As Integer = DrContrato("CveAlmacenDestino").ToString().ToEntero() If CveAlmacenDestino > 0 Then DdlAlmacenAsignado.Items.Clear() DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} And CveTipoAlmacen IN (4, 10)") DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlAlmacenAsignado.Items.Insert(1, New ListItem(DrContrato("Almacen").ToString(), CveAlmacenDestino.ToString())) DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString()) DdlAlmacenAsignado.DataBind() Else DdlAlmacenAsignado.Items.Clear() DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} And CveTipoAlmacen In (4,10)") DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString()) DdlAlmacenAsignado.DataBind() End If Dim CveAlmacenOrigen As Integer = DrContrato("CveAlmacenOrigen").ToString().ToEntero() If CveAlmacenOrigen > 0 Then 'TrAlmacenOrigen.Visible = True 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 If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}") DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString()) DdlAlmacenAsignado.DataBind() DdlAlmacenOrigen.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}") DdlAlmacenOrigen.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlAlmacenOrigen.SelectedValueExist(CveAlmacenOrigen.ToString()) DdlAlmacenOrigen.DataBind() End If UpParametros.Update() End If If NoId > 0 Then 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA GvContratoDetalles.Columns(3).Visible = True 'NoIdentificacion End If ObjContrato.Dispose() If CveOC > 0 Then BtnCargarContratoDetalles.Enabled = True For Each gvr As GridViewRow In GvContratoDetalles.Rows gvr.FCTextBox("TxtCant").Enabled = False Next Dim EsValido = True For Each Dr As DataRow In TmpDT.Rows Dim CantidadActual = Dr("Cantidad").ToString().ToDouble Dim CantidadDispo = 0.0 Dim CantidadAsignada = 0.0 For Each gvr As GridViewRow In GvContratoDetalles.Rows If gvr.DataKey("CvePS").ToEntero() = Dr("CvePS").ToString().ToEntero() Then CantidadDispo = gvr.DataKey("Cantidad").ToString().ToDouble - gvr.FCTextBox("TxtCant").Text.ToDouble If CantidadDispo = 0 Then Continue For CantidadAsignada = If(CantidadDispo > CantidadActual, CantidadActual, CantidadDispo) gvr.FCTextBox("TxtCant").Text = (gvr.FCTextBox("TxtCant").Text.ToDouble + CantidadAsignada).ToString() CantidadActual = CantidadActual - CantidadAsignada If CantidadActual = 0 Then Exit For End If End If Next If CantidadActual > 0 Then EsValido = False Alert("No se cumple con la totalidad de la Orden de Compra. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) BtnCargarContratoDetalles.Enabled = False Exit For End If Next If EsValido Then BtnCargarContratoDetalles_Click(BtnCargarContratoDetalles, EventArgs.Empty) End If End If 'LIMPIA TIPOS DOCTO If (DdlTipoComprobante.Items.FindByValue("Ped") IsNot Nothing) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ped")) End If If (DdlTipoComprobante.Items.FindByValue("PeC") IsNot Nothing) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PeC")) End If If (DdlTipoComprobante.Items.FindByValue("Cot") IsNot Nothing) Then 'NO PUEDEN HACER COTIZACIÓN DE UN CONTRATO DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot")) End If DVEstimacionesObra.Visible = False Select Case RBLTipoContrato.SelectedValue.ToEntero() Case 1 DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) DdlTipoComprobante.SelectedValue = "Ped" DdlTipoComprobante.Enabled = False Case 2 DdlTipoComprobante.Enabled = True DdlTipoComprobante.SelectedValueExist("Ing") Case 3 DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido de Consignación", "PeC")) DdlTipoComprobante.SelectedValue = "PeC" DdlTipoComprobante.Enabled = False Case 4 TabGenerales.Enabled = True DVEstimacionesObra.Visible = True DdlEstimacionesObra.Items.Clear() Dim Con As New ClsContratos If Con.GetContratosAvanceEstimacionVentas(DdlContratosModal.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) Then DdlEstimacionesObra.DataSource = Con.DtResultados Else DdlEstimacionesObra.DataSource = Nothing End If Con.Dispose() DdlEstimacionesObra.DataBind() DdlEstimacionesObra.Items.Insert(0, New ListItem("Todos", "-1")) BtnCargarContratoDetalles.Visible = False BtnCancelarContratoDetalles.Visible = False BtnCalcularTotalesContrato.Visible = False BtnEstimacion.Visible = False GvEst.Visible = False GvContratoDetalles.Visible = False End Select UPEstimaciones.Update() Updatetabs.Update() ChkPSOC.Checked = False CambiaTipoDocto() UpParametros.Update() UPEstimaciones.Update() UPOCFactura.Update() End Sub Private Sub BtnCargarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCargarContratoDetalles.Click ''SI LA VENTA ES TIPO VENTA DE CONTRATO Y EL CONTRATO TIENE LICITACION EL CLIENTE DEBE TENER IMPUESTOS LOCALES 'If RBLTipoContrato.SelectedValue = "2" Then ' Dim ObjClientes As New ClsClientes ' If NumeroLicitacion <> "" Then ' If ObjClientes.GetClienteImpuestosLocales(CveCliente) Then ' If Not ObjClientes.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then ' Alert("El contrato con licitación al que se hace referencia requiere impuestos locales.", TipoMensaje.MsgAdvertencia) ' ObjClientes.Dispose() ' Exit Sub ' End If ' End If ' End If ' ObjClientes.Dispose() 'End If Dim DrContrato As DataRow = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue.ToEntero()}") Dim ps As New ClsInventarios CveContrato = DdlContratosModal.SelectedValue.ToEntero() AplicaGastoContrato = If(DrContrato("CveContratoTipo").ToString().Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento 'VALIDA IMPORTE DEL CONTRATO Dim SeleccionadoContrato = 0.0 '(From row As GridViewRow In GvContratoDetalles.Rows.Cast(Of GridViewRow)() Select row.FCLabel("LtlTotal").Text.ToDecimal).Sum TmpDT.Clear() TxtSubTotal.Text = "0" LblDescuentos.Text = "0" TxtIVA.Text = "0" TxtRetIVA.Text = "0" For Each Row As GridViewRow In GvContratoDetalles.Rows If Row.FCTextBox("TxtCant").Text.ToEntero() > 0 Then 'VALIDA EXISTENCIAS DE ALMACÉN 'Dim DrPS = GlobalDTProductosServicios(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero()).FiltroPrimero("") Dim DrPS = GlobalDTPSSimplificado(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero()).FiltroPrimero("") If DrPS IsNot Nothing Then Dim CveTipoPS As Integer = DrPS("CveTipoPS").ToString().ToEntero() Dim CveTipoInv As Integer = DrPS("Inv_CveMetodoInventario").ToString().ToEntero() Dim existencia As Decimal = ps.GetExistenciasPS(Row.DataKey("CvePS").ToEntero(), Row.DataKey("CveUM").ToEntero(), UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveVendedor:=DdlVendedor.SelectedValue.ToEntero(), CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) If (existencia < Row.FCTextBox("TxtCant").Text.ToEntero() AndAlso CveTipoPS <> 1) AndAlso UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ped") Then ' And DdlContratosModal.SelectedValue.ToEntero() <> 196 Then Alert("No cuenta con la cantidad suficiente en inventario para el producto:
" + Row.FCLiteral("LtlPS").Text + ".", TipoMensaje.MsgAdvertencia) TmpDT.Clear() GvPS.DataSource = Nothing GvPS.DataBind() UpPS.Update() Exit Sub Else Dim ObsPlantilla As String = PlantillaContrato(Row.DataKey("Observaciones")) SeleccionadoContrato += Row.FCTextBox("TxtCant").Text.ToEntero() * Row.FCLiteral("LtlPU").Text.ToDouble AgregarProductoServicio(Row.FCTextBox("TxtCant").Text.ToEntero(), Row.DataKey("CveUM").ToEntero(), Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero(), Row.DataKey("Clasificacion"), Row.DataKey("CvePS").ToEntero(), Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, ObsPlantilla, $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDecimal, 0, DrContrato("CveProyecto").ToString().ToEntero(), DrContrato("ProyectoContrato").ToString(), DrContrato("CveSubProyecto").ToString().ToEntero(), DrContrato("SubProyectoContrato").ToString(), CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero()) 'AddPS(Row.FCTextBox("TxtCant").Text.ToEntero(), Row.DataKey("CveUM").ToEntero(), Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero(), Row.DataKey("Clasificacion"), ' Row.DataKey("CvePS").ToEntero(), Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, Row.DataKey("Observaciones"), $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDouble, If(Row.DataKey("IVA").ToDouble = -1, ViewState("IVA").ToString().ToDouble, Row.DataKey("IVA").ToDouble), 0, 0, 1, 0, True, "", ' DrContrato("CveProyecto").ToString().ToEntero(), DrContrato("ProyectoContrato").ToString(), DrContrato("CveSubProyecto").ToString().ToEntero(), DrContrato("SubProyectoContrato").ToString(), CveTipoPS, CveTipoInv, CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero(), CodigoPS:=Row.FCLiteral("LtlPS").Text) End If Else Alert("El producto presenta una inconsistencia en su información", TipoMensaje.MsgError) TmpDT.Clear() GvPS.DataSource = Nothing GvPS.DataBind() UpPS.Update() Exit Sub End If End If Next 'SI EL CONTRATO TIENE IMPUESTOS LOCALES SE CARGAN LOS DEL CONTRATO AHUEVO If RBLTipoContrato.SelectedValue = "2" Then Dim ObjContratos As New ClsContratos If ObjContratos.GetContratoImpuestosLocales(CveContrato, UsuarioActual.CveEmpresa) Then If ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then Dim DtContratoImpuesto As DataTable = ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") If DtContratoImpuesto IsNot Nothing AndAlso DtContratoImpuesto.Rows.Count > 0 Then ' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear() TmpDTImpuestos = DtContratoImpuesto GvImpuestosLocales2.DataSource = TmpDTImpuestos GvImpuestosLocales2.DataBind() If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then TrOtros.Visible = True GvImpuestosLocales2.Visible = True TrOtros.Style.Add("display", "") Else TrOtros.Visible = False GvImpuestosLocales2.Visible = False End If DtContratoImpuesto.Dispose() End If UpImpuestos.Update() End If End If ObjContratos.Dispose() End If If Not CveCicloComercial > 0 Then 'SI EL IMPORTE MAX O EL IMPORTE FIJO DEL CONTRATO FLEXIBLE ES CERO, NO HAY LIMITE If Not (DrContrato("Importe").ToString().ToDouble = 0 And DrContrato("ImporteMax").ToString().ToDouble = 0) Then If DdlTipoComprobante.SelectedValue = "Ing" And (DrContrato("ModalidadDetalle").ToString() = "1" Or DrContrato("ImporteMax").ToString().ToDouble > 0) AndAlso (DrContrato("ImporteTotal").ToString().ToDouble - DrContrato("Avance").ToString().ToDouble) < (SeleccionadoContrato) Then Alert("Se excede el importe límite del contrato. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) TmpDT.Clear() GvPS.DataSource = Nothing GvPS.DataBind() UpPS.Update() Exit Sub End If End If End If CalculaUsados() CalculaTotalesVenta() LbAgregar.Visible = False UpPS.Update() 'restricciones para evitar cambios una vez seleccionado el contrato If BtnEmitirImprimir.Visible = False Then BtnEmitirImprimir.Visible = True : TrVistaPrevia.Visible = True 'DESACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto disabled") TxtCodigo.ReadOnly = True Tab.ActiveTab = TabGenerales TabGenerales.Enabled = True Updatetabs.Update() PresionarBotonModal("C_BtnCerrarContrato") ps.Dispose() UpFacturar.Update() End Sub Private Sub CargarContratoUrl() Dim ObjContratos As New ClsContratos If ObjContratos.GetContratos(CveContrato, UsuarioActual.CveEmpresa, -1, -1, 1) Then If ObjContratos.DtResultados.Rows.Count > 0 Then Dim CveContratoTipo = ObjContratos.DtResultados.Rows(0)("CveContratoTipo").ToString.ToEntero 'Cargamos los datos del Cliente DtContratos = ObjContratos.DtResultados ViewState("CveCliente") = ObjContratos.DtResultados(0)("CveCliente").ToString().ToEntero() CorreoNotificacionPedDev = ObjContratos.DtResultados(0)("CorreoNotificacionPedDev").ToString() HdnCveCliente.Value = ObjContratos.DtResultados(0)("CveCliente").ToString() CargaCliente(CveCliente) DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) DdlTipoComprobante.SelectedValue = "Ped" DdlTipoComprobante.Enabled = False DdlAlmacenAsignado.Enabled = False DdlSubProyectoDatos.SelectedValueExist(ObjContratos.DtResultados(0)("CveSubProyecto")) AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString().Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento If TipoContrato = 1 Then 'Cargamos los datos del Contrato RblOpcionContrato.SelectedValue = "2" BtnIniciarContrato_Click(Nothing, Nothing) DdlContratosModal.SelectedValue = CveContrato.ToString() DdlContratosModal_SelectedIndexChanged(Nothing, Nothing) DdlAlmacenAsignado.Enabled = False DdlAlmacenOrigen.Enabled = False ElseIf TipoContrato = 0 Then 'Mostramos los almacenes DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} {If(DdlTipoComprobante.SelectedValue = "Ped", "", "AND CveTipoAlmacen IN (4,10)")}") DdlAlmacenAsignado.DataBind() DdlAlmacenAsignado.Enabled = True TrAlmacenAsignado.Visible = True TrAlmacenOrigen.Visible = True TrTipoPedido.Visible = True TrObs.InnerText = "No. Serie" SpObs.InnerText = "Contrato" TrObsGenerales.InnerText = "Número de Contrato " UpParametros.Update() End If If ObjContratos.CveAlmacen > 0 Then If (DdlAlmacenAsignado.Items.FindByValue(ObjContratos.CveAlmacen.ToString()) Is Nothing) Then Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacen.ToString())) If dr IsNot Nothing Then DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString(), dr("CveAlmacen").ToString())) End If End If DdlAlmacenAsignado.SelectedValueExist(ObjContratos.CveAlmacen.ToString()) Else If (DdlAlmacenAsignado.Items.FindByValue("89") Is Nothing) Then Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", "89")) If dr IsNot Nothing Then DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString(), dr("CveAlmacen").ToString())) ' lo genera Obj.SelectedValue = Valor.ToString() DdlAlmacenAsignado.Enabled = False End If End If DdlAlmacenAsignado.SelectedValueExist("89") End If If ObjContratos.CveAlmacenOrigen > 0 AndAlso TipoContrato = 0 Then DdlAlmacenOrigen.Visible = True RequiereAlmacenOrigen = True If CveContratoTipo.Contiene(7, 9, 13, 21, 27) Then Dim CveTipoAlmacenOrigen = "12,15" If CveContratoTipo.Contiene(27) Then CveTipoAlmacenOrigen = "1" End If DdlAlmacenOrigen.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} {If(DdlTipoComprobante.SelectedValue = "Ped", "", $"AND CveTipoAlmacen IN ({CveTipoAlmacenOrigen})")}") DdlAlmacenOrigen.DataBind() End If If (DdlAlmacenOrigen.Items.FindByValue(ObjContratos.CveAlmacenOrigen.ToString()) Is Nothing) Then Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacenOrigen.ToString())) If dr IsNot Nothing Then DdlAlmacenOrigen.Items.Insert(0, New ListItem(dr("Almacen").ToString(), dr("CveAlmacen").ToString())) End If End If DdlAlmacenOrigen.SelectedValueExist(ObjContratos.CveAlmacenOrigen.ToString()) DdlAlmacenOrigen.Enabled = True End If Else Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) End If Else Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) End If ObjContratos.Dispose() End Sub Private Sub CargarPedidoUrl() CargaVenta() CargaFolios() TrAlmacenOrigen.Visible = True TrAlmacenAsignado.Visible = True RequiereAlmacenDestino = True BtnEmitirImprimir.Text = "Devolver Pedido" BtnEmitirImprimir.Visible = True DdlAlmacenAsignado.DataBind() DdlAlmacenAsignado.Items.Insert(0, New ListItem("Productos Financieros Como Dato", "89")) DdlAlmacenAsignado.Enabled = False UpParametros.Update() UpFacturar.Update() End Sub Private Sub GuardarContratoAvanceEstimaciones(ObjContrato As ClsContratos, factura As Modelos.Factura, ErrorList As List(Of String), Multiplicador As Integer, Optional CrearAvance As Boolean = False) If (factura.CveContrato > 0 AndAlso ((DdlContratosModal.Items.Count > 0 AndAlso factura.CveContrato = DdlContratosModal.SelectedValue.ToEntero()) OrElse DdlFiltroContrato.SelectedValue.ToEntero() > 0 OrElse CrearAvance)) Or ContratoOC Then Dim CveEstimacion As Integer = -1 If ObjContrato.AddEstimaciones(factura.CveContrato, factura.Fecha, -1, factura.CveVenta, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then CveEstimacion = ObjContrato.DtResultados(0)("CveEstimacion").ToString().ToEntero() For Each row As DataRow In TmpDT.Rows If row("CveContratoDetalle").ToString().ToEntero() > 0 Then If Not ObjContrato.AddContratosAvance(row("CveContratoDetalle").ToString().ToEntero(), row("Cantidad").ToString().ToEntero() * Multiplicador, factura.Fecha, UsuarioActual.CveUsuario, CveEstimacion:=CveEstimacion) Then ErrorList.Add("Ocurrió un error al agregar los avances") End If End If Next Else ErrorList.Add("Ocurrió un error al agregar las estimaciones") End If End If End Sub Private Sub GvContratoDetalles_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvContratoDetalles.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then Dim CantidadDisponible = If(e.Row.DBCampo("Cantidad").ToDouble < 0, "0", e.Row.DBCampo("Cantidad")) e.Row.FCLiteral("LtlCantDisp").Text = CantidadDisponible If CveCicloComercial > 0 Then 'Si es un Ciclo Comercial quitamos el límite de CantidadDisponible e.Row.Cells(1).Style.Add("display", "none") CantidadDisponible = "10000000" e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadContratada") End If 'Si es contrato flexible le damos una cantidad alta de lo contrario lo maximo es lo estipulado en el contrato If e.Row.DataKey("LimitarCantidad").ToString() = "True" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or e.Row.DataKey("ModalidadDetalle").ToString() = "1" Then e.Row.FCRangeValidator("RVCant").MaximumValue = CantidadDisponible LimitaCantidadSerie = 1 Else e.Row.FCRangeValidator("RVCant").MaximumValue = "10000000" LimitaCantidadSerie = 0 End If 'CONSIGNACION DE VENTA If CveAlmacenExistenciasContrato > 0 And e.Row.DBCampo("Inv_CveMetodoInventario").ToString().ToEntero() = 5 Then GvContratoDetalles.Columns(8).Visible = True e.Row.FCButton("BtnSerieConsignacion").Visible = True e.Row.FCButton("BtnSerieConsignacion").CommandArgument = $"{e.Row.DBCampo("CveContratoDetalle")}°{e.Row.DBCampo("CvePS")}°{e.Row.DBCampo("CveUM")}°{e.Row.DBCampo("CodigoPS")}°{e.Row.DBCampo("Cantidad")}°{LimitaCantidadSerie}" e.Row.FCTextBox("TxtCant").Enabled = False End If ''Si viene de una OC Sin Facturar y tiene contrato 'If TieneContrato AndAlso ContratosConOC IsNot Nothing AndAlso ContratosConOC.ToString().Length > 0 Then ' e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadOC").ToString() 'End If End If End Sub Private Sub BtnCalcularTotalesContrato_Click(sender As Object, e As EventArgs) Handles BtnCalcularTotalesContrato.Click For Each row As GridViewRow In GvContratoDetalles.Rows row.FCLiteral("LtlTotal").Text = (row.FCLiteral("LtlCantDisp").Text.ToEntero() * row.FCTextBox("TxtCant").Text.ToDouble).FormatoNumero(2) Next UpContratos.Update() End Sub Private Sub DdlContratoModalSelectIndex() If Not DdlContratosModal.SelectedValue.ToEntero() > 0 Then GvContratoDetalles.DataBind() UpContratos.Update() Exit Sub End If Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}") If DrContrato Is Nothing Then Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError) Exit Sub End If CargaContratos() DdlContratosOC.SelectedValue = DdlContratosModal.SelectedValue UPOCFactura.Update() End Sub #End Region #Region "C A R G A S" Private Sub ClasificacionModal() DdlClasificacionModal.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion") DdlClasificacionModal.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlClasificacionModal.DataBind() UpModal.Update() End Sub Private Sub CargaOrdenProduccion(Optional Opcion As Integer = 1, Optional CveVenta As Integer = -1) DdlOrdenProduccion.Items.Clear() Dim CveOrdenProduccion As String = "-1" Dim ObjCGame As New ClsCGame If ObjCGame.GetOrdenProduccion(-1, UsuarioActual.CveEmpresa, -1, "-1", MinFecha, MaxFecha, -1) Then If Opcion = 1 Then DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros(String.Format("CveVenta IS NULL ")) ElseIf Opcion = 2 Then LnkActualizarOrdenProduccion.Visible = True DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta} OR CveVenta IS NULL") If ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows.Count > 0 Then CveOrdenProduccion = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows(0)("CveOrdenProduccion").ToString() End If End If DdlOrdenProduccion.Items.Insert(0, New ListItem("Seleccione", "-1")) End If ObjCGame.Dispose() DdlOrdenProduccion.DataBind() DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion) End Sub Private Sub CargaEstatusFactura(Optional TipoDocto As String = "Ing") Dim FiltroCompromiso = If(TipoDocto = "Com", "And CveEstatusFactura In (2, 9)", "And CveEstatusFactura Not In (9)") If TipoDocto.ToUpper.Contiene("EGS", "COM", "ANT") Then TipoDocto = "Ing" 'DdlEstatus.Items.Clear() 'DdlEstatus.Items.Insert(0, New ListItem("Seleccione", "-1")) 'DdlEstatus.SelectedValue = "-1" 'DdlEstatus.DataSource = GlobalDTEstatusFactura.FiltraParametros(String.Format("TipoDocto = '{0}' {1}", TipoDocto, FiltroCompromiso)) 'DdlEstatus.DataBind() ''If DdlEstatus.Items.Count > 1 Then '' DdlEstatus.SelectedIndex = 1 ''End If ''permiso para poder cambiar estatus 'If CveVenta > 0 Then DdlEstatus.Enabled = UsuarioActual.TienePermisoProceso(116) End Sub Private Sub CargaOS(CveOS As Integer) Dim OS As New ClsOS Dim DtDetalle As DataTable = Nothing Dim DtDetalleMateriales As DataTable = Nothing If OS.GetOrdenesServicios(CveOS, -1, -1, -1, -1, UsuarioActual.CveEmpresa) Then HdnCveCliente.Value = OS.CveCliente.ToString() ViewState("CveCliente") = OS.CveCliente CargaCliente(CveCliente) If OS.GetOrdenesServiciosDetalleAFacturar(CveOS) Then Dim Cons As Integer = 1 For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows AgregarProductoServicio(dr("Cantidad").ToString().ToDecimal, dr("CveUM").ToString().ToEntero(), dr("UM").ToString(), -1, "", dr("CvePS").ToString().ToEntero(), "", dr("Obs").ToString(), 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() TxtTotal.Text = TmpDT.SUM("Total").FormatoNumero() GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") UpContado.Update() UpPS.Update() End If End Sub Private Sub CargaEstados(Optional ClaveSATPais As String = "MEX") DdlEstadoSAT.Items.Clear() DdlEstadoSAT.DataSource = GlobalDTGralEstados(ClaveSATPais) DdlEstadoSAT.DataBind() DdlEstadoSAT.Items.Insert(0, New ListItem("Seleccione", "-1")) If UsuarioActual.CveEmpresa = 140 AndAlso ClaveSATPais = "MEX" Then DdlEstadoSAT.SelectedValueExist("26") End If End Sub Protected Sub DdlSATPais_SelectedIndexChanged(sender As Object, e As EventArgs) CargaEstados(DdlSATPais.SelectedValue) End Sub Private Function CargaVenta() As Boolean Dim Retorno As Boolean = False 'CARGA PARA FACTURACION Dim CveRemision As Integer = IfNull(ViewState("CveRemision"), 0).ToString().ToEntero() Dim CveCotizacion As Integer = IfNull(ViewState("CveCotizacion"), 0).ToString().ToEntero() Dim CveVenta As Integer = Me.CveVenta CveVenta = If(CveRemision > 0, CveRemision, CveVenta) CveVenta = If(CveCotizacion > 0, CveCotizacion, CveVenta) CveVenta = If(CvePedido > 0, CvePedido, CveVenta) Dim DtAntRelacionados As DataTable = Nothing Dim SerieFolioPadre As String Dim DbRowVenta As DataRow = Nothing 'CARGA DTs DE VENTAS If CveVenta > 0 Then Using ObjVentas As New ClsVentas() If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then DbRowVenta = ObjVentas.DtResultados.Copy().Rows(0) Else ViewState("CveVenta") = -1 Alert("El documento solicitado no existe, favor de revisar su búsqueda.", TipoMensaje.MsgAdvertencia) End If End If If DbRowVenta IsNot Nothing Then If ObjVentas.GetVentasRelacionadas(CveVenta, 1, UsuarioActual.CveEmpresa) Then DtAntRelacionados = ObjVentas.DtResultados.FiltraParametros("TipoDocto IN ('Ing','Ant','Egs','Dev')") End If 'CargaDetalle If ObjVentas.GetVentaDetalle(CveVenta) Then TmpDT = ObjVentas.DtResultados.Copy() TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) TmpDT.Columns.Add("CveVentaDetalleRNC", GetType(Integer)) TmpDT.Columns.Add("TieneProntoPago", GetType(String)) TmpDT.Columns.Add("ImporteProntoPago", GetType(Decimal)) End If 'CargaFirmas If ObjVentas.GetVentasFirmas(CveVenta) Then If ObjVentas.DtResultados.Rows.Count > 0 Then DTmpF = ObjVentas.DtResultados.Copy() End If End If 'CARGA IMPUESTOS LOCALES If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then If ObjVentas.DtResultados.Rows.Count > 0 Then TmpDTImpuestos = ObjVentas.DtResultados.Copy() End If End If 'CARGA ANTICIPOS If Not (CveRemision > 0 Or CveCotizacion > 0) Then If DbRowVenta("TipoDocto").ToString().Contiene("Ing", "Ant") Then 'carga as notas de credito vinculadas If ObjVentas.GetVentasAntNC(CveVenta, -1) Then TmpDTDocumentosRelacionados = ObjVentas.DtResultados.Copy() GvAntNC.DataSource = TmpDTDocumentosRelacionados GvAntNC.Caption = "
(Anticipos/NC/IxC) Vinculados
" GvAntNC.DataBind() End If End If If DbRowVenta("TipoDocto").ToString().Contiene("Egs", "Dev", "Ant") Then Dim AplicaAmortizacion As Boolean = False If DbRowVenta("TipoDocto").ToString().Contiene("Ant") Then AplicaAmortizacion = True If ObjVentas.GetVentasAntNC(-1, CveVenta, AplicaAmortizacion) Then TmpDTNCVinculadas = ObjVentas.DtResultados.Copy() GvNC.DataSource = TmpDTNCVinculadas GvNC.Caption = "
Ventas Aplicadas
" GvNC.DataBind() InicializaDTVentasNC() For Each Dr As DataRow In TmpDTNCVinculadas.Rows If Dr("CveConceptoContable").ToString().ToEntero() = 91 Then CargaNCDT(Dr("CveVenta").ToString().ToEntero(), Dr("Importe").ToString().ToDecimal, Dr("FolioFiscal").ToString(), TC:=Dr("TipoCambio").ToString().ToDecimal) End If Next If GvNC.Rows.Count > 0 Then ImgAntiPend.Visible = False End If End If End If End If 'CARGA REMISIONES If ObjVentas.GetRemisionesRelacionadas(CveVenta, DbRowVenta("TipoDocto").ToString()) Then GvRemisiones.Caption = "
Remisiones/Facturas
" GvRemisiones.DataSource = ObjVentas.DtResultados.Copy() GvCancelarRemisiones.DataSource = ObjVentas.DtResultados.Copy() GvRemisiones.DataBind() GvCancelarRemisiones.DataBind() '[IPP] SI ES REMISION PARA CANCELARLA NO DEBE TENER NINGUNA FACTURADA RELACIONADA - 24Abril2018 If DbRowVenta("TipoDocto").ToString().Contiene("Rem") And GvRemisiones.Rows.Count > 0 Then LbCancelarDocumento.Visible = False End If 'SI TIENE REMISIONES Y VA A CANCELAR ES NECESARIO EL MOVIMIENTO DE DEVOLUCION If DbRowVenta("TipoDocto").ToString().Contiene("Ing", "Ant") AndAlso GvRemisiones.Rows.Count > 0 Then ChkDevAlm.Checked = True ChkDevAlm.Enabled = False 'LiDevolucionAlmacen.Visible = False End If End If 'SI ES COTIZACION PUEDE GENERAR UNA OC PARA MODIFICAR LOS IMPORTES If DbRowVenta("TipoDocto").ToString() = "Cot" AndAlso UsuarioActual.Empresa.Funcionalidad(583) = "1" Then Dim DtOCGeneradas As DataTable = Nothing If ObjVentas.GetVentasCotizacionesOC(Me.CveVenta, -1, UsuarioActual.CveEmpresa) Then DtOCGeneradas = ObjVentas.DtResultados.Copy() End If If DtOCGeneradas IsNot Nothing AndAlso DtOCGeneradas.Rows.Count > 0 Then LtGenerarOC.Visible = False Else LtGenerarOC.Visible = True End If End If 'CARGA GV DE OC RELACIONADAS If ObjVentas.GetOCRelacionadas(CveVenta) Then If ObjVentas.DtResultados.Rows.Count > 0 Then DivOCRelacionadas.Visible = True GvOCRelacionadas.DataSource = ObjVentas.DtResultados GvOCRelacionadas.DataBind() End If End If End If End Using End If If DbRowVenta IsNot Nothing Then 'CARGAR PS GvPS.DataSource = TmpDT GvPS.DataBind() Dim CveCliente As Integer = DbRowVenta("CveCliente").ToString().ToEntero() HdnCveVenta.Value = CveVenta.ToString() Me.EsGarantia = CBool(DbRowVenta("EsGarantia")) RFCReceptorVenta = DbRowVenta("RFCReceptor").ToString() 'Adjuntar archivo Adjunto = DbRowVenta("Adjunto").ToString() If Adjunto <> "" Then BtnArchivoAdjunto.Text = Adjunto BtnArchivoAdjunto.Visible = True BtnEliminarAdjunto.Visible = False BtnAdjuntar.Visible = False tdAdjuntar.Style.Item("display") = "none" tdAdjunto.Style.Item("display") = "block" Else DivAdjuntar.Visible = False End If ViewState("CveSubProyectoVenta") = DbRowVenta("CveSubProyecto").ToString().ToEntero() Me.CveEstatusFacturaPadre = DbRowVenta("CveEstatusFacturaPadre").ToString().ToEntero() If UsuarioActual.Empresa.Funcionalidad(705) = "1" Then Me.CveLineaAdicionalVenta = DbRowVenta("CveLineaAdicional").ToString().ToEntero() End If 'CargaEncabezado If Not (CveRemision > 0 Or CveCotizacion > 0) Then DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString() If UsuarioActual.TienePermisoProceso(274) Then TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant" End If If TrAntEspecial.Visible Then ChkAntEspecial.Enabled = False ChkAntEspecial.Checked = If(DbRowVenta("AnticipoEspecial").ToString() = "True", True, False) End If CargaEstatusFactura(DdlTipoComprobante.SelectedValue) CveEstatus = DbRowVenta("CveEstatusFactura").ToString().ToEntero() LbEstatus.Text = DbRowVenta("EstatusFactura").ToString() ViewState("SaldoVenta") = DbRowVenta("Saldo").ToString() AplicaCancelarRemision = CBool(DbRowVenta("AplicaCancelarRemision").ToString()) If AplicaCancelarRemision AndAlso CveEstatus.Contiene(2, 3) AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then DivCanRem.Visible = True VentaSaldoAlmacen = DbRowVenta("SaldoAlmacen").ToString().ToDecimal If CveEstatus = 5 Then LbCancelarDocumento.Enabled = False 'If CveEstatus = 20 Then ' LbCancelarDocumentoManual.Visible = True 'End If If (Not CveEstatus.Contiene(4, 5, 12, 13, 20, 23) OrElse (CveEstatus = 5 AndAlso DbRowVenta("CveEstatusRefacturacion").ToString().ToEntero() = 4)) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Ant") AndAlso UsuarioActual.TienePermisoProceso(159) Then Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) If TienePermiso <> "" Then LkRefacturacion.Visible = True If (CveEstatus = 5 AndAlso DbRowVenta("CveEstatusRefacturacion").ToString().ToEntero() = 4) Then RefacturarCancelada = True End If End If End If If DbRowVenta("CveVentaRelacionada").ToString().ToEntero() > 0 Then TrRefacturadaa.Visible = True HplRefacturadaEn.NavigateUrl = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", DbRowVenta("CveVentaRelacionada")) HplRefacturadaEn.Text = DbRowVenta("SerieFolioRelacionada").ToString() LblAlertRefacInv.Visible = True End If If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Ing", "Ant", "Dev", "Rem", "DPe", "RNC", "Pd2", "Cot") AndAlso Not CveEstatus.Contiene(4, 5, 10, 12, 13, 20, 23) Then If UsuarioActual.TienePermisoProceso(159) Then Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) If TienePermiso <> "" Then LbCancelarDocumento.Visible = True 'If UsuarioActual.CveEmpresa = 119 And Not UsuarioActual.CveUsuario.Contiene(100, 1703) Then '[IPP] AD y Jesus de JAM ' 'si es del mes anterior no permita cancelar ' If Not DdlTipoComprobante.SelectedValue.Contiene("Rem") Then ' If DbRowVenta("Fecha").ToString().ToDate <= Now.AddMonths(-1).LastDayOfMonth Then ' LbCancelarDocumento.Visible = False ' End If ' End If 'End If End If End If End If Dim TipoEstatus As Integer = GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {CveEstatus}").ToEntero() If UsuarioActual.Empresa.Funcionalidad(135).Contiene("1", "2") AndAlso DdlTipoComprobante.SelectedValue.Contiene("Cot") Then If UsuarioActual.TienePermisoProceso(116) Then LbCancelarDocumento.Visible = True If TipoEstatus = 2 Then LbCancelarDocumento.Visible = False ElseIf TipoEstatus = 5 Then LbCancelarDocumento.Visible = False End If End If End If If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso CBool(DbRowVenta("ServicioDomicilio")) Then TrServicioDomicilio.Visible = True End If If UsuarioActual.TienePermisoProceso(318) Then If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Ing", "Ant", "Dev") AndAlso String.IsNullOrEmpty(DbRowVenta("FolioFiscal").ToString.Trim) Then HplFolioFiscalModal.Visible = True End If Select Case DbRowVenta("TipoDocto").ToString() Case "Ing" Trsaldo.Visible = True HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then HLPagar.Visible = True HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675" HlCuentaTerminal.Visible = True End If CargarSaldoAuxiliar(CveCliente) TabAuxiliarConta.Visible = UsuarioActual.TienePermisoProceso(306) Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto"))) If TienePermiso <> "" Then ' si tiene acceso en el subproyecto 'LkNotaCredito.Visible = UsuarioActual.TienePermisoProceso(175) If UsuarioActual.TienePermisoProceso(264) Then InicializaAplicaDevolucion(TmpDT) End If End If HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) Case "Egs" HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString() Trsaldo.Visible = True HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) Case "Rem" 'IPP 15 Julio 2017 Trsaldo.Visible = True HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then HLPagar.Visible = True HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675" HlCuentaTerminal.Visible = True End If If UsuarioActual.CveEmpresa = 80 Then LtlImprimir.Text = String.Format("
  • Imprimir
  • ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta))) End If DiasCredito = DbRowVenta("DiasCredito").ToString().ToEntero() EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString()) Case "RNC" Trsaldo.Visible = True HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) Case "OP" TdOrdenPago.Visible = True DdlOrdenPago.SelectedValue = DbRowVenta("Num3").ToString() DdlOrdenPago.Enabled = False Case "Cot" TxtAtencionA.Text = DbRowVenta("AtencionA").ToString() TxtFechaVencimientoCotizacion.Text = DbRowVenta("Vigencia").ToString() PnlImprimir.Visible = True HLOrdendeCompra.Visible = True HLOrdendeCompra.NavigateUrl = String.Format("/OC/OC.aspx?Tipo=Req&CveCotizacion={0}", CveVenta) Dim ObjOS As New ClsOS() If ObjOS.GetCotizacionOS(CveVenta) Then If ObjOS.DtResultados.Rows.Count > 0 Then Dim DbRowOS As DataRow = ObjOS.DtResultados.Rows(0) ViewState("CveOS") = DbRowOS("CveOS").ToString().ToEntero() CargaOS(CveOS) End If Else HLOrdenServicio.Visible = True HLOrdenServicio.NavigateUrl = String.Format("/OS/OrdenesServicios.aspx?CveCotizacion={0}", CveVenta) End If ObjOS.Dispose() If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 145) Then PnlImprimir.Visible = True : LnkImprimir.OnClientClick = "javascript:ImprimirCotizacion();return false;" 'Deshabilitar impresión cuando no esté supervisada If DbRowVenta("TipoEstatus").ToString().ToEntero() = 2 Or UsuarioActual.Empresa.Funcionalidad(113) = "1" Then PnlImprimir.Visible = True Else HplDownPDF.Visible = False PnlImprimir.Visible = False End If 'SI LA AUTORIZACION ES POR SUPERVISOR, BUSCA EL SUPERVISOR QUE TIENE EL VENDEDOR If UsuarioActual.Empresa.Funcionalidad(135) = "1" Then 'Reviso cuales son los supervisores Dim Objeto As New ClsVtaVendedores If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then Dim DTVendedores As New DataTable If DbRowVenta("CveVendedor").ToString().ToEntero() > 0 AndAlso UsuarioActual.CveVendedor > 0 Then DTVendedores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString())).FiltraParametros(String.Format("CveSupervisor = {0}", UsuarioActual.CveVendedor)) End If 'Verifico si es su supervisor asignado If DTVendedores.Rows.Count > 0 Then LkCotizacionAutorizar.Visible = True If TipoEstatus = 2 Then LkCotizacionAutorizar.Visible = False ElseIf TipoEstatus = 5 Then LkCotizacionAutorizar.Visible = False End If End If DTVendedores.Dispose() End If Objeto.Dispose() End If 'SI LA AUTORIZACION ES POR PERMISO, BUSCA QUE EL USUARIO TENGA EL PERMISO PARA AUTORIZAR If UsuarioActual.Empresa.Funcionalidad(135) = "2" Then 'Reviso cuales son los supervisores If UsuarioActual.TienePermisoProceso(116) Then LkCotizacionAutorizar.Visible = True If TipoEstatus = 2 Then LkCotizacionAutorizar.Visible = False ElseIf TipoEstatus = 5 Then LkCotizacionAutorizar.Visible = False End If End If End If Case "Ant" Trsaldo.Visible = True HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) 'LkNotaCredito.Visible = True HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) 'visualizo el saldo de anticipos, para cuando se aplique una Nota de crédito, decida si afecta anticipos o a DSV LblNCSaldoAnticipo.Visible = True ChkAplicaNCAnticipo.Visible = True ChkAplicaNCAnticipo.Checked = True If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then HLPagar.Visible = True HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675" HlCuentaTerminal.Visible = True End If Me.SaldoAnticipo = DbRowVenta("SaldoAnticipo").ToString().ToDecimal If SaldoAnticipo > 0 Then InicializaDTAnticiposAmortizacion() ChkAplicaNCAnticipo.Enabled = False Else ChkAplicaNCAnticipo.Enabled = False ChkAplicaNCAnticipo.Checked = False End If 'If DbRowVenta("SaldoAnticipo").ToString().ToDouble <= 0 Then ChkAplicaNCAnticipo.Checked = False : ChkAplicaNCAnticipo.Enabled = False LblNCSaldoAnticipo.Text = String.Format("Saldo Anticipo: $ {0}", DbRowVenta("SaldoAnticipo").ToString().ToDouble.FormatoNumero) Case "Dev" DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto")))) HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString() 'ViewState("CveDevolucion") = DbRowVenta("CveVentaPadre").ToString().ToEntero() Trsaldo.Visible = True HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta")) Case "Ped" DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped")) Case "DPe" DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe")) Case "PeC" DdlTipoComprobante.Items.Insert(5, New ListItem("Pedido de Consignación", "PeC")) Case "PA" If UsuarioActual.TienePermisoProceso(199) Then BtnGenerarRemision.Visible = If(CveEstatus = 16, True, False) Else BtnGenerarRemision.Visible = False End If CvePedidoA = CveVenta DiasCredito = DbRowVenta("DiasCredito").ToString().ToEntero() EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString()) Case "Pd2" CvePedido2 = CveVenta BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False) If UsuarioActual.TienePermisoProceso(199) Then BtnGenerarRemision.Visible = If(CveEstatus <> 21, True, False) Else BtnGenerarRemision.Visible = False End If End Select DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString() End If DdlTipoRelacionARelacionar.SelectedValueExist(DbRowVenta("CveTipoRelacion").ToString()) 'contado 0, credito 1, terminal 2 If DbRowVenta("CondicionesPago").ToString().ToEntero() = 1 Then RBLPago.SelectedValue = "1" RBLPago_SelectedIndexChanged(Nothing, Nothing) UPCondicionesPago.Update() ElseIf DbRowVenta("CondicionesPago").ToString().ToEntero() = 0 Then RBLPago.SelectedValue = "2" RBLPago.Items(0).Enabled = False RBLPago_SelectedIndexChanged(Nothing, Nothing) UPCondicionesPago.Update() Else DdlCuentasTerminal.SelectedValue = DbRowVenta("CveCuentaTerminal").ToString() RBLPago.SelectedValue = "3" RBLPago.Items(0).Enabled = False RBLPago_SelectedIndexChanged(Nothing, Nothing) UPCondicionesPago.Update() End If 'ESCONDE ACCIONES LnkRemisiones.Visible = False LnkPedido2SinFacturar.Visible = False LnkCotizaciones.Visible = False LnkOCs.Visible = False UpnTools.Update() DivEstatusFac.Visible = True HdnCveCliente.Value = CveCliente.ToString() ViewState("CveCliente") = CveCliente ViewState("CveEmpresaCRM") = DbRowVenta("CveEmpresaCRM").ToString().ToEntero() ViewState("CveAcercamientoCRM") = DbRowVenta("CveAcercamientoCRM").ToString().ToEntero() Entrega = DbRowVenta("Entrega").ToString() Vigencia = DbRowVenta("Vigencia").ToString().ToDate.ToShortDateString HplSaldoAuxiliar.Text = DbRowVenta("Saldo").ToString().FormatoNumero(2) If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then HplSaldoAuxiliar.Visible = False HplPagado.Visible = True Dim EsCancelado = GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {CveEstatus}").ToEntero() = 5 If EsCancelado Then HplPagado.Text = "CANCELADO" End If If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString().ToEntero() > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then ImgAntiPend.Visible = True Else ImgAntiPend.Visible = False End If End If HdnPagado.Value = DbRowVenta("Pagado").ToString() TxtTotal.Text = DbRowVenta("Total").ToString().FormatoNumero(2) HdnVentaSaldo.Value = (SaldoVenta).ToString() CvePrePoliza = DbRowVenta("CvePrePoliza").ToString().ToEntero() CveVentaFacturada = DbRowVenta("CveVentaFacturada").ToString().ToEntero() CveVentaRelacion = DbRowVenta("CveVentaRelacion").ToString().ToEntero() ImporteRelacion = DbRowVenta("ImporteRelacion").ToString().ToDouble DdlMoneda.SelectedValue = DbRowVenta("CveMoneda").ToString() CambiaMoneda() If DbRowVenta("TipoDocto").ToString() = "Pd2" Then 'CANTIDAD FACTURADA If TmpDT.SUM("CantidadFacturadaPed2") > 0 Then GvPS.Columns(7).Visible = True ThCantidadFacturada.Visible = True ThCantidadFacturada2.Visible = True Else GvPS.Columns(7).Visible = False ThCantidadFacturada.Visible = False ThCantidadFacturada2.Visible = False End If ''ACTIVA EDITAR ''SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA 'If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString().ToEntero() Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero()) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") ' BtnPermisoEditarCotizacion.Visible = True 'End If 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR 'If TmpDT.SUM("CantidadFacturadaPed2") < TmpDT.SUM("Cantidad") Then ' BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) ' BtnsFacturar.Visible = True 'End If ElseIf DbRowVenta("TipoDocto").ToString() = "Cot" AndAlso CveCotizacion > 0 Then CveEstatusCotizacion = DbRowVenta("CveEstatusFactura").ToString().ToEntero() End If If CveEmpresaCRM > 0 And Not CveCliente > 0 Then CargaEmpresaCRM(CveEmpresaCRM) Else CveEmpresaCRM = IIf(CveEmpresaCRM > 0, CveEmpresaCRM, 0).ToString().ToEntero() CargaCliente(CveCliente, -1) 'Estatus activo, se requiere para cargar una factura en la que el cliente a sido eliminado End If ViewState("CveAlmacenTransitorio") = DbRowVenta("CveAlmacenTraspasoDestino").ToString().ToEntero() DevolucionAlmacen = DbRowVenta("EsDevolucionVenta").ToString().ToEntero() 'sino esta cargada la información del metodo de pago que le corresponde, la recarga para que se le pueda asignar If DdlMetodoPago33.SelectedValue <> DbRowVenta("CveMetodoPago33").ToString() Then CargaFormaPago(DbRowVenta("CveMetodoPago33").ToString().ToEntero()) End If DdlMetodoPago33.SelectedValueExist(DbRowVenta("CveMetodoPago33").ToString()) DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString().ToEntero()) Me.CveMetodoPago33Venta = DbRowVenta("CveMetodoPago33").ToString().ToEntero() Me.CveFormaPago33Venta = DbRowVenta("CveFormaPago33").ToString().ToEntero() Me.CveVendedorVenta = DbRowVenta("CveVendedor").ToString().ToEntero() 'SI YA TIENE UN VALOR ASIGNADO SELECCIONA EL GUARDADO 'If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso Me.CveVenta > 0 AndAlso Me.CveVendedorVenta > 0 Then ' Dim Vendedor = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=1).FiltroPrimeroValor("Vendedor", String.Format("CveVendedor = {0}", Me.CveVendedorVenta)) ' 'SI NO ENCUENTRA BUSCA EN LOS VENDEDORES DEL PV ' If String.IsNullOrEmpty(Vendedor) Then ' Vendedor = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=4).FiltroPrimeroValor("Vendedor", String.Format("CveVendedor = {0}", Me.CveVendedorVenta)) ' End If ' DdlVendedor.SelectedValueExistInsert(Me.CveVendedorVenta, Vendedor) 'End If If DdlFormaPago33.SelectedValue <> DbRowVenta("CveFormaPago33").ToString() And DbRowVenta("CveFormaPago33").ToString() <> "" Then 'sino está seleccionada la asginada la debe de cargar Dim Nombre As String = GlobalDTVtaFormaPago().FiltroPrimeroValor("FormaPagoSAT", String.Format("CveFormaPago={0}", DbRowVenta("CveFormaPago33"))) DdlFormaPago33.Items.Add(New ListItem(Nombre, DbRowVenta("CveFormaPago33").ToString())) DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString().ToEntero()) End If If DbRowVenta("CveUsoCFDI").ToString().ToEntero() > 0 Then Dim UsoCFDI As String = GlobalDTSATUsosCFDI().FiltroPrimeroValor("UsoCFDIDescripcion", $"CveUsoCFDI={DbRowVenta("CveUsoCFDI").ToString()}") DdlUsoCFDI.SelectedValueExistInsert(DbRowVenta("CveUsoCFDI").ToString(), UsoCFDI) End If If UsuarioActual.CveEmpresa = 126 Then CargaOrdenProduccion(2, CveVenta) If DbRowVenta("CveTipoRelacion").ToString().ToEntero() > 0 Then TrTipoRelacion.Visible = True DdlTiposRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion").ToString().ToEntero()) 'RELACIONAR ANTICIPOS APLICADOS If DbRowVenta("CveTipoRelacion").ToString().ToEntero() = 7 AndAlso DtAntRelacionados IsNot Nothing AndAlso DtAntRelacionados.Rows.Count > 0 Then DdlTipoRelacionAnticipo.SelectedValueExist(7) ListaAnticiposAplicados = New List(Of MAnticipoRelacionado)() For Each RowAnt As DataRow In DtAntRelacionados.Rows ListaAnticiposAplicados.Add(New MAnticipoRelacionado() With {.CveVenta = RowAnt("CveVentaRelacionada").ToString().ToEntero(), .FolioFiscal = RowAnt("FolioFiscal").ToString()}) Next Else HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString() End If End If If DbRowVenta("Saldo").ToString().ToDouble < 0.01 Then If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString().ToEntero() > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then ImgAntiPend.Visible = True Else ImgAntiPend.Visible = False End If ElseIf Opcion <> "Op" Then ImgAntiPend.Visible = True End If If UsuarioActual.CveRol.Contiene(1, 1155) Then LiLnkGuias.Visible = True LiComplementoPago.Visible = True ViewState("FolioFiscal") = DbRowVenta("FolioFiscal").ToString() SerieVenta = DbRowVenta("Serie").ToString() LblSerie.Text = SerieVenta ViewState("Serie") = DbRowVenta("Serie").ToString() ViewState("Folio") = DbRowVenta("Folio").ToString().ToEntero() TxtFolio.Text = DbRowVenta("Folio").ToString() 'TxtDocto.Text = DbRowVenta("Ref").ToString() 'TxtNumCtaPago.Text = DbRowVenta("NumeroCuenta").ToString() LblFolioFiscal.Text = DbRowVenta("FolioFiscal").ToString() TxtFecha.Text = DbRowVenta("Fecha").ToString() TxtSubTotal.Text = DbRowVenta("SubTotal").ToString().FormatoNumero(2) LblDescuentos.Text = DbRowVenta("Descuento").ToString().FormatoNumero(2) LblAmortizacion.Text = DbRowVenta("Amortizacion").ToString().FormatoNumero(2) TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) TxtIVA.Text = DbRowVenta("IVA").ToString().FormatoNumero(2) TxtRetIVA.Text = DbRowVenta("RetIVA").ToString().FormatoNumero(2) TxtCorreoNotificaciones.Text = DbRowVenta("CorreoNotificacion").ToString() If TxtRetIVA.Text.ToDecimal() > 0 Then TrRetIVA.Style.Add("display", "") UsuarioActual.Empresa.MostrarRetIVA = True If DdlTipoRetencion.SelectedValue.ToEntero() > 0 Then DdlTipoRetencion.Visible = True End If If TmpDT IsNot Nothing Then Dim PorcentajeRetIVA = (TmpDT.MAX("PorcentajeRetIVA").ToDecimal() * 100) LblRetIVA.Text = PorcentajeRetIVA.FormatoNumero(2) End If End If TxtRetISR.Text = DbRowVenta("RetISR").ToString().FormatoNumero(2) TxtIEPS.Text = DbRowVenta("IEPS").ToString().FormatoNumero(2) TrIEPS.Visible = TxtIEPS.Text.ToDouble > 0 TxtTotal.Text = DbRowVenta("Total").ToString().FormatoNumero(2) HdnTotalVenta.Value = DbRowVenta("Total").ToString().FormatoNumero(2) TxtMotivoDescuento.Text = DbRowVenta("MotivoDescuento").ToString() TxtObsFact.Text = DbRowVenta("Observaciones").ToString() LblUsuario.Text = DbRowVenta("Nombre").ToString() LblFechaRegistro.Text = DbRowVenta("FechaIng").ToString().ToDate.ToShortDateString LblSeTimbro.Text = DbRowVenta("SeTimbro").ToString() LblMail.Text = DbRowVenta("EnvioMail").ToString() TxtFechaPago.Text = DbRowVenta("FechaVencimiento").ToString() TxtFechaVencimientoCotizacion.Text = Vigencia TxtDet_OrdenCompra.Text = DbRowVenta("Det_OrdenCompra").ToString() TxtDet_FechaOrdenCompra.Text = DbRowVenta("Det_FechaOrdenCompra").ToString() HdnIVAOriginal.Value = TxtIVA.Text TxtPedidoContrato.Text = DbRowVenta("PedidoContrato").ToString() TxtPedidoContrato.Enabled = False TxtKilometraje.Text = DbRowVenta("Kilometraje").ToString().PadLeft(6, "0"c) VentaActual = New Venta VentaActual.CveVenta = CveVenta VentaActual.Fecha = DbRowVenta("Fecha").ToString.ToDate VentaActual.CveCliente = DbRowVenta("CveCliente").ToString.ToEntero VentaActual.CveMoneda = DbRowVenta("CveMoneda").ToString.ToEntero VentaActual.SerieFolio = DbRowVenta("SerieFolio").ToString VentaActual.ClienteNombre = DbRowVenta("ClienteNombre").ToString VentaActual.TC = DbRowVenta("TipoCambio").ToString.ToDecimal VentaActual.Total = DbRowVenta("Total").ToString.ToDecimal VentaActual.IVA = DbRowVenta("IVA").ToString.ToDecimal VentaActual.IEPS = DbRowVenta("IEPS").ToString.ToDecimal VentaActual.RetIVA = DbRowVenta("RetIVA").ToString.ToDecimal VentaActual.RetISR = DbRowVenta("RetISR").ToString.ToDecimal VentaActual.PorcentajeIVA = DbRowVenta("PorcentajeIVA").ToString.ToDecimal VentaActual.UsuarioActual = UsuarioActual VentaActual.CveSubProyecto = DbRowVenta("CveSubProyecto").ToString.ToEntero If CveEmpresaCRM > 0 Then VentaActual.IdCtaContableCliente = -1 VentaActual.IdCtaContableClienteComplementaria = -1 VentaActual.IdCtaContableClienteAnticipo = -1 VentaActual.IdCtaContableClienteAnticipoExtranjera = -1 VentaActual.IdCtaContableClienteAnticipoComplementaria = -1 Else VentaActual.IdCtaContableCliente = IIf(VentaActual.CveMoneda = 1, ViewState("IdCtaContClientes"), ViewState("IdCtaContMonedaExtranjera")).ToString.ToEntero VentaActual.IdCtaContableClienteComplementaria = ViewState("IdCtaContComplementaria").ToString.ToEntero VentaActual.IdCtaContableClienteAnticipo = ViewState("IdCtaContAnticipos").ToString.ToEntero VentaActual.IdCtaContableClienteAnticipoExtranjera = ViewState("IdCtaContAnticiposExtranjera").ToString.ToEntero VentaActual.IdCtaContableClienteAnticipoComplementaria = ViewState("IdCtaContAnticiposComplementaria").ToString.ToEntero End If HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString() HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) 'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString() 'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString() = "True" DdlTipoAmortizacionAnticipo.SelectedValueExist(DbRowVenta("CveTipoAmortizacionAnticipo")) DdlTiposRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion")) 'Si es AMORTIZACIÓN ANTICIPO SOBRE FACTURA EN CERO no debe timbrar If DbRowVenta("CveTipoAmortizacionAnticipo").ToString().ToEntero() = 3 Then BtnEmitir.Visible = False End If 'HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString() 'HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) 'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString() 'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString() = "True" If DbRowVenta("CveTipoRelacion").ToString().ToEntero() > 0 Then TrTipoRelacion2.Visible = True LblTipoRelacion.Text = DbRowVenta("TipoRelacion").ToString() HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString() End If TxtOrdenCompra.Text = DbRowVenta("OrdenCompra").ToString() TxtOrdenCompra.Enabled = False TxtObsAlmacen.Text = DbRowVenta("ObservacionesAlmacen").ToString() CvePAC = DbRowVenta("CvePAC").ToString().ToEntero() If DbRowVenta("Saldo").ToString().ToDecimal > 0 AndAlso UsuarioActual.TienePermisoProceso(204) AndAlso Not UsuarioActual.CveEmpresa.Contiene(119) Then TxtFechaSaldarVenta.Text = TxtFecha.Text CEFechaSaldarVenta.StartDate = TxtFecha.Text.ToDate HLSaldarVenta.Visible = True End If If (UsuarioActual.TienePermisoProceso(166) Or UsuarioActual.CveRol = 1) AndAlso (LblFolioFiscal.Text = "" Or LblFolioFiscal.Text = "test") Then LkEliminarFactura.Visible = True End If If (UsuarioActual.CveRol = 1) AndAlso (LblFolioFiscal.Text <> "") Then LnkUUIDRelacionados.Visible = True End If 'Envio Direccion If DbRowVenta("CveDireccionEnvio").ToString().ToEntero() > 0 AndAlso DbRowVenta("CveDireccionEnvio").ToString() IsNot Nothing Then ChkDireccionEnvio.Checked = True DdlDireccionEnvio.SelectedValueExist(DbRowVenta("CveDireccionEnvio").ToString().ToEntero()) 'DdlDireccionEnvio_SelectedIndexChanged(DdlDireccionEnvio, EventArgs.Empty) DdlDireccionEnvio.Enabled = False ChkDireccionEnvio.Enabled = False DdlDireccionEnvio.Visible = True trDireccionEnvio.Visible = True End If If UsuarioActual.TienePermisoProceso(333) Then LnkEditarDir.Visible = True 'ESTATUS FACTURA If Not (CveRemision > 0 Or CveCotizacion > 0) Then CveEstatus = DbRowVenta("CveEstatusFactura").ToString().ToEntero() End If TxtTipoCambio.Text = DbRowVenta("TipoCambio").ToString() If DbRowVenta("UltimasFluctuaciones").ToString() <> "" Then LblTCValuacion.Text = String.Format("Ult. Val:{0}", DbRowVenta("UltimasFluctuaciones").ToString()) LblTCValuacion.Visible = True End If ViewState("SelloCancelacion") = DbRowVenta("SelloCancelacion").ToString() ViewState("FechaCancelacion") = DbRowVenta("FechaCancelacion").ToString().ToDateTime TxtAtencionA.Text = DbRowVenta("AtencionA").ToString() TxtTelefonoGenerico.Text = DbRowVenta("TelefonoGenerico").ToString() CveVentaPadre = DbRowVenta("CveVentaPadre").ToString().ToEntero() SerieFolioPadre = DbRowVenta("SerieFolioPadre").ToString() If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If If CveVentaPadre > 0 Then If IsNothing(Request("CveDevolucion")) AndAlso IsNumeric(Request("CveDevolucion")) Then DdlNCFactura.Visible = True Else DdlNCFactura.Visible = False End If trNCFactura.Visible = True LblSerieFolioPadre.Visible = True LblSerieFolioPadre.Text = String.Format("{1}", CveVentaPadre, SerieFolioPadre) End If TxtFechaEjecucion.Text = DbRowVenta("FechaEjecucion").ToString().ToDateTime.ToString("dd/MM/yyyy") 'DdlSucursalEjecucion.SelectedValueExist(DbRowVenta("CveSucursalEjecucion").ToString()) 'DdlSucursalCobranza.SelectedValueExist(DbRowVenta("CveSucursalCobranza").ToString()) DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").ToString()) 'DdlSucursal.SelectedValueExist(DbRowVenta("CveSucursal").ToString()) 'DdlSubProyectoDatos.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString()) If DdlSubProyectoDatos.Items.Count = 0 Then DdlSubProyectoDatos.Items.Insert(0, New ListItem("Seleccione", "-1")) End If DdlSubProyectoDatos.SelectedValueExistInsert(DbRowVenta("CveSubProyecto").ToString(), DbRowVenta("SubProyecto").ToString()) DdlSubProyecto.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString()) CargarAlmacenes() If DdlSubProyectoCobranza.Items.Count = 0 Then DdlSubProyectoCobranza.Items.Insert(0, New ListItem("Seleccione", "-1")) End If DdlSubProyectoCobranza.SelectedValueExistInsert(DbRowVenta("CveSubProyectoCobranza").ToString(), GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoCobranza").ToString().ToEntero()).FiltroPrimeroValor("SubProyecto").ToString()) If DdlSubProyectoEjecucion.Items.Count = 0 Then DdlSubProyectoEjecucion.Items.Insert(0, New ListItem("Seleccione", "-1")) End If DdlSubProyectoEjecucion.SelectedValueExistInsert(DbRowVenta("CveSubProyectoEjecucion").ToString(), GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoEjecucion").ToString().ToEntero()).FiltroPrimeroValor("SubProyecto").ToString()) CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString().ToEntero()) If DbRowVenta("CveContrato").ToString().ToEntero() > 0 Then CveContrato = DbRowVenta("CveContrato").ToString().ToEntero() NumeroContrato = DbRowVenta("NumeroContrato").ToString() DescripcionContrato = DbRowVenta("DescripcionContrato").ToString() DdlContrato.Visible = False HLContrato.Text = $"{DbRowVenta("NumeroContrato")} - {DbRowVenta("DescripcionContrato")}" HLContrato.NavigateUrl = $"/Contratos/Contrato.aspx?CveContrato={CveContrato}" 'trPresupuesto.Visible = True 'HplPresupuesto.NavigateUrl = String.Format(" / Presupuestos / Presupuesto.aspx?CvePresupuesto={0}", DbRowVenta("CveContrato").ToString()) Else NumeroContrato = "" DescripcionContrato = "" End If 'DdlEstatus.Items.Remove(DdlEstatus.Items.FindByText("Cotización")) If DbRowVenta("SeTimbro").ToString() <> "No" Then HplDownXML.Visible = True 'If HLImprimir.Visible = False Then HplDownPDF.Visible = True 'End If ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" OrElse DdlTipoComprobante.SelectedValue = "Cot" Then 'If drv("TipoEstatus").ToString().ToEntero() = 2 AndAlso drv("TipoDocto").ToString() = "Cot" Then ' ImgDownPDF.Visible = True 'Else HplDownPDF.Visible = False 'End If ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso DbRowVenta("SeTimbro").ToString() = "No" AndAlso DbRowVenta("CveEstatusFactura").ToString() = "2" AndAlso DbRowVenta("TipoDocto").ToString().Contiene("Ing", "Egs", "Dev", "Ant") Then TrEmitir.Visible = True If TxtFecha.Text.ToDate < Now.AddDays(-3) Then TxtFecha.Enabled = True End If End If 'NO DEBE IMPRIMIR PDF DE COTIZACION If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DbRowVenta("TipoDocto").ToString() = "Cot" Then HplDownPDF.Visible = False End If If DbRowVenta("SeTimbro").ToString() = "Si" Then TrEmitir.Visible = False End If 'CargaAcuseCancelacion If DbRowVenta("CveEstatusFactura").ToString().Contiene("5", "20") Then ImgDownCancelacion.Visible = True ImgDownCancelacion.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CAN&CVEVTA={0}", CveVenta))) End If IdPoliza = DbRowVenta("IdPoliza").ToString().ToEntero() 'Carga si es Contabilizada If IdPoliza > 0 Then HLContabilizada.Text = "Si" HLContabilizada.NavigateUrl = $"/Contabilidad/RegPoliza.aspx?IdPoliza={DbRowVenta("IdPoliza")}" trContabilizada.Visible = True If UsuarioActual.TienePermisoProceso(107) Then BtnDescontabilizar.Visible = True Else 'cuando no este contabilizada y usa AC, habilita el boton para generar la poliza If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC AndAlso UsuarioActual.CveRol = 1 Then BtnGenerarPoliza.Visible = True End If If UsuarioActual.Empresa.Funcionalidad(200) = "1" Then BtnContabilizar.Visible = True End If End If If DbRowVenta("IdPolizaCancelacion").ToString().ToEntero() > 0 Then HPLContaCancelacion.Text = "Cancelación" HPLContaCancelacion.NavigateUrl = String.Format("/Contabilidad/RegPoliza.aspx?IdPoliza={0}", DbRowVenta("IdPolizaCancelacion")) trContabilizada.Visible = True End If If UsuarioActual.Empresa.UsaOS AndAlso DbRowVenta("CveOS").ToString().ToEntero() = 0 Then BtnGenerarOS.Visible = True BtnGenerarOS.OnClientClick = String.Format("javascriptwindow.location.href = '/OS/OrdenesServicios.aspx?CveVenta={0}'; return false;", CveVenta) ' BtnGenerarOS.OnClientClick = String.Format("/OS/OrdenesServicios.aspx?CveVenta={0}", CveVenta) End If '[IPP] COMENTADO 12/MARZO/2018 -SABRA QUE SE QUERIA ESCONDER 'If DbRowVenta("TipoDocto").ToString() = "Rem" Then ' GvPS.Columns(11).Visible = False ' GvPS.Columns(12).Visible = False 'End If 'Ocultamos los botones Clonar y Ordenar GvPS.Columns(19).Visible = False GvPS.Columns(20).Visible = False GvFirmas.DataSource = DTmpF GvFirmas.DataBind() If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then TrOtros.Visible = True GvImpuestosLocales2.DataSource = TmpDTImpuestos GvImpuestosLocales2.DataBind() GvImpuestosLocales2.Enabled = False GvImpuestosLocales2.Visible = True End If DdlVendedor.SelectedValue = If(DbRowVenta("CveVendedor").ToString = "", "0", DbRowVenta("CveVendedor").ToString) 'si viene dbnull, que ponga cero. DdlTipoComprobante.Enabled = False 'TxtDocto.Enabled = False 'PORLET CLIENTE 'DESACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto disabled") TxtCodigo.ReadOnly = True ChkEnviarFactura.Enabled = False ChkDireccionEnvio.Enabled = False TxtAtencionA.Enabled = False TxtFechaVencimientoCotizacion.Enabled = False TxtCantidad.Enabled = False DdlClasificacion.Enabled = False DdlPS.Enabled = False TxtObsPS.Enabled = False DdlProyecto.Enabled = False DdlSubProyecto.Enabled = False TxtPrecio.Enabled = False ImgDescPU.Attributes.Clear() ImgDescTotal.Attributes.Clear() ImgDescConcepto.Attributes.Clear() LbAgregar.Enabled = False LnkAgregarPyME.Enabled = False DdlCuentasTerminal.Enabled = False For Each Row As GridViewRow In GvPS.Rows Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString() Next GvPS.Columns(ColumnaEditar).HeaderText = "" GvPS.Columns(ColumnaEliminar).HeaderText = "" 'GvPS.Columns(ColumnaEliminar).Visible = False TxtObsFact.Enabled = False TxtObsAlmacen.Enabled = False TxtMotivoDescuento.Enabled = False 'GvLeyendasFiscales.Enabled = False TxtSubTotal.ReadOnly = True TxtIVA.ReadOnly = True TxtRetIVA.ReadOnly = True TxtRetISR.ReadOnly = True TxtIEPS.ReadOnly = True TxtTotal.ReadOnly = True 'Sección Detalle DdlMoneda.Enabled = False DdlTipoRetencion.Enabled = False TxtFechaEjecucion.ReadOnly = True ImgCalendarFechaEje.Enabled = False 'DdlSucursalEjecucion.Enabled = False 'DdlSucursalCobranza.Enabled = False DdlVendedor.Enabled = False DdlSucursalCliente.Enabled = False TxtTiempoEntrega.Enabled = False TxtAlfa1.ReadOnly = True TxtAlfa2.ReadOnly = True TxtAlfa3.ReadOnly = True TxtNum1.ReadOnly = True TxtNum2.ReadOnly = True TxtNum3.ReadOnly = True TxtFech1.ReadOnly = True : ImgFech1.Enabled = False TxtFech2.ReadOnly = True : ImgFech2.Enabled = False TxtFech3.ReadOnly = True : ImgFech3.Enabled = False ChkConvertirDoctoPesos.Enabled = False ChkConvertirDolares.Enabled = False TxtTipoCambio.Enabled = UsuarioActual.CveEmpresa.Contiene(13, 83) TxtTipoCambioDlls.Enabled = UsuarioActual.CveEmpresa.Contiene(13, 83) TxtTipoCambio.ReadOnly = Not UsuarioActual.CveEmpresa.Contiene(13, 83) TxtTipoCambioDlls.ReadOnly = Not UsuarioActual.CveEmpresa.Contiene(13, 83) 'Condiciones de Pago RBLPago.Enabled = False DdlFormaPago33.Enabled = False DdlUsoCFDI.Enabled = False DdlMetodoPago33.Enabled = False 'TxtNumCtaPago.Enabled = False If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "Cot") Then TxtFechaPago.ReadOnly = Not UsuarioActual.TienePermisoProceso(260) LnkUpdateFechaVencimiento.Visible = UsuarioActual.TienePermisoProceso(260) Else TxtFechaPago.ReadOnly = False End If imgCalendario.Enabled = False DdlFuenteRecaudacion.Enabled = False TrVistaPrevia.Visible = False BtnEmitirImprimir.Visible = False 'CargaLeyendasFiscales ViewState("VentaFolio") = If(LblSerie.Text.Trim.Length = 0, TxtFolio.Text.Trim, LblSerie.Text.Trim & "-" & TxtFolio.Text.Trim) CalculaTotalesVenta(False) 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") If DbRowVenta("TipoDocto").ToString() = "Rem" Then 'CANTIDAD FACTURADA If TmpDT.SUM("CantidadFacturadaRem") > 0 Then GvPS.Columns(6).Visible = True ThCantidadFacturadaRem.Visible = True ThCantidadFacturadaRem2.Visible = True Else GvPS.Columns(6).Visible = False ThCantidadFacturadaRem.Visible = False ThCantidadFacturadaRem2.Visible = False End If 'ACTIVA EDITAR 'SOLO LA PUEDE EDITAR CON PROCESO | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR If UsuarioActual.TienePermisoProceso(202) And TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then BtnPermisoEditarRemision.Visible = True End If 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR If TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then BtnsFacturar.Visible = True LBFacturarAnticipo.Visible = UsuarioActual.TienePermisoProceso(274) 'ACTIVA CONVERSION DE MONEDA If DdlMoneda.SelectedValue.ToEntero() = 1 Then TrConversionDolares.Visible = True ChkConvertirDolares.Enabled = Not UsuarioActual.TienePermisoProceso(324) TxtTipoCambioDlls.Enabled = True Else TrConversionTipoCambio.Visible = True ChkConvertirDoctoPesos.Enabled = Not UsuarioActual.TienePermisoProceso(324) TxtTipoCambio.Enabled = True End If End If 'Si es Empresa de Acumuladores If CveVenta > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DbRowVenta("TipoDocto").ToString() = "Rem" AndAlso (GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.CveEstatus}").ToEntero() <> 5) Then BtnsFacturar.Visible = False Dim DtUsadosPendientes As DataTable = Nothing Dim DtGarantiasPendientes As DataTable = Nothing Dim ObjUsados As New ClsVentas If ObjUsados.GetVentasUsados(CveVenta, -1, DbRowVenta("Fecha").ToString().ToDateTime, UsuarioActual.CveEmpresa) Then DtUsadosPendientes = ObjUsados.DtResultados.Copy() End If If ObjUsados.GetVentasGarantiaPendiente(CveVenta, Now, UsuarioActual.CveEmpresa) Then DtGarantiasPendientes = ObjUsados.DtResultados.Copy() End If 'If ObjUsados.GetVentasGarantiaPendiente(CveVenta, -1, Now, UsuarioActual.CveEmpresa) Then ' DtGarantiasPendientes = ObjUsados.DtResultados.Copy() 'End If ObjUsados.Dispose() 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 OrElse TmpDT.MAX("CveTipoPS") = "1" Then BtnsFacturar.Visible = True End If 'VERIFICA SI YA SE FACTURO COMPLETAMENTE If TmpDT.SUM("CantidadFacturadaRem") = TmpDT.SUM("Cantidad") Then BtnsFacturar.Visible = False End If 'VERIFICA SI TIENE USADOS O GARANTIAS PENDIENTES If BtnsFacturar.Visible Then If (Not EsGarantia AndAlso (DtUsadosPendientes IsNot Nothing AndAlso DtUsadosPendientes.Rows.Count > 0)) Then BtnsFacturar.Visible = False Alert("Tiene usados pendiente de recibir", TipoMensaje.MsgAdvertencia) End If If (EsGarantia AndAlso (DtGarantiasPendientes IsNot Nothing AndAlso DtGarantiasPendientes.Rows.Count > 0)) Then Alert("Tiene garantías pendientes de recibir", TipoMensaje.MsgAdvertencia) BtnsFacturar.Visible = False End If End If LBFacturarAnticipo.Visible = UsuarioActual.TienePermisoProceso(274) End If End If If DbRowVenta("TipoDocto").ToString().Contiene("Cot", "Pd2") Then 'CANTIDAD FACTURADA If TmpDT.SUM("CantidadFacturadaCot") > 0 Then GvPS.Columns(7).Visible = True ThCantidadFacturada.Visible = True ThCantidadFacturada2.Visible = True Else GvPS.Columns(7).Visible = False ThCantidadFacturada.Visible = False ThCantidadFacturada2.Visible = False End If 'ACTIVA EDITAR 'SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString().ToEntero() Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero()) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") BtnPermisoEditarCotizacion.Visible = True End If 'SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA If UsuarioActual.TienePermisoProceso(281) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") BtnPermisoEditarCotizacion.Visible = True End If 'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR VerificarBtnFacturarCotizacion(DbRowVenta("CveVendedor").ToString().ToEntero()) End If If UsuarioActual.Empresa.Funcionalidad(280) = "1" Then RblPaqueteria.SelectedValue = If(DbRowVenta("FormaPaqueteria").ToString = "", "1", DbRowVenta("FormaPaqueteria").ToString) RblPaqueteria.Enabled = False End If If UsuarioActual.CveEmpresa = 48 Then TxtFecha.AutoPostBack = True End If CargaCodigoUnico() DdlTipoRetencion.SelectedValueExist(DbRowVenta("CveTipoRetencion").ToString()) Me.FacturarSucursal = CBool(DbRowVenta("FacturarSucursal").ToString()) If Me.FacturarSucursal Then HabilitarFacturacionSucursal() End If CargaPS(-1, DdlPS) 'Verifico si tiene la funcionalidad (135) If DdlTipoComprobante.SelectedValue = "Cot" AndAlso UsuarioActual.Empresa.Funcionalidad(135).Contiene("1", "2") Then Select Case UsuarioActual.Empresa.Funcionalidad(135) Case "1" ' POR SUPERVISOR Dim ObjVendedores As New ClsVtaVendedores If ObjVendedores.GetVendedores(UsuarioActual.CveEmpresa) Then Dim DTVendedores As New DataTable If DbRowVenta("CveVendedor").ToString().ToEntero() > 0 AndAlso UsuarioActual.CveVendedor > 0 Then DTVendedores = ObjVendedores.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString())).FiltraParametros(String.Format("CveSupervisor = {0}", UsuarioActual.CveVendedor)) End If 'Verifico si es su supervisor asignado If DTVendedores.Rows.Count > 0 Then If GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.CveEstatus}").ToEntero() = 2 Then BtnsFacturar.Visible = True BtnGenerarRemision.Visible = True Else BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False End If End If DTVendedores.Dispose() End If ObjVendedores.Dispose() Case "2" ' POR PERMISO If GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.CveEstatus}").ToEntero() = 2 Then BtnsFacturar.Visible = UsuarioActual.TienePermisoProceso(60) If UsuarioActual.TienePermisoProceso(199) Then BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) Else BtnGenerarRemision.Visible = False End If Else BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False End If End Select End If If DdlTipoComprobante.SelectedValue = "Cot" Then If GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.CveEstatus}").ToEntero() = 5 Then BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False End If End If If DdlTipoComprobante.SelectedValue = "Rem" Then If GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.CveEstatus}").ToEntero() = 5 Then BtnsFacturar.Visible = False BtnEmitirImprimir.Visible = False BtnPermisoEditarRemision.Visible = False End If End If If UsuarioActual.Empresa.Funcionalidad(705) = "1" AndAlso Me.CveLineaAdicionalVenta > 0 Then CalculaLineasAdicionales() End If UpPS.Update() UpContado.Update() UpEstatus.Update() Retorno = True End If Return Retorno End Function Private Sub VerificarBtnFacturarCotizacion(CveVendedor As Integer, Optional MostrarGenerarRemision As Boolean = True) If TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") AndAlso DdlTipoComprobante.SelectedValue.Contiene("Cot") Then If UsuarioActual.TienePermisoProceso(199) Then BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) Else BtnGenerarRemision.Visible = False End If If UsuarioActual.TienePermisoProceso(60) Then BtnsFacturar.Visible = True 'puede facturar If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso UsuarioActual.TienePermisoProceso(60) Then Select Case UsuarioActual.Empresa.Funcionalidad(135) Case "1" ' POR SUPERVISOR Dim ObjVendedores As New ClsVtaVendedores If ObjVendedores.GetVendedores(UsuarioActual.CveEmpresa) Then Dim DTVendedores As New DataTable If CveVendedor > 0 AndAlso UsuarioActual.CveVendedor > 0 Then DTVendedores = ObjVendedores.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", CveVendedor)).FiltraParametros(String.Format("CveSupervisor = {0}", UsuarioActual.CveVendedor)) End If 'Verifico si es su supervisor asignado If DTVendedores.Rows.Count > 0 Then If GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.CveEstatus}").ToEntero() = 2 Then BtnsFacturar.Visible = True If UsuarioActual.TienePermisoProceso(199) Then BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) Else BtnGenerarRemision.Visible = False End If Else BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False End If End If DTVendedores.Dispose() End If ObjVendedores.Dispose() Case "2" ' POR PERMISO If GlobalDTEstatusFactura().FiltroPrimeroValor("TipoEstatus", $"CveEstatusFactura = {Me.CveEstatus}").ToEntero() = 2 Then BtnsFacturar.Visible = UsuarioActual.TienePermisoProceso(60) If UsuarioActual.TienePermisoProceso(199) Then BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True) Else BtnGenerarRemision.Visible = False End If Else BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False End If End Select End If If BtnGenerarRemision.Visible AndAlso Not MostrarGenerarRemision Then BtnGenerarRemision.Visible = False End If LBFacturarAnticipo.Visible = UsuarioActual.TienePermisoProceso(274) 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) Then If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) 'CargaCliente Dim CveCliente As Integer = drv("CveCliente").ToString().ToEntero() HdnCveCliente.Value = CveCliente.ToString() ViewState("CveCliente") = CveCliente CargaCliente(CveCliente) 'Carga Detalle Sucursal TxtFechaEjecucion.Text = drv("FechaEjecucion").ToString().ToDateTime.ToString("dd/MM/yyyy") TxtFechaPago.Text = drv("FechaVencimiento").ToString().ToDateTime.ToString("dd/MM/yyyy") 'DdlSucursalEjecucion.SelectedValueExist(drv("CveSucursalEjecucion").ToString()) 'DdlSucursalCobranza.SelectedValueExist(drv("CveSucursalCobranza").ToString()) DdlSucursalCliente.SelectedValueExist(drv("CveClienteSucursal").ToString()) 'DdlSucursal.SelectedValueExist(drv("CveSucursal").ToString()) DdlSubProyectoDatos.SelectedValueExist(drv("CveSubProyecto").ToString()) DdlSubProyectoEjecucion.SelectedValueExist(drv("CveSubProyectoEjecucion").ToString()) DdlSubProyectoCobranza.SelectedValueExist(drv("CveSubProyectoCobranza").ToString()) If CveDevolucion > 0 Then CambiaSucursalGeneral() End If CargaClienteSucursal(drv("CveClienteSucursal").ToString().ToEntero()) 'CargaDetalle If ObjVentas.GetVentaDetalle(CveVenta) Then 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 'TmpDT = ObjVentas.DtResultados 'TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) 'TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) ''TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) 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() GvImpuestosLocales2.Enabled = False GvImpuestosLocales2.Visible = True End If End If 'Carga Totales ViewState("TipoDoctoDevolucion") = drv("TipoDocto").ToString() TxtSubTotal.Text = drv("SubTotal").ToString().FormatoNumero(2) LblDescuentos.Text = drv("Descuento").ToString().FormatoNumero(2) LblAmortizacion.Text = drv("Amortizacion").ToString().FormatoNumero(2) TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2) TxtIVA.Text = drv("IVA").ToString().FormatoNumero(2) TxtRetIVA.Text = drv("RetIVA").ToString().FormatoNumero(2) 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() TxtMotivoDescuento.Text = drv("MotivoDescuento").ToString() TxtObsFact.Text = drv("Observaciones").ToString() DdlMoneda.SelectedValue = drv("CveMoneda").ToString() CambiaMoneda() TxtTipoCambio.Text = drv("TipoCambio").ToString() DdlVendedor.SelectedValue = drv("CveVendedor").ToString() CvePAC = drv("CvePAC").ToString().ToEntero() DdlUsoCFDI.SelectedValueExist(drv("CveUsoCFDI").ToString()) DdlMetodoPago33.SelectedValueExist(drv("CveMetodoPago33").ToString()) CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) DdlFormaPago33.SelectedValueExist(drv("CveFormaPago33").ToString()) DdlTipoComprobante.SelectedValueExist(drv("TipoDocto").ToString()) DdlTipoComprobante.Enabled = False HdnIVAOriginal.Value = TxtIVA.Text HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString() HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2) 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If CveContrato = drv("CveContrato").ToString().ToEntero() TabAlmacen.Enabled = False TabDetalleVentas.Enabled = False TabComplementos.Enabled = False 'HplDownPDF.Visible = True 'HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}", CveVenta))) Updatetabs.Update() UpPS.Update() UpContado.Update() If CveDevolucion > 0 Then HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString() 'CALCULA IMPUESTOS LOCALES CON LOS DATOS DEL CLIENTE AL MOMENTO DE LA NUEVA FACTURA NO LA VIEJA 'CalculaTotalesImpuestosLocales() 'CalculaTotales(CBool(ViewState("RetIVAFletes"))) CalculaTotalesVenta() ' al hacer una refacturación que regenere los importes, sino vienen correctos ''CARGA IMPUESTOS LOCALES DE LA VENTA ANTERIOR 'If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then ' If ObjVentas.DtResultados.Rows.Count > 0 Then ' GvImpuestosLocales2.DataSource = ObjVentas.DtResultados ' GvImpuestosLocales2.DataBind() ' GvImpuestosLocales2.Enabled = False ' GvImpuestosLocales2.Visible = True ' End If 'End If 'cuando es refacturacion, la fecha de pago debe de ser la misma If UsuarioActual.Empresa.Funcionalidad(526) = "1" Then ' Dim ObjVenta As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then TxtFechaPago.Text = ObjVentas.DtResultados(0)("FechaVencimiento").ToString().ToDate.ToShortDateString End If End If 'ObjVenta.Dispose() Else TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString End If CreaObjetosVentaDevolucion() End If TabComplementos.Enabled = True End If End If If OVenta Is Nothing Then ObjVentas.Dispose() End If End Sub Private Sub CargaSucursales() If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.Enabled = False : DdlSubProyectoEjecucion.Enabled = False : DdlSubProyectoCobranza.Enabled = False End Sub Private Sub CargaMetodosPago() 'FACTURACION 3.3 DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago DdlMetodoPago33.DataBind() DdlMetodoPago33.SelectedValueExist("3") CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) 'End If End Sub Private Sub CargaFormaPago(CveMetodoPago As Integer) 'EN LA VERSION 4.0 NO PERMITE DESBLOEQUEAR RELACION METODO Y FOMA DE PAGO If UsuarioActual.Empresa.Funcionalidad(350) <> "1" Then 'permiso para desbloquear la relación entre Método de pago y forma de pago If UsuarioActual.TienePermisoProceso(282) Then CveMetodoPago = -1 End If Dim dtt As DataTable = Nothing If CveMetodoPago > 0 Then dtt = GlobalDTVtaFormaPago.FiltraParametros(If(CveMetodoPago = 1, " CveFormaPago <> 20 ", "CveFormaPago = 20")) Else dtt = GlobalDTVtaFormaPago End If DdlFormaPago33.Items.Clear() 'DdlFormaPago33.ClearSelection() 'DdlFormaPago33.DataBind() DdlFormaPago33.DataSource = dtt DdlFormaPago33.SelectedValue = dtt.FiltroPrimeroValor("CveFormaPago", "") DdlFormaPago33.DataBind() DdlFormaCliente.DataSource = GlobalDTVtaFormaPago DdlFormaCliente.DataBind() DdlMetodoCliente.DataSource = GlobalDTVtaMetodoPago DdlMetodoCliente.DataBind() 'End If End Sub Private Sub CargaUsoCFDI() If UsuarioActual.Empresa.Funcionalidad(350) <> "1" Then RegimenFiscalCliente = "-1" End If DdlUsoCFDI.Items.Clear() DdlSucursalUsoCFDI.Items.Clear() If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then 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) Else DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica, RegimenFiscalReceptor:=RegimenFiscalCliente) DdlSucursalUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica, RegimenFiscalReceptor:=RegimenFiscalCliente) End If DdlUsoCFDI.DataBind() DdlSucursalUsoCFDI.DataBind() DdlUsoCFDI.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlSucursalUsoCFDI.Items.Insert(0, New ListItem("Seleccione", "-1")) End Sub Private Sub CargaMotivosCancelacion() DdlMotivoRefacturacion.DataSource = GlobalDTMotivosCancelacionEmpresa(UsuarioActual.CveEmpresa, CveSATMotivoCancelacion:=1) DdlMotivoRefacturacion.DataBind() DdlMotivoCancelacion.DataSource = GlobalDTMotivosCancelacionEmpresa(UsuarioActual.CveEmpresa).FiltraParametros("CveSATMotivoCancelacion IN (2,3)") DdlMotivoCancelacion.DataBind() DdlMotivoRefacturacion.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlMotivoCancelacion.Items.Insert(0, New ListItem("Seleccione", "-1")) End Sub Private Sub CargaTiposRelacion() DdlTiposRelacion.DataSource = GlobalDTVtaTiposRelacion DdlTipoRelacionARelacionar.DataSource = GlobalDTVtaTiposRelacion DdlTiposRelacion.DataBind() DdlTipoRelacionARelacionar.DataBind() DdlTiposRelacion.Items.Insert(0, New ListItem("-", "-1")) DdlTipoRelacionARelacionar.Items.Insert(0, New ListItem("-", "-1")) End Sub Private Sub CargaFormaEntrega() TrFormaEntrega.Visible = True DdlFormaEntrega.DataSource = GlobalDTVtaCondicionesEntrega(UsuarioActual.CveEmpresa) DdlFormaEntrega.DataBind() DdlFormaEntrega.Items.Insert(0, New ListItem("Seleccione", "-1")) End Sub Private Sub CargaMonedas() DdlMoneda.DataSource = GlobalDTMonedas DdlMoneda.DataBind() End Sub Private Sub CargaProyecto() Dim CveSubProyecto As Integer = 0 Dim dtt As DataTable = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) DdlProyecto.DataSource = dtt DdlProyecto.DataBind() DdlProyectoPyME.DataSource = dtt DdlProyectoPyME.DataBind() CveSubProyecto = GetSubProyectoSucursal() CargaSubProyecto(CveSubProyecto) End Sub Private Function GetSubProyectoSucursal() As Integer Dim Retorno As Integer = 0 Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") 'Dim dr As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}") 'si hay un proyecto relacionado con el subproyecto If dr IsNot Nothing AndAlso dr("CveSubProyecto").ToString().ToEntero() > 0 Then DdlProyecto.SelectedValueExist(dr("CveProyecto")) Retorno = dr("CveSubProyecto").ToString().ToEntero() End If Return Retorno End Function Private Sub CargarAlmacenes() If 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) 'DdlSubProyecto.Items.Clear() 'DdlSubProyecto.SelectedValue = Nothing 'If DdlProyecto.SelectedValue.ToEntero() > 0 Then ' DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) ' 'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"}) 'End If 'DdlSubProyecto.DataBind() 'DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) If CveSubProyecto > 0 Then DdlSubProyecto.SelectedValueExist(CveSubProyecto) End Sub Private Sub CargaEmpresaCRM(CveEmpresaCRM As Integer) Dim ObjCRM As New ClsCRM If ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa, CveEmpresaCRM) Then If ObjCRM.DtResultados.Rows.Count > 0 Then ViewState("CveCliente") = IIf(ObjCRM.DtResultados.Rows(0)("CveCliente").ToString().ToEntero() > 0, ObjCRM.DtResultados.Rows(0)("CveCliente"), -1) HdnCveCliente.Value = CveCliente.ToString() If (CveCliente > 0) Then CargaCliente(CveCliente) VerificarContrato(True) 'DESACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto disabled") TxtCodigo.ReadOnly = True UpCliente.Visible = True UpEmpresaCRM.Visible = False Else LblEmpresaCRM.Text = ObjCRM.DtResultados.Rows(0)("Empresa").ToString() LblRFCCRM.Text = ObjCRM.DtResultados.Rows(0)("RFC").ToString() LblMedioCaptacionCRM.Text = ObjCRM.DtResultados.Rows(0)("MedioCaptacion").ToString() ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = False LblEnviarMail.Visible = False UPCondicionesPago.Visible = True UpCliente.Visible = False UpEmpresaCRM.Visible = True End If Me.CveVendedorEmpresaCRM = ObjCRM.DtResultados.Rows(0)("CveVendedorAsignado").ToString().ToEntero() DdlVendedor.SelectedValueExist(ObjCRM.DtResultados.Rows(0)("CveVendedorAsignado").ToString()) DdlVendedor.Enabled = False LbAgregar.Enabled = True End If End If ObjCRM.Dispose() End Sub Private Sub CargaCliente(CveCliente As Integer, Optional Estatus As Integer = -1) If CveCliente <= 0 Then Exit Sub RBLPago.Items(0).Enabled = True Dim ObjCliente As New ClsClientes() If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus, TipoCliente:=-1) Then If ObjCliente.DtResultados.Rows.Count > 0 Then TxtCodigo.Text = ObjCliente.Codigo DdlFormaEntrega.SelectedValueExist(ObjCliente.DtResultados(0)("CveCondicionEntrega").ToString()) LblCliente.Text = String.Format("{1}", CveCliente, ObjCliente.NombreComercial) ViewState("NombreCliente") = ObjCliente.Nombre LtlCliente.Text = 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 If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = False LblEnviarMail.Visible = False Else If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then 'ENVIO DE FACTURA ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True If CveVenta > 0 AndAlso EnviarCorreoCliente Then ChkEnviarFactura.Checked = EnviarCorreoCliente Else ChkEnviarFactura.Checked = EnviarCorreoCliente ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True End If End If 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("CtaContable") = ObjCliente.CuentaContable ViewState("IdCtaContClientes") = ObjCliente.IdCtaContClientes ViewState("IdCtaContMonedaExtranjera") = ObjCliente.IdCtaContMonedaExtranjera ViewState("IdCtaContComplementaria") = ObjCliente.IdCtaContComplementaria ViewState("IdCtaContAnticipos") = ObjCliente.IdCtaContAnticipos ViewState("IdCtaContAnticiposExtranjera") = ObjCliente.IdCtaMonedaExtranjeraAnticipos ViewState("IdCtaContAnticiposComplementaria") = ObjCliente.IdCtaContCompAnticipos ViewState("IdCtaContRetIVA") = ObjCliente.IdCtaContRetIVA ViewState("IdCtaContRetISR") = ObjCliente.IdCtaContRetISR 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 If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then RegimenFiscalCliente = ObjCliente.DtResultados(0)("CodigoRegimenFiscal").ToString() RegimenSociedad = ObjCliente.DtResultados(0)("RegimenSociedad").ToString() TipoPersona = CBool(ObjCliente.DtResultados(0)("TipoPersona")) CargaUsoCFDI() End If 'ViewState("NumCtaPago") = ObjCliente.NumCtaPago ViewState("ClienteDesglosaIEPS") = ObjCliente.DesglosaIEPS If Not ClienteDesglosaIEPS Then DivClienteMsg.Visible = True LtlClienteMsg.Text = "Cálculo sin desglose de IEPS" End If 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 'HABILITA LA OPCION DE DIRECCION DE ENVIO If UsuarioActual.CveEmpresa.Contiene(1, 72, 119, 140) Then trDireccionEnvio.Visible = True CargaDireccionesEnvio() End If If CveCliente = 239903 AndAlso UsuarioActual.CveEmpresa = 119 Then DdlMetodoPago33.Enabled = False 'ObjCliente.CveMetodoPago = 1 ' PUE, y que no se pueda modificar Else DdlMetodoPago33.Enabled = True End If 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 'CveMetodoPagoCliente = ObjCliente.CveMetodoPago If UsuarioActual.Empresa.Funcionalidad(589) = "1" Then 'SI EL METODO DE PAGO ES PUE, SELECCIONA CONTADO If Me.CveMetodoPago33Cliente = 1 Then RBLPago.SelectedValue = "2" ElseIf Me.CveMetodoPago33Cliente = 3 Then RBLPago.SelectedValue = "1" End If RBLPago_SelectedIndexChanged(RBLPago, Nothing) UPCondicionesPago.Update() Else DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33) CambiaMetodoPago33() DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33) End If DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI) 'SI ES RFC GENERICO NO TIENE OBLIGACIONES FISCALES If UsuarioActual.Empresa.Funcionalidad(350).Contiene("1") AndAlso 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 If UsuarioActual.CveEmpresa.Contiene(72, 80) Then TxtFechaPago.ReadOnly = True Calendario.Enabled = False imgCalendario.Visible = False End If 'funcionalidad EnviarSMSTimbrado If CveVenta <= 0 And UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue = "Ing" Then If ObjCliente.CobranzaTelefono <> "" Then LblMensaje.Text = $"Se enviará mensaje SMS a {ObjCliente.CobranzaTelefono}" Else LblMensaje.Text = $"El Cliente no tiene teléfono para envío SMS " End If LblMensaje.Visible = True End If 'If Not ObjCliente.RFC = "XAXX010101000" Then ' TxtNumCtaPago.Text = ObjCliente.NumCtaPago 'End If 'Complementos 'COMERCIO EXTERIOR ViewState("AplicaComercioExterior") = ObjCliente.AplicaComercioExterior ViewState("CveTipoOperacion") = ObjCliente.CveTipoOperacion ViewState("CvePedimento") = ObjCliente.CvePedimento ViewState("CveIncoterm") = ObjCliente.CveIncoterm LblTipoOperacion.Text = ObjCliente.ClaveSATTipoOperacionDescripcion LblClavePedimento.Text = ObjCliente.ClaveSATPedimentoDescripcion If ObjCliente.AplicaComercioExterior Then ChkEmitirComercioExterior.Checked = True End If If ObjCliente.AplicaComercioExterior Then DdlSATMotivoTraslado.DataSource = GlobalDTSATMotivoTraslado DdlSATMotivoTraslado.DataBind() DdlSATMotivoTraslado.SelectedValueExist(ObjCliente.CveMotivoTraslado) DdlIncoterm.Items.Clear() DdlIncoterm.DataSource = GlobalDTIncoterm() DdlIncoterm.DataBind() DdlIncoterm.SelectedValueExist(ObjCliente.CveIncoterm) CargaPais() DdlComExtPais.SelectedValueExist(ObjCliente.CvePais) CargaEstado() DdlComExtEstado.SelectedValueExist(ObjCliente.CveEstado) If ObjCliente.ClaveSATPais = "MEX" Then CargaMunicipio() CargaColonia() Else If ObjCliente.ClaveSATPais.Contiene("USA", "CAN") Then DdlComExtEstado.Visible = True Else TxtComExtEstado.Visible = True : DdlComExtEstado.Visible = False End If TxtComExtMunicipio.Text = ObjCliente.ComExtMunicipio TxtComExtColonia.Text = ObjCliente.ComExtColonia TxtComExtMunicipio.Visible = True : TxtComExtColonia.Visible = True End If TxtNumRegIdTrib.Text = ObjCliente.NumRegIdTrib TxtDestinatarioNombre.Text = ObjCliente.Nombre TxtComExtCalle.Text = ObjCliente.Direccion TxtComExtNumero.Text = ObjCliente.NoExt TxtComExtCP.Text = ObjCliente.CP 'en comercio exterior como regla de timbrado se utiliza el TC del día anterior TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate.AddDays(-1)).ToString() End If 'FEMSA ViewState("AplicaFEMSA") = ObjCliente.AplicaFEMSA TxtFEMSA_NumSociedad.Text = ObjCliente.FEMSA_NumSociedad TxtFEMSA_NumProveedor.Text = ObjCliente.FEMSA_NumProveedor TxtFEMSA_Mail.Text = ObjCliente.FEMSA_Mail 'DETALLISTA ViewState("AplicaDetallista") = ObjCliente.AplicaDetallista TxtDet_GLNComprador.Text = ObjCliente.Detallista_GLNComprador TxtDet_Departamento.Text = ObjCliente.Detallista_Departamento TxtDet_GLNVendedor.Text = ObjCliente.Detallista_GLNVendedor TxtDet_NumProv.Text = ObjCliente.Detallista_NumProveedor Txt7ElevenNumProveedor.Text = ObjCliente.SevenEleven_NumProveedor.Trim ViewState("AplicaFord") = ObjCliente.AplicaFord TxtFordGSDB.Text = ObjCliente.Ford_GSDB If ObjCliente.DtResultados(0)("CveVendedor").ToString().ToEntero() > 0 Then CveVendedorCliente = ObjCliente.DtResultados(0)("CveVendedor").ToString().ToEntero() End If 'SI EL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO 'If Not DdlVendedor.SelectedValue.ToEntero() > 0 Then ' DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString()) 'End If 'If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then ' DdlVendedor.Enabled = False 'End If CargaVendedores() UpFacturar.Update() 'SI LA VENTA YA ESTA REGISTRADA NO DEBE HABILITAR ACCIONES If CveVenta <= 0 Then Dim EsModuloCotizacion As Boolean = False If Request("Op") IsNot Nothing AndAlso Request("Op").ToString() = "Cot" Then EsModuloCotizacion = True End If If Not EsModuloCotizacion Then LnkRemisiones.Visible = If(UsuarioActual.TienePermisoProceso(199), True, False) : LnkOCs.Visible = True : LnkCotizaciones.Visible = True : LnkPedido2SinFacturar.Visible = True : InicializaAplicarNCMasiva() End If End If If UsuarioActual.Empresa.CvePlataforma = 2 Then LnkOCs.Visible = False 'If UsuarioActual.Empresa.UsaInventarios Then ' RblTipo.Items.Remove(RblTipo.Items.FindByValue("1")) ' RblTipo.Items.Remove(RblTipo.Items.FindByValue("2")) 'End If UpnTools.Update() 'UpRemisionesFacturas.Update() If Not CveVenta > 0 Then If ObjCliente.DtResultados.Rows.Count > 0 Then If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto) DdlSubProyectoDatos.Enabled = False Else DdlSubProyectoDatos.SelectedValueExist(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() CargaDatosEstimaciones(CveCliente) If ObjCliente.GetClienteImpuestosLocales(CveCliente) Then 'se cargan impuestos locales Dim DtClienteImpuesto As DataTable = ObjCliente.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") If DtClienteImpuesto IsNot Nothing AndAlso DtClienteImpuesto.Rows.Count > 0 Then ' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear() TmpDTImpuestos = DtClienteImpuesto GvImpuestosLocales2.DataSource = TmpDTImpuestos GvImpuestosLocales2.DataBind() If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then TrOtros.Visible = True GvImpuestosLocales2.Visible = True TrOtros.Style.Add("display", "") Else TrOtros.Visible = False GvImpuestosLocales2.Visible = False End If DtClienteImpuesto.Dispose() End If UpImpuestos.Update() End If If DdlTipoComprobante.SelectedValue.Contiene("Cot") Then TrAtencionA.Visible = True TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False tdTelefonoGen.Visible = False tdTxtTelefonoGen.Visible = False ElseIf ObjCliente.RFC = "XAXX010101000" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ret") Then TrAtencionA.Visible = True TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False tdTelefonoGen.Visible = True tdTxtTelefonoGen.Visible = True Else 'TrAtencionA.Visible = False TrDireccion.Visible = True TrCiudad.Visible = True TrRFC.Visible = True tdTelefonoGen.Visible = False tdTxtTelefonoGen.Visible = False TxtAtencionA.Text = "" TxtTelefonoGenerico.Text = "" End If TrAtencionA.Visible = True tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot") LbAgregar.Enabled = True LnkAgregarPyME.Enabled = True CargarAlmacenes() CargaDocumentacionCliente() If UsuarioActual.CveEmpresa.Contiene(72, 80, 1, 119) Then BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)});" BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation") BtnEmitirImprimir.Attributes.Add("data-popout", "true") BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar") BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar") BtnEmitirImprimir.Attributes.Add("data-html", "true") End If 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True 'Else ' BtnEmitirImprimir.Visible = EstatusCliente ' TrVistaPrevia.Visible = EstatusCliente End If TrVistaPrevia.Visible = True TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString If Not (ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem") Then CargaRestriccionesCreditoCliente(True, Me.CveVenta) End If ' 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() UpDetalle.Update() UpComplementos.Update() UpCliente.Update() UpAplicarNC.Update() UpINV.Update() UPPVentas.Update() UPComplementosSAT.Update() UpnTools.Update() Else Alert("Ocurrió un error al cargar los datos del cliente. Por favor vuelva a intentar.", TipoMensaje.MsgError) End If End If ObjCliente.Dispose() If CveCliente > 0 Then CargaAnticipos(CveCliente) : UpAnticipos.Update() If CveCliente > 0 AndAlso UsuarioActual.CveEmpresa = 140 AndAlso CveVenta <= 0 Then DivVentasUsados.Visible = True Dim ObjClientes As New ClsClientes If ObjClientes.GetHistorialVentas(CveCliente, UsuarioActual.CveEmpresa, CveClienteSucursal:=-1, TipoDocto:="Ing", CveEstatusFactura:=-1) Then DdlVentaUsado.DataSource = ObjClientes.DtResultados.FiltraParametros("UsadoMarcado = 0") End If ObjClientes.Dispose() DdlVentaUsado.DataBind() DdlVentaUsado.Items.Insert(0, New ListItem("No Aplica", "-1")) UpModalRemisionesNC.Update() End If CargaFacturasARelacionar() If RequiereOC Then Dim Documentacion As String = "" 'RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });", "ModalArchivos") Dim Count = 0 For Each GvRow As GridViewRow In GvDocumentosCliente.Rows If GvRow.DataKey("Orden").ToEntero() = 1 Then IndexDocumentoCliente = Count Documentacion = GvRow.DataKey("Documentacion").ToString() AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString() Exit For End If Count = +1 Next LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion BtnModalClienteDocumentoCancelar.Visible = False If CveVenta <= 0 Then LnkUploadDocumentacionCliente.Visible = True End If UpModalTitleUploadDocumentoCliente.Update() UpModalButtonUploadDocumentoCliente.Update() UPObservaciones.Update() ' RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});", "modalOC") End If BloqueaCondiconesPago() DeshabilitarAplicarNotaDeCredito(LblRFC.Text) If CveVenta <= 0 Then CalculaLineasAdicionales() 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 CargaRelacionadasPendientes() If CveVenta > 0 AndAlso UsuarioActual.TienePermisoProceso(321) Then Me.TmpDTFacturasRelacionadas = New DataTable() Me.TmpDTFacturasRelacionadas.Columns.Add(New DataColumn("CveVenta", GetType(Integer))) Me.TmpDTFacturasRelacionadas.Columns.Add(New DataColumn("SerieFolio", GetType(String))) Me.TmpDTFacturasRelacionadas.Columns.Add(New DataColumn("FolioFiscal", GetType(String))) Using ObjVentas As New ClsVentas If ObjVentas.GetVentasRelacionadas(CveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then 'SI LA FACTURA NO SE TIMBRO QUE VUELVA A INTENTAR FACTURAR 'If LblSeTimbro.Text = "No" Then ' Me.AplicaRelacionManual = True 'End If For Each RowRelacionada As DataRow In ObjVentas.DtResultados.Rows Dim Row As DataRow = TmpDTFacturasRelacionadas.NewRow() Row("CveVenta") = RowRelacionada("CveVentaRelacionada").ToString().ToEntero() Row("SerieFolio") = RowRelacionada("SerieFolio").ToString() Row("FolioFiscal") = RowRelacionada("FolioFiscal").ToString() Me.TmpDTFacturasRelacionadas.Rows.Add(Row) Next End If End Using DivDdlFacturaRela.Visible = False BtnAgregarFacturasRelaciondas.Visible = False DdlTipoRelacionARelacionar.Enabled = False GvFacturasRelacionadas.Columns(2).Visible = False GvFacturasRelacionadas.DataSource = Me.TmpDTFacturasRelacionadas GvFacturasRelacionadas.DataBind() UpFacturasRelacionadas.Update() End If End Sub Private Sub CargaFacturasARelacionar() Using ObjClientes As New ClsClientes If ObjClientes.GetHistorialVentas(Me.CveCliente, UsuarioActual.CveEmpresa, TipoDocto:="Ing") Then DdlFacturaARelacionar.DataSource = ObjClientes.DtResultados End If End Using DdlFacturaARelacionar.DataBind() If Not DdlFacturaARelacionar.Items.Contains(New ListItem("Seleccione", "-1")) Then DdlFacturaARelacionar.Items.Insert(0, New ListItem("Seleccione", "-1")) End If UpFacturasRelacionadas.Update() End Sub Protected Sub CreaTmpFacturasRelacionadas() If CveVenta <= 0 OrElse EsCreaApartirDe Then Me.TmpDTFacturasRelacionadas = New DataTable() Me.TmpDTFacturasRelacionadas.Columns.Add(New DataColumn("CveVenta", GetType(Integer))) Me.TmpDTFacturasRelacionadas.Columns.Add(New DataColumn("SerieFolio", GetType(String))) Me.TmpDTFacturasRelacionadas.Columns.Add(New DataColumn("FolioFiscal", GetType(String))) End If End Sub Protected Sub LnkAgregarFacturaRelacionada_Click(sender As Object, e As EventArgs) If CveVenta <= 0 OrElse EsCreaApartirDe Then If Me.TmpDTFacturasRelacionadas Is Nothing Then CreaTmpFacturasRelacionadas() End If If TmpDTFacturasRelacionadas.COUNT("CveVenta", $"CveVenta ={DdlFacturaARelacionar.SelectedValue.ToEntero()}") > 0 Then Alert("La factura ya fue agregada", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim Row As DataRow = TmpDTFacturasRelacionadas.NewRow() Row("CveVenta") = DdlFacturaARelacionar.SelectedValue.ToEntero() Using ObjVentas As New ClsVentas If ObjVentas.GetVenta(DdlFacturaARelacionar.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then Row("SerieFolio") = ObjVentas.DtResultados(0)("SerieFolio").ToString() Row("FolioFiscal") = ObjVentas.DtResultados(0)("FolioFiscal").ToString() End If End Using Me.TmpDTFacturasRelacionadas.Rows.Add(Row) GvFacturasRelacionadas.DataSource = Me.TmpDTFacturasRelacionadas GvFacturasRelacionadas.DataBind() UpFacturasRelacionadas.Update() End If End Sub Protected Sub LnkAgregarFolioFiscalRelacionada_Click(sender As Object, e As EventArgs) If CveVenta <= 0 OrElse EsCreaApartirDe Then If Me.TmpDTFacturasRelacionadas Is Nothing Then CreaTmpFacturasRelacionadas() End If 'If TmpDTFacturasRelacionadas.COUNT("CveVenta", $"CveVenta ={DdlFacturaARelacionar.SelectedValue.ToEntero()}") > 0 Then ' Alert("La factura ya fue agregada", TipoMensaje.MsgAdvertencia) ' Exit Sub 'End If Dim idx As Integer = TmpDTFacturasRelacionadas.MIN("CveVenta", $"CveVenta <= 0").ToEntero() If idx = 0 Then idx = -1 End If Dim Row As DataRow = TmpDTFacturasRelacionadas.NewRow() Row("CveVenta") = idx - 1 Row("SerieFolio") = "SIN ASIGNAR" Row("FolioFiscal") = TxtFolioFiscalRelacionar.Text Me.TmpDTFacturasRelacionadas.Rows.Add(Row) GvFacturasRelacionadas.DataSource = Me.TmpDTFacturasRelacionadas GvFacturasRelacionadas.DataBind() UpFacturasRelacionadas.Update() End If End Sub Protected Sub BtnAgregarFacturasRelaciondas_Click(sender As Object, e As EventArgs) If CveVenta <= 0 OrElse EsCreaApartirDe Then If Me.TmpDTFacturasRelacionadas Is Nothing OrElse Me.TmpDTFacturasRelacionadas.Rows.Count = 0 Then Me.AplicaRelacionManual = False Alert("No hay facturas para relacionar", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlTipoRelacionARelacionar.SelectedValue.ToEntero() <= 0 Then Me.AplicaRelacionManual = False Alert("Debe seleccionar un tipo de relación", TipoMensaje.MsgAdvertencia) Exit Sub End If Me.AplicaRelacionManual = True RegistraScript("$('#DivFacturasRelaciondas').modal('hide');", "R1") Alert("Las facturas seleccionadas se relacionaran con la factura nueva") End If UpFacturasRelacionadas.Update() End Sub Protected Sub LnkEliminarFacturaRelacionada_Click(sender As Object, e As EventArgs) Dim lnkRemove As LinkButton = DirectCast(sender, LinkButton) If Me.TmpDTFacturasRelacionadas.Rows.Count > 0 And lnkRemove.CommandArgument.ToString.Length > 0 Then Dim CveVenta As Integer = lnkRemove.CommandArgument.ToString.ToEntero Dim Drs As DataRow() = Me.TmpDTFacturasRelacionadas.Select(String.Format("CveVenta = {0}", CveVenta)) If Drs.Count > 0 Then Drs(0).Delete() End If Me.TmpDTFacturasRelacionadas.AcceptChanges() End If GvFacturasRelacionadas.EditIndex = -1 GvFacturasRelacionadas.DataSource = Me.TmpDTFacturasRelacionadas GvFacturasRelacionadas.DataBind() UpFacturasRelacionadas.Update() End Sub 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 UsuarioActual.Empresa.Funcionalidad(570) = "1" 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 RBLPago.SelectedValue = "2" RBLPago.Items(0).Enabled = False RBLPago_SelectedIndexChanged(Nothing, Nothing) '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" End If TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString 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")) LnkPedido2SinFacturar.Visible = False LnkCotizaciones.Visible = False 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 RBLPago.SelectedValue = "1" AndAlso PermiteCredito Then 'FUNCIONALIDAD 702 - NO VERIFICAR LIMITE DE CRÉDITO Y CANDADOS DE VENTA If Not UsuarioActual.Empresa.Funcionalidad(702) = "1" Then If UsuarioActual.Empresa.Funcionalidad(589) = "1" Then 'SI EL METODO DE PAGO ES PUE, SELECCIONA CONTADO If Me.CveMetodoPago33Cliente = 1 Then RBLPago.SelectedValue = "2" ElseIf Me.CveMetodoPago33Cliente = 3 Then RBLPago.SelectedValue = "1" End If RBLPago_SelectedIndexChanged(RBLPago, Nothing) UPCondicionesPago.Update() Else RBLPago.SelectedValue = "1" RBLPago_SelectedIndexChanged(RBLPago, Nothing) UPCondicionesPago.Update() End If 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 RBLPago_SelectedIndexChanged(Nothing, Nothing) 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" End If End If TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString 'si llegó por la opción de cotización no debe de restringuir If IfNull(Request("Op"), "").ToString() = "Cot" 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 TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString 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 'RBLPago.SelectedValue = "2" 'RBLPago.Items(0).Enabled = False RBLPago_SelectedIndexChanged(Nothing, Nothing) UPCondicionesPago.Update() DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización") DdlTipoComprobante.SelectedValue = "PA" TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString 'si llegó por la opción de cotización no debe de restringuir If IfNull(Request("Op"), "").ToString() = "Cot" 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 'VERIFICAR LIMITE DE CREDITO If DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0 AndAlso RBLPago.SelectedValue = "1" Then If CreditoDispo < 0 Then BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False Alert("El límite de crédito se ha excedido", TipoMensaje.MsgAdvertencia) End If End If 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 If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then RBLPago.SelectedValue = "2" RBLPago.Items(0).Enabled = False RBLPago_SelectedIndexChanged(Nothing, Nothing) UPCondicionesPago.Update() Else 'este codigo no es temporal If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia) If UsuarioActual.CveEmpresa = 140 Then LnkSolicitarCredito.Visible = True DdlTipoAutorizacion.SelectedValueExist("1") End If End If End If End Select End If End If Else 'VERIFICAR RESTRICCIONES DEL CLIENTE If Not UsuarioActual.Empresa.Funcionalidad(702).ToEntero() > 0 Then If DdlTipoComprobante.SelectedValue = "Cot" AndAlso CveVenta > 0 AndAlso RBLPago.SelectedValue = "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 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 Opcion > 0 AndAlso Autorizacion <= 0 Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False End If Else If Opcion > 0 Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia) BtnsFacturar.Visible = False BtnGenerarRemision.Visible = False End If End If End If End If End If UPPCreditoDisponible.Update() '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 'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = False LblEnviarMail.Visible = False Else If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then 'ENVIO DE FACTURA ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True If CveVenta > 0 AndAlso EnviarCorreoCliente Then ChkEnviarFactura.Checked = EnviarCorreoCliente Else ChkEnviarFactura.Checked = EnviarCorreoCliente ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True 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 = ObjCliente.DtResultados.Rows(0)("Correo").ToString() If Correo.Trim.Length > 0 Then ViewState("Mail") = Correo End If LblDireccion.Text = ObjCliente.DtResultados.Rows(0)("Direccion").ToString() LblColonia.Text = ObjCliente.DtResultados.Rows(0)("Colonia").ToString() LblCiudad.Text = ObjCliente.DtResultados.Rows(0)("Ciudad").ToString() LblEstado.Text = ObjCliente.DtResultados.Rows(0)("Estado").ToString() 'TxtNumCtaPago.Text = ObjCliente.DtResultados.Rows(0)("NumCtaPago").ToString() LblTelefono.Text = ObjCliente.DtResultados.Rows(0)("Telefono").ToString() LblCP.Text = ObjCliente.DtResultados.Rows(0)("CP").ToString() ViewState("CliLocalidad") = ObjCliente.DtResultados.Rows(0)("Localidad").ToString() ViewState("CliPais") = ObjCliente.DtResultados.Rows(0)("Pais").ToString() ViewState("CliNoExt") = ObjCliente.DtResultados.Rows(0)("NoExt").ToString() ViewState("CliNoInt") = ObjCliente.DtResultados.Rows(0)("NoInt").ToString() 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 RBLPago.Items(0).Enabled = False Alert("La Sucursal/Departamento del cliente se encuentra inactivo", TipoMensaje.MsgAdvertencia) Else RBLPago.Items(0).Enabled = True Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero(), ObjVentas) TrCreditoDisponible.Visible = True LblCreditoDisponible.Text = CreditoDispo.FormatoNumero UPPCreditoDisponible.Update() UpParametros.Update() End If '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 UsuarioActual.Empresa.Funcionalidad(350).Contiene("1") AndAlso LblRFC.Text.Contiene("XAXX010101000", "XEXX010101000") Then 'S01 Sin efectos fiscales. DdlUsoCFDI.SelectedValueExist("23") DdlUsoCFDI.Enabled = False RegimenFiscalCliente = "616" ClienteCodigoRegimenFiscal = "616" End If End If If CveVenta < 0 Then TxtAtencionA.Text = ObjCliente.DtResultados.Rows(0)("Contacto").ToString() End If Else Alert("No se pudieron cargar los datos de la sucursal", TipoMensaje.MsgAdvertencia) End If Else If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then If ObjCliente.DtResultados.Rows.Count > 0 Then ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail) LblDireccion.Text = ObjCliente.Direccion LblColonia.Text = ObjCliente.Colonia LblCiudad.Text = ObjCliente.Ciudad LblEstado.Text = ObjCliente.Estado LblCP.Text = ObjCliente.CP LblTelefono.Text = ObjCliente.Telefono 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 UsuarioActual.Empresa.Funcionalidad(350).Contiene("1") AndAlso 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 DdlVendedor.SelectedValue.ToEntero() > 0 Then ' DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString()) 'End If CargaVendedores() 'SI LA VENTA YA ESTA REGISTRADA NO DEBE HABILITAR ACCIONES If CveVenta <= 0 Then Dim EsModuloCotizacion As Boolean = False If Request("Op") IsNot Nothing AndAlso Request("Op").ToString() = "Cot" Then EsModuloCotizacion = True End If If Not EsModuloCotizacion Then LnkRemisiones.Visible = If(UsuarioActual.TienePermisoProceso(199), True, False) : LnkOCs.Visible = True : LnkCotizaciones.Visible = True : LnkPedido2SinFacturar.Visible = True : InicializaAplicarNCMasiva() End If End If ObjCliente.Dispose() UPPVentas.Update() 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() DdlSubProyectoPyME.DataSource = dtt DdlSubProyectoPyME.DataBind() 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") DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") Else DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("Estado = 1", Orderby:="Clasificacion") DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion") End If 'DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa) DdlClasificacion.DataBind() DdlClasificacionPyME.DataBind() End Sub Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost, 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 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 Private Sub CargaNC(pCveVenta As Integer) If pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then If IsNothing(Request("CveDevolucion")) AndAlso IsNumeric(Request("CveDevolucion")) Then trNCFactura.Visible = True End If If DdlNCFactura.Items.Count = 0 Then Dim ObjClientes As New ClsVentas() If ObjClientes.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then DTFacNC = ObjClientes.DtResultados Dim drvv As DataRow = DTFacNC.FiltroPrimero("") DTFacNC.Columns.Add("Factura", GetType(String), " Folio + ' - ' +' $' + Total + ' - ' + Fecha ") HdnFolioFiscalNC.Value = drvv("FolioFiscal").ToString() If DTFacNC IsNot Nothing AndAlso DTFacNC.Rows.Count > 0 Then Me.CveEstatusRefacturacion = DTFacNC.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero() Me.DevolucionAlmacenNC = DTFacNC.Rows(0)("EsDevolucionVenta").ToString().ToEntero() Me.VentaSaldoAlmacenNC = DTFacNC.Rows(0)("SaldoAlmacen").ToString().ToDecimal HdnRFCVenta.Value = DTFacNC.Rows(0)("ClienteRFC").ToString() End If Else DTFacNC = Nothing End If ObjClientes.Dispose() Me.ObjFacturaNC = Nothing Me.ObjFacturaNC = New Modelos.Factura(UsuarioActual, pCveVenta, UsuarioActual.CveEmpresa, DirectorioServidor:=ModExtensiones.DirectorioBaseEmpresas, EsCancelacion:=False) DdlNCFactura.DataSource = DTFacNC DdlNCFactura.DataBind() DdlNCFactura.SelectedValueExist(pCveVenta) DdlNCFactura.Enabled = False End If Else trNCFactura.Visible = False End If End Sub Private Sub CargaCuentasTerminal() DdlCuentasTerminal.Items.Clear() DdlCuentaTerminalModal.Items.Clear() DdlCuentasTerminal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"}) DdlCuentaTerminalModal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"}) DdlCuentasTerminal.DataBind() DdlCuentaTerminalModal.DataBind() DdlCuentasTerminal.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlCuentaTerminalModal.Items.Insert(0, New ListItem("Seleccione", "-1")) UPTarjetaTermminal.Update() UpCuentaTerminal.Update() End Sub Public Sub CargaDdlNCPS() Dim CveSATNC = "84111506" Dim dtt As New DataTable dtt = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC If dtt IsNot Nothing Then DdlNCPS.DataSource = dtt DdlNCPS.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlNCPS.DataBind() DdlNCPSAnt.DataSource = dtt DdlNCPSAnt.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlNCPSAnt.DataBind() dtt.Dispose() End If End Sub #End Region #Region "G R I D V I E W S" #Region "GvPS" Protected Sub GvPS_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvPS.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Attributes("id") = e.Row.RowIndex.ToString() If e.Row.RowIndex = 0 Then End If If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then 'MODO EDICION e.Row.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToEntero(), -1, UsuarioActual.CveEmpresa) e.Row.FCDropDownList("DdlUnidadMedida").DataBind() e.Row.FCDropDownList("DdlUnidadMedida").SelectedValueExist(e.Row.DBCampo("CveUM")) e.Row.FCDropDownList("DdlClasificacion").DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1) e.Row.FCDropDownList("DdlClasificacion").DataBind() e.Row.FCDropDownList("DdlClasificacion").SelectedValue = e.Row.DBCampo("CveClasificacion") CargaPS(e.Row.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero(), e.Row.FCDropDownLost("DdlPS")) e.Row.FCDropDownLost("DdlPS").SelectedText = e.Row.DBCampo("PS") e.Row.FCDropDownLost("DdlPS").SelectedValue = e.Row.DBCampo("CvePS") If e.Row.DBCampo("CveSubProyecto") = "-1" Then 'cargo todos las opciones para e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) e.Row.FCDropDownList("DdlProyecto").DataBind() e.Row.FCDropDownList("DdlProyecto").Items.Insert(0, New ListItem("Sin Proyecto Asignado", "-1")) e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlProyecto.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa, -1, 1) 'e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectos.FiltraParametros("CveEmpresa = " & UsuarioActual.CveEmpresa & " AND CveProyecto = '" & DdlProyecto.SelectedValue & "'") e.Row.FCDropDownList("DdlSubProyecto").DataBind() 'e.Row.FCDropDownList("DdlSubProyectoEdit").SelectedValue = e.Row.DBCampo("CveSubProyecto") e.Row.FCDropDownList("DdlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) Else Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, e.Row.DBCampo("CveSubProyecto").ToEntero(), 1).FiltroPrimero("") If dr IsNot Nothing Then e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1) e.Row.FCDropDownList("DdlProyecto").DataBind() e.Row.FCDropDownList("DdlProyecto").SelectedValue = dr("CveProyecto").ToString() e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, dr("CveProyecto").ToString().ToEntero(), UsuarioActual.CveEmpresa, -1, 1) e.Row.FCDropDownList("DdlSubProyecto").DataBind() e.Row.FCDropDownList("DdlSubProyecto").SelectedValue = e.Row.DBCampo("CveSubProyecto") End If End If If UsuarioActual.TienePermisoProceso(68) Then e.Row.FCTextBox("TxtPrecio").Enabled = False e.Row.FCTextBox("TxtDescuento").Enabled = False End If 'Si es una devolucion If NuevaFactura = 0 Then e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownLost("DdlPS").Enabled = False e.Row.FCDropDownList("DdlProyecto").Enabled = False e.Row.FCDropDownList("DdlSubProyecto").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = False ElseIf NuevaFactura = 1 Or CveContrato > 0 Then e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownLost("DdlPS").Enabled = False e.Row.FCTextBox("TxtCantidad").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = False e.Row.FCTextBox("TxtDescuento").Enabled = False If TieneAlmacen Then e.Row.FCLinkButton("imgD").Visible = False If UsuarioActual.TienePermisoProceso(222) Then e.Row.FCDropDownList("DdlUnidadMedida").Enabled = True e.Row.FCDropDownList("DdlClasificacion").Enabled = True e.Row.FCDropDownLost("DdlPS").Enabled = True e.Row.FCTextBox("TxtCantidad").Enabled = True e.Row.FCTextBox("TxtPrecio").Enabled = True e.Row.FCTextBox("TxtDescuento").Enabled = True End If End If 'Si es facturacion de OC o Contrato If CveContrato > 0 AndAlso Not CveVenta > 0 AndAlso Not CveCicloComercial > 0 Then e.Row.FCLinkButton("imgClone").Visible = False e.Row.FCTextBox("TxtOrden").Visible = True e.Row.FCTextBox("TxtCantidad").Enabled = False e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownLost("DdlPS").Enabled = False e.Row.FCDropDownList("DdlProyecto").Enabled = False e.Row.FCDropDownList("DdlSubProyecto").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = False End If If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then e.Row.FCLinkButton("imgClone").Visible = False e.Row.FCTextBox("TxtOrden").Visible = True e.Row.FCTextBox("TxtCantidad").Enabled = False e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False e.Row.FCDropDownList("DdlClasificacion").Enabled = False e.Row.FCDropDownList("DdlProyecto").Enabled = False e.Row.FCDropDownList("DdlSubProyecto").Enabled = False e.Row.FCLiteral("LtlPSEdit").Visible = True e.Row.FCDropDownLost("DdlPS").Visible = False e.Row.FCDropDownLost("DdlPS").Enabled = False e.Row.FCTextBox("TxtPrecio").Enabled = True End If If CveCicloComercial > 0 Then e.Row.FCTextBox("TxtPrecio").Enabled = True End If 'CUANDO SE QUIERE FACTURAR UNA REMISIÓN NO PERMITE EDITAR SU PRECIO If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso (e.Row.DBCampo("CveVentaDetalle").ToEntero() > 0 Or e.Row.DBCampo("CveVentaDetalleRemision").ToEntero() > 0) Then e.Row.FCTextBox("TxtPrecio").Enabled = False End If 'PERMISO EDITAR REM If e.Row.DBCampo("TipoDocto") = "Rem" And ModalidadEdicion Then 'LO PERMITIDO MODIFICAR e.Row.FCTextBox("TxtPrecio").Enabled = True e.Row.FCTextBox("TxtObsPS").Enabled = True e.Row.FCTextBox("TxtCantidad").Attributes.Add("onblur", $"ValidarCantidadMenor(this,{e.Row.DBCampo("CantidadInventario").ToDouble})") 'LO NO PERMITIDO MODIFICAR e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False 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 = 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 Cotizacíon If e.Row.DBCampo("TipoDocto") = "Cot" Then ThTiempoEntrega.Visible = True ThTiempoEntrega2.Visible = True GvPS.Columns(5).Visible = True End If 'Si es facturacion de OC If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then e.Row.FCLinkButton("imgClone").Visible = False e.Row.FCTextBox("TxtOrden").Visible = True End If If UsuarioActual.Empresa.CvePlataforma = 2 Then e.Row.FCLinkButton("imgE").Visible = False e.Row.FCLinkButton("imgEPyME").Visible = True End If If UsuarioActual.Empresa.Tipo_CentroCosto = 2 Or UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then e.Row.FCLabel("LblProyecto").Visible = False End If If CveVenta > 0 Then 'And e.Row.DBCampo("TipoDocto") = "Rem" If ModalidadEdicion Then e.Row.FCLinkButton("imgE").Visible = Not e.Row.DBCampo("CantidadFacturadaRem").ToDouble > 0 e.Row.FCLinkButton("imgD").Visible = Not e.Row.DBCampo("CantidadInventario").ToDouble > 0 ElseIf Not CveDevolucion > 0 Then e.Row.FCLinkButton("imgE").Visible = False e.Row.FCLinkButton("imgD").Visible = False End If '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 '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(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvPS.RowEditing GvPS.EditIndex = e.NewEditIndex GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() 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 If CveCicloComercial > 0 Then For Each gvr As GridViewRow In GvContratoDetalles.Rows If gvr.RowType = DataControlRowType.DataRow Then If gvr.DataKey("Cantidad").ToString().ToDecimal() = GvPS.Rows(e.NewEditIndex).DataKey("Cantidad").ToString().ToDecimal() AndAlso gvr.DataKey("CvePS").ToString().ToEntero() = GvPS.Rows(e.NewEditIndex).DataKey("CvePS").ToString().ToEntero() Then If gvr.DataKey("LimitarCantidad").ToString() = "False" Then GvPS.Rows(e.NewEditIndex).FCTextBox("TxtCantidad").Enabled = True Exit For End If End If End If Next 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 Descuentos 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:=DdlVendedor.SelectedValue.ToEntero(), 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.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveTipoAlmacen:=1) 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal If Costo = 0 Then Costo = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -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" And ChkSinExistencia.Checked = False 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 = False Dim EsValidoMayor = False Dim CostoMenor = 0.0D Dim CostoMayor = 0.0D 'PRECIO MINIMO If UsuarioActual.Empresa.Funcionalidad(129).ToEntero() > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then '' 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 ' End If 'End If 'NO DEJA REGISTRAR MENOS AL PRECIO MINIMO Dim MensajeCosto As New StringBuilder Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201) If Not EsValido Then MensajeCosto.AppendFormat("El Producto {0}. No se puede vender a un precio menor de su Costo
    ", 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 = TmpDT.Rows(e.RowIndex)("Consec").ToString().ToEntero() If ConsecEliminar > 0 Then Dim descEliminar = 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 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) ' 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() CargaGVInv(DtInv) If UsuarioActual.Empresa.Funcionalidad(533).ToEntero() > 0 Then CalculaUsados() End If 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 = Me.ClienteRetIVA If ClienteRetIVA <= 0 Then If TmpDT.Rows(e.RowIndex)("EsOutSourcing").ToString() <> "" AndAlso CBool(TmpDT.Rows(e.RowIndex)("EsOutSourcing").ToString()) Then ClienteRetIVA = 0.06D DdlTipoRetencion.SelectedValueExist("4") LblRetIVA.Text = (ClienteRetIVA * 100).FormatoNumero TrRetIVA.Style.Add("display", "") DdlTipoRetencion.Visible = True ElseIf 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 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)("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 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 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() CargaGVInv(DtInv) CalculaUsados() End If If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ObjDescuento IsNot Nothing Then ListaDescuentos.Add(ObjDescuento) End If CalculaTotalesVenta() 'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW If AplicaComercioExterior Then CargaGvComercioExterior() End If 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") UpPS.Update() UpContado.Update() End Sub Protected Sub GvPS_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvPS.RowDeleting If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing Then Dim ConsecEliminar = TmpDT.Rows(e.RowIndex)("Consec").ToString().ToEntero() If ConsecEliminar > 0 Then Dim descEliminar = 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(",", "") UpContado.Update() End Sub #End Region #Region "GvINV" Private Sub GvInv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvInv.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If UsuarioActual.Empresa.Funcionalidad(567) = "1" Then e.Row.FCCheckBox("cbInv").Checked = True End If 'SERIE ALMACEN If CveVenta > 0 AndAlso e.Row.DBCampo("Serie") <> "" Then e.Row.FCLiteral("LtlSerie").Visible = True End If If e.Row.DBCampo("CveTipoInvPS").ToEntero() = 5 And CveVenta <= 0 Then e.Row.FCTextBox("TxtSerie").Visible = True e.Row.FCTextBox("TxtSerie").Attributes.Remove("onkeypress") e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeypress", String.Format("SeriePS(event,{0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID)) e.Row.FCTextBox("TxtSerie").Attributes.Remove("onblur") e.Row.FCTextBox("TxtSerie").Attributes.Add("onblur", String.Format("SeriePSBlur({0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID)) 'e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) 'e.Row.FCTextBox("LblCodigo").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) 'e.Row.FCTextBox("LblCodigo").Attributes.Add("onblur", String.Format("LimpiaAF(1, '{0}'); AFBlurEdit(this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID)) End If If e.Row.DBCampo("CvePS") = "" Then e.Row.FCLiteral("LtlPS").Text = String.Format("Folio: {1} Fecha: {2} -- {3} -- {4}", e.Row.DBCampo("CveMovimiento"), e.Row.DBCampo("Folio"), e.Row.DBCampo("Fecha").ToString().ToDate.ToShortDateString, e.Row.DBCampo("Almacen").ToString(), e.Row.DBCampo("Concepto").ToString()) e.Row.FCCheckBox("cbInv").Visible = False e.Row.FCCheckBox("cbInv").Enabled = False If e.Row.DataKey("Origen").ToEntero() > 0 Then e.Row.BackColor = Drawing.Color.FromArgb(224, 130, 131) e.Row.ForeColor = Drawing.Color.White e.Row.Font.Bold = True Else e.Row.CssClass = "SubTotales" End If Else e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left e.Row.FCCheckBox("cbInv").Visible = True e.Row.FCCheckBox("cbInv").Enabled = True 'SI ES REMISION O VENTA DEBE SALIR DE ALMACEN If UsuarioActual.TienePermisoProceso(157) AndAlso e.Row.DBCampo("CvePS").ToEntero() > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") AndAlso UsuarioActual.CveEmpresa <> 72 Then e.Row.FCCheckBox("cbInv").Checked = True e.Row.FCCheckBox("cbInv").Enabled = False End If 'SI DEBE HACER SALIDA DIRECTA DE ALMACEN DEBE ESTAR SELECCIONADO SIEMPRE If UsuarioActual.Empresa.Funcionalidad(567) = "1" Then e.Row.FCCheckBox("cbInv").Checked = True If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then e.Row.FCCheckBox("cbInv").Enabled = False End If End If End If If (CveVenta > 0 And DdlTipoComprobante.SelectedValue <> "Cot") AndAlso Not AplicaDevolucion Then If e.Row.DBCampo("CveConcepto").ToEntero().Contiene(3, 40) Then CveAlmacenDevolucion = e.Row.DBCampo("CveAlmacen").ToEntero() e.Row.FCCheckBox("cbInv").Visible = False End If If (CveVenta > 0 AndAlso EsCreaApartirDe AndAlso UsuarioActual.Empresa.Funcionalidad(558) = "1") Then e.Row.FCCheckBox("cbInv").Visible = True End If End If End Sub Protected Sub GVINV_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvInv.RowEditing GvInv.EditIndex = e.NewEditIndex CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2")) End Sub Protected Sub GVINV_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvInv.RowCancelingEdit GvInv.EditIndex = -1 CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2")) End Sub Protected Sub GVINV_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvInv.RowUpdating Dim Cantidad As Double = DirectCast(GvInv.Rows(e.RowIndex).FindControl("txtECantidad"), TextBox).Text.ToDouble DtInv.Rows.Item(e.RowIndex)("Cantidad") = Cantidad GvInv.DataSource = DtInv.FiltraParametros("CveTipoPS=2") End Sub #End Region #Region "GvInvNC" Protected Sub GvInvNCCheckClick(sender As Object, e As EventArgs) Dim chk As CheckBox = DirectCast(sender, CheckBox) Dim gvr As GridViewRow = DirectCast(chk.NamingContainer, GridViewRow) gvr.FCTextBox("Txtcantidad").Visible = chk.Checked UpINVNC.Update() End Sub 'Private Function SubTotalFacturaVinNC() As Decimal *** ESTABA TRONANDO EN COMPU 11/01/17 *** ' Dim retorno As Decimal = 0 ' If GvInvNC.Rows.Count = 0 Then ' Try ' If Not IsNothing(DTFacNC) AndAlso DTFacNC.FiltraParametros(String.Format("CveVenta={0}", DdlNCFactura.SelectedValue)).Rows.Count > 0 Then ' retorno = DTFacNC.FiltroPrimero(String.Format("CveVenta={0}", DdlNCFactura.SelectedValue))("SubTotal").ToString().ToDecimal ' End If ' Catch ex As Exception ' End Try ' Else ' For Each gvrow As GridViewRow In GvInvNC.Rows ' Dim txt As TextBox = gvrow.FCTextBox("Txtcantidad") ' If txt.Visible Then ' retorno += txt.Text.ToDecimal * gvrow.DataKey("PU").ToString().ToDecimal ' End If ' Next ' End If ' Return retorno 'End Function #End Region #Region "GvConceptos" Protected Sub GvConceptos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvConceptos.RowDeleting DTmpC.Rows.RemoveAt(e.RowIndex) GvConceptos.DataSource = DTmpC GvConceptos.DataBind() UPCD.Update() UPCD.Update() End Sub Protected Sub GvConceptos_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvConceptos.RowEditing GvConceptos.DataSource = DTmpC GvConceptos.EditIndex = e.NewEditIndex GvConceptos.DataBind() End Sub Protected Sub GvConceptos_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvConceptos.RowCancelingEdit GvConceptos.EditIndex = -1 GvConceptos.DataSource = DTmpC GvConceptos.DataBind() End Sub Protected Sub GvConceptos_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvConceptos.RowUpdating DTmpC.Rows(e.RowIndex)("Descripcion") = GvConceptos.Rows(e.RowIndex).FCTextBox("tbDescCE").Text GvConceptos.EditIndex = -1 GvConceptos.DataSource = DTmpC GvConceptos.DataBind() End Sub #End Region #Region "GvFirma" Protected Sub GvFirmas_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvFirmas.RowDataBound If e.Row.RowType = DataControlRowType.DataRow And Not e.Row.RowState = DataControlRowState.Edit Then If e.Row.DBCampo("Lado") = "0" Then e.Row.FCLabel("lbPosF").Text = "Der." ElseIf e.Row.DBCampo("Lado") = "1" Then e.Row.FCLabel("lbPosF").Text = "Izq." End If End If End Sub Protected Sub GvFirmas_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvFirmas.RowDeleting DTmpF.Rows.RemoveAt(e.RowIndex) GvFirmas.DataSource = DTmpF GvFirmas.DataBind() UPCD.Update() UPFirmas.Update() End Sub Protected Sub GvFirmas_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvFirmas.RowEditing GvFirmas.DataSource = DTmpF GvFirmas.EditIndex = e.NewEditIndex GvFirmas.DataBind() End Sub Protected Sub GvFirmas_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvFirmas.RowCancelingEdit GvFirmas.EditIndex = -1 GvFirmas.DataSource = DTmpF GvFirmas.DataBind() End Sub Protected Sub GvFirmas_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvFirmas.RowUpdating DTmpF.Rows(e.RowIndex)("Titulo") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbTituloFE").Text DTmpF.Rows(e.RowIndex)("Nombre") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbNmbFE").Text DTmpF.Rows(e.RowIndex)("Puesto") = GvFirmas.Rows(e.RowIndex).FCTextBox("tbPuestFE").Text DTmpF.Rows(e.RowIndex)("Lado") = GvFirmas.Rows(e.RowIndex).FCDropDownList("ddlPosE").SelectedValue GvFirmas.EditIndex = -1 GvFirmas.DataSource = DTmpF GvFirmas.DataBind() End Sub #End Region #Region "GvIEPS" 'Protected Sub GvIEPS_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvIEPS.RowDataBound ' If e.Row.RowType = DataControlRowType.DataRow Then ' e.Row.FCLiteral("LtlIEPS").Text = String.Format("IEPS ({0}):", If(e.Row.DBCampo("PorcentajeIEPS").ToDecimal = 0.03, "3%", If(e.Row.DBCampo("PorcentajeIEPS").ToDecimal = 0.06, "6%", If(e.Row.DBCampo("PorcentajeIEPS").ToDecimal = 0.07, "7%", "9%")))) ' End If 'End Sub #End Region #End Region #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 UsuarioActual.Empresa.Funcionalidad(350) = "1" AndAlso 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 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 'CUANDO ES PEDIDO SE DEBE ESPECIFICAR EL NUMERO DE CONTRATO If TrTipoPedido.Visible AndAlso DdlTipoPedido.SelectedIndex = 2 Then If String.IsNullOrEmpty(TxtObsFact.Text.Trim()) Then Alert("Se debe especificar el Número de contrato.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If UsuarioActual.Empresa.Funcionalidad(558).ToEntero() = 1 AndAlso TrKilometraje.Visible Then If TxtKilometraje.Text.Length < 6 Then Alert("El kilometraje debe tener 6 digitos.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If ChkEmitirCartaPorte.Checked Then If DdlDireccionOrigen.SelectedValue.ToEntero() <= 0 Then Alert("La carta porte no tiene un origen definido.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlDireccionDestino.SelectedValue.ToEntero() <= 0 Then Alert("La carta porte no tiene un destino definido.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlChofer.SelectedValue.ToEntero() <= 0 Then Alert("La carta porte no tiene un chofer definido.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlUnidadCamion.SelectedValue.ToEntero() <= 0 Then Alert("La carta porte no tiene un chofer definido.", TipoMensaje.MsgAdvertencia) Exit Sub End If If String.IsNullOrEmpty(TxtDistancia.Text.Trim) Then Alert("La carta porte no tiene la distancia definida.", TipoMensaje.MsgAdvertencia) Exit Sub End If If String.IsNullOrEmpty(TxtFechaEntregaCP.Text.Trim) Then Alert("La carta porte no tiene la F.Salida definida.", TipoMensaje.MsgAdvertencia) Exit Sub End If If String.IsNullOrEmpty(TxtFechaLlegadaCP.Text.Trim) Then Alert("La carta porte no tiene la F.Llegada definida.", TipoMensaje.MsgAdvertencia) Exit Sub End If If TxtFechaLlegadaCP.Text.ToDateTime() < TxtFechaEntregaCP.Text.ToDateTime() Then Alert("La fecha de llegada no puede ser menor al fecha de salida.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DtMercancias Is Nothing OrElse DtMercancias.Rows.Count = 0 Then Alert("La carta porte no tiene mercancía definida.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DvConfiguracionVeiculo.Visible Then If DdlConfigAuto.SelectedValue.ToEntero() <= 0 Then Alert("La carta porte no tiene la configuración definida.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If 'CUANDO ES COTIZACION Y SE VA A FACTURAR SE HACE INGRESO If DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar" Then DdlTipoComprobante.SelectedValue = "Ing" EraCotizacion = 1 TxtFecha.Text = Now.ToString() TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranza), Now.AddDays(PlazoCobranza)).ToShortDateString TxtFechaEjecucion.Text = Now.ToString() 'debo de regenerar los folios, para facturar CargaFolios() End If 'VALIDACIONES If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia) Exit Sub End If If TmpDT Is Nothing OrElse TmpDT.Rows.Count = 0 Then Alert("Es necesario tener al menos un concepto registrado.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'Subproyecto Obligatorio If UsuarioActual.Empresa.Funcionalidad(120) = "1" AndAlso TmpDT.FiltraParametros("ISNULL(CveSubProyecto,0) <= 0").Rows.Count > 0 Then Alert("El Subproyecto de los conceptos es obligatorio, Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VENDEDOR OBLIGATORIO If DdlVendedor.SelectedValue.ToEntero() <= 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") AndAlso RBLPago.SelectedValue = "1" Then Dim TipoDocumentoAutorizacion As String = "" Dim ImporteAutorizacion As Decimal = 0 Dim TipoAutorizacion As Integer = 0 Dim DiasVencidosAutorizacion As Integer = 0 Dim CveVendedor As Integer = DdlVendedor.SelectedValue.ToEntero() Dim ObjVentas As New ClsVentas Try If ObjVentas.GetAutorizacionLimite(UsuarioActual.CveEmpresa, CveCliente, CveVendedor, DdlTipoDocto.SelectedValue, 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='{DdlTipoComprobante.SelectedValue}'", Orderby:="Importe DESC") Else RowAutorizacion = ObjVentas.DtResultados.FiltroPrimero($"TipoAutorizacion = 1 AND CveVenta IS NULL AND CveTipoDocumento='{DdlTipoComprobante.SelectedValue}'", Orderby:="Importe DESC") End If If RowAutorizacion IsNot Nothing Then TipoDocumentoAutorizacion = RowAutorizacion("CveTipoDocumento").ToString() ImporteAutorizacion = RowAutorizacion("Importe").ToString().ToDecimal() CveAutorizacion = RowAutorizacion("CveAutorizacion").ToString().ToEntero() TipoAutorizacion = RowAutorizacion("TipoAutorizacion").ToString().ToEntero() DiasVencidosAutorizacion = RowAutorizacion("DiasVencidos").ToString().ToEntero() End If End If Catch ex As Exception OnError("Ocurrió un error al obtener las autorizaciones", ex) End Try 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 'VALIDAR LINEAS ADICIONALES If UsuarioActual.Empresa.Funcionalidad(705) = "1" AndAlso DdlLineaAdicional.SelectedValue.ToEntero() > 0 Then 'VERIFICA QUE LA CLASIFICACION DE LOS PRODUCTOS DEBE SER LA MISMA DE LA LINEA ADICIONAL If TmpDT IsNot Nothing AndAlso Me.CveClasificacionLineaAdicional > 0 Then For Each Row As DataRow In TmpDT.FiltraParametros("", DistinctColumns:={"CveClasificacion", "Clasificacion"}).Rows If Me.CveClasificacionLineaAdicional <> Row("CveClasificacion").ToString().ToEntero() Then Alert($"La clasificación '{Row("Clasificacion")}' no pertenece a la linea adicional.", TipoMensaje.MsgAdvertencia) Exit Sub End If Next End If If Me.SaldoLineaAdicional <= 0 Then Alert("El saldo de la linea adicional debe ser mayor a cero", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VERIFICA QUE LA MONEDA DE LA LINEA ADICIONAL SEA LA MISMA QUE LA VENTA If Me.CveMonedaLineaAdicional <> DdlMoneda.SelectedValue.ToEntero() Then Alert("La moneda de la linea adicional de crédito debe ser la misma que la factura.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VERIFICA QUE EL SALDO DISPONIBLE SEA MENOR AL IMPORTE If Me.SaldoLineaAdicional <= TxtTotal.Text.ToDecimal() Then Alert("El saldo de la linea adicional debe ser mayor o igual al de la factura", TipoMensaje.MsgAdvertencia) Exit Sub End If End If 'VALIDA PRECIO AL AGREGAR A ALMACEN If Not UsuarioActual.TienePermisoProceso(169) Then If (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") AndAlso NuevaFactura <> 1) Or (DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119)) Then Dim MensajeCosto As New StringBuilder Dim CostoMenor = 0.0D Dim CostoMayor = 0.0D Dim Costo = 0.0D Dim EsValido = False 'BANDERA Dim EsValidoMayor = False Dim EsValidoPU = True 'SOLO SE VALIDA CUANDO EL TXTPU = 0 Y LO INVALIDA ALGUNA PROMOCION 'VALIDA PROMOCIONES Y EXISTENCIAS Dim ObjVentas As New ClsVentas If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveCliente, DdlVendedor.SelectedValue.ToEntero(), 1, UsuarioActual.CveEmpresa) Then DtPromociones = ObjVentas.DtResultados End If ObjVentas.Dispose() Dim ObjInventarios As New ClsInventarios Dim PU = 0.0D Dim Cantidad As Double Dim CveUnidad As Integer Dim CveProducto As Integer Dim Existencia As Double Dim CveAlmacen = ddlAlmacen.SelectedValue.ToEntero() For Each dr As DataRow In TmpDT.FiltraParametros("CveTipoPS = 2").Rows If DdlTipoComprobante.SelectedValue <> "Cot" And ChkSinExistencia.Checked = False Then 'VALIDA EXISTENCIA CveProducto = dr("CvePS").ToString().ToEntero() CveUnidad = dr("CveUM").ToString().ToEntero() Cantidad = TmpDT.SUM("Cantidad", $"CvePS = {CveProducto} 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:=DdlVendedor.SelectedValue.ToEntero(), CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) If Existencia < Cantidad Then MensajeCosto.AppendFormat("
    El Producto {0}. No cuenta con la cantidad suficiente en inventario. Cuenta con {1}.", dr("CodigoPS").ToString(), Existencia.FormatoNumero(2)) Continue For End If End If End If EsValido = False EsValidoMayor = False EsValidoPU = True PU = dr("PU").ToString().ToDecimal * If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.ToDecimal) Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString().ToEntero(), dr("Cantidad").ToString().ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero(), 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 TxtKilometraje.Text.ToEntero() = 0 Then 'cuando es la clasificacion de llantas Dim FaltaObservacion As Integer = TmpDT.MAX("CveClasificacion", "Clasificacion like '%Llanta%'").ToEntero '.FiltroPrimeroValor("CveClasificacion", "CveClasificacion = 20342").ToEntero() If FaltaObservacion > 0 Then 'sino se ha especificado km cuando tiene al clasif llanta Alert("No se ha especificado el kilometraje.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If TxtObsFact.Text = "" Then Dim FaltaObservacion As Integer = -1 'For Each PS As GridViewRow In GvPS.Rows ' Dim PsRenglon As GridViewRow = PS ' Dim CveClasificacion As Integer = PsRenglon.DataKey("CveClasificacion").ToEntero() ' If CveClasificacion = 20345 Or CveClasificacion = 20342 Then ' FaltaObservacion = CveClasificacion ' Exit For ' End If ' 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}", DdlVendedor.SelectedValue.ToEntero())) 'Verifico si el supervisor tiene correo para proceder If DTSupervisores.Rows.Count > 0 Then CorreoSupervisor = DTSupervisores.Rows(0)("CorreoSupervisor").ToString() End If End If DTSupervisores.Dispose() Objeto.Dispose() If MandarCorreoSupervisor = True And CorreoSupervisor <> "" Then ViewState("Mail") = CorreoSupervisor End If MandarCorreoSupervisor = False End If If RequiereOC AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Ing") AndAlso Not CveDevolucion > 0 Then If Not CargaDocumentoOC Then Alert("Tiene que cargar un archivo de orden de compra", TipoMensaje.MsgAdvertencia) Exit Sub End If If TxtOrdenCompra.Text.Trim = "" Then Alert("Tiene que especificar un folio de orden de compra", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If 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)) LnkImprimir.Visible = False 'If (UsuarioActual.CveEmpresa.Contiene(1, 4, 5, 7, 11, 12, 72, 80, 81, 83) And UsuarioActual.CveUsuario = 100) Or UsuarioActual.CveEmpresa.Contiene(80, 83) Or UsuarioActual.CveUsuario = 100 Then If (Archivo.Exists Or Archivo2.Exists) And IfNull(CveVenta, 0).ToString().ToEntero() > 0 Then HplDownPDF.Visible = True HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta))) If UsuarioActual.CveRol = 1 Then HplRenerarPDF.Visible = True HplRenerarPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1®ENERAR=1", CveVenta))) HplImprimirPDFStimulsoft.Visible = True HplImprimirPDFStimulsoft.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=0&STIMULSOFT=1", CveVenta))) End If End If 'NO DEBE IMPRIMIR PDF DE COTIZACION If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then HplDownPDF.Visible = False End If 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 CreaObjetosVenta(TipoDoctoViejo:=TipoDoctoViejo) 'Verifica versión 3.3.() If ObjFactura.Version = "3.3" AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then Dim dttsat As DataTable = TmpDT.FiltraParametros("ISNULL(SATClaveProdServ,'') = '' OR ISNULL(SATClaveUM,'') = '' ") If dttsat IsNot Nothing AndAlso dttsat.Rows.Count > 0 Then Dim str As New StringBuilder str.Append("Los siguientes productos no tiene asignado la clave Producto SAT o Unidad Medida SAT

    ") For Each drt As DataRow In dttsat.Rows str.AppendFormat("{0}
    ", drt("CodigoPS")) Next Alert(str.ToString(), TipoMensaje.MsgAdvertencia) dttsat.Dispose() str.Clear() Exit Sub End If dttsat.Dispose() If UsuarioActual.CveEmpresa = 72 Then Dim DtNoEncontrados As DataTable = TmpDT.FiltraParametros("ISNULL(SATClaveProdServ,'') = '01010101' ") If DtNoEncontrados IsNot Nothing AndAlso DtNoEncontrados.Rows.Count > 0 Then Dim StrNoEncontrados As New StringBuilder StrNoEncontrados.Append("Los siguientes productos no existen en el catálogo del SAT

    ") For Each drt As DataRow In DtNoEncontrados.Rows StrNoEncontrados.AppendFormat("{0}
    ", drt("CodigoPS")) Next Alert(StrNoEncontrados.ToString(), TipoMensaje.MsgAdvertencia) DtNoEncontrados.Dispose() StrNoEncontrados.Clear() Exit Sub End If DtNoEncontrados.Dispose() End If End If If ObjFactura Is Nothing Or (ObjFactura.Cliente Is Nothing And Not CveEmpresaCRM > 0) Then Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError) ObjFactura = Nothing Exit Sub End If 'If Not CveEmpresaCRM > 0 Then ' If ObjFactura.Cliente.AplicaComercioExterior Then ' If Not ValidaComercioExterior() Then ' ObjFactura = Nothing ' Exit Sub ' End If ' End If 'End If 'VALIDA TOTAL DE LA NOTA DE CREDITO Y LA FACTURA VINCULADA *** ESTABA TRONANDO EN COMPU 11/01/17 *** 'If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then ' If SubTotalFacturaVinNC() > 0 Then 'pendiente ' If GvInvNC.Rows.Count > 0 Then 'pendiente ' If Not (SubTotalFacturaVinNC() = TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio)) Then ' Alert(String.Format("El sub-total debe ser igual a '{0}'", SubTotalFacturaVinNC().FormatoNumero)) ' Exit Sub ' End If ' Else ' If SubTotalFacturaVinNC() < TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio) Then 'pendiente ' Alert(String.Format("El sub-total no puede exceder a : {0}", SubTotalFacturaVinNC().FormatoNumero)) ' Exit Sub ' End If ' End If ' End If 'End If If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then If UsuarioActual.CveEmpresa.Contiene(72, 80) Then If ObjFactura.SubTotal <= 0 Then Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If 'VALIDA CUENTAS CONTABLES DE AC If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then If ObjFactura.Cliente.IdCtaContClientes <= 0 Then Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError) Exit Sub End If 'If ViewState("IdCtaContClientes").ToString().ToEntero() <= 0 Then 'GetClientes ObjCliente.IdCtaContClientes ' Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError) ' Exit Sub 'End If If ObjFactura.SubTotal <= 0 Then Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'If TxtSubTotal.Text.ToDouble <= 0 Then ' Alert("Especifique importe en conceptos", TipoMensaje.MsgError) ' Exit Sub 'End If End If 'cuando es contado debe de tener especificado la forma de pago 'If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso ObjFactura.Total > 0 AndAlso RBLPago.SelectedValue = "2" AndAlso ObjFactura.Total - If(DtPagos Is Nothing, 0, DtPagos.SUM("Importe")) > 0 Then ' AndAlso ObjFactura.CveCorte > 0 ' Alert("No se han especificado las formas de pago. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) ' Exit Sub 'End If If ObjFactura.CveCliente > 0 Or CveEmpresaCRM > 0 Then If TmpDT.Rows.Count > 0 Then Dim ObjVentas As New ClsVentas() Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) Dim ObjContr As New ClsContratos(ObjVentas.IniciaTransacSQL()) Dim ObjOS As New ClsOS(ObjVentas.IniciaTransacSQL()) Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) Dim ObjClientes As New ClsClientes(ObjVentas.IniciaTransacSQL()) Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) Dim ObjDocCliente As New ClsEdocumentacion(ObjVentas.IniciaTransacSQL()) Dim ObjGeneral As New ClsGenerales(ObjVentas.IniciaTransacSQL()) Dim ObjContPaq As ClsContPAQi = Nothing 'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) ErrorList = New List(Of String) MensajeAlert = New StringBuilder 'CONTABILIDAD AUTOMATICA Y AC If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) ObjContPaq.IniciaTransacSQL() End If 'VERIFICA QUE EL FOLIO NO SEA IGUAL AL DE LA FACTURA ANTERIOR 'If ObjFactura.Folio = TxtFolio.Text.ToEntero() Then ' If ObjFolios.GetFolios(ObjFactura.TipoDocto, UsuarioActual.CveEmpresa) Then ' Dim DtFolios As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSucursal = {0} And Estado = 'Activo'", ObjFactura.CveSucursal)) ' If DtFolios.Rows.Count > 0 Then ' 'ViewState("CveFolio") = DtFolios.Rows(0)("CveFolio").ToString().ToEntero() ' 'ViewState("NumAprobacion") = CLng(DtFolios.Rows(0)("Aprobacion").ToString()) ' 'ViewState("FechaAprobacion") = DtFolios.Rows(0)("FechaAprobacion").ToString().ToDate ' 'ViewState("FolioActual") = DtFolios.Rows(0)("FActual").ToString() ' 'LblSerie.Text = DtFolios.Rows(0)("Serie").ToString() ' If UsuarioActual.CveEmpresa <> 72 Then ' ObjFactura.Folio = DtFolios.Rows(0)("FActual").ToString().ToEntero() ' End If ' End If ' End If 'End If 'GUARDA VENTA Dim TieneAnticipo As Boolean = False Dim CveAnticipoPadre As Integer = 0 ' vinculación con anticipo Dim FolioFiscalRelacionado As String = "" If GVAnticipos.Rows.Count > 0 Then Dim actualindex As Integer = 0 For Each row2 As GridViewRow In GVAnticipos.Rows If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then TieneAnticipo = True CveAnticipoPadre = row2.DataKey("CveVenta").ToEntero() 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 If ObjFactura.TipoDocto = "Egs" AndAlso ChkAplicaNCAnticipo.Checked Then EsNCAmortizacion = True End If Dim CveVentaAnterior As Integer = Me.CveVenta Dim CveTimbreCartaPorte As Integer = -1 GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjFactura, TmpDT, ObjFactura.CveNCaVincular, ObjContPaq, 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 'REGISTRAR UNA ENTREGA DIRECTA If TmpDT.COUNT("EntregaDirecta", "EntregaDirecta = 1") > 0 Then If Not RegistrarPaqueteriaGuia(ObjGeneral, ObjFactura.CveVenta) Then ErrorList.Add("Ocurrió un error al registrar la guia") End If End If 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)) If ErrorList.Count = 0 Then ' cambiar la condicion para saber si hay seleccionado If (TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2") OrElse NCDescuento Then Try 'LIMPIA LOS ANTICIPOS RELACIONADOS QUE YA SE APLICARON If ListaAnticiposAplicados IsNot Nothing Then ListaAnticiposAplicados.Clear() End If Dim CveVentaRelacionada As Integer = -1 If NuevaFactura = 1 Then CveVentaRelacionada = ObjFactura.CveVenta Else CveVentaRelacionada = CveAnticipoPadre End If If (TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2") OrElse (ListaNCDesc IsNot Nothing AndAlso ListaNCDesc.Count > 0) Then CreaObjetosVentaAmortizacion(ObjVentas, FolioFiscalRelacionado, CveVentaRelacionada, NCDescuento:=NCDescuento) If RegistrarNCAmortizacion(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, Nothing, Nothing, NCDescuento:=NCDescuento, ListaNCDescuento:=ListaNCDesc, IndexNC:=(If(DtVentasNC IsNot Nothing, DtVentasNC.Rows.Count - 1, 0))) Then ListaNotasCreditoGeneradas.Add(ObjFacturaDevolucion) End If End If If ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0 Then 'SI HAY UNA NOTA DE CREDITO REGISTRADA ANTERIORMENTE LIMPIA EL REGISTRO If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then DtVentasNC.Rows.RemoveAt(DtVentasNC.Rows.Count - 1) End If CreaObjetosVentaBonificacion(ObjVentas, FolioFiscalRelacionado, CveVentaRelacionada, NCDescuento:=NCDescuento) If RegistrarNCAmortizacion(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaBonificacion, ObjBancos, Nothing, Nothing, NCDescuento:=NCDescuento, ListaNCDescuento:=ListaNCBonificacion, IndexNC:=(DtVentasNC.Rows.Count - 1)) Then ListaNotasCreditoGeneradas.Add(ObjFacturaBonificacion) End If End If Catch ex As Exception OnError("Ocurrió un error al generar nota de crédito de amortización", ex) ErrorList.Add("No se pudo generar la nota de crédito de amortización") End Try If ListaNotasCreditoGeneradas Is Nothing AndAlso ListaNotasCreditoGeneradas.Count = 0 Then ErrorList.Add("No se pudo generar la nota de crédito de amortización") End If End If End If 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 = DtPagos.SUM("Importe").ToString().ToDecimal Dim ImporteRNC As Decimal = LblDescuentosRNC.Text.ToDecimal() If (ImportePagado + ImporteRNC + ObjFactura.DescuentoProntoPago) >= ObjFactura.Total Then Dim RespFacturaProntoPago = GenerarNCProntoPago(ObjVentas.IniciaTransacSQL(), ObjClientes, ObjContPaq, 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 'MARCA PARA NO SURTIR VENTA DE COTNRATO DE CONSIGNACION DE VENTA | [IPP] : PARCHE If ErrorList.Count = 0 Then If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then ErrorList.Add("No se pudo cancelar el movimiento de almacen de la Factura de consignación") End If End If End If If ErrorList.Count = 0 Then If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then If Not RegistraAlmacenConsignacionVenta(ObjInventario, ObjConta, ObjFactura, ObjContPaq) Then ErrorList.Add("Ocurrió un error al registrar los movimientos de almacén del contrato de consignación") End If End If End If If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 Then 'ACTUALIZA VENTA COTIZACIÓN If EraCotizacion = 1 And BtnEmitirImprimir.Text = "Facturar" Then If Not ObjVentas.UpdateVentaCotizacion(ObjFactura.CveVenta, Request("CveVenta").ToEntero()) Then ErrorList.Add("Ocurrió un error al actualizar la cotización") End If End If 'ACTUALIZA VENTAPADRE PEDIDO If Request("DevPed").ToEntero() > 0 AndAlso ErrorList.Count = 0 Then If Not ObjVentas.UpdateVentaCotizacion(Request("DevPed").ToEntero(), ObjFactura.CveVenta) Then ErrorList.Add("Ocurrió un error al actualizar la devolución de pedido") End If End If 'ACTUALIZA LA COLUMNA CveVentaFacturada If (Request("CveRemision") IsNot Nothing AndAlso ViewState("CveRemision").ToString().ToEntero() > 0) AndAlso (Request("Op") IsNot Nothing AndAlso Request("Op") = "Rem") AndAlso ErrorList.Count = 0 Then If Not ObjVentas.UpdateVentaRemision(ViewState("CveRemision").ToString().ToEntero(), ObjFactura.CveVenta) Then ErrorList.Add("Ocurrió un error al actualizar la remision") End If End If 'Agregamos las Cotizaciones a la tabla If DtCotizacionesPS IsNot Nothing AndAlso DtCotizacionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then Dim CveVentaDetalle As Integer = 0 Dim CveVentaDetallePadre As Integer = 0 Dim Cantidad As Decimal = 0 Dim CvePS As Integer = 0 Dim PU As Decimal = 0 For Each row As DataRow In DtCotizacionesPS.Rows Cantidad = DtCotizacionTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal CvePS = DtCotizacionTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero() PU = DtCotizacionTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero() CveVentaDetallePadre = row("CveVentaDetalle").ToString().ToEntero() If Not ObjVentas.AgregaCotizacionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then ErrorList.Add("Ocurrió un Error al agregar el detalle de la Cotización.") End If Next End If 'Marcamos las ventas anteriores a febrero como surtidas - Ajuste Compu If ErrorList.Count = 0 Then If Not ObjVentas.MarcarRemisionesSinSurtir(ObjVentas.CveVenta) Then ErrorList.Add("Ocurrió un Error al marcar la factura") End If End If If CveOS > 0 And FacturaMateriales = 1 AndAlso ErrorList.Count = 0 Then If SalidaAlmacenMateriales(ObjInventario, CveOS, ObjConta, True, 3) Then ErrorList.Add("Ocurrió un Error al dar salida de materiales de almacen") End If End If If CveFactura > 0 AndAlso ErrorList.Count = 0 Then If Not ObjVentas.UpdateVentaFacturas(CveFactura, ObjVentas.CveVenta, UsuarioActual.CveEmpresa) Then ErrorList.Add("No se pudo actualizar la Factura") End If End If If CveCicloComercial > 0 AndAlso ErrorList.Count = 0 Then If Not ObjContr.CicloComercialUpdate(CveCicloComercial, True, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then ErrorList.Add("No se pudo actualizar ") End If End If If ErrorList.Count = 0 AndAlso ObjFactura.CveVenta > 0 AndAlso DtDocumentacionCliente IsNot Nothing Then ' si se cargó algun documento If DtDocumentacionCliente.FiltraParametros("RutaArchivo <> ''").Rows.Count > 0 Then GuardaVentaDocumentosCliente(ObjFactura.CveVenta, ObjDocCliente) End If End If '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 If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 AndAlso (SeGuardoPrePoliza Or ObjFactura.TipoDocto.Contiene("Ped", "Cot", "DPe", "PeC", "PA", "Pd2")) Then ObjVentas.Commit() 'ENVIAR POLIZA VIRTUAL If ErrorList.Count = 0 Then If UsuarioActual.Empresa.Funcionalidad(576) = "1" AndAlso EsProduccion Then GeneraPolizaVentaWS(ObjFactura) 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 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 idCuentaContabilizacion = 10 End If Try If AutoConta Then If idCuentaContabilizacion > 0 Then If ObjConta.ContabilizarPrePoliza(ObjFactura.CvePrePoliza, ObjFactura.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then If ObjContPaq IsNot Nothing Then ObjContPaq.Commit() Else Alert("Ocurrió un Error al contabilizar, pongase en contacto con Soporte Técnico", TipoMensaje.MsgError) If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() End If Else Alert(String.Format("Falta asignación de las siguientes cuentas contables: {0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia) End If Else If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then If ObjContPaq IsNot Nothing Then ObjContPaq.Commit() End If End If Catch ex As Exception OnError("Ocurrió un error al contabilizar la factura", ex) End Try Try 'RMF, cuando es pedido, se manda autorización. If ObjFactura.TipoDocto.Contiene("PA") Then Dim Titulo As String = "Solicitud de autorización" 'usuarios de crédito y cobranza Dim Msg As String = String.Format("{0} - Folio {1} ", DdlSubProyectoDatos.SelectedItem.Text, TxtFolio.Text) If UsuarioActual.CveEmpresa = 119 Then ClsSisNotificaciones.SendNotificacionERP(1715, Titulo, Msg, 1) ClsSisNotificaciones.SendNotificacionERP(1815, Titulo, Msg, 1) ClsSisNotificaciones.SendNotificacionERP(1830, Titulo, Msg, 1) End If End If Catch ex As Exception OnError("Ocurrió un error al mandar las notificaciones de autorización", ex) End Try 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.CveEmpresa, UsuarioActual.CveUsuario, Request("CveEmbarqueManifiesto").ToEntero()) Then End If End If Catch ex As Exception OnError("Ocurrió un error al actualizar el embarque", 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 = 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 'Si es AMORTIZACIÓN ANTICIPO SOBRE FACTURA EN CERO no debe timbrar If DdlTipoAmortizacionAnticipo.SelectedValue = "3" Then DebeTimbrar = False End If If UsuarioActual.TienePermisoProceso(335) Then DebeTimbrar = False End If 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 ChkEmitirCartaPorte.Checked AndAlso CveTimbreCartaPorte > 0 Then Dim RespCartaPorte = Timbres.PreParaCartaPorteFactura(CveTimbreCartaPorte, UsuarioActual) If Not RespCartaPorte.TieneError Then ObjFactura.Timbre.Complementos.CartaPorte = RespCartaPorte.CartaPorte Else DebeTimbrar = False Alert(RespCartaPorte.Mensaje, TipoMensaje.MsgAdvertencia) End If 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 = 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 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 = 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 SeTimbro AndAlso ObjFactura.TipoDocto.Contiene("Ing") Then EstatusSMS = EnviarSMSTimbrado(ObjEventos) 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 'VERIFICAR 100% AVANCE A IMPORTE Y CANTIDAD Try If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso CveContrato > 0 Then If ObjContr.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then If ObjContr.DtResultados.Rows.Count > 0 Then 'SI ES FLEXIBLE QUE NOTIFIQUE EL MONTO MAXIMO, SI NO LO ES QUE NOTIFIQUE EL PORCENTAJE ALCANZADO... FLEXIBLE = 2, NO FLEXIBLE = 1 If ObjContr.DtResultados.Rows(0)("ModalidadDetalle").ToString() = "1" Then Dim PorcentajeAvance As Double = ObjContr.DtResultados.Rows(0)("ContratoAvance").ToString().ToDouble If PorcentajeAvance >= 100 Then EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString()) End If Else Dim MontoMaximo As Double = ObjContr.DtResultados.Rows(0)("ImporteMax").ToString().ToDouble Dim Avance As Double = ObjContr.DtResultados.Rows(0)("Avance").ToString().ToDouble Dim PorcentajeAvance As Double = (Avance / MontoMaximo) * 100 If PorcentajeAvance >= 100 And MontoMaximo > 0 Then EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString(), MontoMaximo) End If End If End If End If End If Catch ex As Exception OnError("Ocurrió un error al notificar el avance.", ex) End Try 'MENSAJE PRINCIPAL MensajeAlert.AppendFormat(String.Format("
    La {0}: {1} se generó correctamente.

    ", ObjFactura.TipoDocumento, ObjFactura.SerieFolio)) ' DESCARGA XML - SI SE TIMBRA MANDA CORREO CON FACTURA If SeTimbro Then Dim ArchivoXML = String.Format("{0}/XML/{1}/{2}.xml", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) If File.Exists(ArchivoXML) Then MensajeAlert.AppendFormat("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", ObjFactura.SerieFolio, ObjFactura.TipoDocto))) End If Try 'MANDA CORREO Dim strURLHOST = String.Format("{0}://{1}:{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port) Dim Factura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=False, CargaDTDetalle:=False, CargaDatosCliente:=False, CargaDatosRelacionados:=False) Dim Hilo As New System.Threading.Thread(Sub() GeneraPDFFactura(ChkEnviarFactura.Checked, 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 'ERROR DE NO TIMBRADO If Not SeTimbro And (DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue = "Ant") Then MensajeAlert.AppendFormat("La factura no se pudo timbrar.
    Por favor intentelo de nuevo a traves del boton Emitir.") End If 'ERROR DE NO TIMBRADO NC If Not IsNothing(ObjNC) AndAlso ObjNC.Count > 0 AndAlso Not SeTimbroNC Then MensajeAlert.AppendFormat("
    La NC #{0} no se pudo timbrar.
    Por favor intentelo de nuevo a traves del boton Emitir.", CType(ObjNC(0), Modelos.Factura).SerieFolio) End If 'NOTIFICACION DE SMS Select Case EstatusSMS Case 1 MensajeAlert.AppendFormat("
    Notificación SMS: enviado con éxito al cliente al celular: {0}", ObjFactura.Cliente.CobranzaTelefono) Case 2 MensajeAlert.AppendFormat("
    Notificación SMS: sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.") Case 3 MensajeAlert.AppendFormat("
    Notificación SMS: sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.") End Select 'AUTO DESCARGAR PDF If UsuarioActual.CveEmpresa.Contiene(72) Then If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") Then RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))}'", "Imprimir") End If End If 'DESCARGAR PDF DE CICOVISA 'If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 Then ' If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then ' MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=CIC&CVEVENTA={0}", CveVenta))) ' End If 'End If If DdlTipoComprobante.SelectedValue = "Cot" Then If Not CveEmpresaCRM > 0 Then 'EN EMPRESA DE ACUMULADORES NO DESCARGAR EL PDF If UsuarioActual.Empresa.Funcionalidad(531) <> "1" Then If CveVenta > 0 Then MensajeAlert = New StringBuilder Dim ArchivoCotizacion As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.rdlc", UsuarioActual.Empresa.Ruta)) If Opcion = "Cot" And UsuarioActual.Empresa.Funcionalidad(558) = "1" Then MensajeAlert.AppendFormat("Facturar

    ", CveVenta) End If If ArchivoCotizacion.Exists Then MensajeAlert.AppendFormat("
    ", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta))) Else MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ") End If End If GeneraPDFCotizacion(ChkEnviarFactura.Checked) ' MANDA CORREO End If ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then If UsuarioActual.CveEmpresa.Contiene(81, 109) Then EnviaPDFRemision(ChkEnviarFactura.Checked) End If End If 'ENVIA CORREO CON DETALLE DEL CONTRATO If DdlTipoComprobante.SelectedValue.Contiene("DPe", "Ped") Then If Not String.IsNullOrEmpty(CorreoNotificacionPedDev) Then EnviarCorreoDevPed() End If End If 'MOVIMIENTO DE ALMACEN If ObjFactura.Inv_CveMovimiento > 0 Then MensajeAlert.AppendFormat("

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

    Se generó una Nota de crédito Folio: {0} amortizando el anticipo
    ", ObjFacturaDevolucion.Folio) End If If RBLPago.SelectedValue.ToEntero() = 2 And TxtCambio.Text.ToDecimal > 0 Then MensajeAlert.AppendFormat("

    Su cambio es de ${0}
    ", TxtCambio.Text.ToDecimal.FormatoNumero(2)) 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 Alert(MensajeAlert.ToString(), TipoMensaje.MsgDosBotones, Liga, TextoConfirmacion:="Seguir Registrando", TextoSegundoBoton:="Ir al Cliente", JSBtn2:=Liga2, ShowCloseButton:=False) MensajeAlert.Clear() Try 'LIMPIA CONDICIONES DE PAGO - CONTADO RBLPago.SelectedValue = "1" LimpiaEscondeContado() BtnEmitirImprimir.Visible = False ObjFactura = Nothing Catch ex As Exception OnError("Ocurrió un error al limpiar los datos", ex) End Try Else ObjVentas.RollBack() If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() For Each ErrorItem In ErrorList Alert(ErrorItem, TipoMensaje.MsgAdvertencia) Next 'MUESTA ALERT ERROR Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) End If ObjVentas.Dispose() ObjConta.Dispose() ObjInventario.Dispose() ObjCGame.Dispose() ObjContr.Dispose() ObjDocCliente.Dispose() 'ObjFolios.Dispose() ErrorList.Clear() ErrorList = Nothing MensajeAlert = Nothing If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() TmpDT = TmpDTError.Copy Else ObjVentas.RollBack() If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() For Each ErrorItem In ErrorList Alert(ErrorItem, TipoMensaje.MsgAdvertencia) Next 'MUESTA ALERT ERROR Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) ObjVentas.Dispose() ObjConta.Dispose() ObjInventario.Dispose() ObjCGame.Dispose() ObjContr.Dispose() ObjDocCliente.Dispose() 'ObjFolios.Dispose() ErrorList.Clear() ErrorList = Nothing MensajeAlert = Nothing If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() TmpDT = TmpDTError.Copy End If ObjFactura = Nothing ListaNotasCreditoGeneradas = Nothing End If End If End Sub Private Sub CreaObjetosVentaAmortizacion(ObjVentas As ClsVentas, FolioFiscalRelacionado As String, CveAnticipoPadre As Integer, Optional CveVentasPadre As Integer = -1, Optional NCDescuento As Boolean = False) ObjFacturaDevolucion = New Modelos.Factura ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() If CveVentasPadre > 0 Then ObjFacturaDevolucion.CveVentaPadre = CveVentasPadre ObjFacturaDevolucion.CveVentaRelacion = CveVentasPadre Else ObjFacturaDevolucion.CveVentaPadre = ObjVentas.CveVenta ObjFacturaDevolucion.CveVentaRelacion = ObjVentas.CveVenta End If ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero() ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") 'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim 'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero(), -1) ObjFacturaDevolucion.Serie = LblSerie.Text ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) ObjFacturaDevolucion.CvePrePoliza = -1 ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero() ObjFacturaDevolucion.MetodoPago = "" ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim ' ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero(), -1) ' ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") 'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim 'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito ObjFacturaDevolucion.FormaPago = 0 ObjFacturaDevolucion.TipoDocto = "Egs" If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Dim ObjFolios As New ClsGralFolios() Dim TipoDoctoConsulta As String = If(ObjFacturaDevolucion.TipoDocto = "Ant", "Ing", If(ObjFacturaDevolucion.TipoDocto = "PA", "Rem", ObjFacturaDevolucion.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 ObjFacturaDevolucion.Serie = DT.Rows(0)("Serie").ToString() End If DT.Dispose() End If ObjFolios.Dispose() End If ObjFacturaDevolucion.Fecha = Now If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then ObjFacturaDevolucion.Version = "4.0" If ObjFacturaDevolucion.Cliente Is Nothing Then ObjFacturaDevolucion.Cliente = New Modelos.ClienteModel End If ObjFacturaDevolucion.Cliente.CodigoRegimenFiscal = ClienteCodigoRegimenFiscal ObjFacturaDevolucion.Cliente.RegimenFiscal = ClienteRegimenFiscal Else ObjFacturaDevolucion.Version = "3.3" End If ObjFacturaDevolucion.CveMetodoPago33 = 1 ObjFacturaDevolucion.MetodoPago33 = "Pago en una sola exhibición" ObjFacturaDevolucion.ClaveMetodoPagoSAT = "PUE" ObjFacturaDevolucion.CveFormaPago33 = 21 ObjFacturaDevolucion.FormaPago33 = "Aplicación de anticipos" ObjFacturaDevolucion.FormaPagoSAT33 = "30" ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero() ObjFacturaDevolucion.UsoCFDI = DdlUsoCFDI.SelectedItem.Text ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") ObjFacturaDevolucion.CveTipoRelacion = DdlTipoRelacionAnticipo.SelectedValue.ToEntero() ObjFacturaDevolucion.TipoRelacion = "07" If NCDescuento Then ObjFacturaDevolucion.CveTipoRelacion = 1 ObjFacturaDevolucion.TipoRelacion = "01" End If Dim Fol As New List(Of String) Fol.Add(FolioFiscalRelacionado) ObjFacturaDevolucion.UUIDRelacionados = Fol Select Case ObjFacturaDevolucion.TipoDocto Case "Ing" ObjFacturaDevolucion.TipoDocumento = "Factura" Case "REM" ObjFacturaDevolucion.TipoDocumento = "Remision" Case "Cot" ObjFacturaDevolucion.TipoDocumento = "Cotizacion" Case "Egs" ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito" Case "Dev" ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución" Case Else ObjFacturaDevolucion.TipoDocumento = "" End Select If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto End If ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate ObjFacturaDevolucion.CveCorte = CveCorte ObjFacturaDevolucion.CveMesa = -1 ObjFacturaDevolucion.NumeroPersonas = 0 ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "") ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero() ObjFacturaDevolucion.Entrega = Entrega ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate ObjFacturaDevolucion.CveVentaPadre = CveAnticipoPadre ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero() If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero() ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero() ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFacturaDevolucion.MonedaAbreviatura = "" If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Clear() End If Dim DR As DataRow = TmpDTImpuestos.NewRow() If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() 'If DdlFormatoImpresion.SelectedValue.ToEntero() = 3 Or DdlFormatoImpresion.SelectedValue.ToEntero() = 4 Then ' DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (TxtSubTotal.Text.ToDecimal + TxtIVA.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal) : DR("Orden") = 55 : TmpDTImpuestos.Rows.Add(DR) ' DR = TmpDTImpuestos.NewRow() 'End If For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then Dim Orden As Integer = 80 If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal > 0 Then DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString() : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal.RoundSQL(2) : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString() : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString() : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString().ToEntero() : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() Orden = Orden + 1 End If End If Next If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC") 'DETALLES If NCDescuento Then PreparaNCDescuento(ObjFacturaDevolucion) Else ObjFacturaDevolucion.DtDetalle = TmpDT ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal ObjFacturaDevolucion.TotalImpuestoLocal = ObjFacturaDevolucion.DtDeduccion.SUMD("Importe", "TipoImpuesto = 1") ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal End If 'Totales, Y se llena TmpDTImpuestos 'ObjFactura.BZDescripcion = TxtBZDescripcion.Text.Trim 'ObjFactura.BZNombreCorto = TxtBZNombreCorto.Text.Trim 'ObjFactura.BZTotalLetra = TxtBZTotalLetra.Text.Trim 'otros ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero() If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then ObjFacturaDevolucion.TipoCambio = 1 ObjFacturaDevolucion.CveMoneda = 1 End If ObjFacturaDevolucion.DtFirmas = DTmpF 'CLIENTE ObjFacturaDevolucion.CveCliente = CveCliente ObjFacturaDevolucion.SetCliente() ''SUCURSAL 'ObjFacturaDevolucion.CveSucursal = DdlSucursal.SelectedValue.ToEntero() 'ObjFacturaDevolucion.SetSucursalMatriz(Me) 'ObjFacturaDevolucion.SetSucursal(Me) ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel If Me.ClienteSucursal IsNot Nothing Then ObjFacturaDevolucion.ClienteSucursal.RFC = Me.ClienteSucursal.RFC ObjFacturaDevolucion.ClienteSucursal.Nombre = Me.ClienteSucursal.Nombre End If ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString() ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero() > 0, DdlSucursalCliente.SelectedItem.Text, "") ObjFacturaDevolucion.SetSubProyectoMatriz(Me) ObjFacturaDevolucion.SetSubProyecto(Me) 'ENVIO DIRECCION ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel If ChkDireccionEnvio.Checked Then If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())).Rows.Count > 0 Then For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())).Rows ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString().ToEntero() ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString() ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString() ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString() ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString() ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString() Next End If End If 'SI NO ES REFACTURACION If NuevaFactura <> 1 Then If DtVentasNC Is Nothing Then InicializaDTVentasNC() Dim Drt = DtVentasNC.NewRow Drt("CveVenta") = ObjFactura.CveVenta Drt("Importe") = 0 Drt("FolioFiscal") = ObjFactura.FolioFiscal Drt("Folio") = ObjFactura.SerieFolio DtVentasNC.Rows.Add(Drt) DtVentasNC.AcceptChanges() End If End Sub Private Sub CreaObjetosVentaBonificacion(ObjVentas As ClsVentas, FolioFiscalRelacionado As String, CveAnticipoPadre As Integer, Optional CveVentasPadre As Integer = -1, Optional NCDescuento As Boolean = False) ObjFacturaBonificacion = New Modelos.Factura ObjFacturaBonificacion.CveUsuario = UsuarioActual.CveUsuario ObjFacturaBonificacion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() If CveVentasPadre > 0 Then ObjFacturaBonificacion.CveVentaPadre = CveVentasPadre ObjFacturaBonificacion.CveVentaRelacion = CveVentasPadre Else ObjFacturaBonificacion.CveVentaPadre = ObjVentas.CveVenta ObjFacturaBonificacion.CveVentaRelacion = ObjVentas.CveVenta End If ObjFacturaBonificacion.CveEmpresa = UsuarioActual.CveEmpresa ObjFacturaBonificacion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) ObjFacturaBonificacion.ConvertirPesos = ChkConvertirDoctoPesos.Checked ObjFacturaBonificacion.CveMoneda = DdlMoneda.SelectedValue.ToEntero() ObjFacturaBonificacion.Moneda = DdlMoneda.SelectedItem.Text ObjFacturaBonificacion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") 'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim 'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero(), -1) ObjFacturaBonificacion.Serie = LblSerie.Text ObjFacturaBonificacion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) ObjFacturaBonificacion.CvePrePoliza = -1 ObjFacturaBonificacion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero() ObjFacturaBonificacion.MetodoPago = "" ObjFacturaBonificacion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFacturaBonificacion.UsuarioCreo = LblUsuario.Text.Trim ' ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero(), -1) ' ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") 'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim 'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim ObjFacturaBonificacion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito ObjFacturaBonificacion.FormaPago = 0 ObjFacturaBonificacion.TipoDocto = "Egs" If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Dim ObjFolios As New ClsGralFolios() Dim TipoDoctoConsulta As String = If(ObjFacturaBonificacion.TipoDocto = "Ant", "Ing", If(ObjFacturaBonificacion.TipoDocto = "PA", "Rem", ObjFacturaBonificacion.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 ObjFacturaBonificacion.Serie = DT.Rows(0)("Serie").ToString() End If DT.Dispose() End If ObjFolios.Dispose() End If ObjFacturaBonificacion.Fecha = Now If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then ObjFacturaBonificacion.Version = "4.0" If ObjFacturaBonificacion.Cliente Is Nothing Then ObjFacturaBonificacion.Cliente = New Modelos.ClienteModel End If ObjFacturaBonificacion.Cliente.CodigoRegimenFiscal = ClienteCodigoRegimenFiscal ObjFacturaBonificacion.Cliente.RegimenFiscal = ClienteRegimenFiscal Else ObjFacturaBonificacion.Version = "3.3" End If ObjFacturaBonificacion.CveMetodoPago33 = 1 ObjFacturaBonificacion.MetodoPago33 = "Pago en una sola exhibición" ObjFacturaBonificacion.ClaveMetodoPagoSAT = "PUE" ObjFacturaBonificacion.CveFormaPago33 = 21 ObjFacturaBonificacion.FormaPago33 = "Aplicación de anticipos" ObjFacturaBonificacion.FormaPagoSAT33 = "30" ObjFacturaBonificacion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero() ObjFacturaBonificacion.UsoCFDI = DdlUsoCFDI.SelectedItem.Text ObjFacturaBonificacion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") ObjFacturaBonificacion.CveTipoRelacion = 1 ObjFacturaBonificacion.TipoRelacion = "01" Dim Fol As New List(Of String) Fol.Add(FolioFiscalRelacionado) ObjFacturaBonificacion.UUIDRelacionados = Fol Select Case ObjFacturaBonificacion.TipoDocto Case "Ing" ObjFacturaBonificacion.TipoDocumento = "Factura" Case "REM" ObjFacturaBonificacion.TipoDocumento = "Remision" Case "Cot" ObjFacturaBonificacion.TipoDocumento = "Cotizacion" Case "Egs" ObjFacturaBonificacion.TipoDocumento = "Nota de Crédito" Case "Dev" ObjFacturaBonificacion.TipoDocumento = "Nota de Devolución" Case Else ObjFacturaBonificacion.TipoDocumento = "" End Select If ObjFacturaBonificacion.TipoDocto IsNot Nothing Then ViewState("TipoDoctoDevolucion") = ObjFacturaBonificacion.TipoDocto End If ObjFacturaBonificacion.Fech1 = TxtFech1.Text.Trim.ToDate ObjFacturaBonificacion.Fech2 = TxtFech2.Text.Trim.ToDate ObjFacturaBonificacion.Fech3 = TxtFech3.Text.Trim.ToDate ObjFacturaBonificacion.Alfa1 = TxtAlfa1.Text.Trim ObjFacturaBonificacion.Alfa2 = TxtAlfa2.Text.Trim ObjFacturaBonificacion.Alfa3 = TxtAlfa3.Text.Trim ObjFacturaBonificacion.Num1 = TxtNum1.Text.Trim.ToDouble ObjFacturaBonificacion.Num2 = TxtNum2.Text.Trim.ToDouble ObjFacturaBonificacion.Num3 = If(ObjFacturaBonificacion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) ObjFacturaBonificacion.FechaPago = TxtFechaPago.Text.ToDate ObjFacturaBonificacion.CveCorte = CveCorte ObjFacturaBonificacion.CveMesa = -1 ObjFacturaBonificacion.NumeroPersonas = 0 ObjFacturaBonificacion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) ObjFacturaBonificacion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "") ObjFacturaBonificacion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero() ObjFacturaBonificacion.Entrega = Entrega ObjFacturaBonificacion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate ObjFacturaBonificacion.CveVentaPadre = CveAnticipoPadre ObjFacturaBonificacion.CveVendedor = DdlVendedor.SelectedValue.ToEntero() If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If ObjFacturaBonificacion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate ObjFacturaBonificacion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero() ObjFacturaBonificacion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero() ObjFacturaBonificacion.AtencionA = If(ObjFacturaBonificacion.TipoDocto = "Cot" Or (ObjFacturaBonificacion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") ObjFacturaBonificacion.MotivoDescuento = TxtMotivoDescuento.Text.Trim ObjFacturaBonificacion.Observaciones = TxtObsFact.Text.Trim ObjFacturaBonificacion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFacturaBonificacion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFacturaBonificacion.MonedaAbreviatura = "" If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Clear() End If Dim DR As DataRow = TmpDTImpuestos.NewRow() If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() 'If DdlFormatoImpresion.SelectedValue.ToEntero() = 3 Or DdlFormatoImpresion.SelectedValue.ToEntero() = 4 Then ' DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (TxtSubTotal.Text.ToDecimal + TxtIVA.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal) : DR("Orden") = 55 : TmpDTImpuestos.Rows.Add(DR) ' DR = TmpDTImpuestos.NewRow() 'End If For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then Dim Orden As Integer = 80 If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal > 0 Then DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString() : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal.RoundSQL(2) : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString() : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString() : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString().ToEntero() : TmpDTImpuestos.Rows.Add(DR) DR = TmpDTImpuestos.NewRow() Orden = Orden + 1 End If End If Next If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR) ObjFacturaBonificacion.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC") 'DETALLES PreparaNCBonificacion(ObjFacturaBonificacion) 'otros ObjFacturaBonificacion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFacturaBonificacion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFacturaBonificacion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero() If ObjFacturaBonificacion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then ObjFacturaBonificacion.TipoCambio = 1 ObjFacturaBonificacion.CveMoneda = 1 End If ObjFacturaBonificacion.DtFirmas = DTmpF 'CLIENTE ObjFacturaBonificacion.CveCliente = CveCliente ObjFacturaBonificacion.SetCliente() ''SUCURSAL 'ObjFacturaBonificacion.CveSucursal = DdlSucursal.SelectedValue.ToEntero() 'ObjFacturaBonificacion.SetSucursalMatriz(Me) 'ObjFacturaBonificacion.SetSucursal(Me) ObjFacturaBonificacion.ClienteSucursal = New Modelos.SucursalModel If Me.ClienteSucursal IsNot Nothing Then ObjFacturaBonificacion.ClienteSucursal.Nombre = Me.ClienteSucursal.Nombre ObjFacturaBonificacion.ClienteSucursal.RFC = Me.ClienteSucursal.RFC End If ObjFacturaBonificacion.ClienteSucursal.NoExt = CliNoExt ObjFacturaBonificacion.ClienteSucursal.NoInt = CliNoInt ObjFacturaBonificacion.ClienteSucursal.Localidad = CliLocalidad ObjFacturaBonificacion.ClienteSucursal.Direccion = LblDireccion.Text ObjFacturaBonificacion.ClienteSucursal.Colonia = LblColonia.Text ObjFacturaBonificacion.ClienteSucursal.Municipio = LblCiudad.Text ObjFacturaBonificacion.ClienteSucursal.Estado = LblEstado.Text ObjFacturaBonificacion.ClienteSucursal.CP = LblCP.Text ObjFacturaBonificacion.ClienteSucursal.Pais = CliPais ObjFacturaBonificacion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString() ObjFacturaBonificacion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text ObjFacturaBonificacion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero() > 0, DdlSucursalCliente.SelectedItem.Text, "") ObjFacturaBonificacion.SetSubProyectoMatriz(Me) ObjFacturaBonificacion.SetSubProyecto(Me) 'ENVIO DIRECCION ObjFacturaBonificacion.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 ObjFacturaBonificacion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString().ToEntero() ObjFacturaBonificacion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString() ObjFacturaBonificacion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString() ObjFacturaBonificacion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString() ObjFacturaBonificacion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString() ObjFacturaBonificacion.EnviarA.EnvioCP = Row("EnvioCP").ToString() Next End If End If 'SI NO ES REFACTURACION If NuevaFactura <> 1 AndAlso Not AplicaDocumentoNuevoNC Then If DtVentasNC Is Nothing Then InicializaDTVentasNC() Dim Drt = DtVentasNC.NewRow Drt("CveVenta") = ObjFactura.CveVenta Drt("Importe") = 0 Drt("FolioFiscal") = ObjFactura.FolioFiscal Drt("Folio") = ObjFactura.SerieFolio DtVentasNC.Rows.Add(Drt) DtVentasNC.AcceptChanges() End If 'ASIGNAR RFC RECEPTOR If ObjFacturaBonificacion.Timbre IsNot Nothing Then If ObjFacturaBonificacion.Timbre.Receptor IsNot Nothing Then ObjFacturaBonificacion.RFCReceptor = ObjFacturaBonificacion.Timbre.Receptor.RFC End If End If End Sub Private Function RegistrarNCAmortizacion(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos, Optional NCDescuento As Boolean = False, Optional ListaNCDescuento As List(Of Modelos.Factura) = Nothing, Optional IndexNC As Integer = 0) As Boolean Dim ProcesoCorrecto As Boolean = True 'GENERAMOS EL NUEVO FOLIO Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue.ToEntero())) If DT.Rows.Count > 0 Then factura.Serie = DT.Rows(0)("Serie").ToString() factura.Folio = DT.Rows(0)("FActual").ToString().ToEntero() Else ProcesoCorrecto = False End If DT.Dispose() End If If NCDescuento Then factura.Num3 = 1000 ' MARCADA PARA AUMENTAR EL FOLIO If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then DtVentasNC.Rows(IndexNC)("Importe") = factura.Total DtVentasNC.Rows(IndexNC)("TC") = factura.TipoCambio DtVentasNC.Rows(IndexNC)("TCCambioValuacion") = factura.TipoCambio End If factura.Timbre = PreParaTimbre(factura) factura.CveVentaPadre = Me.CveVenta 'Registramos la venta GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, factura.DtDetalle, -1, ObjContPaq, ObjBancos, EsNCAmortizacion:=False, NCDescuento:=True, ListaNCDescuento:=ListaNCDescuento) Else 'GENERO LOS DATOS DE LA NC Dim tmpcon As DataTable = TmpDT.Clone tmpcon.Clear() Dim DtImpuestos As New DataTable DtImpuestos.Columns.Add("ImportePU", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteTotal", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeIVA", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteIVA", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteRetIVA", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeRetISR", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteRetISR", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeIEPS", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteIEPS", GetType(Decimal)) DtImpuestos.Columns.Add("CveSubProyecto", GetType(Integer)) DtImpuestos.AcceptChanges() Dim drpss As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlNCPSAnt.SelectedValue.ToEntero()).FiltroPrimero("") If drpss IsNot Nothing Then Dim ii As Integer = 1 Dim CveVentaP As Integer = 0 For Each gvrt As GridViewRow In GVAnticipos.Rows If gvrt.FCCheckBox(String.Format("Chk{0}", gvrt.RowIndex)).Checked Then 'SI SE VA HACER UNA NC EN DOLARES CON UN ANTICIPO EN PESOS If gvrt.DataKey("CveMoneda").ToEntero() = 1 AndAlso gvrt.FCTextBox(String.Format("TxtTC{0}", gvrt.RowIndex)).Text.ToDecimal() > 0 AndAlso factura.CveMoneda = 2 Then factura.TipoCambio = gvrt.FCTextBox(String.Format("TxtTC{0}", gvrt.RowIndex)).Text.ToDecimal() End If Dim CveSub As Integer = TmpDT.FiltroPrimeroValor("CveSubProyecto").ToEntero() Dim dr As DataRow = tmpcon.NewRow Dim Cantidad As Decimal = 1 Dim tTipoAmortizacion As Integer = If(DdlTipoAmortizacionAnticipo.SelectedValue = "2", 1, 2) DtImpuestos = CargaDtImpuestosNC(gvrt.DataKey("CveVenta").ToString().ToEntero(), gvrt.FCTextBox(String.Format("TxtAnticipo{0}", gvrt.RowIndex)).Text.ToDecimal, AplicaImpuestosLocales:=True, NCDescuento:=False, NivelTotal:=tTipoAmortizacion) Dim query = From ddr In DtImpuestos Group By PorcentajeIVA = ddr("PorcentajeIVA").ToString().ToDecimal, PorcentajeRetIVA = ddr("PorcentajeRetIVA").ToString().ToDecimal, PorcentajeRetISR = ddr("PorcentajeRetISR").ToString().ToDecimal, PorcentajeIEPS = ddr("PorcentajeIEPS").ToString().ToDecimal Into x = Group Select ImportePU = x.Sum(Function(s) s("ImportePU").ToString().ToDecimal), ImporteTotal = x.Sum(Function(s) s("ImporteTotal").ToString().ToDecimal), ImporteIVA = x.Sum(Function(s) (s("ImporteIVA").ToString().ToDecimal)).RoundSQL(2), ' Math.Round(s("ImporteIVA").ToString().ToDecimal, 2)) * (1 + PorcentajeIEPS) * PorcentajeIVA, ImporteRetIVA = x.Sum(Function(s) Math.Round(s("ImporteRetIVA").ToString().ToDecimal, 2)),' Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeRetIVA, ImporteRetISR = x.Sum(Function(s) Math.Round(s("ImporteRetISR").ToString().ToDecimal, 2)),' Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeRetISR, ImporteIEPS = x.Sum(Function(s) Math.Round(s("ImporteIEPS").ToString().ToDecimal, 2)), 'Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeIEPS, PorcentajeIVA = PorcentajeIVA, PorcentajeRetIVA = PorcentajeRetIVA, PorcentajeRetISR = PorcentajeRetISR, PorcentajeIEPS = PorcentajeIEPS DtImpuestos = query.QueryToDataTable(False) For Each Drr As DataRow In DtImpuestos.Rows dr("CvePS") = drpss("CvePS") dr("PS") = drpss("PS") dr("OBS") = drpss("PS") dr("PU") = Drr("ImportePU").ToString().ToDecimal dr("Cantidad") = Cantidad dr("CveUM") = drpss("CveUnidadMedida") dr("SATClaveProdServ") = "84111506" dr("SATClaveUM") = "ACT" dr("Consec") = ii dr("PorcentajeIVA") = Drr("PorcentajeIVA").ToString().ToDecimal dr("IVA") = Drr("PorcentajeIVA") dr("ImporteIVA") = Drr("ImporteIVA").ToString().ToDecimal dr("ImporteRetIVA") = Drr("ImporteRetIVA").ToString().ToDecimal dr("ImporteRetISR") = Drr("ImporteRetISR").ToString().ToDecimal dr("PorcentajeRetIVA") = Drr("PorcentajeRetIVA").ToString().ToDecimal dr("PorcentajeRetISR") = Drr("PorcentajeRetISR").ToString().ToDecimal dr("PorcentajeIEPS") = Drr("PorcentajeIEPS").ToString().ToDecimal dr("ImporteIEPS") = Drr("ImporteIEPS").ToString().ToDecimal dr("IEPS") = Drr("ImporteIEPS").ToString().ToDecimal dr("Descuento") = Math.Round(0, NumeroDecimales) dr("TipoDescuento") = HdnTipoDescuento.Value dr("Total") = Drr("ImporteTotal").ToString().ToDecimal dr("CveClasificacion") = drpss("CveClasificacion") dr("CveSubProyecto") = CveSub dr("TotalImporte") = Drr("ImporteTotal").ToString().ToDecimal CveVentaP = gvrt.DataKey("CveVenta").ToEntero() tmpcon.Rows.Add(dr) ii += 1 Next End If Next '**** IMPUESTOS LOCALES factura.DtDetalle = tmpcon Dim TotalSubTotal As Decimal = tmpcon.SUM("TotalImporte").ToDecimal Dim TotalDescuentos As Decimal = tmpcon.SUM("Descuento").ToDecimal Dim TotalIVA As Decimal = tmpcon.SUM("ImporteIVA").ToDecimal Dim TotalIEPS As Decimal = tmpcon.SUM("ImporteIEPS").ToDecimal Dim TotalRetIVA As Decimal = tmpcon.SUM("ImporteRetIVA").ToDecimal Dim TotalRetISR As Decimal = tmpcon.SUM("ImporteRetISR").ToDecimal Dim Total As Decimal = 0 Dim TotalImpuestosLocales As Decimal = factura.TotalImpuestoLocal.ToString().ToDecimal Total = (TotalSubTotal - TotalDescuentos + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) factura.SubTotal = TotalSubTotal factura.Descuento = 0 factura.IVA = TotalIVA factura.IEPS = TotalIEPS factura.RetIVA = TotalRetIVA factura.RetISR = TotalRetISR factura.Total = Total 'SI ES REFACTURACION DEBE RELACIONAR CON LA VENTA NUEVA If NuevaFactura = 1 Then factura.CveVentaPadre = ObjFactura.CveVenta Else factura.CveVentaPadre = CveVentaP End If If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then DtVentasNC.Rows(0)("Importe") = Total DtVentasNC.Rows(0)("TC") = factura.TipoCambio DtVentasNC.Rows(0)("TCCambioValuacion") = factura.TipoCambio End If ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) 'Registramos la venta GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, tmpcon, -1, ObjContPaq, ObjBancos, EsNCAmortizacion:=True) Else ErrorList.Add("No se encontró un producto para generar la nota de crédito") End If End If Return ProcesoCorrecto 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 If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then ObjFactura.Version = "4.0" If ObjFactura.Cliente Is Nothing Then ObjFactura.Cliente = New Modelos.ClienteModel End If ObjFactura.Cliente.CodigoRegimenFiscal = ClienteCodigoRegimenFiscal ObjFactura.Cliente.RegimenFiscal = ClienteRegimenFiscal Else ObjFactura.Version = "3.3" End If 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 'ObjFactura.RefDocto = TxtDocto.Text.Trim If EsCreaApartirDe Then ViewState("EstablecioFolio") = False End If 'si es cancelacion, debe de conservar el folio actual If Not EsCancelacion Then ObjFactura.Folio = If(EstablecioFolio Or VistaPrevia Or (CveVenta > 0 And (NuevaFactura.Contiene(0, 2))), TxtFolio.Text.Trim.ToEntero(), -1) '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 = If(ExFolioFactura, FolioXML.ToEntero(), -1) ObjFactura.Serie = If(VistaPrevia, "VistaPrevia", LblSerie.Text) 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(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) ObjFactura.CvePrePoliza = -1 ObjFactura.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero() ObjFactura.MetodoPago = "" ' DdlMetodoPago.SelectedItem.Text ObjFactura.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFactura.FechaVencimiento = TxtFechaPago.Text.ToDate ' If ObjFactura.TipoDocto = "Cot" Then ObjFactura.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero() ObjFactura.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero() > 0, DdlMetodoPago33.SelectedItem.Text, "") ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFactura.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero() ObjFactura.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero() > 0, DdlFormaPago33.SelectedItem.Text, "") ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}") ObjFactura.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero() ObjFactura.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero() > 0, DdlUsoCFDI.SelectedItem.Text, "") ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") ' End If ObjFactura.UsuarioCreo = LblUsuario.Text.Trim ObjFactura.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero(), -1) ObjFactura.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") 'ObjFactura.NumeroCuenta = TxtNumCtaPago.Text.Trim 'ObjFactura.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim ObjFactura.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, If(RBLPago.SelectedValue = "1", 1, 2)) ' 0 - Contado, 1 - Credito, 2 - termianl ObjFactura.FormaPago = 0 'DdlFormaPago.SelectedValue.ToEntero() 'ObjFactura.AnticipoPosicion = DdlAmortizacionConceptos.SelectedValue.ToEntero() 'ObjFactura.AnticipoEnSubTotal = If(ChkAnticipoEnSubTotal.Checked, True, False) 'ObjFactura.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero() 'ObjFactura.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text) 'ObjFactura.PedidoContrato = TxtPedidoContrato.Text.Trim ObjFactura.AtencionA = TxtAtencionA.Text ObjFactura.FordGSDB = "" ObjFactura.NumeroContrato = NumeroContrato ObjFactura.DescripcionContrato = DescripcionContrato ObjFactura.NumeroDescripcionContrato = If($"{NumeroContrato} - {NumeroLicitacion}" = " - ", "", $"{NumeroContrato} {If(NumeroLicitacion = "", "", $" - Licitación: {NumeroLicitacion}")}") ObjFactura.PedidoContrato = If(TxtPedidoContrato.Text.Trim = "", ObjFactura.NumeroDescripcionContrato, $"{TxtPedidoContrato.Text.Trim} {If(ObjFactura.NumeroDescripcionContrato = "", "", $" / {ObjFactura.NumeroDescripcionContrato}") }") ObjFactura.OrdenCompra = TxtOrdenCompra.Text.Trim Select Case ObjFactura.TipoDocto Case "Ing" ObjFactura.TipoDocumento = "Factura" Case "Rem" ObjFactura.TipoDocumento = "Remision" Case "Cot" ObjFactura.TipoDocumento = "Cotizacion" Case "Egs" ObjFactura.TipoDocumento = "Nota de Crédito" Case "Dev" ObjFactura.TipoDocumento = "Nota de Devolución" Case "DPe" ObjFactura.TipoDocumento = "Devolución de pedido" Case "PeC" ObjFactura.TipoDocumento = "Consignación de Pedido" Case Else ObjFactura.TipoDocumento = "" End Select ObjFactura.Fech1 = TxtFech1.Text.Trim.ToDate ObjFactura.Fech2 = TxtFech2.Text.Trim.ToDate ObjFactura.Fech3 = TxtFech3.Text.Trim.ToDate ObjFactura.Alfa1 = TxtAlfa1.Text.Trim ObjFactura.Alfa2 = TxtAlfa2.Text.Trim ObjFactura.Alfa3 = TxtAlfa3.Text.Trim ObjFactura.Num1 = TxtNum1.Text.Trim.ToDouble ObjFactura.Num2 = TxtNum2.Text.Trim.ToDouble ObjFactura.Num3 = If(ObjFactura.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) If divcondicionespago.Visible Then ObjFactura.FechaPago = TxtFechaPago.Text.ToDate Else ObjFactura.FechaPago = Now End If ObjFactura.DiasCredito = DiasCredito ObjFactura.EsDiasCreditoFijo = EsDiasCreditoFijo ObjFactura.CveCorte = CveCorte ObjFactura.CveMesa = -1 ObjFactura.NumeroPersonas = 0 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 = TxtFechaVencimientoCotizacion.Text.ToDate ObjFactura.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, If(CvePedido2 > 0, CvePedido2, CvePedido)) If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then ObjFactura.CveVentaPadre = DtVentasNC.Rows(0)("CveVenta").ToString().ToEntero() ObjFactura.SerieFolioPadre = DtVentasNC.Rows(0)("FolioFiscal").ToString() End If If DdlTipoComprobante.SelectedValue = "Dev" AndAlso ListaRemisionesNC IsNot Nothing AndAlso ListaRemisionesNC.Count > 0 Then Dim ObjRNC = ListaRemisionesNC.FirstOrDefault If ObjRNC IsNot Nothing Then ObjFactura.CveVentaPadre = ObjRNC.CveVentaPadre ObjFactura.SerieFolioPadre = ObjRNC.SerieFolioPadre End If End If ObjFactura.CveVendedor = DdlVendedor.SelectedValue.ToEntero() If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If ObjFactura.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() ObjFactura.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero() ObjFactura.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero() ObjFactura.AtencionA = If(ObjFactura.TipoDocto = "Cot" Or (ObjFactura.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") ObjFactura.MotivoDescuento = TxtMotivoDescuento.Text.Trim ObjFactura.Observaciones = TxtObsFact.Text.Trim ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim ObjFactura.MonedaAbreviatura = "" 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS If (ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then 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.SUM("Total").ToDecimal ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal TipoCambioRemision = ObjFactura.TipoCambio ObjFactura.TipoCambio = 1 ObjFactura.ConvertirPesos = False ConversionRemision = "/" 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES ElseIf (ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDouble / ObjFactura.TipoCambioDolares, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) End If Next ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal TipoCambioRemision = ObjFactura.TipoCambioDolares ObjFactura.TipoCambioDolares = 1 ObjFactura.ConvertirDolares = False ConversionRemision = "*" 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS REGISTRO DIRECTO SIN VENTA ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True) Then 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").ToDecimal ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales) ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal TipoCambioRemision = ObjFactura.TipoCambio ObjFactura.TipoCambio = 1 ObjFactura.ConvertirPesos = False ConversionRemision = "/" 'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES REGISTRO DIRECTO SIN VENTA ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True) Then For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDouble / ObjFactura.TipoCambioDolares, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDouble * Row("PU").ToString().ToDouble, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString().ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales) End If Next ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales) ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal TipoCambioRemision = ObjFactura.TipoCambioDolares ObjFactura.TipoCambioDolares = 1 ObjFactura.ConvertirDolares = False ConversionRemision = "*" Else 'Totales, Y se llena TmpDTImpuestos ObjFactura.SubTotal = TxtSubTotal.Text.ToDecimal ObjFactura.Descuento = LblDescuentos.Text.Trim.ToDecimal ObjFactura.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal ObjFactura.IVA = TxtIVA.Text.ToDecimal ObjFactura.RetIVA = TxtRetIVA.Text.ToDecimal ObjFactura.RetISR = TxtRetISR.Text.ToDecimal ObjFactura.IEPS = TxtIEPS.Text.ToDecimal ObjFactura.Total = TxtTotal.Text.ToDecimal End If Dim TmpSubtotal As Decimal = TxtSubTotal.Text.ToDecimal - ObjFactura.Descuento Dim TmpAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal ObjFactura.DtDetalle = TmpDT If AplicaFord Then ObjFactura.FordGSDB = TxtFordGSDB.Text Dim SB As New StringBuilder For Each li As ListItem In LstFordASN.Items SB.AppendFormat("{0}, ", li.Text) Next ObjFactura.FordASN = SB.ToString() End If If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone() Dim DR As DataRow = TmpDTImpuestosVista.NewRow() If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = ObjFactura.SubTotal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = ObjFactura.Descuento : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = ObjFactura.Amortizacion : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() 'If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = ObjFactura.IVA : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = ObjFactura.RetIVA : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = ObjFactura.RetISR : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtIEPS.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IEPS" : DR("Importe") = ObjFactura.IEPS : DR("Orden") = 80 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then Dim Orden As Integer = 80 If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString() : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString() : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString() : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString().ToEntero() : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() Orden = Orden + 1 End If End If Next If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = ObjFactura.Total : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) ObjFactura.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC") 'TmpDT DESGLOSE DE IMPUESTOS 3.3 If UsuarioActual.CveEmpresa.Contiene(119) Then If TmpDTDocumentosRelacionados IsNot Nothing Then ObjFactura.DtDocumentosRelacionados = TmpDTDocumentosRelacionados End If If TmpDTNCVinculadas IsNot Nothing Then ObjFactura.DtNCVinculadas = TmpDTNCVinculadas End If End If CreaDTImpuestosIVAIEPS() For Each DrImpuestos33 As DataRow In TmpDT.Rows Dim DrIVA As DataRow = Nothing Dim DrIEPS As DataRow = Nothing Try DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0) Catch ex As Exception DrIVA = Nothing End Try If DrIVA IsNot Nothing Then DrIVA("Importe") = DrIVA("Importe").ToString().ToDouble + DrImpuestos33("ImporteIVA").ToString().ToDouble TmpDTImpuestosIVAIEPS.AcceptChanges() Else Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() If DrImpuestos33("PorcentajeIVA").ToString().ToDecimal > 0 Then DR2("Impuesto") = "IVA" : DR2("tasa") = DdlIVA.SelectedItem.ToString() : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString().ToDecimal : DR2("Orden") = "1" TmpDTImpuestosIVAIEPS.Rows.Add(DR2) TmpDTImpuestosIVAIEPS.AcceptChanges() End If End If Try DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString().ToDecimal * 100} %'")(0) Catch ex As Exception DrIEPS = Nothing End Try If DrIEPS IsNot Nothing Then DrIEPS("Importe") = DrIEPS("Importe").ToString().ToDouble + DrImpuestos33("ImporteIEPS").ToString().ToDouble TmpDTImpuestosIVAIEPS.AcceptChanges() Else Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() If DrImpuestos33("PorcentajeIEPS").ToString().ToDouble > 0 Then DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString().ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString().ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.09", "5", "0")))) TmpDTImpuestosIVAIEPS.Rows.Add(DR2) TmpDTImpuestosIVAIEPS.AcceptChanges() End If End If Next ObjFactura.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC") 'otros ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim ObjFactura.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero() If ObjFactura.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then ObjFactura.TipoCambio = 1 ObjFactura.CveMoneda = 1 ObjFactura.Moneda = "Pesos" ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") End If If ObjFactura.CveMoneda <> 2 AndAlso ChkConvertirDolares.Checked Then ObjFactura.TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal ObjFactura.CveMoneda = 2 ObjFactura.Moneda = "Dólares" ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}") End If 'Se agrega CveVenta -1 For Each Row As DataRow In TmpDT.Rows Row("CveVenta") = ObjFactura.CveVenta Next 'DETALLES ObjFactura.DtDetalle = TmpDT.Copy ObjFactura.DtFirmas = DTmpF.Copy 'CLIENTE ObjFactura.CveCliente = CveCliente ObjFactura.SetCliente() 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 = DdlTipoRelacionAnticipo.SelectedValue.ToEntero() 'If ObjFactura.CveTipoRelacion > 0 Then ' Select Case ObjFactura.CveTipoRelacion ' Case 7 ' ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" ' ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" ' If ListaAnticiposAplicados IsNot Nothing Then ' For Each Ant As 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 = DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() ObjFactura.Timbre.Comprobante.TipoComprobante = If(ObjFactura.TipoDocto.Contiene("Ing", "Ant"), "I", If(ObjFactura.TipoDocto.Contiene("Egs", "Dev"), "E", "")) If ObjFactura.Timbre.Comprobante.TipoComprobante = "E" Then If ObjFactura.TipoDocto = "Egs" Then ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "01" ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso" End If If ObjFactura.TipoDocto = "Dev" Then ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "03" ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso" End If ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero() If HdnFolioFiscalNC.Value <> "0" And HdnFolioFiscalNC.Value <> "" Then ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) End If ' cuando es refacturacoin es cfdirelacionado, con relacion 04 If ObjFactura.Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "04" ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso" ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) End If If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso NuevaFactura = 1 Then ' refacturación ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero() End If If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso DdlTipoRelacionAnticipo.SelectedValue.ToEntero() > 0 Then ' refacturación ObjFactura.CveTipoRelacion = DdlTipoRelacionAnticipo.SelectedValue.ToEntero() If GVAnticipos.Rows.Count > 0 Then For Each gvr As GridViewRow In GVAnticipos.Rows If gvr.FCCheckBox(String.Format("Chk{0}", gvr.RowIndex)).Checked AndAlso gvr.DataKey("CveConceptoContable") = "12" Then ' solo notas de crédito If DtVentasNC Is Nothing Then InicializaDTVentasNC() Dim Drt = DtVentasNC.NewRow Drt("CveVenta") = gvr.DataKey("CveVenta") Drt("Importe") = gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text Drt("FolioFiscal") = gvr.DataKey("FolioFiscal") Drt("Folio") = gvr.DataKey("Folio") DtVentasNC.Rows.Add(Drt) End If Next End If 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 = 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 '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(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1)).RoundSQL(2) } ObjFactura.Timbre.RetencionesLocales.Add(ret) End If Next End If If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows.Count > 0 Then For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows If DrImpuestosLocales("Importe").ToString().ToDecimal > 0 Then Dim ret As New CFDITrasladosLocales With {.TasaTraslado = DrImpuestosLocales("Porcentaje").ToString().ToDecimal, .ImpuestoLocalTraslado = DrImpuestosLocales("ImpuestoLocal").ToString(), .Importe = DrImpuestosLocales("Importe").ToString().ToDecimal(If(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1))} ObjFactura.Timbre.TrasladosLocales.Add(ret) End If Next End If 'INE COMPLEMENTO If RblComplementos.SelectedValue.ToEntero() > 0 Then ObjFactura.CveComplementoTimbrado = RblComplementos.SelectedValue.ToEntero() Dim INE As New Modelos.ComplementoINE Select Case RblComplementos.SelectedValue.ToEntero() Case 5 INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() INE.INETipoProceso = "Ordinario" INE.INETipoComite = "Directivo Estatal" INE.INEEntidad = DdlINEEntidad.SelectedValue Case 6 INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() INE.INETipoProceso = "Ordinario" INE.INETipoComite = "Ejecutivo Estatal" INE.INEEntidad = DdlINEEntidad.SelectedValue Case 7 INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() INE.INETipoProceso = "Ordinario" INE.INETipoComite = "Ejecutivo Nacional" Case 8 INE.INEIdContabilidad = TxtIdConta.Text.ToEntero() INE.INETipoProceso = DdlTipoCampaña.SelectedValue INE.INETipoComite = DdlAmbitoComplemento.SelectedValue INE.INEEntidad = DdlINEEntidad.SelectedValue Case Else INE.INEIdContabilidad = 0 INE.INETipoProceso = "" INE.INETipoComite = "" INE.INEEntidad = "" End Select ObjFactura.ComplementoINE = INE End If ObjFactura.CveTipoRetencion = DdlTipoRetencion.SelectedValue.ToEntero() ObjFactura.DescuentoProntoPago = HdnProntoPago.Value.ToDecimal() ObjFactura.NuevaFactura = Me.NuevaFactura ObjFactura.EsGarantia = Me.EsGarantia If UsuarioActual.Empresa.Funcionalidad(558).ToEntero() = 1 AndAlso TrKilometraje.Visible Then ObjFactura.Kilometraje = TxtKilometraje.Text.Trim.ToDecimal() End If '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 Sub CreaObjetosVentaDevolucion() ObjFacturaDevolucion = New Modelos.Factura ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal) ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero() ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}") 'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim 'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero(), -1) ObjFacturaDevolucion.Serie = LblSerie.Text ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second) ObjFacturaDevolucion.CvePrePoliza = -1 ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero() ObjFacturaDevolucion.MetodoPago = "" 'DdlMetodoPago.SelectedItem.Text ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero(), -1) ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "") 'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim 'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito ObjFacturaDevolucion.FormaPago = 0 'ObjFacturaDevolucion.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text) ObjFacturaDevolucion.TipoDocto = "Egs" If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Dim ObjFolios As New ClsGralFolios() Dim TipoDoctoConsulta As String = If(ObjFacturaDevolucion.TipoDocto = "Ant", "Ing", If(ObjFacturaDevolucion.TipoDocto = "PA", "Rem", ObjFacturaDevolucion.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 ObjFacturaDevolucion.Serie = DT.Rows(0)("Serie").ToString() End If DT.Dispose() End If ObjFolios.Dispose() End If ObjFacturaDevolucion.Fecha = Now 'VALORES DEFAULT DE NC-DEV Dim CveUsoCFDIOld = DdlUsoCFDI.SelectedValue Dim MetodoPago33Old = DdlMetodoPago33.SelectedValue Dim FormaPago33Old = DdlFormaPago33.SelectedValue DdlUsoCFDI.SelectedValueExist("2") DdlMetodoPago33.SelectedValueExist("1") DdlFormaPago33.SelectedValueExist("20") ObjFacturaDevolucion.SerieFolioPadre = HdnFolioFiscalNC.Value.ToString() If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then ObjFacturaDevolucion.Version = "4.0" If ObjFacturaDevolucion.Cliente Is Nothing Then ObjFacturaDevolucion.Cliente = New Modelos.ClienteModel End If ObjFacturaDevolucion.Cliente.CodigoRegimenFiscal = ClienteCodigoRegimenFiscal ObjFacturaDevolucion.Cliente.RegimenFiscal = ClienteRegimenFiscal Else ObjFacturaDevolucion.Version = "3.3" End If ObjFacturaDevolucion.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero() ObjFacturaDevolucion.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero() > 0, DdlMetodoPago33.SelectedItem.Text, "") ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}") ObjFacturaDevolucion.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero() ObjFacturaDevolucion.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero() > 0, DdlFormaPago33.SelectedItem.Text, "") ObjFacturaDevolucion.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}") ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero() ObjFacturaDevolucion.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero() > 0, DdlUsoCFDI.SelectedItem.Text, "") ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}") DdlUsoCFDI.SelectedValueExist(CveUsoCFDIOld) DdlMetodoPago33.SelectedValueExist(MetodoPago33Old) DdlFormaPago33.SelectedValueExist(FormaPago33Old) Select Case ObjFacturaDevolucion.TipoDocto Case "Ing" ObjFacturaDevolucion.TipoDocumento = "Factura" Case "Rem" ObjFacturaDevolucion.TipoDocumento = "Remision" Case "Cot" ObjFacturaDevolucion.TipoDocumento = "Cotizacion" Case "Egs" ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito" Case "Dev" ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución" Case Else ObjFacturaDevolucion.TipoDocumento = "" End Select If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto End If ObjFacturaDevolucion.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero() ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble) ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate ObjFacturaDevolucion.CveCorte = CveCorte ObjFacturaDevolucion.CveMesa = -1 ObjFacturaDevolucion.NumeroPersonas = 0 ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto) ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "") ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero() ObjFacturaDevolucion.Entrega = Entrega ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate ObjFacturaDevolucion.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, CvePedido) ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero() If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate 'ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero() 'ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero() ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() ObjFacturaDevolucion.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero() ObjFacturaDevolucion.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero() ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1") ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFacturaDevolucion.MonedaAbreviatura = "" 'Totales, Y se llena TmpDTImpuestos ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() End If Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone() Dim DR As DataRow = TmpDTImpuestosVista.NewRow() If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then Dim Orden As Integer = 80 If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString() : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString() : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString() : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString().ToEntero() : TmpDTImpuestosVista.Rows.Add(DR) DR = TmpDTImpuestosVista.NewRow() Orden = Orden + 1 End If End If Next If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR) ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC") CreaDTImpuestosIVAIEPS() For Each DrImpuestos33 As DataRow In TmpDT.Rows Dim DrIVA As DataRow = Nothing Dim DrIEPS As DataRow = Nothing Try DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0) Catch ex As Exception DrIVA = Nothing End Try If DrIVA IsNot Nothing Then DrIVA("Importe") = DrIVA("Importe").ToString().ToDouble + DrImpuestos33("ImporteIVA").ToString().ToDouble TmpDTImpuestosIVAIEPS.AcceptChanges() Else Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() If DrImpuestos33("PorcentajeIVA").ToString().ToDouble >= 0 Then DR2("Impuesto") = "IVA" : DR2("tasa") = "16 %" : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString().ToDouble : DR2("Orden") = "1" TmpDTImpuestosIVAIEPS.Rows.Add(DR2) TmpDTImpuestosIVAIEPS.AcceptChanges() End If End If Try DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString().ToDouble * 100} %'")(0) Catch ex As Exception DrIEPS = Nothing End Try If DrIEPS IsNot Nothing Then DrIEPS("Importe") = DrIEPS("Importe").ToString().ToDouble + DrImpuestos33("ImporteIEPS").ToString().ToDouble TmpDTImpuestosIVAIEPS.AcceptChanges() Else Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow() If DrImpuestos33("PorcentajeIEPS").ToString().ToDouble > 0 Then DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString().ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString().ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString() = "0.09", "5", "")))) TmpDTImpuestosIVAIEPS.Rows.Add(DR2) TmpDTImpuestosIVAIEPS.AcceptChanges() End If End If Next ObjFacturaDevolucion.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC") 'otros ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero() If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then ObjFacturaDevolucion.TipoCambio = 1 ObjFacturaDevolucion.CveMoneda = 1 End If 'DETALLES ObjFacturaDevolucion.DtDetalle = TmpDT ObjFacturaDevolucion.DtFirmas = DTmpF 'CLIENTE ObjFacturaDevolucion.CveCliente = CveCliente ObjFacturaDevolucion.SetCliente() 'SUCURSAL ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero() ObjFacturaDevolucion.SetSubProyectoMatriz(Me) ObjFacturaDevolucion.SetSubProyecto(Me) ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel If Me.ClienteSucursal IsNot Nothing Then ObjFacturaDevolucion.ClienteSucursal.RFC = Me.ClienteSucursal.RFC ObjFacturaDevolucion.ClienteSucursal.Nombre = Me.ClienteSucursal.Nombre End If ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString() ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero() > 0, DdlSucursalCliente.SelectedItem.Text, "") ObjFacturaDevolucion.ClienteSucursal.ImprimeNombreSucursal = ImprimeNombreSucursal.ToString() 'ENVIO DIRECCION ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel If ChkDireccionEnvio.Checked Then If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())).Rows.Count > 0 Then For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())).Rows ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString().ToEntero() ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString() ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString() ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString() ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString() ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString() Next End If End If ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) 'ASIGNAR RFC RECEPTOR If ObjFacturaDevolucion.Timbre IsNot Nothing Then If ObjFacturaDevolucion.Timbre.Receptor IsNot Nothing Then ObjFacturaDevolucion.RFCReceptor = ObjFacturaDevolucion.Timbre.Receptor.RFC End If End If End Sub Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre Dim Timbre As New CFDITimbre Timbre.Comprobante.Version = If(UsuarioActual.Empresa.Funcionalidad(350) = "1", "4.0", "3.3") 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 = 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 If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then Timbre.Receptor.Nombre = Obj.Cliente.Nombre Else Timbre.Receptor.Nombre = Obj.Cliente.Nombre + " " + Obj.Cliente.RegimenSociedad End If 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 If HdnTipoDescuento.Value = "3" And DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() > 0 Then Timbre.CFDIRelacionados.TipoRelacion = "07" Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" 'If Timbre.Comprobante.TipoComprobante = "E" Then ' If Obj.TipoDocumento.Contiene("Nota de Crédito") Then ' Timbre.CFDIRelacionados.TipoRelacion = "01" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso" ' End If ' If Obj.TipoDocumento.Contiene("Nota de Devolución") Then ' Timbre.CFDIRelacionados.TipoRelacion = "03" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso" ' End If ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) 'End If '' cuando es refacturacoin es cfdirelacionado, con relacion 04 'If Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then ' Timbre.CFDIRelacionados.TipoRelacion = "04" ' Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso" ' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value) 'End If Else 'SI LA FACTURA VIENE DE SER CANCELADA SISTEMA CUANDO SE REFACTURO NO HAY QUE RELACIONAR If (CveEstatusFacturaPadre > 0 AndAlso CveEstatusFacturaPadre <> 4) OrElse (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) 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 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 = If(UsuarioActual.Empresa.CvePAC = 3, Obj.DtDetalle.SUMD("Total"), Obj.SubTotal) '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 'detalles Dim tPS As String = "" For Each drr As DataRow In Obj.DtDetalle.Rows If drr("PS").ToString().Length = 1 Then tPS = drr("Obs").ToString() Else If drr("PS").ToString().Length = 0 Then tPS = "" Else tPS = String.Format("{0} {1}", drr("PS"), drr("Obs")) End If End If tPS = tPS.Replace("|", " ") If tPS.Length >= 1000 Then Dim tPSRecortado = 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 = If(UsuarioActual.Empresa.CvePAC = 3, drr("Total").ToString().ToDecimal.RoundSQL(2), 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()} '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 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 If 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 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 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 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 Timbre.Conceptos.Add(concepto) i += 1 Next Dim AplicaComercioExteriorSubProyecto As Boolean If ChkEmitirComercioExterior.Checked Then AplicaComercioExteriorSubProyecto = If(GlobalDTSubProyectos(-1, Obj.CveSubProyecto, CveEmpresa:=UsuarioActual.CveEmpresa)(0)("AplicaComercioExterior").ToString() = "True", True, False) Timbre.Complementos.ComercioExterior11.AplicaComercioExteriorSubProyecto = AplicaComercioExteriorSubProyecto If Obj.Cliente.AplicaComercioExterior And AplicaComercioExteriorSubProyecto Then '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.ToString().ToDecimal) Timbre.Complementos.ComercioExterior11.MotivoTraslado = GlobalDTSATMotivoTraslado.FiltroPrimeroValor("ClaveSATMotivoTraslado", $"CveMotivoTraslado={DdlSATMotivoTraslado.SelectedValue}") 'EMISOR Dim Dr As DataRow Dr = Nothing If GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero(), 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() '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 = Obj.Cliente.Direccion Timbre.Complementos.ComercioExterior11.Receptor.NumeroExterior = Obj.Cliente.NoExt Timbre.Complementos.ComercioExterior11.Receptor.NumeroInterior = Obj.Cliente.NoInt Timbre.Complementos.ComercioExterior11.Receptor.Colonia = Obj.Cliente.ClaveSATColonia Timbre.Complementos.ComercioExterior11.Receptor.Localidad = "" Timbre.Complementos.ComercioExterior11.Receptor.Referencia = Obj.Cliente.ReferenciaFiscal Timbre.Complementos.ComercioExterior11.Receptor.Municipio = Obj.Cliente.Ciudad Timbre.Complementos.ComercioExterior11.Receptor.CP = Obj.Cliente.CP Timbre.Complementos.ComercioExterior11.Receptor.Estado = Obj.Cliente.ClaveSATEstado Timbre.Complementos.ComercioExterior11.Receptor.Pais = Obj.Cliente.ClaveSATPais Timbre.Receptor.ResidenciaFiscal = Obj.Cliente.ClaveSATPais Timbre.Receptor.NumeroRegistroTributario = Obj.Cliente.NumRegIdTrib Dim ComExtPais, ComExtEstado, ComExtMunicipio, ComExtColonia, ComExtCalle, ComExtNumero, ComExtCP As String ComExtColonia = "" : ComExtMunicipio = "" ComExtPais = 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 'DESTINATARIO Timbre.Complementos.ComercioExterior11.Destinatario.Nombre = TxtDestinatarioNombre.Text.Trim Timbre.Complementos.ComercioExterior11.Destinatario.Calle = ComExtCalle Timbre.Complementos.ComercioExterior11.Destinatario.NumeroExterior = ComExtNumero Timbre.Complementos.ComercioExterior11.Destinatario.NumeroInterior = "" Timbre.Complementos.ComercioExterior11.Destinatario.Colonia = ComExtColonia Timbre.Complementos.ComercioExterior11.Destinatario.Localidad = "" Timbre.Complementos.ComercioExterior11.Destinatario.Referencia = Obj.Cliente.ReferenciaFiscal Timbre.Complementos.ComercioExterior11.Destinatario.Municipio = ComExtMunicipio Timbre.Complementos.ComercioExterior11.Destinatario.CP = ComExtCP Timbre.Complementos.ComercioExterior11.Destinatario.Estado = ComExtEstado Timbre.Complementos.ComercioExterior11.Destinatario.Pais = ComExtPais Timbre.Complementos.ComercioExterior11.Destinatario.NumRegIdTrib = TxtNumRegIdTrib.Text.Trim 'MERCANCIAS For Each Gvr As GridViewRow In GvComercioExterior.Rows Dim mercancia As New CFDIComercioExterior11Mercancias With {.CantidadAduana = Gvr.FCTextBox("TxtCantidad").Text.ToDecimal, .FraccionArancelaria = Gvr.DataKey("ClaveSATFraccionArancelaria").ToString(), .UnidadAduana = Gvr.DataKey("ClaveSATUnidadAduana").ToString(), .ValorDolares = Math.Round(Gvr.FCTextBox("TxtCantidad").Text.ToDecimal * Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, 2), .ValorUnitarioAduana = Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, .NoIdentificacion = Gvr.DataKey("Codigo")} If Gvr.FCTextBox("TxtMarca").Text <> "" Then mercancia.DescripcionesEspecificas.Marca = Gvr.FCTextBox("TxtMarca").Text End If Timbre.Complementos.ComercioExterior11.Mercancias.Add(mercancia) i += 1 Next End If 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 TmpDT7Eleven.Columns.Add("sevenElevenNumProveedor") TmpDT7Eleven.Columns.Add("sevenElevenFolio") TmpDT7Eleven.Columns.Add("sevenElevenTienda") TmpDT7Eleven.Columns.Add("sevenElevenFecha") Dim Row As DataRow = TmpDT7Eleven.NewRow Row("sevenElevenNumProveedor") = Txt7ElevenNumProveedor.Text.Trim() Row("sevenElevenFolio") = Txt7ElevenFolio.Text.Trim() Row("sevenElevenTienda") = Txt7ElevenTienda.Text.Trim() Row("sevenElevenFecha") = Txt7ElevenFecha.Text.Trim() TmpDT7Eleven.Rows.Add(Row) TmpDTComplementosTimbrado.Columns.Add("CveComplemento") TmpDTComplementosTimbrado.Columns.Add("IdContabilidad") TmpDTComplementosTimbrado.Columns.Add("TipoProceso") TmpDTComplementosTimbrado.Columns.Add("TipoAmbito") TmpDTComplementosTimbrado.Columns.Add("Entidad") Dim Row2 As DataRow = TmpDTComplementosTimbrado.NewRow If RblComplementos.SelectedValue.ToEntero() > 0 Then Select Case RblComplementos.SelectedValue.ToEntero() Case 5 Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() Row2("TipoProceso") = "Ordinario" Row2("TipoAmbito") = "Directivo Estatal" Row2("Entidad") = DdlINEEntidad.SelectedValue Case 6 Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() Row2("TipoProceso") = "Ordinario" Row2("TipoAmbito") = "Ejecutivo Estatal" Row2("Entidad") = DdlINEEntidad.SelectedValue Case 7 Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() Row2("TipoProceso") = "Ordinario" Row2("TipoAmbito") = "Ejecutivo Nacional" Row2("Entidad") = "" Case 8 Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero() Row2("IdContabilidad") = TxtIdConta.Text.ToEntero() Row2("TipoProceso") = DdlTipoCampaña.SelectedValue Row2("TipoAmbito") = DdlAmbitoComplemento.SelectedValue Row2("Entidad") = DdlINEEntidad.SelectedValue End Select Else Row2("CveComplemento") = "" Row2("IdContabilidad") = "" Row2("TipoProceso") = "" Row2("TipoAmbito") = "" Row2("Entidad") = "" End If TmpDTComplementosTimbrado.Rows.Add(Row2) End Sub #End Region #Region "Ordenes de Compra Sin Facurar" Private Sub CargaOCs() Dim ObjVentas As New ClsVentas If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 1) Then If DdlContratosOC.SelectedValue.ToEntero() > 0 Then DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"CveContratoVinculado = '{DdlContratosOC.SelectedValue}'") Else DTOrdenesCompra = ObjVentas.DtResultados End If GVOC.DataSource = DTOrdenesCompra End If If DTOrdenesCompra IsNot Nothing AndAlso Not DTOrdenesCompra.Columns.Contains("Aplicado") Then DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean")) End If ObjVentas.Dispose() GVOC.DataBind() UPOCFactura.Update() End Sub Private Sub CargaOCsxProducto() Dim ObjVentas As New ClsVentas If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 2) Then If DdlContratosOC.SelectedValue.ToEntero() > 0 Then DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0 AND CveContratoVinculado = '{DdlContratosOC.SelectedValue}'") Else DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0") End If GvOCPS.DataSource = DTOrdenesCompra End If If Not DTOrdenesCompra.Columns.Contains("Aplicado") Then DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean")) End If ObjVentas.Dispose() GvOCPS.DataBind() UPOCFactura.Update() End Sub Private Sub ChkOCProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkPSOC.CheckedChanged CargaOCSinFacturar() End Sub Private Sub VerificaOrdenesCompra(ByRef dt As DataTable) If ChkPSOC.Checked Then For Each Gvr As GridViewRow In GvOCPS.Rows If Gvr.RowType = DataControlRowType.DataRow Then If Gvr.FCCheckBox("Chk").Checked Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveOrdenCompraDetalle As Integer = Gvr.DataKey("CveOrdenCompraDetalle").ToEntero() Dim Drs As DataRow() = dt.Select($"CveOrdenCompraDetalle = {CveOrdenCompraDetalle}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If End If Next Else For Each Gvr As GridViewRow In GVOC.Rows If Gvr.RowType = DataControlRowType.DataRow Then If Gvr.FCCheckBox("Chk").Checked Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveOrdenCompra As Integer = Gvr.DataKey("CveOrdenCompra").ToEntero() Dim Drs As DataRow() = dt.Select($"CveOrdenCompra = {CveOrdenCompra}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If End If Next End If End Sub Protected Sub BtnCargarOC_Click(sender As Object, e As EventArgs) Handles BtnCargarOC.Click If GVOC.Rows.Count > 0 Or GvOCPS.Rows.Count > 0 Then 'Checa las facturas selecionadas VerificaOrdenesCompra(DTOrdenesCompra) RegistroxOC = False Dim dtSeleccionadas As DataTable = DTOrdenesCompra.FiltraParametros("Aplicado = True") If GvPS.Rows.Count > 0 Then TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = TxtIVA.Text End If If dtSeleccionadas.Rows.Count > 0 Then If TieneContrato Then ContratoDetalles.Visible = True DivEstimaciones.Visible = False DdlContratosModal.DataSource = DtContratos DdlContratosModal.DataBind() DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) DdlContratosModal.SelectedValue = DdlContratosOC.SelectedValue DdlContrato.SelectedValue = DdlContratosOC.SelectedValue UPEstimaciones.Update() End If IsTotalxConcepto = True Dim ObjClientes As New ClsClientes Dim sb As New StringBuilder If ChkPSOC.Checked Then For Each row As DataRow In dtSeleccionadas.Rows sb.Append($"{row("CveOrdenCompraDetalle").ToString()},") Next Else For Each row As DataRow In dtSeleccionadas.Rows sb.Append($"{row("CveOrdenCompra").ToString()},") Next End If sb.Remove(sb.Length - 1, 1) If ObjClientes.GetVentasOCTotales(CveCliente, sb.ToString(), If(ChkPSOC.Checked, 2, 1)) Then DTOrdenesCompraPS = ObjClientes.DtResultados RegistroxOC = True Dim tCantidad As Decimal = 0 For Each Dr As DataRow In DTOrdenesCompraPS.Select() tCantidad = If(ChkPSOC.Checked, GvOCPS.Rows(IndiceGVDataKey(GvOCPS, "CveOrdenCompraDetalle", $"{Dr("CveOrdenCompraDetalle")}")).FCTextBox("TxtCantidadOC").Text, Dr("Cantidad")).ToString().ToDecimal AgregarProductoServicio(tCantidad, Dr("CveUM").ToString().ToEntero(), Dr("UM").ToString(), Dr("CveClasificacion").ToString().ToEntero(), Dr("Clasificacion").ToString(), Dr("CvePS").ToString().ToEntero(), Dr("PS").ToString(), Dr("Obs").ToString(), Dr("PUCon").ToString().ToDecimal, 0, Dr("CveProyecto").ToString().ToEntero(), Dr("Proyecto").ToString(), Dr("CveSubProyecto").ToString().ToEntero(), Dr("SubProyecto").ToString(), CveContratoDetalle:=Dr("CveContratoDetalle").ToString().ToEntero(), CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString().ToEntero(), EntregaDirecta:=1) Next CveContrato = DTOrdenesCompraPS.FiltroPrimeroValor("CveContrato").ToString().ToEntero() If CveContrato > 0 Then ContratoOC = True CalculaTotalesVenta() GvPS.DataSource = TmpDT GvPS.DataBind() End If ObjClientes.Dispose() BtnEmitirImprimir.Text = "Facturar" 'REGISTRAR UNA ENTREGA DIRECTA If TmpDT.COUNT("EntregaDirecta", "EntregaDirecta = 1") > 0 Then trPaqueteriaOpciones.Visible = False trPaqueteriOpcionesLabel.Visible = False trPaqueteriaDirectaLabel.Visible = True DdlTipoComprobante.Items.Clear() DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) DdlTipoComprobante.Items.Insert(1, New ListItem("Remisión", "Rem")) DdlTipoComprobante.Enabled = True Else DdlTipoComprobante.SelectedValue = "Ing" DdlTipoComprobante.Enabled = False End If Tab.ActiveTab = TabGenerales TabGenerales.Enabled = True Updatetabs.Update() UPObservaciones.Update() 'Else ' If TieneContrato Then ' GvContratoDetalles.DataSource = Nothing ' GvContratoDetalles.DataBind() ' UPEstimaciones.Update() ' End If End If End If ChkPSOC.Checked = False UPOCFactura.Update() UpFacturar.Update() UpPS.Update() UpParametros.Update() RegistraScript("$('#DivOrdenesCompra').modal('hide');") End Sub Private Sub DdlContratosOC_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosOC.SelectedIndexChanged CargaOCSinFacturar() End Sub Private Sub CargaOCSinFacturar() If ChkPSOC.Checked Then GvOCPS.Visible = True GVOC.Visible = False DivFiltroOCPS.Visible = True GVOC.DataSource = Nothing GVOC.DataBind() CargaOCsxProducto() Else GvOCPS.Visible = False GVOC.Visible = True DivFiltroOCPS.Visible = False GvOCPS.DataSource = Nothing GvOCPS.DataBind() CargaOCs() End If End Sub Private Sub LnkOCs_Click(sender As Object, e As EventArgs) Handles LnkOCs.Click Dim ObjContratos As New ClsContratos If Not TieneContrato Then If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'") DdlContratosOC.DataSource = DtContratos DdlContratosOC.DataBind() If Not TieneContrato Then DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0")) End If End If End If GvContratoDetalles.DataSource = Nothing GvContratoDetalles.DataBind() UpContratos.Update() DivEstimaciones.Visible = True ContratoDetalles.Visible = False UPEstimaciones.Update() Tab.ActiveTab = TabGenerales TabGenerales.Enabled = True Updatetabs.Update() End If ObjContratos.Dispose() ChkPSOC.Checked = False UPOCFactura.Update() CargaOCSinFacturar() RegistraScript("$('#DivOrdenesCompra').modal('show');") End Sub Private Sub BtnConsultarOC_Click(sender As Object, e As EventArgs) Handles BtnConsultarOC.Click CargaOCSinFacturar() End Sub #End Region #Region " GUARDAR - VENTA, PREPOLIZAS, INV, ESTIMACIONES, AC, NOTA DE CRÉDITO " Private Sub GuardarVenta(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, factura As Modelos.Factura, ByRef TmpDTDetalle As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, Optional ByRef ObjOS As ClsOS = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, ByRef Optional ObjCGame As ClsCGame = Nothing, ByRef Optional ObjCliente As ClsClientes = Nothing, 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 = -1 Dim EsInterno As Integer = -1 If DdlAlmacenAsignado.Visible Or RequiereAlmacenDestino Then CveAlmacenTraspasoDestino = DdlAlmacenAsignado.SelectedValue.ToEntero() End If If DdlAlmacenOrigen.Visible Or RequiereAlmacenOrigen Then CveAlmacenTraspasoOrigen = DdlAlmacenOrigen.SelectedValue.ToEntero() End If If TrTipoPedido.Visible Then EsInterno = DdlTipoPedido.SelectedValue.ToEntero() End If 'Si es devolucion revertimos los almacenes If CvePedido > 0 And TipoContrato = 2 Then EsDevolucionVenta = 1 CveAlmacenTraspasoOrigen = DdlAlmacenAsignado.SelectedValue.ToEntero() CveAlmacenTraspasoDestino = DdlAlmacenOrigen.SelectedValue.ToEntero() End If 'VALIDA ENTREGA POR ADELANTADO If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then 'INCRUSTAMOS ALMACEN ENTREGA POR ADELANTADO CUANDO SEA REMISION Y NO TRAIGA ASIGNADO POR EL USUARIO If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then CveAlmacenTraspasoDestino = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString().ToEntero() End If 'SI LA SUCURSAL NO TIENE ENTREGA POR ADELANTADO If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then ErrorList.Add("Ocurrió un error al seleccionar el almacen de entrega por adelantado de la sucursal.") End If End If Dim TotalImpuestoLocal As Double = 0 If GvImpuestosLocales2.Rows.Count > 0 Then For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then If gvr.DataKey("TipoImpuesto") = "5" Then ' cuando es traslado local TotalImpuestoLocal -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble Else ' cuando es retención TotalImpuestoLocal += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble End If End If End If Next End If '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 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) 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 If Not ObjVentas.AddVenta(factura.TipoDocto, factura.Folio, factura.CveCliente, factura.CveClienteSucursal, factura.SubTotalTC, factura.DescuentoTC, factura.AmortizacionTC, factura.IVATC, factura.RetIVATC, factura.RetISRTC, factura.TotalTC, factura.CveMoneda, factura.TipoCambio, factura.CveMetodoPago, factura.CondicionesPago, factura.FormaPago, factura.FechaPago, factura.Fecha, factura.MotivoDescuento, factura.Observaciones, factura.FechaEjecucion, factura.CveVendedor, factura.Alfa1, factura.Alfa2, factura.Alfa3, factura.Num1, factura.Num2, factura.Num3, factura.Fech1, factura.Fech2, factura.Fech3, factura.CveCorte, factura.CveMesa, factura.NumeroPersonas, factura.CvePrePoliza, factura.CveUsuario, factura.CveEmpresa, AtencionA:=factura.AtencionA, TelefonoGenerico:=TxtTelefonoGenerico.Text.Trim, CveContrato:=factura.CveContrato, CveVentaPadre:=If(AplicaDevolucion, CveVentaDevolucion, factura.CveVentaPadre), Det_FechaOrdenCompra:=factura.Det_FechaOrdenCompra, Det_OrdenCompra:=factura.Det_OrdenCompra, otros:=factura.Otros, Entrega:=TxtEntrega.Text, Vigencia:=If(DdlTipoComprobante.SelectedValue = "Cot", TxtFechaVencimientoCotizacion.Text.ToDate, MinFecha), CveAlmacenTraspasoDestino:=CveAlmacenTraspasoDestino, CveAlmacenTraspasoOrigen:=CveAlmacenTraspasoOrigen, CveDireccionEnvio:=If(DdlDireccionEnvio.Visible, DdlDireccionEnvio.SelectedValue.ToEntero(), -1), CveOC:=CveOC, IEPS:=factura.IEPSTC, Serie:=factura.Serie, CveCondicionEntrega:=DdlFormaEntrega.SelectedValue.ToEntero(), PedidoContrato:=TxtPedidoContrato.Text, ObservacionesAlmacen:=TxtObsAlmacen.Text, CveSubProyecto:=factura.CveSubProyecto, CveSubProyectoCobranza:=factura.CveSubProyectoCobranza, CveSubProyectoEjecucion:=factura.CveSubProyectoEjecucion, CveFormaPago33:=factura.CveFormaPago33, CveMetodoPago33:=factura.CveMetodoPago33, CveUsoCFDI:=factura.CveUsoCFDI, OrdenCompra:=TxtOrdenCompra.Text, CveCuentaTerminal:=DdlCuentasTerminal.SelectedValue.ToEntero(), CveTipoRelacion:=factura.CveTipoRelacion, ImpuestoLocal:=TotalImpuestoLocal, CveVentaRelacion:=(If(factura.CveVentaRelacion.ToEntero() > 0, factura.CveVentaRelacion, -1)), ImporteRelacion:=(If(factura.ImporteRelacion <> Nothing, factura.ImporteRelacion, -1)), CveTipoAmortizacionAnticipo:=factura.CveTipoAmortizacionAnticipo, CveEmpresaCRM:=CveEmpresaCRM, EsInterno:=EsInterno, CveAcercamientoCRM:=CveAcercamientoCRM, DiasCredito:=factura.DiasCredito, EsDiasCreditoFijo:=factura.EsDiasCreditoFijo, AnticipoEspecial:=If(TrAntEspecial.Visible, ChkAntEspecial.Checked, False), Kilometraje:=TxtKilometraje.Text.ToDouble, EsAmortizacion:=EsNCAmortizacion, CveTipoRetencion:=factura.CveTipoRetencion, CorreoNotificacion:=TxtCorreoNotificaciones.Text, FormaPaqueteria:=RblPaqueteria.SelectedValue.ToEntero, FacturarSucursal:=factura.FacturarSucursal, VentaDesglosaIEPS:=factura.VentaDesglosaIEPS, RFCReceptor:=RFCReceptor, Adjunto:=Adjunto, DevolucionImportePagado:=factura.DevolucionImportePagado, EsGarantia:=factura.EsGarantia, ServicioDomicilio:=TrServicioDomicilio.Visible, CveLineaAdicional:=DdlLineaAdicional.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 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 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 'LO LIMPIA PARA QUE NO VUELVA A APLICAR Me.AplicaRelacionManual = False 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 If UsuarioActual.Empresa.Funcionalidad(280) = "1" And RblPaqueteria.SelectedValue = "1" And Not factura.TipoDocto.Contiene("Rem", "Ped") Then NotificarPaqueteria() 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 'SI ES REFACTURACION, NO DEBE AFECTAR LOS USADOS If Not NuevaFactura.Contiene(1) Then If ObjFactura.TipoDocto = "Ing" Then If Not GuardarUsados(2, ObjVentas.IniciaTransacSQL, factura) Then ErrorList.Add("Error al guardar usados") End If ElseIf ObjFactura.TipoDocto = "Dev" Then If Not GuardarUsados(1, ObjVentas.IniciaTransacSQL, factura) Then ErrorList.Add("Error al guardar usados") End If End If End If If factura.TipoDocto = "Egs" AndAlso NuevaFactura = 1 Then If DtVentasNC Is Nothing Then InicializaDTVentasNC() End If CargaNCDT(factura.CveVentaPadre, factura.Total, NuevaFactura:=NuevaFactura, ObjVentas:=ObjVentas) End If 'Se agregan los PS For Each Row As DataRow In TmpDTDetalle.Rows If Not ObjVentas.AddVentaDetalle(ObjVentas.CveVenta, Row("CvePS").ToString().ToEntero(), Row("Cantidad").ToString().ToDouble, Row("CveUM").ToString().ToEntero(), Row("PU").ToString().ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("ImporteIVA").ToString().ToDouble, Math.Round((Row("Total").ToString().ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)) * (1 + Row("PorcentajeIVA").ToString().ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)))), 6), Row("Obs").ToString(), Row("Descuento").ToString().ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("TipoDescuento").ToString().ToEntero(), Row("CveSubProyecto").ToString().ToEntero(), Row("CvePresupuestoIngreso").ToString().ToEntero(), TiempoEntrega:=Row("TiempoEntrega").ToString(), CveVentaDetallePadre:=Row("CveVentaDetalle").ToString().ToEntero(), CveContratoDetalle:=Row("CveContratoDetalle").ToString().ToEntero(), CvePromocionDetalle:=Row("CvePromocionDetalle").ToString().ToEntero(), IEPS:=Row("ImporteIEPS").ToString().ToDouble, CveMovimientoDetallePedido:=Row("CveMovimientoDetallePedido").ToString().ToEntero(), ImporteRetIVA:=Row("ImporteRetIVA").ToString().ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString().ToDouble, PorcentajeIVA:=Row("PorcentajeIVA").ToString().ToDecimal, PorcentajeIEPS:=Row("PorcentajeIEPS").ToString().ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString().ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString().ToDouble, CuentaPredial:=Row("CuentaPredial").ToString()) Then ErrorList.Add("Ocurrió un error al agregar un Producto o Servicio a la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") Exit For Else 'VERIFICAR QUE EL DESCUENTO NO PASE EL 40% 'If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso Row("CveClasificacion").ToString().ToEntero() <> 20519 AndAlso (Not Row("Obs").ToString().Contains("Descuento por garantía")) Then ' Dim TotalDetalle = Math.Round((Row("Total").ToString().ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)) * (1 + Row("PorcentajeIVA").ToString().ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)))), 6) ' Dim DescuentoDetalle = Row("Descuento").ToString().ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)) ' Dim PorcentajeDescuento As Double = (DescuentoDetalle / TotalDetalle) * 100D ' If PorcentajeDescuento > 40 Then ' ErrorList.Add(String.Format("El descuento del producto/servicio {0} no puede ser mayor al 40%. Porcentaje Actual: {1}%", Row("CodigoPS"), PorcentajeDescuento.RoundSQL(2))) ' Exit For ' End If 'End If 'Agregamos el gasto de contrato 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 EsCargo = (Not ListaNCDescuento.Any(Function(RNC) RNC.Num2 = 1)) ListaRNC = ListaNCDescuento Else EsCargo = RblRNCTipo.SelectedValue = "1" ListaRNC = ListaRemisionesNC End If 'SI SE FACTURAN RNC DE CARGO, SE AGREGA EL CONCEPTO DE ACREDITAMIENTO If ListaRNC IsNot Nothing AndAlso ClienteEsDistribuidor AndAlso EsCargo AndAlso Not factura.EsGarantia Then Dim ObjAcum As New ClsAcumuladores(ObjVentas.IniciaTransacSQL()) Dim CvePSCargo As Integer = -1 For Each RNC In ListaRNC CvePSCargo = RNC.DtDetalle.FiltroPrimeroValor("CvePS", $"CveVentaDetalle={Row("CveVentaDetalleRNC").ToString()}").ToEntero() If CvePSCargo > 0 Then Exit For End If Next Dim CveTamanio As Integer = GlobalDTAcumTamaños().FiltroPrimeroValor("CveTamaño", $"CvePSCargo={CvePSCargo}").ToEntero() If CveTamanio > 0 Then If Not ObjAcum.DistribuidorMovtosAdd(factura.CveCliente, Row("Cantidad").ToString().ToDecimal(), CveTamanio, 6, factura.CveVenta, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 0D, "", Now) Then ErrorList.Add("Ocurrió un error al agregar la venta detalle devolución.") Exit For End If End If 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.Folio}", "-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 'Actualiar el estatus de la venta refacturada 'If ObjVentas.CveVenta > 0 AndAlso NuevaFactura = 1 AndAlso CveDevolucion > 0 Then ' 'If CveEstatusRefacturacion = 1 Then CveEstatusRefacturacion = 2 'cuando viene del proceso de refacturación con aceptació ' If Not ObjVentas.UpdateEstatusRefacturacion(CveDevolucion, 2) Then ' se marca como refacturada ' ErrorList.Add("Ocurrió un error al actualizar el estatus de la refacturacion") ' End If 'End If 'Pedido2' If ObjVentas.CveVenta > 0 And CvePedido2 > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem", "PA") Then If Not ObjCliente.UpdateEstatusPedido(CvePedido2, 21, -1, UsuarioActual.CveUsuario) Then ErrorList.Add("Ocurrió un error al actualizar el estatus del pedido2") End If End If 'Si viene de OS, Se guarda CveVenta en OS If CveOS > 0 Then If Not ObjOS.UpdateVentaOS(factura.CveVenta, CveOS) Then ErrorList.Add("Ocurrió un error al guardar la venta en Ordenes de Servicio") End If End If 'Contratos If factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing") Then GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, 1) '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 'Impuestos Locales For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then If Not ObjVentas.AddVentaImpuestoLocales(factura.CveVenta, gvr.DataKey("CveImpuestoLocal").ToString().ToEntero(), gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1))) Then ErrorList.Add("Ocurrió un error al Guardar Impuestos Locales") End If End If End If Next If DTmpF.Rows.Count > 0 Then For Each Row As DataRow In DTmpF.Rows If Not ObjVentas.AddVentasFirmas(factura.CveVenta, Row("Titulo").ToString(), Row("Nombre").ToString(), Row("Puesto").ToString(), Row("Lado").ToString().ToEntero()) Then ErrorList.Add("Ocurrio un error al Guardar Firmas") End If Next End If 'registro los metodos de pago, cuando hay corte. If factura.CveCorte > 0 Then 'cuando es contado If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then For Each DrPago As DataRow In DtPagos.Rows If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, DrPago("CveMetodoPago").ToString().ToEntero(), DrPago("Importe").ToString().ToDouble) Then ErrorList.Add("Ocurrio un error al guardar los metodos de pago") End If Next Else 'cuando es crédito o terminal If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, 7, TxtTotal.Text.ToDouble) Then ErrorList.Add("Ocurrio un error al guardar los metodos de pago") End If End If End If 'cuando es contado 'If factura.CveCorte > 0 Then ' If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then ' For Each DrPago As DataRow In DtPagos.Rows ' If ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString().ToEntero(), DrPago("CveTipoMovimiento").ToString().ToEntero(), TxtFechaPago.Text.ToDate, DrPago("Folio").ToString(), "", DrPago("Importe").ToString().ToDouble, DdlMoneda.SelectedValue.ToEntero(), If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then ' ErrorList.Add("Ocurrio un error al guardar los metodos de pago") ' End If ' Next ' 'Else ' ' 'cuando es crédito o terminal ' ' If ObjBancos.AddBancos_IE(, 7, TxtFechaPago.Text.ToDate, TxtFolio.Text.ToString(), "", TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero(), If(DdlMoneda.SelectedValue.ToEntero() = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then ' ' ErrorList.Add("Ocurrio un error al guardar los metodos de pago") ' ' End If ' End If 'End If 'INE COMPLEMENTOS If ObjFactura.ComplementoINE IsNot Nothing Then If Not ObjVentas.UpdateVentasComplementos(ObjFactura.CveVenta, ObjFactura.ComplementoINE.INETipoProceso, ObjFactura.ComplementoINE.INETipoComite, ObjFactura.ComplementoINE.INEIdContabilidad.ToString()) Then ErrorList.Add("Ocurrio un error al guardar los complementos") End If End If If ErrorList.Count = 0 AndAlso factura.TipoDocto.Contiene("Ing", "Ant") Then 'Agregamos las remisiones a la tabla If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then Dim CveVentaDetalle As Integer = 0 Dim CveVentaDetallePadre As Integer = 0 Dim Cantidad As Decimal = 0 Dim CvePS As Integer = 0 Dim PU As Decimal = 0 For Each row As DataRow In DtRemisionesPS.Rows Cantidad = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal CvePS = DtRemisionesTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero() PU = DtRemisionesTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero() CveVentaDetallePadre = row("CveVentaDetalle").ToString().ToEntero() If Not ObjVentas.AgregarRemisionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then ErrorList.Add("Ocurrió un error al agregar el detalle de la Remision") End If Next End If 'If DTRemisiones IsNot Nothing AndAlso DTRemisiones.Rows.Count > 0 AndAlso ErrorList.Count = 0 AndAlso factura.TipoDocto.Contiene("Ing", "Ant") Then ' Dim dt As DataTable = DTRemisiones.FiltraParametros("Aplicado = True") ' If dt.Rows.Count > 0 Then ' For Each row As DataRow In dt.Rows ' If Not ObjVentas.UpdateVentaRemision(row("CveVenta").ToString().ToEntero(), ObjFactura.CveVenta) Then ' ErrorList.Add("Ocurrió un error al actualizar la remisión") ' End If ' Next ' End If 'End If If RemisionesLista IsNot Nothing AndAlso RemisionesLista.Count > 0 AndAlso ErrorList.Count = 0 AndAlso factura.TipoDocto.Contiene("Ing", "Ant") Then For Each CveRemision As Integer In RemisionesLista If Not ObjVentas.UpdateVentaRemision(CveRemision, ObjFactura.CveVenta) Then ErrorList.Add("Ocurrió un error al actualizar la remisión") End If Next End If End If If ErrorList.Count = 0 Then 'Agregamos los pedidos2 a la tabla If DtPedidos2PS IsNot Nothing AndAlso DtPedidos2PS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then Dim CveVentaDetalle As Integer = 0 Dim CveVentaDetallePadre As Integer = 0 Dim Cantidad As Decimal = 0 Dim CvePS As Integer = 0 Dim PU As Decimal = 0 For Each row As DataRow In DtPedidos2PS.Rows Cantidad = DtPedidos2TmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal CvePS = DtPedidos2TmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero() PU = DtPedidos2TmpDT.FiltroPrimeroValor("PU", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal CveVentaDetalle = TmpDTDetalle.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero() CveVentaDetallePadre = row("CveVentaDetalle").ToString().ToEntero() If Not ObjVentas.AddVentaDetallePedido2(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then ErrorList.Add("Ocurrió un error al agregar el detalle del Pedido2") End If Next End If If DtPedidos2 IsNot Nothing AndAlso DtPedidos2.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then Dim dt As DataTable = DtPedidos2.FiltraParametros("Aplicado = True") If dt.Rows.Count > 0 Then For Each row As DataRow In dt.Rows If Not ObjVentas.UpdateVentaPedido2(row("CveVenta").ToString().ToEntero(), ObjFactura.CveVenta) Then ErrorList.Add("Ocurrió un error al actualizar el Pedido2") End If Next End If End If End If If ErrorList.Count = 0 AndAlso RBLTipoContrato.SelectedValue = "4" And DdlEstimacionesObra.SelectedValue.ToEntero > 0 Then If Not ObjContr.UpdateContratosAvanceEstimacionVentas(DdlEstimacionesObra.SelectedValue.ToEntero, ObjFactura.CveVenta, UsuarioActual.CveEmpresa) Then ErrorList.Add("Ocurrió un error al actualizar la estimación") End If End If If ErrorList.Count = 0 Then 'prepoliza GuardarVentaPrePolizas(ObjConta, factura, TmpDTDetalle, CveNCaVincular, objContPaqi, ObjBancos, ObjVentas, ObjEventos:=ObjEventos, EsNCAmortizacion:=EsNCAmortizacion, NCDescuento:=NCDescuento, ListaNCDescuento:=ListaNCDescuento, ObjInventario:=ObjInventario) If ErrorList.Count = 0 Then 'INVENTARIOS If ErrorList.Count = 0 Then If Not EsNCAmortizacion AndAlso Not NCDescuento Then If GuardarVentaInventarios(ObjInventario, ObjVentas, ObjConta, factura, TmpDTDetalle) Then ErrorList.Add("Ocurrio un error al Guardar Inventario") End If End If End If If ErrorList.Count = 0 Then 'estimaciones GuardarVentaEstimaciones(ObjContr, factura) If ErrorList.Count = 0 Then 'armonizaccionContable GuardarVentaAC(ObjVentas, factura, Msgok, objContPaqi) If ErrorList.Count = 0 Then 'Impuestos Locales If GuardarVentaImpuestosLocales(ObjVentas, ObjConta, factura) Then ErrorList.Add("Ocurrio un error al Guardar Impuestos Locales") End If End If End If End If End If End If End If End Sub Private Sub GuardarVentaPrePolizas(ByRef ObjConta As ClsContabilidad, factura As Modelos.Factura, TmpDTDetalleMovimientos As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, 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) Dim CveIE As Integer = -1 Dim DT As DataTable = Nothing Dim CveConceptoAfectacion As Integer = 1 'Cliente Dim CveConceptoAntCli As Integer = 3 'Anticipo Cliente Dim CveConceptoVenta As Integer = 4 'Venta Dim CveConceptoCanAnt As Integer = 11 'Cancelacion Anticipos Dim CveConceptoDSV As Integer = 12 ' DSV Dim CveConceptoIVA As Integer = 13 'IVA Trasladado Dim CveConceptoRetIVA As Integer = 8 'Ret IVA Dim CveConceptoRetISR As Integer = 9 'Ret ISR 'P R E P O L I Z A S If DdlTipoComprobante.SelectedValue <> "Cot" Then If factura.CvePrePoliza > 0 Then If ProcesoPrepolizas(ObjConta, factura, CveIE, TmpDTDetalleMovimientos, objContPaqi, ValorMultiplicador, ObjBancos, ObjVentas, ObjEventos:=ObjEventos, EsNCAmortizacion:=EsNCAmortizacion, NCDescuento:=NCDescuento, ListaNCDescuento:=ListaNCDescuento, ObjInventario:=ObjInventario) Then ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If Else ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If End If End Sub Private Function ProcesoPrepolizas(ByRef ObjConta As ClsContabilidad, ObjFactura As Modelos.Factura, CveIE As Integer, TmpDTDetalle As DataTable, ByRef objContPaqi As ClsContPAQi, Optional ValorMultiplicador As Integer = 1, ByRef Optional ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, Optional EsNCAmortizacion As Boolean = False, Optional NCDescuento As Boolean = False, Optional ListaNCDescuento As List(Of Modelos.Factura) = Nothing, Optional ObjInventario As ClsInventarios = Nothing) As Boolean Try Dim DT As DataTable Dim CvePlantilaPoliza As Integer Dim PorcentajeAmortizacion As Decimal = 0 Dim sumaAmorticaciones As Decimal = 0 Dim ErrorPrepoliza As Boolean = False Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " Dim CveCuentaContabilizacion As Integer = 1 Dim tipoCambio As Decimal Dim CuentasContablesInvalidasSIG As New StringBuilder If ObjFactura.TipoDocto = "Ing" Or ObjFactura.TipoDocto = "Ant" Or ObjFactura.TipoDocto = "Com" Then CvePlantilaPoliza = 4 ElseIf ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then CvePlantilaPoliza = 7 ElseIf ObjFactura.TipoDocto.Contiene("Rem", "RNC") Then CvePlantilaPoliza = 4 End If If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then tipoCambio = ObjFactura.TipoCambio ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then If UsuarioActual.CveEmpresa.Contiene(13, 83) Then tipoCambio = GlobalTipoCambio(ObjFactura.Fecha.AddDays(-1)).ToString().ToDecimal Else tipoCambio = GlobalTipoCambio(ObjFactura.Fecha).ToString().ToDecimal 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 IdCtaContable As Integer Dim IdCtaContableCliente As Integer Dim Concepto As String = ObjFactura.SerieFolio Dim Referencia As String = ObjFactura.SerieFolio Dim Fecha = TxtFecha.Text.Trim.ToDate Dim importeMX As Decimal Dim Multiplicador As Integer Dim CveIEPago As Integer Dim FolioIE As Long Dim CveIEAnticipo As Integer Dim CveSubProyectoVenta = DdlSubProyectoDatos.SelectedValue.ToEntero() Dim CveSubProyectoContabilizar As Integer Dim IdCtaIVAXTrasladar As Integer = 0 Dim IdCtaIVATrasladado As Integer = 0 Dim SeContabiliza As Boolean = True Dim SimplificarPrePoliza As Boolean = False If (UsuarioActual.Empresa.Funcionalidad(343) = "1" AndAlso ObjFactura.TipoDocto = "Ant") Or (ChkAntEspecial.Checked AndAlso ObjFactura.TipoDocto = "Ant") Then SeContabiliza = False End If If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVAXTrasladar").ToString().ToEntero() IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVATrasladado").ToString().ToEntero() 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 IdCtaContable = 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 ObjFactura.TipoDocto.Contiene("Ant") Then ' TipoMovimiento = Not TipoMovimiento 'lo contrario a ingreso, en este caso es anticipo 'End If If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If tipoCambio = 1 Then IdCtaContable = ObjFactura.Cliente.IdCtaContClientes Else IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or UsaComplementariaClientes) Then importeMX = importeMovimiento If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=(importeMovimiento * tipoCambio - importeMovimiento).RoundSQL, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True End If End If IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera End If IdCtaContableCliente = IdCtaContable End If 'Case 7 'descuentos ' If LblDescuentos.Text.ToDecimal > 0 Then ' importeMovimiento = (ObjFactura.Descuento) * ValorMultiplicador ' importeMX = importeMovimiento * tipoCambio * Multiplicador ' FechaMovimiento = ObjFactura.FechaPago ' CveSubProyectoContabilizar = CveSubProyectoVenta ' IdCtaContable = 0 ' If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" ' 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 IdCtaContable = ObjFactura.Cliente.IdCtaContAnticipos CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" End If Case 190 'Remisión del cliente If ObjFactura.TipoDocto = "Rem" Then importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador importeMX = importeMovimiento * tipoCambio * Multiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If tipoCambio = 1 Then IdCtaContable = ObjFactura.Cliente.IdCtaContClientes Else IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera End If IdCtaContableCliente = IdCtaContable If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 190, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 193, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, 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 tipoCambio = 1 Then IdCtaContable = ObjFactura.Cliente.IdCtaContClientes Else IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera End If IdCtaContableCliente = IdCtaContable If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 277, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 278, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, 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 importeMovimiento = ObjFactura.Total * ValorMultiplicador importeMX = (importeMovimiento * tipoCambio * Multiplicador).RoundSQL FechaMovimiento = ObjFactura.FechaPago Dim ImporteConcepto12 As Decimal = 0 Dim ImporteAcumulado91 As Decimal = 0 Dim CveUltimaVenta As Integer = 0 If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If tipoCambio = 1 Then IdCtaContable = ObjFactura.Cliente.IdCtaContClientes ElseIf UsaComplementariaClientes Then IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or UsaComplementariaClientes) Then importeMX = importeMovimiento If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If End If IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera 'CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera End If CveSubProyectoContabilizar = CveSubProyectoVenta ImporteConcepto12 = importeMX.RoundSQL If importeMovimiento <> 0 Then If IdCtaContable <= 0 Then CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString()) idCuentaContabilizacion = 0 End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If End If importeMovimiento = 0 If ValorMultiplicador = 1 Then Dim IdCtaContableClienteComplementaria As Integer = ObjFactura.Cliente.IdCtaContComplementaria Dim TipoCambioNC As Decimal = 1 If tipoCambio > 1 Then TipoCambioNC = tipoCambio Else If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TipoCambioNC = GlobalTipoCambio(TxtFecha.Text.ToDate.AddDays(-1)).ToDecimal Else TipoCambioNC = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal End If End If 'APLICA NC SALDOS DIRECTOS If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then For Each Dr As DataRow In DtVentasNC.Rows Dim Importe91 As Decimal = 0 Dim ImporteMN91 As Decimal = 0 Dim Importe251 As Decimal = 0 Dim ImporteMN251 As Decimal = 0 If DdlMoneda.SelectedValue.ToEntero() = 1 AndAlso Not Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then Importe251 = Dr("Importe").ToString().ToDecimal Importe91 = Dr("Importe").ToString().ToDecimal ImporteMN91 = Dr("Importe").ToString().ToDecimal TipoCambioNC = 1 ElseIf DdlMoneda.SelectedValue.ToEntero() = 2 AndAlso Not Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then Importe251 = Dr("Importe").ToString().ToDecimal Importe91 = Dr("Importe").ToString().ToDecimal ImporteMN91 = Dr("Importe").ToString().ToDecimal * TipoCambioNC ElseIf DdlMoneda.SelectedValue.ToEntero() = 2 AndAlso Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then Importe251 = Dr("Importe").ToString().ToDecimal Importe91 = Dr("Importe").ToString().ToDecimal ImporteMN91 = Dr("Importe").ToString().ToDecimal * TipoCambioNC ElseIf DdlMoneda.SelectedValue.ToEntero() = 1 AndAlso Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then Importe91 = Dr("Importe").ToString().ToDecimal / TipoCambioNC ImporteMN91 = Dr("Importe").ToString().ToDecimal End If Dim TCFluctuacion As Decimal = Dr("TCCambioValuacion").ToString().ToDecimal If TCFluctuacion = 1 AndAlso TipoCambioNC > 1 Then If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TCFluctuacion = GlobalTipoCambio(TxtFecha.Text.ToDate.AddDays(-1)).ToDecimal Else TCFluctuacion = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal End If End If If DdlMoneda.SelectedValue.ToEntero() = 2 AndAlso Not Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then ImporteMN251 = Dr("Importe").ToString().ToDecimal * TCFluctuacion ElseIf DdlMoneda.SelectedValue.ToEntero() = 2 AndAlso Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then ImporteMN251 = Dr("Importe").ToString().ToDecimal * TCFluctuacion ElseIf DdlMoneda.SelectedValue.ToEntero() = 1 AndAlso Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then Importe251 = Dr("Importe").ToString().ToDecimal / TCFluctuacion ImporteMN251 = Dr("Importe").ToString().ToDecimal Else ImporteMN251 = Dr("Importe").ToString().ToDecimal End If Importe251 = Importe251.RoundSQL Importe91 = (Importe91).RoundSQL ImporteMN91 = (ImporteMN91 * Multiplicador).RoundSQL If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${Importe91.FormatoNumero(2)}" CveUltimaVenta = Dr("CveVenta").ToString().ToEntero() Dim ImporteComplementarioIngreso As Decimal = 0 If UsaComplementariaClientes = True AndAlso tipoCambio > 1 Then ImporteMN91 = Importe91 ImporteComplementarioIngreso = ((Importe91 * tipoCambio) - Importe91).RoundSQL If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString().ToEntero(), ImporteMX:=ImporteComplementarioIngreso, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=Dr("TCCambioValuacion").ToString().ToDecimal) Then ErrorPrepoliza = True Exit For End If End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString().ToEntero(), ImporteMX:=ImporteMN91, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then ErrorPrepoliza = True Exit For End If ImporteAcumulado91 += (ImporteMN91).RoundSQL If UsaComplementariaClientes = True AndAlso Dr("TCCambioValuacion").ToString().ToDecimal > 1 Then ImporteMN251 = Importe251 Dim ImporteComplementarioNC As Decimal = ((Importe251 * Dr("TCCambioValuacion").ToString().ToDecimal) - Importe251).RoundSQL If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementarioNC, ImporteME:=If(Dr("TCCambioValuacion").ToString().ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString().ToDecimal) Then ErrorPrepoliza = True Exit For End If End If ' Traslado de impuestos cuando es amortizacion de NC If EsNCAmortizacion Then '' aqui no se registra el pago como NC, se deja para el registro de la aplicaion del anticipo '' esto para trasladar los impuestos. If Not AplicoNCFacturaActual Then If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() = 2 AndAlso ObjFactura.TipoDocto.Contiene("Egs") Then For Each row2 As GridViewRow In GVAnticipos.Rows If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 3 Then If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then CveIEAnticipo = row2.DataKey("CveIE").ToString().ToEntero() importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) Dim ImporteAnticipo As Decimal = importeMovimiento If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then ImporteAnticipo = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal * row2.DataKey("SubTotalAnticipo").ToDecimal IdCtaContable = IdCtaContAnticipos CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then 'SI LA NC ES EN DOLARES Y PERO VIENE DE UN ANTICIPO EN PESOS If (Not UsuarioActual.CveEmpresa.Contiene(72, 80, 146)) AndAlso ObjFactura.CveMoneda = 2 Then Dim tipoCambioAnticipo = GlobalTipoCambio(row2.DataKey("Fecha").ToString().ToDate).ToDecimal If UsuarioActual.CveEmpresa.Contiene(13, 83) Then tipoCambioAnticipo = GlobalTipoCambio(row2.DataKey("Fecha").ToString().ToDate.AddDays(-1)).ToDecimal End If If row2.DataKey("CveMoneda").ToString.ToEntero = 2 Then IdCtaContable = IdCtaContAnticiposExtranjera End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ImporteAnticipo, Referencia, 11, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero(), CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=ImporteAnticipo, ImporteME:=If(tipoCambioAnticipo = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza, TipoCambio:=tipoCambioAnticipo) Then ErrorPrepoliza = True Exit For End If If row2.DataKey("CveMoneda").ToString.ToEntero = 2 Then IdCtaContable = IdCtaContAnticiposComplementaria If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ImporteAnticipo * tipoCambioAnticipo - ImporteAnticipo, Referencia, 227, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero(), CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=ImporteAnticipo * tipoCambioAnticipo - ImporteAnticipo, ImporteME:=If(tipoCambioAnticipo = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza, TipoCambio:=tipoCambioAnticipo) Then ErrorPrepoliza = True Exit For End If End If Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 292, NombreCliente, Dr("Folio").ToString, FolioIE.ToString()) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimiento, Referencia, 292, Concepto, FechaMovimiento, ObjFactura.Cliente.IdCtaContMonedaExtranjera, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento, ImporteME:=If(Dr("TCCambioValuacion").ToString().ToDecimal = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, CveIE:=CveIEAnticipo, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString().ToDecimal, TipoCambioPago:=tipoCambio) Then ErrorPrepoliza = True Exit For End If Else If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ImporteAnticipo, Referencia, 11, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero(), CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=ImporteAnticipo, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True Exit For Else ViewState("SeGuardoPrePoliza") = True If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimiento, Referencia, 2, Concepto, FechaMovimiento, ObjFactura.Cliente.IdCtaContClientes, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento, ImporteME:=If(Dr("TCCambioValuacion").ToString().ToDecimal = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, CveIE:=CveIEAnticipo, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString().ToDecimal, TipoCambioPago:=tipoCambio) Then ErrorPrepoliza = True Exit For End If 'se hace acreditamiento de impuestos 'IVA X TRASLADAR Dim EsAnticipoEspecial As Boolean = False If UsuarioActual.CveEmpresa.Contiene(1, 119) Then EsAnticipoEspecial = True If EsAnticipoEspecial Then Dim PorcentajeImpuestoPago As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal '' si se esta aplicando NC por amortizaion, se trasladan impuestos If EsNCAmortizacion Then Dim IngresoIVA As Decimal = TxtIVA.Text.ToDecimal Dim IngresoIEPS As Decimal = TxtIEPS.Text.ToDecimal Dim IngresoTotal As Decimal = TxtTotal.Text.ToDecimal If IngresoIVA > 0 Then IdCtaIVAXTrasladar = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, NombreCliente, Dr("Folio").ToString, FolioIE.ToString()) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, (importeMovimiento * IngresoIVA) / IngresoTotal, Referencia, 13, Concepto, Fecha, IdCtaIVAXTrasladar, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=((importeMovimiento * IngresoIVA) / IngresoTotal) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ErrorPrepoliza = True Exit For End If 'IVA PAGADO IdCtaIVATrasladado = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, NombreCliente, Dr("Folio").ToString, FolioIE.ToString()) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, (importeMovimiento * IngresoIVA) / IngresoTotal, Referencia, 61, Concepto, Fecha, IdCtaIVATrasladado, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=((importeMovimiento * IngresoIVA) / IngresoTotal) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ErrorPrepoliza = True Exit For End If End If If IngresoIEPS > 0 Then 'IEPS X TRASLADAR Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, NombreCliente, Dr("Folio").ToString, FolioIE.ToString()) If IngresoIEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, (importeMovimiento * IngresoIEPS) / IngresoTotal, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=((importeMovimiento * IngresoIEPS) / IngresoTotal) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True Exit For End If 'IEPS PAGADO Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, NombreCliente, Dr("Folio").ToString, FolioIE.ToString()) If IngresoIEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, (importeMovimiento * IngresoIEPS) / IngresoTotal, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=((importeMovimiento * IngresoIEPS) / IngresoTotal) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True Exit For End If End If End If End If End If End If End If End If End If Next End If ElseIf AplicoNCFacturaActual AndAlso ChkAplicaNCAnticipo.Checked Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteMN251, ImporteME:=If(Dr("TCCambioValuacion").ToString().ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString().ToDecimal, TipoCambioPago:=tipoCambio) Then ErrorPrepoliza = True Exit For End If End If Else If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=Dr("CveVenta").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteMN251, ImporteME:=If(Dr("TCCambioValuacion").ToString().ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString().ToDecimal, TipoCambioPago:=tipoCambio) Then ErrorPrepoliza = True Exit For End If End If 'considero fluctuación. If TipoCambioNC <> TCFluctuacion AndAlso TCFluctuacion > 1 AndAlso TipoCambioNC > 1 Then Dim difFluctuacion As Decimal = TipoCambioNC - TCFluctuacion Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida Dim TipoMovtoFluctua As Boolean = True Dim IdCtaContableFluctua As Integer If difFluctuacion < 0 Then CveConceptoFluctua = 65 TipoMovtoFluctua = False IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria Else CveConceptoFluctua = 64 TipoMovtoFluctua = True IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria End If Dim ImporteFluctuacion As Decimal = Math.Abs((Importe251 * difFluctuacion).RoundSQL) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString().ToEntero(), ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=TipoCambioNC, TipoCambioPago:=Dr("TCCambioValuacion").ToString().ToDecimal) Then ErrorPrepoliza = True Exit For End If End If Next If ImporteConcepto12 <> ImporteAcumulado91 Then Dim CveConceptoOtIngresos As Integer = 0 Dim IdCuentaContableOt As Integer = 0 Dim TipoMovtoOt As Boolean = False If ImporteConcepto12 > ImporteAcumulado91 Then IdCuentaContableOt = UsuarioActual.Empresa.Funcionalidad(559).ToEntero() CveConceptoOtIngresos = 211 TipoMovtoOt = False Else IdCuentaContableOt = UsuarioActual.Empresa.IdCuentaOtrosIngresos CveConceptoOtIngresos = 78 TipoMovtoOt = True End If Dim ImporteOtrosIngresos As Decimal = ImporteConcepto12 - ImporteAcumulado91 ' If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ImporteOtrosIngresos, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveUltimaVenta, ImporteMX:=ImporteOtrosIngresos, ImporteME:=0, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoOt, ImporteOtrosIngresos, Referencia, CveConceptoOtIngresos, Concepto, FechaMovimiento, IdCuentaContableOt, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteME:=0, ImporteMX:=ImporteOtrosIngresos, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If 'Else ' ErrorPrepoliza = True 'End If End If If Not ErrorPrepoliza AndAlso ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 5) Then If ObjConta.ValorPolizaDescuadre > 0 Then 'ErrorPrepoliza = True GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then ' Dim DtTest = ObjConta.DtResultados 'End If End If End If If ErrorPrepoliza Then Exit For End If End If 'APLICA DEVOLUCION SALDOS DIRECTOS If AplicaDevolucion Then Dim importeMovimientoDev = TxtTotal.Text.ToDecimal importeMovimientoDev = If(SaldoVentaDevolucion < importeMovimientoDev, SaldoVentaDevolucion, importeMovimientoDev) If importeMovimientoDev > 0 Then Dim importeMXDev = importeMovimientoDev * tipoCambio * Multiplicador If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimientoDev.FormatoNumero(2)}" If UsaComplementariaClientes AndAlso tipoCambio > 1 Then importeMXDev = importeMovimientoDev Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * tipoCambio) - importeMovimientoDev).RoundSQL If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteComplementaria, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura) Then ErrorPrepoliza = True Exit For End If End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True Exit For End If If UsaComplementariaClientes AndAlso TipoCambioFactura > 1 Then importeMXDev = importeMovimientoDev Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * TipoCambioFactura) - importeMovimientoDev).RoundSQL If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementaria, ImporteME:=If(TipoCambioFactura = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=TipoCambioFactura) Then ErrorPrepoliza = True Exit For End If End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True Exit For End If If tipoCambio <> TipoCambioFactura Then Dim difFluctuacion As Decimal = tipoCambio - TipoCambioFactura Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida Dim TipoMovtoFluctua As Boolean = True Dim IdCtaContableFluctua As Integer If difFluctuacion < 0 Then CveConceptoFluctua = 65 TipoMovtoFluctua = False IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria Else CveConceptoFluctua = 64 TipoMovtoFluctua = True IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria End If Dim ImporteFluctuacion As Decimal = Math.Abs((importeMovimientoDev * difFluctuacion).RoundSQL) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura) Then ErrorPrepoliza = True Exit For End If End If If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 2) Then If ObjConta.ValorPolizaDescuadre > 0 Then 'ErrorPrepoliza = True GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then ' Dim DtTest = ObjConta.DtResultados 'End If End If End If End If End If End If End If 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 row2.DataKey("IdCtaContable").ToEntero() > 0 Then IdCtaContable = row2.DataKey("IdCtaContable").ToEntero() Else If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(row2.DataKey("CveConceptoContable").ToEntero(), ObjFactura.CveCliente) Then If ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContFondoGarantia").ToString().ToEntero() End If End If End If If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, If(row2.DataKey("TipoMovto").ToString() = "True", True, False), importeMovimiento, Referencia, row2.DataKey("CveConceptoContable").ToEntero(), Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If End If End If Next importeMovimiento = 0 Case 11 'Anticipo '[IPP] SI ES REFACTURACION LOS ANTICIPOS NO LOS DEBE APLICAR EN EL INGRESO REFACTURADO (VIEJO) If NuevaFactura = 1 And ObjFactura.CveVenta = CveDevolucion Then Exit Select End If If ObjFactura.TipoDocto = "Ing" AndAlso ValorMultiplicador = -1 Then For Each row2 As GridViewRow In GvAntNC.Rows If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 11 Then importeMovimiento = row2.DataKey("Importe").ToString().ToDecimal * ValorMultiplicador '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" IdCtaContable = IdCtaContAnticipos CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero(), CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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)}" IdCtaContable = IdCtaContAnticipos CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVentaAnticipo, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento, 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 If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() = 1 AndAlso ObjFactura.TipoDocto.Contiene("Ing") OrElse DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() = 3 Then For Each row2 As GridViewRow In GVAnticipos.Rows If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 3 Then If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then CveIEAnticipo = row2.DataKey("CveIE").ToString().ToEntero() importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal) If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" IdCtaContable = IdCtaContAnticipos CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero(), CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True Exit For Else ViewState("SeGuardoPrePoliza") = True End If End If End If End If Next End If 'Cuando la funcionalidad de amortizacion en PS esta activa If Not ErrorPrepoliza Then DT = TmpDTDetalle.FiltraParametros($"CvePS = {CvePSAmortizacion}") If DT.Rows.Count > 0 Then For Each Row2 As DataRow In DT.Rows importeMovimiento = Math.Abs(Row2("PU").ToString().ToDecimal) IdCtaContable = IdCtaContAnticipos CveSubProyectoContabilizar = CveSubProyectoVenta If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True Else ViewState("SeGuardoPrePoliza") = True End If End If Next End If End If 'PorcentajeAmortizacion = sumaAmorticaciones / TxtTotal.Text.ToDecimal importeMovimiento = 0 Case 91 'Amortizacion Nota de Credito Dim Contabilizable = If(UsuarioActual.CveEmpresa = 119, False, True) If ValorMultiplicador = -1 Then 'cuando es cancelación For Each row2 As GridViewRow In GvNC.Rows If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 91 Then importeMovimiento = row2.DataKey("Importe").ToDecimal * ValorMultiplicador sumaAmorticaciones += importeMovimiento If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" 'CTACONTABLE 'IdCtaContable = IdCtaContAnticipos 'CveCuenta = CveCuentaAnticipos If tipoCambio = 1 Then IdCtaContable = ObjFactura.Cliente.IdCtaContClientes Else IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera End If CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimiento, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVentaNC").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimiento, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString().ToEntero(), ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then ErrorPrepoliza = True Exit For End If Else ErrorPrepoliza = True Exit For End If 'If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString().ToEntero(), ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True 'End If End If End If Next Else For Each row2 As GridViewRow In GVAnticipos.Rows If row2.DataKey("CveConceptoContable").ToString().ToEntero() = 12 Then If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal sumaAmorticaciones += importeMovimiento If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" IdCtaContable = IdCtaContAnticipos CveSubProyectoContabilizar = CveSubProyectoVenta If importeMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToString().ToEntero(), CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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)}" If tipoCambio = 1 Then IdCtaContable = ObjFactura.Cliente.IdCtaContClientes Else IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera End If '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 IdCtaContableCliente = IdCtaContable 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, Referencia, 277, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, 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, Referencia, 318, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Importe318, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, SubTotalCalculado, Referencia, 150, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=ObjRNC.DtDetalle.MAX("CveClasificacion").ToEntero(), CveSubProyecto:=ObjRNC.CveSubProyecto, ImporteMX:=SubTotalCalculado, 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, Referencia, 277, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 278, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjRNC.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, 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 If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, sumaAmorticaciones, Referencia, 251, Concepto, FechaMovimiento, IdCtaContClientes, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=sumaAmorticaciones * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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 = 4 Dim CveVentaAplicar = ObjFactura.CveVenta Dim CveVentaAmortizacionAplicar = -1 If ObjFactura.TipoDocto.Contiene("Egs") And DdlTipoComprobante.SelectedValue = "Ant" And CveDevolucion > 0 And NuevaFactura = 1 Then ConceptoContableAplicar = 11 CveVentaAplicar = CveDevolucion CveVentaAmortizacionAplicar = ObjFactura.CveVenta End If ''Cuando se está amortizando con un anticipo y es la modalidad de NC 'If ObjFactura.TipoDocto.Contiene("Ing") AndAlso CveAnticipo > 0 AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then ' ConceptoContableAplicar = 11 ' CveVentaAplicar = CveAnticipo ' CveVentaAmortizacionAplicar = ObjFactura.CveVenta 'End If ' If UsuarioActual.CveEmpresa = 119 Then 'código fijo en base el porcentaje iva, que se afecten las clasificaciones For i = 0 To TmpDTDetalle.Rows.Count - 1 'se excluyen las clasificaciones anteriores para que se asignen las de ingreso If Not TmpDTDetalle(i)("CveClasificacion").ToString().Contiene("19958", "19933", "18097") Then 'If TmpDTDetalle(i)("PorcentajeIVA").ToString().ToDecimal > 0 Then ' If TmpDTDetalle(i)("PorcentajeIVA").ToString().ToDecimal = 0.08 Then ' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8% ' Else ' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16% ' End If ' Else ' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0% ' End If 'reclasifica la clasificación del producto, por la del ingreso correspondiente a su iva If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString().ToDecimal).Rows.Count > 0 Then TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString().ToDecimal).Rows(0)("CveClasificacion").ToString() End If End If Next ' End If DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto", "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}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).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 ObjFactura.TipoDocto.Contiene("Egs") Then IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero() Else IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero() End If 'CveCuenta = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresosSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero() If importeMovimiento <> 0 Then If IdCtaContable <= 0 Then CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString() + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString()}")) idCuentaContabilizacion = 0 End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=Row2("CveSubProyecto").ToString().ToEntero(), ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, 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 = 150 Dim CveVentaAplicar = ObjFactura.CveVenta Dim CveVentaAmortizacionAplicar = -1 If UsuarioActual.CveEmpresa = 119 Then 'código fijo en base el porcentaje iva, que se afecten las clasificaciones For i = 0 To TmpDTDetalle.Rows.Count - 1 'se excluyen las clasificaciones anteriores para que se asignen las de ingreso If Not TmpDTDetalle(i)("CveClasificacion").ToString().Contiene("19958", "19933", "18097") Then If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveClasificacion").ToString() End If End If Next End If DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto", "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}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString().ToDecimal) * ValorMultiplicador 'If ObjFactura.TipoDocto = "Egs" Then ' importeMovimiento += (TmpDTDetalle.SUM("ImporteIVA", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString().ToDecimal) * ValorMultiplicador ' importeMovimiento += (TmpDTDetalle.SUM("ImporteIEPS", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString().ToDecimal) * ValorMultiplicador ' importeMovimiento -= (TmpDTDetalle.SUM("ImporteRetIVA", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString().ToDecimal) * ValorMultiplicador ' importeMovimiento -= (TmpDTDetalle.SUM("ImporteRetISR", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString().ToDecimal) * ValorMultiplicador 'End If 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 ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then Dim CampoCuenta As String = "IdCuentaGasto" 'If UsuarioActual.CveEmpresa.Contiene(80, 72, 146) Then CampoCuenta = "IdCuentaDescuento" IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor(CampoCuenta, String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero() Else IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero() End If If UsuarioActual.CveEmpresa = 119 Then If Row2("CveClasificacion").ToString() = "19930" Then IdCtaContable = 1141 If Row2("CveClasificacion").ToString() = "19929" Then IdCtaContable = 1142 End If If importeMovimiento <> 0 Then If IdCtaContable <= 0 Then CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString() + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString()}")) idCuentaContabilizacion = 0 End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=Row2("CveSubProyecto").ToString().ToEntero(), ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, 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 If ObjFactura.Descuento <> 0 AndAlso Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") AndAlso (DdlTipoAmortizacionAnticipo.SelectedValue = "-1" OrElse UsuarioActual.CveEmpresa = 141) Then importeMovimiento = ObjFactura.Descuento * Multiplicador * ValorMultiplicador importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador * ValorMultiplicador FechaMovimiento = ObjFactura.FechaPago CveSubProyectoContabilizar = CveSubProyectoVenta If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then If ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString().ToEntero() 'CveCuenta = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString().ToEntero() End If End If DT = TmpDTDetalle.FiltraParametros("", "", {"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("Descuento", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).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 ObjFactura.TipoDocto.Contiene("Egs") Then IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero() Else IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaDescuento", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero() End If If importeMovimiento <> 0 Then If IdCtaContable <= 0 Then CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString() + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString()}")) idCuentaContabilizacion = 0 End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 103, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveVentaAmortizacion:=-1, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=Row2("CveSubProyecto").ToString().ToEntero(), ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, 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 ' 'si se amortiza anticipo por concepto de descuento, no debe de registrar esta partida. ' If DdlTipoAmortizacionAnticipo.SelectedValue <> "1" Then ' importeMovimiento = ObjFactura.Descuento * ValorMultiplicador ' importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador ' FechaMovimiento = ObjFactura.FechaPago ' If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" ' IdCtaContable = 0 ' End If Case 8 'Ret IVA por Trasladar If Not ObjFactura.TipoDocto.Contiene("Rem", "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 'CONTABILIDAD CONTPAQ If IdCtaContRetIVA > 0 Then IdCtaContable = IdCtaContRetIVA Else If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then If ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString().ToEntero() End If End If End If 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 'OBTENER CUENTAS If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) Then If ObjConta.DtResultados.Rows.Count > 0 Then 'Conta ContPAQ IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString().ToEntero() End If 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)}" 'Contabilidad ContPAQ If IdCtaContRetISR > 0 Then IdCtaContable = IdCtaContRetISR Else If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then If ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString().ToEntero() End If End If End If 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 IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) Else IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) 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 If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then If ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSTrasladado").ToString().ToEntero() End If End If Else If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then If ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxTrasladar").ToString().ToEntero() End If End If End If If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" 'If importeMovimiento <> 0 AndAlso ObjFactura.TipoDocto = "Egs" Then ' 'IEPS X TRASLADAR ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=-1, ImporteMX:=importeMX * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True ' Exit For ' End If ' 'IEPS PAGADO ' Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) ' If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=-1, ImporteMX:=importeMX * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then ' ErrorPrepoliza = True ' Exit For ' End If ' importeMovimiento = 0 ' importeMX = 0 'End If 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 IdCtaContable = 0 CveSubProyectoContabilizar = CveSubProyectoVenta If GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString().ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).Rows.Count = 1 Then IdCtaContable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString().ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0)("IdCtaContable").ToString().ToEntero() ' CveCuenta = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString().ToEntero()).Rows(0)("IdCtaContableSIG").ToString().ToEntero() End If If IdCtaContable <= 0 Then CuentasContablesInvalidas.AppendFormat("
    {0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString().ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0)("NumCuentaMoneda").ToString().ToEntero()) idCuentaContabilizacion = 0 End If '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, Referencia, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMovimiento, 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, Referencia, 204, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEPago, ImporteMX:=ImporteComplementaria, 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, Referencia, 2, Concepto, Fecha, IdCtaContableCliente, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMovimiento, 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, Referencia, 207, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEPago, ImporteMX:=ImporteComplementaria, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, TipoCambioPago:=tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then ErrorPrepoliza = True End If End If SimplificarPrePoliza = True Else 'BANCOS Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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, Referencia, 2, Concepto, Fecha, IdCtaContableCliente, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, 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 IdCtaIVAXTrasladar = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 13, Concepto, Fecha, IdCtaIVAXTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ErrorPrepoliza = True Exit For End If 'IVA PAGADO IdCtaIVATrasladado = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString()) If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 61, Concepto, Fecha, IdCtaIVATrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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 Dim IdCtaContableRetIVA = 0 'RETIVA X TRASLADAR 'OBTENER CUENTAS If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(313, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then 'Conta ContPAQ IdCtaContableRetIVA = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero Else IdCtaContableRetIVA = 0 End If 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, Referencia, 313, Concepto, Fecha, IdCtaContableRetIVA, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.RetIVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then ErrorPrepoliza = True Exit For End If 'RETIVA PAGADO If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(314, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then 'Conta ContPAQ IdCtaContableRetIVA = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero Else IdCtaContableRetIVA = 0 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, Referencia, 314, Concepto, Fecha, IdCtaContableRetIVA, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.RetIVA) / ObjFactura.Total) * tipoCambio * Multiplicador, 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 End Select If (importeMovimiento <> 0 OrElse (importeMovimiento = 0 AndAlso ObjFactura.Total = 0 AndAlso ConceptoContable = 1)) And Not ErrorPrepoliza Then If IdCtaContable <= 0 Then CuentasContablesInvalidas.Append("
    " & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString()) idCuentaContabilizacion = 0 End If If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), 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 'Factura If Not ObjEventos.AddEventoBitacora($"Remisión facturada : {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then ErrorPrepoliza = True End If 'Remision If Not ObjEventos.AddEventoBitacora($"Facturación de remisión en: {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveRemision) Then ErrorPrepoliza = True End If Next End If End If 'REGRESA SALDO A LAS REMISIONES QUE SE FACTURARON EN EL INGRESO QUE SE ESTA CANCELANDO If ObjFactura.TipoDocto = "Ing" And ValorMultiplicador = -1 AndAlso NuevaFactura <> 1 AndAlso Not SeCancelaRemisionProceso Then ' se debe de excluir cuando es refacturación If ObjVentas.GetRemisionesRelacionadas(ObjFactura.CveVenta, ObjFactura.TipoDocto) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then For Each Dr As DataRow In ObjVentas.DtResultados.Rows Dim Selecciono As Boolean = False If ChkCanRem.Checked Then For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows If Gvr.DataKey("CveVenta").ToEntero() = Dr("CveVenta").ToString().ToEntero() AndAlso Gvr.FCCheckBox("ChkCancelarRemision").Checked Then Selecciono = True End If Next End If If Not Selecciono Then If Not ObjConta.TraspasarSaldosRemision(Dr("CveVenta").ToString().ToEntero(), ObjFactura.CvePrePoliza, ObjFactura.CveVenta, 1) Then ErrorPrepoliza = True End If 'Remision If Not ObjEventos.AddEventoBitacora($"Facturación cancelada en: {TxtFolio.Text}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Dr("CveVenta").ToString().ToEntero()) Then ErrorPrepoliza = True End If End If Next End If End If If NuevaFactura = 1 AndAlso TotalOriginal > TxtTotal.Text.ToDouble AndAlso ObjEventos IsNot Nothing Then If Not ObjEventos.AddEventoBitacora($"Factura a menor precio de la factura origen.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then ErrorPrepoliza = True Else Alert("Factura a menor precio de la factura origen.", TipoMensaje.MsgAdvertencia) End If End If '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 If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 2) Then If ObjConta.ValorPolizaDescuadre > 0 Then If ObjConta.ValorPolizaDescuadre = 2 Then ErrorPrepoliza = True Alert(ObjConta.MensajePolizaDescuadre, TipoMensaje.MsgError) End If 'ErrorPrepoliza = True GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas") 'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA 'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then ' Dim DtTest = ObjConta.DtResultados 'End If End If End If '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 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 End If Return ErrorPrepoliza Catch ex As Exception GuardaLog("GuardaPreP." & ex.ToString()) Return True End Try End Function Private Function GuardarVentaInventarios(ObjInventario As ClsInventarios, ObjVentas As ClsVentas, ObjConta As ClsContabilidad, factura As Modelos.Factura, TmpDTDetalle As DataTable) As Boolean Dim OcurrioError As Boolean = False Try If UsuarioActual.Empresa.UsaInventarios AndAlso factura.TipoDocto.Contiene("Ing", "Egs", "Rem", "Dev") Then If RemisionesLista.Count > 0 AndAlso factura.TipoDocto.Contiene("Ing", "Rem") Then For Each CveRemision As Integer In RemisionesLista 'El almacen general es el Primer Almacen de Material en la Sucursal If Not TraspasoAlmacen(ObjInventario, ObjVentas, CveRemision, ObjConta, True, 9, TmpDTDetalle) Then OcurrioError = True ErrorList.Add("Ocurrió un error al verificar inventario de remisiones.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") ModExtensiones.GuardaLog("Ocurrió un error al verificar inventario de remisiones.Revise su factura y cualquier detalle comuníquese a Soporte Técnico") Exit For End If Next End If 'EN ECONOLLANTAS DEBE REALIZAR SIEMPRE LA SALIDA DE ALMACEN If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso UsuarioActual.Empresa.Funcionalidad(567) = "1" AndAlso factura.TipoDocto.Contiene("Ing", "Egs", "Rem") Then For Each GvRow As GridViewRow In GvInv.Rows If GvRow.RowType = DataControlRowType.DataRow Then GvRow.FCCheckBox("cbInv").Checked = True End If Next End If If DivAlmacen.Visible AndAlso GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked) > 0 Then Dim Filtro As String = "" Select Case factura.TipoDocto Case "Ing", "Ped" Filtro = "CveConcepto IN (3,40)" Case "Dev" Filtro = "CveConcepto IN (3,40)" Case Else Filtro = "CveConcepto = 9" End Select Dim CveConceptoAlmacen As Integer = 3 If factura.TipoDocto = "Dev" Then CveConceptoAlmacen = 18 End If Dim CveAlmacen = ddlAlmacen.SelectedValue.ToEntero() If CveAlmacen <= 0 Then OcurrioError = True ErrorList.Add("Ocurrió un error al agregar los Movimientos de salida al Inventario.
    No ha seleccionado ningun almacen o no tiene permiso para el almacen de esta sucursal.") End If Dim CveMovimientoInventario As Integer = ObjInventario.AddMovimiento(CveAlmacen, CveConceptoAlmacen, factura.CveMoneda, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1, Modulo:="Vta/E1") If CveMovimientoInventario <= 0 Then OcurrioError = True ErrorList.Add("Ocurrió un error al agregar los Movimientos de salida al Inventario.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") Else Dim Mensaje As String = "" Dim i As Integer = 0 Dim Cantidad As Double Dim CveUnidad As Integer Dim CveProducto As Integer Dim Existencia As Double Dim PU As Decimal = 0 Dim DtEquivalencias As DataTable For Each Dr As DataRow In DtInv.Rows If GvInv.Rows(i).FCCheckBox("cbInv").Checked Then CveProducto = Dr("CvePS").ToString().ToEntero() CveUnidad = Dr("CveUM").ToString().ToEntero() Cantidad = Dr("Cantidad").ToString().ToDouble Dim AplicaSeccion As Boolean = CBool(GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CvePS:=CveProducto).FiltroPrimeroValor("AplicaSeccion")) If Dr("CveTipoInvPS").ToString().ToEntero() = 5 And Dr("Serie").ToString() = "" Then OcurrioError = True ErrorList.Add("Se deben especificar las Series de los productos de almacén") Exit For End If If CveConceptoAlmacen = 3 AndAlso UsuarioActual.CveEmpresa.Contiene({72, 80, 119, 140}) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") AndAlso Dr("EntregaDirecta").ToString().ToEntero() < 1 Then Existencia = ObjInventario.GetExistenciasPS(CveProducto, CveUnidad, UsuarioActual.CveEmpresa, CveAlmacen, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveVendedor:=DdlVendedor.SelectedValue.ToEntero(), CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) If Existencia < Cantidad Then OcurrioError = True ErrorList.Add($"No cuenta con la cantidad suficiente en inventario del producto {Dr("CodigoPS")} .Cuenta con {Existencia.FormatoNumero(2)}.") Exit For End If End If If UsuarioActual.CveEmpresa = 1 Then DtEquivalencias = New DataTable DtEquivalencias = GlobalDTProductosServiciosEquivalencias(CveProducto, -1, UsuarioActual.CveEmpresa) Dim CveUnidadBase As Integer = DtEquivalencias.FiltroPrimeroValor("CveUM", "UnidadBase = 'True'").ToEntero() Dim drUMBase As DataRow = DtEquivalencias.FiltroPrimero("UnidadBase = 'True'") 'SI LA UNIDAD ACTUAL NO ES LA BASE SACA PROPORCION (EQUIVALENTE) If CveUnidadBase <> CveUnidad Then ' LO QUE PUSE LO QUE VALE UNIDAD BASE LO QUE VALE UNIDAD SELECCIONADA Cantidad = Dr("Cantidad").ToString().ToDouble * drUMBase("Cantidad").ToString().ToDouble / DtEquivalencias.FiltraParametros(String.Format("CveUM = {0}", CveUnidad)).Rows(0)("Cantidad").ToString().ToDouble CveUnidad = CveUnidadBase End If End If If CveProducto > 0 Then 'SI ES ENTRADA DEBE TENER EL COSTO DE LA SALIDA If CveConceptoAlmacen.Contiene(18) Then Dim DtExistencias As DataTable = Nothing If ObjInventario.GetInv_Mov(Me.CveVentaDevolucion, UsuarioActual.CveEmpresa) Then DtExistencias = ObjInventario.DtResultados.FiltraParametros($"CvePS Is Not NULL AND {Filtro}") End If PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString().ToEntero()}").ToString().ToDecimal If PU <= 0 Then ErrorList.Add("Ocurrió un error al obtener el costo.
    ") OcurrioError = True Exit For End If End If Dim CveSeccionAlmacen As Integer = -3 'If AplicaSeccion Then CveSeccionAlmacen = GlobalDTInvPSSeccionesAlmacen(UsuarioActual.CveEmpresa, CveAlmacen, CveProducto).FiltroPrimeroValor("CveSeccionAlmacen", "").ToEntero If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, Cantidad, CveUnidad, CveProducto, PU, -1, Serie:=Dr("Serie").ToString(), CveSeccionAlmacen:=CveSeccionAlmacen, CveVentaDetalle:=Dr("CveVentaDetalle").ToString().ToEntero()) Then OcurrioError = True ErrorList.Add("Ocurrió un error al agregar los Movimientos de salida al Inventario.
    ") Exit For End If Else OcurrioError = True ErrorList.Add("Ocurrió un error al agregar los Movimientos de salida al Inventario.
    ") Exit For End If End If PU = 0 i = i + 1 Next 'REGISTRO LA PREPOLIZA DE COSTO VS ALMACEN If Not OcurrioError Then Dim DtCostos As DataTable = Nothing Dim ValorInventario As Decimal = 0 Dim TotalCosto As Decimal = 0 Dim TipoMovto68 As Boolean = True Dim TipoMovto69 As Boolean = False If CveConceptoAlmacen.Contiene(18) Then TipoMovto68 = False TipoMovto69 = True End If If ObjInventario.GetMovimientosDetalle(CveMovimientoInventario, UsuarioActual.CveEmpresa) Then DtCostos = ObjInventario.DtResultados TotalCosto = DtCostos.SUMD("Total").RoundSQL Dim tmpCostos As DataTable = DtCostos.FiltraParametros("", "", {"CveClasificacion"}) Dim IdCtaContable As Integer = 0 Dim CveCuenta As Integer = 0 If tmpCostos.Rows.Count > 0 Then Dim TotalCostoAcumulado As Decimal = 0 Dim cont As Integer = 1 'Se agrega movimiento separado por la cuenta de ventas (ER) For Each RowInv As DataRow In tmpCostos.Rows ValorInventario = DtCostos.SUMD("Total", $"CveClasificacion = {RowInv("CveClasificacion")}").RoundSQL TotalCostoAcumulado += ValorInventario 'cuando es el último movimiento y hay diferencias en los importes If cont = tmpCostos.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) End If 'Concepto = String.Format("{0} - {1}", Row2("Clasificacion").ToString(), Row2("SubProyecto").ToString()) IdCtaContable = GlobalDTClasificaciones(factura.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() 'CveCuenta = GlobalDTClasificaciones(factura.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() 'If ValorInventario <> 0 Then If Not ObjConta.AddPrePolizasDetalle(factura.CvePrePoliza, TipoMovto69, ValorInventario, factura.SerieFolio, 69, factura.SerieFolio, factura.Fecha, IdCtaContable, -1, CveVenta:=factura.CveVenta, CveCliente:=factura.CveCliente, CveSubProyecto:=factura.CveSubProyecto, CveClasificacion:=RowInv("CveClasificacion").ToString().ToEntero(), CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta) Then OcurrioError = True End If 'End If cont += 1 Next End If IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacen)).ToEntero() 'If TotalCosto <> 0 Then If Not ObjConta.AddPrePolizasDetalle(factura.CvePrePoliza, TipoMovto68, TotalCosto, factura.SerieFolio, 68, factura.SerieFolio, factura.Fecha, IdCtaContable, -1, CveVenta:=factura.CveVenta, CveCliente:=factura.CveCliente, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=TotalCosto, CveCuenta:=CveCuenta, CveSubProyecto:=factura.CveSubProyecto) Then OcurrioError = True ErrorList.Add("Ocurrió un error al guardar movimiento de almacen.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If 'End If Else OcurrioError = True ErrorList.Add("Ocurrió un error al consultar los movimientos de almacen.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If factura.Inv_CveMovimiento = CveMovimientoInventario factura.Inv_ValorInventario = ValorInventario End If End If 'DEBE GENERAR MOVIMIENTO SI SE FACTURAON PRODUCTOS, O NO SE REALIZA UNA REFACTURACION Dim DebeGenerarMovimiento As Boolean = TmpDT.COUNT("CvePS", "CveTipoPS = 2") > 0 AndAlso (NuevaFactura <> 1) 'VERIFICA QUE SE REALIZO EL MOVIMIENTO DE ALMACEN If Not OcurrioError AndAlso DebeGenerarMovimiento AndAlso UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso UsuarioActual.Empresa.Funcionalidad(567) = "1" AndAlso factura.TipoDocto.Contiene("Ing", "Rem") Then If Not (ObjInventario.GetInv_Mov(factura.CveVenta, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0) Then OcurrioError = True ErrorList.Add("Ocurrió un error al verificar inventario.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If End If End If End If Catch ex As Exception OcurrioError = True OnError("Ocurrió un error al guardar el inventario", ex) End Try Return OcurrioError End Function Private Sub GuardarVentaEstimaciones(ObjContr As ClsContratos, factura As Modelos.Factura) Dim Str As New StringBuilder For Each gvr As GridViewRow In GvEst.Rows If gvr.FCCheckBox("Chk").Checked Then Str.AppendFormat("{0},", gvr.DataKey("CveContratoAvance")) End If Next 'debe de ser por contrato el movimiento If Str.Length > 0 Then If Not ObjContr.AddEstimaciones(CveContrato, factura.Fecha, -1, factura.CveVenta, Str.ToString(), factura.CveUsuario, factura.CveEmpresa) Then ErrorList.Add("Ocurrió un error al agregar la estimación a la Factura.
    Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If End If End Sub Private Sub GuardarVentaAC(ObjVentas As ClsVentas, factura As Modelos.Factura, Msgok As StringBuilder, ObjAC As ClsContPAQi) If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then If factura.TipoDocto.Contiene("Ing", "Egs", "OP", "Com") Then Dim IDPoliza As Modelos.RetornoPolizaConta = GenerarPolizaAC(ObjAC, factura) If IDPoliza.IdPoliza > 0 Then If ObjVentas.UpdateVentaPrePoliza(IDPoliza.IdPoliza, IDPoliza.FolioPoliza, factura.CvePrePoliza, factura.CveVenta, factura.CveEmpresa) Then 'Si se facturó la cotización hay que vincular la venta Msgok.AppendFormat("Abono Registrado Correctamente.

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

    ") End If End If End Sub Private Function GuardarVentaImpuestosLocales(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, Factura As Modelos.Factura, Optional ValorMultiplicador As Integer = 1) As Boolean Dim ErrorPrepoliza As Boolean = False If TmpDTImpuestos IsNot Nothing AndAlso Factura.CvePrePoliza > 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "Rem") Then Dim Importe As Decimal Dim IdCtaContable As Integer Dim Concepto As String Dim tipoCambio As Decimal Dim CveSubProyectoContabilizar = DdlSubProyectoDatos.SelectedValue.ToEntero() For Each RowIL As DataRow In TmpDTImpuestos.Rows If RowIL("TipoImpuesto").ToString().ToEntero() > 0 Then Importe = RowIL("Importe").ToString().ToDecimal * ValorMultiplicador IdCtaContable = RowIL("IdCtaContable").ToString().ToEntero() 'CveCuenta = -1 'RowIL("IdCtaContable").ToString().ToEntero() Concepto = ViewState("VentaFolio").ToString() If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then tipoCambio = Factura.TipoCambio ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then 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, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Case "3" If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 116, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Case "4" If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 58, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If Case "5" If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, True, Importe, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveSubProyecto:=CveSubProyectoContabilizar) Then ErrorPrepoliza = True End If End Select End If Next End If Return ErrorPrepoliza End Function 'Private Function generaNC(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, ByRef ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ByRef ObjBancos As ClsBancos, ByRef ObjEventos As ClsOIEventos) As List(Of Object) ' Dim Obj As New List(Of Object) ' Dim CveVentaNueva As Integer = ObjVentas.CveVenta ' Dim BanderaGeneraNC As Boolean = True ' 'If UsuarioActual.CveEmpresa.Contiene(1, 119) Then BanderaGeneraNC = True ' If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then ' If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then ' Dim drv As DataRow = ObjVentas.DtResultados.Rows(0) ' Dim TmpDTconceptos As DataTable = Nothing ' Dim CveNCaVincular As Integer = DdlNCFactura.SelectedValue.ToEntero() ' 'CargaCliente ' Dim CveCliente As Integer = drv("CveCliente").ToString().ToEntero() ' If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then ' Return Nothing ' ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then ' Return Nothing ' End If ' factura.TipoDocto = drv("TipoDocto").ToString() ' factura.Serie = drv("Serie").ToString() ' factura.FechaEjecucion = drv("FechaEjecucion").ToString().ToDateTime ' factura.Fecha = drv("Fecha").ToString().ToDateTime ' factura.CveSubProyectoEjecucion = drv("CveSubProyectoEjecucion").ToString().ToEntero() ' factura.CveSubProyectoCobranza = drv("CveSubProyectoCobranza").ToString().ToEntero() ' factura.CveClienteSucursal = drv("CveClienteSucursal").ToString().ToEntero() ' factura.CveSubProyecto = drv("CveSubProyecto").ToString().ToEntero() ' 'Carga Detalle Sucursal ' CargaClienteSucursal(drv("CveClienteSucursal").ToString().ToEntero(), ObjVentas) ' 'CargaDetalle ' If ObjVentas.GetVentaDetalle(CveVenta) Then ' TmpDTconceptos = ObjVentas.DtResultados ' TmpDTconceptos.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) ' GvPS.DataSource = TmpDTconceptos ' GvPS.DataBind() ' End If ' 'Carga Totales ' factura.SubTotal = drv("SubTotal").ToString().ToDecimal ' factura.Descuento = drv("Descuento").ToString().ToDecimal ' factura.Amortizacion = drv("Amortizacion").ToString().ToDecimal ' factura.IVA = drv("IVA").ToString().ToDecimal ' factura.RetIVA = drv("RetIVA").ToString().ToDecimal ' factura.RetISR = drv("RetISR").ToString().ToDecimal ' factura.Total = drv("Total").ToString().ToDecimal ' factura.MotivoDescuento = drv("MotivoDescuento").ToString() ' factura.Observaciones = drv("Observaciones").ToString() ' factura.CveMoneda = drv("CveMoneda").ToString().ToEntero() ' factura.TipoCambio = drv("TipoCambio").ToString().ToDecimal ' factura.CveVendedor = drv("CveVendedor").ToString().ToEntero() ' factura.RefDocto = drv("Ref").ToString() ' 'factura.SerieFolioPadre = drv("SerieFolio").ToString() ' HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString() ' ViewState("FolioFiscal") = drv("FolioFiscal").ToString() ' 'JJMQ 20160506: Se agrego para la validacion de pago de contado. ' 'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "") ' UpContado.Update() ' If factura.CveCliente > 0 Then ' If Not IsNothing(TmpDTconceptos) AndAlso TmpDTconceptos.Rows.Count > 0 Then ' If Not drv("Total").ToString().ToDecimal = factura.Total Then ' Return Nothing ' End If ' If FolioFiscal = "" Then ' CveEstatus = 4 ' Else ' CveEstatus = 5 ' End If ' '[IPP] - CANCELA INVENTARIO DE VENTA NUEVA Y NO TRASPASA MOVTOS DE ALMACEN ' 'If UsuarioActual.CveEmpresa.Contiene(1) Then ' 'QUEMA DOCUMENTO NUEVO ' If Not ObjInventario.ActualizarEsDevolucionVenta(CveVentaNueva, 2) Then ' Return Nothing ' End If ' 'Else ' ' 'TRASPASA ALMACEN A DOCUMENTO NUEVO ' ' If Not CancelarMovimientoInventario(ObjInventario, ObjConta, CveVentaNueva, CveDevolucion) Then ' ' Return Nothing ' ' End If ' 'End If ' 'CANCELA PAGOS ' If ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Ant") Then ' If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, ObjFactura.CvePrePoliza) Then ' Return Nothing ' End If ' End If ' 'CANCELA FACTURA ' BanderaGeneraNC = True ' '2019.05.10- RMF. se activa la bandera a true, para que siempre se cancele, y no genere la NC ' If Month(factura.Fecha) = Month(Now) OrElse BanderaGeneraNC = True Then ' If CancelarFactura(ObjVentas, ObjConta, ObjContPaq, ObjBancos) Then ' Obj.Add(factura) ' Else ' Return Nothing ' End If ' Else ' ObjFacturaDevolucion.TipoDocto = "Egs" ' ObjFacturaDevolucion.Fecha = Now ' If RegistrarNC(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, TmpDTconceptos, ObjEventos) Then ' Obj.Add(ObjFacturaDevolucion) ' Else ' Return Nothing ' End If ' End If ' 'TRASPASA PAGADO ' If Not ObjConta.TraspasarSaldosPrePolizas(CveDevolucion, ObjFactura.CveVenta, ObjFactura.CvePrePoliza) Then ' Return Nothing ' End If ' If Not ObjInventario.TraspasaEntregaDirectaOCInv(ObjFactura.CveVenta, UsuarioActual.CveEmpresa) Then ' Return Nothing ' End If ' End If ' End If ' End If ' End If ' If Obj.Count > 0 Then ' Return Obj ' Else ' Return Nothing ' End If 'End Function 'Private Function RegistrarNC(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean ' Dim ProcesoCorrecto As Boolean = True ' RefacturacionGeneroNC = True ' ''Generamos el nuevo folio ' 'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL()) ' 'If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then ' ' Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue)) ' ' If DT.Rows.Count > 0 Then ' ' factura.Folio = DT.Rows(0)("FActual").ToString().ToEntero() ' ' Else ' ' ProcesoCorrecto = False ' ' End If ' ' DT.Dispose() ' 'End If ' factura.Folio = -1 ' 'Registramos la venta ' GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, TmpDTconceptos, -1, ObjContPaq, ObjBancos) ' 'CargaNCDT(factura.CveVentaPadre, factura.Total) ' 'ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion) ' ''Timbramos ' 'If factura.TipoDocto.Contiene("Ing", "Egs", "Ant") AndAlso FolioFiscal <> "" Then ' ' If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then ' ' Dim sw As New Diagnostics.Stopwatch ' ' sw.Start() ' ' 'FACTURA INGRESO/EGRESO ' ' Dim ObjTimbrado As New Modelos.Timbrado ' ' Dim FM As New Modelos.FemsaFactura ' ' Dim TmpDT7Eleven As New DataTable ' ' Dim TmpDTComplementosTimbrado As New DataTable ' ' PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado) ' ' ObjTimbrado.TimbrarFactura(UsuarioActual, factura, FM, TmpDT, TmpDTImpuestos, TmpDT7Eleven, TmpDTComplementosTimbrado, Ruta, LstFordASN, TxtFordGSDB.Text, ObjVentas) ' ' sw.Stop() ' ' GuardaLogTimbrado(sw.ElapsedMilliseconds.ToString(), UsuarioActual.Empresa.CvePAC) ' ' ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then ' ' GeneraPDFCBB(ObjFactura.Fecha, Nothing, ObjFactura.SerieFolio, False) ' ' End If ' 'End If ' If ErrorList.Count > 0 Then ' ProcesoCorrecto = False ' End If ' Return ProcesoCorrecto 'End 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) '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 = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) 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) 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) Dim pdf As Byte() = Nothing 'GUARDA PDF Dim LocalSerieFolio As String = String.Empty Dim LocalTipoDocto As String = String.Empty 'TIMBRADO NUEVO Try If CveVenta > 0 Then ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=False) End If pdf = PdfFactura(ObjFactura) Catch ex As Exception OnError("Ocurrió un error al generar el PDF", ex) End Try LocalSerieFolio = ObjFactura.SerieFolio LocalTipoDocto = ObjFactura.TipoDocto 'MANDA CORREO If EnviaCorreo Then Dim ArchivoAdjunto As String = "" Dim ArchivoXML = "" Dim ArchivoPDF = 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, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF, ArchivoAdjunto)) Hilo.Start() Catch ex As Exception OnError("Ocurrió error al mandar Mail", ex) Dim ObjVentas As New ClsVentas If ChkEnviarFactura.Checked Then ObjVentas.UpdateVentaMail(3, CveVenta) Else ObjVentas.UpdateVentaMail(0, CveVenta) End If ObjVentas.Dispose() End Try End If End Sub Private Sub EnviaPDFRemision(EnviaCorreo As Boolean) 'MANDA CORREO If EnviaCorreo Then 'GUARDA PDF Dim pdf As Byte() = Nothing Dim LocalSerieFolio As String = String.Empty Dim LocalTipoDocto As String = String.Empty 'TIMBRADO NUEVO Try pdf = PdfFactura(ObjFactura, AplicaPagare:="1") Catch ex As Exception Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError) End Try If CveVenta > 0 Then ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=False, CargaDTDetalle:=False, CargaDatosCliente:=False, CargaDatosRelacionados:=False) End If LocalSerieFolio = ObjFactura.SerieFolio LocalTipoDocto = ObjFactura.TipoDocto Dim ArchivoAdjunto As String = "" Dim ArchivoXML = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) 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, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF, ArchivoAdjunto)) Hilo.Start() Catch ex As Exception OnError("Ocurrió error al mandar Mail", ex) Dim ObjVentas As New ClsVentas If ChkEnviarFactura.Checked Then ObjVentas.UpdateVentaMail(3, CveVenta) Else ObjVentas.UpdateVentaMail(0, CveVenta) End If ObjVentas.Dispose() End Try End If End Sub #End Region #Region " ANTICIPOS " Private Sub CargaAnticipos(CveCliente As Integer) HdnTieneAnticipos.Value = "0" If CveCliente > 0 Then HdnIVACalculado.Value = "0" 'SI ES REFACTURACION NO LIMPIAR EL FOLIO FISCAL If NuevaFactura <> 1 Then HdnFolioFiscalNC.Value = "0" End If LblAntAplicados.Text = "" LblAntAplicados.Visible = False LblAmortizacion.Text = "0.00" HdnTipoDescuento.Value = "-1" HdnTieneAnticiposVinculados.Value = "0" Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente) Then Dim DtMovtos = ObjMovtos.DtResultados.FiltraParametros($"Saldo > 0 AND SaldoSubtotal > 0 {If(CveVenta < 0, $"AND Tipo = 'Ant' ", "")} {If(DdlTipoComprobante.SelectedValue = "Ant", "AND Tipo = 'NC'", "")}") If UsuarioActual.CveEmpresa.Contiene(72, 80, 146) Then DtMovtos = DtMovtos.FiltraParametros($"{If(CveVenta < 0, $"Tipo = 'Ant'{If(DdlTipoComprobante.SelectedValue = "Ing", $" AND CveMoneda ={DdlMoneda.SelectedValue.ToEntero()}", "")} ", "")}") End If GVAnticipos.DataSource = DtMovtos If ObjMovtos.DtResultados.SUM("Saldo", "Saldo > 0 AND SaldoSubtotal > 0 AND Tipo = 'Ant'") > 0 Then HdnTieneAnticipos.Value = "1" End If Else GVAnticipos.DataSource = Nothing End If ObjMovtos.Dispose() If CveVenta <= 0 OrElse (EsCreaApartirDe Or CveDevolucion > 0) Then divAmortizacionTipo.Visible = True divAmortizacionTipoRelacion.Visible = True End If If UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 146) Then If Not DdlTipoAmortizacionAnticipo.Items.Cast(Of ListItem).Any(Function(x) x.Value = "3") Then DdlTipoAmortizacionAnticipo.Items.Add(New ListItem("Amortización anticipo sobre factura en cero", "3")) End If End If If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1")) End If GVAnticipos.Columns(4).Visible = False GVAnticipos.Columns(7).Visible = False GVAnticipos.DataBind() End If UpAnticipos.Update() End Sub Protected Sub GVAnticipos_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowCreated If e.Row.RowType = DataControlRowType.Header Then e.Row.ClientIDMode = ClientIDMode.Static e.Row.ID = String.Format("TrH{0}", e.Row.RowIndex) ElseIf e.Row.RowType = DataControlRowType.DataRow Then e.Row.ClientIDMode = ClientIDMode.Static e.Row.ID = String.Format("Tr{0}", e.Row.RowIndex) e.Row.FCCheckBox("Chk").ID = "Chk" & e.Row.RowIndex e.Row.FCTextBox("TxtAnticipo").ID = "TxtAnticipo" & e.Row.RowIndex e.Row.FCTextBox("TxtTC").ID = "TxtTC" & e.Row.RowIndex DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ID = "CVAmortAnti" & e.Row.RowIndex DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).ID = "VCOAmortAnti" & e.Row.RowIndex DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ControlToValidate = "TxtAnticipo" & e.Row.RowIndex DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).TargetControlID = "CVAmortAnti" & e.Row.RowIndex End If End Sub Protected Sub GVAnticipos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex = 0 Then e.Row.Cells(1).Width = Unit.Pixel(60) e.Row.Cells(2).Width = Unit.Pixel(100) e.Row.Cells(3).Width = Unit.Pixel(80) e.Row.Cells(4).Width = Unit.Pixel(80) End If e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right If e.Row.DataKey("Saldo").ToDouble < 0 Then e.Row.Cells(3).ForeColor = Drawing.Color.Red If e.Row.DataKey("Saldo").ToDouble = 0 Then e.Row.FCLiteral("LtlAnticipos").Text = "" Dim saldo As Decimal = 0 Dim tipoCambio As Decimal = 0 Dim total As Decimal = TxtTotal.Text.ToString().ToDecimal If CveVentaRelacion > 0 Then ' dejo seleccionado el la venta relacionado en anticipo If e.Row.DataKey("CveVenta").ToEntero() = CveVentaRelacion Then e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Checked = True e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Text = ImporteRelacion.ToString() End If End If If e.Row.DBCampo("Tipo").ToString() = "NC" And e.Row.DataKey("CveVenta").ToString().ToEntero() > 0 OrElse (e.Row.DBCampo("Tipo").ToString() = "Ant" And e.Row.DataKey("CveMoneda").ToString().ToEntero() = 1 AndAlso DdlMoneda.SelectedValue.ToEntero() = 2) Then 'If e.Row.DBCampo("CveMoneda").ToString().ToEntero() = 2 Then ' tipoCambio = e.Row.DBCampo("TipoCambioHoy").ToString().ToDecimal 'Else ' tipoCambio = GlobalTipoCambio(e.Row.DataKey("Fecha").ToString().ToDate).ToDecimal 'End If tipoCambio = e.Row.DBCampo("TipoCambioHoy").ToString().ToDecimal e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Text = tipoCambio.FormatoNumero(4) If DdlMoneda.SelectedValue.ToEntero() = 1 And e.Row.DBCampo("CveMoneda").ToString().ToEntero() = 1 Then saldo = e.Row.DataKey("Saldo").ToDecimal ElseIf DdlMoneda.SelectedValue.ToEntero() = 2 And e.Row.DBCampo("CveMoneda").ToString().ToEntero() = 1 And tipoCambio > 0 Then saldo = (e.Row.DataKey("Saldo").ToString().ToDecimal / tipoCambio) ElseIf DdlMoneda.SelectedValue.ToEntero() = 1 And e.Row.DBCampo("CveMoneda").ToString().ToEntero() = 2 Then saldo = (e.Row.DataKey("Saldo").ToString().ToDecimal * tipoCambio) Else saldo = e.Row.DataKey("Saldo").ToDecimal End If Else saldo = e.Row.DataKey("Saldo").ToString().ToDecimal If CveVenta <= 0 Then If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then 'cuando es por NC, debe de tomar el total de su saldo respectivo saldo = e.Row.DataKey("SaldoConImpuestos").ToString().ToDecimal Else saldo = e.Row.DataKey("SaldoSubTotal").ToString().ToDecimal End If e.Row.FCLiteral("LtlAnticipos").Text = saldo.FormatoNumero ElseIf CveVenta > 0 AndAlso e.Row.DBCampo("Tipo").ToString() = "Ant" Then saldo = e.Row.DataKey("SaldoConImpuestos").ToString().ToDecimal e.Row.FCLiteral("LtlAnticipos").Text = saldo.FormatoNumero End If End If saldo = saldo.RoundSQL() Dim maxsaldo As Decimal If total > saldo Then maxsaldo = saldo Else maxsaldo = total End If If DdlContratosModal.SelectedValue.ToEntero > 0 AndAlso AmortizacionSujeridaContrato > 0 Then If AmortizacionSujeridaContrato > saldo Then AmortizacionSujeridaContrato = saldo End If End If e.Row.FCLiteral("MonedaVenta").Text = saldo.FormatoNumero(2) e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Attributes.Add("onclick", String.Format("chkAnt(this,{0},{1},{2});", e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, saldo, AmortizacionSujeridaContrato)) e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, saldo)) e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("CambioTipoMoneda({0},{1},{2},{3},{4});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, e.Row.DataKey("Saldo"), e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).ClientID, e.Row.DataKey("CveMoneda"))) If e.Row.DataKey("CveIE").ToString().ToEntero() > 0 Then e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveIE"), e.Row.DataKey("Folio")) Else e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveVenta"), e.Row.DataKey("Folio")) End If If e.Row.DataKey("ISTotal") = "1" Then e.Row.Cells(0).Visible = False e.Row.Cells(1).ColumnSpan = 3 e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Right e.Row.FCLiteral("LtlFactura").Text = String.Format("Total {0} ", e.Row.DataKey("Tipo")) e.Row.BackColor = Drawing.Color.LightGray e.Row.Cells(2).Visible = False e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Visible = False e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False e.Row.FCLabel("LblTotalAnticipos").Visible = True e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right End If 'SI UN REGISTRO ES DE DIFERENTE MONEDA AL DOCUMENTO SE MUESTRAN LAS COLUMNAS If e.Row.DBCampo("CveMoneda").ToString().ToEntero() > 0 And e.Row.DBCampo("CveMoneda").ToString().ToEntero() <> DdlMoneda.SelectedValue.ToEntero() Then GVAnticipos.Columns(4).Visible = True GVAnticipos.Columns(7).Visible = True End If If e.Row.DBCampo("CveMoneda").ToString().ToEntero() = DdlMoneda.SelectedValue.ToEntero() Then e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False End If End If End Sub Protected Sub BtnAceptarAnticipos_Click(sender As Object, e As System.EventArgs) Handles BtnAceptarAnticipos.Click AplicaAnticipos() End Sub Private Sub AplicaAnticipos() If CveVenta > 0 And CveCliente > 0 And Not EsCreaApartirDe And CveDevolucion <= 0 Then Dim EsAnticipo2017Jam As Boolean = False For Each gvr As GridViewRow In GVAnticipos.Rows If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then If gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal > SaldoVenta Then Alert("No puede ingresar un importe mayor al saldo", TipoMensaje.MsgAdvertencia) Exit Sub ElseIf UsuarioActual.CveEmpresa = 119 AndAlso gvr.DataKey("Tipo").ToString() = "NC" AndAlso gvr.DataKey("Fecha").ToDate.Year <= 2017 Then EsAnticipo2017Jam = True End If End If Next Dim ObjConta As New ClsContabilidad Dim ObjVenta As New ClsVentas(ObjConta.IniciaTransacSQL()) Dim ObjIE As New ClsBancos(ObjConta.IniciaTransacSQL()) Dim ObjCliente As New ClsClientes(ObjConta.IniciaTransacSQL()) Dim ObjContpaq As ClsContPAQi = Nothing Dim CvePrePoliza As Integer Dim ErrorConta As Boolean Dim CveIEAnticipo As Integer Dim CvePlantillaPoliza As Integer = 10 'Dim PorcentajeAmortizacion As Decimal 'Dim sumaAmorticaciones As Decimal = 0 'Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " 'Dim CveCuentaContabilizacion As Integer = 1 Dim CuentasContablesInvalidas As New StringBuilder Dim ContaIdPoliza As Integer = 0 'Dim ConceptoAmortizacion As Integer = 0 'Dim UsaComplementariaClientes As Boolean = True Dim SimplificaPrePoliza As Boolean = True ''[IPP] PARCHE TEMPORAL PARA ANTICIPOS DE JAM 'If FechaMaxima < "01/01/2018".ToDate And UsuarioActual.CveEmpresa = 119 Then ' FechaMaxima = "01/01/2018".ToDate 'End If 'Dim Now As DateTime = New DateTime(2020, 2, 19) Try CvePrePoliza = ObjConta.AddPrePolizas("Ventas/Anticipos", CvePlantillaPoliza, TxtTotal.Text.ToDecimal, TxtTotal.Text.ToDecimal, DdlMoneda.SelectedValue.ToEntero(), TxtFechaAnticipoCliente.Text.ToDate, String.Format("{0} {1} {2}-{3}", If(EsAnticipo2017Jam, "Aplicación Anticipo 2017", ""), NombreCliente, Serie, TxtFolio.Text), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) If CvePrePoliza > 0 Then Dim tipoCambioPago As Decimal = 1 Dim tipoCambioVenta As Decimal = 1 Dim tipoCambioVentaValuacion As Decimal = 1 Dim PorcentajePago As Decimal = 100 Dim dtConceptos As DataTable = Nothing Dim CveMonedaVenta = DdlMoneda.SelectedValue.ToEntero() If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPoliza) Then dtConceptos = ObjConta.DtResultados End If Dim PorcentajeImpuestoAmortizacion As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal Dim IdCtaIVAXTrasladar As Integer = 0 Dim IdCtaIVATrasladado As Integer = 0 Dim CveSubProyectoVenta As Integer = DdlSubProyectoDatos.SelectedValue.ToEntero() Dim Importe91 As Decimal = 0 For Each gvr As GridViewRow In GVAnticipos.Rows If gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then Dim FechaUltimaFluctuacion As Date = MinFecha Dim TipoCambioFluctuacion As Decimal = 1 Dim tFecha As Date = Now Dim UltimaFluctuacion As MTipoCambioFluctuacion = GlobalTipoCambioUltimaFluctuacion(tFecha) If UsuarioActual.Empresa.Funcionalidad(703) = "1" AndAlso UltimaFluctuacion IsNot Nothing Then If UltimaFluctuacion.FechaFluctuacion <= tFecha Then FechaUltimaFluctuacion = UltimaFluctuacion.FechaFluctuacion TipoCambioFluctuacion = UltimaFluctuacion.TCFluctuacion End If End If If DdlMoneda.SelectedValue.ToEntero() = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero() = 1 Then 'SI LA VENTA VIENE EN PESOS Y SE VA A PAGAR EN PESOS tipoCambioPago = 1 tipoCambioVenta = 1 tipoCambioVentaValuacion = 1 PorcentajePago = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal ElseIf DdlMoneda.SelectedValue.ToEntero() = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero() = 1 Then 'SI LA VENTA VIENE EN DOLARES Y SE VA A PAGAR EN PESOS tipoCambioPago = gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal tipoCambioVenta = TxtTipoCambio.Text.ToDecimal tipoCambioVentaValuacion = If(TxtFecha.Text.ToDate < FechaUltimaFluctuacion, TipoCambioFluctuacion, TxtTipoCambio.Text.ToDecimal) PorcentajePago = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal) / gvr.DataKey("Original").ToDecimal ElseIf DdlMoneda.SelectedValue.ToEntero() = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero() = 2 Then 'SI LA VENTA VIENE EN DOLARES Y SE VA A PAGAR EN DOLARES tipoCambioPago = gvr.DataKey("TipoCambio").ToString().ToDecimal tipoCambioVenta = TxtTipoCambio.Text.ToDecimal tipoCambioVentaValuacion = If(TxtFecha.Text.ToDate < FechaUltimaFluctuacion, TipoCambioFluctuacion, TxtTipoCambio.Text.ToDecimal) PorcentajePago = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal ElseIf DdlMoneda.SelectedValue.ToEntero() = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero() = 2 Then 'SI LA VENTA VIENE EN PESOS Y SE VA A PAGAR EN DOLARES tipoCambioPago = gvr.DataKey("TipoCambioHoy").ToDecimal() ' gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal tipoCambioVenta = 1 tipoCambioVentaValuacion = If(TxtFecha.Text.ToDate < FechaUltimaFluctuacion, TipoCambioFluctuacion, TxtTipoCambio.Text.ToDecimal) PorcentajePago = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal) / gvr.DataKey("Original").ToDecimal End If Dim importeMovimiento As Decimal = 0 Dim importeMN As Decimal = 0 Dim TC As Decimal Dim IdCtaContable As Integer Dim TipoMovimiento As Boolean = True Dim Concepto As String = VentaActual.SerieFolio Dim Referencia As String = VentaActual.SerieFolio CveIEAnticipo = gvr.DataKey("CveIE").ToEntero() Select Case gvr.DataKey("CveConceptoContable").ToString() Case "3" importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) If importeMovimiento <> 0 Then Dim Pago As New VentaPago Pago.ImportePagoVenta = importeMovimiento Pago.ImportePago = importeMovimiento Pago.CveIE = CveIEAnticipo Pago.CveMonedaPago = gvr.DataKey("CveMoneda").ToEntero() Pago.TipoPago = "A" Pago.CveVentaAmortizacion = gvr.DataKey("CveVenta").ToEntero() Pago.AplicaTraslado = gvr.DataKey("RegresarImpuesto") = "1" Pago.Referencia = gvr.DataKey("Folio") ErrorConta = AplicaPrePolizaPagoVenta(VentaActual, Pago, CvePrePoliza, ObjConta) End If Case "12" If CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToEntero = 1 Then importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal ElsermatveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToEntero = 2 Then importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal ElseIf CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToEntero = 2 Then importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal ElseIf CveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToEntero = 1 Then importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal End If importeMovimiento = importeMovimiento.RoundSQL If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso ObjConta.GetRetCuenta(12, CveCliente) Then If ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString().ToEntero() End If End If If importeMovimiento <> 0 Then Dim Pago As New VentaPago Pago.Fecha = TxtFechaAnticipoCliente.Text.ToDate Pago.FechaDocumentoRelacionado = gvr.DataKey("Fecha").ToDate Pago.ImportePagoVenta = importeMovimiento Pago.ImportePago = importeMovimiento Pago.CveIE = CveIEAnticipo Pago.CveMonedaPago = gvr.DataKey("CveMoneda").ToEntero() Pago.TCPago = gvr.DataKey("TipoCambio").ToDecimal Pago.TipoPago = "NC" Pago.CveVentaAmortizacion = gvr.DataKey("CveVenta").ToEntero() Pago.AplicaTraslado = gvr.DataKey("RegresarImpuesto") = "1" Pago.Referencia = gvr.DataKey("Folio") Pago.CveConceptoPago = 251 ErrorConta = AplicaPrePolizaPagoVenta(VentaActual, Pago, CvePrePoliza, ObjConta) SimplificaPrePoliza = False End If Case "66" If gvr.DataKey("CveIE").ToEntero() > 0 Then importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal IdCtaContable = IdCtaContClientes If importeMovimiento <> 0 Then Dim Pago As New VentaPago Pago.ImportePago = importeMovimiento Pago.CveIE = CveIEAnticipo Pago.CveMonedaPago = gvr.DataKey("CveMoneda").ToEntero() Pago.TipoPago = "A" Pago.CveVentaAmortizacion = gvr.DataKey("CveVenta").ToEntero() Pago.AplicaTraslado = gvr.DataKey("RegresarImpuesto") = "1" Pago.Referencia = gvr.DataKey("Folio") ErrorConta = AplicaPrePolizaPagoVenta(VentaActual, Pago, CvePrePoliza, ObjConta) ' Agregamos el 2 If tipoCambioPago = 1 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, Now, IdCtaContClientes, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento, CveSubProyecto:=CveSubProyectoVenta) Then ErrorConta = True End If Else 'Cuando son dolares If importeMovimiento <> 0 Then If IdCtaContComplementaria > 0 Or 0 > 0 Then 'Agregamos la Complementaria If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, 0, Concepto, 207, Concepto, Now, IdCtaContComplementaria, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta, CveSubProyecto:=CveSubProyectoVenta) Then ErrorConta = True End If 'Agregamos la Extranjera If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, Now, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta, CveSubProyecto:=CveSubProyectoVenta) Then ErrorConta = True End If Else 'Agregamos la Extranjera If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, Now, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta, CveSubProyecto:=CveSubProyectoVenta) Then ErrorConta = True End If End If End If End If importeMovimiento = ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / TxtTotal.Text.ToDecimal) * TxtIVA.Text.ToDecimal) importeMN = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) 'Agregamos el 92 importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal 'gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo" & gvr.RowIndex).ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal) importeMN = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero) IdCtaContable = IdCtaContAnticipos If ObjCliente.GetClientes(gvr.DataKey("CveCliente").ToEntero(), "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa) Then If ObjCliente.DtResultados.Rows.Count > 0 Then If Not tipoCambioPago = 1 Then IdCtaContable = ObjCliente.IdCtaMonedaExtranjeraAnticipos Else IdCtaContable = ObjCliente.IdCtaContAnticipos End If End If End If If UsuarioActual.CveEmpresa.Contiene(119) Then If gvr.DataKey("Fecha").ToDate.Year <= 2017 AndAlso TxtFechaAnticipoCliente.Text.ToDate.Year >= 2018 Then If ObjCliente.DtResultados.Rows.Count > 0 Then If Not tipoCambioPago = 1 Then IdCtaContable = ObjCliente.IdCtaContMonedaExtranjera Else IdCtaContable = ObjCliente.IdCtaContClientes End If End If End If End If If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Concepto, 555, Concepto, Now, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMN, CveCuenta:=-1, TipoCambio:=tipoCambioPago, CveSubProyecto:=CveSubProyectoVenta) Then ErrorConta = True End If End If End If End Select End If Next Else ErrorConta = True End If If Not ErrorConta AndAlso SimplificaPrePoliza AndAlso Not ObjConta.PrePolizaSimplificacion(CvePrePoliza, UsuarioActual.CveEmpresa) Then Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError) End If If ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 3) Then If ObjConta.ValorPolizaDescuadre > 0 Then GuardaLogAD($"Ventas/Ventas-Anticipos | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas") ErrorConta = True End If End If Catch ex As Exception ErrorConta = True OnError("Ocurrió un error al guardar el anticipo", ex) End Try If ErrorConta Then Alert("Ocurrió un error al amortizar el documento. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError) ObjConta.RollBack() If ObjContpaq IsNot Nothing Then ObjContpaq.RollBack() Else Dim Msg As New StringBuilder Msg.Append("Se ha amortizado correctamente") 'AJUSTA POLIZA If ContaIdPoliza > 0 Then Msg.AppendFormat("

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

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

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

    ", ofa.TipoDocumento, ofa.SerieFolio)) End If End If End If End If 'NOTIFICACION DE SMS Dim EstatusSMS = 0 If ObjFactura.TipoDocto = "Ing" Then Dim ObjEventos As New ClsOIEventos EnviarSMSTimbrado(ObjEventos) ObjEventos.Dispose() End If Select Case EstatusSMS Case 1 MensajeAlert.AppendFormat("Notificación SMS: enviado con éxito al cliente al celular: {0}", ObjFactura.Cliente.CobranzaTelefono) Case 2 MensajeAlert.AppendFormat("Notificación SMS: sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.") Case 3 MensajeAlert.AppendFormat("Notificación SMS: sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.") End Select 'MUESTA Alert OK 'MensajeAlert.Append("El Documento se generó correctamente") Dim Liga = If(UsuarioActual.CveRol = 1165, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}&Opt=2"";") Alert(MensajeAlert.ToString(), TipoMensaje.MsgInformacion, Liga) TrEmitir.Visible = False Else Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgError) End If Else Me.OnError("El SAT regresó el siguiente mensaje: Crédito insuficiente.", New Exception) End If ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then End If End Sub #End Region #Region " DESCUENTOS " Protected Sub BtnAplicarDescG_Click(sender As Object, e As System.EventArgs) Handles BtnAplicarDescG.Click If HdnTipoDescuento.Value = "2" Then If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2) Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString().ToDouble If IVAPromedio <> IVA Then Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError) Else 'Dim Descuento As Double = HdnDescuento.Value.Trim.Replace(",", "").ToDouble CalculaTotalesVenta() 'LblDescuentos.Text = Descuento.FormatoNumero(2) 'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Descuento - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2) 'HdnIVAOriginal.Value = TxtIVA.Text 'CalculaTotales(True) HdnTipoDescuento.Value = "-1" HdnDescuento.Value = "0" RegistraScript("BorraDescuentos();") End If End If ElseIf HdnTipoDescuento.Value = "3" Then If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2) Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString().ToDouble If IVAPromedio <> IVA Then Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError) Else 'Dim Amortizacion As Decimal = HdnDescuento.Value.Trim.Replace(",", "").ToDecimal 'LblAmortizacion.Text = Amortizacion.FormatoNumero(2) 'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Amortizacion - LblDescuentos.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2) 'HdnIVAOriginal.Value = TxtIVA.Text 'CalculaTotales(True) CalculaTotalesVenta() HdnTipoDescuento.Value = "-1" HdnDescuento.Value = "0" RegistraScript("BorraDescuentos();") HdnTieneAnticiposVinculados.Value = "1" End If End If End If RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal") UpPS.Update() End Sub Private Sub BtnAplicarOtrosConceptos_Click(sender As Object, e As EventArgs) Handles BtnAplicarOtrosConceptos.Click TotalOtrosConceptos = 0 For Each row As GridViewRow In GVOtrosConceptos.Rows TotalOtrosConceptos += row.FCTextBox("TxtCantidadConcepto").Text.ToDecimal Next RegistraScript("$('#ModalOtrosConceptos').modal('hide')", "hidemodal") End Sub 'Private Sub BtnAplicarComplementos_Click(sender As Object, e As EventArgs) Handles AplicarComplementosTimbrado.Click ' LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs green" ' UpPS.Update() ' RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal") 'End Sub 'Private Sub BtnCancelarComplementos_Click(sender As Object, e As EventArgs) Handles CancelarComplementosTimbrado.Click ' trEntidad.Visible = False ' trContaComplementos.Visible = False ' trAmbito.Visible = False ' trTipoCampaña.Visible = False ' RblComplementos.SelectedIndex = -1 ' TxtIdConta.Text = "" ' DdlTipoCampaña.SelectedIndex = -1 ' DdlAmbitoComplemento.SelectedIndex = -1 ' DdlINEEntidad.SelectedIndex = -1 ' LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs gray" ' UpComplementos.Update() ' UpDatosComplementos.Update() ' UpPS.Update() ' RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal") 'End Sub '2019-07-31 OSCAR Nuevo cancela usando el metodo de cancelacion de facturas Protected Sub LnkCancelarComplemetno_Click(sender As Object, e As EventArgs) Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).BindingContainer, GridViewRow) Dim ObjCancelacion As New Timbrado Dim ObjBanco As New ClsBancos Dim CveComplementoPago As Integer = GvRow.DataKey("CveComplementoPago").ToEntero() Dim FolioFiscal As String = GvRow.DataKey("FolioFiscal").ToString() Dim RFCEmisor As String = UsuarioActual.Empresa.RFC Dim RFCReceptor As String = GvRow.DataKey("RFCReceptor") Dim CvePACCancelacion As Integer = GvRow.DataKey("CvePAC").ToEntero() Dim RespCancelacion = ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, 0, RFCReceptor, RFCEmisor, CvePACCancelacion) If RespCancelacion.Verificado Then If ObjBanco.UpdateComplementoPagoCancelado(CveComplementoPago, 2, CvePACCancelacion, UsuarioActual.CveEmpresa, ObjCancelacion.CancelacionFecha, ObjCancelacion.CancelacionAcuse, 1) Then CargaComplementosPago() Alert("El complemento se canceló correctamente.") End If Else Alert("Los servicios de cancelación del SAT no se encuentran disponibles o presentan time out. Intente de nuevo en unos minutos.
    Origen del error: WebService www.sat.gob.mx", TipoMensaje.MsgError) End If ObjBanco.Dispose() End Sub #End Region #Region " VISTA PREVIA " Protected Sub BtnVistaPrevia_Click(sender As Object, e As System.EventArgs) Handles BtnVistaPrevia.Click VistaPreviaNew() End Sub #End Region #Region "I M A G E - B U T T O N S" Protected Function CancelarFactura(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjAC As ClsContPAQi, ByRef ObjBancos As ClsBancos) As Boolean Dim IDPoliza As Integer = -1 Dim CvePrePoliza As Integer Dim CvePlantillaPoliza As Integer Dim ErrorCancelar As Boolean = False Dim Mensaje As String = "" Try ObjFacturaDevolucion.TipoDocto = ObjFactura.TipoDocto If ObjFacturaDevolucion.TipoDocto.Contiene("Egs", "Dev") Then CvePlantillaPoliza = 7 ElseIf ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem", "Ant") Then CvePlantillaPoliza = 4 End If CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero(), Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) ObjFacturaDevolucion.CveVenta = CveVenta ObjFacturaDevolucion.CvePrePoliza = CvePrePoliza If NuevaFactura = 1 AndAlso UsuarioActual.TienePermisoProceso(222) Then If ObjVentas.GetVentaDetalle(ObjFacturaDevolucion.CveVenta) Then TmpDT = ObjVentas.DtResultados TmpDT.Columns.Add("CveVentaDetalleRNC", GetType(Integer)) TmpDT.Columns.Add("TieneProntoPago", GetType(String)) TmpDT.Columns.Add("ImporteProntoPago", GetType(Decimal)) End If ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) Else ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) End If If Not ErrorCancelar Then ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFacturaDevolucion, -1) End If If CveEstatus = 4 Then If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then Mensaje = "El nuevo estatus se guardó correctamente" Else ErrorCancelar = True End If 'Si se está mandando a Cancelada SAT ElseIf CveEstatus = 5 Then Dim DT As DataTable = Nothing If FolioFiscal = "" Then Dim XmlDoc As New XmlDocument XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml") ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText End If Dim ObjCancelacion As New Timbrado Dim Total As Decimal = TxtTotal.Text.ToDecimal Dim RFCReceptor As String = HdnRFCVenta.Value If Not ObjVentas.UpdateEstatusFactura(13, FolioFiscal, "", Now, CveVenta, IDPoliza) Then 'Marcamos la factura como refacturada, si no se cancelo en el SAT el estatus nos dejara cancelarla despues ErrorCancelar = True End If Dim RespCancelacion = ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, Total, RFCReceptor, UsuarioActual.Empresa.RFC) If RespCancelacion.Verificado Then 'falta verificar traer el acuse y reenviarlo If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then Dim IDMPoliza As Modelos.RetornoPolizaConta = GenerarPolizaAC(ObjAC, ObjFacturaDevolucion, True) IDPoliza = IDMPoliza.IdPoliza If IDMPoliza.IdPoliza <= 0 Then Mensaje = "No se pudo generar la poliza" ErrorCancelar = True End If End If If Not ErrorCancelar Then If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, ObjCancelacion.CancelacionAcuse, Now, CveVenta, IDPoliza, CvePAC:=UsuarioActual.Empresa.CvePAC) Then Mensaje = "El nuevo estatus se guardó correctamente" Else ErrorCancelar = True End If End If Else ErrorCancelar = True End If ObjCancelacion = Nothing End If Catch ex As Exception GuardaLog("CancelF." & ex.ToString()) ErrorCancelar = True End Try Return Not ErrorCancelar End Function Protected Function CancelarFactura2(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjAC As ClsContPAQi, ObjBancos As ClsBancos) As Boolean Dim IDPoliza As Integer = -1 Dim CvePrePoliza As Integer Dim CvePlantillaPoliza As Integer Dim ErrorCancelar As Boolean = False Dim Mensaje As String = "" CreaObjetosVenta() If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then CvePlantillaPoliza = 7 ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem") Then CvePlantillaPoliza = 4 End If CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero(), Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) ObjFactura.CveVenta = CveVenta ObjFactura.CvePrePoliza = CvePrePoliza If HplSaldoAuxiliar.Text.ToDecimal > 0 Then ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas) End If If Not ErrorCancelar Then ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, -1) End If If CveEstatus = 4 Then If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then Mensaje = "El nuevo estatus se guardó correctamente" Else ErrorCancelar = True End If 'Si se está mandando a Cancelada SAT ElseIf CveEstatus = 5 Then Dim DT As DataTable = Nothing If FolioFiscal = "" Then Dim XmlDoc As New XmlDocument XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml") ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText End If 'Si es cancelar en el SAT: Dim CFDi As New ClbNegBICFDv3_2.ClsNegEDI Dim Respuesta As New ClbNegBICFDv3_2.ClsNegRespuesta Respuesta = CFDi.CancelaCFdi(UsuarioActual.Empresa.BIUsuario, UsuarioActual.Empresa.BIContraseña, Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoPfx, UsuarioActual.Empresa.ContraseñaKey, UsuarioActual.Empresa.RFC, FolioFiscal, "http://208.43.160.178/srvCFDi/service1.asmx") If Respuesta Is Nothing Then 'Alert("La factura no se pudo cancelar.
    Posbiles causas:
      - Los servicios del SAT están ocupados.
      - El Folio Fiscal no ha quedado registrado.", TipoMensaje.MsgError) Me.GuardaLog(CFDi.MsgError) ErrorCancelar = True Mensaje = "La factura no se pudo cancelar.
    Posbiles causas:
      - Los servicios del SAT están ocupados.
      - El Folio Fiscal no ha quedado registrado." ElseIf Respuesta.NoCertificadoSAT <> String.Empty Then If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then Dim IDMPoliza As Modelos.RetornoPolizaConta = GenerarPolizaAC(ObjAC, ObjFacturaDevolucion, True) IDPoliza = IDMPoliza.IdPoliza If IDMPoliza.IdPoliza <= 0 Then Mensaje = "No se pudo generar la poliza" ErrorCancelar = True End If End If If Not ErrorCancelar Then If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, Respuesta.NoCertificadoSAT, Respuesta.FechaTimbrado, CveVenta, IDPoliza) Then Mensaje = "El nuevo estatus se guardó correctamente" Else ErrorCancelar = True End If End If End If End If Return Not ErrorCancelar End Function Protected Sub ImgBtnAddC_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddC.Click Dim Row As DataRow = Nothing Row = DTmpC.NewRow Row("Descripcion") = tbDescC.Text DTmpC.Rows.Add(Row) tbDescC.Text = "" tbDescC.Focus() GvConceptos.DataSource = DTmpC GvConceptos.DataBind() UPCD.Update() End Sub Protected Sub ImgBtnAddF_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddF.Click Dim Row As DataRow = Nothing Dim ObjVentas As New ClsVentas Row = DTmpF.NewRow Row("CveVenta") = 0 Row("Titulo") = tbTituloF.Text Row("Nombre") = tbNmbF.Text Row("Puesto") = tbPuesF.Text Row("Lado") = ddlPos.SelectedValue.ToEntero() DTmpF.Rows.Add(Row) tbNmbF.Text = "" tbPuesF.Text = "" tbTituloF.Text = "" ddlPos.SelectedValue = CStr(0) GvFirmas.DataSource = DTmpF GvFirmas.DataBind() UPFirmas.Update() tbTituloF.Focus() End Sub #End Region #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 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 PrecioSugerido = CalculaPrecioSugerido(CvePSParametro, drPS("CveClasificacion").ToString().ToEntero()) If PrecioSugerido <= 0 Then PrecioSugerido = tPrecioSugerido TxtPrecio.Text = PrecioSugerido.ToString("#,###.####") ' que muestre hasta los 4 digitos si lo requiere If IsNumeric(TxtCantidad.Text.Trim) Then LblTotalPS.Text = (TxtCantidad.Text.Trim.ToDouble * TxtPrecio.Text.ToDouble).ToString().FormatoNumero(2) Else LblTotalPS.Text = "0.00" End If LblPrecio1.Text = TxtPrecio.Text UPPDescuento.Update() HdnIVAPS.Value = If(drPS("IVA").ToString() = "-1", ViewState("IVA"), drPS("IVA").ToString()).ToString() HdnIVARetAPS.Value = drPS("RetIVA").ToString() HdnAsientoContable.Value = drPS("AsientoContableVentas").ToString() HdnCtaContable.Value = drPS("IdCtaContVentas").ToString() HdnAplicaParaConcepto.Value = drPS("AplicaParaConcepto").ToString() HdnCodigo.Value = drPS("Codigo").ToString() If DdlClasificacion.SelectedIndex = 0 Then If drPS("CveClasificacion").ToString() IsNot Nothing Then DdlClasificacion.SelectedValueExist(drPS("CveClasificacion").ToString()) Else Alert("El Productos/Servicio no tiene asignada una Clasificación.", TipoMensaje.MsgInformacion) End If End If End If ElseIf CvePSParametro = -2 Then CargaPS(DdlClasificacion.SelectedValue.ToEntero(), Ddl) End If UPPPS.Update() UpPS.Update() End Sub Private Function CalculaPrecioSugerido(CvePSParametro As Integer, CveClasificacion As Integer) As Decimal Dim PrecioSugerido As Decimal = 0 If UsuarioActual.CveEmpresa.Contiene(1) Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPorcentajeProductos(CveCliente) Then Dim PrecioAplicado = ObjPS.DtResultados.FiltraParametros($"CvePS = {CvePSParametro}").FiltroPrimeroValor("PrecioA").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 End If If CvePrecioListaPS > 0 Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDecimal PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal End If ObjPS.Dispose() End If If PrecioSugerido = 0 Then Dim ObjInventarios As New ClsInventarios Dim CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveTipoAlmacen:=1) 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1, CveTipoAlmacen:=1) ObjInventarios.Dispose() If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If CvePrecioLista = CvePrecioListaPS End If 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 Return PrecioSugerido 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() LimpiaEscondeContado() End Sub Private Sub CambiaTipoDocto() CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString().ToEntero()) ConfiguraTipoDocto() CargaFolios() CargaEstatusFactura(DdlTipoComprobante.SelectedValue) UpEstatus.Update() If UsuarioActual.TienePermisoProceso(274) Then TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant" End If 'REINICIALIZA VALORES DE ENTREGA POR ADELANTADO RequiereAlmacenDestino = False TrAlmacenAsignado.Visible = False TrAlmacenOrigen.Visible = 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 RBLPago.SelectedValue = "2" RBLPago_SelectedIndexChanged(RBLPago, EventArgs.Empty) TxtFechaVencimientoCotizacion.Text = Now.ToString() GvPS.Columns(5).Visible = True ThTiempoEntrega.Visible = True ThTiempoEntrega2.Visible = True ChkEnviarFactura.Checked = True UpnTools.Update() tdTelefonoGen.Visible = False tdTxtTelefonoGen.Visible = False If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 140, 145) Then ChkEnviarFactura.Checked = False End If Else If DdlTipoComprobante.SelectedValue = "Cot" Then TrDireccion.Visible = False TrCiudad.Visible = False TrRFC.Visible = False 'RBLPago.Enabled = False 'RBLPago.SelectedValue = "2" TxtFechaVencimientoCotizacion.Text = Now.ToString() GvPS.Columns(5).Visible = True ThTiempoEntrega.Visible = True ThTiempoEntrega2.Visible = True tdTelefonoGen.Visible = False tdTxtTelefonoGen.Visible = False 'CUANDO SEA COMPUPROVEEDORES NO MANDA COTIZACIONES If UsuarioActual.CveEmpresa = 72 Then ChkEnviarFactura.Checked = False ChkEnviarFactura.Visible = False LblEnviarMail.Visible = False End If If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then ChkEnviarFactura.Checked = False End If Else TrDireccion.Visible = True TrCiudad.Visible = True TrRFC.Visible = True GvPS.Columns(5).Visible = False ThTiempoEntrega.Visible = False ThTiempoEntrega2.Visible = False RBLPago.Enabled = True LblMensaje.Visible = UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue.Contiene("Ing") If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev") Then ChkEnviarFactura.Checked = EnviarCorreoCliente ChkEnviarFactura.Visible = True LblEnviarMail.Visible = True ObtenerFechaVencimientoCER() If DdlTipoComprobante.SelectedValue.Contiene("Egs") Then 'se cargan las facturas timbradas 'CargaFacturasRelacionar() 'RegistraScript("$('#DivRelacionarFacturasNC').modal('show');") End If End If If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then 'ENTREGA POR ADELANTADO If UsuarioActual.Empresa.Funcionalidad(145) = "1" And Not DdlTipoComprobante.SelectedValue.Contiene("PA") Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then RequiereAlmacenDestino = True 'If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then ' TrAlmacenAsignado.Visible = True 'End If Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero() If CveAlmacenDestino > 0 Then DdlAlmacenAsignado.Items.Clear() DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} And CveTipoAlmacen In (4,10)") DdlAlmacenAsignado.DataBind() DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString())) DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString() Else DdlAlmacenAsignado.Items.Clear() DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()} AND CveTipoAlmacen IN (10)") DdlAlmacenAsignado.DataBind() End If 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 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 TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString TabAlmacen.Enabled = DdlTipoComprobante.SelectedValue <> "Ant" 'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True Else If LblCliente.Text <> "Cliente" And Not EstatusCliente Then Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia) End If If Not CveEmpresaCRM > 0 Then BtnEmitirImprimir.Visible = EstatusCliente TrVistaPrevia.Visible = EstatusCliente Else BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True End If End If If DdlTipoComprobante.SelectedValue = "Ing" Then ImgAntiPend.Visible = True End If MostrarOpcionesPaqueteria() 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()) CargaRestriccionesCreditoCliente(Alertas:=True, CveVenta:=Me.CveVenta) End Sub Protected Sub DdlCCEdit_SelectedIndexChanged(sender As Object, e As System.EventArgs) Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) Dim CveProyecto As String = DirectCast(sender, DropDownList).SelectedValue gvr.FCDropDownList("DDlSubProyecto").Items.Clear() gvr.FCDropDownList("DDlSubProyecto").DataSource = GlobalDTSubProyectos(CveProyecto.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa) gvr.FCDropDownList("DDlSubProyecto").DataBind() gvr.FCDropDownList("DDlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) End Sub Protected Sub DdlClasificacion_SelectedIndexChanged1(sender As Object, e As EventArgs) Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow) CargaPS(gvr.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero(), gvr.FCDropDownLost("DdlPS")) End Sub Protected Sub BtnEstimacion_Click(sender As Object, e As EventArgs) Handles BtnEstimacion.Click Dim Contrato As String = "" Dim Importe As Decimal = 0 Dim CvePS As Integer Dim PS As String Dim PSCodigo As String Dim CveUM As Integer Dim UM As String Dim CveClasificacion As Integer Dim Clasificacion As String Dim CveProyecto As Integer Dim Proyecto As String Dim CveSubProyecto As Integer Dim SubProyecto As String Dim FechaInicial As String = "" TmpDT.Rows.Clear() For Each Row As GridViewRow In GvEst.Rows If Row.FCCheckBox("Chk").Checked Then Importe += Row.FCLiteral("LtlImporte").Text.ToDecimal Contrato = Row.DataKey("NumeroContrato") CveContrato = Row.DataKey("CveContrato").ToEntero() FechaInicial = Row.DataKey("FechaInicial").ToString().ToDate.ToString("dd MMMM yyyy") CveSubProyecto = Row.DataKey("CveSubProyecto").ToEntero() End If Next If Importe > 0 Then CvePS = UsuarioActual.Empresa.Funcionalidad(106).ToEntero() If CvePS > 0 Then Dim rowPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If rowPS IsNot Nothing Then PS = rowPS("PS").ToString() PSCodigo = rowPS("PSCodigo").ToString() CveUM = rowPS("CveUM").ToString().ToEntero() UM = rowPS("UnidadMedida").ToString() CveClasificacion = rowPS("CveClasificacion").ToString().ToEntero() Clasificacion = rowPS("Clasificacion").ToString() Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto={0}", CveSubProyecto)) Proyecto = rowSP("Proyecto").ToString() CveProyecto = rowSP("CveProyecto").ToString().ToEntero() SubProyecto = rowSP("SubProyecto").ToString() AgregarProductoServicio(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero), Importe, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) 'AddPS(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero), Importe, 0.16, 0, 0, 1, 0, True, "", CveProyecto, Proyecto, CveSubProyecto, SubProyecto, rowPS("CveTipoPS").ToString().ToEntero(), rowPS("Inv_CveMetodoInventario").ToString().ToEntero(), CodigoPS:=PSCodigo) DdlTipoComprobante.SelectedValue = "Rem" DdlTipoComprobante_SelectedIndexChanged(DdlTipoComprobante, Nothing) End If UpParametros.Update() Tab.ActiveTab = TabGenerales Else Alert("La empresa no contiene un producto asignado a la estimació", TipoMensaje.MsgInformacion) End If Updatetabs.Update() End If End Sub Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlProyecto.SelectedIndexChanged CargaSubProyecto() End Sub #End Region #Region " SUCURSAL FACTURACION " Private Sub DdlSubProyectoDatos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSubProyectoDatos.SelectedIndexChanged CambiaSucursalGeneral() End Sub Private Sub CambiaSucursalGeneral(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) DdlSubProyectoEjecucion.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) DdlSubProyectoCobranza.SelectedValueExist(DdlSubProyectoDatos.SelectedValue) '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() CargaVendedores() UpDetalle.Update() UpEmitirTransitorio.Update() End Sub Private Sub CambiaSucursal(Optional RecargarPartidas As Boolean = True) CargaFormatoSucursal() CargaFolios() CargaVendedores() CargarAlmacenes() If RecargarPartidas Then RecargaSucursalPartidas() End If DdlPS.Attributes.Remove("data-cvesubproyecto") DdlPS.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue) DdlPSPyME.Attributes.Remove("data-cvesubproyecto") DdlPSPyME.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 ExFolioFactura Then Exit Sub End If If DdlSubProyectoDatos.SelectedValue.ToEntero() <= 0 Then Alert("No se tienen asignadas sucursales", TipoMensaje.MsgError) Exit Sub End If 'If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue <> "Cot" AndAlso (CveVenta <= 0 Or (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Or CveDevolucion > 0) Then ' TxtFolio.Text = "" 'Else Dim ObjFolios As New ClsGralFolios() Dim TipoDoctoConsulta As String = If(DdlTipoComprobante.SelectedValue = "Ant", "Ing", If(DdlTipoComprobante.SelectedValue = "PA", "Rem", DdlTipoComprobante.SelectedValue)) If ObjFolios.GetFolios(TipoDoctoConsulta, UsuarioActual.CveEmpresa) Then Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue)) If DT.Rows.Count > 0 Then ViewState("CveFolio") = DT.Rows(0)("CveFolio").ToString().ToEntero() 'ViewState("NumAprobacion") = CLng(DT.Rows(0)("Aprobacion").ToString()) 'ViewState("FechaAprobacion") = DT.Rows(0)("FechaAprobacion").ToString().ToDate ViewState("FolioActual") = DT.Rows(0)("FActual").ToString() If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso CveVenta > 0 AndAlso Not EsCreaApartirDe AndAlso Not String.IsNullOrEmpty(SerieVenta) Then LblSerie.Text = SerieVenta Else LblSerie.Text = DT.Rows(0)("Serie").ToString() End If TxtFolio.Text = DT.Rows(0)("FActual").ToString() If Not FacturarDocumentoNuevo Then If Not CveEmpresaCRM > 0 Then BtnCrearApartirDe.Enabled = EstatusCliente BtnEmitirImprimir.Visible = EstatusCliente TrVistaPrevia.Visible = EstatusCliente Else If TipoDoctoConsulta.Contiene("Ing", "Egs", "Ant", "Dev") Then BtnCrearApartirDe.Enabled = EstatusCliente BtnEmitirImprimir.Visible = EstatusCliente TrVistaPrevia.Visible = EstatusCliente Else BtnCrearApartirDe.Enabled = True BtnEmitirImprimir.Visible = True TrVistaPrevia.Visible = True End If End If End If 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 BtnCrearApartirDe.Enabled = 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 = 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") 'ViewState("Serie") = dr("Serie") 'If UsuarioActual.CveEmpresa = 140 AndAlso Me.CveVenta > 0 AndAlso Not EsCreaApartirDe AndAlso Not String.IsNullOrEmpty(SerieVenta) Then ' LblSerie.Text = SerieVenta 'Else ' LblSerie.Text = dr("Serie").ToString() 'End If If SerieXML <> "" Then LblSerie.Text = SerieXML Dim CveSubProyecto As Integer = GetSubProyectoSucursal() If CveSubProyecto > 0 Then CargaSubProyecto(CveSubProyecto) UPPProy.Update() TipoVentaSucursal = dr("TipoVenta").ToString().ToEntero() If dr("TipoVenta").ToString() = "1" Then LiBuscarPrecio.Visible = True UpnTools.Update() 'activa el modo de pago efectivo directamente, y es venta nueva If ViewState("CveVenta").ToString().ToEntero() < 0 Then InicializaCondicionesPago() RBLPago.SelectedValue = "2" LimpiaEscondeContado() If DdlCuentaEfectivo.Items.Count = 2 Then DdlCuentaEfectivo.SelectedIndex = 0 End If End If End If UpFacturar.Update() UpPS.Update() UpParametros.Update() End Sub Private Sub CargaVendedores() Dim CveVendedorActual As Integer = 0 Dim EsVentaNueva As Boolean = (Me.CveVenta <= 0 OrElse Me.EsCreaApartirDe OrElse NuevaFactura = 1) DdlVendedor.Items.Clear() DdlVendedor.SelectedValue = Nothing DdlVendedorSucursal.Items.Clear() DdlVendedorSucursal.SelectedValue = Nothing If UsuarioActual.Empresa.Funcionalidad(302) = "1" AndAlso DdlSubProyectoDatos.SelectedValue.ToEntero() > 0 Then DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=-1).FiltraParametros(String.Format("VendedorTipo IN (1,4) AND (CveSubProyecto IS NULL OR CveSubProyecto = {0})", DdlSubProyectoDatos.SelectedValue)) Else DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros("VendedorTipo = 1") End If DdlVendedorSucursal.DataSource = DdlVendedor.DataSource DdlVendedor.DataBind() DdlVendedorSucursal.DataBind() DdlVendedor.Items.Insert(0, New ListItem("Sin Asignar")) DdlVendedorSucursal.Items.Insert(0, New ListItem("Sin Asignar")) DdlVendedor.SelectedValueExist("0") DdlVendedorSucursal.SelectedValueExist("0") 'SI NO ES VENTA ACTUAL If EsVentaNueva Then 'PRIMERO TOMA EL VENDEDOR DEL USUARIO If UsuarioActual.CveVendedor > 0 Then CveVendedorActual = UsuarioActual.CveVendedor End If 'DAR PREFERENCIA AL VENDEDOR ASIGNADO AL CLIENTE If Me.CveVendedorCliente > 0 Then CveVendedorActual = Me.CveVendedorCliente End If 'DAR PREFERENCIA AL VENDEDOR ASIGNADO LA SUCURSAL CLIENTE If Me.CveVendedorClienteSucursal > 0 Then CveVendedorActual = Me.CveVendedorClienteSucursal End If 'SI TIENE CONTRATO TOMA EL DEL CONTRATO If Me.CveVendedorContrato > 0 Then CveVendedorActual = Me.CveVendedorContrato End If 'SI ES EMPRESA CRM TOMA DE AQUI If Me.CveVendedorEmpresaCRM > 0 Then CveVendedorActual = Me.CveVendedorEmpresaCRM End If Else 'SI ES VENTA EXISTENTE TOMA EL DE LA VENTA If Me.CveVendedorVenta > 0 Then CveVendedorActual = Me.CveVendedorVenta End If End If If CveVendedorActual > 0 Then Dim VendedorActual As String = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=-1).FiltroPrimeroValor("Vendedor", $"CveVendedor = {CveVendedorActual}") 'SI NO ENCUENTRA BUSCA EN LOS VENDEDORES DEL PV 'If String.IsNullOrEmpty(VendedorActual) Then ' VendedorActual = GlobalDTVendedores(UsuarioActual.CveEmpresa, VendedorTipo:=4).FiltroPrimeroValor("Vendedor", String.Format("CveVendedor = {0}", CveVendedorActual)) 'End If If String.IsNullOrEmpty(VendedorActual) Then DdlVendedor.SelectedValueExist(CveVendedorActual) Else DdlVendedor.SelectedValueExistInsert(CveVendedorActual, VendedorActual) End If End If If DdlVendedor.SelectedValue.ToEntero() > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = False End If 'multiples vendedores visible If UsuarioActual.TienePermisoProceso(153) OrElse UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = True End If UPPVentas.Update() 'TxtCorreoNotificaciones.Text = GlobalDTUsuarios(UsuarioActual.CveUsuario).FiltroPrimeroValor("Correo") End Sub #End Region #Region " AGREGAR PS " Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click AgregarPS() End Sub Private Function ValidaAgregarPS(CvePS As Integer, CveUM As Integer, PU As Double, CveTipoPS As Integer) As Boolean 'NO TOCAR - IPP 'VALIDA PARAMETROS If CvePS <= 0 Or CveUM <= 0 Then Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) Return False End If If HdnPS.Value = "" Or HdnPS.Value = "-1" Then Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia) Return False End If 'SI USA CONTABILIDAD LA CLASIFICACION ES OBLIGATORIA If DdlClasificacion.SelectedValue.ToEntero() <= 0 AndAlso UsuarioActual.Empresa.UsaContabilidad Then Alert("La Clasificación es obligatoria, favor de seleccionarla", TipoMensaje.MsgAdvertencia) Return False End If 'SUBPROYECTO OBLIGATORIO If DdlSubProyecto.SelectedValue.ToEntero() <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(120) = "1" Then Alert("El Subproyecto es obligatorio, favor de seleccionarlo", TipoMensaje.MsgAdvertencia) Return False End If If CveCliente <= 0 And Not CveEmpresaCRM > 0 Then Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact', 800, 547, 'N', 'PopUpBuscar')") Return False End If If PU <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(558) = "1" Then Alert("El precio debe ser mayor a 0", TipoMensaje.MsgAdvertencia) Return False End If 'VALIDA PROMOCIONES Dim ObjVentas As New ClsVentas If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveCliente, DdlVendedor.SelectedValue.ToEntero(), 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 Not 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:=DdlVendedor.SelectedValue.ToEntero(), CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1) Dim Costo As Decimal = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero(), 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.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -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" And ChkSinExistencia.Checked = False 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 = False Dim EsValidoMayor = 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 Descuentos Dim Descuento As Decimal = HdnDescuento.Value.ToDecimal If UsuarioActual.Empresa.Funcionalidad(572) = "1" AndAlso Not TbDescuentosRNC.Visible Then TbDescuentosRNC.Visible = True LnkDescuentosRNC.Visible = UsuarioActual.TienePermisoProceso(328) End If If HdnTipoDescuento.Value = "0" Then Descuento = HdnDescuento.Value.ToDecimal * Cantidad End If 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 Descuentos 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 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 = 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 = RowPorcentaje("PorcentajeProducto").ToString().ToDecimal() / 100D Dim PorcentajeProducto2 = RowPorcentaje("PorcentajeProducto2").ToString().ToDecimal() / 100D Dim PorcentajeProducto3 = RowPorcentaje("PorcentajeProducto3").ToString().ToDecimal() / 100D Dim TotalInicial As Decimal = (Cantidad * (PU)) '- Descuento Dim TotalFinal = TotalInicial 'SI APLICA EL PRIMER DESCUENTO If PorcentajeProducto > 0 Then Dim Descuento1 As Decimal = (TotalInicial * PorcentajeProducto).RoundSQL(2) Dim Total2 = (TotalInicial - Descuento1) 'SI APLICA EL SEGUNDO DESCUENTO If PorcentajeProducto2 > 0 Then Dim Descuento2 As Decimal = (Total2 * PorcentajeProducto2).RoundSQL(2) Dim Total3 = (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 TotalProntoPago As Decimal = (Cantidad * (PU)) - Descuento Dim PorcentajeProntoPago = 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 = (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 Dim CvePS As Integer = -1 If DIVCod.Visible Then CvePS = HdnCvePS.Value.ToEntero() Else CvePS = DdlPS.SelectedValue.ToEntero() End If If ValidaAgregarPS(CvePS, DdlUnidadMedida.SelectedValue.ToEntero(), TxtPrecio.Text.Trim.ToDouble, HdnTipoPS.Value.ToEntero()) Then If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then CvePSAmortizacion = DdlPS.SelectedValue.ToEntero().ToEntero() End If Dim 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 Descuentos = CalcularDescuentos(CvePS, Cantidad, PU) If ObjDescuento.EsPUModificado Then PU = ObjDescuento.PU End If AgregarProductoServicio(Cantidad, DdlUnidadMedida.SelectedValue.ToEntero(), DdlUnidadMedida.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero(), DdlClasificacion.SelectedItem.Text, CvePS, "", TxtObsPS.Text.TrimEnd, PU, ObjDescuento.ImporteDescuento, DdlProyecto.SelectedValue.ToEntero(), DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero(), DdlSubProyecto.SelectedItem.Text, Serie:=If(DIVCod.Visible, TxtCodigoSerie.Text.Trim, ""), TiempoEntrega:=TxtTiempoEntrega.Text, CuentaPredial:=TxtCuentaPredial.Text.Trim, RegeneraIEPS:=ClienteDesglosaIEPS, CvePromocionDetalle:=ObjDescuento.CvePromocionDetalle, ImporteProntoPago:=ObjDescuento.ImporteProntoPago, ObjDescuento:=ObjDescuento) CalculaUsados() If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso ListaDescuentos IsNot Nothing AndAlso ObjDescuento IsNot Nothing Then ListaDescuentos.Add(ObjDescuento) End If CalculaTotalesVenta() LimpiaAgregar() 'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW If AplicaComercioExterior Then CargaGvComercioExterior() End If End If UpPS.Update() Catch ex As Exception OnError("Ocurrió un error al agregar el producto", ex) End Try End Sub Private Sub CalculaLineasAdicionales() If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") AndAlso UsuarioActual.Empresa.Funcionalidad(705) = "1" Then DdlLineaAdicional.DataSource = Nothing Using ObjVentas As New ClsVentas If CveVenta > 0 Then If ObjVentas.GetLineasAdicionalesSaldo(-1, CveCliente, -1, DdlMoneda.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa, ConSaldo:=-1) Then If ObjVentas.DtResultados.Rows.Count > 0 Then TrLineaAdicional.Visible = True DdlLineaAdicional.DataSource = ObjVentas.DtResultados.FiltraParametros($"Saldo > 0 OR CveLineaAdicional = {Me.CveLineaAdicionalVenta}") End If End If Else If ObjVentas.GetLineasAdicionalesSaldo(-1, CveCliente, -1, DdlMoneda.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa, ConSaldo:=1) Then If ObjVentas.DtResultados.Rows.Count > 0 Then TrLineaAdicional.Visible = True DdlLineaAdicional.DataSource = ObjVentas.DtResultados End If End If End If End Using DdlLineaAdicional.DataBind() DdlLineaAdicional.Items.Insert(0, New ListItem("Seleccione", "-1")) If Me.CveLineaAdicionalVenta > 0 Then DdlLineaAdicional.SelectedValueExist(CveLineaAdicionalVenta.ToString()) DdlLineaAdicional_SelectedIndexChanged(DdlLineaAdicional, EventArgs.Empty) DdlLineaAdicional.Enabled = False LnkUpdateLineaAdicional.Visible = True End If End If UPCondicionesPago.Update() End Sub Private Sub AgregarPSPYME() If Modalidad = "A" Then Dim CveProyecto As Integer = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedValue, "0").ToString().ToEntero() Dim Proyecto As String = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedItem.Text, "").ToString() Dim CveSubProyecto As Integer = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedValue, "0").ToString().ToEntero() Dim SubProyecto As String = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedItem.Text, "").ToString() Dim PU As Decimal = TxtPrecioPyME.Text.ToDecimal() Dim Cantidad As Decimal = TxtCantidadPyME.Text.ToDecimal() Dim CvePS As Integer = DdlPSPyME.SelectedValue.ToEntero() Dim Descuento As Descuentos = CalcularDescuentos(CvePS, Cantidad, PU) AgregarProductoServicio(Cantidad, DdlUMPyME.SelectedValue.ToEntero(), DdlUMPyME.SelectedItem.Text, DdlClasificacionPyME.SelectedValue.ToEntero(), DdlClasificacionPyME.SelectedItem.Text, CvePS, DdlPSPyME.SelectedText, TxtObsPyME.Text, PU, Descuento.ImporteDescuento, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) CalculaUsados() CalculaTotalesVenta() ElseIf Modalidad = "U" Then Dim ErrorEdit As Boolean = True Dim Contador As Integer = 0 For Each row As DataRow In TmpDT.Rows If row("Consec").ToString().ToEntero() = Index Then ErrorEdit = False Exit For End If Contador = Contador + 1 Next If ErrorEdit = True Then Exit Sub Else TmpDT.AcceptChanges() TmpDT.Rows.RemoveAt(Contador) TmpDT.AcceptChanges() End If End If End Sub Private Sub LimpiaAgregar() TxtCantidad.Text = "" HdnPS.Value = "-1" HdnCodigoPS.Value = "-1" HdnTipoPS.Value = "-1" HdnTipoInv.Value = "-1" DdlClasificacion.SelectedIndex = 0 If Not UsuarioActual.Empresa.Funcionalidad(141).ToString() = "1" Then DdlPS.SelectedValue = "-1" Else DdlPS.SelectedValue = "" DdlPS.SelectedText = "" End If TxtObsPS.Text = "" TxtPrecio.Text = "" LblTotalPS.Text = "0.00" HdnIVAPS.Value = "-1" HdnIVARetAPS.Value = "-1" HdnAplicaIEPS.Value = "False" HdnPorcentajeIEPS.Value = "0" HdnAsientoContable.Value = "-1" HdnCtaContable.Value = "-1" HdnAplicaParaConcepto.Value = "False" HdnCodigo.Value = "-1" TxtCuentaPredial.Text = "" ' codigo comentado RMF. 2016.06.13, esto paa que respete el que tenga selecionado e nla sucursal 'DdlProyecto.SelectedIndex = 0 'DdlSubProyecto.Items.Clear() 'DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1")) TxtCantidad.Focus() 'Limpia descuentos HdnTipoDescuento.Value = "-1" HdnDescuento.Value = "0" LblPrecio1.Text = "0.00" LblTotalPS1.Text = "0.00" TxtPorDescP.Text = "0" TxtDescP.Text = "0" LblDescuento.Text = "0.00" LblPrecioFinal.Text = "0.00" 'CODIGO BARRAS TxtCodigoBarras.Text = "" TxtCodigoSerie.Text = "" 'FOCUS DEPENDIENDO MODALIDAD DE CODIGO BARRAS If DIVCod.Visible Then TxtCodigoBarras.Focus() Else TxtCantidad.Focus() End If UPPDescuento.Update() UpINV.Update() UPPPS.Update() End Sub Private 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 Descuentos = Nothing) 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 'If (Obs.Length + PS.Length > 1000) AndAlso DdlTipoComprobante.SelectedValue <> "Cot" Then ' Alert(String.Format("El Nombre y observación del producto tiene longitud de {0} caracteres y excede los 1000 caracteres permitidos.", Obs.Length + PS.Length), TipoMensaje.MsgAdvertencia) ' Return False 'End If 'VALIDA CONCEPTOS EN CERO - YA SE VALIDA ANTES CON FUNCIONALIDAD - A MIRAS DE ELIMINAR - IPP 28 AGOSTO 2017 If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant") Then If UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso CveOrdenCompraDetalle = 0 Then ' si viene de una oc, se permiten valores en cero If Cantidad * PU <= 0 Then If Not DdlTipoComprobante.SelectedValue = "DPe" Then Alert("El importe del concepto debe ser mayor a cero. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If End If End If End If Dim Row As DataRow = Nothing Dim TotalCalculableImpuestos As Decimal = 0 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 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 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 = 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 CBool(DrPS("EsOutSourcing").ToString()) Then ClienteRetIVA = 0.06D DdlTipoRetencion.SelectedValueExist("4") ElseIf 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") = HdnTipoDescuento.Value Row("CvePromocionDetalle") = CvePromocionDetalle Row("Total") = (Cantidad * PU) Row("TotalImporte") = (Cantidad * PU).RoundSQL(NumeroDecimales) 'Row("AsientoContableVentas") = DrPS("AsientoContableVentas") ' Row("IdCtaContVentas") = IdCtaContable ' Row("AplicaParaConcepto") = AplicaParaConcepto 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("EsOutSourcing") = DrPS("EsOutSourcing") 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" 'SOLO DEBE MOSTRASE SI EL PAGO ES DE CONTADO If RBLPago.SelectedValue = "2" Then GvPS.Columns(22).Visible = True thProntoPago.Visible = True thProntoPago2.Visible = True End If End If If UsuarioActual.CveEmpresa = 119 Then If Not RemisionesLista.Count > 0 Then 'SI VIENE DE REMISION NO SE CONSIDERA 'MONEDA DIFERENTE DEL PS AL PRIMER PS AGREGADO If DdlMoneda.Enabled = False And CveVenta < 0 And TmpDT.Rows.Count > 0 Then If DdlMoneda.SelectedValue <> DrPS("CveMoneda").ToString() Then Alert($"La moneda base del producto: {DrPS("PSCodigo").ToString()} es diferente a la moneda del documento.", TipoMensaje.MsgAdvertencia) Return False End If End If 'ACTIVA PRODUCTOS DE LA MISMA MONEDA If TmpDT.Rows.Count = 0 And CveVenta < 0 Then DdlMoneda.SelectedValueExist(DrPS("CveMoneda").ToString()) CambiaMoneda() DdlMoneda.Enabled = False End If End If End If '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 = 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 = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString().ToDecimal, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveTipoAlmacen:=1) 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString().ToDecimal, -1, "-1", TxtFecha.Text.ToDate, -1, CveTipoAlmacen:=1) ObjInventarios.Dispose() Dim PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If ObjPS.Dispose() End If End If If PrecioSugerido > 0 Then PU = PrecioSugerido End If PU = 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") = HdnTipoDescuento.Value DrPoliza("Total") = (DrPoliza("Cantidad").ToString().ToDecimal * PU) DrPoliza("TotalImporte") = (DrPoliza("Cantidad").ToString().ToDecimal * PU).RoundSQL(NumeroDecimales) DrPoliza("SATClaveProdServ") = DrPSAdicional("SATClavePS") DrPoliza("SATClaveUM") = DrPSAdicional("SATClaveUnidadMedida") 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("AsientoContableVentas", GetType(Integer)) TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer)) TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean)) TmpDT.Columns.Add("CveProyecto", GetType(Integer)) TmpDT.Columns.Add("Proyecto", GetType(String)) TmpDT.Columns.Add("CveSubProyecto", GetType(Integer)) TmpDT.Columns.Add("SubProyecto", GetType(String)) TmpDT.Columns.Add("CveVentaDetallePadre", GetType(Integer)) 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("EsOutSourcing", GetType(Boolean)) 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("EsOutSourcing").DefaultValue = False TmpDT.Columns("EsCargo").DefaultValue = False TmpDT.Columns("TieneProntoPago").DefaultValue = "No" TmpDT.Columns("ImporteProntoPago").DefaultValue = 0 End Sub Private Sub CreaDTmpC() DTmpC = New DataTable DTmpC.Columns.Add("Descripcion", GetType(String)) End Sub Private Sub CreaDTmpF() DTmpF = New DataTable DTmpF.Columns.Add("CveVenta", GetType(Integer)) DTmpF.Columns.Add("Titulo", GetType(String)) DTmpF.Columns.Add("Nombre", GetType(String)) DTmpF.Columns.Add("Puesto", GetType(String)) DTmpF.Columns.Add("Lado", GetType(Integer)) End Sub Private Sub CreaDTImpuestos() TmpDTImpuestos = New DataTable TmpDTImpuestos.Columns.Add("CveImpuestoLocal", GetType(Integer)) TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String)) TmpDTImpuestos.Columns.Add("Porcentaje", GetType(Decimal)) TmpDTImpuestos.Columns.Add("Importe", GetType(Decimal)) TmpDTImpuestos.Columns.Add("TipoImpuesto", GetType(Integer)) TmpDTImpuestos.Columns.Add("IdCtaContable", GetType(Integer)) TmpDTImpuestos.Columns.Add("CveCuenta", GetType(Integer)) TmpDTImpuestos.Columns.Add("Orden", GetType(Integer)) End Sub Private Sub CreaDTImpuestosIVAIEPS() TmpDTImpuestosIVAIEPS = New DataTable TmpDTImpuestosIVAIEPS.Columns.Add("Impuesto", GetType(String)) TmpDTImpuestosIVAIEPS.Columns.Add("tasa", GetType(String)) TmpDTImpuestosIVAIEPS.Columns.Add("Importe", GetType(Decimal)) TmpDTImpuestosIVAIEPS.Columns.Add("Orden", GetType(Integer)) End Sub Private Sub CreaDTDocumentosRelacionados() TmpDTDocumentosRelacionados = New DataTable TmpDTDocumentosRelacionados.Columns.Add("SerieFolio", GetType(String)) TmpDTDocumentosRelacionados.Columns.Add("Fecha", GetType(String)) TmpDTDocumentosRelacionados.Columns.Add("Importe", GetType(Decimal)) TmpDTDocumentosRelacionados.Columns.Add("FolioFiscal", GetType(Integer)) End Sub #End Region #Region "P D F" #End Region #Region "A C T U A L I Z A " #Region "New" 'Private Function ActualizaTimbrado(Timbro As Boolean, CveVenta As Integer) As Boolean ' Dim Retorno = False ' Dim ObjVentas As New ClsVentas() ' 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, "", Now, 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 CargaOtrosConceptos() Dim ObjVentas As New ClsVentas If ObjVentas.GetVentaOtrosConceptos(UsuarioActual.CveEmpresa, CveVenta) Then GVOtrosConceptos.DataSource = ObjVentas.DtResultados GVOtrosConceptos.DataBind() UpOtrosConceptos.Update() End If ObjVentas.Dispose() End Sub Private Function GenerarPolizaAC(ObjAC As ClsContPAQi, factura As Modelos.Factura, Optional CancelacionIngreso As Boolean = False) As Modelos.RetornoPolizaConta Dim Retorno As New Modelos.RetornoPolizaConta Dim IDPoliza As Integer = 0 Dim ErrorAC As Boolean = False 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() Dim Fecha As Date = factura.Fecha Dim Concepto As String = String.Format("GD {0}", factura.Cliente.Nombre) Dim Paridad As Integer = 1 Dim TipoMovto As Boolean = False If CancelacionIngreso Then Concepto = String.Format("Cancelación GD {0}", factura.Cliente.Nombre) Paridad = -1 TipoMovto = True End If Dim TipoPoliza = If(factura.TipoDocto = "OP" Or factura.TipoDocto = "Com", 3, 1) IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, factura.Total * 2, factura.Total * 2, factura.CveUsuario, Fecha) Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue)) 'Dim Importe As Double = TxtTotal.Text.ToDouble Dim CtaCliente As Integer = factura.Cliente.IdCtaContClientes Dim CtaISSSTESON As Integer = 643 Dim CtaISPT As Integer = 1745 ' Dim NombreCliente As String = ViewState("NombreCliente").ToString() If IDPoliza > 0 Then Retorno.IdPoliza = IDPoliza Retorno.FolioPoliza = ObjAC.Folio 'Orden de PAGO If factura.TipoDocto = "OP" Then If DdlOrdenPago.SelectedValue.ToEntero() = 1 Then 'ISSSTESON If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then ErrorAC = True End If Else ErrorAC = True End If Else 'ISPT If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then ErrorAC = True End If Else ErrorAC = True End If End If ' NORMAL Else Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)() Group gvr By Grp = New With { Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero() } Into Group Select Grp.CvePresupuestoIngreso, TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble) 'Select Case TipoComprobante ' Case "Ing", "Egs" For Each grp In Detalles dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso)) Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString(), TxtFolio.Text) If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString().ToEntero(), False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "V||" & factura.CveVenta) Then If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString().ToEntero(), True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "V||" & factura.CveVenta) Then 'CARGO la deuda del cliente If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "V||" & factura.CveVenta) Then 'abono, If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString().ToEntero(), Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "V||" & factura.CveVenta) Then ErrorAC = True End If Else ErrorAC = True End If Else ErrorAC = True End If Else ErrorAC = True End If Next 'Case "OP", "Com" ' Dim Importe As Decimal = 0 ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then ' End If ' End If 'End Select End If Else ErrorAC = True End If If Not ErrorAC Then ObjAC.AjustaPoliza(IDPoliza) Else Retorno.IdPoliza = 0 Retorno.FolioPoliza = -1 Alert("Error al agregar la Póliza de AC.", TipoMensaje.MsgError) End If ' ObjAC.Dispose() Return Retorno End Function 'Private Function GenerarPolizaAC(ObjAC As ClsContPAQi, Optional CancelacionIngreso As Boolean = False) As Integer ' Dim Retorno As Integer = 0 ' Dim IDPoliza As Integer = 0 ' Dim ErrorAC As Boolean = False ' 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() ' Dim Fecha As Date = TxtFecha.Text.ToDate ' Dim Concepto As String = String.Format("GD {0}", NombreCliente) ' Dim Paridad As Integer = 1 ' Dim TipoMovto As Boolean = False ' If CancelacionIngreso Then ' Concepto = String.Format("Cancelación GD {0}", NombreCliente) ' Paridad = -1 ' TipoMovto = True ' End If ' Dim TipoPoliza = If(DdlTipoComprobante.SelectedValue.ToString() = "OP" Or DdlTipoComprobante.SelectedValue.ToString() = "Com", 3, 1) ' IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, TxtTotal.Text.ToDouble * 2, TxtTotal.Text.ToDouble * 2, UsuarioActual.CveUsuario, Fecha) ' Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue)) ' 'Dim Importe As Double = TxtTotal.Text.ToDouble ' Dim CtaCliente As Integer = ViewState("IdCtaContClientes").ToString().ToEntero() ' Dim CtaISSSTESON As Integer = 643 ' Dim CtaISPT As Integer = 1745 ' ' Dim NombreCliente As String = ViewState("NombreCliente").ToString() ' If IDPoliza > 0 Then ' 'Orden de PAGO ' If DdlTipoComprobante.SelectedValue.ToString() = "OP" Then ' If DdlOrdenPago.SelectedValue.ToEntero() = 1 Then ' 'ISSSTESON ' If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "V||" & CveVenta) Then ' If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "V||" & CveVenta) Then ' ErrorAC = True ' End If ' Else ' ErrorAC = True ' End If ' Else ' 'ISPT ' If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "V||" & CveVenta) Then ' If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "V||" & CveVenta) Then ' ErrorAC = True ' End If ' Else ' ErrorAC = True ' End If ' End If ' ' NORMAL ' Else ' Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)() ' Group gvr By Grp = New With { ' Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero() ' } Into Group ' Select Grp.CvePresupuestoIngreso, ' TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble) ' 'Select Case TipoComprobante ' ' Case "Ing", "Egs" ' For Each grp In Detalles ' dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso)) ' Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString(), TxtFolio.Text) ' If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString().ToEntero(), False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then ' If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString().ToEntero(), True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then ' 'CARGO la deuda del cliente ' If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then ' 'abono, ' If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString().ToEntero(), Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then ' ErrorAC = True ' End If ' Else ' ErrorAC = True ' End If ' Else ' ErrorAC = True ' End If ' Else ' ErrorAC = True ' End If ' Next ' 'Case "OP", "Com" ' ' Dim Importe As Decimal = 0 ' ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then ' ' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then ' ' End If ' ' End If ' 'End Select ' End If ' Else ' ErrorAC = True ' End If ' If Not ErrorAC Then ' ObjAC.AjustaPoliza(IDPoliza) ' Retorno = IDPoliza ' Else ' Retorno = -1 ' Alert("Error al agregar la Póliza de AC.", TipoMensaje.MsgError) ' End If ' ' ObjAC.Dispose() ' Return Retorno 'End Function Private Sub SetValues() ViewState("TipoCambio") = 1 If UsuarioActual.Empresa.MostrarRetIVA Then TrRetIVA.Style.Add("display", "") If UsuarioActual.Empresa.MostrarRetISR Then TrRetISR.Style.Add("display", "") If UsuarioActual.CveEmpresa.Contiene(72, 80) Then ' agregar en el modal de PS. que forme el código del producto TxtPS.Enabled = False DivDdlTipo.Visible = True DivTxtModelo.Visible = True DivTxtAdicional.Visible = True DdlTipo.Attributes.Add("onChange", "CreaDescripcionPS();") DdlMarcaPSDes.Attributes.Add("onChange", "CreaDescripcionPS();") TxtModelo.Attributes.Add("onKeyUp ", "CreaDescripcionPS();") TxtAdicional.Attributes.Add("onKeyUp ", "CreaDescripcionPS();") CargaClasificacionesDetalles() ClasificacionModal() End If If Not UsuarioActual.CveEmpresa.Contiene(1, 119) Then 'PAGO CON TERMINAL PARA JAM RBLPago.Items.RemoveAt(2) End If End Sub Private Sub SetPermisos() If CveVenta < 1 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")) LnkFacturarRemision.Visible = False LnkRemisiones.Visible = False 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) 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 : thEncIEPS1.Visible = True : thEncIEPS2.Visible = True Else TrIEPS.Visible = False : GvPS.Columns(ColumnaIEPS).Visible = False : thEncIEPS1.Visible = False : thEncIEPS2.Visible = False If TotalRetIVA > 0 Then GvPS.Columns(ColumnaRetIVA).Visible = True Else GvPS.Columns(ColumnaRetIVA).Visible = False If TotalRetISR > 0 Then GvPS.Columns(ColumnaRetISR).Visible = True Else GvPS.Columns(ColumnaRetISR).Visible = False If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero().Contiene(2, 1) Then TotalAmortizacion = 0 End If 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 'SI ES PAGO DE CONTADO If RBLPago.SelectedValue = "2" Then TotalProntoPago = TmpDT.SUM("ImporteProntoPago").ToDecimal End If HdnProntoPago.Value = TotalProntoPago.ToString() LblProntoPago.Text = TotalProntoPago.FormatoNumero(2) LblTotalAPagar.Text = (TxtTotal.Text.ToDecimal() - TotalRemNCAplicado - TotalProntoPago).FormatoNumero LblAmort.Text = TxtSubTotal.Text If CveVenta <= 0 OrElse (CveDevolucion > 0 And NuevaFactura = 1) Then HdnVentaSaldo.Value = Total.ToString() Else HdnVentaSaldo.Value = SaldoVenta.ToString() End If HdnIVAOriginal.Value = TxtIVA.Text 'JJMQ 20160506: Se agrego para la validacion de pago de contado. 'CVImporteContado.ValueToCompare = Total.ToString() If MensajeCveSAT IsNot Nothing AndAlso MensajeCveSAT.ToString().Length > 0 Then Alert($"Los siguientes conceptos hace falta especificar clave SAT

    {MensajeCveSAT.ToString()}", TipoMensaje.MsgAdvertencia) MensajeCveSAT.Clear() End If Dim view As DataView = New DataView(TmpDT) view.Sort = "Consec" GvPS.DataSource = view GvPS.DataBind() 'RECARGA GV INVENTARIO If (Not CveVenta > 0 Or DdlTipoComprobante.SelectedValue = "Cot") OrElse (UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso EsCreaApartirDe) Then DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") CargaGVInv(DtInv) End If 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 Descuentos 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 UPObservaciones.Update() UpContado.Update() UpPS.Update() RegistraScript("BorraDescuentos();", "BorraDescuentos") End Sub Private Function ValidaAdendaFEMSA() As Boolean Dim Retorno As Boolean = False If Not AplicaFEMSA Then Retorno = True Else If TxtFEMSA_Version.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_Version.Text.Trim) Then Retorno = False Alert("La versión de la Adenda es requerida y debe ser numérica. Por favor corrija.", TipoMensaje.MsgAdvertencia) ElseIf TxtFEMSA_NumSociedad.Text.Trim.Length = 0 Then Retorno = False Alert("El número de Sociedad para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) ElseIf TxtFEMSA_NumProveedor.Text.Trim.Length = 0 Then Retorno = False Alert("El número de Proveedor para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumPedido.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumPedido.Text.Trim)) Then Retorno = False Alert("El número de Pedido para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumEntrada.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumEntrada.Text.Trim)) Then Retorno = False Alert("El número de Entrada para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso TxtFEMSA_NumRemision.Text.Trim.Length = 0 Then Retorno = False Alert("El número de Remisión para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) ElseIf TxtFEMSA_Mail.Text.Trim.Length = 0 Then Retorno = False Alert("El Mail para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia) Else Retorno = True End If End If Return Retorno End Function Private Function ValidaComplementoDetallista() As Boolean Dim Retorno As Boolean = False If Not AplicaDetallista Then Retorno = True Else If TxtDet_OrdenCompra.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_OrdenCompra.Text.Trim) Then Retorno = False Alert("El campo Orden de Compra es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia, "") ElseIf TxtDet_FechaOrdenCompra.Text.Trim.Length = 0 OrElse Not IsDate(TxtDet_FechaOrdenCompra.Text.Trim) Then Retorno = False Alert("El campo Fecha de Orden de Compra es requerido y debe de contar con un formato válido de fecha. Por favor corrija.", TipoMensaje.MsgAdvertencia) ElseIf TxtDet_GLNComprador.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNComprador.Text.Trim) Then Retorno = False Alert("El campo GLN-Comprador es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) ElseIf TxtDet_Departamento.Text.Trim.Length = 0 Then Retorno = False Alert("El campo Departamento es requerido. Por favor ingrese uno.", TipoMensaje.MsgAdvertencia) ElseIf TxtDet_GLNVendedor.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNVendedor.Text.Trim) Then Retorno = False Alert("El campo GLN-Vendedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) ElseIf TxtDet_NumProv.Text.Trim.Length = 0 Then Retorno = False Alert("El campo Número de Proveedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia) Else Retorno = True End If End If Return Retorno End Function Private Function ValidaComplementoFord() As Boolean Dim Retorno As Boolean = False If Not AplicaFord Then Retorno = True Else If TxtFordGSDB.Text.Trim.Length = 0 Then Retorno = False Alert("El campo GSDB es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia) Else If LstFordASN.Items.Count = 0 Then Retorno = True 'Alert("El campo ASN es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia) Else Retorno = True End If End If End If Return Retorno End Function Private Sub VinculaCotizacionVenta() Dim ObjVentas As New ClsVentas() ObjVentas.UpdateVentaCotizacion(CveVenta, Request("CveVenta").ToEntero()) ObjVentas.Dispose() End Sub Private Sub GeneraAddenda7Eleven(Archivo As String) Dim cfdi As String = "" Dim SB As New StringBuilder Try Using sr As New StreamReader(Archivo) cfdi = sr.ReadToEnd() End Using Catch e As Exception Alert("The file could not be read:", TipoMensaje.MsgError) End Try cfdi = cfdi.Replace("", "") SB.Append(cfdi) SB.Append("") SB.AppendFormat("", Txt7ElevenNumProveedor.Text.Trim) SB.AppendFormat("", Txt7ElevenFolio.Text.Trim, Txt7ElevenTienda.Text.Trim, Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-MM-dd")) For Each Row As DataRow In TmpDT.Rows SB.AppendFormat("", Row("Codigo"), Row("PS"), Row("Cantidad").ToString().ToDouble.FormatoNumero(), Row("PU").ToString().ToDouble.FormatoNumero()) Next SB.Append("") Using outfile As New StreamWriter(Archivo) outfile.Write(SB.ToString()) End Using 'Exit Sub 'Dim MyXmlDocument As New XmlDocument() 'MyXmlDocument.Load("C:/Temp/aaa.xml") 'Dim nsmgr = New XmlNamespaceManager(MyXmlDocument.NameTable) 'nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3") 'Dim ParentElement As XmlElement = MyXmlDocument.CreateElement("cfdi:Addenda", "https://edixcfisecure.ekomercio.com/esquemas") 'ParentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") 'ParentElement.SetAttribute("xsi:schemaLocation", "https://edixcfisecure.ekomercio.com/esquemas https:/edixcfdisecure.ekomercio.com/esquemas/7Eleven.xsd") 'Dim Prov As XmlElement = MyXmlDocument.CreateElement("cfdi:Proveedor", "") 'Prov.SetAttribute("Clave", "3125") 'Dim ns As String = "cfdi" 'MyXmlDocument.DocumentElement.GetNamespaceOfPrefix("cfdi") 'Dim Recepciones As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepciones") 'Recepciones.Prefix = "cfdi" 'Dim Recepcion As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepcion") 'Recepcion.SetAttribute("folio", Txt7ElevenFolio.Text.Trim) 'Recepcion.SetAttribute("tienda", Txt7ElevenTienda.Text.Trim) 'Recepcion.SetAttribute("fecha", Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-dd-MM")) 'Dim Productos As XmlElement = MyXmlDocument.CreateElement("cfdi:Productos") ''dentro de un ciclo 'Dim Producto As XmlElement = MyXmlDocument.CreateElement("cfdi:Producto") 'Producto.SetAttribute("codigo", "cod1") 'Producto.SetAttribute("descripcion", "prod1") 'Producto.SetAttribute("cantidad", "99") 'Producto.SetAttribute("precio", "2000") 'Productos.AppendChild(Producto) ''fin de ciclo 'Recepcion.AppendChild(Productos) 'Recepciones.AppendChild(Recepcion) 'ParentElement.AppendChild(Prov) 'ParentElement.AppendChild(Recepciones) 'MyXmlDocument.DocumentElement.AppendChild(ParentElement) 'MyXmlDocument.Save("C:/Temp/aa.xml") End Sub Protected Sub DdlFuenteRecaudacion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFuenteRecaudacion.SelectedIndexChanged For Each dr As DataRow In TmpDT.Rows dr("CvePresupuestoIngreso") = DdlFuenteRecaudacion.SelectedValue Next GvPS.DataSource = TmpDT GvPS.DataBind() UpPS.Update() End Sub Protected Sub DdlFR_SelectedIndexChanged(sender As Object, e As EventArgs) Dim DdlFR_Gv As DropDownList = CType(sender, DropDownList) Dim index As Integer = CType(DdlFR_Gv.NamingContainer, GridViewRow).FCLiteral("LtlConsecutivo").Text.ToString().ToEntero() If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.Empresa.UsaAC Then TmpDT(index - 1)("CvePresupuestoIngreso") = DdlFR_Gv.SelectedValue End If TmpDT.AcceptChanges() End Sub Protected Sub LnkASN_Click(sender As Object, e As EventArgs) Handles LnkASN.Click If TxtFordASN.Text.Trim.Length > 20 Then Alert("Maximo 20 Caracteres", TipoMensaje.MsgAdvertencia) : Exit Sub LstFordASN.Items.Add(New ListItem(TxtFordASN.Text.Trim)) TxtFordASN.Text = "" TxtFordASN.Focus() End Sub Protected Sub LnkFordQuitar_Click(sender As Object, e As EventArgs) Handles LnkFordQuitar.Click LstFordASN.Items.RemoveAt(LstFordASN.SelectedIndex) End Sub Private Sub LnkImprimir_Click(sender As Object, e As EventArgs) Handles LnkImprimir.Click GeneraPDFCot(TxtFecha.Text.Trim.ToDate, Nothing, VentaFolio, False, False) End Sub Protected Sub TxtCodigo_TextChanged(sender As Object, e As System.EventArgs) Handles TxtCodigo.TextChanged Dim ObjClientes As New ClsClientes() Dim Nombre As String = "-1" Dim Codigo As String = "-1" Dim NombreCorto As String = "-1" Dim RFC As String = "-1" Dim Telefono As String = "-1" Dim Mail As String = "-1" If TxtCodigo.Text.Trim <> String.Empty Then Codigo = TxtCodigo.Text.Trim If Codigo <> "-1" Then If ObjClientes.GetClientes(-1, Nombre, Codigo, NombreCorto, RFC, Telefono, Mail, -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then If ObjClientes.DtResultados.Rows.Count > 0 Then If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not ObjClientes.CveCliente.Contiene(10450, 10460, 10458) Then TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False UpFacturar.Update() Exit Sub ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not ObjClientes.CveCliente.Contiene(27448) Then TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False UpFacturar.Update() Exit Sub Else HdnCveCliente.Value = ObjClientes.CveCliente.ToString() End If BtnBuscarCliente_Click(sender, e) Else Alert("No se encontró el cliente con el código: " & TxtCodigo.Text.Trim & ".", Extensiones.TipoMensaje.MsgAdvertencia) TxtCodigo.Text = "" LblCliente.Text = "Cliente" LblDireccion.Text = "Dirección" LblColonia.Text = "Colonia" LblCiudad.Text = "Ciudad" LblEstado.Text = "Estado" LblCP.Text = "00000" LblRFC.Text = "AAA010101AAA" LblTelefono.Text = "9999999999" trsucursalciente.Visible = False End If End If ObjClientes.Dispose() End If End Sub Protected Sub TxtFolio_TextChanged(sender As Object, e As System.EventArgs) Handles TxtFolio.TextChanged ViewState("EstablecioFolio") = True Alert("Se estableció el Folio Fijo para el nuevo documento.") 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 Protected Sub LnkAgregarSucursal_Click(sender As Object, e As EventArgs) RegistraScript("showDivAgregarSucursal();") End Sub Protected Sub BtnAgregar_Click(sender As Object, e As System.EventArgs) Handles BtnAgregarSucursal.Click Dim LT As String = "0" Dim LG As String = "0" If CveCliente > 0 Then Dim ObjCliente As New ClsClientes Try If ObjCliente.AddSucursal(CveCliente, TxtNombreSucursal.Text.Trim, UsuarioActual.CveUsuario, TxtCiudadSucursal.Text.Trim, TxtColoniaSucursal.Text.Trim, TxtCPSucursal.Text.Trim, TxtDireccionSucursal.Text.Trim, TxtEstadoSucursal.Text.Trim, TxtLocalidadSucursal.Text.Trim, TxtPaisSucursal.Text.Trim, TxtNumExtSucursal.Text.Trim, TxtNumIntSucursal.Text.Trim, TxtTelefonoSucursal.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", ""), TxtCorreoSucursal.Text.Trim, "", "", DdlVendedorSucursal.SelectedValue.ToEntero, "", -1, 0, -1, DdlSucursalUsoCFDI.SelectedValue.ToEntero, -1, -1, LT:=LT, LG:=LG, RFC:=TxtRFCSucursal.Text.Trim()) Then TxtNombreSucursal.Text = "" TxtCiudadSucursal.Text = "" TxtColoniaSucursal.Text = "" TxtCPSucursal.Text = "" TxtDireccionSucursal.Text = "" TxtEstadoSucursal.Text = "" TxtLocalidadSucursal.Text = "" TxtPaisSucursal.Text = "" TxtNumExtSucursal.Text = "" TxtNumIntSucursal.Text = "" TxtTelefonoSucursal.Text = "" TxtCorreoSucursal.Text = "" DdlVendedorSucursal.SelectedIndex = 0 DdlSucursalUsoCFDI.SelectedIndex = 0 Alert("La nueva Sucursal del Cliente se guardó correctamente.", TipoMensaje.MsgInformacion) 'VUELVE A CARGAR LAS SUCURSALES 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() End If Catch ex As Exception OnError("Ocurrió un error al agregar la sucursal", ex) End Try ObjCliente.Dispose() End If UpCliente.Update() RegistraScript("hideDivAgregarSucursal();") End Sub Private Sub ConfiguraTipoDocto() 'Esconde Todo TdOrdenPago.Visible = False Tr33.Visible = False 'si tiene la funcionalidad que se active independiente del tipo de documento RMF 15-10-2017 Tr33.Visible = True If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then BtnEmitirImprimir.Text = "Emitir e Imprimir" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then BtnEmitirImprimir.Text = "Emitir e Imprimir" 'TdReferencia.Style.Remove("display") ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then BtnEmitirImprimir.Text = "Registrar" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC", "PA", "Pd2") Then BtnEmitirImprimir.Text = "Registrar" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue = "Cot" Then BtnEmitirImprimir.Text = "Cotizar" 'TdReferencia.Style.Add("display", "none") 'FACTURACION 3.3 Tr33.Visible = True ElseIf DdlTipoComprobante.SelectedValue = "Com" Then BtnEmitirImprimir.Text = "Registrar" 'TdReferencia.Style.Add("display", "none") ElseIf DdlTipoComprobante.SelectedValue.ToString() = "OP" Then BtnEmitirImprimir.Text = "Registrar" TdOrdenPago.Visible = True End If UpFacturar.Update() End Sub Private Sub EliminaPoliza() 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 TraspasoAlmacen(ByRef ObjInventario As ClsInventarios, ByRef ObjVentas As ClsVentas, CveRemision As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer, TmpDTDetalle As DataTable) As Boolean Dim OcurrioError As Boolean = False Try Dim DtMovimientos As DataTable Dim DtMovimientosDetalles As DataTable DtRemConceptosSurtidos = Nothing Dim TieneMovimientosServicioDomicilio As Boolean = False Dim TieneMovimientosSinCosto As Boolean = False Dim TieneMovimientosContrato As Boolean = False 'Obtenemos los movimientos detalle If ObjInventario.GetInv_Mov(CveRemision, UsuarioActual.CveEmpresa) Then If ObjInventario.DtResultados.Rows.Count > 0 Then DtMovimientos = ObjInventario.DtResultados.FiltraParametros("", DistinctColumns:={"CveMovimiento"}) 'Si estamos facturando remisiones ajustamos por ventadetalle If RemisionesLista.Count > 0 AndAlso DtRemisionesTmpDT IsNot Nothing AndAlso DtRemisionesTmpDT.Rows.Count > 0 AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then Dim resultados = From DtRemisiones In DtRemisionesTmpDT Join DtMovDet In ObjInventario.DtResultados.FiltraParametros("CvePS > 0") On DtRemisiones("CveVentaDetalleRemision").ToString().ToEntero() Equals DtMovDet("CveVentaDetalle").ToString().ToEntero() Select DtMovDet Try If resultados.Count > 0 Then DtMovimientosDetalles = resultados.CopyToDataTable Else DtMovimientosDetalles = New DataTable End If Catch ex As Exception GuardaLog($"LOG IPP: Ventas LN: 10033. - DtRemisionesTmpDT.Rows.Count: {DtRemisionesTmpDT.Rows.Count} - ObjInventario.DtResultados.FiltraParametros('CvePS > 0').Rows.Count: {ObjInventario.DtResultados.FiltraParametros("CvePS > 0").Rows.Count} Ex:{ex.Message}") DtMovimientosDetalles = New DataTable End Try 'SE FILTRAN LOS MOVIMIENTOS DE LA PARTE QUE SE FACTURA DE LA REMISION DtMovimientos = DtMovimientosDetalles.FiltraParametros("", DistinctColumns:={"CveMovimiento"}) Else DtMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0") End If 'VALIDAR SI TIENE PRODUCTOS POR TRASPASAR If DtMovimientos.Rows.Count > 0 Then Dim GeneroMovimientoAlmacen As Boolean = False TieneMovimientosServicioDomicilio = DtMovimientosDetalles.COUNT("CveTipoAlmacen", "CveTipoAlmacen=29") > 0 TieneMovimientosSinCosto = DtMovimientosDetalles.COUNT("CveTipoAlmacen", "CveTipoAlmacen=26") > 0 TieneMovimientosContrato = DtMovimientosDetalles.COUNT("CveTipoAlmacen", "CveTipoAlmacen IN (11)") > 0 For Each dr As DataRow In DtMovimientos.Rows 'VERIFICA SI YA SE GENERARON LAS SALIDAS DE ALMACEN NECESARIAS If DtRemConceptosSurtidos IsNot Nothing Then If DtRemConceptosSurtidos.SUMD("Surtido") = DtRemConceptosSurtidos.SUMD("Cantidad") Then Exit For End If End If 'Obtenemos los Movimientos de salida If ObjInventario.GetMovimientos(dr("CveMovimiento").ToString().ToEntero(), ConceptoMovimiento, -1, UsuarioActual.CveEmpresa) Then If ObjInventario.DtResultados.Rows.Count > 0 AndAlso DtMovimientosDetalles.Rows.Count > 0 Then Dim RowMovimiento As DataRow = ObjInventario.DtResultados(0) Dim CveAlmacenSalida As Integer = RowMovimiento("CveAlmacen").ToString().ToEntero() Dim CveAlmacenEntrada As Integer = RowMovimiento("CveAlmacenRelacionado").ToString().ToEntero() Dim CveMoneda As Integer = RowMovimiento("CveMoneda").ToString().ToEntero() Dim CveTipoAlmacen As Integer = RowMovimiento("CveTipoAlmacen").ToString().ToEntero() If (CveAlmacenEntrada > 0 AndAlso CveTipoAlmacen <> 1) Or RemisionesLista.Count = 0 Then 'Con remisiones parciales ignoramos las surtidas ya realizadas Dim MovDetalle As New DataTable Dim AplicaMovimientoDetalleEntrada As Boolean = False If RemisionesLista.Count > 0 Then AplicaMovimientoDetalleEntrada = True If TieneMovimientosSinCosto OrElse TieneMovimientosServicioDomicilio Then MovDetalle = DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}") Else If TieneMovimientosContrato Then MovDetalle = CuadrarFacturaMovimientos(ObjVentas, CveRemision, DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}")) Else MovDetalle = CuadrarFacturaMovimientos(ObjVentas, CveRemision, DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")} AND (TieneSalidaxFactura IS NULL OR SaldoAlmacen > 0)")) End If End If Else MovDetalle = DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}") End If If ErrorList.Count = 0 AndAlso MovDetalle.Rows.Count > 0 Then Dim CveMovimientoSalidaPorTraspaso As Integer = -1 Dim CveConceptoSalidaAlmacen As Integer = 3 Dim CveAlmacenParaSalida As Integer = CveAlmacenEntrada 'SALIDA DEFINITIVA DEL SISTEMA If UsuarioActual.Empresa.Funcionalidad(575) = "1" Then CveConceptoSalidaAlmacen = 40 CveAlmacenParaSalida = CveAlmacenSalida AplicaMovimientoDetalleEntrada = True Else 'Le damos salida de apartado por traspaso CveMovimientoSalidaPorTraspaso = GenerarMovimientoAlmacen(ObjInventario, MovDetalle, CveAlmacenSalida, 8, CveMoneda, CveRemision, AplicaMovimientoDetalleEntrada:=AplicaMovimientoDetalleEntrada, ObjConta:=ObjConta) If Not CveMovimientoSalidaPorTraspaso > 0 Then OcurrioError = True Exit For End If 'Le damos entrada al general por traspaso If Not OcurrioError Then GeneroMovimientoAlmacen = GenerarMovimientoAlmacen(ObjInventario, MovDetalle, CveAlmacenEntrada, 9, CveMoneda, CveRemision, CveMovimientoRelacionado:=CveMovimientoSalidaPorTraspaso, AplicaMovimientoDetalleEntrada:=AplicaMovimientoDetalleEntrada, ObjConta:=ObjConta) > 0 If Not GeneroMovimientoAlmacen Then OcurrioError = True Exit For End If End If End If 'Le damos salida normal If ConSalida AndAlso Not OcurrioError Then If Not OcurrioError Then Dim CveMovimientoSalidaAlmacen As Integer = GenerarMovimientoAlmacen(ObjInventario, MovDetalle, CveAlmacenParaSalida, CveConceptoSalidaAlmacen, CveMoneda, ObjFactura.CveVenta, AplicaMovimientoDetalleEntrada:=AplicaMovimientoDetalleEntrada, MovimientoPrePoliza:=True, ObjConta:=ObjConta) GeneroMovimientoAlmacen = CveMovimientoSalidaAlmacen > 0 If Not GeneroMovimientoAlmacen Then OcurrioError = True Exit For End If If Not OcurrioError AndAlso UsuarioActual.Empresa.Funcionalidad(573) = "1" Then OcurrioError = Not GenerarMovimientoAlmacenVirtual(TmpDTDetalle, CveMovimientoSalidaAlmacen, CveAlmacenParaSalida, ObjInventario, ObjConta:=ObjConta) End If End If End If End If MovDetalle.Dispose() If OcurrioError Then Exit For End If End If End If End If If OcurrioError Then Exit For End If Next 'VERIFICA QUE SE HAYA GENERADO MOVIMIENTO DE ALMACEN If Not OcurrioError Then OcurrioError = Not GeneroMovimientoAlmacen End If 'VERIFICA SI YA SE GENERARON LAS SALIDAS DE ALMACEN NECESARIAS If Not OcurrioError AndAlso RemisionesLista.Count > 0 AndAlso DtRemConceptosSurtidos IsNot Nothing Then If DtRemConceptosSurtidos.SUMD("Surtido") <> DtRemConceptosSurtidos.SUMD("Cantidad") Then OcurrioError = True End If End If End If End If Else OcurrioError = True End If 'LIMPIAR EL DT DE CONCEPTOS SURTIDOS If DtRemConceptosSurtidos IsNot Nothing Then DtRemConceptosSurtidos.Clear() DtRemConceptosSurtidos = Nothing End If Catch ex As Exception OcurrioError = True OnError("Ocurrió un error al realizar el traspaso", ex) End Try Return Not OcurrioError End Function 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 Double = 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 Private Function SalidaEntradaAlmacen(ByRef ObjInventario As ClsInventarios, CveRemision As Integer, ByRef ObjConta As ClsContabilidad) As Boolean Dim OcurrioError As Boolean = False Dim DtMovimientos As DataTable Dim DtMovimientosDetalles As DataTable 'Obtenemos los movimientos detalle If ObjInventario.GetInv_Mov(CveRemision, UsuarioActual.CveEmpresa) Then If ObjInventario.DtResultados.Rows.Count > 0 Then DtMovimientos = ObjInventario.DtResultados.FiltraParametros("", DistinctColumns:={"CveMovimiento"}) DtMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0") For Each dr As DataRow In DtMovimientos.Rows 'Obtenemos los Movimientos de salida If ObjInventario.GetMovimientos(dr("CveMovimiento").ToString().ToEntero(), 3, -1, UsuarioActual.CveEmpresa) Then Dim CveAlmacenSalida As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString().ToEntero() Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString().ToEntero() 'Le damos entrada If Not GenerarMovimientoAlmacen(ObjInventario, DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}"), CveAlmacenSalida, 2, CveMoneda, CveRemision) > 0 Then OcurrioError = True End If End If Next End If End If Return Not OcurrioError End Function Private Function GenerarMovimientoAlmacen(ByRef ObjInventario As ClsInventarios, DtMovDetalle As DataTable, CveAlmacen As Integer, ConceptoEntrada As Integer, CveMoneda As Integer, CveVenta As Integer, Optional MovimientoPrePoliza As Boolean = True, Optional ByRef ObjConta As ClsContabilidad = Nothing, Optional CveMovimientoRelacionado As Integer = -1, Optional AplicaMovimientoDetalleEntrada As Boolean = False, Optional ObjContPaq As ClsContPAQi = Nothing) As Integer Dim OcurrioError As Boolean = False Dim ContadorMovtosDetalles = 0 'If Not AplicaMovimientoDetalleEntrada Then ' Dim rowa As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen={0}", CveAlmacen)) ' If Not IsNothing(rowa) AndAlso rowa("CveTipoAlmacen").ToString() = "10" Then ' AplicaMovimientoDetalleEntrada = True ' End If 'End If 'Creamos el movimiento Dim CveMovimientoInventario As Integer = ObjInventario.AddMovimiento(CveAlmacen, ConceptoEntrada, CveMoneda, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, CveMovimientoRelacionado:=CveMovimientoRelacionado, Modulo:="Vta/E4") If CveMovimientoInventario > 0 Then 'Agregamos los detalles For Each MovDet As DataRow In DtMovDetalle.Rows Dim Cantidad = 0.0 Dim CantidadRemision = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={MovDet("CveVentaDetalle").ToString()}").ToDouble Dim CantidadInventario = MovDet("Cantidad").ToString().ToDecimal If RemisionesLista.Count > 0 AndAlso ChkRemProductos.Checked AndAlso CantidadInventario >= CantidadRemision Then Cantidad = CantidadRemision Else Cantidad = CantidadInventario End If Dim CveUnidad As Integer = MovDet("CveUM").ToString().ToEntero() Dim PU As Decimal = MovDet("PU").ToString().ToDecimal Dim CveProducto As Integer = MovDet("CvePS").ToString().ToEntero() Dim Serie As String = MovDet("Serie").ToString() Dim Lote As String = MovDet("Lote").ToString() Dim FechaCaducidad As Date = MovDet("FechaCaducidad").ToString.ToDate Dim CveSeccionAlmacen As Integer = -3 'SE DEBE CALCULAR LA SECCION EL EN TRIGGER DE INVENTARIOS Dim Consec As Integer = DtRemisionesTmpDT.FiltroPrimeroValor("Consec", $"CveVentaDetalle = {MovDet("CveVentaDetalle").ToString()}").ToEntero() 'COMIENZA: VENTADETALLE 'CUANDO SEA SALIDA VA POR LA VENTA DETALLE DE LA FACTURA DE LA REMISION - OJO!! SOLO FUNCIONA HASTA ORITA QUE SE HACE SALIDA SOLO CUANDO SE FACTURA LA REMISION Dim CveVentaDetalle = If(ConceptoEntrada.Contiene(3, 40), TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"Consec={Consec}").ToEntero(), MovDet("CveVentaDetalle").ToString().ToEntero()) Dim CveVentaDetalleRemision As Integer = -1 If ConceptoEntrada = 40 AndAlso MovDet("CveVentaDetalle").ToString().ToEntero() > 0 Then CveVentaDetalleRemision = MovDet("CveVentaDetalle").ToString().ToEntero() End If 'If ConceptoEntrada = 3 Then ' CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"Consec={Consec}").ToEntero() 'ElseIf ConceptoEntrada = 40 Then ' CveVentaDetalle = MovDet("CveVentaDetalle").ToString().ToEntero() ' CveVentaDetallePadre = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"Consec={Consec}").ToEntero() ' 'CUANDO LA VENTADETALLE NO TENGA VALOR DEBE MARCAR ERROR, NUEVA RESTRICCION DE ALMACEN ' If CveVentaDetallePadre < 0 Then ' Alert("no se encontro la venta detalle nueva. Por favor comuniquese con atención SIG.", TipoMensaje.ToastError) ' OcurrioError = True ' Exit For ' End If 'Else ' CveVentaDetalle = MovDet("CveVentaDetalle").ToString().ToEntero() 'End If 'CUANDO LA VENTADETALLE NO TENGA VALOR DEBE MARCAR ERROR, NUEVA RESTRICCION DE ALMACEN If CveVentaDetalle < 0 Then Alert("no se encontro la venta detalle. Por favor comuniquese con atención SIG.", TipoMensaje.ToastError) OcurrioError = True Exit For End If 'TERMINA: VENTADETALLE If Cantidad < 0 Then Alert("Ocurrió un Error al generar los movimientos de almacén. Por favor comuniquese con atención SIG.", TipoMensaje.MsgError) OcurrioError = True Exit For End If 'CUANDO SEA REMISION FACTURADA DEBE RELACIONAR LOS NUEVOS MOVIMIENTOS POR EL DETALLE Dim CveMovimientoDetalleEntrada As Integer = -1 If AplicaMovimientoDetalleEntrada Then CveMovimientoDetalleEntrada = MovDet("CveMovimientoDetalle").ToString().ToEntero() End If If ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, Cantidad, CveUnidad, CveProducto, PU, -1, CveSeccionAlmacen:=CveSeccionAlmacen, Serie:=Serie, Lote:=Lote, FechaCaducidad:=FechaCaducidad, CveVentaDetalle:=CveVentaDetalle, CveMovimientoDetalleEntrada:=CveMovimientoDetalleEntrada, CveVentaDetalleRemision:=CveVentaDetalleRemision) Then ContadorMovtosDetalles += 1 Else OcurrioError = True Exit For End If Next 'Agregamos las PrePolizas If Not OcurrioError Then If MovimientoPrePoliza AndAlso CveMovimientoInventario > 0 Then 'OcurrioError = Not GeneraPrePolizaMovimientoAlmacen(ObjInventario, ObjConta, ObjContPaq, ObjFactura, ObjFactura.CvePrePoliza, CveMovimientoInventario, CveAlmacen) If ObjInventario.GetMovimientosDetalle(CveMovimientoInventario, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then Dim DtCostos = ObjInventario.DtResultados.Copy Dim DtCostosDistinct As DataTable = ObjInventario.DtResultados.FiltraParametros("", "", {"CveClasificacion"}) Dim IdCtaContable As Integer = 0 Dim ValorInventario As Decimal Dim TotalCostoAcumulado As Decimal = 0D Dim Cont As Integer = 1 Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL Dim TipoMovto69 As Boolean = False 'SI ES MOVIMIENTO DE ENTRADA CAMBIAR LA NATURALEZA DEL MOVIMIENTO If ConceptoEntrada.Contiene(9) Then TipoMovto69 = True End If For Each RowInv As DataRow In DtCostosDistinct.Rows ValorInventario = DtCostos.SUMD("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).RoundSQL IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() TotalCostoAcumulado += ValorInventario 'cuando es el último movimiento y hay diferencias en los importes If Cont = DtCostosDistinct.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) End If Try 'If ValorInventario <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovto69, ValorInventario, ValorInventario, 69, ObjFactura.SerieFolio, ObjFactura.SerieFolio, IdCtaContable, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString().ToEntero(), CveMovimientoAlmacen:=CveMovimientoInventario, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True Exit For End If 'End If Catch ex As Exception OcurrioError = True ModExtensiones.GuardaLog("Error inesperado (15147)." + ex.ToString()) Alert("Error inesperado (15147). Por favor comuniquese con atención SIG.", TipoMensaje.ToastError) End Try Cont += 1 Next If Not OcurrioError Then IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacen)).ToEntero() If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovto69, TotalCosto, TotalCosto, 68, ObjFactura.SerieFolio, ObjFactura.SerieFolio, IdCtaContable, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveMovimientoAlmacen:=CveMovimientoInventario, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True End If End If Else OcurrioError = True End If End If End If 'VALIDA QUE SE HALLAN AGREGADO DETALLES AL MOVIMIENTO If ContadorMovtosDetalles = 0 Then OcurrioError = True End If Else OcurrioError = True End If If OcurrioError Then Return -1 Else Return CveMovimientoInventario End If 'Return Not OcurrioError End Function Private Function GeneraPrePolizaMovimientoAlmacen(ByRef ObjInventario As ClsInventarios, ByRef ObjConta As ClsContabilidad, ByRef ObjContPaq As ClsContPAQi, ObjFactura As Modelos.Factura, CvePrePoliza As Integer, CveMovimientoInventario As Integer, CveAlmacen As Integer) As Boolean Dim OcurrioError As Boolean = False Dim GenerarPrePolizaNueva As Boolean = False Try Dim DtCostos As DataTable = Nothing Dim DtCostosDistinct As DataTable = Nothing Dim IdCtaContable As Integer = 0 Dim CveCuenta As Integer = 0 Dim ValorInventario As Decimal = 0D Dim TotalCostoAcumulado As Decimal = 0D Dim Cont As Integer = 1 If ObjInventario.GetMovimientosDetalle(CveMovimientoInventario, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then DtCostos = ObjInventario.DtResultados.Copy DtCostosDistinct = ObjInventario.DtResultados.FiltraParametros("", "", {"CveClasificacion"}) Else OcurrioError = True End If If OcurrioError Then Return Not OcurrioError End If Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL If CvePrePoliza <= 0 Then GenerarPrePolizaNueva = True CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GeneraMovimientoAlmacen", ObjFactura.CvePlantillaPoliza, TotalCosto, TotalCosto, ObjFactura.CveMoneda, ObjFactura.Fecha, If(CveEmpresaCRM > 0, LblEmpresaCRM.Text, ObjFactura.Cliente.Nombre), ObjFactura.CveUsuario, UsuarioActual.CveEmpresa) If CvePrePoliza <= 0 Then OcurrioError = True Return Not OcurrioError End If End If For Each RowInv As DataRow In DtCostosDistinct.Rows ValorInventario = DtCostos.SUMD("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).RoundSQL IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() TotalCostoAcumulado += ValorInventario 'cuando es el último movimiento y hay diferencias en los importes If Cont = DtCostosDistinct.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) End If Try 'If ValorInventario <> 0 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString().ToEntero(), CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True Exit For End If 'End If Catch ex As Exception OcurrioError = True Alert("Error inesperado (15147). Por favor comuniquese con atención SIG.", TipoMensaje.ToastError) End Try Cont += 1 Next If Not OcurrioError Then IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacen)).ToEntero() If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, TotalCosto, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=TotalCosto, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True End If End If If GenerarPrePolizaNueva Then Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" AutoConta = AutocontaMatriz(AutoConta) If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Rem", "RNC", "Cot", "Ped", "Pd2", "PA", "Egs", "Dev") Then AutoConta = False End If If AutoConta Then If idCuentaContabilizacion > 0 Then If Not ObjConta.ContabilizarPrePoliza(ObjFactura.CvePrePoliza, ObjFactura.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then Alert("Ocurrio un Error al contabilizar la prepoliza de almacen, pongase en contacto con Soporte Técnico", TipoMensaje.MsgError) End If Else Alert(String.Format("Falta asignación de las siguientes cuentas contables: {0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia) End If End If End If Catch ex As Exception OnError("Ocurrió un error al generar la prepoliza del movimiento de almacen", ex) OcurrioError = True End Try Return Not OcurrioError End Function Private Function GenerarMovimientoAlmacenVirtual(TmpDTDetalle As DataTable, CveMovimientoSalidaAlmacen As Integer, CveAlmacen As Integer, ByRef ObjInventario As ClsInventarios, Optional ByRef ObjConta As ClsContabilidad = Nothing) As Boolean Dim OcurrioError As Boolean = False Try Dim CveMovimientoVirtual As Integer = -1 Dim CveAlmacenVirtual As Integer = -1 Dim CveConceptoMovimientoVirtual As Integer = 37 Dim DtPSVirtual As DataTable = Nothing CveAlmacenVirtual = GlobalDTAlmacen(UsuarioActual.CveEmpresa, CveAlmacen:=CveAlmacen).FiltroPrimeroValor("CveAlmacenVirtual").ToEntero() 'SI TIENE ALMACEN VIRTUAL ASIGNADO GENERA EL MOVIMIENTO VIRTUAL If CveAlmacenVirtual > 0 Then If ObjInventario.GetMovimientosDetalleVirtual(CveMovimientoSalidaAlmacen, UsuarioActual.CveEmpresa) Then DtPSVirtual = ObjInventario.DtResultados.Copy() Else OcurrioError = True End If If Not OcurrioError AndAlso DtPSVirtual IsNot Nothing AndAlso DtPSVirtual.Rows.Count > 0 Then CveMovimientoVirtual = ObjInventario.AddMovimiento(CveAlmacenVirtual, CveConceptoMovimientoVirtual, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, ObjFactura.CveVenta, -1, -1, Modulo:="Vta/VV2", CveMovimientoRelacionado:=CveMovimientoSalidaAlmacen) If CveMovimientoVirtual > 0 Then For Each RowUsado As DataRow In DtPSVirtual.Rows Dim CvePS = RowUsado("CvePS").ToString().ToEntero() Dim CantidadUsado As Double = RowUsado("Cantidad").ToString().ToDouble() Dim PU As Decimal = RowUsado("Cargo").ToString().ToDecimal() Dim CveUM As Integer = RowUsado("CveUM").ToString().ToEntero() Dim CveVentaDetalle As Integer = -1 'RELACIONA LA VENTA DETALLA DE LA REMISION If TmpDTDetalle IsNot Nothing Then CveVentaDetalle = TmpDTDetalle.FiltroPrimeroValor("CveVentaDetalle", $"Cantidad = {RowUsado("Cantidad")} AND CvePS = {RowUsado("CvePS")}").ToEntero() End If If Not ObjInventario.AddMovimientoDetalle(CveMovimientoVirtual, CantidadUsado, CveUM, CvePS, PU, -1, CveVentaDetalle:=CveVentaDetalle) Then OcurrioError = True Exit For End If Next Else OcurrioError = True End If 'Agregamos las PrePolizas If Not OcurrioError Then If CveMovimientoVirtual > 0 Then 'OcurrioError = Not GeneraPrePolizaMovimientoAlmacen(ObjInventario, ObjConta, ObjContPaq, ObjFactura, ObjFactura.CvePrePoliza, CveMovimientoInventario, CveAlmacen) If ObjInventario.GetMovimientosDetalle(CveMovimientoVirtual, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then Dim DtCostos = ObjInventario.DtResultados.Copy Dim DtCostosDistinct As DataTable = ObjInventario.DtResultados.FiltraParametros("", "", {"CveClasificacion"}) Dim IdCtaContable As Integer = 0 Dim CveCuenta As Integer = 0 Dim ValorInventario As Decimal Dim TotalCostoAcumulado As Decimal = 0D Dim Cont As Integer = 1 Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL For Each RowInv As DataRow In DtCostosDistinct.Rows ValorInventario = DtCostos.SUMD("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).RoundSQL IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() TotalCostoAcumulado += ValorInventario 'cuando es el último movimiento y hay diferencias en los importes If Cont = DtCostosDistinct.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) End If Try 'If ValorInventario <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString().ToEntero(), CveMovimientoAlmacen:=CveMovimientoVirtual, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True Exit For End If 'End If Catch ex As Exception OcurrioError = True Alert("Error inesperado (15148). Por favor comuniquese con atención SIG.", TipoMensaje.ToastError) End Try Cont += 1 Next If Not OcurrioError Then IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacenVirtual)).ToEntero() If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, TotalCosto, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveMovimientoAlmacen:=CveMovimientoVirtual, ImporteMX:=TotalCosto, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True End If End If Else OcurrioError = True End If End If End If End If Else Alert("No se tiene definido el almacen virtual.") OcurrioError = True End If Catch ex As Exception OnError("Ocurrió un error al generar el almacen virtual.", ex) OcurrioError = True End Try Return Not OcurrioError End Function Private Function GenerarMovimientoAlmacenVirtualConsignacion(CveVenta As Integer, CveAlmacenContrato As Integer, ByRef ObjInventario As ClsInventarios, ObjFactura As Modelos.Factura, Optional ByRef ObjConta As ClsContabilidad = Nothing) As Boolean Dim OcurrioError As Boolean = False If UsuarioActual.Empresa.Funcionalidad(573) = "1" Then Try Dim CveMovimientoVirtual As Integer = -1 Dim CveAlmacenVirtual As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa, CveAlmacen:=CveAlmacenContrato).FiltroPrimeroValor("CveAlmacenVirtual").ToEntero() Dim CveConceptoMovimientoVirtual As Integer = 37 Dim DtPSVirtual As DataTable = Nothing Dim DtTamanios As DataTable = Nothing Dim CveMovimientoReferencia As Integer = -1 Dim CveSubProyecto As Integer = -1 'SI TIENE UN ALMACEN VIRTUAL GENERA EL MOVIMIENTO If CveAlmacenVirtual > 0 Then If ObjInventario.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then Dim RowMovimiento As DataRow = ObjInventario.DtResultados.FiltroPrimero("CvePS IS NULL AND ((CveTipoAlmacen = 24 AND CveConcepto = 2) OR (CveTipoAlmacen = 17 AND CveConcepto = 8)) AND CveVenta > 0") If RowMovimiento IsNot Nothing Then CveMovimientoReferencia = RowMovimiento("CveMovimiento").ToString().ToEntero() Else OcurrioError = True End If Else OcurrioError = True End If If ObjInventario.GetMovimientosDetalleVirtual(CveMovimientoReferencia, UsuarioActual.CveEmpresa) Then DtPSVirtual = ObjInventario.DtResultados.Copy() Else OcurrioError = True End If If Not OcurrioError AndAlso DtPSVirtual.Rows.Count > 0 Then CveMovimientoVirtual = ObjInventario.AddMovimiento(CveAlmacenVirtual, CveConceptoMovimientoVirtual, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, ObjFactura.CveVenta, -1, -1, Modulo:="Vta/VV", CveMovimientoRelacionado:=CveMovimientoReferencia) If CveMovimientoVirtual > 0 Then For Each RowUsado As DataRow In DtPSVirtual.Rows Dim CvePS = RowUsado("CvePS").ToString().ToEntero() Dim CantidadUsado As Double = RowUsado("Cantidad").ToString().ToDouble() Dim PU As Decimal = RowUsado("Cargo").ToString().ToDecimal() Dim CveUM As Integer = RowUsado("CveUM").ToString().ToEntero() If Not ObjInventario.AddMovimientoDetalle(CveMovimientoVirtual, CantidadUsado, CveUM, CvePS, PU, -1) Then OcurrioError = True Exit For End If Next Else OcurrioError = True End If 'Agregamos las PrePolizas If Not OcurrioError Then If CveMovimientoVirtual > 0 Then 'OcurrioError = Not GeneraPrePolizaMovimientoAlmacen(ObjInventario, ObjConta, ObjContPaq, ObjFactura, ObjFactura.CvePrePoliza, CveMovimientoInventario, CveAlmacen) If ObjInventario.GetMovimientosDetalle(CveMovimientoVirtual, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then Dim DtCostos = ObjInventario.DtResultados.Copy Dim DtCostosDistinct As DataTable = ObjInventario.DtResultados.FiltraParametros("", "", {"CveClasificacion"}) Dim IdCtaContable As Integer = 0 Dim CveCuenta As Integer = 0 Dim ValorInventario As Decimal Dim TotalCostoAcumulado As Decimal = 0D Dim Cont As Integer = 1 Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL For Each RowInv As DataRow In DtCostosDistinct.Rows ValorInventario = DtCostos.SUMD("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).RoundSQL IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero() TotalCostoAcumulado += ValorInventario 'cuando es el último movimiento y hay diferencias en los importes If Cont = DtCostosDistinct.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) End If Try 'If ValorInventario <> 0 Then If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString().ToEntero(), CveMovimientoAlmacen:=CveMovimientoVirtual, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True Exit For End If 'End If Catch ex As Exception OcurrioError = True Alert("Error inesperado (15148). Por favor comuniquese con atención SIG.", TipoMensaje.ToastError) End Try Cont += 1 Next If Not OcurrioError Then IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacenVirtual)).ToEntero() If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, TotalCosto, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveMovimientoAlmacen:=CveMovimientoVirtual, ImporteMX:=TotalCosto, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then OcurrioError = True End If End If Else OcurrioError = True End If End If End If End If End If Catch ex As Exception OnError("Ocurrió un error al generar el almacen virtual.", ex) OcurrioError = True End Try End If Return Not OcurrioError End Function Private Function SalidaAlmacenMateriales(ByRef ObjInventario As ClsInventarios, CveOS As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer) As Boolean Dim TieneError As Boolean = False Dim CveMovimientoSalida = 0 Dim CveMovimientoEntrada = 0 Dim CveMovimientoSalida2 = 0 Dim CveMovimientoEntrada2 = 0 Dim CveMovimientoSalida3 = 0 Dim CveMovimientoEntrada3 = 0 Dim AlmacenEntrada = -1 Dim FolioSalida = 0 Dim FolioEntrada = 0 Dim TextoError = "" Dim TextoExistencia As StringBuilder = New StringBuilder 'Obtenemos los movimientos detalle If ObjInventario.GetMovimientosOS(9, CveOS, UsuarioActual.CveEmpresa) Then If ObjInventario.DtResultados.Rows.Count > 0 Then Dim CveMovimiento As Integer = ObjInventario.DtResultados(0)("CveMovimiento").ToString().ToEntero() Dim CveAlmacenOrigen As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString().ToEntero() Dim CveAlmacenDestino As Integer = ObjInventario.DtResultados(0)("AlmacenDestino2").ToString().ToEntero() Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString().ToEntero() Dim CveTipoAlmacen As Integer = ObjInventario.DtResultados(0)("CveTipoAlmacen").ToString().ToEntero() 'AGREGAMOS LA ENTRADA Movto 1 If Not TieneError Then AlmacenEntrada = CveAlmacenOrigen CveMovimientoEntrada = ObjInventario.AddMovimiento(AlmacenEntrada, 8, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida, CveOS:=CveOS, Modulo:="Vta/OS") FolioEntrada = ObjInventario.Folio If CveMovimientoEntrada <= 0 Then TextoError = "No se pudo generar el movimiento de entrada correctamente" TieneError = True Else If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then For Each Dr As DataRow In ObjInventario.DtResultados.Rows If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Dr("Cantidad").ToString().ToDecimal, Dr("CveUM").ToString().ToEntero(), Dr("CvePS").ToString().ToEntero(), Dr("PU").ToString().ToDecimal, -1, -1) Then TieneError = True TextoError = "Ocurrió un Error al guardar los movimientos de entrada" Exit For End If Next End If End If End If 'AGREGAMOS LA ENTRADA Movto 2 If Not TieneError Then AlmacenEntrada = CveAlmacenDestino CveMovimientoEntrada2 = ObjInventario.AddMovimiento(AlmacenEntrada, 9, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida2, CveOS:=CveOS, Modulo:="Vta/OS") FolioEntrada = ObjInventario.Folio If CveMovimientoEntrada2 <= 0 Then TextoError = "No se pudo generar el movimiento de entrada correctamente" TieneError = True Else If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada, UsuarioActual.CveEmpresa) Then For Each Dr As DataRow In ObjInventario.DtResultados.Rows If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada2, Dr("Cantidad").ToString().ToDecimal, Dr("CveUM").ToString().ToEntero(), Dr("CvePS").ToString().ToEntero(), Dr("PU").ToString().ToDecimal, -1, -1) Then TieneError = True TextoError = "Ocurrió un Error al guardar los movimientos de entrada" Exit For End If Next End If End If End If 'AGREGAMOS LA ENTRADA Movto 3 If Not TieneError Then AlmacenEntrada = CveAlmacenDestino CveMovimientoEntrada3 = ObjInventario.AddMovimiento(AlmacenEntrada, 3, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida3, CveOS:=CveOS, Modulo:="Vta/OS") FolioEntrada = ObjInventario.Folio If CveMovimientoEntrada3 <= 0 Then TextoError = "No se pudo generar el movimiento de entrada correctamente" TieneError = True Else If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada2, UsuarioActual.CveEmpresa) Then For Each Dr As DataRow In ObjInventario.DtResultados.Rows If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada3, Dr("Cantidad").ToString().ToDecimal, Dr("CveUM").ToString().ToEntero(), Dr("CvePS").ToString().ToEntero(), Dr("PU").ToString().ToDecimal, -1, -1) Then TieneError = True TextoError = "Ocurrió un Error al guardar los movimientos de entrada" Exit For End If Next End If End If End If End If End If TextoExistencia.Clear() Return TieneError End Function 'Protected Sub LbVerInventario_Click(sender As Object, e As EventArgs) Handles LbVerInventario.Click ' RegistraScript(String.Format("AbrirVentana('/Inventarios/PopUpExistenciasAlmacen.aspx?CvePS={0}',800,547,'N');", DdlPS.SelectedValue)) 'End Sub #End Region #Region " MANDA CORREO " Private Sub MandaMails(UsuarioActual As Usuario, CveVenta As Integer, TipoDocto As String, SerieFolio As String, EnviarFactura As Boolean, XML As String, PDF As String, Adjunto As String) Dim ObjMail As New ClsSisMail() Dim ResultadoMail As Integer = 0 Try Dim Asunto As String = String.Empty Dim Cuerpo As String = String.Empty Dim TipoComprobante = "" If TipoDocto = "Ing" Then TipoComprobante = "Factura" If TipoDocto = "Egs" Then TipoComprobante = "Nota de Crédito" If TipoDocto = "Dev" Then TipoComprobante = "Nota de Devolución" If TipoDocto = "Rem" Then TipoComprobante = "Remisión" If TipoDocto = "Cot" Then TipoComprobante = "Cotización" If TipoDocto = "Ant" Then TipoComprobante = "Anticipo" If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa) Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim) Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante) Cuerpo = Cuerpo.Replace("{""Fecha""}", TxtFecha.Text) Cuerpo = Cuerpo.Replace("{""Total""}", TxtTotal.Text) Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", TxtFechaPago.Text) Cuerpo = Cuerpo.Replace("{""SerieFolio""}", SerieFolio) End If If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante) Asunto = Asunto.Replace("{""Sucursal""}", DdlSubProyectoDatos.SelectedItem.Text) Asunto = Asunto.Replace("{""SerieFolio""}", SerieFolio) End If If Not EnviarFactura Then ResultadoMail = 0 End If Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) If DdlTipoComprobante.SelectedValue = "Cot" Then LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) Else LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML}) End If If Adjunto <> "" Then LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = Adjunto}) End If Dim DisplayName As String = "" If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM" If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then ResultadoMail = 1 Else ResultadoMail = 3 End If 'CASO ESPECIAL If CveUsuarioActual = 1446 Then ' Flora Dim str As String = "Flora Envio: Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString() str.GuardaLog() ElseIf CveUsuarioActual = 1513 Then ' Flora Dim str As String = "Flora Envio (secundario): Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString() str.GuardaLog() End If 'Next Catch ex As Exception OnError("Ocurrió error al mandar el Mail", ex) ResultadoMail = 3 Finally Dim ObjVentas As New ClsVentas ObjVentas.UpdateVentaMail(ResultadoMail, CveVenta) ObjVentas.Dispose() End Try End Sub #End Region #Region " ESTIMACIONES " Protected Sub DdlContrato_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContrato.SelectedIndexChanged Dim valueselect = DdlContrato.SelectedValue CargaDatosEstimaciones(CveCliente) DdlContrato.SelectedValue = valueselect If DdlContrato.SelectedValue.ToEntero() > 0 Then For Each gvr As GridViewRow In GvEst.Rows If gvr.DataKey("CveContratoAvance").ToEntero() > 0 Then gvr.FCCheckBox("Chk").Checked = True gvr.FCCheckBox("Chk").Visible = True End If Next BtnEstimacion.Visible = True End If 'If RblOpcionContrato.SelectedValue = "3" Then ' GvEst.DataSource = Nothing ' GvEst.DataBind() ' BtnEstimacion.Visible = False ' BtnCargarContratoDetalles.Visible = False ' BtnCancelarContratoDetalles.Visible = False ' UPEstimaciones.Update() 'End If End Sub Private Sub CargaDatosEstimaciones(CveCliente As Integer) If CveVenta > 0 Then Exit Sub End If Dim Con As New ClsContratos If Con.GetEstimacionesPorFacturar(-1, CveCliente, DdlContrato.SelectedValue.ToEntero(), 0, UsuarioActual.CveEmpresa) Then GvEst.DataSource = Con.DtResultados If Con.DtResultados.Rows.Count > 0 Then 'BtnEstimacion.Visible = True DdlContrato.Items.Clear() DdlContrato.Items.Add(New ListItem("Todos", "-1")) DdlContrato.DataSource = Con.DtResultados.FiltraParametros("CveContrato > 0", "NumeroContrato", DistinctColumns:={"CveContrato", "NumeroContrato"}) End If End If UPEstimaciones.Update() Con.Dispose() DdlContrato.DataBind() GvEst.DataBind() End Sub Protected Sub GVEst_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvEst.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex = 0 Then e.Row.Cells(0).Width = Unit.Pixel(30) e.Row.Cells(1).Width = Unit.Pixel(300) 'Seccion e.Row.Cells(2).Width = Unit.Pixel(100) 'Cantidad e.Row.CssClass = "Totales" Else If e.Row.DBCampo("CveContratoAvance").ToString().ToEntero() > 0 Then ' e.Row.FCCheckBox("Chk").Visible = True Else If e.Row.DBCampo("CveSubFamilias").ToString().ToEntero() > 0 Then e.Row.CssClass = "SubTotales3" Else If e.Row.DBCampo("CveFamilias").ToString().ToEntero() > 0 Then e.Row.CssClass = "SubTotales2" Else e.Row.CssClass = "SubTotales" End If End If End If End If End If End Sub Private Sub ObtenerFechaVencimientoCER() Try Dim CerFile As New FileStream(Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoCer, FileMode.Open, FileAccess.Read) Dim Size As Integer = CerFile.Length.ToString().ToEntero() Dim Data As Byte() = New Byte(Size - 1) {} Size = CerFile.Read(Data, 0, Size) CerFile.Close() CerFile.Dispose() Dim x509 As New X509Certificate2() x509.Import(Data) If x509.NotAfter <= Now() Then TrVistaPrevia.Visible = False TrEmitir.Visible = False BtnEmitirImprimir.Visible = False BtnCrearApartirDe.Enabled = False Alert("La fecha del certificado ha expirado", TipoMensaje.MsgAdvertencia) End If Catch ex As Exception Alert("No se pudo verificar la fecha del certificado", TipoMensaje.ToastError) End Try End Sub #End Region #Region "E V E N T O - B I T A C O R A" Protected Sub GvEB_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvEB.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex = 0 Then e.Row.Cells(0).Width = Unit.Pixel(200) e.Row.Cells(1).Width = Unit.Pixel(200) e.Row.Cells(2).Width = Unit.Pixel(100) e.Row.Cells(3).Width = Unit.Pixel(500) End If If e.Row.DBCampo("Archivo").ToString() <> "" Then e.Row.FCLinkButton("LinkArchivo").Visible = True e.Row.FCLinkButton("LinkArchivo").CommandArgument = String.Format("OI\{0}", e.Row.DBCampo("Archivo").ToString()) ScriptManager.GetCurrent(Me).RegisterPostBackControl(e.Row.FCLinkButton("LinkArchivo")) 'Registro un evento Postbacktrigger, que recargue toda la pagina para que funcione End If e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left End If End Sub Protected Sub BtnGuardarEventoBitacora_Click(sender As Object, e As EventArgs) Handles BtnGuardarEventoBitacora.Click Dim FileExtension As String = "-1" Dim filesgral As List(Of Archivo) = Anexo.getfiles().Archivos Dim Filename As String = "" For Each fileItem As Archivo In filesgral FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "") Filename = fileItem.filename Next Dim ObjEventos As New ClsOIEventos() If ObjEventos.AddEventoBitacora(TxtEventoDescripcion.Text.Trim, String.Format(".{0}", FileExtension), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then If Filename <> "" Then Filename.FilesMove(String.Format("OI{0}", ObjEventos.CveEvento.ToString()), String.Format("{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 Protected Sub LnkContratoAcptar_Click(sender As Object, e As EventArgs) Handles LnkContratoAcptar.Click Dim objcontra As New ClsContratos objcontra.IniciaTransacSQL() If objcontra.AddContratosAceptados(ViewState("CveVenta").ToString().ToEntero(), TxtNombreContrato.Text, 13, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then '-----------------------------------------------Falata la CveContrato!!!!!!!!!!!!!! objcontra.Commit() Alert("La cotización fue aceptada" & objcontra.CveContrato, TipoMensaje.MsgInformacion) Else objcontra.RollBack() Alert("La cotización no fue aceptada", TipoMensaje.MsgError) End If objcontra.Dispose() End Sub Private Sub BtnGarantia_Click(sender As Object, e As EventArgs) Handles LkGarantia.Click Dim s As String = "" 'Nos vamos a la nueva factura Dim url As String = String.Format("/RMA/Garantias.aspx?CveVenta={0}", CveVenta) Response.Redirect(url) End Sub 'Private Sub LkNotaCreditoC_Click(sender As Object, e As EventArgs) Handles LkNotaCredito.Click ' Dim url As String = String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=2", CveVenta) ' Response.Redirect(url) 'End Sub Private Sub BtnNuevaFactura_Click(sender As Object, e As EventArgs) Handles LkRefacturacion.Click 'Nos vamos a la nueva factura If RefacturarCancelada Then Response.Redirect($"Ventas.aspx?CveDevolucion={CveVenta}&NuevaFactura=1") Else Dim script As String = "" If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then Dim sb As New StringBuilder() If Not String.IsNullOrEmpty(FolioFiscal) AndAlso Not (UsuarioActual.Empresa.Funcionalidad(529) = "1") Then sb.Append("La factura se encuentra en el siguiente estatus del SAT:
    ") Dim TotalT As Decimal = TxtTotal.Text.ToDecimal Dim RFCReceptor As String = LblRFC.Text.Trim 'SI SE FACTURO LA SUCURSAL DEL CLIENTE TOMA EL RFC DE ESTA If FacturarSucursal AndAlso Me.ClienteSucursal IsNot Nothing Then RFCReceptor = Me.ClienteSucursal.RFC End If Dim SWatch As New Stopwatch SWatch.Start() Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True) SWatch.Stop() Dim SegundosRespuesta As Double = SWatch.ElapsedMilliseconds / 1000 SegundosRespuesta = SegundosRespuesta.ToEntero If SegundosRespuesta >= 5 Then Alert($"Los servicios de validacion del SAT presentan lentitud en la respuesta [{ SegundosRespuesta } s].", TipoMensaje.ToastError, "") End If If Vigencia IsNot Nothing Then If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) DivRelacionadasRefacturacion.Visible = True BtnMotivoRefacturacion.Visible = False DivMotivoRefacturacionTexto.Visible = False Dim Relacionados = Timbrado.ConsultarUUIDRelacionados(UsuarioActual.Empresa, FolioFiscal, UsuarioActual.Empresa.FacturaProduccion) If Relacionados IsNot Nothing Then Dim sbExtra As New StringBuilder() If Relacionados.Codigo = 500 Then sbExtra.Append("El servicio de verificación de documentos relacionados no esta disponible.") Else sbExtra.Append(Relacionados.Mensaje) Dim SbHijos = New StringBuilder() Dim SbPadres = New StringBuilder() 'If Relacionados.RelacionadosHijo IsNot Nothing Then ' For Each hijo In Relacionados.RelacionadosHijo ' SbHijos.AppendFormat("{0};", hijo.Uuid) ' Next ' If SbHijos.Length > 0 Then ' SbHijos.Remove(SbHijos.Length - 1, 1) ' End If 'End If If Relacionados.RelacionadosPadre IsNot Nothing Then For Each padre In Relacionados.RelacionadosPadre SbPadres.AppendFormat("{0};", padre.Uuid) Next If SbPadres.Length > 0 Then SbPadres.Remove(SbPadres.Length - 1, 1) End If End If Using ObjVentas As New ClsVentas 'If SbHijos.Length > 0 Then ' If ObjVentas.GetFacturasRelacionadasPorFolioFiscal(SbHijos.ToString(), UsuarioActual.CveEmpresa) Then ' GvFacturasHijosCancelar.DataSource = ObjVentas.DtResultados.Copy() ' End If 'End If If SbPadres.Length > 0 Then If ObjVentas.GetFacturasRelacionadasPorFolioFiscal(SbPadres.ToString(), UsuarioActual.CveEmpresa) Then GvFacturasPadreRefacturar.DataSource = ObjVentas.DtResultados.FiltraParametros($"CveVenta <> {CveVenta}") End If End If End Using 'GvFacturasHijosCancelar.DataBind() GvFacturasPadreRefacturar.DataBind() End If If sbExtra.Length > 0 Then LbExtraRefacturacion.Text = $"
    *{sbExtra.ToString()}" End If End If End If If Vigencia.EsCancelable = "Cancelable sin aceptación" Then 'script = "BtnRefacturacionConfirmarAceptacion();" Me.CveEstadoCancelacion = 1 sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) sb.Append("Está seguro de realizar la refacturación?.") End If If Vigencia.EsCancelable = "Cancelable con aceptación" OrElse String.IsNullOrEmpty(Vigencia.EsCancelable) Then 'script = "BtnRefacturacionConfirmar();" Me.CveEstadoCancelacion = 2 sb.AppendFormat("{0}
    ", "Cancelable con aceptación") sb.Append("Está seguro de cancelar el documento para realizar la refacturación?.") End If Else 'If Not UsuarioActual.Empresa.FacturaProduccion Then ' script = "BtnRefacturacionConfirmar();" 'End If sb.Append("No encontrado
    ") End If Else 'sb.Append("¿Desea realizar la refacturación?
    ") script = "BtnRefacturacionConfirmarAceptacion();" End If LblEstatusRefacturacion.Text = sb.ToString() UpMotivoRefac.Update() RegistraScript("$('#DivMotivoRefacturacion').modal({ backdrop: 'static', keyboard: false });", "R1") 'Alert(sb.ToString(), TipoMensaje.MsgConfirmacion, JSBtnAceptar:=script, TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") End If End If End Sub Private Sub BtnMotivoRefacturacion_Click(sender As Object, e As System.EventArgs) Handles BtnMotivoRefacturacion.Click CancelarDocumento(EsRefacturacion:=True) 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 Private Sub BtnContabilizar_Click(sender As Object, e As System.EventArgs) Handles BtnContabilizar.Click 'Dim ObjMov As New ClsContabilidad 'Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:

    " 'If ObjMov.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.Empresa, 2) Then ' Alert(alertaContabilizacion & ObjMov.AlertaMensaje, ModExtensiones.TipoMensaje.MsgInformacion) 'Else ' Alert(String.Format("Ocurrio un error al contabilizar {0}", ObjMov.AlertaMensaje)) 'End If 'ObjMov.Dispose() End Sub Protected Sub BtnDescontabilizar_Click(sender As Object, e As EventArgs) 'Alert("Hola entre", TipoMensaje.MsgError) 'Exit Sub Dim ObjConta As New ClsContabilidad Dim Movimientos = ObjConta.GetMovimientosPoliza(IdPoliza, UsuarioActual.CveEmpresa) 'Verifica que solo exista 1 compra asociada If Movimientos = 1 Then EliminaPoliza() Else RegistraScript("ConfirmEliminarPolizaMultiple();") End If ObjConta.Dispose() End Sub Private Sub BtnMateriales_Click(sender As Object, e As EventArgs) Handles BtnMateriales.Click Dim OS As New ClsOS Dim DtDetalle As DataTable = Nothing Dim DtDetalleMateriales As DataTable = Nothing DtDetalle = TmpDT.Copy For Each Row As DataRow In DtDetalle.Rows If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString().ToEntero(), CveOS) Then Dim Cons As Integer = TmpDT.Rows.Count + 1 For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows Dim drt As DataRow = TmpDT.NewRow FacturaMateriales = 1 drt("Consec") = Cons drt("CveClasificacion") = dr("CveClasificacion") drt("Clasificacion") = dr("Clasificacion") drt("CvePS") = dr("CvePS") drt("PS") = dr("PS") drt("CodigoPS") = dr("CodigoPS") drt("Cantidad") = dr("Cantidad") drt("CveOSDetalle") = dr("CveOSDetalle") drt("CveSubProyecto") = dr("CveSubProyecto") drt("SubProyecto") = dr("SubProyecto") TmpDT.Rows.Add(drt) Cons = Cons + 1 Next End If DtDetalleMateriales = OS.DtResultados.FiltraParametros("SeFacturara = 1 ") Next OS.Dispose() GvPS.DataSource = TmpDT DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") GvPS.DataBind() UpPS.Update() End Sub Private Sub BtnPermisoEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarRemision.Click BtnEditarRemision.Visible = True BtnPermisoEditarRemision.Visible = False BtnCrearApartirDe.Visible = False TxtObsFact.Enabled = True TxtOrdenCompra.Enabled = True TxtPedidoContrato.Enabled = True TxtObsAlmacen.Enabled = True DdlUsoCFDI.Enabled = True DdlMetodoPago33.Enabled = True DdlFormaPago33.Enabled = True UPCondicionesPago.Update() If Me.PermiteCredito Then RBLPago.Enabled = True ModalidadEdicion = True ViewState("CveClienteAnterior") = CveCliente Dim CantidadFacturadaRemision = 0.0 'EN BDH NO DEBE PERMITIR EDITAR EL PU If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = True Gvr.FCLinkButton("imgD").Visible = False CantidadFacturadaRemision += Gvr.DataKey("CantidadFacturadaRem").ToString().ToDouble Next Else 'SI EL DETALLE NO TIENE MOVIMIENTOS DE INVENTARIO ES VISIBLE For Each Gvr As GridViewRow In GvPS.Rows Gvr.FCLinkButton("imgE").Visible = Not Gvr.DataKey("CantidadFacturadaRem").ToString().ToDouble > 0 Gvr.FCLinkButton("imgD").Visible = Not Gvr.DataKey("CantidadInventario").ToString().ToDouble > 0 CantidadFacturadaRemision += Gvr.DataKey("CantidadFacturadaRem").ToString().ToDouble 'If GvInv.Rows.Count > 0 Then ' Gvr.FCLinkButton("imgE").Enabled = False ' Gvr.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen." 'End If Next End If 'ACTIVA CAMBIO DE CLIENTE - SI NO TIENE NADA FACTURADO If Not CantidadFacturadaRemision > 0 AndAlso UsuarioActual.TienePermisoProceso(284) Then HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto") TxtCodigo.ReadOnly = False End If If CantidadFacturadaRemision = 0 AndAlso UsuarioActual.TienePermisoProceso(161) Then DdlVendedor.Enabled = True End If TxtCantidad.Enabled = True DdlClasificacion.Enabled = True DdlPS.Enabled = True TxtObsPS.Enabled = True DdlProyecto.Enabled = True DdlSubProyecto.Enabled = True TxtPrecio.Enabled = True LbAgregar.Enabled = True LnkAgregarPyME.Enabled = True ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") LblSubTotal1.Text = TxtSubTotal.Text LblAmort.Text = TxtSubTotal.Text LimpiaEscondeContado() UPPVentas.Update() UpPS.Update() UpCliente.Update() UPObservaciones.Update() End Sub Private Sub BtnEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnEditarRemision.Click Dim OcurrioError As Boolean = False Dim ObjVentas As New ClsVentas ObjVentas.IniciaTransacSQL() Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) Dim ObjAC As ClsContPAQi = Nothing Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero() Dim TipoCambio As Double = TxtTipoCambio.Text.ToDouble EditoRemision = True Try 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS If DdlMoneda.SelectedValue.ToEntero() <> 2 AndAlso ChkConvertirDolares.Checked Then For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) End If Next TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal Moneda = 2 End If 'CONVERTIR REMISION - TIPO MONEDA -PESO A DOLARES If DdlMoneda.SelectedValue.ToEntero() <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then Dim Importe As Decimal Dim TCC As Decimal = TxtTipoCambio.Text.Trim.ToDecimal For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDecimal * TCC, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDecimal * TCC, NumeroDecimales) Importe = Row("Total").ToString().ToDecimal - Row("Descuento").ToString().ToDecimal Row("ImporteIEPS") = Math.Round(Importe * Row("PorcentajeIEPS").ToString().ToDecimal, NumeroDecimales) Row("ImporteIVA") = Math.Round(Importe * Row("PorcentajeIVA").ToString().ToDecimal, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Importe * Row("PorcentajeRetIVA").ToString().ToDecimal, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Importe * Row("PorcentajeRetISR").ToString().ToDecimal, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) End If Next TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero TipoCambio = 1 Moneda = 1 End If 'Actualizo los parametros de la venta If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDecimal, LblDescuentos.Text.ToDecimal, TxtIVA.Text.ToDecimal, TxtIEPS.Text.ToDecimal, TxtTotal.Text.ToDecimal, Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, UsuarioActual.CveEmpresa, CveVenta, 0, 0, Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1), PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero(), CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero(), TipoDocto:="Rem", CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal, Kilometraje:=TxtKilometraje.Text.ToDouble, CveUsoCFDi:=DdlUsoCFDI.SelectedValue.ToEntero(), CveVendedor:=DdlVendedor.SelectedValue.ToEntero(), ServicioDomicilio:=TrServicioDomicilio.Visible) Then OcurrioError = True End If 'Cargo de nueva cuenta el detalle de Ventas (Conceptos) If Not OcurrioError Then Dim index As Integer = 0 For Each Row As DataRow In TmpDT.Rows Dim CveVentaDetalle As Integer = Row("CveVentaDetalle").ToString().ToEntero() If CveVentaDetalle > 0 Then If Not ObjVentas.UpdateVentaDetalleRemision(Row("CveVentaDetalle").ToString().ToEntero(), Row("CvePS").ToString().ToEntero(), Row("Cantidad").ToString().ToDecimal, Row("PU").ToString().ToDecimal(), Row("ImporteIEPS").ToString().ToDecimal(), Row("PorcentajeIEPS").ToString().ToDecimal(), Row("ImporteIVA").ToString().ToDecimal(), Row("PorcentajeIVA").ToString().ToDecimal(), Row("Descuento").ToString().ToDecimal(), Row("Obs").ToString(), UsuarioActual.CveUsuario) Then OcurrioError = True Exit For End If Else If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString().ToEntero(), Row("Cantidad").ToString().ToDouble, Row("CveUM").ToString().ToEntero(), Row("PU").ToString().ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("ImporteIVA").ToString().ToDouble, Math.Round((Row("Total").ToString().ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)) * (1 + Row("PorcentajeIVA").ToString().ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)))), 6), Row("Obs").ToString(), Row("Descuento").ToString().ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("TipoDescuento").ToString().ToEntero(), Row("CveSubProyecto").ToString().ToEntero(), Row("CvePresupuestoIngreso").ToString().ToEntero(), PorcentajeIVA:=Row("PorcentajeIVA").ToString().ToDecimal, IEPS:=Row("ImporteIEPS").ToString().ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString().ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString(), CveVentaDetallePadre:=Row("CveVentaDetalle").ToString().ToEntero(), CveContratoDetalle:=Row("CveContratoDetalle").ToString().ToEntero(), CvePromocionDetalle:=If(DtPromociones IsNot Nothing, DtPromociones.FiltroPrimeroValor("CvePromocionDetalle", $"CvePS={Row("CvePS").ToString()}").ToEntero(), -1), ImporteRetIVA:=Row("ImporteRetIVA").ToString().ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString().ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString().ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString().ToDouble, CuentaPredial:=Row("CuentaPredial").ToString()) Then OcurrioError = True Exit For Else TmpDT.Rows(index)("CveVentaDetalle") = ObjVentas.CveVentaDetalle End If End If index = index + 1 Next End If 'ELIMINA LOS DETALLES If Not OcurrioError Then Dim DtEliminados As New DataTable If ObjVentas.GetVentaDetalle(CveVenta) Then DtEliminados = ObjVentas.DtResultados.FiltraParametros("", "", {"CveVentaDetalle"}) For Each Dr1 As DataRow In DtEliminados.Rows If TmpDT.FiltraParametros($"CveVentaDetalle = {Dr1("CveVentaDetalle")}").Rows.Count = 0 Then If Not ObjVentas.RemoveVentasDetalle(CveVenta, Dr1("CveVentaDetalle").ToString().ToEntero()) Then OcurrioError = True End If End If Next Else OcurrioError = True End If End If 'OcurrioError = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, 1, ObjBancos, ObjVentas) 'Actualizo impuestos locales If Not OcurrioError Then For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString().ToEntero(), gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal) Then OcurrioError = True End If End If Next End If 'Orden Produccion' If Not OcurrioError Then If UsuarioActual.CveEmpresa.Contiene(126) Then If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero() > 0 Then If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then OcurrioError = True End If End If End If End If If Not OcurrioError Then If RegeneracionPolizas(ObjVentas, ObjAC, ObjConta, ObjBancos) Then OcurrioError = True End If End If If ObjConta.ValidacionPrePolizaCuadre(-1, 2, CveVenta) Then If ObjConta.ValorPolizaDescuadre > 0 Then If ObjConta.ValorPolizaDescuadre = 2 Then OcurrioError = True Alert(ObjConta.MensajePolizaDescuadre, TipoMensaje.MsgError) End If End If End If Catch ex As Exception OcurrioError = True OnError("Ocurrió un error al actualizar la remisión", ex) End Try If OcurrioError Then ObjVentas.RollBack() Alert("Ocurrió un error al guardar los cambios. Por favor intente de nuevo.", TipoMensaje.MsgError) Else ObjVentas.Commit() If ObjAC IsNot Nothing Then ObjAC.Commit() Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();") End If ObjVentas.Dispose() ObjConta.Dispose() ObjBancos.Dispose() If ObjAC IsNot Nothing Then ObjAC.Dispose() 'REGENERAR EL PDF If Not OcurrioError Then Try Dim strURLHOST = String.Format("{0}://{1}:{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port) Dim Hilo As New System.Threading.Thread(Sub() RegenerarPDF(CveVenta, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario, strURLHOST)) Hilo.Start() Catch ex As Exception OnError("Ocurrió un error al regenerar el PDF", ex) End Try End If 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 Private Sub BtnActualizarCuentaTerminal_Click(sender As Object, e As EventArgs) Handles BtnActualizarCuentaTerminal.Click Dim ObjVentas As New ClsVentas ObjVentas.IniciaTransacSQL() Dim TieneError = False If Not ObjVentas.UpdateVentaCuentaTerminal(DdlCuentaTerminalModal.SelectedValue.ToEntero(), CveVenta) Then TieneError = True End If If TieneError Then ObjVentas.RollBack() Else ObjVentas.Commit() RegistraScript("$('#ModalCuentaTerminal').modal('hide')") Alert("Se asignó correctamente la cuenta terminal", JSBtnAceptar:="BtnRefrescarPagina();") End If ObjVentas.Dispose() End Sub #End Region #Region "CODIGO DE BARRAS" Protected Sub ChkClasificacion_CheckedChanged(sender As Object, e As EventArgs) If ChkClasificacion.Checked Then DIVClasificacion.Visible = False DIVClasif.Visible = False DIVCodBarras.Visible = True DIVCod.Visible = True TxtCodigoBarras.Focus() Else DIVClasificacion.Visible = True DIVClasif.Visible = True DIVCodBarras.Visible = False DIVCod.Visible = False End If End Sub Protected Sub CargarCodigo() Dim TipoVenta As Integer = 0 Dim drSucursal As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue))) If drSucursal IsNot Nothing Then TipoVenta = drSucursal("TipoVenta").ToString().ToEntero() If TipoVenta = 1 Then ChkClasificacion.Checked = True DIVClasif.Visible = False DIVClasificacion.Visible = False DIVCodBarras.Visible = True DIVCod.Visible = True TxtCodigoBarras.Focus() 'RegistraScript(String.Format("$( document ).ready(function() {{$('#{0}').focus()}});", TxtCodigoBarras.ClientID), "cb") Else ChkClasificacion.Visible = False End If End Sub Protected Sub BtnCodigoBarras_Click(sender As Object, e As EventArgs) Handles BtnCodigoBarrasSerie.Click Dim DrProducto As DataRow = Nothing If TxtCantidad.Text.Trim.ToDouble <= 0 Then TxtCantidad.Text = "1" Dim SerieL As String = "" Dim CodigoBarras As String = "" Dim CvePS As Integer 'LIMPIA "PROPIEDAD" HdnCvePS.Value = "" 'BUSCA POR SERIE E IGNORA CODIGO DE BARRAS (LIMPIA) If TxtCodigoSerie.Text.Trim <> "" Then Dim Serie As String = TxtCodigoSerie.Text.Trim().ToUpper() Dim Objinventarios As New ClsInventarios Dim Existencia = Objinventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, -1, Serie:=Serie, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero()) Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("Serie = '{0}'", Serie)) CvePS = Objinventarios.CvePS Objinventarios.Dispose() If Existencia - ExistenciaActual > 0 Then If CvePS > 0 Then DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If DrProducto IsNot Nothing Then HdnCvePS.Value = CvePS.ToString() TxtCantidad.Text = "1" Else Alert($"No se encontró un producto con la serie: {Serie}. Por favor verifique y vuelva a intentar ", TipoMensaje.MsgAdvertencia) End If End If Else Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", Serie), TipoMensaje.MsgAdvertencia) TxtCodigoSerie.Focus() RegistraScript($"$('#{TxtCodigoSerie.ClientID}').select();") Exit Sub End If End If 'BUSCA POR CODIGO DE BARRAS If Not CvePS > 0 Then CodigoBarras = TxtCodigoBarras.Text.Trim() DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero($"CodigoBarras = '{CodigoBarras}'") If DrProducto IsNot Nothing Then If DrProducto("Inv_CveMetodoInventario").ToString() = "5" Then 'si es serie TxtCodigoSerie.Focus() Exit Sub Else CvePS = DrProducto("CvePS").ToString().ToEntero() HdnCvePS.Value = CvePS.ToString() End If Else TxtCodigoBarras.Focus() RegistraScript($"$('#{TxtCodigoBarras.ClientID}').select();") Alert($"No se encontró un producto con el código de barras: {Serie}. Por favor verifique y vuelva a intentar ", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If DrProducto Is Nothing Then Alert("El producto no fue encontrado", TipoMensaje.MsgAdvertencia) End If 'CARGA VALORES DEL PS DdlPSIndexChange(CvePS, DdlPS) If Not TxtCantidad.Text.ToDouble > 0 Then TxtCantidad.Text = "1" TxtPrecio.Focus() RegistraScript($"$('#{TxtPrecio.ClientID}').select();") 'LO DE ABAJO YA NO SE USA - ES VIEJO Exit Sub 'PARA AGREGAR PS DIRECTO If DrProducto IsNot Nothing Then TxtObsPS.Text = "" If UsuarioActual.CveEmpresa = 80 Then 'BUSCA EL PRECIO DE LA SUCURSAL Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSSucursales(DrProducto("CvePS").ToString().ToEntero(), UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero()) Then Dim dtt As DataTable = ObjPS.DtResultados Dim drPrecio As DataRow = dtt.FiltroPrimero("") If drPrecio IsNot Nothing And TxtPrecio.Enabled = False Then TxtPrecio.Text = drPrecio("Importe").ToString().ToDouble.ToString("N4") End If dtt.Dispose() End If ObjPS.Dispose() 'SI NO CARGA PRECIO DE LA SUCURSAL TOMA EL DEL PS If TxtPrecio.Text.ToDouble <= 0 Then TxtPrecio.Text = DrProducto("Precio").ToString().ToDouble.ToString("N4") End If HdnPS.Value = DrProducto("PS").ToString() HdnCodigoPS.Value = DrProducto("PSCodigo").ToString() HdnTipoPS.Value = DrProducto("CveTipoPS").ToString() HdnTipoInv.Value = DrProducto("Inv_CveMetodoInventario").ToString() HdnAplicaIEPS.Value = DrProducto("AplicaIEPS").ToString() HdnPorcentajeIEPS.Value = DrProducto("IEPSPorcentaje").ToString() HdnIVAPS.Value = If(DrProducto("IVA").ToString() = "-1", ViewState("IVA"), DrProducto("IVA").ToString()).ToString() HdnIVARetAPS.Value = DrProducto("RetIVA").ToString() HdnAsientoContable.Value = DrProducto("AsientoContableVentas").ToString() HdnCtaContable.Value = DrProducto("IdCtaContVentas").ToString() HdnAplicaParaConcepto.Value = DrProducto("AplicaParaConcepto").ToString() HdnCodigo.Value = DrProducto("Codigo").ToString() If ValidaAgregarPS(DrProducto("CvePS").ToString().ToEntero(), DrProducto("CveUM").ToString().ToEntero(), TxtPrecio.Text.Trim.ToDouble, DrProducto("CveTipoPS").ToString().ToEntero()) Then If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then CvePSAmortizacion = DdlPS.SelectedValue.ToEntero().ToEntero() End If AgregarProductoServicio(TxtCantidad.Text.Trim.ToDecimal, DrProducto("CveUM").ToString().ToEntero(), DrProducto("UnidadMedida").ToString(), DrProducto("CveClasificacion").ToString().ToEntero(), DrProducto("Clasificacion").ToString(), DrProducto("CvePS").ToString().ToEntero(), DrProducto("PS").ToString(), TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDecimal, 0, DdlProyecto.SelectedValue.ToEntero(), DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero(), DdlSubProyecto.SelectedItem.Text) 'AddPS(TxtCantidad.Text.Trim.ToDouble, DrProducto("CveUM").ToString().ToEntero(), DrProducto("UnidadMedida").ToString(), DrProducto("CveClasificacion").ToString().ToEntero(), DrProducto("Clasificacion").ToString(), ' DrProducto("CvePS").ToString().ToEntero(), DrProducto("PS").ToString(), TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDouble, HdnIVAPS.Value.ToDouble, 0, 0, ' -1, -1, True, DrProducto("Codigo").ToString(), DdlProyecto.SelectedValue.ToEntero(), ' DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero(), DdlSubProyecto.SelectedItem.Text, DrProducto("CveTipoPS").ToString().ToEntero(), DrProducto("Inv_CveMetodoInventario").ToString().ToEntero(), Serie:=Serie, CodigoPS:=DrProducto("PSCodigo").ToString()) LimpiaAgregar() End If End If Else Alert("El producto no fue encontrado.", TipoMensaje.MsgAdvertencia) End If UpPS.Update() End Sub Private Sub DdlMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMoneda.SelectedIndexChanged CambiaMoneda() End Sub Private Sub CambiaMoneda() TrConversionTipoCambio.Visible = False TrConversionDolares.Visible = False Select Case DdlMoneda.SelectedValue Case "1" TxtTipoCambio.Text = "1" TxtTipoCambioDlls.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString() TrConversionDolares.Visible = True ChkConvertirDolares.Enabled = Not UsuarioActual.TienePermisoProceso(324) Case "2" TxtTipoCambioDlls.Text = "1" If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate.AddDays(-1)).ToString() Else TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString() End If TrConversionTipoCambio.Visible = True ChkConvertirDoctoPesos.Enabled = Not UsuarioActual.TienePermisoProceso(324) Case Else If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate.AddDays(-1)).ToString() Else TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).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() If CveCliente > 0 Then CargaAnticipos(CveCliente) End If If CveVenta <= 0 Then CalculaLineasAdicionales() End If End Sub Private Sub btnBuscarPrecio_Click(sender As Object, e As EventArgs) Handles btnBuscarPrecio.Click Dim Codigo, CodigoBarras As String Dim CvePS As Integer CvePS = If(DdlBPPS.SelectedValue.ToEntero() > 0, DdlBPPS.SelectedValue.ToEntero(), -1) Codigo = If(TxtBPCodigo.Text.Trim.Length = 0, "", TxtBPCodigo.Text) CodigoBarras = If(TxtBPCodigoBarras.Text.Trim.Length = 0, "", TxtBPCodigoBarras.Text) Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSSucursalesALL(DdlPS.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), Codigo:=Codigo, CodigoBarras:=CodigoBarras) Then GVBuscarPrecio.DataSource = ObjPS.DtResultados Else GVBuscarPrecio.DataSource = Nothing End If ObjPS.Dispose() GVBuscarPrecio.DataBind() UpBuscarPrecio.Update() End Sub #End Region #Region " CONDICIONES DE PAGO " Private Sub InicializaCondicionesPago() DtPagos = New DataTable DtPagos.Columns.Add("CveTipoMovimiento", GetType(String)) DtPagos.Columns.Add("TipoMovimiento", GetType(String)) DtPagos.Columns.Add("CveCuenta", GetType(String)) DtPagos.Columns.Add("Cuenta", GetType(String)) DtPagos.Columns.Add("Folio", GetType(String)) DtPagos.Columns.Add("Importe", GetType(Decimal)) DtPagos.Columns.Add("Observaciones", GetType(String)) DtPagos.Columns.Add("Tipo", GetType(String)) DtPagos.Columns.Add("CveMetodoPago", GetType(Integer)) DtPagos.Columns.Add("MesesSinIntereses", GetType(Integer)) CargaCuentas() End Sub Private Sub LimpiaContado() CargaCuentas() DdlCuentaEfectivo.SelectedValueExist(-1) TxtImporteEfectivo.Text = "0.00" TxtImporteCredito.Text = "0.00" TxtImporteDebito.Text = "0.00" TxtImporteCheque.Text = "0.00" TxtImporteTransferencia.Text = "0.00" TxtImporteContado.Text = "0.00" TxtImporteOtrosContado.Text = "0.00" End Sub Private Sub LimpiaEscondeContado() 'LIMPIA DivContado.Visible = False DivTerminal.Visible = False If DtPagos IsNot Nothing Then DtPagos.Rows.Clear() CargaGridContado() Select Case RBLPago.SelectedValue.ToEntero() Case 1 'CREDITO TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString 'SI ES CREDITO EL METODO DE PAGO DEBE SER PPD If UsuarioActual.Empresa.Funcionalidad(589) = "1" Then DdlMetodoPago33.SelectedValueExist("3") DdlMetodoPago33.Enabled = False If Me.CveVenta > 0 AndAlso (Not Me.EsCreaApartirDe) AndAlso (Not Me.ModalidadEdicion) AndAlso Me.CveMetodoPago33Venta > 0 Then DdlMetodoPago33.SelectedValueExist(Me.CveMetodoPago33Venta) End If CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) 'SI ES VENTA NUEVA, ASIGNA LA DEL CLIENTE If (Me.CveVenta <= 0 OrElse Me.EsCreaApartirDe) AndAlso Me.CveFormaPago33Cliente > 0 Then DdlFormaPago33.SelectedValueExist(Me.CveFormaPago33Cliente) End If 'SI ES VENTA EXISTENTE, ASIGNA LA GUARDADA If Me.CveVenta > 0 AndAlso (Not Me.EsCreaApartirDe) AndAlso Me.CveFormaPago33Venta > 0 Then DdlFormaPago33.SelectedValueExist(Me.CveFormaPago33Venta) End If If UsuarioActual.CveEmpresa.Contiene(72, 80, 146) Then DdlFormaPago33.Enabled = False DdlFormaPago33.SelectedValueExist("20") End If End If Case 2 'CONTADO If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") OrElse (UsuarioActual.Empresa.Funcionalidad(558).ToEntero() = 1 And DdlTipoComprobante.SelectedValue = "Cot") OrElse (CveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue = "Cot" AndAlso Not UsuarioActual.CveEmpresa.Contiene(119, 158)) Then DivContado.Visible = True If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then DivTransferencia.Visible = False End If TxtImporteContado.Text = TxtTotal.Text End If TxtFechaPago.Text = Now.ToShortDateString 'SI ES CONTADO EL METODO DE PAGO DEBE SER PUE If UsuarioActual.Empresa.Funcionalidad(589) = "1" Then DdlMetodoPago33.SelectedValueExist("1") DdlMetodoPago33.Enabled = False If UsuarioActual.CveEmpresa.Contiene(72, 80, 146) Then DdlFormaPago33.Enabled = True End If CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) 'SI ES VENTA NUEVA, ASIGNA LA DEL CLIENTE If (Me.CveVenta <= 0 OrElse Me.EsCreaApartirDe) AndAlso Me.CveFormaPago33Cliente > 0 Then DdlFormaPago33.SelectedValueExist(Me.CveFormaPago33Cliente) End If 'SI ES VENTA EXISTENTE, ASIGNA LA GUARDADA If Me.CveVenta > 0 AndAlso (Not Me.EsCreaApartirDe) AndAlso (Not Me.ModalidadEdicion) AndAlso Me.CveFormaPago33Venta > 0 Then DdlFormaPago33.SelectedValueExist(Me.CveFormaPago33Venta) End If End If Case 3 ' TERMINAL DivTerminal.Visible = True TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString End Select LimpiaContado() LimpiaProntoPago() 'NO PERMITE EDITAR FECHA DEL PAGO If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(260) Then TxtFechaPago.Enabled = False imgCalendario.Visible = False End If UpContado.Update() UPCondicionesPago.Update() End Sub Private Sub LimpiaProntoPago() If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then If RBLPago.SelectedValue = "2" Then GvPS.Columns(22).Visible = True thProntoPago.Visible = True thProntoPago2.Visible = True Else GvPS.Columns(22).Visible = False thProntoPago.Visible = False thProntoPago2.Visible = False End If CalculaTotalesVenta() End If End Sub Private Sub CargaCuentas() DdlCuentaEfectivo.Items.Clear() DdlCuentaTarjetaCredito.Items.Clear() DdlCuentaTarjetaDebito.Items.Clear() DdlCuentaCheque.Items.Clear() DdlCuentaTransferencia.Items.Clear() Dim DtCC As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa) 'MOSTRAR SOLO CUENTAS DE CONTADO EN BDH If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then DdlCuentaEfectivo.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1 AND TieneTerminal = 0", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) DdlCuentaCheque.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1 AND TieneTerminal = 0", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) Else DdlCuentaEfectivo.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) DdlCuentaCheque.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) End If If UsuarioActual.Empresa.Funcionalidad(558) = "1" OrElse UsuarioActual.Empresa.Funcionalidad(531) = "1" Then DdlCuentaTarjetaCredito.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1 AND TieneTerminal = 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) DdlCuentaTarjetaDebito.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1 AND TieneTerminal = 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) Else DdlCuentaTarjetaCredito.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND (CveTipoCuenta <> 1 OR TieneTerminal = 1)", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) DdlCuentaTarjetaDebito.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND (CveTipoCuenta <> 1 OR TieneTerminal = 1)", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) End If DdlCuentaTransferencia.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) DtCC.Dispose() DdlCuentaEfectivo.DataBind() 'DdlCuentaEfectivo.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlCuentaTarjetaCredito.DataBind() 'DdlCuentaTarjetaCredito.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlCuentaTarjetaDebito.DataBind() 'DdlCuentaTarjetaDebito.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlCuentaCheque.DataBind() 'DdlCuentaCheque.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlCuentaTransferencia.DataBind() 'DdlCuentaTransferencia.Items.Insert(0, New ListItem("Seleccione", "-1")) End Sub Protected Sub DdlOtroFormaPago_SelectedIndexChanged(sender As Object, e As EventArgs) DivContadoOtrosCuenta.Attributes.Add("class", "col-md-6") DivMesesSinIntereses2.Visible = False Select Case DdlOtroFormaPago.SelectedValue.ToEntero() Case 1 DivContadoOtrosCuenta.Attributes.Add("class", "col-md-3") DivMesesSinIntereses2.Visible = True DdlCuentaOtrosContado.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) Exit Select Case 2 DdlCuentaOtrosContado.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) Exit Select Case 3 DdlCuentaOtrosContado.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero() <= 0, 1, DdlMoneda.SelectedValue.ToEntero()))) Exit Select Case -1 DdlCuentaOtrosContado.DataSource = Nothing Exit Select End Select DdlCuentaOtrosContado.DataBind() UpContado.Update() End Sub 'DdlOtroFormaPago Private Function CargaFolioContado(CveCuenta As Integer, TipoTransaccion As Integer) As Long Dim Folio As Long If CveCuenta > 0 And TipoTransaccion > 0 Then Dim Banco As New ClsBancos Folio = Banco.GetNextFolio(CveCuenta, TipoTransaccion) Banco.Dispose() Else Folio = -1 End If Return Folio End Function Private Sub CargaGridContado() 'If DtPagos IsNot Nothing Then ' HdnPagadoContado.Value = DtPagos.SUMD("Importe").ToString() 'Else ' HdnPagadoContado.Value = "0" 'End If GvPagos.DataSource = DtPagos GvPagos.DataBind() End Sub Protected Sub GvPagos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvPagos.RowDeleting DtPagos.Rows.RemoveAt(e.RowIndex) 'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P. Dim abonado = DtPagos.SUM("Importe") Dim saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado 'CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString() CargaGridContado() UpContado.Update() End Sub Private Sub BtnAgregarPago_Click(sender As Object, e As EventArgs) Handles BtnAgregarPago.Click Dim abonado, saldo As Double Dim total As Decimal = TxtImporteEfectivo.Text.ToDecimal + TxtImporteCredito.Text.ToDecimal + TxtImporteDebito.Text.ToDecimal + TxtImporteCheque.Text.ToDecimal + TxtImporteTransferencia.Text.ToDecimal DtPagos = Nothing DtPagos = New DataTable Dim Cambio As Decimal = TxtCambio.Text.ToDecimal 'SI ES FALTANTE NO DEBE CONSIDERARSE If HdnCambioFaltante.Value = "2" Then Cambio = 0 End If DtPagos.Columns.Add("CveTipoMovimiento", GetType(String)) DtPagos.Columns.Add("TipoMovimiento", GetType(String)) DtPagos.Columns.Add("CveCuenta", GetType(String)) DtPagos.Columns.Add("Cuenta", GetType(String)) DtPagos.Columns.Add("Folio", GetType(String)) DtPagos.Columns.Add("Importe", GetType(Decimal)) DtPagos.Columns.Add("Observaciones", GetType(String)) DtPagos.Columns.Add("Tipo", GetType(String)) DtPagos.Columns.Add("CveMetodoPago", GetType(Integer)) DtPagos.Columns.Add("MesesSinIntereses", GetType(Integer)) If total <= 0 Then Alert("No se ha ingresado importe", TipoMensaje.MsgAdvertencia) : Exit Sub If Cambio > 0 And TxtImporteEfectivo.Text.ToDecimal < Cambio Then Alert("Debe haber un pago en efectivo y ser mayor que el cambio. Si no, ser pago exacto.", TipoMensaje.MsgAdvertencia) CargaGridContado() Exit Sub End If If (DtPagos.SUM("Importe").ToString().ToDecimal + total - Cambio) > TxtTotal.Text.ToDecimal Then Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor rectifique.", TipoMensaje.MsgAdvertencia) CargaGridContado() Exit Sub End If 'Pago en Efectivo If TxtImporteEfectivo.Text.ToDecimal > 0 Then If DdlCuentaEfectivo.Items.Count > 0 Then Dim DrEfectivo = DtPagos.NewRow DrEfectivo("CveTipoMovimiento") = 13 DrEfectivo("TipoMovimiento") = "Pago en Efectivo" DrEfectivo("CveCuenta") = DdlCuentaEfectivo.SelectedValue DrEfectivo("Cuenta") = DdlCuentaEfectivo.SelectedItem.Text DrEfectivo("Importe") = TxtImporteEfectivo.Text.ToDecimal - Cambio DrEfectivo("Folio") = CargaFolioContado(DdlCuentaEfectivo.SelectedValue.ToEntero(), 6) DrEfectivo("Observaciones") = "" DrEfectivo("Tipo") = "Caja Chica" DrEfectivo("CveMetodoPago") = 1 DrEfectivo("MesesSinIntereses") = -1 DtPagos.Rows.Add(DrEfectivo) Else Alert("Debe seleccionar una cuenta válida de caja", TipoMensaje.MsgAdvertencia) End If End If 'Pago Tarjeta Credito If TxtImporteCredito.Text.ToDecimal > 0 Then If DdlCuentaTarjetaCredito.Items.Count > 0 Then Dim DrCredito = DtPagos.NewRow DrCredito("CveTipoMovimiento") = 12 DrCredito("TipoMovimiento") = "Tarjeta de Crédito" DrCredito("CveCuenta") = DdlCuentaTarjetaCredito.SelectedValue DrCredito("Cuenta") = DdlCuentaTarjetaCredito.SelectedItem.Text DrCredito("Importe") = TxtImporteCredito.Text DrCredito("Folio") = CargaFolioContado(DdlCuentaTarjetaCredito.SelectedValue.ToEntero(), 12) DrCredito("Observaciones") = "" DrCredito("Tipo") = "Tarjeta de Crédito" DrCredito("CveMetodoPago") = 4 If UsuarioActual.Empresa.Funcionalidad(558).ToEntero() = 1 Then DrCredito("MesesSinIntereses") = DDlMesesSinIntereses.SelectedValue.ToEntero() Else DrCredito("MesesSinIntereses") = -1 End If DtPagos.Rows.Add(DrCredito) Else Alert("Debe seleccionar una cuenta válida de crédito", TipoMensaje.MsgAdvertencia) End If End If 'Pago Tarjeta Debito If TxtImporteDebito.Text.ToDecimal > 0 Then If DdlCuentaTarjetaDebito.Items.Count > 0 Then Dim DrDebito = DtPagos.NewRow DrDebito("CveTipoMovimiento") = 11 DrDebito("TipoMovimiento") = "Tarjeta de Debito" DrDebito("CveCuenta") = DdlCuentaTarjetaDebito.SelectedValue DrDebito("Cuenta") = DdlCuentaTarjetaDebito.SelectedItem.Text DrDebito("Importe") = TxtImporteDebito.Text DrDebito("Folio") = CargaFolioContado(DdlCuentaTarjetaDebito.SelectedValue.ToEntero(), 11) DrDebito("Observaciones") = "" DrDebito("Tipo") = "Tarjeta de Débito" DrDebito("CveMetodoPago") = 18 DrDebito("MesesSinIntereses") = -1 DtPagos.Rows.Add(DrDebito) Else Alert("Debe seleccionar una cuenta válida de débito", TipoMensaje.MsgAdvertencia) End If End If 'Pago Tarjeta Debito If TxtImporteCheque.Text.ToDecimal > 0 Then If DdlCuentaCheque.Items.Count > 0 Then Dim DrCheque = DtPagos.NewRow DrCheque("CveTipoMovimiento") = 3 DrCheque("TipoMovimiento") = "Cheque" DrCheque("CveCuenta") = DdlCuentaCheque.SelectedValue DrCheque("Cuenta") = DdlCuentaCheque.SelectedItem.Text DrCheque("Importe") = TxtImporteCheque.Text DrCheque("Folio") = CargaFolioContado(DdlCuentaCheque.SelectedValue.ToEntero(), 3) DrCheque("Observaciones") = "" DrCheque("Tipo") = "Cheque" DrCheque("CveMetodoPago") = 2 DrCheque("MesesSinIntereses") = -1 DtPagos.Rows.Add(DrCheque) Else Alert("Debe seleccionar una cuenta de cheque", TipoMensaje.MsgAdvertencia) End If End If 'Pago Transferencia If TxtImporteTransferencia.Text.ToDecimal > 0 Then If DdlCuentaTransferencia.Items.Count > 0 Then Dim DrCheque = DtPagos.NewRow DrCheque("CveTipoMovimiento") = 8 DrCheque("TipoMovimiento") = "Transferencia" DrCheque("CveCuenta") = DdlCuentaTransferencia.SelectedValue DrCheque("Cuenta") = DdlCuentaTransferencia.SelectedItem.Text DrCheque("Importe") = TxtImporteTransferencia.Text DrCheque("Folio") = CargaFolioContado(DdlCuentaTransferencia.SelectedValue.ToEntero(), 8) DrCheque("Observaciones") = "" DrCheque("Tipo") = "Transferencia" DrCheque("CveMetodoPago") = 3 DrCheque("MesesSinIntereses") = -1 DtPagos.Rows.Add(DrCheque) Else Alert("Debe seleccionar una cuenta de transferencia", TipoMensaje.MsgAdvertencia) End If End If 'Otro Metodo de pago Select Case DdlOtroFormaPago.SelectedValue.ToEntero() Case -1 Exit Select Case 1 If TxtImporteOtrosContado.Text.ToDecimal > 0 Then If DdlCuentaOtrosContado.Items.Count > 0 Then Dim DrCredito = DtPagos.NewRow DrCredito("CveTipoMovimiento") = 12 DrCredito("TipoMovimiento") = "Tarjeta de Crédito" DrCredito("CveCuenta") = DdlCuentaOtrosContado.SelectedValue DrCredito("Cuenta") = DdlCuentaOtrosContado.SelectedItem.Text DrCredito("Importe") = TxtImporteOtrosContado.Text DrCredito("Folio") = CargaFolioContado(DdlCuentaOtrosContado.SelectedValue.ToEntero(), 12) DrCredito("Observaciones") = "" DrCredito("Tipo") = "Tarjeta de Crédito" DrCredito("CveMetodoPago") = 4 If UsuarioActual.Empresa.Funcionalidad(558).ToEntero() = 1 Then DrCredito("MesesSinIntereses") = DdlMesesSinIntereses2.SelectedValue.ToEntero() Else DrCredito("MesesSinIntereses") = -1 End If DtPagos.Rows.Add(DrCredito) Else Alert("Debe seleccionar una cuenta válida de crédito( Otra condición de pago)", TipoMensaje.MsgAdvertencia) End If End If Exit Select Case 2 If TxtImporteOtrosContado.Text.ToDecimal > 0 Then If DdlCuentaOtrosContado.Items.Count > 0 Then Dim DrDebito = DtPagos.NewRow DrDebito("CveTipoMovimiento") = 11 DrDebito("TipoMovimiento") = "Tarjeta de Debito" DrDebito("CveCuenta") = DdlCuentaOtrosContado.SelectedValue DrDebito("Cuenta") = DdlCuentaOtrosContado.SelectedItem.Text DrDebito("Importe") = TxtImporteOtrosContado.Text DrDebito("Folio") = CargaFolioContado(DdlCuentaOtrosContado.SelectedValue.ToEntero(), 11) DrDebito("Observaciones") = "" DrDebito("Tipo") = "Tarjeta de Débito" DrDebito("CveMetodoPago") = 18 DrDebito("MesesSinIntereses") = -1 DtPagos.Rows.Add(DrDebito) Else Alert("Debe seleccionar una cuenta válida de débito( Otra condición de pago)", TipoMensaje.MsgAdvertencia) End If End If Exit Select Case 3 If TxtImporteOtrosContado.Text.ToDecimal > 0 Then If DdlCuentaOtrosContado.Items.Count > 0 Then Dim DrCheque = DtPagos.NewRow DrCheque("CveTipoMovimiento") = 3 DrCheque("TipoMovimiento") = "Cheque" DrCheque("CveCuenta") = DdlCuentaOtrosContado.SelectedValue DrCheque("Cuenta") = DdlCuentaOtrosContado.SelectedItem.Text DrCheque("Importe") = TxtImporteOtrosContado.Text DrCheque("Folio") = CargaFolioContado(DdlCuentaOtrosContado.SelectedValue.ToEntero(), 3) DrCheque("Observaciones") = "" DrCheque("Tipo") = "Cheque" DrCheque("CveMetodoPago") = 2 DrCheque("MesesSinIntereses") = -1 DtPagos.Rows.Add(DrCheque) Else Alert("Debe seleccionar una cuenta de cheque( Otra condición de pago)", TipoMensaje.MsgAdvertencia) End If End If Exit Select End Select 'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P. abonado = DtPagos.SUM("Importe") saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado 'CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString() If (Not UsuarioActual.CveEmpresa.Contiene(119, 158)) AndAlso Me.CveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue = "Cot" AndAlso Not ValidaPagosContado(MostrarAlertas:=False) Then VerificarBtnFacturarCotizacion(DdlVendedor.SelectedValue.ToEntero(), MostrarGenerarRemision:=False) UpFacturar.Update() End If 'TOMA EL VALOR DEL PAGO MAS ALTO QUE SE APLIQUE If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DtPagos IsNot Nothing Then Dim RowPagoMasAlto As DataRow = DtPagos.FiltraParametros("", Orderby:="Importe DESC").FiltroPrimero("") If RowPagoMasAlto IsNot Nothing Then DdlFormaPago33.SelectedValueExist(RowPagoMasAlto("CveMetodoPago")) End If End If CargaGridContado() UpContado.Update() End Sub Private Sub RBLPago_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLPago.SelectedIndexChanged LimpiaEscondeContado() End Sub Private Function ValidaPagosContado(Optional MostrarAlertas As Boolean = True, Optional TipoDoctoViejo As String = "") As Boolean Dim Retorno = False Dim AmortizacionNC As Decimal = 0 'SI ES AMORTIZACION POR NOTA DE CREDITO DEBE SUMAR LA TOTALIDAD PARA COMPARAR EL PAGO If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then For Each gvr As GridViewRow In GVAnticipos.Rows If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked AndAlso gvr.DataKey("CveConceptoContable").ToEntero().Contiene(3) Then AmortizacionNC += gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal End If Next End If 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 'SI LA VENTA ES NUEVA VALIDAR TAMBIEN LOS PAGOS DE CONTADO If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso CveVenta <= 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") Then If Not PermiteCredito AndAlso Not TienePagos AndAlso TxtTotal.Text.ToDecimal > 0 Then If MostrarAlertas Then Alert("Es necesario especificar un pago.", TipoMensaje.MsgAdvertencia) End If Retorno = True Return Retorno End If If (Not PermiteCredito OrElse RBLPago.SelectedValue = "2") AndAlso TienePagos AndAlso TxtTotal.Text.ToDecimal > 0 Then Dim TotalPago As Decimal = DtPagos.SUM("Importe").ToDecimal() + AmortizacionNC If TotalPago <> TxtTotal.Text.ToDecimal Then If MostrarAlertas Then Alert("La suma de los pagos debe ser igual al total de la venta.", TipoMensaje.MsgAdvertencia) End If Retorno = True Return Retorno End If End If End If 'VALIDA PAGOS EN FACTURAS DE ING,ANT NUEVAS O FACTURACION DE REM O COTIZACIONES If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso RBLPago.SelectedValue = "2" AndAlso ((CveVenta <= 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant")) OrElse TipoDoctoViejo.Contiene("Rem", "Cot")) Then If Not TienePagos AndAlso TxtTotal.Text.ToDecimal > 0 Then If MostrarAlertas Then Alert("Es necesario especificar un pago.", TipoMensaje.MsgAdvertencia) End If Retorno = True Return Retorno End If If TienePagos Then Dim TotalPagoContado As Decimal = If(DtPagos IsNot Nothing, DtPagos.SUM("Importe").ToDecimal(), 0) + AmortizacionNC Dim TotalProntoPago As Decimal = LblProntoPago.Text.ToDecimal() If UsuarioActual.Empresa.Funcionalidad(572) = "1" Then Dim TotalRNC As Decimal = If((ListaNCDesc IsNot Nothing AndAlso ListaNCDesc.Count > 0) OrElse (ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0), LblDescuentosRNC.Text.Trim().ToDecimal(), 0) Dim ImporteTotal As Decimal = (TxtTotal.Text.ToDecimal).RoundSQL(2) Dim TotalPagado = (TotalPagoContado + TotalRNC + TotalProntoPago).RoundSQL(2) If TotalPagado <> ImporteTotal Then If MostrarAlertas Then Alert("La suma de los pagos debe ser igual al total de la venta.", TipoMensaje.MsgAdvertencia) End If Retorno = True Return Retorno End If Else Dim TotalPagado = (TotalPagoContado + TotalProntoPago).RoundSQL(2) If TotalPagado <> TxtTotal.Text.ToDecimal.RoundSQL(2) Then If MostrarAlertas Then Alert("La suma de los pagos debe ser igual al total de la venta.", TipoMensaje.MsgAdvertencia) End If Retorno = True Return Retorno End If End If End If End If 'SI TIENE SALDO PENDIENTE VALIDA SI TIENE PAGOS If Me.SaldoVenta > 0 Then If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso (UsuarioActual.Empresa.Funcionalidad(531) = "1") AndAlso (Not PermiteCredito) AndAlso Not TienePagos And TxtTotal.Text.ToDecimal > 0 Then If MostrarAlertas Then Alert("Es necesario especificar un pago.", TipoMensaje.MsgAdvertencia) End If Retorno = True End If If UsuarioActual.Empresa.Funcionalidad(558) = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") Then If Not PermiteCredito AndAlso TienePagos AndAlso TxtTotal.Text.ToDecimal > 0 Then Dim TotalPago As Decimal = DtPagos.SUM("Importe").ToDecimal() + AmortizacionNC If TotalPago <> TxtTotal.Text.ToDecimal Then If MostrarAlertas Then Alert("La suma de los pagos debe ser igual al total de la venta.", TipoMensaje.MsgAdvertencia) End If Retorno = True Return Retorno End If End If End If If UsuarioActual.Empresa.Funcionalidad(572) = "1" Then Dim TotalNC As Decimal = If((ListaNCDesc IsNot Nothing AndAlso ListaNCDesc.Count > 0) OrElse (ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0), LblTotalAPagar.Text.Trim().ToDecimal(), 0) If TotalNC > 0 Then If (DtPagos.SUM("Importe").ToString().ToDecimal() + AmortizacionNC + Total - TxtCambio.Text.ToDecimal) > TotalNC Then If MostrarAlertas Then Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor verifique.", TipoMensaje.MsgAdvertencia) End If Retorno = True End If Else If (DtPagos.SUM("Importe").ToString().ToDecimal() + AmortizacionNC + Total - TxtCambio.Text.ToDecimal) > TxtTotal.Text.ToDecimal Then If MostrarAlertas Then Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor verifique.", TipoMensaje.MsgAdvertencia) End If Retorno = True End If End If Else If (DtPagos.SUM("Importe").ToString().ToDecimal() + AmortizacionNC + Total - TxtCambio.Text.ToDecimal) > TxtTotal.Text.ToDecimal Then If MostrarAlertas Then Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor verifique.", TipoMensaje.MsgAdvertencia) End If Retorno = True End If End If End If Return Retorno End Function #End Region #Region " SERIE ALMACEN " Protected Sub BtnSerie_Click(sender As Object, e As EventArgs) Dim Row = CType(CType(sender, Button).NamingContainer, GridViewRow) If Row.FCTextBox("TxtSerie").Text.Trim = "" Then Exit Sub Dim Index = Row.RowIndex Dim ObjInventarios As New ClsInventarios Dim Existencia = ObjInventarios.GetExistenciasPSSerie(Row.FCTextBox("TxtSerie").Text.ToString(), ddlAlmacen.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("Serie = '{0}'", Row.FCTextBox("TxtSerie").Text.ToString())) 'Valida Existencia If Existencia - ExistenciaActual <= 0 Then Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", Row.FCTextBox("TxtSerie").Text.ToString()), TipoMensaje.MsgAdvertencia) Row.FCTextBox("TxtSerie").Text = "" Row.FCHiddenField("HdnSerie").Value = "" TmpDT.Rows(Index)("Serie") = "" Else Row.FCHiddenField("HdnSerie").Value = Row.FCTextBox("TxtSerie").Text TmpDT.Rows(Index)("Serie") = Row.FCTextBox("TxtSerie").Text End If TmpDT.AcceptChanges() DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") ObjInventarios.Dispose() UpINV.Update() End Sub Private Function ValidaSerieINV() As Boolean Dim Retorno = False Dim Existencia = 0.0 Dim ExistenciaActual = 0.0 Dim ObjInventarios As New ClsInventarios For Each Gvr As GridViewRow In GvInv.Rows If Gvr.FCCheckBox("cbInv").Checked Then 'VACIO If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim = "" Then Alert("Algun producto con salida de inventario no tiene especificada la SERIE. Por favor verifique.", TipoMensaje.MsgAdvertencia) Retorno = True Exit For End If 'SIN EXISTENCIA If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim <> "" Then Existencia = ObjInventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, ddlAlmacen.SelectedValue.ToEntero(), Serie:=Gvr.FCTextBox("TxtSerie").Text.ToString(), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1) ExistenciaActual = DtInv.SUM("Cantidad", String.Format("Serie = '{0}'", Gvr.FCTextBox("TxtSerie").Text.Trim)) 'Valida Existencia If Existencia - ExistenciaActual < 0 Then Alert(String.Format("No hay existencia suficiente del producto con la Serie: {0}. Por favor rectifique y vuelva a intentar", Gvr.FCTextBox("TxtSerie").Text.ToString()), TipoMensaje.MsgAdvertencia) Gvr.FCTextBox("TxtSerie").Text = "" Retorno = True Exit For End If End If End If Next Return Retorno End Function #End Region #Region " BUSCAR CLIENTE " Protected Sub BtnBuscarCliente_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnBuscarCliente.Click ViewState("CveCliente") = HdnCveCliente.Value.ToEntero() CargaCliente(HdnCveCliente.Value.ToEntero()) If DdlPS.SelectedValue IsNot Nothing AndAlso DdlPS.SelectedValue.ToEntero() > 0 Then DdlPS_SelectedIndexChanged(sender, e) DdlPS.Focus() Else TxtCantidad.Focus() End If 'DdlPS.SelectedIndex = 14 'DdlPS_SelectedIndexChanged(sender, e) 'TxtCantidad.Focus() 'CARGA CONTRATOS VerificarContrato() End Sub Private Sub LnkAgregarCliente_Click(sender As Object, e As EventArgs) Handles LnkAgregarCliente.Click DivNombreCliente.Visible = False DivTipoPersona.Visible = False DivDireccionCliente.Visible = False DivNumeroCPCliente.Visible = False DivColoniaTelefonoCliente.Visible = False DivCiudadLocalidadCliente.Visible = False DivEstadoPaisCliente.Visible = False DivCorreoCuentaCliente.Visible = False DivBotonesAgregarCliente.Visible = False DivFormaCliente.Visible = False UpAgregarCliente.Update() CargaEstados() RegistraScript("showDivEC();") End Sub Private Sub BtnValidarRFC_Click(sender As Object, e As EventArgs) Handles BtnValidarRFC.Click If TxtRFCCliente.Text.ToUpper = "XAXX010101000" Then DivNombreCliente.Visible = True DivTipoPersona.Visible = True DivDireccionCliente.Visible = True DivNumeroCPCliente.Visible = True DivColoniaTelefonoCliente.Visible = True DivCiudadLocalidadCliente.Visible = True DivEstadoPaisCliente.Visible = True DivCorreoCuentaCliente.Visible = True DivBotonesAgregarCliente.Visible = True DivFormaCliente.Visible = True RFVDireccionC.Visible = False RFVNoEC.Visible = False RFVColoniaC.Visible = False RFVCiudadC.Visible = False RFVLocalidadC.Visible = False RFVSATPais.Visible = False DdlMetodoCliente.SelectedValueExist(1) DdlFormaCliente.SelectedValueExist(1) Else Dim ObjCliente As New ClsClientes If ObjCliente.ValidaClienteRFC(TxtRFCCliente.Text, UsuarioActual.CveEmpresa) Then If ObjCliente.DtResultados.Rows.Count > 0 Then RegistraScript("hideDivEC();") ViewState("CveCliente") = ObjCliente.DtResultados(0)("CveCliente").ToString().ToEntero() HdnCveCliente.Value = ObjCliente.DtResultados(0)("CveCliente").ToString() CargaCliente(CveCliente) UpCliente.Update() Else DivNombreCliente.Visible = True DivTipoPersona.Visible = True DivDireccionCliente.Visible = True DivNumeroCPCliente.Visible = True DivColoniaTelefonoCliente.Visible = True DivCiudadLocalidadCliente.Visible = True DivEstadoPaisCliente.Visible = True DivCorreoCuentaCliente.Visible = True DivBotonesAgregarCliente.Visible = True DivFormaCliente.Visible = True End If End If ObjCliente.Dispose() RFVDireccionC.Visible = True RFVNoEC.Visible = True RFVColoniaC.Visible = True RFVCiudadC.Visible = True RFVLocalidadC.Visible = True RFVSATPais.Visible = True DdlMetodoCliente.SelectedValueExist(-1) DdlFormaCliente.SelectedValueExist(-1) End If End Sub Private Sub BtnAgregarCliente_Click(sender As Object, e As EventArgs) Handles BtnAgregarCliente.Click Dim CvePrecioLista As Integer = -1 If DdlSubProyectoDatos.SelectedValue.ToEntero() > 0 Then Dim Dr As DataRow = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa).Rows(0) If Dr IsNot Nothing Then If Dr("CvePrecioLista").ToString().ToEntero() > 0 Then CvePrecioLista = Dr("CvePrecioLista").ToString().ToEntero() End If End If End If Dim ObjCliente As New ClsClientes Dim TipoPersona As Boolean = If(RdTipoPersona.SelectedValue.ToEntero = 1, True, False) If ObjCliente.AgregarClienteNoFrecuente(TxtNombreCliente.Text.Trim, TxtDireccionCliente.Text.Trim, TxtNumExtCliente.Text.Trim, TxtNumIntCliente.Text.Trim, TxtColoniaCliente.Text.Trim, TxtLocalidadCliente.Text.Trim, TxtCiudadCliente.Text.Trim, DdlEstadoSAT.SelectedValue.ToEntero, TxtRFCCliente.Text.Trim, TxtCPCliente.Text.Trim, TxtTelefonoCliente.Text.Trim, TxtCorreoCliente.Text.Trim, DdlSubProyectoDatos.SelectedValue.ToEntero(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "", -1, -1, CvePrecioLista:=CvePrecioLista, RegimenSociedad:=TxtRegimenSociedad.Text, TipoPersona:=TipoPersona) Then If ObjCliente.DtResultados.Rows.Count > 0 Then RegistraScript("hideDivEC();") ViewState("CveCliente") = ObjCliente.DtResultados(0)("CveCliente").ToString().ToEntero() HdnCveCliente.Value = ObjCliente.DtResultados(0)("CveCliente").ToString() CargaCliente(CveCliente) UpCliente.Update() End If End If ObjCliente.Dispose() RecargaGlobalCliente() End Sub Private Sub RecargaGlobalCliente() 'Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDTCliente) 'Hilo.Start() GeneraGlobalDTCliente() End Sub Private Sub GeneraGlobalDTCliente() GlobalDTCliente(UsuarioActual.CveEmpresa) = Nothing 'Dim Objclientes As New ClsClientes 'If Objclientes.GetClientes(-1, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus:=-1, TipoCliente:=-1) Then ' Application("GlobalDTCliente" & UsuarioActual.CveEmpresa) = Objclientes.DtResultados 'End If 'Objclientes.Dispose() End Sub #End Region #Region " INVENTARIO POR ENTREGA" Private Sub InventarioMov(Optional CveVentaPadre As Integer = -1) If CveVentaPadre > 0 Then Dim ObjVentas As New ClsVentas() If ObjVentas.GetVenta(CveVentaPadre, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 AndAlso ObjVentas.DtResultados.Rows(0)("TipoDocto").ToString() = "Ing" AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then ' Dim CveEstatusRefacturacion As Integer = ObjVentas.DtResultados.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero() ' If CveEstatusRefacturacion = 2 Then CargaInventario(Me.CveVenta) 'End If Else CargaInventario(Me.CveVenta) End If End If ObjVentas.Dispose() Else CargaInventario(Me.CveVenta) End If End Sub Private Sub CargaInventario(CveVenta As Integer) Dim ObjInv As New ClsInventarios If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then If ObjInv.DtResultados.Rows.Count > 0 Then If UsuarioActual.TienePermisoProceso(269) AndAlso Not DevolucionAlmacen = 2 Then DivDevAlm.Visible = True TieneAlmacen = True End If CargaGVInv(ObjInv.DtResultados) End If End If ObjInv.Dispose() 'si es la empresa 119, Candado, no permite refacturar, si no se ha surtido y que no sea refacturación, para que cancele la factura mejor. If UsuarioActual.CveEmpresa = 119 AndAlso LkRefacturacion.Visible AndAlso VentaSaldoAlmacen = 0 And CveVentaPadre <= 0 Then LkRefacturacion.Visible = False End If If UsuarioActual.CveEmpresa = 119 AndAlso CveVenta = 620098 Then LkRefacturacion.Visible = True End If End Sub Private Sub CargaGVInv(DtTemporal As DataTable) If Not DtTemporal.Columns.Contains("Lote") Then DtTemporal.Columns.Add("Lote", Type.GetType("System.String")) End If If Not DtTemporal.Columns.Contains("FechaCaducidad") Then DtTemporal.Columns.Add("FechaCaducidad", Type.GetType("System.DateTime")) End If If Not DtTemporal.Columns.Contains("Serie") Then DtTemporal.Columns.Add("Serie", Type.GetType("System.String")) End If GvInv.Columns(4).Visible = DtTemporal.MAX("Serie", "Serie <> ''") <> "" Or CveVenta <= 0 GvInv.Columns(5).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> "" GvInv.Columns(6).Visible = DtTemporal.MAX("FechaCaducidad").ToDate > MinFecha GvInv.DataSource = DtTemporal GvInv.DataBind() UpINV.Update() End Sub #End Region #Region "IMPUESTOS LOCALES" Private Sub GvImpuestosLocales2_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvImpuestosLocales2.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then 'e.Row.FCTextBox("TxtImpuestoLocalPS").Text = (TxtSubTotal.Text.ToDouble - (TxtSubTotal.Text.ToDouble * (e.Row.DBCampo("Porcentaje").ToString().ToDouble) / 100)).ToString() e.Row.FCTextBox("TxtImpuestoLocalPS").Attributes.Add("onKeyUp", String.Format("FnSuma();")) End If End Sub Private Function RegeneracionPolizas(ByRef ObjVentas As ClsVentas, ByRef ObjAC As ClsContPAQi, 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, ObjAC, 1, ObjBancos, ObjVentas) If Not ErrorCancelar Then ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, 1) Return ErrorCancelar End Function #End Region #Region " DEVOLUCION ALMACEN " Private Sub InicializaDevolucionAlmacen() If Not GvInv.Rows.Count > 0 Then Exit Sub End If If CveVenta > 0 AndAlso (SaldoVenta = TxtTotal.Text.ToDecimal OrElse DdlTipoComprobante.SelectedValue = "Dev" OrElse (DdlTipoComprobante.SelectedValue = "Ped" AndAlso TmpDT IsNot Nothing AndAlso TmpDT.COUNT("CveContratoDetalle", "CveContratoDetalle > 0") > 0)) Then 'And (DdlTipoComprobante.SelectedValue.Contiene({"Rem", "Ped"}) Or (DdlTipoComprobante.SelectedValue.Contiene({"Ing"}) And TxtFecha.Text.ToDate.Month = Now.Month And TxtFecha.Text.ToDate.Year = Now.Year)) Then If Not DevolucionAlmacen = 2 Then 'If UsuarioActual.Empresa.Funcionalidad(555) = "1" Then LiDevolucionAlmacen.Visible = True 'End If End If If DevolucionAlmacen = 1 Then LBDevolucionAlmacen.Text = " Cancelar Devolución Almacén" LBDevolucionAlmacen.ToolTip = "¿Está seguro de Cancelar la Devolución de Almacén?" Else LBDevolucionAlmacen.Text = " Solicitar Devolución Almacén" LBDevolucionAlmacen.ToolTip = "¿Está seguro de Solicitar la Devolución de Almacén?" End If If VentaSaldoAlmacen < 0 Then If DevolucionAlmacen = 0 Then LBAplicaDevolucion.Visible = True ElseIf DevolucionAlmacen.Contiene(1, 2) Then LBAplicaDevolucion.Visible = False End If ElseIf VentaSaldoAlmacen >= 0 Then LBAplicaDevolucion.Visible = False End If End If UpnTools.Update() 'UpInvDev.Update() End Sub Protected Sub LBDevolucionAlmacen_Click(sender As Object, e As EventArgs) Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0) Me.DevolucionAlmacen = DbRowVenta("EsDevolucionVenta").ToString().ToEntero() End If End If If Me.DevolucionAlmacen.Contiene(2) Then InicializaDevolucionAlmacen() UpnTools.Update() ObjVentas.Dispose() Alert("El movimiento ya fue devuelto.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim EstatusDevolucion = If(Me.DevolucionAlmacen = 0, 1, 0) If ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then Alert("La solicitud de Devolución de Almacén se guardó correctamente") End If ObjVentas.Dispose() Me.DevolucionAlmacen = EstatusDevolucion InicializaDevolucionAlmacen() 'UpnTools.Update() End Sub #End Region #Region "D I R E C C I O N E N V I O" Private Sub CargaDireccionesEnvio() Dim ObjClientes As New ClsClientes Dim TieneError = False DdlDireccionEnvio.Items.Clear() If ObjClientes.DireccionEnvioGet(-1, CveCliente, CveClienteSucursal) Then DdlDireccionEnvio.DataSource = ObjClientes.DtResultados.FiltraParametros(String.Format("Estatus = 1")) DdlDireccionEnvio.DataBind() 'DdlDireccionEnvio.Items.Insert(0, New ListItem("Seleccione", "-1")) TmpDTEnvioDireccion = ObjClientes.DtResultados Else TieneError = True End If If TieneError Then Alert("Ocurrió un error al obtener las direcciones de envío", TipoMensaje.MsgError) End If ObjClientes.Dispose() UpCliente.Update() End Sub Private Sub ChkDireccionEnvio_CheckedChanged(sender As Object, e As EventArgs) Handles ChkDireccionEnvio.CheckedChanged If ChkDireccionEnvio.Checked Then DdlDireccionEnvio.Visible = True LnkOtraDireccion.Visible = True Else DdlDireccionEnvio.Visible = False LnkOtraDireccion.Visible = False End If End Sub Private Sub BtnAgregarDireccion_Click(sender As Object, e As EventArgs) Handles BtnAgregarDireccion.Click Dim ObjClientes As New ClsClientes Dim TieneError = False Dim CveDireccionEnvio As Integer CveDireccionEnvio = ObjClientes.DireccionEnvioAdd(CveCliente, TxtEnvioDireccion.Text.Trim, TxtEnvioNoExt.Text.Trim, TxtEnvioNoInt.Text.Trim, DdlDirClienteColonia.SelectedItem.Text.Trim, DdlDirClienteMunicipio.SelectedItem.Text.Trim, DdlDirClienteEstado.SelectedItem.Text.Trim, TxtEnvioCP.Text.ToEntero(), TxtEnvioContacto.Text.Trim, UsuarioActual.CveUsuario, 1, CveClienteSucursal:=CveClienteSucursal, EnvioTel:=TxtEnvioTel.Text.Trim.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace("_", ""), CvePais:=DdlDirClientePais.SelectedValue.ToEntero, CveEstado:=DdlDirClienteEstado.SelectedValue.ToEntero, CveMunicipio:=DdlDirClienteMunicipio.SelectedValue.ToEntero, CveLocalidad:=DdlDirClienteLocalidad.SelectedValue.ToEntero, CveColonia:=DdlDirClienteColonia.SelectedValue.ToEntero) If CveDireccionEnvio < 0 Then TieneError = True End If If Not TieneError Then 'TxtDireccion.Text = "" 'TxtColonia.Text = "" 'TxtCiudad.Text = "" 'TxtEstado.Text = "" 'TxtCP.Text = "" 'TxtNoExt.Text = "" 'TxtNoInt.Text = "" 'TxtContacto.Text = "" 'TxtDepartamento.Text = "" TxtEnvioDireccion.Text = "" TxtEnvioNoExt.Text = "" TxtEnvioNoInt.Text = "" DdlDirClienteEstado.SelectedValueExist("-1") DdlDirClienteMunicipio.SelectedValueExist("-1") DdlDirClienteColonia.SelectedValueExist("-1") 'TxtEnvioColonia.Text = "" 'TxtEnvioCiudad.Text = "" 'TxtEnvioEstado.Text = "" TxtEnvioContacto.Text = "" TxtEnvioCP.Text = "" TxtEnvioTel.Text = "" CargaDireccionesEnvio() DdlDireccionEnvio.SelectedValueExist(CveDireccionEnvio) 'DdlDireccionEnvio_SelectedIndexChanged(DdlDireccionEnvio, EventArgs.Empty) End If ObjClientes.Dispose() RegistraScript("$('#divAddDireccionEnvio').modal('hide');") End Sub Private Sub LnkOtraDireccion_Click(sender As Object, e As EventArgs) Handles LnkOtraDireccion.Click 'TxtDireccion.Text = LblDireccion.Text.Trim 'TxtNoExt.Text = CliNoExt.Trim 'TxtNoInt.Text = CliNoInt.Trim 'TxtColonia.Text = LblColonia.Text.Trim 'TxtCiudad.Text = LblCiudad.Text.Trim 'TxtEstado.Text = LblEstado.Text.Trim 'TxtCP.Text = LblCP.Text.Trim CargaCombosDirecionesClientesSAT() Dim DtDireccionEnvio As DataTable = Nothing Dim ObjClientes As New ClsClientes If ObjClientes.DireccionEnvioGet(DdlDireccionEnvio.SelectedValue.ToEntero(), CveCliente, CveClienteSucursal) Then DtDireccionEnvio = ObjClientes.DtResultados End If ObjClientes.Dispose() If DtDireccionEnvio IsNot Nothing And DtDireccionEnvio.Rows.Count > 0 Then Dim Dr As DataRow = DtDireccionEnvio.Rows(0) TxtEnvioDireccion.Text = Dr("EnvioDireccion").ToString() TxtEnvioNoExt.Text = Dr("EnvioNoExt").ToString() TxtEnvioNoInt.Text = Dr("EnvioNoInt").ToString() TxtEnvioContacto.Text = Dr("EnvioContacto").ToString() TxtEnvioCP.Text = Dr("EnvioCP").ToString() TxtEnvioTel.Text = Dr("EnvioTel").ToString() DdlDirClientePais.SelectedValueExist(Dr("CvePais")) CargaDirClienteEstado() DdlDirClienteEstado.SelectedValueExist(Dr("CveEstado")) CargaDirClienteMunicipio() DdlDirClienteMunicipio.SelectedValueExist(Dr("CveMunicipio")) CargaDirClienteColonia() DdlDirClienteLocalidad.SelectedValueExist(Dr("CveLocalidad")) CargaDirClienteLocalidad() DdlDirClienteColonia.SelectedValueExist(Dr("CveColonia")) Else TxtEnvioDireccion.Text = LblDireccion.Text.Trim TxtEnvioNoExt.Text = CliNoExt.Trim TxtEnvioNoInt.Text = CliNoInt.Trim DdlDirClienteEstado.SelectedValueExist("-1") DdlDirClienteMunicipio.SelectedValueExist("-1") DdlDirClienteColonia.SelectedValueExist("-1") 'TxtEnvioColonia.Text = LblColonia.Text.Trim 'TxtEnvioCiudad.Text = LblCiudad.Text.Trim 'TxtEnvioEstado.Text = LblEstado.Text.Trim TxtEnvioContacto.Text = "" TxtEnvioCP.Text = LblCP.Text.Trim TxtEnvioTel.Text = "" End If UpBodyDireccion.Update() RegistraScript("$('#divAddDireccionEnvio').modal();") End Sub #Region "D I R E C C I O N E N V I O - C O M B O S" Protected Sub BtnDirClienteValidar_Click(sender As Object, e As EventArgs) DirClientevalidaCodigoPostal() End Sub Private Sub CargaCombosDirecionesClientesSAT() CargaDirClientePais() CargaDirClienteEstado() CargaDirClienteMunicipio() CargaDirClienteLocalidad() CargaDirClienteColonia() End Sub Private Sub CargaDirClientePais() DdlDirClientePais.DataSource = GlobalDTGralPaises() DdlDirClientePais.DataBind() DdlDirClientePais.SelectedValueExist("151") End Sub Private Sub CargaDirClienteEstado() DdlDirClienteEstado.Items.Clear() If DdlDirClientePais.SelectedValue.ToEntero > 0 Then DdlDirClienteEstado.DataSource = GlobalDTGralEstados("-1", DdlDirClientePais.SelectedValue.ToEntero) End If DdlDirClienteEstado.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlDirClienteEstado.DataBind() End Sub Private Sub CargaDirClienteColonia() DdlDirClienteColonia.Items.Clear() If DdlDirClienteMunicipio.SelectedValue.ToEntero > 0 Then DdlDirClienteColonia.DataSource = GlobalDTGralColonias("-1", "-1", "-1", DdlDirClienteMunicipio.SelectedValue.ToEntero, CodigoPostal:=If(TxtEnvioCP.Text.Trim.Length > 0, TxtEnvioCP.Text.ToEntero, -1)) End If DdlDirClienteColonia.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlDirClienteColonia.DataBind() End Sub Protected Sub CargaDirClienteLocalidad() DdlDirClienteLocalidad.Items.Clear() If DdlEstadoSAT.SelectedValue.ToEntero > 0 Then DdlDirClienteLocalidad.DataSource = GlobalDTLocalidad(DdlDirClienteEstado.SelectedValue.ToEntero, DdlDirClienteMunicipio.SelectedValue.ToEntero) DdlDirClienteLocalidad.DataBind() End If DdlDirClienteLocalidad.Items.Insert(0, New ListItem("Seleccione una", "-1")) End Sub Private Sub CargaDirClienteMunicipio() DdlDirClienteMunicipio.Items.Clear() If DdlDirClienteEstado.SelectedValue.ToEntero > 0 Then DdlDirClienteMunicipio.DataSource = GlobalDTGralMunicipios("-1", DdlDirClienteEstado.SelectedValue.ToEntero) End If DdlDirClienteMunicipio.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlDirClienteMunicipio.DataBind() End Sub Protected Sub DdlDirClientePais_SelectedIndexChanged(sender As Object, e As EventArgs) CargaDirClienteEstado() CargaDirClienteMunicipio() CargaDirClienteColonia() CargaDirClienteLocalidad() End Sub Protected Sub DdlDirClienteEstado_SelectedIndexChanged(sender As Object, e As EventArgs) CargaDirClienteMunicipio() CargaDirClienteColonia() CargaDirClienteLocalidad() End Sub Protected Sub DdlDirClienteMunicipio_SelectedIndexChanged(sender As Object, e As EventArgs) CargaDirClienteColonia() CargaDirClienteLocalidad() End Sub Protected Sub DdlDirClienteColonia_SelectedIndexChanged(sender As Object, e As EventArgs) DirClientevalidaCodigoPostal() End Sub Private Sub DirClientevalidaCodigoPostal() Dim CPTxt As Integer = TxtEnvioCP.Text.ToEntero() Dim CveColonia As Integer = DdlDirClienteColonia.SelectedValue.ToEntero If CPTxt > 0 And CveColonia > 0 Then Dim CP As Integer = GlobalDTGralColonias("-1", "-1", "-1", CveColonia:=CveColonia).FiltroPrimeroValor("CP", "").ToEntero If CPTxt <> CP Then Alert("El código postal selecionado es diferente del codigo postal de la Colonia.", TipoMensaje.MsgAdvertencia) End If End If End Sub #End Region #End Region #Region " CARGA FACTURA OC " Private Sub CargaFacturaOC() CveOC = IfNull(Request("CveOC"), -1).ToString().ToEntero() If CveOC > 0 Then Dim tDT As DataTable = Nothing Dim ObjOC As New ClsOC If ObjOC.GetOCFacturacion(CveOC, UsuarioActual.CveEmpresa) Then tDT = ObjOC.DtResultados.Copy() 'tTmpDT.Columns.Add("TipoDocto", GetType(String)) 'tTmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) 'tTmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) Else Alert("Ocurrió un error al obtener los detalles de la orden de compra. Por favor vuelva a intentar.", TipoMensaje.MsgError) End If ObjOC.Dispose() If tDT IsNot Nothing AndAlso tDT.Rows.Count > 0 Then ViewState("CveCliente") = tDT.Rows(0)("CveCliente") HdnCveCliente.Value = CveCliente.ToString() CargaCliente(CveCliente) If (DdlTipoComprobante.Items.FindByValue("Rem") IsNot Nothing) Then DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem")) End If For Each Dr As DataRow In tDT.Rows AgregarProductoServicio(Dr("Cantidad").ToString().ToDecimal, Dr("CveUM").ToString().ToEntero(), Dr("UM").ToString(), Dr("CveClasificacion").ToString().ToEntero(), Dr("Clasificacion").ToString(), Dr("CvePS").ToString().ToEntero(), Dr("PS").ToString(), Dr("Obs").ToString(), Dr("PU").ToString().ToDecimal, Dr("Descuento").ToString().ToDecimal, Dr("CveProyecto").ToString().ToEntero(), Dr("Proyecto").ToString(), Dr("CveSubProyecto").ToString().ToEntero(), Dr("SubProyecto").ToString(), CveContratoDetalle:=Dr("CveContratoDetalle").ToString().ToEntero(), CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString().ToEntero()) Next 'GvPS.DataSource = TmpDT 'GvPS.DataBind() 'TxtSubTotal.Text = TmpDT.SUM("Total").FormatoNumero(2) 'TxtIVA.Text = (TxtSubTotal.Text.ToDecimal * ViewState("IVA").ToString().ToDecimal).ToString() 'CalculaTotalesImpuestosLocales() 'CalculaTotales(False) UpPS.Update() VerificarContrato(True) If UsuarioActual.TienePermisoProceso(175) Then DdlTipoComprobante.Items.FindByText("Egresos").Enabled = False End If DdlTipoComprobante.Items.FindByText("Cotización").Enabled = False DdlTipoComprobante.Items.FindByText("Anticipos").Enabled = False 'DESACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto disabled") TxtCodigo.ReadOnly = True UpCliente.Update() tDT.Dispose() Else Alert("No se encontró la orden de compra especificada. Por favor verifique y vuelta a intentar.", TipoMensaje.MsgAdvertencia) End If CalculaTotalesVenta() End If End Sub #End Region #Region "CargaFactura" Private Function CargaFactura(CveFactura As Integer) As String Dim RFC As String = "" Dim XMLDoc As New XmlDocument Dim Archivo As String = String.Format("{0}Ventas\{1}\{2}", UsuarioActual.Empresa.Ruta, Request("RFC"), $"{Request("CveFactura")}.xml") If IO.File.Exists(Archivo) Then Dim Validada As Boolean = True LbAgregar.Visible = False If Validada Then XMLDoc.Load(Archivo) CreaDTConceptos() CargaConceptosXML(XMLDoc) CargaComprobanteXML(XMLDoc) Select Case TipoComprobante Case "ingreso" : DdlTipoComprobante.SelectedValue = "Ing" Case "egreso" : DdlTipoComprobante.SelectedValue = "Egs" End Select Dim Descuentos As Decimal = 0 RFC = ReceptorRFC TxtFecha.Text = Fecha TxtFolio.Text = FolioXML.ToString() If (FolioXML <> "") Then ViewState("ExFolioFactura") = True End If Dim IVA As Decimal IVA = TrasladoIVA If Not UsuarioActual.TienePermisoProceso(130) Then TxtFolio.Enabled = False End If DdlTipoComprobante.Enabled = False TxtFecha.Enabled = False ImgFecha.Enabled = False TxtSubTotal.Enabled = False TxtSubTotal2.Enabled = False TxtIVA.Enabled = False 'TxtTotal.Enabled = False RegistraScript("SetDisabledTxtTotal(true);") If TxtFolio.Text.Trim = "" Then TxtFolio.Enabled = True If UsuarioActual.TienePermisoProceso(112) Then TxtSubTotal.Enabled = True TxtSubTotal2.Enabled = True TxtIVA.Enabled = True 'TxtTotal.Enabled = True RegistraScript("SetDisabledTxtTotal(false);") End If TxtIVA.Text = IVA.FormatoNumero TxtRetIVA.Text = RetencionIVA.FormatoNumero LblDescuentos.Text = Descuentos.FormatoNumero TxtFecha.Text = Fecha.ToDate.ToShortDateString Dim Msg As String = "" 'PRUEBA 'http://rm/Compras/Compras.aspx?CveFactura=122518 Emp: 48 'tTotal = Math.Round(SubTotal2 + IVA - RetencionIVA - RetencionISR + IEPS + OtrosImpuestos, 2) Dim AjustaUltimoConcepto = False 'en otro impuesto lo esta registrando en ajuste en automatico If OtrosImpuestos > 0 Then AjustaUltimoConcepto = True End If If RFC = "CFE370814QI0" Then ' RFC de CFE, se hace un ajuste por diferencia para sacar el DAP 'OtrosImpuestos = Total - (SubTotal2 + IVA) 'este importe lo vamos a meter al gasto 'AjustaImporteUltimoConcepto(OtrosImpuestos) OtrosImpuestos = 1 AjustaUltimoConcepto = True 'SubTotal2 = SubTotal End If Dim SubTotalReal As Decimal = Math.Round(Total + RetencionISR + RetencionIVA - IVA + Descuentos, 2) ' NO se incluye otros impuestos para ajustar esa cifra Dim DiferenciaTotales As Decimal = SubTotalReal - Math.Round(SubTotalConceptos, 2) ViewState("Folio") = FolioXML End If Else Alert("No se encontró la factura", TipoMensaje.MsgAdvertencia) End If 'GvPS.DataSource = 'DTConceptos 'GvPS.DataBind() Return RFC End Function Private Sub CreaDTConceptos() DTConceptos = New DataTable DTConceptos.Columns.Add("Consec", GetType(Integer)) DTConceptos.Columns.Add("Cantidad", GetType(Decimal)) DTConceptos.Columns.Add("UM", GetType(String)) DTConceptos.Columns.Add("CveClasificacion", GetType(Integer)) DTConceptos.Columns.Add("PS", GetType(String)) DTConceptos.Columns.Add("PU", GetType(Decimal)) DTConceptos.Columns.Add("Descuento", GetType(Decimal)) DTConceptos.Columns.Add("IVA", GetType(Decimal)) DTConceptos.Columns.Add("Total", GetType(Decimal)) End Sub Private Sub CargaConceptosXML(XMLDoc As XmlDocument) Dim i As Integer = 0 Dim node As XmlNode Dim PU As Decimal = 0 Dim Descuento As Double = 0 Dim CveUM As Integer = 0 Dim UMM As String = "No Aplica" Dim tCvePS As Integer = 0 Dim TipoPS As Integer = 0 Dim tCveClasif As Integer = -1 Dim Clasif As String = "Sin Clasificación" Dim tPSCodigo As String = "-" Dim tPSDescripcion As String = "-" Dim PSS As String = "" Dim Obs As String = "" Dim SubTotalTemp = 0.0D 'GLOBALS Dim DtUM = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa).AsEnumerable Dim DtUMAlias = GlobalDTUnidadesMedidaAlias(UsuarioActual.CveEmpresa).AsEnumerable 'Dim DtPS = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).AsEnumerable Dim DtPS = GlobalDTPS(UsuarioActual.CveEmpresa).AsEnumerable Dim DtPSAlias = GlobalDTProductosServiciosAlias(UsuarioActual.CveEmpresa).AsEnumerable ''AGREGA EN TABLA TEMPORAL 'Dim DtPSTemp = TmpDT.Clone 'Dim Row As DataRow = Nothing For i = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1 ' INICIALIZA VALORES PU = 0 Descuento = 0 CveUM = 0 UMM = "No Aplica" tCvePS = 0 TipoPS = 0 tCveClasif = -1 Clasif = "Sin Clasificación" tPSCodigo = "-" tPSDescripcion = "-" PSS = "" Obs = "" Total = 0 'CARGA NODO ACTUAL node = XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i) 'CARGA PU PU = ValorXML(node, "valorUnitario").ToDecimal 'SI PU >= TOTAL AND CANTIDAD > 0 : PU / CANTIDAD, por si tiene descuento en el importe y el valor unitario es mayor, lo ajusta If ValorXML(node, "cantidad").ToDecimal > 0 AndAlso ValorXML(node, "valorUnitario").ToDecimal >= (ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal) Then PU = ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal End If If ValorXML(node, "cantidad").ToDecimal > 0 AndAlso ValorXML(node, "valorUnitario").ToDouble <= 0 And ValorXML(node, "importe").ToDouble > 0 Then PU = ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal End If 'OBTIENE DESCUENTO If ValorXML(node, "descuento") IsNot Nothing Then Descuento = ValorXML(node, "descuento").Trim.ToDouble 'OBTIENE TOTAL If ValorXML(node, "importe") IsNot Nothing Then Total = ValorXML(node, "importe").Trim.ToDecimal 'OBTIENE SUBTOTAL SubTotalTemp += If(Total > 0, Total, PU * ValorXML(node, "cantidad").ToDecimal) 'OBTIENE UM If ValorXML(node, "unidad") IsNot Nothing Then UMM = ValorXML(node, "unidad").Trim 'BUSCA UM EN CATALOGO UMM = UMM.ToUpper.Replace(".", "").Replace(",", "") Dim fUM = (From u In DtUM Where String.Compare(u!UnidadMedida.ToString().ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0 OrElse String.Compare(u!Abreviatura.ToString().ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0 Select CveUnidadMedida = u!CveUnidadMedida, UnidadMedida = u!UnidadMedida).FirstOrDefault() If fUM IsNot Nothing AndAlso fUM.CveUnidadMedida.ToString().ToEntero() > 0 Then CveUM = fUM.CveUnidadMedida.ToString().ToEntero() UMM = fUM.UnidadMedida.ToString() Else 'BUSCA UM EN ALIAS Dim fUMAlias = (From u In DtUMAlias Where String.Compare(u!UnidadMedidaAlias.ToString().ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0 Select u!CveUnidadMedida, u!UnidadMedida).FirstOrDefault() If fUMAlias IsNot Nothing Then CveUM = fUMAlias.CveUnidadMedida.ToString().ToEntero() UMM = fUMAlias.UnidadMedida.ToString() End If End If 'se le puso una condicion de que ignorara los acentos, porque en la bd, marcaria error porque no distingue acentos 'CONCEPTO PRUEBA "TRABAJOS DE CONSTRUCCION", RM/Compras/Compras.aspx?CveFactura=13402&RFC=ECO061206QW7 '' u!PS.ToString().ToUpper.Trim = PSS 'BUSCA PS PSS = ValorXML(node, "descripcion").ToUpper.Trim.Replace(vbCrLf, " ").Replace(vbLf, " ").Replace("'", "''").Replace(" ", " ") If PSS.Length > 844 Then PSS = PSS.Substring(0, 844) '844,por ser el numero de caracteres aceptados en la columna de la BD End If tPSCodigo = PSS 'BUSCA PS EN CATALOGO Dim fPS = (From u In DtPS Where String.Compare(u!PS.ToString().ToUpper.Trim, PSS, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0 Select u!CvePS, u!CveClasificacion, u!Clasificacion, u!CveTipoPS, u!PSCodigo).FirstOrDefault() If fPS IsNot Nothing Then PSS = fPS.PSCodigo.ToString() tCvePS = fPS.CvePS.ToString().ToEntero() TipoPS = fPS.CveTipoPS.ToString().ToEntero() tCveClasif = fPS.CveClasificacion.ToString().ToEntero() Clasif = fPS.Clasificacion.ToString() tPSCodigo = fPS.PSCodigo.ToString() Else 'BUSCA PS EN ALIAS Dim fPSAlias = (From u In DtPSAlias Where String.Compare(u!PSAlias.ToString().ToUpper.Trim, PSS, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0 Select u!CvePS, u!PS, u!CveClasificacion, u!Clasificacion, u!CveTipoPS, u!PSCodigo).FirstOrDefault() If fPSAlias IsNot Nothing Then Obs = PSS PSS = fPSAlias.PS.ToString() tCvePS = fPSAlias.CvePS.ToString().ToEntero() TipoPS = fPSAlias.CveTipoPS.ToString().ToEntero() tCveClasif = fPSAlias.CveClasificacion.ToString().ToEntero() Clasif = fPSAlias.Clasificacion.ToString() tPSCodigo = fPSAlias.PSCodigo.ToString() Else tCvePS = 20168 End If End If 'PARA GLUYAS If UsuarioActual.CveEmpresa = 66 Then tPSCodigo = String.Format("{1} - {0}", ValorXML(node, "descripcion").ToUpper.Trim.Replace(vbCrLf, " ").Replace(vbLf, " ").Replace("'", "''"), ValorXML(node, "noIdentificacion").Trim) End If '' AGREGA PS 'AGREGA A TMPDT 'AddPS(ValorXML(node, "cantidad").ToDouble, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, TipoPS, "-1", "SE", "SE", Obs, PU, Total, 0, 0, PSCodigo:=tPSCodigo, TCalculaTotales:=False) AgregarProductoServicio(ValorXML(node, "cantidad").ToDecimal, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, Obs, PU, 0, 0, "", 0, "") Next CalculaTotalesVenta() 'AddPS2(False) 'Dim SubTotalConceptos = Math.Round(SubTotalTemp, 2) 'TmpDT = DtPSTemp.Copy 'DtPSTemp.Dispose() End Sub Private Sub CargaComprobanteXML(XMLDoc As XmlDocument) Dim nodo As XmlNode = XMLDoc.DocumentElement _SerieXML = ValorXML(nodo, "serie") If _SerieXML <> "" Then _SerieXML = _SerieXML _Version = ValorXML(nodo, "version") _FolioXML = ValorXML(nodo, "folio") _Fecha = ValorXML(nodo, "fecha") SubTotal = ValorXML(nodo, "subTotal").ToDecimal Total = ValorXML(nodo, "total").ToDecimal 'Descuentos = ValorXML(nodo, "descuento").ToDecimal _Moneda = ValorXML(nodo, "Moneda") _TipoComprobante = ValorXML(nodo, "tipoDeComprobante") Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix) Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) If Prefijo.ToLower <> "cfdi" Then cfdVer = "http://www.sat.gob.mx/cfd/2" namespaces.AddNamespace(Prefijo, cfdVer) namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal") namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal") Dim node As XmlNode node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then EmisorRFC = ValorXML(node, "RFC") 'EmisorNombre = ValorXML(node, "nombre") End If node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces) If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then ReceptorRFC = ValorXML(node, "RFC") End If node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces) If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces) TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDecimal For Each retencion As XmlNode In nodeRetenciones If retencion.Attributes("impuesto").Value = "IVA" Then RetencionIVA += retencion.Attributes("importe").Value.ToDecimal End If If retencion.Attributes("impuesto").Value = "ISR" Then RetencionISR += retencion.Attributes("importe").Value.ToDecimal End If ' Do something. Next SumaTotalRetenciones += RetencionIVA SumaTotalRetenciones += RetencionISR TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDecimal Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) For Each traslado As XmlNode In nodeTraslados If traslado.Attributes("impuesto").Value = "IVA" Then TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal End If If traslado.Attributes("impuesto").Value = "IEPS" Then TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal End If 'If traslado.Attributes("impuesto").Value = "ISR" Then ' TrasladoISR = traslado.Attributes("importe").Value 'End If ' Do something. Next SumaTotalTraslados += TrasladoIVA SumaTotalTraslados += TrasladoIEPS End If Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces) If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces) _TFDUUID = ValorXML(nodeTFD, "UUID", "") Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces) If nodeRF IsNot Nothing Then _FolioXML = ValorXML(nodeRF, "folio").TrimStart("0"c) End If node = node.SelectSingleNode(String.Format("//{0}:ImpuestosLocales", "implocal"), namespaces) If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then OtrosImpuestos = ValorXML(node, "TotaldeTraslados", "0").ToDecimal If RetencionIVA <= 0 AndAlso ValorXML(node, "TotaldeRetenciones", "0").ToDouble > 0 Then RetencionIVA = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal 'For Each retencion As XmlNode In nodeImpLocales ' If retencion.Attributes("impuesto").Value = "IVA" Then ' RetencionIVA += retencion.Attributes("importe").Value.ToDouble ' End If ' If retencion.Attributes("impuesto").Value = "ISR" Then ' RetencionISR += retencion.Attributes("importe").Value.ToDouble ' End If ' ' Do something. 'Next ' SumaTotalRetenciones += RetencionIVA ' SumaTotalRetenciones += RetencionISR 'TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble 'Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) 'For Each traslado As XmlNode In nodeTraslados ' If traslado.Attributes("impuesto").Value = "IVA" Then ' TrasladoIVA += traslado.Attributes("importe").Value.ToDouble ' End If ' If traslado.Attributes("impuesto").Value = "IEPS" Then ' TrasladoIEPS += traslado.Attributes("importe").Value.ToDouble ' End If ' 'If traslado.Attributes("impuesto").Value = "ISR" Then ' ' TrasladoISR = traslado.Attributes("importe").Value ' 'End If ' ' Do something. 'Next 'SumaTotalTraslados += TrasladoIVA 'SumaTotalTraslados += TrasladoIEPS End If End If End Sub Private Function ValorXML(n As XmlNode, Campo As String, Optional Retorno As String = "") As String Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, True) = 0) If o Is Nothing Then Return Retorno Else Return o.Value End If End Function #End Region #Region "Metodos Viejos" Private Sub GeneraPDF(FechaFactura As DateTime, FolioFiscal As String, NoSerieCertificado As String, FechaCertificacion As DateTime, NoSerieCertificadoContribuyente As String, DTConceptos As DataTable, SelloCFDi As String, SelloSAT As String, CBB As String, Folio As String, RutaXML As String, EsVistaPrevia As Boolean, MuestraAlert As Boolean, Optional MR As ReportViewer = Nothing) Alert("No se pudo generar el PDF", TipoMensaje.MsgError) End Sub Private Sub GeneraPDFCBB(FechaFactura As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean) End Sub Private Sub GeneraPDFCot(FechaCotizacion As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean, GeneraDescarga As Boolean) End Sub Private Sub LkEliminarFactura_Click(sender As Object, e As EventArgs) Handles LkEliminarFactura.Click If HdnPagado.Value.ToDecimal = 0 Then Dim ObjVentas As New ClsVentas ObjVentas.IniciaTransacSQL() If ObjVentas.EliminarVenta(CveVenta) Then ObjVentas.Commit() Alert("La venta ha sido eliminada correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Clientes.aspx?CveCliente=" & CveCliente & """;") Else ObjVentas.RollBack() End If ObjVentas.Dispose() Else Alert("La venta no se puede eliminar ya que tiene pagos vinculados.", TipoMensaje.MsgError) End If End Sub Private Sub RblComplementos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblComplementos.SelectedIndexChanged If RblComplementos.SelectedValue.Contiene("5", "6") Then 'Directivo/Ejecutivo Estatal trEntidad.Visible = True trContaComplementos.Visible = True trAmbito.Visible = False trTipoCampaña.Visible = False ElseIf RblComplementos.SelectedValue = "7" Then 'Ejecutivo Nacional trEntidad.Visible = False trContaComplementos.Visible = True trAmbito.Visible = False trTipoCampaña.Visible = False ElseIf RblComplementos.SelectedValue = "8" Then 'Campaña/PreCampaña trEntidad.Visible = True trContaComplementos.Visible = True trAmbito.Visible = True trTipoCampaña.Visible = True End If UpDatosComplementos.Update() End Sub Private Sub GvPS_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPS.RowCommand If e.CommandName = "Clonar" Then Dim RowNum As Integer = Convert.ToInt32(e.CommandArgument) Dim GvRow As GridViewRow = GvPS.Rows(RowNum) TxtCantidad.Text = GvPS.Rows(RowNum).FCLiteral("LtlCantidad").Text DdlClasificacion.SelectedValue = GvRow.DataKey("CveClasificacion") DdlPS.SelectedValue = GvRow.DataKey("CvePS") DdlPS_SelectedIndexChanged(Nothing, Nothing) DdlUnidadMedida.SelectedValue = GvRow.DataKey("CveUM") TxtObsPS.Text = GvRow.FCLiteral("LtlObsPS").Text DdlProyecto.SelectedValue = GvRow.DataKey("CveProyecto") DdlProyecto_SelectedIndexChanged(Nothing, Nothing) DdlSubProyecto.SelectedValue = GvRow.DataKey("CveSubProyecto") TxtPrecio.Text = GvRow.FCLiteral("LtlPU").Text RegistraScript("Recalcula();") LbAgregar_Click(Nothing, Nothing) 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 Private Sub LkCotizacionAutorizar_Click(sender As Object, e As EventArgs) Handles LkCotizacionAutorizar.Click EsSupervisor = True Dim ActualizoEstatus As Boolean = False Dim ObjVentas As New ClsVentas If ObjVentas.UpdateEstatusFactura(8, FolioFiscal, "", Now, CveVenta) Then ActualizoEstatus = True End If ObjVentas.Dispose() If ActualizoEstatus Then If UsuarioActual.Empresa.Funcionalidad(135) = "1" Then GeneraPDFCotizacion(True) Alert("La cotización ha sido enviada al correo de nuestro cliente:" & Mail) ElseIf UsuarioActual.Empresa.Funcionalidad(135) = "2" Then Alert("La cotización ha sido autorizada.") End If Else Alert("No se pudo autorizar la cotización", TipoMensaje.MsgError) End If End Sub #End Region #Region "Cancelar, Generar y mandar por correo el acuse de cancelación." Private Sub BtnEnviarMailCancelacion_Click(sender As Object, e As EventArgs) Handles BtnEnviarMailCancelacion.Click EnviarPDFCancelacion(HdnCveVentaAcuse.Value.ToEntero()) HdnCveVentaAcuse.Value = "0" End Sub Private Function DescargarPDF(Parametros As String) As Byte() Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?P={1}", ClsPaginas.UrlSitio, Parametros)) Dim File As Byte() = Nothing Try Using httpClient = New HttpClient() httpClient.Timeout = New TimeSpan(0, 15, 0) Using request = New HttpRequestMessage(HttpMethod.Get, Url) request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CVEUSUARIO={2}", UsuarioActual.CveEmpresa, DateTime.UtcNow.Ticks, UsuarioActual.CveUsuario))) Dim response = httpClient.SendAsync(request).Result If 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 Public Sub EnviarPDFCancelacion(CveVenta As Integer) Dim FacturaRef As New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, CargaDTDetalle:=False, CargaDatosRelacionados:=False) If FacturaRef IsNot Nothing Then Dim ObjetoPDF As Byte() = DescargarPDF(Encripta(String.Format("OP=CAN&CVEVTA={0}", CveVenta))) If ObjetoPDF IsNot Nothing Then Dim RFC = UsuarioActual.Empresa.RFC Dim ObjMail As New ClsSisMail Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) Dim Asunto As String = String.Empty Dim Cuerpo As String = String.Empty Dim ResultadoMail As Integer Dim sb As New StringBuilder() If UsuarioActual.CveEmpresa = 119 Then sb.Append("") sb.Append("") sb.Append("") sb.Append("") sb.Append(" Acuse De Cancelación") sb.Append(" ") sb.Append("") sb.Append("") sb.Append(" ") sb.Append($" Estimado Cliente {FacturaRef.Cliente.Nombre},

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




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

    ") sb.Append($" A través del presente medio la Empresa {UsuarioActual.Empresa.Empresa} - {RFC}, canceló el documento tipo {FacturaRef.TipodeComprobante}
    ") sb.Append($" con folio {FacturaRef.SerieFolio} y el Importe de ${FacturaRef.Total}.

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




    ") sb.Append(" Este correo se generó automaticamente, favor de no responder este mensaje.") sb.Append("
    ") sb.Append("") sb.Append("") End If Asunto = $"Acuse de Cancelación {FacturaRef.SerieFolio}" Cuerpo = sb.ToString() Dim DisplayName As String = "" If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM" LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.ArchivoBinario = ObjetoPDF, .NombreArchivo = $"AcuseCancelacion{FacturaRef.SerieFolio}.pdf"}) If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then ResultadoMail = 1 Alert("El acuse de cancelación ha sido envíado correctamente.", JSBtnAceptar:="BtnRefrescarPagina();", ShowCloseButton:=False) Else ResultadoMail = 0 End If sb.Clear() FacturaRef.Dispose() FacturaRef = Nothing End If Else Alert("No se pudo enviar el acuse de cancelación", TipoMensaje.MsgAdvertencia) End If End Sub Private Sub MostrarCondicionesCancelacion(Optional Extra As String = "") Dim SbCondiciones As New StringBuilder() If VentaSaldoAlmacen < 0 AndAlso ChkDevAlm.Checked Then SbCondiciones.Append("*Se realizará una devolución en automatico al realizar la cancelación.") End If If GvRemisiones.Rows.Count > 0 AndAlso Not DivCanRem.Visible AndAlso Not AplicaCancelarRemision Then SbCondiciones.Append("

    *No se puede cancelar las remisiones ligadas a la factura, esto puede deberse por los siguientes motivo:") SbCondiciones.Append("
         -La remisión no está facturada al 100%.") SbCondiciones.Append("
         -La remisión está relacionada con otra factura.") End If If Extra.Length > 0 Then SbCondiciones.AppendFormat("
    *{0}", Extra) End If LbCancelarDescripcion.Text = SbCondiciones.ToString() SbCondiciones.Clear() UpCancelarDocumento.Update() End Sub Private Sub LbCancelarDocumento_Click(sender As Object, e As EventArgs) Handles LbCancelarDocumento.Click If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then Dim sb As New StringBuilder() Dim sbExtra As New StringBuilder() sb.Append("La factura se encuentra en el siguiente estatus del SAT:
    ") Dim TotalT As Decimal = TxtTotal.Text.ToDecimal Dim RFCReceptor As String = "" If String.IsNullOrEmpty(Me.RFCReceptorVenta) Then RFCReceptor = LblRFC.Text.Trim 'SI SE FACTURO LA SUCURSAL DEL CLIENTE TOMA EL RFC DE ESTA If FacturarSucursal AndAlso Me.ClienteSucursal IsNot Nothing Then RFCReceptor = Me.ClienteSucursal.RFC End If Else RFCReceptor = Me.RFCReceptorVenta End If Dim SWatch As New Stopwatch SWatch.Start() Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True) SWatch.Stop() Dim SegundosRespuesta As Double = SWatch.ElapsedMilliseconds / 1000 SegundosRespuesta = SegundosRespuesta.ToEntero If SegundosRespuesta >= 5 Then Alert($"Los servicios de validacion del SAT presentan lentitud en la respuesta [{ SegundosRespuesta } s].", TipoMensaje.ToastAdventencia, "") End If If Vigencia IsNot Nothing Then If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then DivRelacionadasCancelacion.Visible = True BtnCancelarDocumento.Visible = False DivMotivoCancelacion.Visible = False DivMotivoCancelacionTxt.Visible = False DivCanRem.Visible = False DivDevAlm.Visible = False Dim Relacionados = Timbrado.ConsultarUUIDRelacionados(UsuarioActual.Empresa, FolioFiscal, UsuarioActual.Empresa.FacturaProduccion) If Relacionados IsNot Nothing Then If Relacionados.Codigo = 500 Then sbExtra.Append("El servicio de verificación de documentos relacionados no esta disponible.") Else sbExtra.Append(Relacionados.Mensaje) Dim SbHijos = New StringBuilder() Dim SbPadres = New StringBuilder() 'If Relacionados.RelacionadosHijo IsNot Nothing Then ' For Each hijo In Relacionados.RelacionadosHijo ' SbHijos.AppendFormat("{0};", hijo.Uuid) ' Next ' If SbHijos.Length > 0 Then ' SbHijos.Remove(SbHijos.Length - 1, 1) ' End If 'End If If Relacionados.RelacionadosPadre IsNot Nothing Then For Each padre In Relacionados.RelacionadosPadre SbPadres.AppendFormat("{0};", padre.Uuid) Next If SbPadres.Length > 0 Then SbPadres.Remove(SbPadres.Length - 1, 1) End If End If Using ObjVentas As New ClsVentas 'If SbHijos.Length > 0 Then ' If ObjVentas.GetFacturasRelacionadasPorFolioFiscal(SbHijos.ToString(), UsuarioActual.CveEmpresa) Then ' GvFacturasHijosCancelar.DataSource = ObjVentas.DtResultados.Copy() ' End If 'End If If SbPadres.Length > 0 Then If ObjVentas.GetFacturasRelacionadasPorFolioFiscal(SbPadres.ToString(), UsuarioActual.CveEmpresa) Then GvFacturasPadreCancelar.DataSource = ObjVentas.DtResultados.FiltraParametros($"CveVenta <> {CveVenta}") End If End If End Using 'GvFacturasHijosCancelar.DataBind() GvFacturasPadreCancelar.DataBind() End If End If End If If String.IsNullOrEmpty(Vigencia.EsCancelable) Then If UsuarioActual.Empresa.FacturaProduccion AndAlso Not String.IsNullOrEmpty(FolioFiscal) Then Alert("No se pudo encontrar el estatus de la factura en el SAT.", TipoMensaje.MsgAdvertencia) Exit Sub End If MostrarRemisionesCancelar() sb.Append("No encontrado
    ") sb.Append("Está seguro de cancelar el documento?.") Else 'GUARDA EL ESTADO DE CANCELACION If Vigencia.EsCancelable.ToUpper() = "CANCELABLE CON ACEPTACIÓN" Then Me.CveEstadoCancelacion = 2 ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then Me.CveEstadoCancelacion = 1 End If sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) If Vigencia.EsCancelable.ToUpper() <> "NO CANCELABLE" Then MostrarRemisionesCancelar() sb.Append("Está seguro de cancelar el documento?.") End If End If Else MostrarRemisionesCancelar() sb.Append("No encontrado
    ") sb.Append("Está seguro de cancelar el documento?.") End If LblCancelarDocumento.Text = sb.ToString() MostrarCondicionesCancelacion(sbExtra.ToString()) RegistraScript("$('#ModalCancelarDocumento').modal();") UpCancelarDocumento.Update() sb.Clear() ElseIf DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then Dim ObjVentas As New ClsVentas If ObjVentas.UpdateEstatusVenta(CveVenta, 22, UsuarioActual.CveEmpresa) Then Dim redirectString As String = String.Format("document.location.href=""/Ventas/Ventas.aspx?CveVenta={0}""", CveVenta) Alert("Pedido cancelado.", JSBtnAceptar:=redirectString) ', "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta End If ObjVentas.Dispose() ElseIf DdlTipoComprobante.SelectedValue.Contiene("RNC") Then LblCancelarDocumento.Text = "¿Desea cancelar la remisión de nota de crédito?
    " Dim sbExtra As New StringBuilder Using ObjAcum As New ClsAcumuladores If ObjAcum.DistribuidorMovtosGet(Me.CveCliente, UsuarioActual.CveEmpresa, CveVentaRNCCargo:=Me.CveVenta, CveConcepto:=1) Then Dim DtBon As DataTable = ObjAcum.DtResultados.FiltraParametros("CveVentaBonificacion > 0", DistinctColumns:={"SerieFolioBonificacion", "CveVentaBonificacion"}) If DtBon IsNot Nothing AndAlso DtBon.Rows.Count > 0 Then sbExtra.Append("*Se cancelaran las siguientes remisiones de nota de crédito de bonificación.
    ") For Each RowBon As DataRow In DtBon.Rows sbExtra.AppendFormat("     {1}
    ", RowBon("CveVentaBonificacion"), RowBon("SerieFolioBonificacion")) Next DtBon.Dispose() End If End If End Using LbCancelarDescripcion.Text = sbExtra.ToString() DivRelacionadasCancelacion.Visible = False BtnCancelarDocumento.Visible = True DivMotivoCancelacion.Visible = False DivMotivoCancelacionTxt.Visible = False DivCanRem.Visible = False DivDevAlm.Visible = False UpCancelarDocumento.Update() RegistraScript("$('#ModalCancelarDocumento').modal();") Else CancelarDocumento() End If End Sub Private Sub MostrarRemisionesCancelar() If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing") AndAlso DivCanRem.Visible Then ChkCanRem.Checked = True ChkCanRem_CheckedChanged(ChkCanRem, EventArgs.Empty) ChkCanRem.Enabled = False If DivGvCancelarRemision.Visible Then For Each GvRow As GridViewRow In GvCancelarRemisiones.Rows If GvRow.RowType = DataControlRowType.DataRow Then GvRow.FCCheckBox("ChkCancelarRemision").Checked = True GvRow.FCCheckBox("ChkCancelarRemision").Enabled = False End If Next End If End If End Sub Protected Sub ChkDevAlm_CheckedChanged(sender As Object, e As EventArgs) MostrarCondicionesCancelacion() End Sub Protected Sub BtnCancelarDocumento_Click(sender As Object, e As EventArgs) CancelarDocumento() RegistraScript("$('#ModalCancelarDocumento').modal('hide');") End Sub 'Private Sub CancelarRefacturada() ' Dim CancelacionFecha As Date ' Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() ' Dim CancelacionAcuse As String = "" ' Dim Mensaje As String = "" ' Dim ObjCancelacion As New Timbrado ' Dim TotalT As Decimal = TxtTotal.Text.ToDecimal ' Dim RFCReceptor As String = LblRFC.Text.Trim ' Dim CvePACCancelacion As Integer = CvePAC ' Dim CveEstatus As Integer = 4 ' Try ' If FolioFiscal <> "" Then ' Dim resp = ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) ' If resp.Verificado Then ' 'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017 ' CancelacionFecha = ObjCancelacion.CancelacionFecha ' CancelacionAcuse = ObjCancelacion.CancelacionAcuse ' CveEstatus = 5 ' Else ' Alert("Los servicios de cancelación del SAT no se encuentran disponibles o presentan time out. Intente de nuevo en unos minutos.
    Origen del error: WebService www.sat.gob.mx", TipoMensaje.MsgError) ' Exit Sub ' End If ' Else ' CancelacionFecha = Now.Date ' CancelacionAcuse = "" ' End If ' If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IdPoliza, CvePAC:=CvePACCancelacion) Then ' ObjVentas.Commit() ' Alert("El nuevo estatus se guardó correctamente") ' Else ' ObjVentas.RollBack() ' Alert("Ocurrió un error al intentar cancelar la factura") ' End If ' Catch ex As Exception ' ObjVentas.RollBack() ' Mensaje = "Ocurrio un error al Cancelar la factura" ' GuardaLog($"{ex.Message}") ' End Try ' ObjVentas.Dispose() 'End Sub Private Function DecodeBase64(ByVal strXMLCodificado As String) As String Try Dim decbuff As Byte() = Convert.FromBase64String(strXMLCodificado) Return System.Text.Encoding.UTF8.GetString(decbuff) Catch Return "" End Try End Function 'Private Sub ActualizaEstatusVentaCancelada(Optional CveEstatusCancelacion As Integer = 5) ' Me.CveEstatus = CveEstatusCancelacion ' Dim ObjVentas As New ClsVentas() ' If CveEstatusCancelacion = 5 Then ' Dim IDPoliza As Integer = -1 ' Dim ErrorCancelar As Boolean = False ' Dim MensajeError As String = "" ' Dim CvePACCancelacion As Integer = CvePAC ' Dim ObjAC As ClsContPAQi = Nothing ' ObjVentas.IniciaTransacSQL() ' Try ' If UsuarioActual.Empresa.UsaAC Then ' ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() ' IDPoliza = GenerarPolizaAC(ObjAC, True) ' If IDPoliza <= 0 Then ' ErrorCancelar = True ' MensajeError = "Ocurrió un error al generar la poliza de cancelación." ' End If ' End If ' Dim solicitud = New WSGF.Service1SoapClient() ' Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) ' If acuse.Estado = 0 Then ' Dim xmlAcuse = New System.Xml.XmlDocument() ' xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) ' Dim CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText ' Dim CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() ' If Not ObjVentas.UpdateEstatusFactura(Me.CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion) Then ' ErrorCancelar = True ' MensajeError = "Ocurrió un error al guardar el estatus de cancelación." ' End If ' Else ' 'sino se pudo sacar el acuse, porque se canceló en el SAT, debe de marcarlo ' End If ' Catch ex As Exception ' ErrorCancelar = True ' Alert("Ocurrió un error al actualizar el estatus", TipoMensaje.MsgError) ' Finally ' If Not ErrorCancelar Then ' ObjVentas.Commit() ' If Me.CveEstatus = 5 Then ' Dim MensajeAlert As New StringBuilder ' MensajeAlert.Append("El Documento se canceló correctamente.") ' MensajeAlert.Append($"
    Imprimir Acuse") ' MensajeAlert.Append("

    ¿Desea enviar el Acuse de Cancelación al Cliente?") ' Alert(MensajeAlert.ToString(), TipoMensaje.MsgConfirmacion, "BtnEnviarMailCancelacion()", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") ' Else ' Alert("El documento se canceló exitosamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="location.reload();") ' End If ' LbCancelarDocumento.Enabled = False ' If ObjAC IsNot Nothing Then ObjAC.Commit() ' Else ' Alert(MensajeError, TipoMensaje.MsgError) ' ObjVentas.RollBack() ' If ObjAC IsNot Nothing Then ObjAC.RollBack() ' End If ' ObjVentas.Dispose() ' If ObjAC IsNot Nothing Then ObjAC.Dispose() ' End Try ' ElseIf CveEstatusCancelacion = 20 Then ' If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta) Then ' Alert("El estatus de la factura fue cambiado a 'Cancelación en Proceso'") ' End If ' ObjVentas.Dispose() ' End If 'End Sub Private Sub CancelarDocumento(Optional EsRefacturacion As Boolean = False) Dim LigaRedirigir As String = "" 'Si es cancelacion de una refactura ignoramos las condiciones 'If Me.CveEstatus = 13 Then ' CancelarRefacturada() 'End If Dim ObjFacturaCancelacion As New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=True) Try Dim resp As Modelos.Factura.MCancelacionVentaMensaje = Nothing Dim strMensaje As New StringBuilder() If ObjFacturaCancelacion IsNot Nothing AndAlso ObjFacturaCancelacion.CveVenta > 0 Then Dim SWatch As New Stopwatch SWatch.Start() If EsRefacturacion Then 'Dim msgBitacora As String = $"Motivo de refacturación: {TxtMotivoRefac.Text}" 'Dim ObjE As New ClsOIEventos() 'ObjE.AddEventoBitacora(msgBitacora, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) 'ObjE.Dispose() resp = ObjFacturaCancelacion.CancelarPorRefacturacion(DdlMotivoRefacturacion.SelectedValue.ToEntero(), TxtMotivoRefac.Text.Trim(), CveEstadoCancelacion:=Me.CveEstadoCancelacion) strMensaje.Append(resp.Mensaje) Else Dim ListaRemisionesCancelar As New List(Of Integer) If ChkCanRem.Checked Then For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows If Gvr.FCCheckBox("ChkCancelarRemision").Checked Then ListaRemisionesCancelar.Add(Gvr.DataKey("CveVenta").ToEntero()) End If Next End If ObjFacturaCancelacion.CveAlmacenDevolucion = CveAlmacenDevolucion If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso ObjFacturaCancelacion.TipoDocto = "Rem" Then ChkDevAlm.Checked = True End If resp = ObjFacturaCancelacion.CancelarFactura(ChkDevAlm.Checked, ListaRemisionesCancelar, CveMotivoCancelacion:=DdlMotivoCancelacion.SelectedValue.ToEntero(), Motivo:=TxtMotivoCancelacion.Text.Trim(), CveEstadoCancelacion:=Me.CveEstadoCancelacion) strMensaje.Append(resp.Mensaje) Dim DtBonificaciones As DataTable = Nothing 'SI ES RNC DE CARGO DEBE CANCELAR LAS BON If Not resp.HuboError AndAlso ObjFacturaCancelacion.TipoDocto.Contiene("RNC") AndAlso ObjFacturaCancelacion.Num1 = 1 Then Using ObjAcum As New ClsAcumuladores If ObjAcum.DistribuidorMovtosGet(ObjFacturaCancelacion.CveCliente, UsuarioActual.CveEmpresa, CveVentaRNCCargo:=ObjFacturaCancelacion.CveVenta, CveConcepto:=1) Then DtBonificaciones = ObjAcum.DtResultados.FiltraParametros("CveVentaBonificacion > 0", DistinctColumns:={"CveVentaBonificacion"}) End If End Using If DtBonificaciones IsNot Nothing AndAlso DtBonificaciones.Rows.Count > 0 Then For Each RowBon As DataRow In DtBonificaciones.Rows Try 'VERIFICA SI TIENE RNC DE BONIFICACION Dim Bon = New Modelos.Factura(UsuarioActual, RowBon("CveVentaBonificacion").ToString().ToEntero(), UsuarioActual.CveEmpresa, VerificaAlmacen:=False) Dim respBon = Bon.CancelarFactura(False, ListaRemisionesCancelar, CveMotivoCancelacion:=DdlMotivoCancelacion.SelectedValue.ToEntero(), Motivo:=TxtMotivoCancelacion.Text.Trim(), CveEstadoCancelacion:=Me.CveEstadoCancelacion) If respBon.HuboError Then strMensaje.AppendFormat("
    Ocurrió un error al cancelar la remisión de NC de bonificación {0} .", Bon.SerieFolio) Else strMensaje.AppendFormat("
    La remisión de nota de credito de bonificación {0} fue cancelada correctamente.", Bon.SerieFolio) End If strMensaje.AppendFormat("
    {0}", resp.Mensaje) Catch ex As Exception OnError("Ocurrió un error al cancelar la bonificación", ex) strMensaje.Append("
    Ocurrió un error al cancelar la bonificación") End Try Next DtBonificaciones.Dispose() End If End If End If SWatch.Stop() Dim SegundosRespuesta As Double = SWatch.ElapsedMilliseconds / 1000 SegundosRespuesta = SegundosRespuesta.ToEntero If SegundosRespuesta >= 5 Then Alert($"Los servicios de cancelación del SAT presentan lentitud en la respuesta [{ SegundosRespuesta } s].", TipoMensaje.ToastAdventencia, "") End If If resp.HuboError Then Alert(strMensaje.ToString(), resp.TipoMensaje, JSBtnAceptar:="BtnRefrescarPagina();") Else If resp.CveEstatus = 5 AndAlso Not EsRefacturacion Then Alert(strMensaje.ToString(), resp.TipoMensaje, JSBtnAceptar:=$"BtnEnviarMailCancelacion({CveVenta});", TextoConfirmacion:="    Si    ", TextoCancelacion:="    
    No    ") Else If EsRefacturacion Then If resp.CveEstatus = 20 Then LigaRedirigir = $"/Ventas/RepCancelacionesPorRespuesta.aspx?CveVenta={CveVenta}" ElseIf resp.CveEstatus.Contiene(4, 5, 23) Then LigaRedirigir = $"Ventas.aspx?CveDevolucion={CveVenta}&NuevaFactura=1" Else Alert(strMensaje.ToString(), resp.TipoMensaje, JSBtnAceptar:="BtnRefrescarPagina();") End If Else Alert(strMensaje.ToString(), resp.TipoMensaje, JSBtnAceptar:="BtnRefrescarPagina();") End If End If End If Else Alert("Ocurrió un error al generar la cancelación", TipoMensaje.MsgError) End If Catch ex As Exception OnError("Ocurrío un error al cancelar", ex) End Try ObjFacturaCancelacion.Dispose() UpEstatus.Update() If Not String.IsNullOrEmpty(LigaRedirigir) Then Response.Redirect(LigaRedirigir) End If End Sub #End Region #Region "CiclosComerciales" Private Sub CargaCicloComercialURL() Dim ObjContratos As New ClsContratos Dim huboerror = False Dim SubProyecto As String = "" Dim CveSubProyecto As Integer = -1 Dim Proyecto As String = "" If ObjContratos.CicloComercialGet(-1, -1, CveCicloComercial, UsuarioActual.CveEmpresa, MinFecha, MaxFecha, -1) Then If ObjContratos.DtResultados.Rows.Count > 0 Then Dim i As Integer = 0 Dim PU As Decimal = 0 Dim Descuento As Double = 0 Dim CveUM As Integer = 0 Dim UMM As String = "No Aplica" Dim tCvePS As Integer = 0 Dim TipoPS As Integer = 0 Dim tCveClasif As Integer = -1 Dim Clasif As String = "Sin Clasificación" Dim tPSCodigo As String = "-" Dim tPSDescripcion As String = "-" Dim PSS As String = "" Dim Obs As String = "" Dim SubTotalTemp = 0.0D 'Cargamos los datos del Cliente DtContratos = ObjContratos.DtResultados If ObjContratos.DtResultados(0)("IVA").ToString().ToDecimal > 0 Then ViewState("IVA") = ObjContratos.DtResultados(0)("IVA").ToString().ToDecimal End If ViewState("CveCliente") = ObjContratos.DtResultados(0)("CveCliente").ToString().ToEntero() ViewState("CveContrato") = ObjContratos.DtResultados(0)("CveContrato").ToString().ToEntero() HdnCveCliente.Value = ObjContratos.DtResultados(0)("CveCliente").ToString() CargaCliente(CveCliente) DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) DdlTipoComprobante.SelectedValue = "Ing" DdlTipoComprobante.Enabled = False DdlAlmacenAsignado.Enabled = False 'CARGO DATOS DE PS/CONTRATO SubProyecto = ObjContratos.DtResultados(0)("SubProyectoContrato").ToString() CveSubProyecto = ObjContratos.DtResultados(0)("CveSubProyecto").ToString().ToEntero() Proyecto = ObjContratos.DtResultados(0)("ProyectoContrato").ToString() DdlSubProyectoDatos.SelectedValueExist(CveSubProyecto) ContratoDetalles.Visible = True DivEstimaciones.Visible = False DdlContratosModal.DataSource = DtContratos DdlContratosModal.DataBind() DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0")) UPEstimaciones.Update() Tab.ActiveTab = TabE TabGenerales.Enabled = False Updatetabs.Update() DdlContratosModal.DataSource = ObjContratos.DtResultados DdlContratosModal.SelectedValue = ObjContratos.DtResultados(0)("CveContrato").ToString() DdlContratosModal_SelectedIndexChanged(Nothing, Nothing) If GvContratoDetalles.HeaderRow IsNot Nothing Then If GvContratoDetalles.HeaderRow.Cells.Count > 0 Then GvContratoDetalles.HeaderRow.Cells(1).Style.Add("display", "none") End If End If TxtObsFact.Text = PlantillaContrato(ObjContratos.DtResultados(0)("ObservacionesGenerales").ToString()) BtnCargarContratoDetalles_Click(Nothing, Nothing) LbAgregar.Visible = True UpPS.Update() 'AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString().Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento Else Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) huboerror = True End If Else Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError) huboerror = True End If ObjContratos.Dispose() End Sub Private Function PlantillaContrato(texto As String) As String Dim Plantilla As String = texto If Plantilla.Contains("{DIA}") Then Plantilla = Plantilla.Replace("{DIA}", DateTime.Now.Day.ToString()) End If If Plantilla.Contains("{MES}") Then Dim fecha As DateTime = DateTime.Now Dim formatoFecha = Globalization.CultureInfo.CurrentCulture.DateTimeFormat Dim nombreMes = formatoFecha.GetMonthName(fecha.Month).ToUpper() Plantilla = Plantilla.ToString().Replace("{MES}", nombreMes) End If If Plantilla.Contains("{AÑO}") Then Plantilla = Plantilla.Replace("{AÑO}", DateTime.Now.Year.ToString()) End If If Plantilla.Contains("{TC}") Then Plantilla = Plantilla.Replace("{TC}", GlobalTipoCambio(Now).FormatoNumero) End If If Plantilla.Contains("{MESANTERIOR}") Then Dim fecha As DateTime = DateTime.Now.AddMonths(-1) Dim formatoFecha = Globalization.CultureInfo.CurrentCulture.DateTimeFormat Dim nombreMes = formatoFecha.GetMonthName(fecha.Month).ToUpper() Plantilla = Plantilla.ToString().Replace("{MESANTERIOR}", nombreMes) End If If Plantilla.Contains("{INICIOMESANTERIOR}") Then Dim fecha As DateTime = DateTime.Now.AddMonths(-1) Dim formatoFecha = Globalization.CultureInfo.CurrentCulture.DateTimeFormat Dim nombreMes = formatoFecha.GetMonthName(fecha.Month).ToUpper() Dim mesAnterior As String = String.Format("01 {0} {1}", nombreMes, fecha.Year) Plantilla = Plantilla.ToString().Replace("{INICIOMESANTERIOR}", mesAnterior) End If If Plantilla.Contains("{FINMESANTERIOR}") Then Dim fecha As DateTime = DateTime.Now.AddMonths(-1) Dim formatoFecha = Globalization.CultureInfo.CurrentCulture.DateTimeFormat Dim nombreMes = formatoFecha.GetMonthName(fecha.Month).ToUpper() Dim LastDayOfMonth = DateTime.DaysInMonth(fecha.Year, fecha.Month) Dim mesAnterior As String = String.Format("{0} {1} {2}", LastDayOfMonth, nombreMes, fecha.Year) Plantilla = Plantilla.ToString().Replace("{FINMESANTERIOR}", mesAnterior) End If Return Plantilla End Function #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 Public Sub LbDescargarExcel_Click(sender As Object, e As EventArgs) Handles LbDescargarExcelVentas.Click DescargarFormato() End Sub Private Sub CargarArchivo(Ruta As String, FileName As String, Tipo As String, FileUrl As String) Dim dt As New DataTable Dim ErrorArchivo = 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 PrecioUnitario = CalculaPrecioSugerido(CvePS, CveClasificacion) End If AgregarProductoServicio(Cantidad, CveUM, UM, -1, "", CvePS, HdnPS.Value, Observaciones, PrecioUnitario, HdnDescuento.Value.ToDecimal, 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 Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcel.Click If TxtExcel.getfiles().Archivos.Count > 0 Then Dim file As Archivo = TxtExcel.getfiles().Archivos(0) Dim Directorio As String = ModExtensiones.DirectorioBaseEmpresas & file.path Dim Tipo As String = If(file.Extension.Contiene("xlsx", "xlsx", "xlsm", "xlsb"), "EXCEL", "CSV") CargarArchivo(Directorio, file.filename, Tipo, file.FileUrl) Else Alert("No existe el archivo. Favor de subir un archivo excel a la plataforma.", TipoMensaje.MsgError) End If 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 "P E D I D O S" Private Sub CargaNotificacionContrato() Dim ObjContratos As New ClsContratos If ObjContratos.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then If ObjContratos.DtResultados IsNot Nothing AndAlso ObjContratos.DtResultados.Rows.Count > 0 Then CorreoNotificacionPedDev = ObjContratos.DtResultados(0)("CorreoNotificacionPedDev").ToString() End If End If ObjContratos.Dispose() End Sub Private Sub EnviarCorreoDevPed() Try Dim Body As String = GeneraCorreoDevPed() Dim Asunto As String = $"SIG - Favor de surtir el siguiente {DdlTipoComprobante.SelectedItem.Text}" Dim Hilo As New System.Threading.Thread(Sub() MandaCorreoDevPed(CorreoNotificacionPedDev, Asunto, Body)) Hilo.Start() Catch ex As Exception OnError($"Ocurrió error al mandar el correo de solicitud de {DdlTipoComprobante.SelectedItem.Text}", ex) End Try End Sub Private Sub MandaCorreoDevPed(Para As String, Asunto As String, Body As String) Dim Mail As New ClsSisMail() Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body) End Sub Private Function GeneraCorreoDevPed() As String Dim strBody As New StringBuilder strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.AppendFormat("
    Favor de surtir el siguiente {0}

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

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

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

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

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

    ") Destinatario = "" If UsuarioActual.CveEmpresa.Contiene(72, 80) Then Destinatario = "luzdelmarcoeto@compuproveedores.com;ramonmartinez@compuproveedores.com" End If 'correo a ramón y a luz If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then Cuerpo.AppendLine("") Cuerpo.AppendLine("") For Each Drow As DataRow In tDtMovimientos.Rows Cuerpo.AppendLine($"") Next Cuerpo.AppendLine("
    CantidadProducto
    {Drow("Cantidad").ToString().ToEntero() }{Drow("PS").ToString()}
    ") End If Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString()) Cuerpo.Clear() Exit Select End Select End Sub Private Sub GuardarBitacora(CveVenta As Integer, RutaAdjunto As String, Obser As String) Dim ObjEventos As New ClsOIEventos() Try If ObjEventos.AddEventoBitacora(Obser, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then End If Catch ex As Exception OnError("Se presento un Error al guardar la Bitacora", ex) End Try ObjEventos.Dispose() End Sub Private Function RegistrarPaqueteriaGuia(ByRef ObjGeneral As ClsGenerales, CveVenta As Integer) As Boolean Dim ErrorMovInv As Boolean = False Dim CveSubProyecto As Integer = DdlSubProyectoDatos.SelectedValue.ToEntero() Dim CveEstatus As Integer = 1 Dim Fecha As String = Now.ToString("dd/MM/yyyy") Dim FechaEstimada As String = "-1" Dim NoCajas As Integer = 0 Dim Observaciones As String = "" Dim CvePaqueteria As Integer = -1 ' GlobalDTPaqueterias(UsuarioActual.CveEmpresa, 0).FiltroPrimeroValor("CvePaqueteria", "").ToEntero If CveSubProyecto > 0 Then Dim CvePaqueteriaGuia As Integer = ObjGeneral.AddPaqueteriasGuias(CvePaqueteria, 9, CveEstatus, CveSubProyecto, Fecha, "", "", NoCajas, 0.00, "-1", FechaEstimada, Observaciones, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, ImplicaCosto:=False) If CvePaqueteriaGuia > 0 Then If CveVenta > 0 OrElse CveSubProyecto > 0 Then If Not ObjGeneral.AddPaqueteriasGuiasDetalles(CvePaqueteriaGuia, CveVenta, -1, -1, -1) Then ErrorMovInv = True End If End If Else ErrorMovInv = True End If Else ErrorMovInv = True End If Return Not ErrorMovInv End Function #End Region #Region " APLICAR NOTA DE CREDITO " Private Sub InicializaAplicarNC() 'If Not UsuarioActual.CveUsuario = 100 Then ' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then ' Exit Sub ' End If 'End If If CveVenta <= 0 Or Not DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Or Not HplSaldoAuxiliar.Text.ToDouble > 0 Then ''If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then LkNotaCredito.Visible = False Exit Sub End If 'sino tiene el permiso de peude generar NC If Not UsuarioActual.TienePermisoProceso(175) Then Exit Sub End If If DeshabilitarAplicarNotaDeCredito(LblRFC.Text) Then Exit Sub End If AplicaNCMasiva = False AplicaNC = False LBNotaCredito.Visible = True If UsuarioActual.CveUsuario = 100 Then LnkAplicarRNCDevolucion.Visible = True End If 'LkNotaCredito.Visible = False TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNC();") TxtNCImporte.Attributes.Add("onkeyup", "CalculaPorcentajeNC();") Dim PorcentajeMaximo = 0.0 If TxtTotal.Text.ToDouble > 0 Then PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.ToDouble Else RVNCPorcentaje.MinimumValue = "0" RVTxtNCImporte.MinimumValue = "0" End If TxtNCPorcentaje.Text = PorcentajeMaximo.FormatoNumero(4) If PorcentajeMaximo < RVNCPorcentaje.MinimumValue.ToDouble Then RVNCPorcentaje.MinimumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString() End If RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString() TxtNCImporte.Text = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero If ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble < RVTxtNCImporte.MinimumValue.ToDouble Then RVTxtNCImporte.MinimumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString() End If RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString() 'RVIRNC.MinimumValue = RVTxtNCImporte.MinimumValue 'RVIRNC.MaximumValue = RVTxtNCImporte.MaximumValue UpAplicarNC.Update() End Sub Protected Sub DdlVentaUsado_SelectedIndexChanged(sender As Object, e As EventArgs) RblRNCTipo_SelectedIndexChanged(RblRNCTipo, EventArgs.Empty) End Sub Private Sub InicializaAplicarNCMasiva() 'If Not UsuarioActual.CveUsuario = 100 Then ' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then ' Exit Sub ' End If 'End If 'sino tiene el permiso de peude generar NC If Not UsuarioActual.TienePermisoProceso(175) Then 'sino tiene el permiso de peude generar NC no directas, solo relacionadas por proceso If Not UsuarioActual.TienePermisoProceso(334) Then 'sino tiene el 175 y tampoco el 334, que se salga Exit Sub End If End If AplicaNCMasiva = True LBNotaCredito.Visible = True If UsuarioActual.CveUsuario = 100 Then LnkAplicarRNCDevolucion.Visible = True End If 'LkNotaCredito.Visible = False DivGvCxC.Visible = True CargaCxC() 'CARGAR RNC RblRNCTipo_SelectedIndexChanged(RblRNCTipo, EventArgs.Empty) TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNCMasivo();") TxtNCImporte.Text = "0.00" TxtNCImporte.Enabled = False RVTxtNCImporte.Enabled = False UpAplicarNC.Update() UpModalRemisionesNC.Update() End Sub Private Sub CargaCxC() Dim CveClienteSucursal As Integer = -1 If DdlSucursalCliente.SelectedValue.ToEntero() > 0 Then CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero() End If Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetCxCClienteDetalle(ViewState("CveCliente").ToString().ToEntero(), "-1", "-1", -1, -1, UsuarioActual.CveEmpresa, CveClienteSucursal:=CveClienteSucursal) Then Dim DtTemporal As DataTable = ObjMovtos.DtResultados.FiltraParametros("TipoDocto NOT IN ('RNC','Rem') AND Tipo = 'Act' AND CveVenta > 0", "Moneda, OrdenVencimiento, FechaVencimiento") GvCxC.DataSource = DtTemporal End If ObjMovtos.Dispose() GvCxC.DataBind() End Sub Protected Sub RblRNCTipo_SelectedIndexChanged(sender As Object, e As EventArgs) ChkMostarProductosRNC.Checked = False DivRNCCargosDetalle.Visible = False DivRNCCargos.Visible = True ChkMostarProductosRNCBon.Checked = False DivRNCBonificacionesDetalle.Visible = False DivRNCBonificaciones.Visible = True Select Case RblRNCTipo.SelectedValue Case "1" 'CARGOS LtlCargos.Text = "CARGOS" DivRNCCargo.Visible = True DivRNCBon.Visible = False CargaRNC(DdlVentaUsado.SelectedValue.ToEntero(), False, False) Case "2" 'BONIFICACIONES DivRNCCargo.Visible = False DivRNCBon.Visible = True CargaRNC(-1, True, False) Case "3" 'AJUSTE/GARANTIAS LtlCargos.Text = "AJUSTES/GARANTIAS" DivRNCCargo.Visible = True DivRNCBon.Visible = False CargaRNC(DdlVentaUsado.SelectedValue.ToEntero(), False, True) End Select End Sub Protected Sub RblRNCTipoDesc_SelectedIndexChanged(sender As Object, e As EventArgs) Select Case RblRNCTipoDesc.SelectedValue Case "1" 'CARGOS LtlCargoDesc.Text = "CARGOS" DivRNCCargoDesc.Visible = True DivRNCBonDesc.Visible = True If ChkMostarProductosRNCDesc.Checked Then DivRNCCargoDescTotal.Visible = False DivRNCCargoDescDetalle.Visible = True CargaRNCDetalleDesc() Else DivRNCCargoDescTotal.Visible = True DivRNCCargoDescDetalle.Visible = False CargaRNCDesc(False, False) End If CargaBonificacionesDesc("-1", True) Case "2" 'BONIFICACIONES DivRNCCargoDesc.Visible = False DivRNCBonDesc.Visible = True If ChkMostarProductosRNCDesBonificacion.Checked Then DivRNCBonDescTotal.Visible = False DivRNCBonDescDetalle.Visible = True CargaRNCDetalleDescBonificacion() Else DivRNCBonDescTotal.Visible = True DivRNCBonDescDetalle.Visible = False CargaRNCDesc(True, False) End If Case "3" 'AJUSTE/GARANTIAS LtlCargoDesc.Text = "AJUSTES/GARANTIAS" DivRNCCargoDesc.Visible = True DivRNCBonDesc.Visible = True If ChkMostarProductosRNCDesc.Checked Then DivRNCCargoDescTotal.Visible = False DivRNCCargoDescDetalle.Visible = True CargaRNCDetalleDesc(True) Else DivRNCCargoDescTotal.Visible = True DivRNCCargoDescDetalle.Visible = False CargaRNCDesc(False, True) End If CargaBonificacionesDesc("-1", True) End Select End Sub Protected Sub ChkMostarProductosRNC_CheckedChanged(sender As Object, e As EventArgs) If ChkMostarProductosRNC.Checked Then DivRNCCargos.Visible = False DivRNCCargosDetalle.Visible = True CargaRNCDetalle(DdlVentaUsado.SelectedValue.ToEntero(), CargaSoloGarantias:=RblRNCTipo.SelectedValue = "3") Else DivRNCCargos.Visible = True DivRNCCargosDetalle.Visible = False RblRNCTipo_SelectedIndexChanged(RblRNCTipo, EventArgs.Empty) End If UpModalRemisionesNC.Update() End Sub Protected Sub ChkMostarProductosRNCBon_CheckedChanged(sender As Object, e As EventArgs) If ChkMostarProductosRNCBon.Checked Then DivRNCBonificaciones.Visible = False DivRNCBonificacionesDetalle.Visible = True CargaRNCDetalleBonificacion(DdlVentaUsado.SelectedValue.ToEntero()) Else DivRNCBonificaciones.Visible = True DivRNCBonificacionesDetalle.Visible = False RblRNCTipo_SelectedIndexChanged(RblRNCTipo, EventArgs.Empty) End If UpModalRemisionesNC.Update() End Sub Protected Sub ChkMostarProductosRNCDesc_CheckedChanged(sender As Object, e As EventArgs) RblRNCTipoDesc_SelectedIndexChanged(RblRNCTipo, EventArgs.Empty) UpModalRemisionesNC.Update() End Sub Protected Sub ChkMostarProductosRNCDesBonificacion_CheckedChanged(sender As Object, e As EventArgs) RblRNCTipoDesc_SelectedIndexChanged(RblRNCTipo, EventArgs.Empty) UpModalRemisionesNC.Update() End Sub Private Sub CargaRNC(Optional CveVentaUsado As Integer = -1, Optional CargarBonificaciones As Boolean = False, Optional CargarSoloGarantias As Boolean = False) Dim DtNC As DataTable = Nothing Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, CveMoneda:=-1) Then DtNC = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'RNC' AND CveVenta > 0 and Saldo > 0", "Moneda,Fecha,Folio") End If ObjMovtos.Dispose() Me.TmpDTRNCBonificacionesSeleccionadas = Nothing If DtNC IsNot Nothing Then Me.TmpDTRNCBonificacionesCliente = DtNC.FiltraParametros("TipoRNC = 2") Me.TmpDTRNCBonificacionesCliente.Columns.Add("ImporteBonificacion", GetType(Decimal)) Me.TmpDTRNCBonificacionesCliente.Columns.Add("IVABonificacion", GetType(Decimal)) Me.TmpDTRNCBonificacionesCliente.Columns.Add("CveVentaRNCCargo", GetType(Integer)) If CargarBonificaciones Then 'Me.TmpDTRNCBonificacionesSeleccionadas = Me.TmpDTRNCBonificacionesCliente.Copy() CargaBonificaciones(-1, True) End If If CargarSoloGarantias Then GvRemisionesNC.DataSource = DtNC.FiltraParametros("TipoRNC = 1 AND EsGarantia = True") Else GvRemisionesNC.DataSource = DtNC.FiltraParametros("TipoRNC = 1 AND EsGarantia = False") End If GvRemisionesNC.DataBind() 'GvRemisionesNCBon.DataSource = Me.TmpDTRNCBonificacionesSeleccionadas 'GvRemisionesNCBon.DataBind() Dim SaldoMaximoUtilizable As Decimal = 0 If CargarSoloGarantias Then Dim SaldoMaximo As Decimal = DtNC.SUMD("Saldo", "TipoRNC = 1 AND EsGarantia = True") If SaldoMaximo > 0 Then SaldoMaximoUtilizable = SaldoMaximo Else SaldoMaximoUtilizable = 0 End If Else Dim ObjAcum As New ClsAcumuladores If ObjAcum.GetMovimientosDistribuidorResumen(CveCliente, UsuarioActual.CveEmpresa) Then Dim RowUsadosNC As DataRow = ObjAcum.DtResultados.Rows(2) DivSMU.Visible = True Dim SaldoMaximo As Decimal = RowUsadosNC("ValorConImpuestos").ToString().ToDecimal() If SaldoMaximo > 0 Then SaldoMaximoUtilizable = RowUsadosNC("ValorConImpuestos").ToString().ToDecimal() Else SaldoMaximoUtilizable = 0 End If Else SaldoMaximoUtilizable = 0 End If ObjAcum.Dispose() End If If CveVentaUsado > 0 Then DivSMU.Visible = True 'Dim FacUsado As New Modelos.Factura(UsuarioActual, CveVentaUsado, UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) Dim DtDetalleUsado As DataTable = Nothing Using ObjVentas As New ClsVentas If ObjVentas.GetVentaDetalle(CveVentaUsado) Then DtDetalleUsado = ObjVentas.DtResultados.Copy() End If End Using If DtDetalleUsado IsNot Nothing Then Dim SaldoMaximoUsadosFactura As Decimal = DtDetalleUsado.SUM("Total", "EsCargo = True").ToDecimal() + DtDetalleUsado.SUM("ImporteIVA", "EsCargo = True").ToDecimal() If SaldoMaximoUtilizable < SaldoMaximoUsadosFactura Then HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() LtlSMU.Text = String.Format("{0:N2}", SaldoMaximoUtilizable) Else HdnSaldoMaximoUsados.Value = SaldoMaximoUsadosFactura.ToString() LtlSMU.Text = String.Format("{0:N2}", SaldoMaximoUsadosFactura) End If Else HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() LtlSMU.Text = String.Format("{0:N2}", SaldoMaximoUtilizable) End If Else HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() LtlSMU.Text = SaldoMaximoUtilizable.FormatoNumero(2) End If Else HdnSaldoMaximoUsados.Value = "0" LtlSMU.Text = "0" End If UpModalRemisionesNC.Update() UpDescNC.Update() End Sub Private Sub CargaRNCDesc(Optional CargarBonificaciones As Boolean = False, Optional CargarSoloGarantias As Boolean = False) Dim DtNC As DataTable = Nothing Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, CveMoneda:=-1) Then DtNC = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'RNC' AND CveVenta > 0 and Saldo > 0", "Moneda,Fecha,Folio") End If ObjMovtos.Dispose() Me.TmpDTRNCBonificacionesSeleccionadas = Nothing If DtNC IsNot Nothing Then Me.TmpDTRNCBonificacionesCliente = DtNC.FiltraParametros("TipoRNC = 2") Me.TmpDTRNCBonificacionesCliente.Columns.Add("ImporteBonificacion", GetType(Decimal)) Me.TmpDTRNCBonificacionesCliente.Columns.Add("IVABonificacion", GetType(Decimal)) Me.TmpDTRNCBonificacionesCliente.Columns.Add("CveVentaRNCCargo", GetType(Integer)) If CargarBonificaciones Then 'Me.TmpDTRNCBonificacionesSeleccionadas = Me.TmpDTRNCBonificacionesCliente.Copy() CargaBonificacionesDesc("-1", True) End If If CargarSoloGarantias Then GvDescNCCargos.DataSource = DtNC.FiltraParametros("TipoRNC = 1 AND EsGarantia = True") Else GvDescNCCargos.DataSource = DtNC.FiltraParametros("TipoRNC = 1 AND EsGarantia = False") End If GvDescNCCargos.DataBind() Dim SaldoMaximoCliente As Decimal = 0 Dim SaldoEntregado As Decimal = 0 If CargarSoloGarantias Then Dim SaldoMaximo As Decimal = DtNC.SUMD("Saldo", "TipoRNC = 1 AND EsGarantia = True") If SaldoMaximo > 0 Then SaldoMaximoCliente = SaldoMaximo Else SaldoMaximoCliente = 0 End If Else Dim ObjAcum As New ClsAcumuladores If ObjAcum.GetMovimientosDistribuidorResumen(CveCliente, UsuarioActual.CveEmpresa) Then Dim RowUsadosNC As DataRow = ObjAcum.DtResultados.Rows(2) DivSMU.Visible = True Dim SaldoMaximo As Decimal = RowUsadosNC("ValorConImpuestos").ToString().ToDecimal() If SaldoMaximo > 0 Then SaldoMaximoCliente = RowUsadosNC("ValorConImpuestos").ToString().ToDecimal() Else SaldoMaximoCliente = 0 End If Dim RowEntregado As DataRow = ObjAcum.DtResultados.Rows(1) SaldoEntregado = RowEntregado("ValorConImpuestos").ToString().ToDecimal() Else SaldoMaximoCliente = 0 End If ObjAcum.Dispose() End If Dim SaldoMaximoUsadosFactura As Decimal = Me.TmpDT.SUM("Total", "EsCargo = True").ToDecimal() + Me.TmpDT.SUM("ImporteIVA", "EsCargo = True").ToDecimal() If SaldoMaximoCliente > 0 AndAlso SaldoMaximoCliente < SaldoMaximoUsadosFactura Then SaldoMaximoUsadosFactura = SaldoMaximoCliente End If Dim SaldoMaximoUtilizable = If(SaldoMaximoUsadosFactura < SaldoEntregado, SaldoMaximoUsadosFactura, SaldoEntregado) If SaldoMaximoUtilizable > 0 Then HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() LblSaldoMaximoUsados.Text = String.Format("{0:N2}", SaldoMaximoUtilizable) Else HdnSaldoMaximoUsados.Value = "0" LblSaldoMaximoUsados.Text = String.Format("{0:N2}", 0) End If Else HdnSaldoMaximoUsados.Value = "0" LblSaldoMaximoUsados.Text = "0" End If UpDescNC.Update() End Sub Private Sub CargaRNCDetalle(Optional CveVentaUsado As Integer = -1, Optional CargaSoloGarantias As Boolean = False) Dim DtNC As DataTable = Nothing Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetRemisionesNCCliente(CveCliente, True, CveMoneda:=-1) Then Me.TmpDTRNCDetalle = ObjMovtos.DtResultados.FiltraParametros("Total > 0") End If ObjMovtos.Dispose() If CargaSoloGarantias Then TmpDTRNCDetalle = TmpDTRNCDetalle.FiltraParametros("EsGarantia = True") Else TmpDTRNCDetalle = TmpDTRNCDetalle.FiltraParametros("EsGarantia = False") End If Me.TmpDTRNCDetalle.Columns.Add(New DataColumn("CveVentaDetalleNCGenerada", GetType(Integer))) Me.TmpDTRNCDetalleSelecciondas = Nothing Me.TmpDTRNCDetalleSelecciondas = TmpDTRNCDetalle.Clone() Me.TmpDTRNCDetalleSelecciondas.Clear() GvRemisionesNCDetalle.DataSource = TmpDTRNCDetalle.FiltraParametros("TipoRNC = 1") 'GvRemisionesNCBon.DataSource = TmpDTRNCBonificacionesSeleccionadas 'Me.TmpDTRNCBonificacionesCliente = DtNC.FiltraParametros("TipoRNC = 2") 'Me.TmpDTRNCBonificacionesCliente.Columns.Add("ImporteBonificacion", GetType(Decimal)) 'Me.TmpDTRNCBonificacionesCliente.Columns.Add("IVABonificacion", GetType(Decimal)) 'Me.TmpDTRNCBonificacionesCliente.Columns.Add("CveVentaRNCCargo", GetType(Integer)) GvRemisionesNCDetalle.DataBind() 'GvRemisionesNCBon.DataBind() Dim SaldoMaximoUtilizable As Decimal = 0 If CargaSoloGarantias Then Dim SaldoMaximo As Decimal = TmpDTRNCDetalle.SUMD("Total", "TipoRNC = 1") If SaldoMaximo > 0 Then SaldoMaximoUtilizable = SaldoMaximo Else SaldoMaximoUtilizable = 0 End If Else Dim ObjAcum As New ClsAcumuladores If ObjAcum.GetMovimientosDistribuidorResumen(CveCliente, UsuarioActual.CveEmpresa) Then Dim RowUsadosNC As DataRow = ObjAcum.DtResultados.Rows(2) DivSMU.Visible = True SaldoMaximoUtilizable = RowUsadosNC("ValorConImpuestos").ToString().ToDecimal() Else 'DivSMU.Visible = False SaldoMaximoUtilizable = 0 End If ObjAcum.Dispose() End If If CveVentaUsado > 0 Then DivSMU.Visible = True 'Dim FacUsado As New Modelos.Factura(UsuarioActual, CveVentaUsado, UsuarioActual.CveEmpresa) Dim DtDetalleUsado As DataTable = Nothing Using ObjVentas As New ClsVentas If ObjVentas.GetVentaDetalle(CveVentaUsado) Then DtDetalleUsado = ObjVentas.DtResultados.Copy() End If End Using If DtDetalleUsado IsNot Nothing Then Dim SaldoMaximoUsados As Decimal = DtDetalleUsado.SUM("Total", "EsCargo = True").ToDecimal() + DtDetalleUsado.SUM("ImporteIVA", "EsCargo = True").ToDecimal() HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() If SaldoMaximoUtilizable < SaldoMaximoUsados Then HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() LtlSMU.Text = String.Format("{0:N2}", SaldoMaximoUtilizable) Else HdnSaldoMaximoUsados.Value = SaldoMaximoUsados.ToString() LtlSMU.Text = String.Format("{0:N2}", SaldoMaximoUsados) End If End If Else HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() LtlSMU.Text = SaldoMaximoUtilizable.FormatoNumero(2) End If UpModalRemisionesNC.Update() UpDescNC.Update() End Sub Private Sub CargaRNCDetalleDesc(Optional CargarSoloGarantias As Boolean = False) Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetRemisionesNCCliente(CveCliente, True, CveMoneda:=-1) Then Me.TmpDTRNCDetalle = ObjMovtos.DtResultados.Copy() End If ObjMovtos.Dispose() Me.TmpDTRNCDetalle.Columns.Add(New DataColumn("CveVentaDetalleNCGenerada", GetType(Integer))) Me.TmpDTRNCDetalleSelecciondas = Nothing Me.TmpDTRNCDetalleSelecciondas = TmpDTRNCDetalle.Clone() Me.TmpDTRNCDetalleSelecciondas.Clear() If CargarSoloGarantias Then GvDescNCCargosDetalle.DataSource = TmpDTRNCDetalle.FiltraParametros("TipoRNC = 1 AND EsGarantia = True") Else GvDescNCCargosDetalle.DataSource = TmpDTRNCDetalle.FiltraParametros("TipoRNC = 1 AND EsGarantia = False") End If GvDescNCCargosDetalle.DataBind() Dim SaldoMaximoCliente As Decimal = 0 Dim SaldoEntregado As Decimal = 0 If CargarSoloGarantias Then Dim SaldoMaximo As Decimal = TmpDTRNCDetalle.SUMD("Saldo", "TipoRNC = 1 AND EsGarantia = True") If SaldoMaximo > 0 Then SaldoMaximoCliente = SaldoMaximo Else SaldoMaximoCliente = 0 End If Else Dim ObjAcum As New ClsAcumuladores If ObjAcum.GetMovimientosDistribuidorResumen(CveCliente, UsuarioActual.CveEmpresa) Then Dim RowUsadosNC As DataRow = ObjAcum.DtResultados.Rows(2) DivSMU.Visible = True Dim SaldoMaximo As Decimal = RowUsadosNC("ValorConImpuestos").ToString().ToDecimal() If SaldoMaximo > 0 Then SaldoMaximoCliente = RowUsadosNC("ValorConImpuestos").ToString().ToDecimal() Else SaldoMaximoCliente = 0 End If Dim RowEntregado As DataRow = ObjAcum.DtResultados.Rows(1) SaldoEntregado = RowEntregado("ValorConImpuestos").ToString().ToDecimal() Else SaldoMaximoCliente = 0 End If ObjAcum.Dispose() End If Dim SaldoMaximoUsadosFactura As Decimal = Me.TmpDT.SUM("Total", "EsCargo = True").ToDecimal() + Me.TmpDT.SUM("ImporteIVA", "EsCargo = True").ToDecimal() If SaldoMaximoCliente > 0 AndAlso SaldoMaximoCliente < SaldoMaximoUsadosFactura Then SaldoMaximoUsadosFactura = SaldoMaximoCliente End If Dim SaldoMaximoUtilizable = If(SaldoMaximoUsadosFactura < SaldoEntregado, SaldoMaximoUsadosFactura, SaldoEntregado) If SaldoMaximoUtilizable > 0 Then HdnSaldoMaximoUsados.Value = SaldoMaximoUtilizable.ToString() LblSaldoMaximoUsados.Text = String.Format("{0:N2}", SaldoMaximoUtilizable) Else HdnSaldoMaximoUsados.Value = "0" LblSaldoMaximoUsados.Text = String.Format("{0:N2}", 0) End If UpDescNC.Update() End Sub Private Sub CargaRNCDetalleBonificacion(Optional CveVentaUsado As Integer = -1) 'Dim ObjMovtos As New ClsMovimientos() 'If ObjMovtos.GetRemisionesNCCliente(CveCliente, True, CveMoneda:=-1, CveClienteSucursal:=DdlSucursalCliente.SelectedValue.ToEntero()) Then ' Me.TmpDTRNCBonificacionDetalle = ObjMovtos.DtResultados.Copy() 'End If 'ObjMovtos.Dispose() 'Me.TmpDTRNCBonificacionDetalle.Columns.Add(New DataColumn("CveVentaDetalleNCGenerada", GetType(Integer))) 'Me.TmpDTRNCBonificacionDetalleSeleccionadas = Nothing 'Me.TmpDTRNCBonificacionDetalleSeleccionadas = TmpDTRNCBonificacionDetalle.Clone() 'Me.TmpDTRNCBonificacionDetalleSeleccionadas.Clear() 'GvRemisionesNCBonDetalle.DataSource = TmpDTRNCBonificacionDetalle.FiltraParametros("TipoRNC = 2") 'GvRemisionesNCBonDetalle.DataBind() Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetRemisionesNCCliente(CveCliente, True, CveMoneda:=-1) Then Me.TmpDTRNCDetalle = ObjMovtos.DtResultados.Copy() End If ObjMovtos.Dispose() Me.TmpDTRNCDetalle.Columns.Add(New DataColumn("CveVentaDetalleNCGenerada", GetType(Integer))) Me.TmpDTRNCDetalleSelecciondas = Nothing Me.TmpDTRNCDetalleSelecciondas = TmpDTRNCDetalle.Clone() Me.TmpDTRNCDetalleSelecciondas.Clear() GvRemisionesNCBonDetalle.DataSource = TmpDTRNCDetalle.FiltraParametros("TipoRNC = 2") GvRemisionesNCBonDetalle.DataBind() Dim SaldoMaximoUtilizable As Decimal = 0 If TmpDTRNCBonificacionesSeleccionadas IsNot Nothing Then Dim SaldoMaximo As Decimal = TmpDTRNCBonificacionesSeleccionadas.SUMD("Saldo") If SaldoMaximo > 0 Then SaldoMaximoUtilizable = SaldoMaximo Else SaldoMaximoUtilizable = 0 End If End If If DdlVentaUsado.SelectedValue.ToEntero() > 0 Then Dim DtDetalleFactura As DataTable = Nothing Using ObjVentas As New ClsVentas If ObjVentas.GetVentaDetalle(DdlVentaUsado.SelectedValue.ToEntero()) Then DtDetalleFactura = ObjVentas.DtResultados.FiltraParametros("EsCargo = True") End If End Using Dim ImporteBon As Decimal = DtDetalleFactura.SUMD("PUBonificacion") * (1 + DtDetalleFactura.MAX("PorcentajeIVA").ToDecimal()) If SaldoMaximoUtilizable < ImporteBon Then LtlSMUBon.Text = String.Format("{0:N2}", SaldoMaximoUtilizable) HdnSMUBon.Value = SaldoMaximoUtilizable.ToString() Else LtlSMUBon.Text = String.Format("{0:N2}", ImporteBon) HdnSMUBon.Value = ImporteBon.ToString() End If DtDetalleFactura.Dispose() Else HdnSMUBon.Value = SaldoMaximoUtilizable.ToString() LtlSMUBon.Text = SaldoMaximoUtilizable.FormatoNumero(2) End If UpModalRemisionesNC.Update() End Sub Private Sub CargaRNCDetalleDescBonificacion() Dim DtNC As DataTable = Nothing Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetRemisionesNCCliente(CveCliente, True, CveMoneda:=-1) Then Me.TmpDTRNCBonificacionDetalle = ObjMovtos.DtResultados.Copy() End If ObjMovtos.Dispose() Me.TmpDTRNCBonificacionDetalle.Columns.Add(New DataColumn("CveVentaDetalleNCGenerada", GetType(Integer))) Me.TmpDTRNCBonificacionDetalleSeleccionadas = Nothing Me.TmpDTRNCBonificacionDetalleSeleccionadas = TmpDTRNCBonificacionDetalle.Clone() Me.TmpDTRNCBonificacionDetalleSeleccionadas.Clear() GvDescNCBonDetalle.DataSource = TmpDTRNCBonificacionDetalle.FiltraParametros("TipoRNC = 2") GvDescNCBonDetalle.DataBind() 'Dim SaldoMaximoUsados As Decimal = Me.TmpDT.SUM("Total", "EsCargo = True").ToDecimal() + Me.TmpDT.SUM("ImporteIVA", "EsCargo = True").ToDecimal() 'If SaldoMaximoUsados > 0 Then ' HdnSaldoMaximoUsados.Value = SaldoMaximoUsados.ToString() ' LblSaldoMaximoUsados.Text = String.Format("{0:N2}", SaldoMaximoUsados) 'Else ' HdnSaldoMaximoUsados.Value = "0" ' LblSaldoMaximoUsados.Text = "0" 'End If UpDescNC.Update() End Sub Private Sub CargaBonificaciones(CveVentaRNCCargo As Integer, AplicarRNC As Boolean) If TmpDTRNCBonificacionesSeleccionadas Is Nothing Then TmpDTRNCBonificacionesSeleccionadas = Me.TmpDTRNCBonificacionesCliente.Clone() End If If ChkMostarProductosRNCBon.Checked Then DivRNCBonificaciones.Visible = False DivRNCBonificacionesDetalle.Visible = True CargaRNCDetalleBonificacion() Else DivRNCBonificaciones.Visible = True DivRNCBonificacionesDetalle.Visible = False Dim ListaBon As New List(Of VentasBonificaciones) Dim DtBon As DataTable = Nothing Dim SbFiltro As New StringBuilder() SbFiltro.Append("CveVenta IN(") Using ObjAcum As New ClsAcumuladores If ObjAcum.DistribuidorMovtosGet(CveCliente, UsuarioActual.CveEmpresa, CveVentaRNCCargo:=CveVentaRNCCargo) Then DtBon = ObjAcum.DtResultados.Copy() End If End Using If DtBon IsNot Nothing Then Dim queryBonificacion = From dr In DtBon Where dr("CveVentaBonificacion").ToString().ToEntero > 0 Group By CveVentaBonificacion = dr("CveVentaBonificacion").ToString().ToEntero, CveVenta = dr("CveVenta").ToString().ToEntero Into x = Group Select New With { .CveVentaRNCCargo = CveVenta, .CveVentaBonificacion = CveVentaBonificacion, .ImporteBonificacion = x.Sum(Function(s) s("ImporteBonificacion").ToString().ToDecimal), .IVABonificacion = x.Sum(Function(s) s("IVABonificacion").ToString().ToDecimal) } For Each bon In queryBonificacion SbFiltro.AppendFormat("'{0}',", bon.CveVentaBonificacion) ListaBon.Add(New VentasBonificaciones() With {.CveVentaRNCCargo = bon.CveVentaRNCCargo, .CveVentaBonificacion = bon.CveVentaBonificacion, .ImporteBonificacion = bon.ImporteBonificacion, .IVABonificacion = bon.IVABonificacion}) Next SbFiltro.Remove(SbFiltro.Length - 1, 1) SbFiltro.Append(")") End If If ListaBon.Count > 0 Then Dim Bonificaciones = Me.TmpDTRNCBonificacionesCliente.Select(SbFiltro.ToString()) For Each RowBonificacion As DataRow In Bonificaciones Dim RNCBonificacion = ListaBon.Where(Function(x) x.CveVentaBonificacion = RowBonificacion("CveVenta").ToString().ToEntero()) RowBonificacion("ImporteBonificacion") = RNCBonificacion.Sum(Function(x) x.ImporteBonificacion) RowBonificacion("IVABonificacion") = RNCBonificacion.Sum(Function(x) x.IVABonificacion) RowBonificacion("CveVentaRNCCargo") = CveVentaRNCCargo If AplicarRNC Then TmpDTRNCBonificacionesSeleccionadas.Rows.Add(RowBonificacion.ItemArray) Else For Each RowEliminar In Me.TmpDTRNCBonificacionesSeleccionadas.Select(SbFiltro.ToString()) RowEliminar.Delete() Next End If Next End If 'VERIFICA SI TIENE BONIFICACIONES PARA AGREGARLAS If TmpDTRNCBonificacionesSeleccionadas IsNot Nothing AndAlso TmpDTRNCBonificacionesSeleccionadas.Rows.Count > 0 Then DivRNCBon.Visible = True Else DivRNCBon.Visible = False End If GvRemisionesNCBon.DataSource = TmpDTRNCBonificacionesSeleccionadas GvRemisionesNCBon.DataBind() 'Dim SMUBon As Decimal = Me.TmpDTRNCBonificacionesSeleccionadas.SUM("ImporteBonificacion").ToDecimal() + Me.TmpDTRNCBonificacionesSeleccionadas.SUM("IVABonificacion").ToDecimal() 'LtlSMUBon.Text = String.Format("{0:N2}", SMUBon) 'HdnSMUBon.Value = SMUBon.ToString() Dim SaldoMaximoUtilizable As Decimal = TmpDTRNCBonificacionesSeleccionadas.SUMD("Saldo") If DdlVentaUsado.SelectedValue.ToEntero() > 0 Then Dim DtDetalleFactura As DataTable = Nothing Using ObjVentas As New ClsVentas If ObjVentas.GetVentaDetalle(DdlVentaUsado.SelectedValue.ToEntero()) Then DtDetalleFactura = ObjVentas.DtResultados.FiltraParametros("EsCargo = True") End If End Using Dim ImporteBon As Decimal = DtDetalleFactura.SUMD("PUBonificacion") * (1 + DtDetalleFactura.MAX("PorcentajeIVA").ToDecimal()) If SaldoMaximoUtilizable < ImporteBon Then LtlSMUBon.Text = String.Format("{0:N2}", SaldoMaximoUtilizable) HdnSMUBon.Value = SaldoMaximoUtilizable.ToString() Else LtlSMUBon.Text = String.Format("{0:N2}", ImporteBon) HdnSMUBon.Value = ImporteBon.ToString() End If DtDetalleFactura.Dispose() Else If SaldoMaximoUtilizable > 0 Then HdnSMUBon.Value = SaldoMaximoUtilizable.ToString() LtlSMUBon.Text = SaldoMaximoUtilizable.FormatoNumero(2) Else HdnSMUBon.Value = "0" LtlSMUBon.Text = "0" End If End If UpModalRemisionesNC.Update() End If End Sub 'Protected Sub ChkAplicarRNC_CheckedChanged(sender As Object, e As EventArgs) ' Dim ChkAplicarRNC As CheckBox = DirectCast(sender, CheckBox) ' Dim SbRNC As New StringBuilder() ' For Each GvRow As GridViewRow In GvDescNCCargos.Rows ' If GvRow.RowType = DataControlRowType.DataRow Then ' If GvRow.FCCheckBox("ChkAplicar").Checked Then ' SbRNC.AppendFormat("{0},", GvRow.DataKey("CveVenta")) ' End If ' End If ' Next ' If SbRNC.Length > 0 Then ' SbRNC.Remove(SbRNC.Length - 1, 1) ' CargaBonificacionesDesc(SbRNC.ToString(), True) ' Else ' CargaBonificacionesDesc(SbRNC.ToString(), ChkAplicarRNC.Checked) ' End If 'End Sub 'Protected Sub ChkAplicarRNCDesc_CheckedChanged(sender As Object, e As EventArgs) ' Dim ChkAplicarRNC As CheckBox = DirectCast(sender, CheckBox) ' Dim SbRNC As New StringBuilder() ' For Each GvRow As GridViewRow In GvDescNCCargosDetalle.Rows ' If GvRow.RowType = DataControlRowType.DataRow Then ' If GvRow.FCCheckBox("ChkAplicar").Checked Then ' SbRNC.AppendFormat("{0},", GvRow.DataKey("CveVenta")) ' End If ' End If ' Next ' If SbRNC.Length > 0 Then ' SbRNC.Remove(SbRNC.Length - 1, 1) ' CargaBonificacionesDesc(SbRNC.ToString(), True) ' Else ' CargaBonificacionesDesc(SbRNC.ToString(), ChkAplicarRNC.Checked) ' End If 'End Sub Private Sub CargaBonificacionesDesc(CvesVentaRNCCargo As String, AplicarRNC As Boolean) If ChkMostarProductosRNCDesBonificacion.Checked Then DivRNCBonDescTotal.Visible = False DivRNCBonDescDetalle.Visible = True CargaRNCDetalleDescBonificacion() Else DivRNCBonDescTotal.Visible = True DivRNCBonDescDetalle.Visible = False If TmpDTRNCBonificacionesSeleccionadas Is Nothing Then TmpDTRNCBonificacionesSeleccionadas = Me.TmpDTRNCBonificacionesCliente.Clone() Else TmpDTRNCBonificacionesSeleccionadas.Clear() End If Dim ListaVentasRNCCargos As String() = {} If CvesVentaRNCCargo <> "-1" OrElse Not String.IsNullOrEmpty(CvesVentaRNCCargo) Then ListaVentasRNCCargos = CvesVentaRNCCargo.Split(","c) End If Dim ListaBon As New List(Of VentasBonificaciones) Dim DtBon As DataTable = Nothing Dim SbFiltro As New StringBuilder() SbFiltro.Append("CveVenta IN(") Using ObjAcum As New ClsAcumuladores For Each CveVentaRNC As String In ListaVentasRNCCargos If ObjAcum.DistribuidorMovtosGet(CveCliente, UsuarioActual.CveEmpresa, CveVentaRNCCargo:=CveVentaRNC.ToEntero()) Then Dim DtDist = ObjAcum.DtResultados.Copy() If DtBon Is Nothing Then DtBon = DtDist.Clone() End If DtBon.Merge(DtDist) End If Next End Using If DtBon IsNot Nothing Then Dim queryBonificacion = From dr In DtBon Group By CveVentaBonificacion = dr("CveVentaBonificacion").ToString().ToEntero, CveVentaRNCCargo = dr("CveVentaRNCCargo").ToString().ToEntero Into x = Group Select New With { .CveVentaRNCCargo = CveVentaRNCCargo, .CveVentaBonificacion = CveVentaBonificacion, .ImporteBonificacion = x.Sum(Function(s) s("ImporteBonificacion").ToString().ToDecimal), .IVABonificacion = x.Sum(Function(s) s("IVABonificacion").ToString().ToDecimal) } For Each bon In queryBonificacion SbFiltro.AppendFormat("'{0}',", bon.CveVentaBonificacion) ListaBon.Add(New VentasBonificaciones() With {.CveVentaRNCCargo = bon.CveVentaRNCCargo, .CveVentaBonificacion = bon.CveVentaBonificacion, .ImporteBonificacion = bon.ImporteBonificacion, .IVABonificacion = bon.IVABonificacion}) Next SbFiltro.Remove(SbFiltro.Length - 1, 1) SbFiltro.Append(")") End If If ListaBon.Count > 0 Then Dim Bonificaciones = Me.TmpDTRNCBonificacionesCliente.Select(SbFiltro.ToString()) For Each RowBonificacion As DataRow In Bonificaciones Dim RNCBonificacion = ListaBon.Where(Function(x) x.CveVentaBonificacion = RowBonificacion("CveVenta").ToString().ToEntero()) RowBonificacion("ImporteBonificacion") = RNCBonificacion.Sum(Function(x) x.ImporteBonificacion) RowBonificacion("IVABonificacion") = RNCBonificacion.Sum(Function(x) x.IVABonificacion) RowBonificacion("CveVentaRNCCargo") = RNCBonificacion(0).CveVentaRNCCargo If AplicarRNC Then TmpDTRNCBonificacionesSeleccionadas.Rows.Add(RowBonificacion.ItemArray) Else For Each RowEliminar In Me.TmpDTRNCBonificacionesSeleccionadas.Select(SbFiltro.ToString()) RowEliminar.Delete() Next End If Next End If 'VERIFICA SI TIENE BONIFICACIONES PARA AGREGARLAS If TmpDTRNCBonificacionesSeleccionadas IsNot Nothing AndAlso TmpDTRNCBonificacionesSeleccionadas.Rows.Count > 0 Then DivRNCBonDesc.Visible = True Else DivRNCBonDesc.Visible = False End If GvDescNCBonificaciones.DataSource = TmpDTRNCBonificacionesSeleccionadas GvDescNCBonificaciones.DataBind() End If UpDescNC.Update() End Sub Protected Sub GvDescNCCargos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDescNCCargos.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble}, this);") e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble});") End If End Sub Protected Sub GvDescNCCargosDetalle_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDescNCCargosDetalle.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveVentaDetalleRNC").ToEntero() = 0 Then e.Row.CssClass = "Totales" e.Row.FCCheckBox("ChkAplicar").Visible = False e.Row.FCTextBox("TxtCantidadRNC").Visible = False Else e.Row.CssClass = "ImportesRNCDetalle" e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCChkDetalle({e.Row.FCTextBox("TxtCantidadRNC").ClientID},{e.Row.DBCampo("CantidadPendiente").ToDouble},{e.Row.DBCampo("Total").ToDouble}, this);") 'e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble});") End If End If End Sub Protected Sub GvDescNCBonDetalle_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDescNCBonDetalle.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveVentaDetalleRNC").ToEntero() = 0 Then e.Row.CssClass = "Totales" e.Row.FCCheckBox("ChkAplicar").Visible = False e.Row.FCTextBox("TxtCantidadRNC").Visible = False Else e.Row.CssClass = "ImportesRNCDetalle" e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCChkDetalleBonificacion({e.Row.FCTextBox("TxtCantidadRNC").ClientID},{e.Row.DBCampo("CantidadPendiente").ToDouble},{e.Row.DBCampo("Total").ToDouble}, this);") 'e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble});") End If End If End Sub Protected Sub GvRemisionesNCBonDetalle_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvRemisionesNCBonDetalle.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveVentaDetalleRNC").ToEntero() = 0 Then e.Row.FCLiteral("TtlTotal").Text = DirectCast(GvRemisionesNCBonDetalle.DataSource, DataTable).SUMD("Total", $"CveVenta = {e.Row.DBCampo("CveVenta")}").FormatoNumero(2) e.Row.CssClass = "Totales" e.Row.FCCheckBox("ChkAplicar").Visible = False e.Row.FCTextBox("TxtCantidadRNC").Visible = False Else e.Row.CssClass = "ImportesRNCDetalle" e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCChkDetalleBon({e.Row.FCTextBox("TxtCantidadRNC").ClientID},{e.Row.DBCampo("CantidadPendiente").ToDouble},{e.Row.DBCampo("Total").ToDouble}, this);") 'e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble});") End If End If End Sub Protected Sub GvRNCDevoluciones_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvRNCDevoluciones.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCBonChkDesc({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble}, this);") e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCBonChkDesc({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble});") End If End Sub Protected Sub GvDescNCBonificaciones_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDescNCBonificaciones.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCBonChkDesc({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble}, this);") e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCBonChkDesc({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble});") End If End Sub Protected Sub GvCxC_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCCheckBox("ChkCxC").Attributes.Add("onclick", $"CalculaTotalChk({e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble},{TxtNCPorcentaje.Text.ToDouble}, this);") e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaCantidadNCMasivo({TxtNCPorcentaje.Text.ToDouble()},{e.Row.DBCampo("Saldo").ToDouble},{e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{TxtNCImporte.ClientID},{e.Row.FCCheckBox("ChkCxC").ClientID}, this);") End If End Sub Protected Sub GvRemisionesNC_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvRemisionesNC.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble}, this);") e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble}, this);") End If End Sub Protected Sub GvRemisionesNCDetalle_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvRemisionesNCDetalle.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveVentaDetalleRNC").ToEntero() = 0 Then e.Row.FCLiteral("TtlTotal").Text = DirectCast(GvRemisionesNCDetalle.DataSource, DataTable).SUMD("Total", $"CveVenta = {e.Row.DBCampo("CveVenta")}").FormatoNumero(2) e.Row.CssClass = "Totales" e.Row.FCCheckBox("ChkAplicar").Visible = False e.Row.FCTextBox("TxtCantidadRNC").Visible = False End If End If End Sub Protected Sub GvRemisionesNCBon_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvRemisionesNCBon.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCBonChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble}, this);") e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaSaldoRNCBonChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble});") End If End Sub Protected Sub DdlNCNivelImporte_SelectedIndexChanged(sender As Object, e As EventArgs) Dim ImporteReferencia As Double = 0, PorcentajeMaximo As Double = 0 If Not AplicaNCMasiva Then ImporteReferencia = If(DdlNCNivelImporte.SelectedValue.ToEntero() = 1, TxtTotal.Text.Trim.ToDouble, TxtSubTotal.Text.Trim.ToDouble) PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.Trim.ToDouble RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString() RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * ImporteReferencia) / 100).FormatoNumero().ToDouble.ToString() End If If AplicaNCMasiva Then RegistraScript($"CalculaImporteNCMasivo()", "CalculaImporteNCMasivo") Else RegistraScript("CalculaImporteNC();", "CalculaImporteNC") UpAplicarNC.Update() End Sub Protected Sub BtnAplicarNC_Click(sender As Object, e As EventArgs) 'SOLO APLICA SI NO HAY DOCUMENTOS QUE SELECCIONAR If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Dim Verificacion As Boolean = False If ListaRemisionesNC IsNot Nothing AndAlso ListaRemisionesNC.Count > 0 Then ' si hay opciones seleccionadas, se activa el generar las NCs Verificacion = True Else If UsuarioActual.TienePermisoProceso(175) Then ' si es una nc, que se va a generar directa, el permiso de generar NC directas Verificacion = True Else 'verificar autorizaciones Dim ObjVentas As New ClsVentas If ObjVentas.GetAutorizacionLimite(UsuarioActual.CveEmpresa, CveCliente, -1, "Egs", CveEstatus:=1) Then Dim RowAutorizacion As DataRow = ObjVentas.DtResultados.FiltroPrimero($"CveVenta IS NULL ", Orderby:="TipoAutorizacion,Importe DESC") If RowAutorizacion IsNot Nothing Then Dim ImporteAutorizacion As Decimal = RowAutorizacion("Importe").ToString().ToDecimal() If ImporteAutorizacion >= TxtNCImporte.Text.ToDecimal Then Verificacion = True End If End If End If ObjVentas.Dispose() ' si es una nc, que se va a generar directa, debe de revisar que tenga una autorización, o el permiso de generar NC directas End If End If If GvCxC.Rows.Count = 0 OrElse GvCxC.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("ChkCxC").Checked) = 0 Then If Verificacion Then If ClienteEsDistribuidor AndAlso TxtImportesRemisionesNC.Text.ToDecimal() > 0 Then Alert("No se puede generar una nota de crédito para devolución de efectivo si el cliente es distribuidor.", TipoMensaje.MsgAdvertencia) Else Alert("No se ha seleccionado ninguna factura, en caso de no seleccionar ninguna se creará una nueva nota de crédito. ¿Está seguro de realizar esta acción?", TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnAplicaNuevaNC();", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") End If Else Alert("No se puede Generar notas de crédito directas", TipoMensaje.MsgAdvertencia) End If Else ' si viene de remisiones, puede seguir adelante If Verificacion Then AplicarNotaCreditoDesdeVenta() Else Alert("No se puede Generar notas de crédito directas", TipoMensaje.MsgAdvertencia) End If End If Else AplicarNotaCreditoDesdeVenta() End If End Sub Private Sub BtnAplicaNuevaNC_Click(sender As Object, e As EventArgs) Handles BtnAplicaNuevaNC.Click AplicarNotaCreditoDesdeVenta(AplicaNuevoDocumento:=True) End Sub Private Sub AplicarNotaCreditoDesdeVenta(Optional AplicaNuevoDocumento As Boolean = False) If UsuarioActual.Empresa.Funcionalidad(344) = "1" Then If AplicaNuevoDocumento AndAlso TxtImportesRemisionesNC.Text.ToDecimal() > 0 Then TxtNCImporte.Text = TxtImportesRemisionesNC.Text End If If ListaRemisionesNC IsNot Nothing AndAlso ListaRemisionesNC.Count > 0 Then If TxtImportesRemisionesNC.Text.ToDecimal() <> TxtNCImporte.Text.ToDecimal() Then Alert($"Los importes no coinciden", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If Dim Monedas As New List(Of Integer) For Each gvr As GridViewRow In GvCxC.Rows If gvr.FCCheckBox("ChkCxC").Checked Then Monedas.Add(gvr.DataKey("CveMoneda").ToString().ToEntero()) End If Next Monedas = Monedas.Distinct().ToList() If Monedas.Count > 0 Then If Monedas.Count > 1 Then Alert($"Debe seleccionar facturas de la misma moneda", TipoMensaje.MsgAdvertencia) Exit Sub End If DdlMoneda.SelectedValueExist(Monedas(0).ToString()) End If RegistraScript("$('#ModalAplicarNC').modal('hide');", "EscondeModalNC") CveVentaUsadoDevolucionEfectivo = -1 DdlTipoComprobante.SelectedValueExistInsert("Egs", "Egresos") Dim AplicaImpuestosLocales As Boolean = False 'Dim ObjCliente As New ClsClientes 'If ObjCliente.GetClienteImpuestosLocales(CveCliente) Then ' 'se cargan impuestos locales ' Dim DtClienteImpuesto As DataTable = ObjCliente.DtResultados.FiltraParametros("Seleccionado = 1", "Orden") ' AplicaImpuestosLocales = (DtClienteImpuesto IsNot Nothing AndAlso DtClienteImpuesto.Rows.Count > 0) 'End If 'ObjCliente.Dispose() 'CARGA IMPUESTOS LOCALES Dim ObjVentas As New ClsVentas() If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then If ObjVentas.DtResultados.Rows.Count > 0 Then AplicaImpuestosLocales = True TrOtros.Visible = True TmpDTImpuestos = ObjVentas.DtResultados GvImpuestosLocales2.DataSource = ObjVentas.DtResultados GvImpuestosLocales2.DataBind() GvImpuestosLocales2.Enabled = False GvImpuestosLocales2.Visible = True End If End If ObjVentas.Dispose() 'SI SE SELECCIONO UNA FACTURA PARA DEVOLUCION DE EFECTIVO DEBE ASOCIARLA A LA NOTA DE CREDITO If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso AplicaNuevoDocumento AndAlso DdlVentaUsado.SelectedValue.ToEntero() > 0 AndAlso TxtImportesRemisionesNC.Text.ToDecimal() > 0 Then CveVentaUsadoDevolucionEfectivo = DdlVentaUsado.SelectedValue.ToEntero() End If AplicarNC(DdlNCPS.SelectedValue.ToEntero(), EsNCAmortizacion:=ChkAplicaNCAnticipo.Checked, AplicaImpuestosLocales:=AplicaImpuestosLocales, AplicaNuevoDocumento:=AplicaNuevoDocumento, AplicoNCFacturaActual:=True) End Sub Private Sub AplicarNC(CvePS As Integer, Optional NCDescuento As Boolean = False, Optional EsNCAmortizacion As Boolean = False, Optional AplicaImpuestosLocales As Boolean = True, Optional AplicaNuevoDocumento As Boolean = False, Optional AplicoNCFacturaActual As Boolean = False, Optional TipoDoctoNC As String = "Egs") Try Me.AplicaDocumentoNuevoNC = AplicaNuevoDocumento Dim DrPS As DataRow = Nothing If CvePS > 0 AndAlso TipoDoctoNC = "Egs" Then DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If DrPS Is Nothing Then Alert("Ocurrió un error al cargar la información del producto. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError) Exit Sub Else 'VALIDA CLAVES SAT If DrPS("SATClavePS").ToString() = "" Then Alert($"El concepto {DrPS("Codigo").ToString()}-{DrPS("PS").ToString()} no cuenta con producto SAT. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) Exit Sub End If If DrPS("SATClaveUnidadMedida").ToString() = "" Then Alert($"El concepto {DrPS("Codigo").ToString()}-{DrPS("PS").ToString()} no cuenta con Unidad Medida SAT. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If If Not AplicaImpuestosLocales Then If TmpDTImpuestos IsNot Nothing Then TmpDTImpuestos.Rows.Clear() GvImpuestosLocales2.DataSource = TmpDTImpuestos GvImpuestosLocales2.DataBind() End If End If Me.AplicoNCFacturaActual = AplicoNCFacturaActual 'CREAMOS DT PARA UTILIZAR AL TIMBRAR InicializaDTVentasNC() Dim DtImpuestos As New DataTable DtImpuestos.Columns.Add("ImportePU", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteTotal", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeIVA", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteIVA", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteRetIVA", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeRetISR", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteRetISR", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeIEPS", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteIEPS", GetType(Decimal)) DtImpuestos.Columns.Add("CveSubProyecto", GetType(Integer)) DtImpuestos.AcceptChanges() Dim AcumuladoNC As Decimal = 0 Dim DtImpuestosBonificacion As DataTable = DtImpuestos.Copy() If Not AplicaNuevoDocumento Then If AplicaNCMasiva Then If NCDescuento Then For Each RNC In ListaNCDesc DtImpuestos.Merge(CargaDtImpuestosNC(RNC.CveVenta, RNC.TotalRemNCAplicado, NCDescuento:=True, AplicaImpuestosLocales:=AplicaImpuestosLocales, NivelTotal:=DdlNCNivelImporte.SelectedValue.ToEntero()), True, MissingSchemaAction.Ignore) Next 'SI HAY RNC DE BONIFICACION SE AGREGAN If ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0 Then For Each RNC In ListaNCBonificacion DtImpuestosBonificacion.Merge(CargaDtImpuestosNC(RNC.CveVenta, RNC.TotalRemNCAplicado, NCDescuento:=True, AplicaImpuestosLocales:=AplicaImpuestosLocales, NivelTotal:=DdlNCNivelImporte.SelectedValue.ToEntero()), True, MissingSchemaAction.Ignore) Next End If Else Dim NumVentasAplicar As Integer = 1 For Each Gvr As GridViewRow In GvCxC.Rows If Gvr.FCCheckBox("ChkCxC").Checked Then DtImpuestos.Merge(CargaDtImpuestosNC(Gvr.DataKey("CveVenta").ToString().ToEntero(), Gvr.FCTextBox("TxtImporte").Text.ToString().ToDecimal, AplicaImpuestosLocales:=AplicaImpuestosLocales, NivelTotal:=DdlNCNivelImporte.SelectedValue.ToEntero()), True, MissingSchemaAction.Ignore) 'CARGA FACTURA A LA CUAL SE APLICA LA NC AcumuladoNC += Gvr.FCTextBox("TxtImporte").Text.ToString().ToDecimal CargaNCDT(Gvr.DataKey("CveVenta").ToString().ToEntero(), Gvr.FCTextBox("TxtImporte").Text.ToString().ToDecimal) If UsuarioActual.CveEmpresa = 140 AndAlso NumVentasAplicar = 1 Then DdlMetodoPago33.Enabled = True DdlMetodoPago33.SelectedValueExist(Gvr.DataKey("CveMetodoPago33").ToString()) CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) DdlFormaPago33.Enabled = True DdlFormaPago33.SelectedValueExist(Gvr.DataKey("CveFormaPago33").ToString()) End If NumVentasAplicar += 1 End If Next End If Else DtImpuestos = CargaDtImpuestosNC(CveVenta, TxtNCImporte.Text.Trim.ToDecimal, AplicaImpuestosLocales:=AplicaImpuestosLocales, NivelTotal:=DdlNCNivelImporte.SelectedValue.ToEntero()) If EsNCAmortizacion Then If DtAnticipoAmortizacion Is Nothing Then InicializaDTAnticiposAmortizacion() End If Dim PorcentajeAplicado As Decimal = (TxtNCPorcentaje.Text.ToDecimal / 100D) Dim RowAnticipo As DataRow = DtAnticipoAmortizacion.NewRow RowAnticipo("CveVenta") = Me.CveVenta RowAnticipo("Importe") = TxtNCImporte.Text.Trim.ToDecimal RowAnticipo("SaldoAnticipo") = SaldoAnticipo * PorcentajeAplicado DtAnticipoAmortizacion.Rows.Add(RowAnticipo) End If End If Else If ListaRemisionesNC IsNot Nothing Then For Each RNC In ListaRemisionesNC DtImpuestos.Merge(CargaDtImpuestosNC(RNC.CveVenta, RNC.TotalRemNCAplicado, NCDescuento:=True, AplicaImpuestosLocales:=AplicaImpuestosLocales, NivelTotal:=DdlNCNivelImporte.SelectedValue.ToEntero(), AplicaNCUsado:=(UsuarioActual.CveEmpresa = 140)), True, MissingSchemaAction.Ignore) Next End If If ListaNCBonificacion IsNot Nothing Then For Each RNC In ListaNCBonificacion DtImpuestosBonificacion.Merge(CargaDtImpuestosNC(RNC.CveVenta, RNC.TotalRemNCAplicado, NCDescuento:=True, AplicaImpuestosLocales:=AplicaImpuestosLocales, NivelTotal:=DdlNCNivelImporte.SelectedValue.ToEntero(), AplicaNCUsado:=(UsuarioActual.CveEmpresa = 140)), True, MissingSchemaAction.Ignore) Next End If End If Dim query = From dr In DtImpuestos Group By PorcentajeIVA = dr("PorcentajeIVA").ToString().ToDecimal, PorcentajeRetIVA = dr("PorcentajeRetIVA").ToString().ToDecimal, PorcentajeRetISR = dr("PorcentajeRetISR").ToString().ToDecimal, PorcentajeIEPS = dr("PorcentajeIEPS").ToString().ToDecimal Into x = Group Select ImportePU = x.Sum(Function(s) s("ImportePU").ToString().ToDecimal), ImporteTotal = x.Sum(Function(s) s("ImporteTotal").ToString().ToDecimal).RoundSQL(2), ImporteIVA = x.Sum(Function(s) (s("ImporteIVA").ToString().ToDecimal)).RoundSQL(2), ' Math.Round(s("ImporteIVA").ToString().ToDecimal, 2)) * (1 + PorcentajeIEPS) * PorcentajeIVA, ImporteRetIVA = x.Sum(Function(s) (s("ImporteRetIVA").ToString().ToDecimal)).RoundSQL(2),' Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeRetIVA, ImporteRetISR = x.Sum(Function(s) (s("ImporteRetISR").ToString().ToDecimal)).RoundSQL(2),' Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeRetISR, ImporteIEPS = x.Sum(Function(s) (s("ImporteIEPS").ToString().ToDecimal)).RoundSQL(2), 'Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeIEPS, PorcentajeIVA = PorcentajeIVA, PorcentajeRetIVA = PorcentajeRetIVA, PorcentajeRetISR = PorcentajeRetISR, PorcentajeIEPS = PorcentajeIEPS Dim queryBonificacion = From dr In DtImpuestosBonificacion Group By PorcentajeIVA = dr("PorcentajeIVA").ToString().ToDecimal, PorcentajeRetIVA = dr("PorcentajeRetIVA").ToString().ToDecimal, PorcentajeRetISR = dr("PorcentajeRetISR").ToString().ToDecimal, PorcentajeIEPS = dr("PorcentajeIEPS").ToString().ToDecimal Into x = Group Select ImportePU = x.Sum(Function(s) s("ImportePU").ToString().ToDecimal), ImporteTotal = x.Sum(Function(s) s("ImporteTotal").ToString().ToDecimal).RoundSQL(2), ImporteIVA = x.Sum(Function(s) (s("ImporteIVA").ToString().ToDecimal)).RoundSQL(2), ' Math.Round(s("ImporteIVA").ToString().ToDecimal, 2)) * (1 + PorcentajeIEPS) * PorcentajeIVA, ImporteRetIVA = x.Sum(Function(s) (s("ImporteRetIVA").ToString().ToDecimal)).RoundSQL(2),' Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeRetIVA, ImporteRetISR = x.Sum(Function(s) (s("ImporteRetISR").ToString().ToDecimal)).RoundSQL(2),' Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeRetISR, ImporteIEPS = x.Sum(Function(s) (s("ImporteIEPS").ToString().ToDecimal)).RoundSQL(2), 'Math.Round(s("ImportePU").ToString().ToDecimal, 2)) * PorcentajeIEPS, PorcentajeIVA = PorcentajeIVA, PorcentajeRetIVA = PorcentajeRetIVA, PorcentajeRetISR = PorcentajeRetISR, PorcentajeIEPS = PorcentajeIEPS Dim DrSubProyecto = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa, -1).FiltroPrimero("") If DrSubProyecto Is Nothing Then Alert("Ocurrió un error al cargar la información de centro de costos. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError) Exit Sub End If DtImpuestos = query.QueryToDataTable(False) DtImpuestosBonificacion = queryBonificacion.QueryToDataTable(False) Dim TieneMultiplesSubProyectos As Boolean = False 'VERIFICA SI EN LA FACTURA ACTUAL TUVO MULTIPLES SUBPROYECTOS, PARA CUADRAR AL FINAL EL IMPORTE ACUMULADO If Not AplicaNCMasiva AndAlso AplicoNCFacturaActual Then TieneMultiplesSubProyectos = TmpDT.FiltraParametros("", "", {"CveSubProyecto"}).COUNT("CveSubProyecto", "CveSubProyecto > 0") > 1 If TieneMultiplesSubProyectos Then AcumuladoNC = TxtNCImporte.Text.Trim.ToDecimal End If End If 'ASUSTO LA DIFERENCIA EN EL ÚLTIMO CONCEPTO If TipoDoctoNC = "Egs" AndAlso (Not AplicaNuevoDocumento) AndAlso (AplicaNCMasiva OrElse TieneMultiplesSubProyectos) AndAlso (Not NCDescuento) AndAlso AcumuladoNC > 0 Then 'CODIGO PARA AJUSTE DE CENTAVO, SI EL IMPORTE TOTAL NO CUADRA CON LOS TOTALES Dim ImporteNC As Decimal = DtImpuestos.SUMD("ImporteTotal") + DtImpuestos.SUMD("ImporteIVA") + DtImpuestos.SUMD("ImporteIEPS") - DtImpuestos.SUMD("ImporteRetIVA") - DtImpuestos.SUMD("ImporteRetISR") Dim difTmp As Decimal = AcumuladoNC - ImporteNC If Math.Abs(difTmp) > 0.00D Then Dim ImporteAjustado As Decimal = DtImpuestos.Rows(DtImpuestos.Rows.Count - 1)("ImporteTotal").ToString().ToDecimal + difTmp DtImpuestos.Rows(DtImpuestos.Rows.Count - 1)("ImporteTotal") = ImporteAjustado DtImpuestos.Rows(DtImpuestos.Rows.Count - 1)("ImportePU") = ImporteAjustado End If End If If Not NCDescuento Then LimpiaDocumentoNC() End If Dim CveSubProyecto = DrSubProyecto("CveSubProyecto").ToString().ToEntero() Dim SubProyecto = DrSubProyecto("SubProyecto").ToString() Dim CveProyecto = DrSubProyecto("CveProyecto").ToString().ToEntero() Dim Proyecto = DrSubProyecto("Proyecto").ToString() AplicaNC = True If NCDescuento Then TmpDTDescNC = TmpDT.Clone() TmpDTDescNC.Clear() If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then If AplicaRNCXDetalle Then CrearDTNCCargoDetalle(ListaNCDesc, TmpDTDescNC, DrPS, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) Else CrearDTNCCargo(ListaNCDesc, TmpDTDescNC, DrPS, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) End If 'CONSULTA EL CONCEPTO DE NC Dim ArrayNC As String() = UsuarioActual.Empresa.Funcionalidad(591).Split(",".ToCharArray()) Dim NCBonificacion As Integer = 0 If ArrayNC.Length > 4 Then NCBonificacion = ArrayNC(4).ToEntero() End If Dim DrBonRef As DataRow = Nothing 'EN LA NC DE BONIFICACION EL CONCEPTO DEBE SER SIEMPRE 'BONIFICACION POR USADO' Dim DrPSBonificacion = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=NCBonificacion).FiltroPrimero("") If DrPSBonificacion IsNot Nothing Then DrBonRef = DrPSBonificacion Else DrBonRef = DrPS Alert("No se encontró el concepto de BONIFICACION POR USADO", TipoMensaje.MsgAdvertencia) End If If AplicaRNCBonificacionXDetalle Then CrearDTNCBonificacionDescDetalle(ListaNCBonificacion, TmpDTDescNC, DrBonRef, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) Else CrearDTNCBonificacionDesc(DtImpuestosBonificacion, TmpDTDescNC, DrBonRef, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) End If Else For Each Dr As DataRow In DtImpuestos.Rows AgregaTempDT(TmpDTDescNC, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, TxtNCObservaciones.Text.Trim, 1, Dr("ImportePU").ToString.ToDecimal, Dr("PorcentajeIVA").ToString.ToDecimal, Dr("ImporteIVA").ToString.ToDecimal, Dr("PorcentajeRetIVA").ToString().ToDecimal, Dr("ImporteRetIVA").ToString().ToDecimal, Dr("PorcentajeRetISR").ToString().ToDecimal, Dr("ImporteRetISR").ToString().ToDecimal, Dr("PorcentajeIEPS").ToString().ToDecimal, Dr("ImporteIEPS").ToString().ToDecimal, -1, 0, Dr("ImporteTotal").ToString().ToDecimal, "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1) Next End If TrTipoRelacion.Visible = True DdlTiposRelacion.SelectedValueExist("1") 'verifica el tipo de cambio que se actualice If DdlMoneda.SelectedValue <> "1" Then If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TxtTipoCambio.Text = GlobalTipoCambio(Now.AddDays(-1)).ToString() Else TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString() End If End If Else If DdlTipoComprobante.SelectedValue = "Ant" Then CveAnticipo = CveVenta DdlTipoComprobante.SelectedValueExist(TipoDoctoNC) 'verifica el total de multiples facturas Dim Acumulado12 As Decimal = 0 Dim UltimoRenglon As Integer = 1 Dim Ajuste As Decimal = 0 'DEBE AGREGAR LOS USADOS DE LA REMISION EN LA NOTA DE CREDITO If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso (ListaRemisionesNC IsNot Nothing AndAlso ListaRemisionesNC.Count > 0) Then If AplicaRNCXDetalle Then CrearDTNCCargoDetalle(ListaRemisionesNC, TmpDT, DrPS, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) Else CrearDTNCCargo(ListaRemisionesNC, TmpDT, DrPS, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) End If 'EN LA NC DE BONIFICACION EL CONCEPTO DEBE SER SIEMPRE 'BONIFICACION POR USADO' 'CONSULTA EL CONCEPTO DE NC Dim ArrayNC As String() = UsuarioActual.Empresa.Funcionalidad(591).Split(",".ToCharArray()) Dim NCBonificacion As Integer = 0 If ArrayNC.Length > 4 Then NCBonificacion = ArrayNC(4).ToEntero() End If Dim DrPSBonificacion = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=NCBonificacion).FiltroPrimero("") If DrPSBonificacion IsNot Nothing Then CrearDTNCBonificacion(ListaRemisionesNC, DtImpuestosBonificacion, TmpDT, DrPSBonificacion, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) Else Alert("No se encontró el concepto de BONIFICACION POR USADO", TipoMensaje.MsgAdvertencia) CrearDTNCBonificacion(ListaRemisionesNC, DtImpuestosBonificacion, TmpDT, DrPS, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) End If ElseIf TipoDoctoNC = "Dev" Then CrearDTNCDevolucion(ListaRemisionesNC, TmpDT, CveProyecto, Proyecto, CveSubProyecto, SubProyecto) Else For Each Dr As DataRow In DtImpuestos.Rows Acumulado12 += Dr("ImportePU").ToString().ToDecimal.RoundSQL + Dr("ImporteIVA").ToString().ToDecimal.RoundSQL + Dr("ImporteIEPS").ToString().ToDecimal If UltimoRenglon = DtImpuestos.Rows.Count Then 'ajusta 5 centavos de diferencia If Acumulado12 <> AcumuladoNC And Math.Abs(Acumulado12 - AcumuladoNC) <= 0.05 Then Ajuste = (Acumulado12 - AcumuladoNC) End If End If UltimoRenglon += 1 AgregaTempDT(TmpDT, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, TxtNCObservaciones.Text.Trim, 1, Dr("ImportePU").ToString().ToDecimal + Ajuste, Dr("PorcentajeIVA").ToString().ToDecimal, Dr("ImporteIVA").ToString().ToDecimal, Dr("PorcentajeRetIVA").ToString().ToDecimal, Dr("ImporteRetIVA").ToString().ToDecimal, Dr("PorcentajeRetISR").ToString().ToDecimal, Dr("ImporteRetISR").ToString().ToDecimal, Dr("PorcentajeIEPS").ToString().ToDecimal, Dr("ImporteIEPS").ToString().ToDecimal, -1, 0, Dr("ImporteTotal").ToString().ToDecimal(), "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1) Next End If GvPS.DataSource = TmpDT GvPS.DataBind() CalculaTotalesVenta(RecalculaImpuestosLocales:=AplicaImpuestosLocales) TrTipoRelacion.Visible = True If TipoDoctoNC = "Egs" Then DdlTiposRelacion.SelectedValueExist("1") ElseIf TipoDoctoNC = "Dev" Then If DdlTipoComprobante.Items.FindByValue("Dev") Is Nothing Then DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) End If DdlTipoComprobante.SelectedValueExist("Dev") DdlTiposRelacion.SelectedValueExist("3") End If DdlSubProyectoDatos.Enabled = False 'condicióon, en la que se verifica que el importe total de aplicación de la nota de crédito sea igual al del total de la nota de crédito, ej. saldo de la factura 1000.01 y la nota de crédito se generó po 1000.00 If Not AplicaNCMasiva Then Dim TT As Decimal = TxtNCImporte.Text.ToDecimal If TT > TxtTotal.Text.ToDecimal Then TT = TxtTotal.Text.ToDecimal CargaNCDT(CveVenta, TT) End If 'verifica el tipo de cambio que se actualice If DdlMoneda.SelectedValue <> "1" Then If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TxtTipoCambio.Text = GlobalTipoCambio(Now.AddDays(-1)).ToString() Else TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString() End If End If LblTCValuacion.Visible = False UpPS.Update() LBNotaCredito.Visible = False LnkAplicarRNCDevolucion.Visible = False CambiaTipoDocto() End If Catch ex As Exception OnError("Ocurrió un error al aplicar NC", ex) End Try UPCondicionesPago.Update() End Sub Private Sub CrearDTNCCargo(ListaNC As List(Of Modelos.Factura), ByRef TmpDTCargo As DataTable, DrPS As DataRow, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String) For Each RNC In ListaNC Dim UltimoRenglonRNC As Integer = 1 Dim TotalAcumuladoRNC As Decimal = 0 Dim Terminar As Boolean = False For Each RowUsado As DataRow In RNC.DtDetalle.FiltraParametros("", Orderby:="PU").Rows Dim Cantidad As Decimal = RowUsado("Cantidad").ToString().ToDecimal() Dim CvePSCargo As Integer = RowUsado("CvePS").ToString().ToEntero() Dim Obs = "" 'SI ES ACUMULADOR LAS OBSERVACIOENS DEBEN SER EL NOMBRE DEL ACUMULADOR If GlobalDTAcumTamaños().FiltroPrimero($"CvePSCargo = {CvePSCargo}") IsNot Nothing Then Obs = RowUsado("CodigoPS").ToString() Else Obs = RowUsado("Obs").ToString() End If If Not String.IsNullOrEmpty(TxtNCObservaciones.Text.Trim()) Then Obs = String.Format("{0} - {1}", Obs, TxtNCObservaciones.Text.Trim()) End If Dim ImportePU = RowUsado("PU").ToString().ToDecimal Dim TotalCalculableImpuestos As Decimal = (Cantidad * ImportePU) Dim ImporteIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteIEPS = (TotalCalculableImpuestos * RowUsado("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetISR = (TotalCalculableImpuestos * RowUsado("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) Dim ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) 'SI EL IMPORTE ES MAYOR REALIZA EL AJUSTE If TotalAcumuladoRNC > RNC.TotalRemNCAplicado Then Terminar = True 'RESTA LO SUMANDO DEL ACUMULADO TotalAcumuladoRNC -= (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim Diferencia As Decimal = RNC.TotalRemNCAplicado - TotalAcumuladoRNC Dim TotalPartida As Decimal = (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim PorcentajePorAplicar As Decimal = (Diferencia / TotalPartida) Cantidad = Cantidad * PorcentajePorAplicar TotalCalculableImpuestos = (Cantidad * ImportePU) ImporteIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) ImporteIEPS = (TotalCalculableImpuestos * RowUsado("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) ImporteRetIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) ImporteRetISR = (TotalCalculableImpuestos * RowUsado("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) End If 'SI ES EL ULTIMO REGLON REALIZA UN AJUSTE If UltimoRenglonRNC = RNC.DtDetalle.Rows.Count OrElse Terminar Then Dim Ajuste As Decimal = 0 If Math.Abs(RNC.TotalRemNCAplicado - TotalAcumuladoRNC) > 0.00 Then Ajuste = RNC.TotalRemNCAplicado - TotalAcumuladoRNC ImporteIVA += Ajuste End If End If UltimoRenglonRNC += 1 'SOLO AGREGA SI LA CANTIDAD ES MAYOR CERO If Cantidad.RoundSQL(6) > 0D AndAlso ImportePU.RoundSQL(6) > 0 Then AgregaTempDT(TmpDTCargo, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, Obs, Cantidad, ImportePU, RowUsado("PorcentajeIVA").ToString().ToDecimal, ImporteIVA, RowUsado("PorcentajeRetIVA").ToString().ToDecimal, ImporteRetIVA, RowUsado("PorcentajeRetISR").ToString().ToDecimal, ImporteRetISR, RowUsado("PorcentajeIEPS").ToString().ToDecimal, ImporteIEPS, -1, 0, ImporteTotal, "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1, CveVentaDetalleRNC:=RowUsado("CveVentaDetalle").ToString().ToEntero()) End If If Terminar Then Exit For End If Next Next End Sub Private Sub CrearDTNCCargoDetalle(ListaNC As List(Of Modelos.Factura), ByRef TmpDTCargo As DataTable, DrPS As DataRow, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String) For Each RNC In ListaNC Dim UltimoRenglonRNC As Integer = 1 Dim TotalAcumuladoRNC As Decimal = 0 Dim Terminar As Boolean = False For Each RowUsado As DataRow In Me.TmpDTRNCDetalleSelecciondas.FiltraParametros($"CveVenta={RNC.CveVenta}", Orderby:="PU").Rows Dim Cantidad As Decimal = RowUsado("Cantidad").ToString().ToDecimal() Dim CvePSCargo As Integer = RowUsado("CvePS").ToString().ToEntero() Dim Obs = "" 'SI ES ACUMULADOR LAS OBSERVACIOENS DEBEN SER EL NOMBRE DEL ACUMULADOR If GlobalDTAcumTamaños().FiltroPrimero($"CvePSCargo = {CvePSCargo}") IsNot Nothing Then Obs = RowUsado("CodigoPS").ToString() End If 'SI TIENE BCI EN LAS OBSERVACIONES AGREGARLO A LA FACTURA If Not String.IsNullOrEmpty(RowUsado("Observaciones").ToString()) Then If String.IsNullOrEmpty(Obs) Then Obs = RowUsado("Observaciones").ToString() Else Obs = String.Format("{0} - {1}", Obs, RowUsado("Observaciones").ToString()) End If End If If Not String.IsNullOrEmpty(TxtNCObservaciones.Text.Trim()) Then Obs = String.Format("{0} - {1}", Obs, TxtNCObservaciones.Text.Trim()) End If Dim ImportePU = RowUsado("PU").ToString().ToDecimal Dim TotalCalculableImpuestos As Decimal = (Cantidad * ImportePU) Dim ImporteIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteIEPS = 0 '(TotalCalculableImpuestos * RowUsado("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetIVA = 0 ' (TotalCalculableImpuestos * RowUsado("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetISR = 0 ' (TotalCalculableImpuestos * RowUsado("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) Dim ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA) 'SI EL IMPORTE ES MAYOR REALIZA EL AJUSTE If TotalAcumuladoRNC > RNC.TotalRemNCAplicado Then Terminar = True 'RESTA LO SUMANDO DEL ACUMULADO TotalAcumuladoRNC -= (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim Diferencia As Decimal = RNC.TotalRemNCAplicado - TotalAcumuladoRNC Dim TotalPartida As Decimal = (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim PorcentajePorAplicar As Decimal = (Diferencia / TotalPartida) Cantidad = Cantidad * PorcentajePorAplicar TotalCalculableImpuestos = (Cantidad * ImportePU) ImporteIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) End If 'SI ES EL ULTIMO REGLON REALIZA UN AJUSTE If UltimoRenglonRNC = Me.TmpDTRNCDetalleSelecciondas.FiltraParametros($"CveVenta={RNC.CveVenta}").Rows.Count OrElse Terminar Then Dim Ajuste As Decimal = 0 If Math.Abs(RNC.TotalRemNCAplicado - TotalAcumuladoRNC) > 0.00 Then Ajuste = RNC.TotalRemNCAplicado - TotalAcumuladoRNC ImporteIVA += Ajuste End If End If UltimoRenglonRNC += 1 'SOLO AGREGA SI LA CANTIDAD ES MAYOR CERO If Cantidad.RoundSQL(6) > 0D AndAlso ImportePU.RoundSQL(6) > 0 Then AgregaTempDT(TmpDTCargo, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, Obs, Cantidad, ImportePU, RowUsado("PorcentajeIVA").ToString().ToDecimal, ImporteIVA, 0, ImporteRetIVA, 0, ImporteRetISR, 0, ImporteIEPS, -1, 0, ImporteTotal, "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1, CveVentaDetalleRNC:=RowUsado("CveVentaDetalleRNC").ToString().ToEntero()) End If If Terminar Then Exit For End If Next Next End Sub Private Sub CrearDTNCBonificacion(ListaNC As List(Of Modelos.Factura), DtImpuestosBonificacion As DataTable, ByRef TmpDTNC As DataTable, DrPS As DataRow, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String) 'SI TIENE DE BONIFICACION LOS AGREGA If DtImpuestosBonificacion IsNot Nothing AndAlso ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0 Then TmpDTDescNCBonificacion = TmpDTNC.Clone() TmpDTDescNCBonificacion.Clear() For Each RNCBonificacion In ListaNCBonificacion Dim UltimoRenglonRNC As Integer = 1 Dim TotalAcumuladoRNC As Decimal = 0 Dim Terminar As Boolean = False Dim RNCCargo = ListaNC.Where(Function(f) f.CveVenta = RNCBonificacion.CveVentaRNCCargo).FirstOrDefault() For Each RowCargo As DataRow In RNCCargo.DtDetalle.FiltraParametros("", Orderby:="PU").Rows Dim PorcentajeAplicado = (RNCBonificacion.TotalRemNCAplicado / RNCBonificacion.Total) Dim Cantidad As Decimal = RowCargo("Cantidad").ToString().ToDecimal() '* PorcentajeAplicado Dim Obs = RowCargo("CodigoPS").ToString() If Not String.IsNullOrEmpty(TxtNCObservaciones.Text.Trim()) Then Obs = String.Format("{0} - {1}", Obs, TxtNCObservaciones.Text.Trim()) End If Dim ImportePU = RowCargo("PUBonificacion").ToString().ToDecimal Dim TotalCalculableImpuestos As Decimal = (Cantidad * ImportePU) Dim ImporteIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteIEPS = (TotalCalculableImpuestos * RowCargo("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetISR = (TotalCalculableImpuestos * RowCargo("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) Dim ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) 'SI EL IMPORTE ES MAYOR REALIZA EL AJUSTE If TotalAcumuladoRNC > RNCBonificacion.TotalRemNCAplicado Then Terminar = True 'RESTA LO SUMANDO DEL ACUMULADO TotalAcumuladoRNC -= (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim Diferencia As Decimal = RNCBonificacion.TotalRemNCAplicado - TotalAcumuladoRNC Dim TotalPartida As Decimal = (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim PorcentajePorAplicar As Decimal = (Diferencia / TotalPartida) Cantidad = Cantidad * PorcentajePorAplicar TotalCalculableImpuestos = (Cantidad * ImportePU) ImporteIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) ImporteIEPS = (TotalCalculableImpuestos * RowCargo("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) ImporteRetIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) ImporteRetISR = (TotalCalculableImpuestos * RowCargo("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) End If 'SI ES EL ULTIMO REGLON REALIZA UN AJUSTE If UltimoRenglonRNC = RNCCargo.DtDetalle.Rows.Count Then Dim Ajuste As Decimal = 0 If Math.Abs(RNCBonificacion.TotalRemNCAplicado - TotalAcumuladoRNC) > 0.00 Then Ajuste = RNCBonificacion.TotalRemNCAplicado - TotalAcumuladoRNC ImporteIVA += Ajuste End If End If UltimoRenglonRNC += 1 'SOLO AGREGA SI LA CANTIDAD ES MAYOR CERO If Cantidad.RoundSQL(6) > 0D AndAlso ImportePU.RoundSQL(6) > 0 Then AgregaTempDT(TmpDTDescNCBonificacion, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, Obs, Cantidad, ImportePU, RowCargo("PorcentajeIVA").ToString().ToDecimal, ImporteIVA, RowCargo("PorcentajeRetIVA").ToString().ToDecimal, ImporteRetIVA, RowCargo("PorcentajeRetISR").ToString().ToDecimal, ImporteRetISR, RowCargo("PorcentajeIEPS").ToString().ToDecimal, ImporteIEPS, -1, 0, ImporteTotal, "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1) End If Next Next End If End Sub Private Sub CrearDTNCBonificacionDesc(DtImpuestosBonificacion As DataTable, ByRef TmpDTNC As DataTable, DrPS As DataRow, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String) 'SI TIENE DE BONIFICACION LOS AGREGA If DtImpuestosBonificacion IsNot Nothing AndAlso ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0 Then TmpDTDescNCBonificacion = TmpDTNC.Clone() TmpDTDescNCBonificacion.Clear() For Each RNCBonificacion In ListaNCBonificacion Dim UltimoRenglonRNC As Integer = 1 Dim TotalAcumuladoRNC As Decimal = 0 Dim Terminar As Boolean = False 'Dim RNCCargo = ListaNC.Where(Function(f) f.CveVenta = RNCBonificacion.CveVentaRNCCargo).FirstOrDefault() For Each RowCargo As DataRow In TmpDT.FiltraParametros("EsCargo = True", Orderby:="PU").Rows Dim CantidadCargo = RowCargo("Cantidad").ToString().ToDecimal() Dim ImportePU As Decimal = GlobalDTAcumTamaños().FiltroPrimeroValor("Bonificacion", $"CvePSCargo={RowCargo("CvePS")}").ToDecimal() Dim TotalCalculableImpuestosCargo As Decimal = (CantidadCargo * ImportePU) Dim TotalCargo As Decimal = TotalCalculableImpuestosCargo + (TotalCalculableImpuestosCargo * RowCargo("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) Dim PorcentajeAplicado = (RNCBonificacion.TotalRemNCAplicado / TotalCargo) Dim Cantidad As Decimal = RowCargo("Cantidad").ToString().ToDecimal() * PorcentajeAplicado Dim Obs = RowCargo("CodigoPS").ToString() If Not String.IsNullOrEmpty(TxtNCObservaciones.Text.Trim()) Then Obs = String.Format("{0} - {1}", Obs, TxtNCObservaciones.Text.Trim()) End If 'Dim ImportePU = RowCargo("PUBonificacion").ToString().ToDecimal Dim TotalCalculableImpuestos As Decimal = (Cantidad * ImportePU) Dim ImporteIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteIEPS = (TotalCalculableImpuestos * RowCargo("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetISR = (TotalCalculableImpuestos * RowCargo("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) Dim ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) 'SI EL IMPORTE ES MAYOR REALIZA EL AJUSTE If TotalAcumuladoRNC > RNCBonificacion.TotalRemNCAplicado Then Terminar = True 'RESTA LO SUMANDO DEL ACUMULADO TotalAcumuladoRNC -= (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim Diferencia As Decimal = RNCBonificacion.TotalRemNCAplicado - TotalAcumuladoRNC Dim TotalPartida As Decimal = (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim PorcentajePorAplicar As Decimal = (Diferencia / TotalPartida) Cantidad = Cantidad * PorcentajePorAplicar TotalCalculableImpuestos = (Cantidad * ImportePU) ImporteIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) ImporteIEPS = (TotalCalculableImpuestos * RowCargo("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) ImporteRetIVA = (TotalCalculableImpuestos * RowCargo("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) ImporteRetISR = (TotalCalculableImpuestos * RowCargo("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) End If 'SI ES EL ULTIMO REGLON REALIZA UN AJUSTE If UltimoRenglonRNC = TmpDT.FiltraParametros("EsCargo = True", Orderby:="PU").Rows.Count Then Dim Ajuste As Decimal = 0 If Math.Abs(RNCBonificacion.TotalRemNCAplicado - TotalAcumuladoRNC) > 0.00 Then Ajuste = RNCBonificacion.TotalRemNCAplicado - TotalAcumuladoRNC ImporteIVA += Ajuste End If End If UltimoRenglonRNC += 1 'SOLO AGREGA SI LA CANTIDAD ES MAYOR CERO If Cantidad.RoundSQL(6) > 0D AndAlso ImportePU.RoundSQL(6) > 0 Then AgregaTempDT(TmpDTDescNCBonificacion, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, Obs, Cantidad, ImportePU, RowCargo("PorcentajeIVA").ToString().ToDecimal, ImporteIVA, RowCargo("PorcentajeRetIVA").ToString().ToDecimal, ImporteRetIVA, RowCargo("PorcentajeRetISR").ToString().ToDecimal, ImporteRetISR, RowCargo("PorcentajeIEPS").ToString().ToDecimal, ImporteIEPS, -1, 0, ImporteTotal, "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1) End If Next Next End If End Sub Private Sub CrearDTNCBonificacionDescDetalle(ListaNC As List(Of Modelos.Factura), ByRef TmpDTCargo As DataTable, DrPS As DataRow, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String) TmpDTDescNCBonificacion = TmpDTCargo.Clone() TmpDTDescNCBonificacion.Clear() For Each RNC In ListaNC Dim UltimoRenglonRNC As Integer = 1 Dim TotalAcumuladoRNC As Decimal = 0 Dim Terminar As Boolean = False For Each RowUsado As DataRow In Me.TmpDTRNCBonificacionDetalleSeleccionadas.FiltraParametros($"CveVenta={RNC.CveVenta}", Orderby:="PU").Rows Dim Cantidad As Decimal = RowUsado("Cantidad").ToString().ToDecimal() Dim CvePSCargo As Integer = RowUsado("CvePS").ToString().ToEntero() Dim Obs = "" 'SI ES ACUMULADOR LAS OBSERVACIOENS DEBEN SER EL NOMBRE DEL ACUMULADOR If GlobalDTAcumTamaños().FiltroPrimero($"CvePSCargo = {CvePSCargo}") IsNot Nothing Then Obs = RowUsado("CodigoPS").ToString() 'Else ' Obs = RowUsado("Obs").ToString() End If If Not String.IsNullOrEmpty(TxtNCObservaciones.Text.Trim()) Then Obs = String.Format("{0} - {1}", Obs, TxtNCObservaciones.Text.Trim()) End If Dim ImportePU = RowUsado("PU").ToString().ToDecimal Dim TotalCalculableImpuestos As Decimal = (Cantidad * ImportePU) Dim ImporteIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteIEPS = 0 '(TotalCalculableImpuestos * RowUsado("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetIVA = 0 ' (TotalCalculableImpuestos * RowUsado("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetISR = 0 ' (TotalCalculableImpuestos * RowUsado("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) Dim ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA) 'SI EL IMPORTE ES MAYOR REALIZA EL AJUSTE If TotalAcumuladoRNC > RNC.TotalRemNCAplicado Then Terminar = True 'RESTA LO SUMANDO DEL ACUMULADO TotalAcumuladoRNC -= (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim Diferencia As Decimal = RNC.TotalRemNCAplicado - TotalAcumuladoRNC Dim TotalPartida As Decimal = (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim PorcentajePorAplicar As Decimal = (Diferencia / TotalPartida) Cantidad = Cantidad * PorcentajePorAplicar TotalCalculableImpuestos = (Cantidad * ImportePU) ImporteIVA = (TotalCalculableImpuestos * RowUsado("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) End If 'SI ES EL ULTIMO REGLON REALIZA UN AJUSTE If UltimoRenglonRNC = Me.TmpDTRNCBonificacionDetalleSeleccionadas.FiltraParametros($"CveVenta={RNC.CveVenta}").Rows.Count OrElse Terminar Then Dim Ajuste As Decimal = 0 If Math.Abs(RNC.TotalRemNCAplicado - TotalAcumuladoRNC) > 0.00 Then Ajuste = RNC.TotalRemNCAplicado - TotalAcumuladoRNC ImporteIVA += Ajuste End If End If UltimoRenglonRNC += 1 'SOLO AGREGA SI LA CANTIDAD ES MAYOR CERO If Cantidad.RoundSQL(6) > 0D AndAlso ImportePU.RoundSQL(6) > 0 Then AgregaTempDT(TmpDTDescNCBonificacion, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, Obs, Cantidad, ImportePU, RowUsado("PorcentajeIVA").ToString().ToDecimal, ImporteIVA, 0, ImporteRetIVA, 0, ImporteRetISR, 0, ImporteIEPS, -1, 0, ImporteTotal, "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1, CveVentaDetalleRNC:=RowUsado("CveVentaDetalleRNC").ToString().ToEntero()) End If If Terminar Then Exit For End If Next Next End Sub Private Sub CrearDTNCDevolucion(ListaNC As List(Of Modelos.Factura), ByRef TmpDTCargo As DataTable, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String) For Each RNC In ListaNC Dim UltimoRenglonRNC As Integer = 1 Dim TotalAcumuladoRNC As Decimal = 0 Dim Terminar As Boolean = False For Each RowRNC As DataRow In RNC.DtDetalle.FiltraParametros("", Orderby:="PU").Rows Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=RowRNC("CvePS").ToString().ToEntero()).FiltroPrimero("") Dim Cantidad As Decimal = RowRNC("Cantidad").ToString().ToDecimal() Dim CvePSCargo As Integer = RowRNC("CvePS").ToString().ToEntero() Dim ImportePU = RowRNC("PU").ToString().ToDecimal Dim Obs As String = "" Dim TotalCalculableImpuestos As Decimal = (Cantidad * ImportePU) Dim ImporteIVA = (TotalCalculableImpuestos * RowRNC("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteIEPS = (TotalCalculableImpuestos * RowRNC("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetIVA = (TotalCalculableImpuestos * RowRNC("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) Dim ImporteRetISR = (TotalCalculableImpuestos * RowRNC("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) Dim ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR).RoundSQL 'SI EL IMPORTE ES MAYOR REALIZA EL AJUSTE If TotalAcumuladoRNC > RNC.TotalRemNCAplicado Then Terminar = True 'RESTA LO SUMANDO DEL ACUMULADO TotalAcumuladoRNC -= (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim Diferencia As Decimal = RNC.TotalRemNCAplicado - TotalAcumuladoRNC Dim TotalPartida As Decimal = (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR) Dim PorcentajePorAplicar As Decimal = (Diferencia / TotalPartida) Cantidad = Cantidad * PorcentajePorAplicar TotalCalculableImpuestos = (Cantidad * ImportePU) ImporteIVA = (TotalCalculableImpuestos * RowRNC("PorcentajeIVA").ToString().ToDecimal).RoundSQL(2) ImporteIEPS = (TotalCalculableImpuestos * RowRNC("PorcentajeIEPS").ToString().ToDecimal).RoundSQL(2) ImporteRetIVA = (TotalCalculableImpuestos * RowRNC("PorcentajeRetIVA").ToString().ToDecimal).RoundSQL(2) ImporteRetISR = (TotalCalculableImpuestos * RowRNC("PorcentajeRetISR").ToString().ToDecimal).RoundSQL(2) ImporteTotal = TotalCalculableImpuestos TotalAcumuladoRNC += (TotalCalculableImpuestos + ImporteIVA + ImporteIEPS - ImporteRetIVA - ImporteRetISR).RoundSQL End If 'SI ES EL ULTIMO REGLON REALIZA UN AJUSTE If UltimoRenglonRNC = RNC.DtDetalle.Rows.Count OrElse Terminar Then Dim Ajuste As Decimal = 0 If Math.Abs(RNC.TotalRemNCAplicado - TotalAcumuladoRNC) > 0.00 Then Ajuste = RNC.TotalRemNCAplicado - TotalAcumuladoRNC If ImporteIVA > 0 Then ImporteIVA += Ajuste ElseIf ImporteIEPS > 0 Then ImporteIEPS += Ajuste End If End If End If UltimoRenglonRNC += 1 'SOLO AGREGA SI LA CANTIDAD ES MAYOR CERO If Cantidad.RoundSQL(6) > 0D AndAlso ImportePU.RoundSQL(6) > 0 Then AgregaTempDT(TmpDTCargo, DrPS("CvePS").ToString().ToEntero(), DrPS("PS").ToString(), DrPS("Codigo").ToString(), DrPS("PSCodigo").ToString(), DrPS("CveTipoPS").ToString().ToEntero(), DrPS("Inv_CveMetodoInventario").ToString().ToEntero(), DrPS("CveUM").ToString().ToEntero(), DrPS("UnidadMedida").ToString(), DrPS("CveClasificacion").ToString().ToEntero(), DrPS("Clasificacion").ToString(), CveProyecto, Proyecto, CveSubProyecto, SubProyecto, Obs, Cantidad, ImportePU, RowRNC("PorcentajeIVA").ToString().ToDecimal, ImporteIVA, RowRNC("PorcentajeRetIVA").ToString().ToDecimal, ImporteRetIVA, RowRNC("PorcentajeRetISR").ToString().ToDecimal, ImporteRetISR, RowRNC("PorcentajeIEPS").ToString().ToDecimal, ImporteIEPS, -1, 0, ImporteTotal, "", "", -1, -1, DrPS("SATClavePS").ToString(), DrPS("SATClaveUnidadMedida").ToString(), -1, -1, -1, -1, -1, -1, CveVentaDetalleRNC:=RowRNC("CveVentaDetalle").ToString().ToEntero()) End If If Terminar Then Exit For End If Next Next End Sub Private Function CargaDtImpuestosNC(CveVentaNC As Integer, Importe As Decimal, Optional NCDescuento As Boolean = False, Optional AplicaImpuestosLocales As Boolean = True, Optional NivelTotal As Integer = 1, Optional AplicaNCUsado As Boolean = False) As DataTable Dim Total As Decimal = 0, SubTotal As Decimal = 0, Saldo As Decimal = 0 Dim TmpDT As DataTable = Nothing Dim TmpDTImpuestos As DataTable = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVentaImpuestosLocales(CveVentaNC) Then If ObjVentas.DtResultados.Rows.Count > 0 Then TmpDTImpuestos = ObjVentas.DtResultados.Copy() End If End If If ObjVentas.GetVentaDetalle(CveVentaNC) Then TmpDT = ObjVentas.DtResultados.Copy() 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)) End If Dim FechaFactura As DateTime = Now If AplicaNCMasiva OrElse AplicaNCUsado Then If ObjVentas.GetVenta(CveVentaNC, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then Total = ObjVentas.DtResultados()(0)("Total").ToString().ToDecimal SubTotal = ObjVentas.DtResultados()(0)("SubTotal").ToString().ToDecimal FechaFactura = ObjVentas.DtResultados()(0)("Fecha").ToString().ToDateTime() End If End If Else Total = TxtTotal.Text.ToDecimal SubTotal = TxtSubTotal.Text.ToDecimal End If ObjVentas.Dispose() Dim DtImpuestosLocal = TmpDT.FiltraParametros("", "", {"PorcentajeIVA", "PorcentajeRetIVA", "PorcentajeRetISR", "PorcentajeIEPS", "CveSubProyecto"}).Copy() DtImpuestosLocal.Columns.Add("ImportePU", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteTotal", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteIVA", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteRetIVA", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteRetISR", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteIEPS", GetType(Decimal)) Dim ImporteReferencia As Decimal = If(NivelTotal = 1, Total, SubTotal) Dim Porcentaje As Decimal = ((Importe * 100) / ImporteReferencia) / 100 Dim FiltroStr As String = "" Dim TotalImpuestosLocalesVentaOriginal As Decimal = 0 Dim TotalImpuestosLocalesRecalculado As Decimal = 0 'CALCULA LO EQUIVALENTE EN IMPUSTOS LOCALES If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then TotalImpuestosLocalesVentaOriginal = TmpDTImpuestos.SUM("Importe").ToDecimal() TotalImpuestosLocalesRecalculado = TotalImpuestosLocalesVentaOriginal * Porcentaje End If Dim AplicaRedondeo As Boolean = True Dim TieneMultiplesSubProyectos As Boolean = TmpDT.FiltraParametros("", "", {"CveSubProyecto"}).COUNT("CveSubProyecto", "CveSubProyecto > 0") > 1 If AplicaNCMasiva AndAlso Not NCDescuento OrElse TieneMultiplesSubProyectos Then AplicaRedondeo = False End If For Each Dr As DataRow In DtImpuestosLocal.Rows FiltroStr = String.Format("ISNULL(PorcentajeIVA,0) = {0} AND ISNULL(PorcentajeRetIVA,0) = {1} AND ISNULL(PorcentajeRetISR,0) = {2} AND ISNULL(PorcentajeIEPS,0) = {3} AND ISNULL(CveSubProyecto,0) = {4} ", Dr("PorcentajeIVA").ToString().ToDecimal, Dr("PorcentajeRetIVA").ToString().ToDecimal, Dr("PorcentajeRetISR").ToString().ToDecimal, Dr("PorcentajeIEPS").ToString().ToDecimal, Dr("CveSubProyecto")) Dim importePuTemp As Decimal = (Porcentaje * (TmpDT.SUMD("TotalImporte", FiltroStr) - TmpDT.SUMD("Descuento", FiltroStr))) If Not AplicaImpuestosLocales Then importePuTemp = importePuTemp - TotalImpuestosLocalesVentaOriginal End If Dr("ImporteTotal") = importePuTemp.RoundSQL(2) Dr("ImporteIEPS") = (importePuTemp * Dr("PorcentajeIEPS").ToString().ToDecimal()) 'A PARTIR DEL 2020 SE CAMBIO EL CALCULO PARA EL IVA CONSIDERANDO EL IEPS If FechaFactura.Year <= 2019 Then Dr("ImporteIVA") = (importePuTemp * Dr("PorcentajeIVA").ToString().ToDecimal()) Else Dim TotalCalculableImpuestosIVA As Decimal = importePuTemp * (1 + Dr("PorcentajeIEPS").ToString().ToDecimal) Dr("ImporteIVA") = ((TotalCalculableImpuestosIVA) * Dr("PorcentajeIVA").ToString().ToDecimal) End If Dr("ImporteRetIVA") = (importePuTemp * Dr("PorcentajeRetIVA").ToString().ToDecimal()) Dr("ImporteRetISR") = (importePuTemp * Dr("PorcentajeRetISR").ToString().ToDecimal()) Dr("ImportePU") = importePuTemp If AplicaRedondeo Then Dr("ImporteIEPS") = Dr("ImporteIEPS").ToString().ToDecimal().RoundSQL(2) Dr("ImporteIVA") = Dr("ImporteIVA").ToString().ToDecimal().RoundSQL(2) Dr("ImporteRetIVA") = Dr("ImporteRetIVA").ToString().ToDecimal().RoundSQL(2) Dr("ImporteRetISR") = Dr("ImporteRetISR").ToString().ToDecimal().RoundSQL(2) Dr("ImportePU") = Dr("ImportePU").ToString().ToDecimal().RoundSQL(6) End If Next Dim importeNC = (DtImpuestosLocal.SUMD("ImporteTotal") + DtImpuestosLocal.SUMD("ImporteIVA") + DtImpuestosLocal.SUMD("ImporteIEPS") - DtImpuestosLocal.SUMD("ImporteRetIVA") - DtImpuestosLocal.SUMD("ImporteRetISR")) If AplicaImpuestosLocales Then Importe = Importe + TotalImpuestosLocalesRecalculado End If If AplicaRedondeo Then 'ASUSTO LA DIFERENCIA EN EL ÚLTIMO CONCEPTO 'CODIGO PARA AJUSTE DE CENTAVO, SI EL IMPORTE TOTAL NO CUADRA CON LOS TOTALES Dim difTmp As Decimal = Importe - importeNC If Math.Abs(difTmp) > 0.00D Then Dim ImporteAjustado As Decimal = DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal").ToString().ToDecimal + difTmp DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal") = ImporteAjustado DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImportePU") = ImporteAjustado End If End If If Not NCDescuento Then Me.TmpDT = TmpDT End If 'CARGA FACTURA A LA CUAL SE APLICA LA NC 'CargaNCDT(CveVentaNC, Importe.ToDecimal) Return DtImpuestosLocal End Function Private Sub AgregaTempDT(ByRef TmpDT As DataTable, CvePS As Integer, PS As String, Codigo As String, CodigoPS As String, CveTipoPS As Integer, CveTipoInvPS As Integer, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, Obs As String, Cantidad As Decimal, PU As Decimal, PorcentajeIVA As Decimal, ImporteIVA As Decimal, PorcentajeRetIVA As Decimal, ImporteRetIVA As Decimal, PorcentajeRetISR As Decimal, ImporteRetISR As Decimal, PorcentajeIEPS As Decimal, ImporteIEPS As Decimal, TipoDescuento As Integer, Descuento As Decimal, Total As Decimal, Serie As String, TiempoEntrega As String, CvePresupuestoIngreso As Integer, EntregaDirecta As Integer, SATClaveProdServ As String, SATClaveUM As String, CveContratoDetalle As Integer, CveVentaDetalle As Integer, CveMovimientoDetallePedido As Integer, CveOrdenCompraDetalle As Integer, CveVentaDetalleRemision As Integer, CveVentaDetalleCotizacion As Integer, Optional CveTamaño As Integer = -1, Optional CveVentaDetalleRNC As Integer = -1) Dim Row As DataRow = Nothing Row = TmpDT.NewRow() Row("Consec") = TmpDT.Rows.Count + 1 Row("Orden") = TmpDT.Rows.Count + 1 Row("CvePS") = CvePS Row("PS") = PS Row("Codigo") = Codigo Row("CodigoPS") = CodigoPS Row("CveTipoPS") = CveTipoPS Row("CveTipoInvPS") = CveTipoInvPS Row("CveUM") = CveUM Row("UM") = UM Row("CveClasificacion") = CveClasificacion Row("Clasificacion") = Clasificacion Row("CveProyecto") = CveProyecto Row("Proyecto") = Proyecto Row("CveSubProyecto") = CveSubProyecto Row("SubProyecto") = SubProyecto Row("Obs") = Obs Row("Cantidad") = Cantidad Row("PU") = PU.RoundSQL(6) Row("PorcentajeIVA") = PorcentajeIVA Row("IVA") = PorcentajeIVA Row("ImporteIVA") = Math.Round(ImporteIVA, NumeroDecimales) Row("PorcentajeRetIVA") = PorcentajeRetIVA Row("ImporteRetIVA") = Math.Round(ImporteRetIVA, NumeroDecimales) Row("PorcentajeRetISR") = PorcentajeRetISR Row("ImporteRetISR") = Math.Round(ImporteRetISR, NumeroDecimales) Row("PorcentajeIEPS") = PorcentajeIEPS Row("ImporteIEPS") = Math.Round(ImporteIEPS, NumeroDecimales) Row("IEPS") = Math.Round(ImporteIEPS, NumeroDecimales) Row("TipoDescuento") = TipoDescuento Row("Descuento") = Math.Round(Descuento, NumeroDecimales) Row("Total") = Math.Round(Total, NumeroDecimales) Row("TotalImporte") = Math.Round(Total, NumeroDecimales) Row("Serie") = Serie Row("TiempoEntrega") = TiempoEntrega Row("CvePresupuestoIngreso") = CvePresupuestoIngreso Row("EntregaDirecta") = EntregaDirecta Row("SATClaveProdServ") = SATClaveProdServ Row("SATClaveUM") = SATClaveUM 'Contratos Row("CveContratoDetalle") = CveContratoDetalle Row("CveVentaDetalle") = CveVentaDetalle Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle Row("CveVentaDetalleRemision") = CveVentaDetalleRemision Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion Row("CveTamaño") = CveTamaño Row("CveVentaDetalleRNC") = CveVentaDetalleRNC TmpDT.Rows.Add(Row) End Sub Private Sub LimpiaDocumentoNC() EsCreaApartirDe = True DivEstatusFac.Visible = False TabAlmacen.Visible = False 'LIMPIA ACCIONES HLOrdendeCompra.Visible = False LBAplicaDevolucion.Visible = False 'LkNotaCredito.Visible = False LkEliminarFactura.Visible = False ImgDownCancelacion.Visible = False LkRefacturacion.Visible = False HLOrdenServicio.Visible = False LkCotizacionAutorizar.Visible = False LnkFacturarRemision.Visible = False LnkRemisiones.Visible = False LnkPedido2SinFacturar.Visible = False LnkCotizaciones.Visible = False LnkOCs.Visible = False LbCancelarDocumento.Visible = False LBCancelarPedido.Visible = False LiDevolucionAlmacen.Visible = False HLPagar.Visible = False HlAgregarExcel.Visible = False HplDownXML.Visible = False HplDownPDF.Visible = False HLSaldarVenta.Visible = False LBNotaCredito.Visible = False LnkAplicarRNCDevolucion.Visible = False LiComplementoPago.Visible = False HlCuentaTerminal.Visible = False LiLnkGuias.Visible = False LiDocumentoCliente.Visible = False 'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION GvPS.Columns(6).Visible = False ThCantidadFacturadaRem.Visible = False ThCantidadFacturadaRem2.Visible = False GvPS.Columns(7).Visible = False ThCantidadFacturada.Visible = False ThCantidadFacturada2.Visible = False 'LIMPIA DETALLES TmpDT.Clear() GvPS.DataSource = Nothing GvPS.DataBind() LblFolioFiscal.Text = "" TxtFecha.Text = Now.ToShortDateString 'DESACTIVA/ACTIVA BOTONES TrVistaPrevia.Visible = True BtnEmitir.Visible = False BtnCrearApartirDe.Visible = False BtnGenerarRemision.Visible = False BtnPermisoEditarCotizacion.Visible = False BtnEditarCotizacion.Visible = False BtnGenerarOS.Visible = False 'ACTIVA CONDICIONES DE PAGO DdlUsoCFDI.Enabled = True DdlUsoCFDI.SelectedValueExist("2") If UsuarioActual.CveEmpresa <> 140 Then DdlMetodoPago33.Enabled = True DdlMetodoPago33.SelectedValueExist("1") ' PUE CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) DdlFormaPago33.Enabled = True DdlFormaPago33.SelectedValueExist("11") ' condonación por default End If UpEstatus.Update() UpnTools.Update() UpCliente.Update() UpParametros.Update() UpPS.Update() UpFacturar.Update() UPObservaciones.Update() UPPDescuento.Update() UPCondicionesPago.Update() UpDetalle.Update() BloqueaCondiconesPago() End Sub Private Sub InicializaDTAnticiposAmortizacion() Me.DtAnticipoAmortizacion = New DataTable Me.DtAnticipoAmortizacion.Columns.Add("CveVenta", GetType(Integer)) Me.DtAnticipoAmortizacion.Columns.Add("Importe", GetType(Decimal)) Me.DtAnticipoAmortizacion.Columns.Add("SaldoAnticipo", GetType(Decimal)) End Sub Private Sub InicializaDTVentasNC() DtVentasNC = New DataTable DtVentasNC.Columns.Add("CveVenta", GetType(Integer)) DtVentasNC.Columns.Add("Importe", GetType(Decimal)) DtVentasNC.Columns.Add("FolioFiscal", GetType(String)) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TC", .DataType = GetType(Decimal), .DefaultValue = 1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TCCambioValuacion", .DataType = GetType(Decimal), .DefaultValue = 1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "CveEstatusFactura", .DataType = GetType(Integer), .DefaultValue = -1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "Folio", .DataType = GetType(String), .DefaultValue = ""}) End Sub Private Sub CargaNCDT(pCveVenta As Integer, Importe As Decimal, Optional FolioFiscal As String = "", Optional NuevaFactura As Integer = -1, Optional ByRef ObjVentas As ClsVentas = Nothing, Optional TC As Decimal = 1) If (pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs")) OrElse (pCveVenta > 0 AndAlso NuevaFactura = 1) Then Dim CveEstatusFacturaNC As Integer = -1 Dim TCCambioValuacion As Decimal = 1 Dim Folio As String = "" If FolioFiscal = "" Then Dim ObjVentasAplicar As ClsVentas If ObjVentas IsNot Nothing Then ObjVentasAplicar = ObjVentas Else ObjVentasAplicar = New ClsVentas End If If ObjVentasAplicar.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentasAplicar.DtResultados.Rows.Count > 0 Then Folio = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("SerieFolio").ToString() FolioFiscal = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("FolioFiscal").ToString() TC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambio").ToString().ToDecimal() TCCambioValuacion = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambioValuacion").ToString().ToDecimal() CveEstatusFacturaNC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("CveEstatusFactura").ToString().ToEntero() End If If ObjVentas Is Nothing Then ObjVentasAplicar.Dispose() End If End If Dim Dr = DtVentasNC.NewRow Dr("CveVenta") = pCveVenta Dr("Importe") = Importe Dr("FolioFiscal") = FolioFiscal Dr("TC") = TC Dr("TCCambioValuacion") = TCCambioValuacion Dr("CveEstatusFactura") = CveEstatusFacturaNC Dr("Folio") = Folio DtVentasNC.Rows.Add(Dr) End If End Sub #End Region #Region " APLICA DEVOLUCION " Private Sub InicializaAplicaDevolucion(DtDetalle As DataTable) 'If Not UsuarioActual.CveUsuario = 100 Then ' If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119, 140, 141, 146) Then ' Exit Sub ' End If 'End If 'sino tiene el permiso no puede generar Devolucion If Not UsuarioActual.TienePermisoProceso(264) Then Exit Sub End If 'SOLO APLICA DEVOLUCION SI TIENE MOVIMIENTOS DE ALMACEN If VentaSaldoAlmacen < 0 Then LBAplicaDevolucion.Visible = True ElseIf VentaSaldoAlmacen >= 0 Then LBAplicaDevolucion.Visible = False End If Dim SeEsconde As Boolean = False If DtDetalle IsNot Nothing AndAlso DtDetalle.Rows.Count > 0 Then If Not DtDetalle.SUM("CantSur").ToString().ToDecimal > 0 Then SeEsconde = True 'NO MOSTRAR LOS PRODUCTOS CON LA CLASIFICACION DE USADOS GvAplicaDevolucion.DataSource = DtDetalle.FiltraParametros("CantRes > 0 AND CveClasificacion <> 20519") End If 'activo el permiso para registrar el importe diferente a la devolución GvAplicaDevolucion.Columns(9).Visible = UsuarioActual.TienePermisoProceso(253) 'MODALIDAD CENTRO COSTOS If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal" ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto" ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal/Proyecto" ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto/Sucursal" End If If SeEsconde Then GvAplicaDevolucion.Columns(1).Visible = False : GvAplicaDevolucion.Columns(2).Visible = False : GvAplicaDevolucion.Columns(3).Visible = False GvAplicaDevolucion.DataBind() UpDevolucion.Update() End Sub Protected Sub BtnCalcularPenalizacion_Click(sender As Object, e As EventArgs) Dim PorcentajePenalizacion As Decimal = (TxtPorPenalizacion.Text.ToDecimal() / 100D) For Each GvRow As GridViewRow In GvAplicaDevolucion.Rows If GvRow.FCCheckBox("Chk").Checked Then Dim Total As Decimal = GvRow.DataKey("PU").ToDecimal() - (GvRow.DataKey("Descuento").ToDecimal() / GvRow.DataKey("Cantidad").ToDecimal()) 'APLICA EL PORCENTAJE DE PENALIZACION GvRow.FCTextBox("TxtPrecioEditado").Text = (Total - (Total * PorcentajePenalizacion)).FormatoNumero(2) End If Next UpDevolucion.Update() End Sub Protected Sub BtnAplicaDevolucion_Click(sender As Object, e As EventArgs) 'VALIDACIONES Dim Selecciono As Boolean = False For Each Gv As GridViewRow In GvAplicaDevolucion.Rows If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDouble > 0 Then Selecciono = True Exit For End If Next If Not Selecciono Then Alert("Tiene que seleccionar al menos un concepto y este dege tener una cantidad mayor a 0. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia) Exit Sub End If AplicaDevolucion = True SaldoVentaDevolucion = HplSaldoAuxiliar.Text.ToDecimal CveVentaDevolucion = CveVenta DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev")) DdlTipoComprobante.SelectedValue = "Dev" Dim AplicaPUEditado As Boolean = UsuarioActual.TienePermisoProceso(253) Dim DtUsados As DataTable = TmpDT.FiltraParametros("EsCargo = True") TmpDT.Clear() For Each Gv As GridViewRow In GvAplicaDevolucion.Rows If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal > 0 Then Dim Cantidad As Decimal = Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal Dim Descuento As Decimal = Cantidad * Gv.DataKey("Descuento").ToString().ToDecimal / Gv.DataKey("Cantidad").ToString().ToDecimal Dim PU As Decimal = If(AplicaPUEditado, Gv.FCTextBox("TxtPrecioEditado").Text.ToDecimal, Gv.DataKey("PU").ToDecimal) Dim Total As Decimal = (Cantidad * PU) Dim TotalImpuestos As Decimal = (Cantidad * PU) - Descuento Dim ImporteIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIVA").ToString().ToDecimal Dim ImporteRetIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetIVA").ToString().ToDecimal Dim ImporteRetISR As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetISR").ToString().ToDecimal Dim ImporteIEPS As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIEPS").ToString().ToDecimal AgregaTempDT(TmpDT, Gv.DataKey("CvePS").ToString().ToEntero(), Gv.DataKey("PS").ToString(), Gv.DataKey("Codigo").ToString(), Gv.DataKey("CodigoPS").ToString(), Gv.DataKey("CveTipoPS").ToString().ToEntero(), Gv.DataKey("CveTipoInvPS").ToString().ToEntero(), Gv.DataKey("CveUM").ToString().ToEntero(), Gv.DataKey("UM").ToString(), Gv.DataKey("CveClasificacion").ToString().ToEntero(), Gv.DataKey("Clasificacion").ToString(), Gv.DataKey("CveProyecto").ToString().ToEntero(), Gv.DataKey("Proyecto").ToString(), Gv.DataKey("CveSubProyecto").ToString().ToEntero(), Gv.DataKey("SubProyecto").ToString(), Gv.DataKey("Obs").ToString(), Cantidad, PU, Gv.DataKey("PorcentajeIVA").ToString().ToDecimal, ImporteIVA, Gv.DataKey("PorcentajeRetIVA").ToString().ToDecimal, ImporteRetIVA, Gv.DataKey("PorcentajeRetISR").ToString().ToDecimal, ImporteRetISR, Gv.DataKey("PorcentajeIEPS").ToString().ToDecimal, ImporteIEPS, -1, Descuento, Total, "", "", -1, -1, Gv.DataKey("SATClaveProdServ").ToString(), Gv.DataKey("SATClaveUM").ToString(), -1, Gv.DataKey("CveVentaDetalle").ToString().ToEntero(), -1, -1, -1, -1, Gv.DataKey("CveTamaño").ToEntero()) End If Next 'AGREGAR LOS USADOS EN LA DEVOLUCION CalculaUsados(DtUsados) TrTipoRelacion.Visible = True DdlTiposRelacion.SelectedValueExist("3") LimpiaDocumentoDEV() If UsuarioActual.Empresa.Funcionalidad(567) = "1" Then DivAlmacen.Visible = True LltSalidaAlmacen.Text = "Devolución Almacen" Dim DTAlmacen As DataTable ddlAlmacen.Items.Clear() DTAlmacen = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}") ddlAlmacen.DataSource = DTAlmacen If DTAlmacen Is Nothing Or DTAlmacen.Rows.Count = 0 Then ddlAlmacen.Items.Insert(0, New ListItem(" Seleccione ", "-1")) ddlAlmacen.SelectedValue = "-1" End If ddlAlmacen.DataBind() If GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero()}").Rows.Count > 0 Then ddlAlmacen.SelectedValueExist(UsuarioActual.CveAlmacen) End If GvInv.Columns(0).Visible = True DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2") CargaGVInv(DtInv) End If CambiaTipoDocto() CargaNC(CveVenta) CalculaTotalesVenta() RegistraScript("$('#DivAplicaDevolucion').modal('hide')") End Sub Protected Sub GvAplicaDevolucion_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCTextBox("TxtCantidadAplicaDevolucion").Attributes.Add("onkeyup", $"LimitaCantidadAplicaDev({e.Row.DBCampo("CantRes").ToDecimal}, this);") If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Or UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then e.Row.FCLabel("LblProyecto").Text = e.Row.FCLabel("LblSubProyecto").Text e.Row.FCLabel("LblProyecto").Style.Clear() e.Row.FCLabel("LblSubProyecto").Text = "" 'e.Row.FCCheckBox("ChkAplicar").Attributes.Add("onclick", $"CalculaSaldoRNCChk({e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble}, this);") End If End If End Sub Private Sub LimpiaDocumentoDEV() 'REINICIALIZA PORLET CLIENTES ChkEnviarFactura.Enabled = True 'ACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto") TxtCodigo.ReadOnly = False 'REINICIALIZA PORLET DATOS DE EMIISION trNCFactura.Visible = True DdlSubProyectoDatos.Enabled = True TrFolioFiscal.Visible = False TxtFecha.Text = Now.ToShortDateString() TipoCambioFactura = TxtTipoCambio.Text.ToDecimal If DdlMoneda.SelectedValue.ToEntero() > 1 Then Dim tFecha As Date = TxtFecha.Text.ToDate Dim UltimaFluctuacion As MTipoCambioFluctuacion = GlobalTipoCambioUltimaFluctuacion(tFecha) If UsuarioActual.Empresa.Funcionalidad(703) = "1" AndAlso UltimaFluctuacion IsNot Nothing Then If UltimaFluctuacion.FechaFluctuacion > tFecha Then TipoCambioFactura = UltimaFluctuacion.TCFluctuacion End If End If 'Dim ObjIE As New ClsBancos 'If ObjIE.GetFluctuacionesBitacora(UsuarioActual.CveEmpresa) Then ' If ObjIE.DtResultados.Rows.Count > 0 Then ' Dim tFecha As Date = TxtFecha.Text.ToDate ' Dim Fecha As String = String.Format("{0}/{1}/{2}", tFecha.Year, tFecha.Month, tFecha.Day) ' Dim drr As DataRow = ObjIE.DtResultados.FiltroPrimero("Fecha > #" & Fecha & "#", "Fecha DESC") ' If drr IsNot Nothing Then ' TipoCambioFactura = drr("TipoCambio").ToString().ToDecimal ' End If ' End If 'End If 'ObjIE.Dispose() Else TipoCambioFactura = 1 End If If UsuarioActual.CveEmpresa.Contiene(13, 83) Then TxtTipoCambio.Text = GlobalTipoCambio(Now.AddDays(-1)).ToString() Else TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString() End If DivEstatusFac.Visible = False 'REINICIALIZA TABS TabAlmacen.Enabled = False TabE.Enabled = False 'REINICIALIZA GENERALES PS LbAgregar.Visible = False GvPS.Columns(17).Visible = False GvPS.Columns(18).Visible = False GvPS.Columns(19).Visible = False GvPS.Columns(20).Visible = False DivRemisionesFacturadas.Visible = False DivAnticiposVinculados.Visible = False 'REINICIALIZA TOTALES TrConversionDolares.Visible = False 'ACTIVA CONDICIONES DE PAGO DdlUsoCFDI.Enabled = True DdlUsoCFDI.SelectedValueExist("2") DdlMetodoPago33.Enabled = True DdlMetodoPago33.SelectedValueExist("1") CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) DdlFormaPago33.Enabled = True DdlFormaPago33.SelectedValueExist("11") 'REINICIALIZA OBSERVACIONES TxtObsFact.Enabled = True TxtOrdenCompra.Enabled = True TxtPedidoContrato.Enabled = True TxtObsAlmacen.Enabled = True 'DESACTIVA/ACTIVA BOTONES BtnCrearApartirDe.Visible = False BtnEmitirImprimir.Visible = True BtnVistaPrevia.Visible = True BtnEmitir.Visible = False 'REINICIALIZA ACCIONES 'LkNotaCredito.Visible = False LkEliminarFactura.Visible = False ImgDownCancelacion.Visible = False LkRefacturacion.Visible = False HLOrdenServicio.Visible = False LkCotizacionAutorizar.Visible = False LnkFacturarRemision.Visible = False LnkRemisiones.Visible = False LnkPedido2SinFacturar.Visible = False LnkCotizaciones.Visible = False LnkOCs.Visible = False LbCancelarDocumento.Visible = False LBCancelarPedido.Visible = False LiDevolucionAlmacen.Visible = False HLPagar.Visible = False HlAgregarExcel.Visible = False HplDownXML.Visible = False HplDownPDF.Visible = False HLSaldarVenta.Visible = False LBNotaCredito.Visible = False LnkAplicarRNCDevolucion.Visible = False LiComplementoPago.Visible = False HlCuentaTerminal.Visible = False LiLnkGuias.Visible = False LiDocumentoCliente.Visible = False LBAplicaDevolucion.Visible = False HplFolioFiscalModal.Visible = False 'Limpia Anticipos Seleccionados For Each row2 As GridViewRow In GVAnticipos.Rows If row2.RowType = DataControlRowType.DataRow Then row2.FCCheckBox("Chk" & row2.RowIndex).Checked = False End If Next BloqueaCondiconesPago() UpAnticipos.Update() UpParametros.Update() UpPS.Update() UpEstatus.Update() UpCliente.Update() UpRemisiones.Update() Updatetabs.Update() UpFacturar.Update() UPCondicionesPago.Update() UpnTools.Update() UPObservaciones.Update() UpAntNC.Update() End Sub #End Region #Region "COMERCIO EXTERIOR" 'Public Sub InicializaComercioExterior() ' 'CargoComercioExterior = True ' 'CargaCombos() ' CargaGvComercioExterior() 'End Sub Public Sub CargaGvComercioExterior() GvComercioExterior.DataSource = TmpDT GvComercioExterior.DataBind() UpComercioExterior.Update() End Sub 'Public Sub CargaCombos() ' 'DdlTipoOperacion.DataSource = GlobalDTTipoOperacion() ' 'DdlTipoOperacion.Items.Insert(0, New ListItem("Seleccione", "-1")) ' 'DdlTipoOperacion.DataBind() ' 'DdlIncoterm.DataSource = GlobalDTIncoterm() ' 'DdlIncoterm.Items.Insert(0, New ListItem("Seleccione", "-1")) ' 'DdlIncoterm.DataBind() ' 'DdlClavePedimento.DataSource = GlobalDTClavePedimento() ' 'DdlClavePedimento.Items.Insert(0, New ListItem("Seleccione", "-1")) ' 'DdlClavePedimento.DataBind() 'End Sub Protected Sub GvComercioExterior_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCTextBox("TxtValorUnitario").Attributes.Add("onkeyup", $"CalculaTotalUSD({e.Row.FCLabel("LblTotalUSD").ClientID}, this,{e.Row.FCTextBox("TxtCantidad").ClientID});") End If End Sub 'Protected Sub BtnCargaComercioExterior_Click(sender As Object, e As EventArgs) ' If Not CargoComercioExterior Then ' InicializaComercioExterior() ' End If 'End Sub Public Function ValidaComercioExterior() As Boolean If Not CveTipoOperacion > 0 Then Alert("Tiene que seleccionar un tipo de operación", TipoMensaje.MsgAdvertencia) Return False End If If Not CvePedimento > 0 Then Alert("Tiene que seleccionar una clave de pedimento", TipoMensaje.MsgAdvertencia) Return False End If If Not CveIncoterm > 0 Then Alert("Tiene que seleccionar un incoterm", TipoMensaje.MsgAdvertencia) Return False End If If Not GvComercioExterior.Rows.Count > 0 Then Alert("Tiene que seleccionar fraccion arancelaria,unidad aduana y valor unitario", TipoMensaje.MsgAdvertencia) End If For Each Gvr As GridViewRow In GvComercioExterior.Rows If Not Gvr.DataKey("Codigo").ToString() <> "" Then Alert("Todos los conceptos tienen que tener un codigo asignado", TipoMensaje.MsgAdvertencia) Return False End If If Not Gvr.DataKey("ClaveSATFraccionArancelaria").ToEntero() > 0 Then Alert("Todos los productos tienen que tener una fraccion arancelaria", TipoMensaje.MsgAdvertencia) Return False End If If Not Gvr.DataKey("ClaveSATUnidadAduana").ToEntero() > 0 Then Alert("Todos los productos tienen que tener una unidad aduana", TipoMensaje.MsgAdvertencia) Return False End If If Not Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal > 0 Then Alert("Todos los conceptos tienen que tener un valor unitario mayor a 0", TipoMensaje.MsgAdvertencia) Return False End If Next Return True End Function #End Region #Region "NOTIFICACIONES AVACE" Private Sub EnviarNotificacionAvance(NumeroContrato As String, DescripcionContrato As String, ContratoTipo As String, Cliente As String, CorreoVendedor As String, Optional MontoMaximo As Double = 0) Dim ObjMail As New ClsSisMail() Dim CorreoLicitacion As String = "" Dim Para As String = String.Format("{0};{1}", CorreoVendedor, CorreoLicitacion) Dim Asunto As String = "NOTIFICACION DE 100% DE AVANCE DE CONTRATO" Dim Cuerpo As String = "" If MontoMaximo > 0 Then Cuerpo = String.Format("El Contrato {0} - {1} ({2}) con cliente {4} ha alcanzado el monto máximo de {3}.", NumeroContrato, DescripcionContrato, ContratoTipo, MontoMaximo.ToString("C2"), Cliente) Else Cuerpo = String.Format("El Contrato {0} - {1} ({2}) con cliente {3} ha llegado al 100% de Avance.", NumeroContrato, DescripcionContrato, ContratoTipo, Cliente) End If ObjMail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Cuerpo) End Sub #End Region #Region "Comercio Exterior" Private Sub CargaPais() DdlComExtPais.Items.Clear() DdlComExtPais.DataSource = GlobalDTGralPaises() DdlComExtPais.DataBind() DdlComExtPais.SelectedValueExist("151") End Sub Private Sub CargaEstado() DdlComExtEstado.Items.Clear() If DdlComExtPais.SelectedValue.ToEntero() > 0 Then DdlComExtEstado.DataSource = GlobalDTGralEstados("-1", CvePais:=DdlComExtPais.SelectedValue.ToEntero) '(0)("ClaveSATPais").ToString() End If DdlComExtEstado.Visible = True DdlComExtEstado.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlComExtEstado.DataBind() End Sub Private Sub CargaMunicipio() DdlComExtMunicipio.Items.Clear() If DdlComExtEstado.SelectedValue.ToEntero() > 0 Then DdlComExtMunicipio.DataSource = GlobalDTGralMunicipios("-1", CveEstado:=DdlComExtEstado.SelectedValue.ToEntero()) End If DdlComExtMunicipio.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlComExtMunicipio.DataBind() DdlComExtMunicipio.Visible = True End Sub Private Sub CargaColonia() DdlComExtColonia.Items.Clear() If DdlComExtMunicipio.SelectedValue.ToEntero() > 0 Then DdlComExtColonia.DataSource = GlobalDTGralColonias("-1", "-1", "-1", CveMunicipio:=DdlComExtMunicipio.SelectedValue.ToEntero) End If DdlComExtColonia.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlComExtColonia.DataBind() DdlComExtColonia.Visible = True End Sub Protected Sub DdlPais_SelectedIndexChanged(sender As Object, e As EventArgs) 'si contiene MX, USA o CANADA carga ddls, si no carga txt If DdlComExtPais.SelectedValue.Contiene("151", "66", "40") Then DdlComExtEstado.Visible = True DdlComExtMunicipio.Visible = True DdlComExtColonia.Visible = True TxtComExtEstado.Visible = False TxtComExtMunicipio.Visible = False TxtComExtColonia.Visible = False CargaEstado() CargaMunicipio() CargaColonia() Else DdlComExtEstado.Visible = False DdlComExtMunicipio.Visible = False DdlComExtColonia.Visible = False TxtComExtEstado.Visible = True TxtComExtMunicipio.Visible = True TxtComExtColonia.Visible = True End If End Sub Protected Sub DdlEstado_SelectedIndexChanged(sender As Object, e As EventArgs) 'si contiene USA o CANADA carga txt If DdlComExtPais.SelectedValue.Contiene("151") Then CargaMunicipio() CargaColonia() Else If DdlComExtPais.SelectedValue.Contiene("66", "40") Then DdlComExtMunicipio.Visible = False DdlComExtColonia.Visible = False TxtComExtMunicipio.Visible = True TxtComExtColonia.Visible = True End If End If End Sub Protected Sub DdlMunicipio_SelectedIndexChanged(sender As Object, e As EventArgs) CargaColonia() End Sub Private Sub BtnComExtConvertirUnidad_Click(sender As Object, e As EventArgs) Handles BtnComExtConvertirUnidad.Click For Each gvr As GridViewRow In GvComercioExterior.Rows gvr.FCTextBox("TxtCantidad").Text = (gvr.FCTextBox("TxtCantidad").Text.ToDecimal * TxtComExtConvertir.Text.ToDecimal).ToString() gvr.FCTextBox("TxtValorUnitario").Text = (gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal / TxtComExtConvertir.Text.ToDecimal).ToString() Next End Sub #End Region Private Sub BtnFolioFiscalAsignar_Click(sender As Object, e As EventArgs) Handles BtnFolioFiscalAsignar.Click Dim ObjVentas As New ClsVentas() If ObjVentas.UpdateVentaFolioFiscal(TxtModalFolioFiscal.Text.Trim, CveVenta, UsuarioActual.CveEmpresa) Then Alert("Folio asignado", TipoMensaje.MsgInformacion) RegistraScript("$('#ModalFolioFiscal').modal('hide')") End If ObjVentas.Dispose() End Sub #Region "FORMATO CICOVISA" Protected Sub LnkImprimirFormatoCicovisa_Click(sender As Object, e As EventArgs) Dim ObjVentas As New ClsVentas Dim ObjInventario As New ClsInventarios Dim SerieFolio As String = "" Dim PedidoContrato As String = "" Dim EnvioContacto As String = "" Dim EnvioDireccion As String = "" Dim Guia As String = "" If ObjInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then If ObjInventario.DtResultados.Rows.Count > 0 Then Guia = ObjInventario.DtResultados.Rows(0)("Guia").ToString() End If End If If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then SerieFolio = ObjVentas.DtResultados.Rows(0)("SerieFolio").ToString() PedidoContrato = ObjVentas.DtResultados.Rows(0)("PedidoContrato").ToString() EnvioContacto = ObjVentas.DtResultados.Rows(0)("EnvioContacto").ToString() EnvioDireccion = $"{ObjVentas.DtResultados.Rows(0)("EnvioDireccion").ToString()}, NO. EXT: {ObjVentas.DtResultados.Rows(0)("EnvioNoExt").ToString()}, COLONIA: {ObjVentas.DtResultados.Rows(0)("EnvioColonia").ToString()}, CP: {ObjVentas.DtResultados.Rows(0)("EnvioCP").ToString()}" End If End If Dim Dt As DataTable = Nothing If ObjVentas.GetVentaDetalle(CveVenta) Then Dt = ObjVentas.DtResultados End If ObjVentas.Dispose() ObjInventario.Dispose() If Dt.Rows.Count > 0 Then Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) params.Add(New ReportParameter("EnvioContacto", EnvioContacto)) params.Add(New ReportParameter("SerieFolio", SerieFolio)) params.Add(New ReportParameter("PedidoContrato", PedidoContrato)) params.Add(New ReportParameter("EnvioDireccion", EnvioDireccion)) params.Add(New ReportParameter("Guia", Guia)) ImprimirPDF("Empresas/Grales/Formatos/Cicovisa.rdlc", Dt, params, String.Format("Formato Cicovisa -{0}", Now.ToDateTime.ToShortDateString)) End If End Sub Protected Sub LnkImprimirFormatoTelcel_Click(sender As Object, e As EventArgs) Dim ObjVentas As New ClsVentas Dim ObjInventario As New ClsInventarios Dim SerieFolio As String = "" Dim PedidoContrato As String = "" Dim EnvioContacto As String = "" Dim EnvioDireccion As String = "" Dim EnviarOficina As String = "" Dim EnviarCalle As String = "" Dim EnviarColonia As String = "" Dim EnvioCiudad As String = "" Dim EnvioTel As String = "" Dim Guia As String = "" Dim EnvioNoExt As String = "" Dim EnvioNoInt As String = "" Dim EnvioEstado As String = "" Dim Pais As String = "" Dim CP As String = "" If ObjInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then If ObjInventario.DtResultados.Rows.Count > 0 Then Guia = ObjInventario.DtResultados.Rows(0)("Guia").ToString() End If End If If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then SerieFolio = ObjVentas.DtResultados.Rows(0)("SerieFolio").ToString() PedidoContrato = ObjVentas.DtResultados.Rows(0)("PedidoContrato").ToString() If ObjVentas.DtResultados.Rows(0)("CveDireccionEnvio").ToString().ToEntero() > 0 Then EnvioContacto = ObjVentas.DtResultados.Rows(0)("EnvioContacto").ToString() EnvioDireccion = $"{ObjVentas.DtResultados.Rows(0)("EnvioDireccion").ToString()}, COLONIA: {ObjVentas.DtResultados.Rows(0)("EnvioColonia").ToString()}, CP: {ObjVentas.DtResultados.Rows(0)("EnvioCP").ToString()}" EnviarOficina = ObjVentas.DtResultados.Rows(0)("EnvioDepartamento").ToString() EnviarCalle = ObjVentas.DtResultados.Rows(0)("EnvioDireccion").ToString() EnviarColonia = ObjVentas.DtResultados.Rows(0)("EnvioColonia").ToString() EnvioCiudad = ObjVentas.DtResultados.Rows(0)("EnvioCiudad").ToString() EnvioTel = ObjVentas.DtResultados.Rows(0)("EnvioTel").ToString() EnvioNoExt = ObjVentas.DtResultados.Rows(0)("EnvioNoExt").ToString() EnvioNoInt = ObjVentas.DtResultados.Rows(0)("EnvioNoInt").ToString() EnvioEstado = ObjVentas.DtResultados.Rows(0)("EnvioEstado").ToString() Pais = ObjVentas.DtResultados.Rows(0)("SucClientePais").ToString() CP = ObjVentas.DtResultados.Rows(0)("EnvioCP").ToString() 'CP = "Envio" Else If ObjVentas.DtResultados.Rows(0)("CveClienteSucursal").ToString().ToEntero() > 0 Then 'EnvioContacto = ObjVentas.DtResultados.Rows(0)("EnvioContacto").ToString() EnvioDireccion = $"{ObjVentas.DtResultados.Rows(0)("SucClienteDireccion").ToString()}, COLONIA: {ObjVentas.DtResultados.Rows(0)("SucClienteColonia").ToString()}, CP: {ObjVentas.DtResultados.Rows(0)("SucClienteCP").ToString()}" 'EnviarOficina = ObjVentas.DtResultados.Rows(0)("EnvioDepartamento").ToString() EnviarCalle = ObjVentas.DtResultados.Rows(0)("SucClienteDireccion").ToString() EnviarColonia = ObjVentas.DtResultados.Rows(0)("SucClienteColonia").ToString() EnvioCiudad = ObjVentas.DtResultados.Rows(0)("SucClienteCiudad").ToString() EnvioTel = ObjVentas.DtResultados.Rows(0)("EnvioTel").ToString() EnvioNoExt = ObjVentas.DtResultados.Rows(0)("SucClienteNoExt").ToString() EnvioNoInt = ObjVentas.DtResultados.Rows(0)("SucClienteNoInt").ToString() EnvioEstado = ObjVentas.DtResultados.Rows(0)("SucClienteEstado").ToString() Pais = ObjVentas.DtResultados.Rows(0)("SucClientePais").ToString() 'CP = ObjVentas.DtResultados.Rows(0)("SucClienteCP").ToString() CP = "Sucursal" Else 'EnvioContacto = ObjVentas.DtResultados.Rows(0)("EnvioContacto").ToString() EnvioDireccion = $"{ObjVentas.DtResultados.Rows(0)("ClienteDireccion").ToString()}, COLONIA: {ObjVentas.DtResultados.Rows(0)("ColoniaCliente").ToString()}, CP: {ObjVentas.DtResultados.Rows(0)("CPCliente").ToString()}" 'EnviarOficina = ObjVentas.DtResultados.Rows(0)("EnvioDepartamento").ToString() EnviarCalle = ObjVentas.DtResultados.Rows(0)("ClienteDireccion").ToString() EnviarColonia = ObjVentas.DtResultados.Rows(0)("ColoniaCliente").ToString() EnvioCiudad = ObjVentas.DtResultados.Rows(0)("ClienteCiudad").ToString() EnvioTel = ObjVentas.DtResultados.Rows(0)("EnvioTel").ToString() EnvioNoExt = ObjVentas.DtResultados.Rows(0)("ClienteNoExt").ToString() EnvioNoInt = ObjVentas.DtResultados.Rows(0)("ClienteNoInt").ToString() EnvioEstado = ObjVentas.DtResultados.Rows(0)("ClienteEstado").ToString() Pais = ObjVentas.DtResultados.Rows(0)("ClientePais").ToString() 'CP = ObjVentas.DtResultados.Rows(0)("CPCliente").ToString() CP = "Cliente" End If EnvioContacto = "" EnviarOficina = "" End If End If End If Dim Dt As DataTable = Nothing If ObjVentas.GetVentaDetalle(CveVenta) Then Dt = ObjVentas.DtResultados End If ObjVentas.Dispose() ObjInventario.Dispose() If Dt.Rows.Count > 0 Then Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) params.Add(New ReportParameter("EnvioContacto", EnvioContacto)) params.Add(New ReportParameter("SerieFolio", SerieFolio)) params.Add(New ReportParameter("PedidoContrato", PedidoContrato)) params.Add(New ReportParameter("EnvioDireccion", EnvioDireccion)) params.Add(New ReportParameter("Guia", Guia)) params.Add(New ReportParameter("EnviarOficina", EnviarOficina)) params.Add(New ReportParameter("EnviarCalle", EnviarCalle)) params.Add(New ReportParameter("EnviarColonia", EnviarColonia)) params.Add(New ReportParameter("EnvioCiudad", EnvioCiudad)) params.Add(New ReportParameter("EnvioTel", EnvioTel)) params.Add(New ReportParameter("NoExt", EnvioNoExt)) params.Add(New ReportParameter("NoInt", EnvioNoInt)) params.Add(New ReportParameter("EnvioEstado", EnvioEstado)) params.Add(New ReportParameter("Pais", Pais)) params.Add(New ReportParameter("CP", CP)) ImprimirPDF("Empresas/Grales/Formatos/Telcel.rdlc", Dt, params, String.Format("Formato RADIO MOVIL DIPSA S.A DE C.V. -{0}", Now.ToDateTime.ToShortDateString), "PDF") End If End Sub #End Region #Region "REQUIERE OC" Protected Sub btnBuscarOCRegistrada_Click(sender As Object, e As EventArgs) Dim ObjVentas As New ClsVentas If CveCliente > 0 AndAlso TxtOrdenCompra.Text.Trim <> "" AndAlso CveVenta <= 0 Then If ObjVentas.GetOCVentas(CveCliente, TxtOrdenCompra.Text) Then If ObjVentas.DtResultados.Rows.Count > 0 Then Alert("Ya existen ventas con el mismo folio de orden de compra registrado", TipoMensaje.MsgAdvertencia) End If End If End If ObjVentas.Dispose() End Sub #End Region #Region "CLASIFICACIONES DETALLES" Protected Sub DdlClasificacionPS_SelectedIndexChanged(sender As Object, e As EventArgs) CargaClasificacionesDetalles() End Sub Protected Sub BtnAddClasificacionDetalle_Click(sender As Object, e As EventArgs) TxtClasificacionDetalle.Text = "" DdlClasificacionModal.SelectedValueExist(DdlClasificacionPS.SelectedValue) UpModal.Update() RegistraScript(String.Format("$('#{0}').modal('show');", "DModalClasificacion")) End Sub Protected Sub BtnAddClasificacionDetalleModal_Click(sender As Object, e As EventArgs) Dim ObjVentas As New ClsVentas If ObjVentas.AddClasificacionDetalle(TxtClasificacionDetalle.Text, DdlClasificacionModal.SelectedValue.ToEntero(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then CargaClasificacionesDetalles() DdlTipo.SelectedValueExist(ObjVentas.CveClasificacionDetalle) UpAddPS.Update() RegistraScript(String.Format("$('#{0}').modal('hide');", "DModalClasificacion"), "1") RegistraScript("CreaDescripcionPS();", "2") End If ObjVentas.Dispose() End Sub Private Sub GVAnticipos_PageIndexChanged(sender As Object, e As EventArgs) Handles GVAnticipos.PageIndexChanged End Sub Private Sub DdlTipoAmortizacionAnticipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoAmortizacionAnticipo.SelectedIndexChanged ImporteSujeridoAnticipo(DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero) divAnticipoMsg.Visible = False If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("1", "2") Then 'cuando es amortización por descuento, debe tener seleccionado descuentos previamente registrados If DdlTipoAmortizacionAnticipo.SelectedValue = "1" AndAlso LblDescuentos.Text.ToDecimal <= 0 Then divAnticipoMsg.Visible = True End If If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then 'debo de cambiar la columna que se tomaria como total, por si tiene impuestos, la NC estaria abarcandolos DivConceptoNC.Visible = True Else DivConceptoNC.Visible = False End If CargaAnticipos(CveCliente) DdlTipoRelacionAnticipo.SelectedValueExist("7") Else DivConceptoNC.Visible = False DdlTipoRelacionAnticipo.SelectedValueExist("-1") End If End Sub Private Sub ImporteSujeridoAnticipo(TipoAmortizacion As Integer) 'TipoAmortizacion '1.-Anticpo como descuento se basa en subtotal '2.-Anticipo con notade credito se basa en total AmortizacionSujeridaContrato = 0 Dim Porcentaje As Decimal = PorAmortizacionAnticipo * 0.01D If PorAmortizacionAnticipo > 0 AndAlso TipoAmortizacion > 0 Then If TipoAmortizacion = 1 Then AmortizacionSujeridaContrato = (TxtSubTotal2.Text.ToDecimal * Porcentaje).RoundSQL(2) ElseIf TipoAmortizacion = 2 Then AmortizacionSujeridaContrato = (TxtTotal.Text.ToDecimal * Porcentaje).RoundSQL(2) End If Else AmortizacionSujeridaContrato = 0 End If End Sub Private Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMetodoPago33.SelectedIndexChanged CambiaMetodoPago33() End Sub Private Sub CambiaMetodoPago33() CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) End Sub #End Region #Region " COTIZACIONES - EDITAR " Private Sub BtnPermisoEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarCotizacion.Click ModalidadEdicion = True 'ACTIVA BOTONES PARA EDITAR For Each Row As GridViewRow In GvPS.Rows Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString() Next GvPS.Columns(ColumnaEditar).HeaderText = "Editar" GvPS.Columns(ColumnaEliminar).HeaderText = "Eliminar" GvPS.DataSource = TmpDT GvPS.DataBind() 'PORLET CLIENTE 'ACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto") TxtCodigo.ReadOnly = False ChkEnviarFactura.Enabled = True DdlSucursalCliente.Enabled = True ChkDireccionEnvio.Enabled = True DdlDireccionEnvio.Enabled = True TxtAtencionA.Enabled = True TxtFechaVencimientoCotizacion.Enabled = True 'BOTONERA BtnGenerarRemision.Visible = False BtnCrearApartirDe.Visible = False BtnEmitirImprimir.Visible = False BtnGenerarOS.Visible = False TxtCantidad.Enabled = True DdlClasificacion.Enabled = True DdlPS.Enabled = True TxtObsPS.Enabled = True DdlProyecto.Enabled = True DdlSubProyecto.Enabled = True TxtPrecio.Enabled = True LbAgregar.Enabled = True LnkAgregarPyME.Enabled = True ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") LblSubTotal1.Text = TxtSubTotal.Text LblAmort.Text = TxtSubTotal.Text TxtTiempoEntrega.Enabled = True DdlVendedor.Enabled = True TxtObsFact.Enabled = True TxtMotivoDescuento.Enabled = True BtnEditarCotizacion.Visible = True BtnPermisoEditarCotizacion.Visible = False DdlFormaPago33.Enabled = True DdlUsoCFDI.Enabled = True DdlMetodoPago33.Enabled = True 'TxtNumCtaPago.Enabled = True DdlMoneda.Enabled = True TxtPedidoContrato.Enabled = True TxtOrdenCompra.Enabled = True If DdlMoneda.SelectedValue = "2" Then TrConversionTipoCambio.Visible = True End If ChkConvertirDoctoPesos.Enabled = Not UsuarioActual.TienePermisoProceso(324) TxtTipoCambio.Enabled = True TxtTotal.ReadOnly = False TxtTotal.Attributes("readonly") = "readonly" RBLPago.Enabled = True If Me.PermiteCredito Then RBLPago.Items(0).Enabled = True End If GvImpuestosLocales2.Enabled = True If DdlTipoComprobante.SelectedValue = "Cot" Then DdlIVA.Visible = True End If BloqueaCondiconesPago() CargaVendedores() If UsuarioActual.Empresa.Funcionalidad(572) = "1" AndAlso Not TbDescuentosRNC.Visible Then TbDescuentosRNC.Visible = True LnkDescuentosRNC.Visible = UsuarioActual.TienePermisoProceso(328) End If UpPS.Update() UPPDescuento.Update() UPObservaciones.Update() UPCondicionesPago.Update() UpCliente.Update() End Sub Private Sub BtnEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnEditarCotizacion.Click Dim VaFacturarCotizacion As Boolean = False 'SI CARGA UNA COTIZACION DEBE GUARDAR TAMBIEN If IfNull(ViewState("CveCotizacion"), 0).ToString().ToEntero() > 0 Then ViewState("CveVenta") = IfNull(ViewState("CveCotizacion"), 0).ToString().ToEntero() VaFacturarCotizacion = True End If If Not TmpDT.Rows.Count > 0 Then Alert("Es necesario agregar al menos un producto o servicio a la factura.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero() Dim TipoCambio As Double = TxtTipoCambio.Text.Trim.ToDecimal If DdlMoneda.SelectedValue.ToEntero() <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then TipoCambio = 1 Moneda = 1 End If Dim ObjVentas As New ClsVentas Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) Dim OcurrioError = False Dim MensajeError = "" Try 'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS If DdlMoneda.SelectedValue.ToEntero() <> 2 AndAlso ChkConvertirDolares.Checked Then For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString().ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales) End If Next TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal Moneda = 2 End If 'CONVERTIR REMISION - TIPO MONEDA -PESO A DOLARES If DdlMoneda.SelectedValue.ToEntero() <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then Dim Importe As Decimal Dim TCC As Decimal = TxtTipoCambio.Text.Trim.ToDecimal For Each Row As DataRow In TmpDT.Rows Row("PU") = Math.Round(Row("PU").ToString().ToDecimal * TCC, 6) Row("Total") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("TotalImporte") = Math.Round(Row("Cantidad").ToString().ToDecimal * Row("PU").ToString().ToDecimal, NumeroDecimales) Row("Descuento") = Math.Round(Row("Descuento").ToString().ToDecimal * TCC, NumeroDecimales) Importe = Row("Total").ToString().ToDecimal - Row("Descuento").ToString().ToDecimal Row("ImporteIEPS") = Math.Round(Importe * Row("PorcentajeIEPS").ToString().ToDecimal, NumeroDecimales) Row("ImporteIVA") = Math.Round(Importe * Row("PorcentajeIVA").ToString().ToDecimal, NumeroDecimales) Row("ImporteRetIVA") = Math.Round(Importe * Row("PorcentajeRetIVA").ToString().ToDecimal, NumeroDecimales) Row("ImporteRetISR") = Math.Round(Importe * Row("PorcentajeRetISR").ToString().ToDecimal, NumeroDecimales) Next Dim ImpuestosLocales As Double = 0 For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal).FormatoNumero ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales) End If Next TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero TipoCambio = 1 Moneda = 1 End If 'ACTUALIZA VENTA If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDouble(), LblDescuentos.Text.ToDouble(), TxtIVA.Text.ToDouble(), TxtIEPS.Text.ToDouble(), TxtTotal.Text.ToDouble(), Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, UsuarioActual.CveEmpresa, CveVenta, 0, 0, Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1), PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero(), CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero(), CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal, TipoDocto:=DdlTipoComprobante.SelectedValue, Kilometraje:=TxtKilometraje.Text.ToDouble, CveUsoCFDi:=DdlUsoCFDI.SelectedValue.ToEntero()) Then MensajeError = "Ocurrió un error al actualizar la información de la cotización" OcurrioError = True End If 'ELIMINA DETALLES If Not ObjVentas.RemoveVentasDetalle(CveVenta) Then MensajeError = "Ocurrió un error al actualizar las partidas de la cotización" OcurrioError = True End If 'RE-INSERTA DETALLES For Each Row As DataRow In TmpDT.Rows If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString().ToEntero(), Row("Cantidad").ToString().ToDouble, Row("CveUM").ToString().ToEntero(), Row("PU").ToString().ToDouble(), Row("ImporteIVA").ToString().ToDouble, Math.Round((Row("Total").ToString().ToDouble() * (1 + Row("PorcentajeIVA").ToString().ToDouble())), 6), Row("Obs").ToString(), Row("Descuento").ToString().ToDouble(), Row("TipoDescuento").ToString().ToEntero(), Row("CveSubProyecto").ToString().ToEntero(), Row("CvePresupuestoIngreso").ToString().ToEntero(), PorcentajeIVA:=Row("PorcentajeIVA").ToString().ToDecimal, IEPS:=Row("ImporteIEPS").ToString().ToDouble(), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString().ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString(), PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString().ToDecimal, ImporteRetIVA:=Row("ImporteRetIVA").ToString().ToDecimal) Then MensajeError = "Ocurrió un error al guardar las partidas de la cotización" OcurrioError = True Exit For End If Next For Each gvr As GridViewRow In GvImpuestosLocales2.Rows If gvr.RowType = DataControlRowType.DataRow Then If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString().ToEntero(), gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble) Then MensajeError = "Ocurrió un error al actualizar los impuestos locales" OcurrioError = True End If End If Next 'ORDEN PRODUCCION If UsuarioActual.CveEmpresa.Contiene(126) Then If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero() > 0 Then If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then MensajeError = "Ocurrió un error al actualizar la orden de producción" OcurrioError = True End If End If End If 'If ObjConta.ValidacionPrePolizaCuadre(-1, 2, CveVenta) Then ' If ObjConta.ValorPolizaDescuadre > 0 Then ' If ObjConta.ValorPolizaDescuadre = 2 Then ' OcurrioError = True ' MensajeError = ObjConta.MensajePolizaDescuadre ' End If ' End If 'End If Catch ex As Exception OcurrioError = True OnError("Ocurrió un error al guardar la cotización", ex) End Try If OcurrioError Then ObjVentas.RollBack() Alert($"{MensajeError}. Por favor vuelva a intentar.", TipoMensaje.MsgError) Else ObjVentas.Commit() 'ELIMINA PDF VIEJO Dim ArchivoPDF = New System.IO.FileInfo(String.Format("{0}PDF\{1}\{2}-{3}.pdf", UsuarioActual.Empresa.Ruta, DdlTipoComprobante.SelectedValue, Serie, Folio)) If ArchivoPDF.Exists Then ArchivoPDF.Delete() End If 'GENERA PDF NUEVO GeneraPDFCotizacion(ChkEnviarFactura.Checked) If VaFacturarCotizacion Then Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveCotizacion=" & CveVenta & """;") Else Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta & "&&Tipo=Cot"";") End If End If ObjVentas.Dispose() ObjConta.Dispose() ObjCGame.Dispose() End Sub #End Region #Region " COTIZACIONES - SIN FACTURAR " Private Sub LnkCotizaciones_Click(sender As Object, e As EventArgs) Handles LnkCotizaciones.Click If ChkCotProductos.Checked Then CargaCotizacionesxProducto() Else CargaCotizaciones() End If RegistraScript("$('#DivCotizaciones').modal('show');") End Sub Private Sub BtnConsultarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnConsultarCotizaciones.Click If ChkCotProductos.Checked Then CargaCotizacionesxProducto() Else CargaCotizaciones() End If End Sub Private Sub ChkCotProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkCotProductos.CheckedChanged If ChkCotProductos.Checked Then GvCotPS.Visible = True GvCot.Visible = False DivFiltroCotPS.Visible = True DivFiltroCot.Visible = False GvCot.DataSource = Nothing GvCot.DataBind() CargaCotizacionesxProducto() Else GvCotPS.Visible = False GvCot.Visible = True DivFiltroCotPS.Visible = False DivFiltroCot.Visible = True GvCotPS.DataSource = Nothing GvCotPS.DataBind() CargaCotizaciones() End If End Sub Private Sub CargaCotizaciones() Dim ObjVentas As New ClsVentas If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 1) Then DtCotizaciones = ObjVentas.DtResultados If Not DtCotizaciones.Columns.Contains("Aplicado") Then DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) End If GvCot.DataSource = DtCotizaciones End If ObjVentas.Dispose() GvCot.DataBind() UpCotizacionesFacturas.Update() End Sub Private Sub CargaCotizacionesxProducto() Dim ObjVentas As New ClsVentas If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 2) Then DtCotizaciones = ObjVentas.DtResultados If Not DtCotizaciones.Columns.Contains("Aplicado") Then DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) End If If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then GvCotPS.DataSource = DtCotizaciones.FiltraParametros("Cantidad > 0 AND EsAcumulador = False") Else GvCotPS.DataSource = DtCotizaciones.FiltraParametros("Cantidad > 0") End If End If ObjVentas.Dispose() GvCotPS.DataBind() UpCotizacionesFacturas.Update() End Sub Protected Sub BtnGuardarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnGuardarCotizaciones.Click If GvCot.Rows.Count = 0 And GvCotPS.Rows.Count = 0 Then Alert("Debe existir por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'MARCA LAS SELECCIONADAS VerificaCotizaciones(DtCotizaciones) CargarCotizacionesAFacturar() RegistraScript("$('#DivCotizaciones').modal('hide');") End Sub Private Sub CargarCotizacionesAFacturar() Dim DTSeleccionadas = DtCotizaciones.FiltraParametros("Aplicado = True") If DTSeleccionadas.Rows.Count = 0 Then Alert("Debe seleccionar por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then Alert("Solo debe seleccionar cotizaciones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") DdlMoneda.Enabled = False CambiaMoneda() 'LIMPIA LAS PARTIDAS ACTUALES If GvPS.Rows.Count > 0 Then TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtIEPS.Text = "0.00" TxtRetISR.Text = "0.00" TxtRetIVA.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = "0.00" End If Dim Cves As New StringBuilder Dim CveMetodoPago As Integer = -1 Dim MetodoPagoDif As Boolean = False Dim ListaVentaDetalleCotizacion As List(Of MVentaDetalleCotizacion) = Nothing If ChkCotProductos.Checked Then For Each row As DataRow In DTSeleccionadas.Rows If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString().ToEntero() <> CveMetodoPago Then MetodoPagoDif = True End If CveMetodoPago = row("CveMetodoPago33").ToString().ToEntero() Cves.Append($"{row("CveVentaDetalle").ToString()},") Next For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows CotizacionesLista.Add(row("CveVenta").ToString().ToEntero()) Next 'CARGA LOS USADOS RELACIONADOS A LOS PRODUCTOS SELECCIONADOS DE LA COTIZACION If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then ListaVentaDetalleCotizacion = CalculaUsadosCotizacion(Cves, DTSeleccionadas, DtCotizaciones) End If Else For Each row As DataRow In DTSeleccionadas.Rows If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString().ToEntero() <> CveMetodoPago Then MetodoPagoDif = True End If Cves.Append($"{row("CveVenta").ToString()},") CotizacionesLista.Add(row("CveVenta").ToString().ToEntero()) CveMetodoPago = row("CveMetodoPago33").ToString().ToEntero() Next End If If MetodoPagoDif Then Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia) End If Cves.Remove(Cves.Length - 1, 1) Dim ObjClientes As New ClsClientes If ObjClientes.GetVentasCotizacionesTotales(CveCliente, Cves.ToString(), If(ChkCotProductos.Checked, 2, 1)) Then DtCotizacionesPS = ObjClientes.DtResultados End If ObjClientes.Dispose() Cves.Clear() 'SI SE CALCULARON USADOS LA CANTIDAD DEBE ASIGNARSE A PARTIR DEL CALCULO If ListaVentaDetalleCotizacion IsNot Nothing AndAlso ListaVentaDetalleCotizacion.Count > 0 Then For Each Dr As DataRow In DtCotizacionesPS.Rows Dim VentaDetalle = ListaVentaDetalleCotizacion.FirstOrDefault(Function(cot) cot.CveVentaDetalle = Dr("CveVentaDetalle").ToString().ToEntero()) If VentaDetalle IsNot Nothing Then Dr("Cantidad") = VentaDetalle.Cantidad End If Next End If If Not AgregaPSCotizacion() Then Alert("Ocurrió un error validar las partidas de las cotizaciones seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'BtnEmitirImprimir.Text = "Facturar" Dim CveTipoDocto = DdlTipoComprobante.SelectedValue DdlTipoComprobante.Items.Clear() DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem")) DdlTipoComprobante.SelectedIndex = 0 DdlTipoComprobante.SelectedValueExist(CveTipoDocto) CambiaTipoComprobante() 'DdlTipoComprobante.Enabled = False UpRemisionesFacturas.Update() UpFacturar.Update() UpPS.Update() UpParametros.Update() End Sub 'Private Function AjustarTotalCotizacionFacturada(CveCotizacion As Integer, TotalAjustar As Decimal) As Boolean ' Dim ErrorAjuste As Boolean = False ' Dim ObjCotizacion As New Modelos.Factura(UsuarioActual, CveCotizacion, UsuarioActual.CveEmpresa) ' If ObjCotizacion.CveMoneda = 1 Then ' Dim TotalNuevoDocumento As Decimal = TotalAjustar ' Dim Diferencia As Decimal = (ObjCotizacion.Total - TotalNuevoDocumento) ' If Diferencia <> 0 Then ' 'AJUSTAR EN EL IVA ' For Each RowNuevoDocumento As DataRow In TmpDT.Rows ' Dim CveVentaDetalleCotizacion As Integer = RowNuevoDocumento("CveVentaDetalleCotizacion").ToString().ToEntero() ' Dim ImporteIVANuevoDocumento As Decimal = RowNuevoDocumento("ImporteIVA").ToString().ToDecimal() ' Dim ImporteIEPSNuevoDocumento As Decimal = RowNuevoDocumento("ImporteIEPS").ToString().ToDecimal() ' If CveVentaDetalleCotizacion > 0 Then ' 'AJUSTAR IVA ' If ImporteIVANuevoDocumento > 0 Then ' Dim ImporteIVACotizacion As Decimal = ObjCotizacion.DtDetalle.FiltroPrimeroValor("ImporteIVA", $"CveVentaDetalle={CveVentaDetalleCotizacion}").ToDecimal ' If ImporteIVANuevoDocumento <> ImporteIVACotizacion Then ' RowNuevoDocumento("ImporteIVA") = ImporteIVACotizacion ' End If ' End If ' 'AJUSTAR IEPS ' If ImporteIEPSNuevoDocumento > 0 Then ' Dim ImporteIEPSCotizacion As Decimal = ObjCotizacion.DtDetalle.FiltroPrimeroValor("ImporteIEPS", $"CveVentaDetalle={CveVentaDetalleCotizacion}").ToDecimal ' If ImporteIEPSNuevoDocumento <> ImporteIEPSCotizacion Then ' RowNuevoDocumento("ImporteIEPS") = ImporteIEPSCotizacion ' End If ' End If ' End If ' Next ' End If ' CalculaTotalesVenta(RecalculaImpuestosLocales:=False) ' If Math.Abs(ObjCotizacion.Total - TotalAjustar) > 0 OrElse Math.Abs(TxtTotal.Text.ToDecimal - TotalAjustar) > 0 Then ' ErrorAjuste = True ' End If ' End If ' ObjCotizacion.Dispose() ' Return Not ErrorAjuste 'End Function Private Class MVentaDetalleCotizacion Public Property CveVentaDetalle As Integer Public Property Cantidad As Decimal End Class Private Function CalculaUsadosCotizacion(ByRef SbVentasDetalle As StringBuilder, ByVal DTSeleccionadas As DataTable, ByVal DtCotizaciones As DataTable) As List(Of MVentaDetalleCotizacion) Dim Retorno As New List(Of MVentaDetalleCotizacion) Dim DTTamanios As DataTable = GlobalDTAcumTamaños() Dim DTCvePSCostos As DataTable = DTTamanios.FiltraParametros("", "", {"CvePSCargo"}) For Each Dr As DataRow In DTSeleccionadas.Rows Dim tCantidad = If(ChkCotProductos.Checked, GvCotPS.Rows(IndiceGVCotDataKey(GvCotPS, Dr("CveVentaDetalle").ToString())).FCTextBox("TxtCantidadCot").Text.ToDecimal, Dr("Cantidad")).ToString().ToDecimal Dr("Cantidad") = tCantidad Retorno.Add(New MVentaDetalleCotizacion() With {.CveVentaDetalle = Dr("CveVentaDetalle").ToString().ToEntero(), .Cantidad = tCantidad}) Next Dim TmpDTCalculo As DataRow() = DTSeleccionadas.Rows.Cast(Of DataRow).ToArray() Dim DTPSTemp As New DataTable '= TmpDT.Clone DTPSTemp.Columns.Add("CveVenta", GetType(Integer)) DTPSTemp.Columns.Add("Cantidad", GetType(Integer)) DTPSTemp.Columns.Add("CvePS", GetType(Integer)) DTPSTemp.Columns.Add("PU", GetType(Decimal)) For Each DrowPartidas As DataRow In TmpDTCalculo Dim CveTamanioTemp As Integer = DrowPartidas("CveTamaño").ToString().ToEntero() Dim CveVenta As Integer = DrowPartidas("CveVenta").ToString().ToEntero() If CveTamanioTemp > 0 Then Dim DTTamanioTemp As New DataTable Dim CvePsTemp As Integer = DTTamanios.FiltraParametros($"CveTamaño = { CveTamanioTemp } ").Rows(0)("CvePSCargo").ToString().ToEntero() Dim Cargo As Decimal = DTTamanios.FiltroPrimeroValor("Cargo", $" CveTamaño = { CveTamanioTemp }").ToDecimal If DTPSTemp.FiltraParametros($"CvePs = { CvePsTemp }").Rows.Count > 0 Then For Each dRowUpdate As DataRow In DTPSTemp.Rows If (dRowUpdate("CvePS").ToString().ToEntero() = CvePsTemp) Then dRowUpdate("Cantidad") = dRowUpdate("Cantidad").ToString().ToDecimal + DrowPartidas("Cantidad").ToString().ToDecimal dRowUpdate("PU") = Cargo ' dRowUpdate("Total").ToString().ToDecimal + ImporteCargo dRowUpdate("CveVenta") = CveVenta End If Next DTPSTemp.AcceptChanges() Else Dim dRowNuevo As DataRow = DTPSTemp.NewRow dRowNuevo("CvePS") = CvePsTemp dRowNuevo("Cantidad") = DrowPartidas("Cantidad").ToString().ToDecimal dRowNuevo("PU") = Cargo dRowNuevo("CveVenta") = CveVenta DTPSTemp.Rows.Add(dRowNuevo) DTPSTemp.AcceptChanges() End If End If Next For Each drowPsTamaños As DataRow In DTPSTemp.Rows If drowPsTamaños("PU").ToString().ToDecimal > 0 Then Dim CveVentaDetalleUsado = DtCotizaciones.FiltroPrimeroValor("CveVentaDetalle", $"CveVenta = {drowPsTamaños("CveVenta")} AND CvePS = {drowPsTamaños("CvePS")}").ToEntero() SbVentasDetalle.AppendFormat("{0},", CveVentaDetalleUsado) Retorno.Add(New MVentaDetalleCotizacion() With {.CveVentaDetalle = CveVentaDetalleUsado, .Cantidad = drowPsTamaños("Cantidad").ToString().ToDecimal()}) End If Next Return Retorno End Function Private Sub VerificaCotizaciones(ByRef dt As DataTable) If ChkCotProductos.Checked Then For Each Gvr As GridViewRow In GvCotPS.Rows If Gvr.RowType = DataControlRowType.DataRow Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero() Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If Next Else For Each Gvr As GridViewRow In GvCot.Rows If Gvr.RowType = DataControlRowType.DataRow Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero() Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If Next End If End Sub Private Function IndiceGVCotDataKey(GridView As GridView, DataKeyValue As String) As Integer For Each row As GridViewRow In GridView.Rows If row.DataKey("CveVentaDetalle") = DataKeyValue Then Return row.RowIndex End If Next Return Nothing End Function Private Function AgregaPSCotizacion(Optional RecalculaImpustosLocales As Boolean = True) As Boolean 'Dim ObjFactCotizacion As New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa) 'Dim TotalCotizacion As Decimal = ObjFactCotizacion.Total 'TmpDT.SUM("TotalImporte").ToDecimal() + TmpDT.SUM("ImporteIVA").ToDecimal() + TmpDT.SUM("ImporteIEPS").ToDecimal() - TmpDT.SUM("ImporteRetIVA").ToDecimal() - TmpDT.SUM("ImporteRetISR").ToDecimal() 'ObjFactCotizacion.Dispose() If DtCotizacionesPS IsNot Nothing Then Dim tCantidad As Decimal = 0 For Each Dr As DataRow In DtCotizacionesPS.Select() If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then tCantidad = Dr("Cantidad").ToString().ToDecimal() Else tCantidad = If(ChkCotProductos.Checked, GvCotPS.Rows(IndiceGVCotDataKey(GvCotPS, Dr("CveVentaDetalle").ToString())).FCTextBox("TxtCantidadCot").Text.ToDecimal, Dr("Cantidad")).ToString().ToDecimal End If 'AgregarProductoServicioCotizacion(tCantidad, Dr("CveUM").ToString().ToEntero(), Dr("UM").ToString(), Dr("CveClasificacion").ToString().ToEntero(), Dr("Clasificacion").ToString(), ' Dr("CvePS").ToString().ToEntero(), Dr("PS").ToString(), Dr("Obs").ToString(), Dr("PU").ToString().ToDecimal, Dr("Descuento").ToString().ToDecimal, ' Dr("PorcentajeIVA").ToString().ToDecimal, Dr("IVA").ToString().ToDecimal, ' Dr("CveProyecto").ToString().ToEntero(), Dr("Proyecto").ToString(), Dr("CveSubProyecto").ToString().ToEntero(), Dr("SubProyecto").ToString(), ' CveContratoDetalle:=Dr("CveContratoDetalle").ToString().ToEntero(), CveVentaDetalleCotizacion:=Dr("CveVentaDetalle").ToString().ToEntero(), SeActualiza:=True) AgregarProductoServicio(tCantidad, Dr("CveUM").ToString().ToEntero(), Dr("UM").ToString(), Dr("CveClasificacion").ToString().ToEntero(), Dr("Clasificacion").ToString(), Dr("CvePS").ToString().ToEntero(), Dr("PS").ToString(), Dr("Obs").ToString(), Dr("PU").ToString().ToDecimal, Dr("Descuento").ToString().ToDecimal, Dr("CveProyecto").ToString().ToEntero(), Dr("Proyecto").ToString(), Dr("CveSubProyecto").ToString().ToEntero(), Dr("SubProyecto").ToString(), CveContratoDetalle:=Dr("CveContratoDetalle").ToString().ToEntero(), CveVentaDetalleCotizacion:=Dr("CveVentaDetalle").ToString().ToEntero(), SeActualiza:=True) Next 'Dim TotalFactura = TmpDT.SUM("TotalImporte").ToDecimal() + TmpDT.SUM("ImporteIVA").ToDecimal() + TmpDT.SUM("ImporteIEPS").ToDecimal() - TmpDT.SUM("ImporteRetIVA").ToDecimal() - TmpDT.SUM("ImporteRetISR").ToDecimal() 'Dim Diferencia As Decimal = TotalCotizacion - TotalFactura 'If Diferencia <> 0 Then ' Dim LastRow As DataRow = TmpDT.Rows(TmpDT.Rows.Count - 1) ' LastRow("ImporteIVA") = LastRow("ImporteIVA").ToString().ToDecimal() - Diferencia 'End If CalculaTotalesVenta(RecalculaImpuestosLocales:=RecalculaImpustosLocales) Return True Else Return False End If End Function #End Region #Region " COTIZACIONES - FACTURAR " Private Function PreparaFacturarCotizacion() As Boolean 'LIMPIAMOS 'Dim TotalCotizacion As Decimal = TxtTotal.Text.Replace(",", "").ToDecimal() TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtIEPS.Text = "0.00" TxtRetIVA.Text = "0.00" TxtRetISR.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = TxtIVA.Text CreaDTVentas() If CveEmpresaCRM > 0 And CveAcercamientoCRM > 0 And Not CveCliente > 0 Then Alert(String.Format("La Empresa CRM no tiene un Cliente vinculado. Por favor verifique y vuelva a intentar.

    Crear Cliente
    ", CveEmpresaCRM), TipoMensaje.MsgAdvertencia) Return False End If Dim ObjClientes As New ClsClientes If ObjClientes.GetVentasCotizacionesTotales(CveCliente, CveVenta.ToString(), 1) Then DtCotizacionesPS = ObjClientes.DtResultados End If ObjClientes.Dispose() If Not AgregaPSCotizacion(RecalculaImpustosLocales:=False) Then Alert("Ocurrió un error al agregar los conceptos de la cotización. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If 'Dim TotalFactura As Decimal = TmpDT.SUM("TotalImporte").ToDecimal() + TmpDT.SUM("ImporteIVA").ToDecimal() + TmpDT.SUM("ImporteIEPS").ToDecimal() - TmpDT.SUM("ImporteRetIVA").ToDecimal() - TmpDT.SUM("ImporteRetISR").ToDecimal() 'Dim Diferencia As Decimal = TotalCotizacion - TotalFactura 'If Diferencia <> 0 Then ' Dim LastRow As DataRow = TmpDT.Rows(TmpDT.Rows.Count - 1) ' LastRow("ImporteIVA") = LastRow("ImporteIVA").ToString().ToDecimal() + Diferencia ' CalculaTotalesVenta() 'End If If TmpDT.Rows.Count = 0 Then Alert("No hay conceptos por facturar de esta cotización o ha sido cambiada su información. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If Return True End Function #End Region #Region " REMISIONES - SIN FACTURAR " Protected Sub ChkCanRem_CheckedChanged(sender As Object, e As EventArgs) If ChkCanRem.Checked Then DivGvCancelarRemision.Visible = True Else DivGvCancelarRemision.Visible = False End If MostrarCondicionesCancelacion() End Sub Private Sub LnkRemisiones_Click(sender As Object, e As EventArgs) Handles LnkRemisiones.Click Dim ObjContratos As New ClsContratos If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1) Then DdlFiltroContrato.DataSource = ObjContratos.DtResultados DdlFiltroContrato.DataBind() DdlFiltroContrato.Items.Insert(0, New ListItem("Remisiones sin Contrato", "-1")) End If DdlFiltroRemMoneda.Items.Clear() DdlFiltroRemMoneda.DataSource = GlobalDTMonedas DdlFiltroRemMoneda.DataBind() DdlFiltroRemMoneda.Items.Insert(0, New ListItem("Todas", "-1")) GvContratoDetalles.DataSource = Nothing GvContratoDetalles.DataBind() UpContratos.Update() DivEstimaciones.Visible = True ContratoDetalles.Visible = False UPEstimaciones.Update() Tab.ActiveTab = TabGenerales TabGenerales.Enabled = True Updatetabs.Update() If ChkRemProductos.Checked Then CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) Else CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) End If RegistraScript("$('#DivRemisiones').modal('show');") End Sub Private Sub BtnConsultarRem_Click(sender As Object, e As EventArgs) Handles BtnConsultarRem.Click If ChkRemProductos.Checked Then CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) Else CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) End If End Sub Private Sub ChkRemProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkRemProductos.CheckedChanged If ChkRemProductos.Checked Then GvRemPS.Visible = True GvRem.Visible = False DivFiltroRemPS.Visible = True DivFiltroRem.Visible = False GvRem.DataSource = Nothing GvRem.DataBind() CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) Else GvRemPS.Visible = False GvRem.Visible = True DivFiltroRemPS.Visible = False DivFiltroRem.Visible = True GvRemPS.DataSource = Nothing GvRemPS.DataBind() CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) End If End Sub Private Sub DdlFiltroContrato_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroContrato.SelectedIndexChanged If ChkRemProductos.Checked Then CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) Else CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) End If End Sub Private Sub DdlFiltroRemMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroRemMoneda.SelectedIndexChanged If ChkRemProductos.Checked Then CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) Else CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero(), DdlFiltroRemMoneda.SelectedValue.ToEntero()) End If End Sub Private Sub CargaRemisiones(CveContrato As Integer, CveMoneda As Integer) Dim ObjVentas As New ClsVentas If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 1, CveMoneda) Then If CveContrato = -1 Then DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0") Else DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}") End If If Not DTRemisiones.Columns.Contains("Aplicado") Then DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) End If GvRem.DataSource = DTRemisiones End If ObjVentas.Dispose() GvRem.DataBind() UpRemisionesFacturas.Update() End Sub Private Sub CargaRemisionesxProducto(CveContrato As Integer, CveMoneda As Integer) Dim ObjVentas As New ClsVentas If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 2, CveMoneda) Then If CveContrato = -1 Then DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0") Else DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}") End If If Not DTRemisiones.Columns.Contains("Aplicado") Then DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean")) End If GvRemPS.DataSource = DTRemisiones End If ObjVentas.Dispose() GvRemPS.DataBind() UpRemisionesFacturas.Update() End Sub Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblTipo.SelectedIndexChanged HuboCambioRemi = Not HuboCambioRemi 'TOTAL X CONCEPTO If RblTipo.SelectedValue = "3" Then 'DivPSRemision.Visible = False ChkRemProductos.Visible = True Else 'DivPSRemision.Visible = True 'CargaPSRemision(-1, DdlPSRemision) ChkRemProductos.Visible = False ChkRemProductos.Checked = False End If ChkRemProductos_CheckedChanged(ChkRemProductos, EventArgs.Empty) End Sub Protected Sub BtnGuardarRemisiones_Click(sender As Object, e As EventArgs) Handles BtnGuardarRemisiones.Click If GvRem.Rows.Count > 0 Or GvRemPS.Rows.Count > 0 Then If RblTipo.SelectedValue.Contiene("1", "2") AndAlso DdlPSRemision.SelectedValue.ToEntero() <= 0 Then Alert("Debe seleccionar un producto para facturar la remisión", TipoMensaje.MsgAdvertencia) Exit Sub End If 'Checa las facturas selecionadas If Not VerificaRemisiones(DTRemisiones) Then Alert("La cantidad/total debe ser mayor que 0", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim dtSeleccionadas As DataTable = DTRemisiones.FiltraParametros("Aplicado = True") Dim CveContrato = DTRemisiones.FiltroPrimeroValor("CveContrato", "Aplicado = True").ToEntero() If dtSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then Alert("Solo debe seleccionar remisiones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VERIFICA QUE LAS FACTURAS TENGAN EL MISMO ESTATUS EN ALMACEN (NO MEZCLAR REMISIONES 'SURTIDAS' CON 'NO SURTIDAS') 'If dtSeleccionadas.COUNT("Surtido", "Surtido = 'Si'") > 0 AndAlso dtSeleccionadas.COUNT("Surtido", "Surtido = 'No'") > 0 Then ' Dim SbRem As New StringBuilder ' SbRem.Append("Solo debe seleccionar remisiones con el mismo estatus de almacen. Por favor verifique y vuelva a intentar.
    ") ' SbRem.Append("Remisiones Surtidas:
    ") ' For Each RowSurtida As DataRow In dtSeleccionadas.FiltraParametros("Surtido = 'Si'", DistinctColumns:={"Folio"}).Rows ' SbRem.AppendFormat("{0}
    ", RowSurtida("Folio")) ' Next ' SbRem.Append("Remisiones No Surtidas:
    ") ' For Each RowSurtida As DataRow In dtSeleccionadas.FiltraParametros("Surtido = 'No'", DistinctColumns:={"Folio"}).Rows ' SbRem.AppendFormat("{0}
    ", RowSurtida("Folio")) ' Next ' Alert(SbRem.ToString(), TipoMensaje.MsgAdvertencia) ' Exit Sub 'End If DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{dtSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") DdlMoneda.Enabled = False CambiaMoneda() DdlUsoCFDI.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) DdlMetodoPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) DdlFormaPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveFormaPago")) DiasCredito = dtSeleccionadas.FiltroPrimeroValor("DiasCredito").ToEntero() EsDiasCreditoFijo = CBool(dtSeleccionadas.FiltroPrimeroValor("EsDiasCreditoFijo")) 'validación, cuando las remisiones sean de una sucursal y el usuario solo tenga acceso a otra, deberá tener priodidad la sucursal de la que solo se factura If DdlSubProyectoDatos.Enabled = True Then DdlSubProyectoDatos.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveSubProyecto")) End If DdlSucursalCliente.SelectedValueExist(If(dtSeleccionadas.FiltroPrimeroValor("CveClienteSucursal").ToEntero() > 0, dtSeleccionadas.FiltroPrimeroValor("CveClienteSucursal"), "-1")) DdlVendedor.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveVendedor")) CambiaSucursalGeneral() CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero()) DdlUsoCFDI.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) DdlMetodoPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero()) DdlFormaPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveFormaPago")) If GvPS.Rows.Count > 0 Then TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = TxtIVA.Text End If RBLPago.Items(0).Enabled = True 'sino está activo lo activamos porque las remisiones pueden ser a crédito RBLPago.SelectedValue = "1" RemisionesLista.Clear() Dim MsgUsados As New StringBuilder Dim UsadosValidados As Boolean = True If dtSeleccionadas.Rows.Count > 0 Then Select Case RblTipo.SelectedValue Case "1" 'T O T A L G E N E R A L For Each row As DataRow In dtSeleccionadas.Rows If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Using ObjUsados As New ClsVentas If ObjUsados.GetVentasUsados(row("CveVenta").ToString().ToEntero(), -1, row("Fecha").ToString().ToDateTime, UsuarioActual.CveEmpresa) Then If ObjUsados.DtResultados.Rows.Count > 0 Then UsadosValidados = False MsgUsados.AppendFormat("{0},", row("Folio").ToString()) End If End If End Using End If If UsadosValidados Then RemisionesLista.Add(row("CveVenta").ToString().ToEntero()) End If Next IsTotalxConcepto = False Dim PU As Decimal = dtSeleccionadas.SUM("SubTotal").ToDecimal Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPSRemision.SelectedValue.ToEntero())(0) Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16) Dim rowSP As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa)(0) AgregarProductoServicio(1, PS("CveUM").ToString().ToEntero(), PS("UnidadMedida").ToString(), PS("CveClasificacion").ToString().ToEntero(), PS("Clasificacion").ToString(), PS("CvePS").ToString().ToEntero(), PS("PS").ToString(), "", PU, 0, rowSP("CveProyecto").ToString().ToEntero(), rowSP("Proyecto").ToString(), rowSP("CveSubProyecto").ToString().ToEntero(), rowSP("SubProyecto").ToString(), RegeneraIEPS:=True) CalculaTotalesVenta() Case "2" 'T O T A L X R E M I S I O N For Each row As DataRow In dtSeleccionadas.Rows If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Using ObjUsados As New ClsVentas If ObjUsados.GetVentasUsados(row("CveVenta").ToString().ToEntero(), -1, row("Fecha").ToString().ToDateTime, UsuarioActual.CveEmpresa) Then If ObjUsados.DtResultados.Rows.Count > 0 Then UsadosValidados = False MsgUsados.AppendFormat("{0},", row("Folio").ToString()) End If End If End Using End If If UsadosValidados Then RemisionesLista.Add(row("CveVenta").ToString().ToEntero()) End If Next Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPSRemision.SelectedValue.ToEntero())(0) Dim rowSP As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero(), CveEmpresa:=UsuarioActual.CveEmpresa)(0) Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16) For Each gvr As GridViewRow In GvRem.Rows If gvr.FCCheckBox("Chk").Checked Then AgregarProductoServicio(1, PS("CveUM").ToString().ToEntero(), PS("UnidadMedida").ToString(), PS("CveClasificacion").ToString().ToEntero(), PS("Clasificacion").ToString(), PS("CvePS").ToString().ToEntero(), PS("PS").ToString(), "", gvr.DataKey("SubTotal").ToString().ToDecimal, 0, rowSP("CveProyecto").ToString().ToEntero(), rowSP("Proyecto").ToString(), rowSP("CveSubProyecto").ToString().ToEntero(), rowSP("SubProyecto").ToString(), RegeneraIEPS:=True) End If Next CalculaTotalesVenta() Case "3" 'T O T A L X C O N C E P T O IsTotalxConcepto = True Dim sb As New StringBuilder If ChkRemProductos.Checked Then For Each row As DataRow In dtSeleccionadas.Rows sb.Append($"{row("CveVentaDetalle").ToString()},") Next For Each row As DataRow In dtSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta", "Fecha", "Folio"}).Rows If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Using ObjUsados As New ClsVentas If ObjUsados.GetVentasUsados(row("CveVenta").ToString().ToEntero(), -1, row("Fecha").ToString().ToDateTime, UsuarioActual.CveEmpresa) Then If ObjUsados.DtResultados.Rows.Count > 0 Then UsadosValidados = False MsgUsados.AppendFormat("{0},", row("Folio").ToString()) End If End If End Using End If If UsadosValidados Then RemisionesLista.Add(row("CveVenta").ToString().ToEntero()) End If Next Else For Each row As DataRow In dtSeleccionadas.Rows sb.Append($"{row("CveVenta").ToString()},") If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then Using ObjUsados As New ClsVentas If ObjUsados.GetVentasUsados(row("CveVenta").ToString().ToEntero(), -1, row("Fecha").ToString().ToDateTime, UsuarioActual.CveEmpresa) Then If ObjUsados.DtResultados.Rows.Count > 0 Then UsadosValidados = False MsgUsados.AppendFormat("{0},", row("Folio").ToString()) End If End If End Using End If If UsadosValidados Then RemisionesLista.Add(row("CveVenta").ToString().ToEntero()) End If Next End If sb.Remove(sb.Length - 1, 1) If UsadosValidados Then CargaConceptosRemisionPorFacturar(sb.ToString(), If(ChkRemProductos.Checked, 2, 1)) End If sb.Clear() End Select Dim CveTipoDocto = DdlTipoComprobante.SelectedValue DdlTipoComprobante.Items.Clear() DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) DdlTipoComprobante.SelectedIndex = 0 DdlTipoComprobante.SelectedValueExist(CveTipoDocto) CambiaTipoComprobante() Dim MensajeRemisiones As New StringBuilder Dim ObsOC As New StringBuilder Dim ObsPedido As New StringBuilder Dim ObsInv As New StringBuilder MensajeRemisiones.Append("Remisiones: ") Dim CveMetodoPago As Integer = -1 Dim MetodoPagoDif As Boolean = False For Each Dr As DataRow In dtSeleccionadas.Rows MensajeRemisiones.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString().Length > 0, $"({Dr("ObsFact")})", "")) ObsOC.AppendFormat("{0}, ", Dr("ObsOC")) ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido")) ObsInv.AppendFormat("{0}, ", Dr("ObsInv")) If CveMetodoPago <> -1 And Dr("CveMetodoPago33").ToString().ToEntero() <> CveMetodoPago Then MetodoPagoDif = True End If CveMetodoPago = Dr("CveMetodoPago33").ToString().ToEntero() Next TxtObsFact.Text = If(MensajeRemisiones.ToString().Length > 0, MensajeRemisiones.ToString().Substring(0, MensajeRemisiones.ToString().Length - 2), "") TxtOrdenCompra.Text = If(ObsOC.ToString().Length > 0, ObsOC.ToString().Substring(0, ObsOC.ToString().Length - 2), "") TxtPedidoContrato.Text = If(ObsPedido.ToString().Length > 0, ObsPedido.ToString().Substring(0, ObsPedido.ToString().Length - 2), "") TxtObsAlmacen.Text = If(ObsInv.ToString().Length > 0, ObsInv.ToString().Substring(0, ObsInv.ToString().Length - 2), "") UPObservaciones.Update() If MetodoPagoDif Then Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia) End If If CveContrato > 0 Then DdlContrato.DataSource = DtContratos.FiltraParametros($"CveContrato = {CveContrato}") DdlContrato.DataBind() End If MensajeRemisiones.Clear() ObsOC.Clear() ObsPedido.Clear() ObsInv.Clear() End If If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso Not UsadosValidados Then If MsgUsados.Length > 0 Then MsgUsados.Remove(MsgUsados.Length - 1, 1) End If Alert($"Las siguientes remisiones no se pueden facturar porque no se ha recibido el usado correspondiente:
    {MsgUsados.ToString()}", TipoMensaje.MsgAdvertencia) BtnEmitirImprimir.Visible = False End If End If TxtFechaPago.Text = If(EsDiasCreditoFijo, Now.AddDays(DiasCredito).ToShortDateString, TxtFechaPago.Text) UpRemisionesFacturas.Update() UpFacturar.Update() UpPS.Update() UpParametros.Update() UPEstimaciones.Update() UPCondicionesPago.Update() HuboCambioRemi = Not HuboCambioRemi RegistraScript("$('#DivRemisiones').modal('hide');", "DivRemisionesHide") End Sub Private Function VerificaRemisiones(ByRef dt As DataTable) As Boolean Dim Valido As Boolean = True If ChkRemProductos.Checked Then Valido = Not (From GvRow In GvRemPS.Rows.Cast(Of GridViewRow) Let Cantidad = GvRow.FCTextBox("TxtCantidadRem").Text.Trim().ToDecimal(), Aplicar = GvRow.FCCheckBox("Chk").Checked Where GvRow.RowType = DataControlRowType.DataRow AndAlso Cantidad <= 0D AndAlso Aplicar Select GvRow ).Any If Valido Then For Each Gvr As GridViewRow In GvRemPS.Rows If Gvr.RowType = DataControlRowType.DataRow Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero() Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If Next End If Else For Each Gvr As GridViewRow In GvRem.Rows If Gvr.RowType = DataControlRowType.DataRow Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero() Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If Next End If Return Valido End Function Private Sub CargaConceptosRemisionPorFacturar(CveRemisiones As String, TipoCargas As Integer) Dim ObjClientes As New ClsClientes If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveRemisiones, TipoCargas) Then DtRemisionesPS = ObjClientes.DtResultados End If ObjClientes.Dispose() If DtRemisionesPS IsNot Nothing Then Dim tCantidad As Decimal = 0 For Each Dr As DataRow In DtRemisionesPS.Select() tCantidad = If(ChkRemProductos.Checked, GvRemPS.Rows(IndiceGVDataKey(GvRemPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadRem").Text, Dr("Cantidad")).ToString().ToDecimal AgregarProductoServicio(tCantidad, Dr("CveUM").ToString().ToEntero(), Dr("UM").ToString(), Dr("CveClasificacion").ToString().ToEntero(), Dr("Clasificacion").ToString(), Dr("CvePS").ToString().ToEntero(), Dr("PS").ToString(), Dr("Obs").ToString(), Dr("PU").ToString().ToDecimal, Dr("Descuento").ToString().ToDecimal, Dr("CveProyecto").ToString().ToEntero(), Dr("Proyecto").ToString(), Dr("CveSubProyecto").ToString().ToEntero(), Dr("SubProyecto").ToString(), CveVentaDetalle:=Dr("CveVentaDetalle").ToString().ToEntero(), CveContratoDetalle:=Dr("CveContratoDetalle").ToString().ToEntero(), CveVentaDetalleRemision:=Dr("CveVentaDetalle").ToString().ToEntero(), RegeneraIEPS:=True) Next If DdlFiltroContrato.SelectedValue.ToEntero() > 0 Then CveContrato = DdlFiltroContrato.SelectedValue.ToEntero() End If End If CalculaTotalesVenta() End Sub Private Function IndiceGVDataKey(GridView As GridView, DataKey As String, DataKeyValue As String) As Integer For Each row As GridViewRow In GridView.Rows If row.DataKey(DataKey) = DataKeyValue Then Return row.RowIndex End If Next Return Nothing End Function #End Region #Region " REMISIONES - FACTURAR " Private Sub ActivaFacturarRemision() 'If UsuarioActual.CveUsuario <> 100 Then ' Exit Sub 'End If Dim ObjClientes As New ClsClientes If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveVenta.ToString(), 1) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then LnkFacturarRemision.Visible = True If ThCantidadFacturadaRem.Visible Then LnkFacturarRemision.ToolTip = "¿Seguro que desea facturar lo pendiente por facturar de la remisión?" End If If DdlMoneda.SelectedValue.ToEntero() = 1 Then TrConversionDolares.Visible = True ChkConvertirDolares.Enabled = Not UsuarioActual.TienePermisoProceso(324) TxtTipoCambioDlls.Enabled = True Else TrConversionTipoCambio.Visible = True ChkConvertirDoctoPesos.Enabled = Not UsuarioActual.TienePermisoProceso(324) TxtTipoCambio.Enabled = True End If UpPS.Update() End If ObjClientes.Dispose() End Sub Private Sub LnkFacturarRemision_Click(sender As Object, e As EventArgs) Handles LnkFacturarRemision.Click 'LIMPIAMOS TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtIEPS.Text = "0.00" TxtRetIVA.Text = "0.00" TxtRetISR.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = TxtIVA.Text CreaDTVentas() CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero() > 0, DdlContrato.SelectedValue.ToEntero(), -1), DdlMoneda.SelectedValue.ToEntero()) Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}") If DrRemision.Count > 0 Then DrRemision(0)("Aplicado") = "True" End If DTRemisiones.AcceptChanges() RemisionesLista.Add(CveVenta) CargaConceptosRemisionPorFacturar(CveVenta.ToString(), 1) BtnEmitirImprimir.Text = "Facturar" DdlTipoComprobante.SelectedValue = "Ing" If Not (EstablecioFolio AndAlso UsuarioActual.TienePermisoProceso(130)) Then TxtFecha.Text = Now.ToShortDateString() End If UpPS.Update() UpFacturar.Update() If TmpDT.Rows.Count = 0 Then Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If BtnEmitirImprimir_Click(BtnEmitirImprimir, EventArgs.Empty) End Sub Private Function PreparaFacturarRemision() As Boolean 'LIMPIAMOS TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtIEPS.Text = "0.00" TxtRetIVA.Text = "0.00" TxtRetISR.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = TxtIVA.Text CreaDTVentas() CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero() > 0, DdlContrato.SelectedValue.ToEntero(), -1), DdlMoneda.SelectedValue.ToEntero()) Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}") If DrRemision.Count > 0 Then DrRemision(0)("Aplicado") = "True" End If DTRemisiones.AcceptChanges() RemisionesLista.Add(CveVenta) CargaConceptosRemisionPorFacturar(CveVenta.ToString(), 1) If TmpDT.Rows.Count = 0 Then Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If Return True End Function #End Region #Region " PEDIDOS2 - SIN FACTURAR " Protected Sub LnkPedido2SinFacturar_Click(sender As Object, e As EventArgs) DdlMonedaModalPedido2.Items.Clear() DdlMonedaModalPedido2.DataSource = GlobalDTMonedas DdlMonedaModalPedido2.DataBind() DdlMonedaModalPedido2.Items.Insert(0, New ListItem("Todas", "-1")) Tab.ActiveTab = TabGenerales TabGenerales.Enabled = True Updatetabs.Update() CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero(), If(ChkMostrarProductosPedido2.Checked, 0, 1)) RegistraScript("$('#DivPedidos2').modal('show');") End Sub Private Sub BtnConsultaPedido_Click(sender As Object, e As EventArgs) Handles BtnConsultaPedido.Click CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero(), If(ChkMostrarProductosPedido2.Checked, 0, 1)) End Sub Protected Sub ChkMostrarProductosPedido2_CheckedChanged(sender As Object, e As EventArgs) MostrarProductoPedido2() CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero(), If(ChkMostrarProductosPedido2.Checked, 0, 1)) End Sub Private Sub MostrarProductoPedido2() If ChkMostrarProductosPedido2.Checked Then GvPedidos2SinFacturarPS.Visible = True GvPedidos2SinFacturar.Visible = False DivBuscadorPedido2PS.Visible = True DivBuscadorPedido2.Visible = False GvPedidos2SinFacturar.DataSource = Nothing GvPedidos2SinFacturar.DataBind() Else GvPedidos2SinFacturarPS.Visible = False GvPedidos2SinFacturar.Visible = True DivBuscadorPedido2PS.Visible = False DivBuscadorPedido2.Visible = True GvPedidos2SinFacturarPS.DataSource = Nothing GvPedidos2SinFacturarPS.DataBind() End If End Sub Private Sub CargaPedidos2(CveMoneda As Integer, Tipo As Integer) Dim ObjVentas As New ClsVentas If ObjVentas.GetVentaDetallePedido2SinFacturar(TxtFechaIPed.Text, TxtFechaFPedido.Text, CveCliente, CveMoneda, Tipo) Then DtPedidos2 = ObjVentas.DtResultados If Not DtPedidos2.Columns.Contains("Aplicado") Then DtPedidos2.Columns.Add("Aplicado", Type.GetType("System.Boolean")) End If If Tipo = 1 Then GvPedidos2SinFacturar.DataSource = DtPedidos2 Else GvPedidos2SinFacturarPS.DataSource = DtPedidos2 End If End If ObjVentas.Dispose() If Tipo = 1 Then GvPedidos2SinFacturar.DataBind() Else GvPedidos2SinFacturarPS.DataBind() End If UpModalPedidos2.Update() End Sub Protected Sub BtnGuardarPedido2_Click(sender As Object, e As EventArgs) If GvPedidos2SinFacturar.Rows.Count = 0 And GvPedidos2SinFacturarPS.Rows.Count = 0 Then Alert("Debe existir por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'MARCA LAS SELECCIONADAS VerificaPedidos2(DtPedidos2) Dim DTSeleccionadas As DataTable = DtPedidos2.FiltraParametros("Aplicado = True") If DTSeleccionadas.Rows.Count = 0 Then Alert("Debe seleccionar por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'SOLO PUEDE SELECCIONAR DE LA MISMA MONEDA If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then Alert("Solo debe seleccionar pedidos de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'LIMPIA LAS PARTIDAS ACTUALES If GvPS.Rows.Count > 0 Then TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtIEPS.Text = "0.00" TxtRetISR.Text = "0.00" TxtRetIVA.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = "0.00" End If Pedidos2Lista.Clear() 'CARGAMOS LOS VALORES DEL PEDIDO DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'") DdlMoneda.Enabled = False CambiaMoneda() DdlMetodoPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveMetodoPago")) DdlFormaPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveFormaPago")) DdlUsoCFDI.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveUsoCFDI")) If DdlSubProyectoDatos.Enabled Then 'validación, cuando los pedido2 sean de una sucursal y el usuario solo tenga acceso a otra, deberá tener priodidad la sucursal de la que solo se factura DdlSubProyectoDatos.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveSubProyecto")) End If DdlSucursalCliente.SelectedValueExist(If(DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal").ToEntero() > 0, DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal"), "-1")) DdlVendedor.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveVendedor")) CambiaSucursalGeneral() CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero()) Dim Cves As New StringBuilder If ChkMostrarProductosPedido2.Checked Then For Each row As DataRow In DTSeleccionadas.Rows Cves.Append($"{row("CveVentaDetalle").ToString()},") Next For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows Pedidos2Lista.Add(row("CveVenta").ToString().ToEntero()) Next Else For Each row As DataRow In DTSeleccionadas.Rows Cves.Append($"{row("CveVenta").ToString()},") Pedidos2Lista.Add(row("CveVenta").ToString().ToEntero()) Next End If Cves.Remove(Cves.Length - 1, 1) Dim ObjVentas As New ClsVentas If ObjVentas.GetVentasPedidos2Totales(CveCliente, Cves.ToString(), If(ChkMostrarProductosPedido2.Checked, 2, 1)) Then DtPedidos2PS = ObjVentas.DtResultados End If ObjVentas.Dispose() Cves.Clear() If Not AgregaPSPedido2() Then Alert("Ocurrió un error validar las partidas de los pedidos seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim CveTipoDocto = DdlTipoComprobante.SelectedValue DdlTipoComprobante.Items.Clear() DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing")) DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant")) DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem")) DdlTipoComprobante.SelectedIndex = 0 DdlTipoComprobante.SelectedValueExist(CveTipoDocto) CambiaTipoComprobante() 'CARGA OBSERVACIONES DE LOS PEDIDOS Dim MensajePedidos2 As New StringBuilder Dim ObsOC As New StringBuilder Dim ObsPedido As New StringBuilder Dim ObsInv As New StringBuilder MensajePedidos2.Append("Pedidos: ") For Each Dr As DataRow In DTSeleccionadas.Rows MensajePedidos2.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString().Length > 0, $"({Dr("ObsFact")})", "")) ObsOC.AppendFormat("{0}, ", Dr("ObsOC")) ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido")) ObsInv.AppendFormat("{0}, ", Dr("ObsInv")) Next TxtObsFact.Text = If(MensajePedidos2.ToString().Length > 0, MensajePedidos2.ToString().Substring(0, MensajePedidos2.ToString().Length - 2), "") TxtOrdenCompra.Text = If(ObsOC.ToString().Length > 0, ObsOC.ToString().Substring(0, ObsOC.ToString().Length - 2), "") TxtPedidoContrato.Text = If(ObsPedido.ToString().Length > 0, ObsPedido.ToString().Substring(0, ObsPedido.ToString().Length - 2), "") TxtObsAlmacen.Text = If(ObsInv.ToString().Length > 0, ObsInv.ToString().Substring(0, ObsInv.ToString().Length - 2), "") MensajePedidos2.Clear() ObsOC.Clear() ObsPedido.Clear() ObsInv.Clear() UpModalPedidos2.Update() UpFacturar.Update() UpPS.Update() UpParametros.Update() UPEstimaciones.Update() UPObservaciones.Update() RegistraScript("$('#DivPedidos2').modal('hide');", "DivPedidos2Hide") End Sub Private Sub VerificaPedidos2(ByRef dt As DataTable) If ChkMostrarProductosPedido2.Checked Then For Each Gvr As GridViewRow In GvPedidos2SinFacturarPS.Rows If Gvr.RowType = DataControlRowType.DataRow Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero() Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If Next Else For Each Gvr As GridViewRow In GvPedidos2SinFacturar.Rows If Gvr.RowType = DataControlRowType.DataRow Then Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk") Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero() Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}") If Drs.Count > 0 Then Drs(0)("Aplicado") = ChkAplicar.Checked End If dt.AcceptChanges() End If Next End If End Sub Private Function AgregaPSPedido2() As Boolean If DtPedidos2PS IsNot Nothing Then Dim tCantidad As Decimal = 0 For Each Dr As DataRow In DtPedidos2PS.Select() tCantidad = If(ChkMostrarProductosPedido2.Checked, GvPedidos2SinFacturarPS.Rows(IndiceGVDataKey(GvPedidos2SinFacturarPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadPedido2").Text, Dr("Cantidad")).ToString().ToDecimal AgregarProductoServicio(tCantidad, Dr("CveUM").ToString().ToEntero(), Dr("UM").ToString(), Dr("CveClasificacion").ToString().ToEntero(), Dr("Clasificacion").ToString(), Dr("CvePS").ToString().ToEntero(), Dr("PS").ToString(), Dr("Obs").ToString(), Dr("PU").ToString().ToDecimal, Dr("Descuento").ToString().ToDecimal, Dr("CveProyecto").ToString().ToEntero(), Dr("Proyecto").ToString(), Dr("CveSubProyecto").ToString().ToEntero(), Dr("SubProyecto").ToString(), CveVentaDetalle:=Dr("CveVentaDetalle").ToString().ToEntero(), CveVentaDetallePedido2:=Dr("CveVentaDetalle").ToString().ToEntero(), RegeneraIEPS:=True) Next CalculaTotalesVenta() Return True Else Return False End If End Function #End Region #Region " PEDIDOS2 - FACTURAR " Private Function PreparaFacturarPedido() As Boolean 'LIMPIAMOS TmpDT.Rows.Clear() TxtSubTotal.Text = "0.00" TxtSubTotal2.Text = "0.00" TxtIVA.Text = "0.00" TxtIEPS.Text = "0.00" TxtRetIVA.Text = "0.00" TxtRetISR.Text = "0.00" TxtTotal.Text = "0.00" HdnIVAOriginal.Value = TxtIVA.Text CreaDTVentas() Dim ObjVentas As New ClsVentas If ObjVentas.GetVentasPedidos2Totales(CveCliente, CveVenta.ToString(), 1) Then DtPedidos2PS = ObjVentas.DtResultados End If ObjVentas.Dispose() If Not AgregaPSPedido2() Then Alert("Ocurrió un error validar las partidas de los pedidos seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If If TmpDT.Rows.Count = 0 Then Alert("No hay conceptos por facturar de esta cotización o ha sido cambiada su información. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If TxtObsFact.Text = String.Format("Pedido: {0}-{1} {2}", LblSerie.Text, TxtFolio.Text, If(TxtObsFact.Text.Length > 0, $"({TxtObsFact.Text})", "")) Return True End Function #End Region #Region " BOTONERA - ACCIONES DE ABAJO " #Region " CREAR APARTIR DE " Protected Sub BtnCrearApartirDe_Click(sender As Object, e As System.EventArgs) Handles BtnCrearApartirDe.Click ''[IPP-2Novimebre2018] COMENTADO POR SER UNA FUNCIONALIDAD SUPER RARA! LA REEMPLAZA EL EDITAR COTIZACION ''Cuando es Cotizacion, actualiza la original 'If DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnCrearApartirDe.Text = "Guardar Cambios" Then ' Dim OcurrioError As Boolean = False ' Dim ObjVentas As New ClsVentas ' ObjVentas.IniciaTransacSQL() ' 'Elimino los movimientos del detalle de Ventas (Conceptos) ' If Not ObjVentas.RemoveVentasDetalle(CveVenta) Then OcurrioError = True ' 'Actualizo los parametros de la venta ' If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.Replace(",", "").ToDouble, LblDescuentos.Text.ToDouble, TxtIVA.Text.ToDouble, TxtIEPS.Text.ToDouble, TxtTotal.Text.ToDouble, ' DdlMoneda.SelectedValue.ToEntero(), TxtTipoCambio.Text.Trim.ToDouble, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim, UsuarioActual.CveEmpresa, CveVenta, DdlMetodoPago.SelectedValue.ToEntero(), ' DdlFormaPago.SelectedValue.ToEntero(), TxtNumCtaPago.Text.Trim, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero(), CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero()) Then ' OcurrioError = True ' End If ' 'Cargo de nueva cuenta el detalle de Ventas (Conceptos) ' For Each Row As DataRow In TmpDT.Rows ' If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString().ToEntero(), Row("Cantidad").ToString().ToDouble, Row("CveUM").ToString().ToEntero(), ' Row("PU").ToString().ToDouble, Row("IVA").ToString().ToDouble, Math.Round((Row("Total").ToString().ToDouble * (1 + Row("IVA").ToString().ToDouble)), 6), ' Row("Obs").ToString(), Row("Descuento").ToString().ToDouble, Row("TipoDescuento").ToString().ToEntero(), Row("CveSubProyecto").ToString().ToEntero(), Row("CvePresupuestoIngreso").ToString().ToEntero(), IEPS:=Row("IEPS").ToString().ToDouble) Then ' OcurrioError = True ' Exit For ' End If ' Next ' If OcurrioError Then ' ObjVentas.RollBack() ' Alert("Ocurrió un error al guardar los cambios. Por favor intente de nuevo.", TipoMensaje.MsgError) ' Else ' '/Ventas/Ventas.aspx?CveVenta={0}&Tipo=Cot ' Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta & "&&Tipo=Cot"";") ' BtnCrearApartirDe.Text = "Editar" ' ObjVentas.Commit() ' ' GeneraPDFCot(TxtFecha.Text.Trim.ToDate, DTPS, VentaFolio, False, False) ' End If ' ObjVentas.Dispose() ' Exit Sub 'End If ''[IPP-2Novimebre2018] COMENTADO POR SER UNA FUNCIONALIDAD SUPER RARA! LA REEMPLAZA EL EDITAR COTIZACION 'If DdlTipoComprobante.SelectedValue = "Cot" Then ' BtnCrearApartirDe.Text = "Guardar Cambios" ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs")) ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev")) ' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2")) 'Else ' BtnCrearApartirDe.Visible = False 'End If Dim FolioOriginal As String = TxtFolio.Text HdnCveVenta.Value = "" BtnCrearApartirDe.Visible = False '[IPP-2Novimebre2018] REEMPLAZA LO COMENTADO ARRIBA EsCreaApartirDe = True ModalidadEdicion = True DivEstatusFac.Visible = False TabAlmacen.Visible = False 'CUANDO ES CREAR APARTIR DE SE LIMPIAN FUNCIONALIDADES DE DOCUMENTOS YA REGISTRADOS BtnGenerarRemision.Visible = False BtnEditarRemision.Visible = False BtnPermisoEditarRemision.Visible = False BtnPermisoEditarCotizacion.Visible = False BtnEditarCotizacion.Visible = False BtnGenerarOS.Visible = False BtnsFacturar.Visible = False LBFacturarAnticipo.Visible = UsuarioActual.TienePermisoProceso(274) HLOrdendeCompra.Visible = False LBAplicaDevolucion.Visible = False 'LkNotaCredito.Visible = False LkEliminarFactura.Visible = False ImgDownCancelacion.Visible = False LkRefacturacion.Visible = False HLOrdenServicio.Visible = False LkCotizacionAutorizar.Visible = False LnkFacturarRemision.Visible = False LnkRemisiones.Visible = False LnkPedido2SinFacturar.Visible = False LnkCotizaciones.Visible = False LnkOCs.Visible = False LbCancelarDocumento.Visible = False LBCancelarPedido.Visible = False LiDevolucionAlmacen.Visible = False HLPagar.Visible = False HlAgregarExcel.Visible = False 'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION/COTIZACIÓN GvPS.Columns(6).Visible = False ThCantidadFacturadaRem.Visible = False ThCantidadFacturadaRem2.Visible = False GvPS.Columns(7).Visible = False ThCantidadFacturada.Visible = False ThCantidadFacturada2.Visible = False 'Cuando es cotización, Genera nueva cotizacion If DdlTipoComprobante.SelectedValue = "Cot" Then BtnEmitirImprimir.Text = "Cotizar" ImgAntiPend.Visible = False 'TdReferencia.Style.Add("display", "none") End If HplDownXML.Visible = False HplDownPDF.Visible = False LblFolioFiscal.Text = "" DdlTipoComprobante.Enabled = True TxtFecha.Text = Now.ToShortDateString() LblUsuario.Text = UsuarioActual.Usuario LblFechaRegistro.Text = Now.ToShortDateString() LblSeTimbro.Text = "No" LblMail.Text = "No" 'PORLET CLIENTE 'ACTIVA CAMBIO DE CLIENTE HlCliente.Attributes.Remove("class") HlCliente.Attributes.Add("class", "Texto") TxtCodigo.ReadOnly = False ChkEnviarFactura.Enabled = True DdlSucursalCliente.Enabled = True ChkDireccionEnvio.Enabled = True DdlDireccionEnvio.Enabled = True LnkOtraDireccion.Visible = True TxtAtencionA.Enabled = True TxtFechaVencimientoCotizacion.Enabled = True TxtCantidad.Enabled = True DdlClasificacion.Enabled = True DdlPS.Enabled = True TxtObsPS.Enabled = True DdlProyecto.Enabled = True DdlSubProyecto.Enabled = True TxtPrecio.Enabled = True LbAgregar.Enabled = True LnkAgregarPyME.Enabled = True ImgDescPU.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '0'; $get('LblPrecio1').style.display = ''; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") ImgDescConcepto.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '1'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = ''; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';") ImgDescTotal.Visible = False ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';") TxtMotivoDescuento.Enabled = True LblSubTotal1.Text = TxtSubTotal.Text TxtObsFact.Enabled = True TxtMotivoDescuento.Enabled = True TxtSubTotal.ReadOnly = False TxtIVA.ReadOnly = False TxtRetIVA.ReadOnly = False TxtRetISR.ReadOnly = False TxtTotal.ReadOnly = False CalculaTotalesVenta() BtnEmitirImprimir.Visible = True GvImpuestosLocales2.Enabled = True 'Sección Detalle DdlMoneda.Enabled = True ChkConvertirDoctoPesos.Enabled = Not UsuarioActual.TienePermisoProceso(324) TxtTipoCambio.Enabled = True TxtFechaEjecucion.ReadOnly = False TxtFechaEjecucion.Text = Now.ToShortDateString ImgCalendarFechaEje.Enabled = True DdlVendedor.Enabled = True DdlSubProyectoDatos.Enabled = True DdlSubProyectoEjecucion.Enabled = True DdlSubProyectoCobranza.Enabled = True TxtTiempoEntrega.Enabled = True TxtAlfa1.ReadOnly = False TxtAlfa2.ReadOnly = False TxtAlfa3.ReadOnly = False TxtNum1.ReadOnly = False TxtNum2.ReadOnly = False TxtNum3.ReadOnly = False TxtFech1.ReadOnly = False : ImgFech1.Enabled = True TxtFech2.ReadOnly = False : ImgFech2.Enabled = True TxtFech3.ReadOnly = False : ImgFech3.Enabled = True 'Condiciones de Pago RBLPago.Enabled = True RBLPago.Items(0).Enabled = True DdlFormaPago33.Enabled = True DdlUsoCFDI.Enabled = True DdlMetodoPago33.Enabled = True 'TxtNumCtaPago.Enabled = True TxtFechaPago.ReadOnly = False imgCalendario.Enabled = True TxtPedidoContrato.Enabled = True TxtOrdenCompra.Enabled = True Dim ObjCliente As New ClsClientes() If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then If ObjCliente.DtResultados.Rows.Count > 0 Then PlazoCobranza = ObjCliente.PlazoCobranza PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision 'TxtNumCtaPago.Text = ObjCliente.NumCtaPago TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString DdlTipoRetencion.SelectedValueExist(ObjCliente.DtResultados(0)("CveTipoRetencion").ToString()) End If End If ObjCliente.Dispose() DdlTipoRetencion_SelectedIndexChanged(DdlTipoRetencion, EventArgs.Empty) TrVistaPrevia.Visible = True TxtFechaVencimientoCotizacion.Text = Now.ToShortDateString 'HABILITA EDITAR Y ELIMINAR DEL GV GvPS.Columns(17).Visible = True GvPS.Columns(18).Visible = True SetPermisos() CambiaTipoDocto() CambiaSucursalGeneral(RecargarPartidas:=False) CargaAnticipos(CveCliente) CargaRestriccionesCreditoCliente(CveVenta:=-1) If UsuarioActual.Empresa.Funcionalidad(558) = "1" Then TabAlmacen.Visible = True DivAlmacen.Visible = True CargaGVInv(TmpDT.FiltraParametros("CveTipoPS = 2")) End If BloqueaCondiconesPago() DivDdlFacturaRela.Visible = True BtnAgregarFacturasRelaciondas.Visible = True DdlTipoRelacionARelacionar.Enabled = True GvFacturasRelacionadas.Columns(2).Visible = True CalculaTotalesVenta() Dim PorcentajeRetIVA = (TmpDT.MAX("PorcentajeRetIVA").ToDecimal() * 100) If PorcentajeRetIVA > 0 Then TrRetIVA.Style.Add("display", "") UsuarioActual.Empresa.MostrarRetIVA = True DdlTipoRetencion.Visible = True End If If DivCartaPorte.Visible Then HabilitarControlesCartaPorte(True) End If If DivAdjuntar.Visible Then Dim FolioNuevo As String = TxtFolio.Text If FolioNuevo <> FolioOriginal Then If Adjunto <> "" Then Adjunto = "" BtnArchivoAdjunto.Text = "" BtnArchivoAdjunto.Visible = False BtnEliminarAdjunto.Visible = False BtnAdjuntar.Visible = True tdAdjuntar.Style.Item("display") = "block" tdAdjunto.Style.Item("display") = "none" Else DivAdjuntar.Visible = True End If Else DivAdjuntar.Visible = False End If UpAdjuntar.Update() Else DivAdjuntar.Visible = True End If UpnTools.Update() UpCliente.Update() UpParametros.Update() UpPS.Update() UpFacturar.Update() UPObservaciones.Update() UPPDescuento.Update() UPCondicionesPago.Update() UpDetalle.Update() UpEstatus.Update() UpParametros.Update() UpINV.Update() UpFacturasRelacionadas.Update() UpEmitirTransitorio.Update() End Sub #End Region #Region " GENERAR FACTURA " Protected Sub LBFacturarIngreso_Click(sender As Object, e As EventArgs) EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) 'DdlTipoComprobante.SelectedValue = "Ing" EmitirDocumentoNuevo("Ing") End Sub Protected Sub LBFacturarAnticipo_Click(sender As Object, e As EventArgs) EraCotizacion = If(DdlTipoComprobante.SelectedValue = "Cot", 1, 0) 'DdlTipoComprobante.SelectedValue = "Ant" EmitirDocumentoNuevo("Ant") 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 'SI ES AMORTIZACION POR NOTA DE CREDITO DEBE SUMAR LA TOTALIDAD PARA COMPARAR EL PAGO If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then For Each gvr As GridViewRow In GVAnticipos.Rows If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked AndAlso gvr.DataKey("CveConceptoContable").ToEntero().Contiene(3) Then AmortizacionNC += gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal End If Next End If 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").ToDecimal() + 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 DdlVendedor.SelectedValue.ToEntero() <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso TipoDoctoNuevo = "Ing" Then Alert("Debe seleccionar un vendedor.", TipoMensaje.MsgAdvertencia) Exit Sub End If 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 If GvPagos.Rows.Count = 0 And UsuarioActual.Empresa.Funcionalidad(558).ToEntero() = 1 And RBLPago.SelectedValue.ToEntero() = 2 Then Alert("No se puede facturar hasta que se haya especificado detalladamente la forma de pago", TipoMensaje.MsgAdvertencia) Else Dim FolioFijo As Integer = 0 'CARGA LO PENDIENTE POR FACTURAR DE COTIZACION If EraCotizacion = 1 Then If Not ValidaFacturarCotizacion() Then Exit Sub End If If Not PreparaFacturarCotizacion() Then EraCotizacion = 0 DdlTipoComprobante.SelectedValue = "Cot" Exit Sub End If 'If Not AjustarTotalCotizacionFacturada(Me.CveVenta) Then ' Alert("Ocurrió un error al ajustar el importe", TipoMensaje.MsgError) ' Exit Sub 'End If End If 'CARGA LO PENDIENTE POR FACTURAR DE REMISION If DdlTipoComprobante.SelectedValue = "Rem" Then If Not PreparaFacturarRemision() Then DdlTipoComprobante.SelectedValue = "Rem" Exit Sub End If End If 'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO2 If DdlTipoComprobante.SelectedValue = "Pd2" Then If Not PreparaFacturarPedido() Then DdlTipoComprobante.SelectedValue = "Pd2" Exit Sub End If End If 'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO AUTORIZACION If DdlTipoComprobante.SelectedValue = "PA" Then ' que tome el folio fijo de la autorización FolioFijo = TxtFolio.Text.ToEntero() ViewState("FolioActual") = FolioFijo ViewState("EstablecioFolio") = True TxtFolio.Text = FolioFijo.ToString() End If If EstablecioFolio AndAlso UsuarioActual.CveEmpresa = 140 Then ' CÓDIGO TEMPORAL 2022/01/17 FolioFijo = TxtFolio.Text.ToEntero() ViewState("FolioActual") = FolioFijo End If Dim TipoDoctoViejo As String = DdlTipoComprobante.SelectedValue DdlTipoComprobante.SelectedValue = TipoDoctoNuevo If Not (EstablecioFolio AndAlso UsuarioActual.TienePermisoProceso(130)) Then TxtFecha.Text = Now.ToString() End If TxtFechaPago.Text = If(TipoDoctoViejo = "Rem" AndAlso EsDiasCreditoFijo, Now.AddDays(DiasCredito), If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza))).ToShortDateString TxtFechaEjecucion.Text = Now.ToString() 'VALIDAR QUE NO SE HAYA REMISIONADO If TipoDoctoViejo = "PA" Then Dim RowVenta As DataRow = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then RowVenta = ObjVentas.DtResultados.Rows(0) End If ObjVentas.Dispose() If RowVenta IsNot Nothing Then Dim CveEstatusAutorizacion As Integer = RowVenta("CveEstatusFactura").ToString().ToEntero() 'SI LA AUTORIZACION ESTA REMISIONADA NO DEBE REMISIONAR DE NUEVO If CveEstatusAutorizacion = 18 Then Alert("La autorización ya está remisionada") Exit Sub End If Else Alert("No se encontró información de la autorización") Exit Sub End If End If If FolioFijo = 0 Then CargaFolios(FacturarDocumentoNuevo:=True) 'RECARGA FOLIOS CON EL NUEVO TIPO DOCTO EmitirImprimir(TipoDoctoViejo) 'MANDA A EMITIR - PROCESO VIEJO End If End Sub #End Region #End Region #Region "ACTUALIZAR FECHA DE VENCIMIENTO" Protected Sub LnkUpdateFechaVencimiento_Click(sender As Object, e As EventArgs) Dim ObjVentas As New ClsVentas Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) Dim ErrorTrans As Boolean = False Dim FechaVencimientoAnterior As String = "" If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then FechaVencimientoAnterior = ObjVentas.DtResultados.Rows(0)("FechaVencimiento").ToString().ToDate.ToShortDateString Else ErrorTrans = True End If End If If FechaVencimientoAnterior = TxtFechaPago.Text Then Alert("La fecha de pago seleccionada es igual que la anterior.", TipoMensaje.MsgAdvertencia) ObjVentas.RollBack() ObjVentas.Dispose() ObjEventos.Dispose() Exit Sub End If If Not ObjVentas.UpdateFechaVencimientoVenta(CveVenta, TxtFechaPago.Text.ToDate) Then ErrorTrans = True End If If Not ObjEventos.AddEventoBitacora($"Se actualizo la fecha de pago. Anterior:{FechaVencimientoAnterior} Actual:{TxtFechaPago.Text}.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then ErrorTrans = True End If If Not ErrorTrans Then ObjVentas.Commit() Alert("Fecha de pago actualizada correctamente.") Else ObjVentas.RollBack() End If ObjVentas.Dispose() ObjEventos.Dispose() End Sub Private Sub BtnRefrescarPagina_Click(sender As Object, e As EventArgs) Handles BtnRefrescarPagina.Click Response.Redirect($"~/Ventas/Ventas.aspx?CveVenta={Me.CveVenta}") End Sub #End Region #Region "U S A D O S" Private Sub CalculaUsados(Optional DtUsadosDevolucion As DataTable = Nothing) If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Cot", "Dev", "PA") Then If ViewState("CargoUsado").ToString() = "False" Then Exit Sub End If Dim DTTamanios As DataTable = GlobalDTAcumTamaños() Dim DTCvePSCostos As DataTable DTCvePSCostos = DTTamanios.FiltraParametros("", "", {"CvePSCargo"}) If Not TmpDT.Columns.Contains("Eliminar") Then TmpDT.Columns.Add("Eliminar", GetType(Integer)) End If Dim TmpDTCalculo As DataRow() = Nothing 'SI ES VENTA NUEVA O SI VA SER DEVOLUCION CONSIDERAR TODOS If Me.CveVenta <= 0 OrElse DtUsadosDevolucion IsNot Nothing Then TmpDTCalculo = TmpDT.Rows.Cast(Of DataRow).ToArray() 'SI ES EDICION DE REMISION SOLO CONSIDERAR LOS PRODUCTOS NUEVOS ElseIf Me.CveVenta > 0 AndAlso DtUsadosDevolucion Is Nothing AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Cot") Then TmpDTCalculo = TmpDT.Select("CveVentaDetalle IS NULL OR CveVentaDetalle <=0") End If For Each drow As DataRow In TmpDTCalculo If DTCvePSCostos IsNot Nothing Then For Each drow2 As DataRow In DTCvePSCostos.Rows If drow("CvePS").ToString().ToEntero() = drow2("CvePSCargo").ToString().ToEntero() Then drow("Eliminar") = 1 Exit For End If Next End If Next Dim TmpDTView As New DataView(TmpDT) TmpDTView.RowFilter = "Eliminar = 1" For Each dRowEliminar As DataRowView In TmpDTView dRowEliminar.Delete() Next 'SI ES VENTA NUEVA O SI VA SER DEVOLUCION CONSIDERAR TODOS If Me.CveVenta <= 0 OrElse DtUsadosDevolucion IsNot Nothing Then TmpDTCalculo = TmpDT.Rows.Cast(Of DataRow).ToArray() 'SI ES EDICION DE REMISION SOLO CONSIDERAR LOS PRODUCTOS NUEVOS ElseIf Me.CveVenta > 0 AndAlso DtUsadosDevolucion Is Nothing AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Cot") Then TmpDTCalculo = TmpDT.Select("CveVentaDetalle IS NULL OR CveVentaDetalle <=0") End If TmpDT.AcceptChanges() Dim CveUnidadMedidaPSA As Integer = -1 Dim UnidadMedidaPSA As String = "Unidad" Dim CveClasificacionPSA As Integer = -1 Dim ClasificacionPSA As String = "" Dim CveSubProyectoPSA As Integer = -1 Dim SubProyectoPSA As String = "" Dim PSPSA As String = "" Dim DTPSTemp As New DataTable '= TmpDT.Clone DTPSTemp.Columns.Add("Cantidad", GetType(Integer)) DTPSTemp.Columns.Add("CveUnidadMedida", GetType(Integer)) DTPSTemp.Columns.Add("UnidadMedida", GetType(String)) DTPSTemp.Columns.Add("CveClasificacion", GetType(Integer)) DTPSTemp.Columns.Add("Clasificacion", GetType(String)) DTPSTemp.Columns.Add("CvePS", GetType(Integer)) DTPSTemp.Columns.Add("PS", GetType(String)) DTPSTemp.Columns.Add("PU", GetType(Decimal)) DTPSTemp.Columns.Add("CveSubProyecto", GetType(Integer)) DTPSTemp.Columns.Add("SubProyecto", GetType(String)) For Each DrowPartidas As DataRow In TmpDTCalculo Dim CveTamanioTemp As Integer = DrowPartidas("CveTamaño").ToString().ToEntero() If CveTamanioTemp > 0 Then Dim DTTamanioTemp As New DataTable Dim CvePsTemp As Integer = DTTamanios.FiltraParametros($"CveTamaño = { CveTamanioTemp } ").Rows(0)("CvePSCargo").ToString().ToEntero() CveSubProyectoPSA = DrowPartidas("CveSubProyecto").ToString().ToEntero() SubProyectoPSA = DrowPartidas("SubProyecto").ToString() Dim ObjProductosServicios As New ClsProductosServicios() If ObjProductosServicios.GetPS(CvePsTemp, -1, UsuarioActual.CveEmpresa) Then CveUnidadMedidaPSA = ObjProductosServicios.CveUnidadMedida CveClasificacionPSA = ObjProductosServicios.CveClasificacion ClasificacionPSA = ObjProductosServicios.Clasificacion UnidadMedidaPSA = ObjProductosServicios.DtResultados.FiltroPrimeroValor("UnidadMedida") PSPSA = ObjProductosServicios.PS End If ObjProductosServicios.Dispose() Dim Cargo As Decimal = DTTamanios.FiltroPrimeroValor("Cargo", $" CveTamaño = { CveTamanioTemp }").ToDecimal If DTPSTemp.FiltraParametros($"CvePs = { CvePsTemp }").Rows.Count > 0 Then For Each dRowUpdate As DataRow In DTPSTemp.Rows If (dRowUpdate("CvePS").ToString().ToEntero() = CvePsTemp) Then dRowUpdate("Cantidad") = dRowUpdate("Cantidad").ToString().ToDecimal + DrowPartidas("Cantidad").ToString().ToDecimal dRowUpdate("PU") = Cargo ' dRowUpdate("Total").ToString().ToDecimal + ImporteCargo End If Next DTPSTemp.AcceptChanges() Else Dim dRowNuevo As DataRow = DTPSTemp.NewRow dRowNuevo("Cantidad") = DrowPartidas("Cantidad").ToString().ToDecimal dRowNuevo("PU") = Cargo dRowNuevo("CveUnidadMedida") = CveUnidadMedidaPSA dRowNuevo("UnidadMedida") = UnidadMedidaPSA dRowNuevo("CveClasificacion") = CveClasificacionPSA dRowNuevo("Clasificacion") = ClasificacionPSA dRowNuevo("CvePS") = CvePsTemp dRowNuevo("PS") = PSPSA dRowNuevo("CveSubProyecto") = DrowPartidas("CveSubProyecto").ToString().ToEntero() dRowNuevo("SubProyecto") = DrowPartidas("SubProyecto").ToString() DTPSTemp.Rows.Add(dRowNuevo) DTPSTemp.AcceptChanges() End If End If Next If DTPSTemp IsNot Nothing AndAlso DTPSTemp.Rows.Count > 0 Then DTPSTemp = DTPSTemp.Select().OrderBy(Function(row) row("PU")).CopyToDataTable() End If For Each drowPsTamaños As DataRow In DTPSTemp.Rows Modalidad = "A" If drowPsTamaños("PU").ToString().ToDecimal > 0 Then Dim CveVentaDetalleDevolucion As Integer = -1 If DtUsadosDevolucion IsNot Nothing AndAlso DtUsadosDevolucion.Rows.Count > 0 Then CveVentaDetalleDevolucion = DtUsadosDevolucion.FiltroPrimeroValor("CveVentaDetalle", $"CvePS = {drowPsTamaños("CvePS").ToString().ToEntero()}").ToEntero() End If AgregarProductoServicio(drowPsTamaños("Cantidad").ToString().ToEntero(), drowPsTamaños("CveUnidadMedida").ToString().ToEntero(), drowPsTamaños("UnidadMedida").ToString(), drowPsTamaños("CveClasificacion").ToString().ToEntero(), drowPsTamaños("Clasificacion").ToString(), drowPsTamaños("CvePS").ToString().ToEntero(), drowPsTamaños("PS").ToString(), "", drowPsTamaños("PU").ToString().ToDecimal, 0, -1, "", drowPsTamaños("CveSubProyecto").ToString().ToEntero(), drowPsTamaños("SubProyecto").ToString(), CveVentaDetalle:=CveVentaDetalleDevolucion, EsCargo:=True) End If Next End If End Sub Private Function GuardarUsados(CveConcepto As Integer, SqlTransaccion As SqlClient.SqlTransaction, factura As Modelos.Factura) As Boolean Dim Resultado As Boolean = True If ClienteEsDistribuidor AndAlso Not factura.EsGarantia Then Dim ObjAcum As New ClsAcumuladores(SqlTransaccion) Dim CvePSPSA As Integer = UsuarioActual.Empresa.Funcionalidad(533).ToEntero For Each drow As DataRow In factura.DtDetalle.Rows If drow("CveTamaño").ToString.ToEntero > 0 And (CvePSPSA <> drow("CvePS").ToString.ToEntero) Then If Not ObjAcum.DistribuidorMovtosAdd(factura.CveCliente, drow("Cantidad").ToString.ToDecimal, drow("CveTamaño").ToString.ToEntero, CveConcepto, factura.CveVenta, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 0D, "", Now) Then Resultado = False Exit For End If End If Next Else Resultado = True End If Return Resultado End Function #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 = 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 = 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 #Region "D E S C U E N T O S X R E M I S I O N D E N O T A D E C R E D I T O" Protected Sub BtnAplicarRemisionNC_Click(sender As Object, e As EventArgs) Me.AplicaRNCXDetalle = False Me.AplicaRNCBonificacionXDetalle = False If ListaRemisionesNC Is Nothing Then ListaRemisionesNC = New List(Of Modelos.Factura) Else ListaRemisionesNC.Clear() End If If ListaNCBonificacion Is Nothing Then ListaNCBonificacion = New List(Of Modelos.Factura) Else ListaNCBonificacion.Clear() End If Dim TotalRemNCAplicado As Decimal = 0 Dim ArrayNC As String() = UsuarioActual.Empresa.Funcionalidad(591).Split(",".ToCharArray()) Dim NCConcepto As Integer = -1 Select Case RblRNCTipo.SelectedValue Case "1" 'CARGOS NCConcepto = ArrayNC(3).ToEntero() Case "2" 'BONIFICACIONES NCConcepto = ArrayNC(4).ToEntero() Case "3" 'AJUSTE/GARANTIAS NCConcepto = ArrayNC(1).ToEntero() End Select 'CARGOS/AJUSTES POR GARANTIA POR PRODUCTO If RblRNCTipo.SelectedValue.Contiene("1", "3") AndAlso ChkMostarProductosRNC.Checked Then Dim TotalAcumulado As Decimal = 0 Me.AplicaRNCXDetalle = True For Each GvRow As GridViewRow In GvRemisionesNCDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim Rows = TmpDTRNCDetalle.Select($"CveVentaDetalleRNC = {GvRow.DataKey("CveVentaDetalleRNC").ToEntero()}") For Each row In Rows row("Cantidad") = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() TmpDTRNCDetalleSelecciondas.Rows.Add(row.ItemArray) Next End If End If Next Dim TerminarCiclo As Boolean = False For Each Dr As DataRow In TmpDTRNCDetalleSelecciondas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows Dim RemNC As New Modelos.Factura(UsuarioActual, Dr("CveVenta").ToString().ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) Dim TotalRNC As Decimal = 0 For Each GvRow As GridViewRow In GvRemisionesNCDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked AndAlso GvRow.DataKey("CveVenta").ToEntero() = Dr("CveVenta").ToString().ToEntero() Then Dim Cantidad As Decimal = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() Dim PU = GvRow.DataKey("PU").ToDecimal() Dim PorcentajeIVA As Decimal = GvRow.DataKey("PorcentajeIVA").ToDecimal() Dim TotalCalculableImpuestos As Decimal = (Cantidad * PU) Dim ImporteIVA As Decimal = (TotalCalculableImpuestos * PorcentajeIVA).RoundSQL(2) Dim TotalRNCDetalle As Decimal = (TotalCalculableImpuestos + ImporteIVA) TotalRNC += TotalRNCDetalle End If End If Next TotalAcumulado += TotalRNC 'SI SE EXECE RESTA AL ULTIMO If TotalAcumulado > LtlSMU.Text.ToDecimal() Then TerminarCiclo = True TotalAcumulado -= TotalRNC TotalRNC = LtlSMU.Text.ToDecimal() - TotalAcumulado End If RemNC.TotalRemNCAplicado = TotalRNC 'MARCA LA VENTA QUE FUE USADA PARA EL FILTRO RemNC.Num3 = DdlVentaUsado.SelectedValue.ToEntero() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaRemisionesNC.Clear() Exit Sub End If ListaRemisionesNC.Add(RemNC) If TerminarCiclo Then Exit For End If Next 'CARGOS/AJUSTES POR GARANTIA POR TOTAL ElseIf RblRNCTipo.SelectedValue.Contiene("1", "3") AndAlso Not ChkMostarProductosRNC.Checked Then For Each GvRow As GridViewRow In GvRemisionesNC.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim RemNC As New Modelos.Factura(UsuarioActual, GvRow.DataKey("CveVenta").ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) RemNC.TotalRemNCAplicado = GvRow.FCTextBox("TxtImporte").Text.ToDecimal() 'MARCA LA VENTA QUE FUE USADA PARA EL FILTRO RemNC.Num3 = DdlVentaUsado.SelectedValue.ToEntero() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaRemisionesNC.Clear() Exit Sub End If ListaRemisionesNC.Add(RemNC) End If End If Next 'SI TIENE ALGUN AJUSTE O GARANTIA If ListaRemisionesNC.Any(Function(RNC) RNC.Num2 = 1) Then For Each RNC In ListaRemisionesNC.Where(Function(x) x.Num2 = 1) Dim Salir As Boolean = False Using ObjAcum As New ClsAcumuladores If ObjAcum.GetGarantiasDetalle(RNC.CveVenta) Then 'SI ES GARANTIA TOTAL If ObjAcum.DtResultados.MAX("PorcentajeAjuste") = "1" Then If ArrayNC.Length > 2 Then NCConcepto = ArrayNC(2).ToEntero() End If Salir = True Else If ArrayNC.Length > 2 Then NCConcepto = ArrayNC(1).ToEntero() End If End If End If End Using If Salir Then Exit For End If Next Else DdlNCPS.Enabled = True End If 'BONIFICACIONES POR PRODUCTO ElseIf RblRNCTipo.SelectedValue.Contiene("2") AndAlso ChkMostarProductosRNCBon.Checked Then Dim TotalAcumulado As Decimal = 0 Me.AplicaRNCXDetalle = True For Each GvRow As GridViewRow In GvRemisionesNCBonDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim Rows = TmpDTRNCDetalle.Select($"CveVentaDetalleRNC = {GvRow.DataKey("CveVentaDetalleRNC").ToEntero()}") For Each row In Rows row("Cantidad") = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() TmpDTRNCDetalleSelecciondas.Rows.Add(row.ItemArray) Next End If End If Next Dim TerminarCiclo As Boolean = False For Each Dr As DataRow In TmpDTRNCDetalleSelecciondas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows Dim RemNC As New Modelos.Factura(UsuarioActual, Dr("CveVenta").ToString().ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) Dim TotalRNC As Decimal = 0 For Each GvRow As GridViewRow In GvRemisionesNCBonDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked AndAlso GvRow.DataKey("CveVenta").ToEntero() = Dr("CveVenta").ToString().ToEntero() Then Dim Cantidad As Decimal = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() Dim PU = GvRow.DataKey("PU").ToDecimal() Dim PorcentajeIVA As Decimal = GvRow.DataKey("PorcentajeIVA").ToDecimal() Dim TotalCalculableImpuestos As Decimal = (Cantidad * PU) Dim ImporteIVA As Decimal = (TotalCalculableImpuestos * PorcentajeIVA).RoundSQL(2) Dim TotalRNCDetalle As Decimal = (TotalCalculableImpuestos + ImporteIVA) TotalRNC += TotalRNCDetalle End If End If Next TotalAcumulado += TotalRNC 'SI SE EXECE RESTA AL ULTIMO If TotalAcumulado > LtlSMUBon.Text.ToDecimal() Then TerminarCiclo = True TotalAcumulado -= TotalRNC TotalRNC = LtlSMUBon.Text.ToDecimal() - TotalAcumulado End If RemNC.TotalRemNCAplicado = TotalRNC 'MARCA LA VENTA QUE FUE USADA PARA EL FILTRO RemNC.Num3 = DdlVentaUsado.SelectedValue.ToEntero() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaRemisionesNC.Clear() Exit Sub End If ListaRemisionesNC.Add(RemNC) BtnAplicarNC.Enabled = True If TerminarCiclo Then Exit For End If Next 'BONIFICACIONES POR TOTAL ElseIf RblRNCTipo.SelectedValue.Contiene("2") AndAlso Not ChkMostarProductosRNCBon.Checked Then For Each GvRow As GridViewRow In GvRemisionesNCBon.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim RemNC As New Modelos.Factura(UsuarioActual, GvRow.DataKey("CveVenta").ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) RemNC.TotalRemNCAplicado = GvRow.FCTextBox("TxtImporte").Text.ToDecimal() RemNC.CveVentaRNCCargo = GvRow.DataKey("CveVentaRNCCargo").ToEntero() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaRemisionesNC.Clear() Exit Sub End If ListaRemisionesNC.Add(RemNC) End If End If Next 'SI SON SOLO BONIFICACIONES GENERA LA NC PRINCIPAL EN BASE A ESAS 'If RblRNCTipo.SelectedValue.ToString() = "2" AndAlso ListaRemisionesNC.Count = 0 Then ' ListaRemisionesNC.AddRange(ListaNCBonificacion) ' ListaNCBonificacion.Clear() 'End If End If Dim DrPSSeleccionado As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=NCConcepto).FiltroPrimero("") If DrPSSeleccionado IsNot Nothing Then DdlNCPS.SelectedValueExistInsert(NCConcepto, DrPSSeleccionado("PS").ToString()) DdlNCPS.Enabled = False End If TxtImportesRemisionesNC.Text = TotalRemNCAplicado.FormatoNumero 'TxtNCImporte.Text = TotalRemNCAplicado.FormatoNumero If ListaRemisionesNC.Count > 0 Then ' si hay opciones seleccionadas, se activa el generar las NCs BtnAplicarNC.Enabled = True End If UpModalRemisionesNC.Update() UpAplicarNC.Update() RegistraScript("CerrarModalRemNC();") End Sub Protected Sub LnkDescuentosRNC_Click(sender As Object, e As EventArgs) RblRNCTipoDesc_SelectedIndexChanged(RblRNCTipoDesc, EventArgs.Empty) RegistraScript("$('#ModalAplicarDescuentoNC').modal('show'); ") End Sub Protected Sub BtnAplicarDesc_Click(sender As Object, e As EventArgs) Try Me.AplicaRNCXDetalle = False Me.AplicaRNCBonificacionXDetalle = False Dim DrPS As DataRow = Nothing Dim ArrayNC As String() = UsuarioActual.Empresa.Funcionalidad(591).Split(",".ToCharArray()) If ArrayNC.Length >= 4 Then Dim CvePSNC As Integer = ArrayNC(3).ToEntero() DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSNC, AplicaParaVenta:=1).FiltroPrimero("") Else Dim CveSATNC = "84111506" DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1).Rows(0) End If If DrPS Is Nothing Then Alert("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.", TipoMensaje.MsgError) Exit Sub End If AplicaNCMasiva = True If ListaNCDesc Is Nothing Then ListaNCDesc = New List(Of Modelos.Factura) Else ListaNCDesc.Clear() End If If ListaNCBonificacion Is Nothing Then ListaNCBonificacion = New List(Of Modelos.Factura) Else ListaNCBonificacion.Clear() End If Dim TotalRemNCAplicado As Decimal = 0 Dim LimiteUsados As Decimal = LblSaldoMaximoUsados.Text.Trim().ToDecimal() If RblRNCTipoDesc.SelectedValue.Contiene("1", "3") Then If ChkMostarProductosRNCDesc.Checked Then TmpDTRNCDetalleSelecciondas.Clear() Dim TotalAcumulado As Decimal = 0 Me.AplicaRNCXDetalle = True For Each GvRow As GridViewRow In GvDescNCCargosDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim Rows = TmpDTRNCDetalle.Select($"CveVentaDetalleRNC = {GvRow.DataKey("CveVentaDetalleRNC").ToEntero()}") For Each row In Rows If GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() > 0 Then row("Cantidad") = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() Dim TotalCalculableImpuestos As Decimal = row("Cantidad").ToString().ToDecimal() * row("PU").ToString().ToDecimal() Dim IVA As Decimal = (TotalCalculableImpuestos * row("PorcentajeIVA").ToString().ToDecimal()).RoundSQL() row("IVA") = IVA row("Total") = (TotalCalculableImpuestos + IVA).RoundSQL TmpDTRNCDetalleSelecciondas.Rows.Add(row.ItemArray) End If Next End If End If Next If TmpDTRNCDetalleSelecciondas.SUMD("Total") > LblSaldoMaximoUsados.Text.ToDecimal() Then Alert($"El importe no debe exceder el saldo maximo utilizable. Importe:{TmpDTRNCDetalleSelecciondas.SUMD("Total"):N2}", TipoMensaje.MsgAdvertencia) TmpDTRNCDetalleSelecciondas.Clear() ListaNCDesc.Clear() Exit Sub End If Dim TerminarCiclo As Boolean = False For Each Dr As DataRow In TmpDTRNCDetalleSelecciondas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows Dim RemNC As New Modelos.Factura(UsuarioActual, Dr("CveVenta").ToString().ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) Dim TotalRNC As Decimal = 0 For Each GvRow As GridViewRow In GvDescNCCargosDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked AndAlso GvRow.DataKey("CveVenta").ToEntero() = Dr("CveVenta").ToString().ToEntero() Then Dim Cantidad As Decimal = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() If Cantidad > 0 Then Dim PU = GvRow.DataKey("PU").ToDecimal() Dim PorcentajeIVA As Decimal = GvRow.DataKey("PorcentajeIVA").ToDecimal() Dim TotalCalculableImpuestos As Decimal = (Cantidad * PU) Dim ImporteIVA As Decimal = (TotalCalculableImpuestos * PorcentajeIVA).RoundSQL(2) Dim TotalRNCDetalle As Decimal = (TotalCalculableImpuestos + ImporteIVA) TotalRNC += TotalRNCDetalle If RemNC.CveVentaRNCCargo <= 0 Then RemNC.CveVentaRNCCargo = GvRow.DataKey("CveVenta").ToEntero() End If Else Alert($"La cantidad seleccionada debe ser mayor a 0.", TipoMensaje.MsgAdvertencia) ListaNCDesc.Clear() ListaNCBonificacion.Clear() Exit Sub End If End If End If Next TotalAcumulado += TotalRNC 'SI SE EXECE RESTA AL ULTIMO If TotalAcumulado > LblSaldoMaximoUsados.Text.ToDecimal() Then TerminarCiclo = True TotalAcumulado -= TotalRNC TotalRNC = LblSaldoMaximoUsados.Text.ToDecimal() - TotalAcumulado End If RemNC.TotalRemNCAplicado = TotalRNC TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaNCDesc.Clear() Exit Sub End If ListaNCDesc.Add(RemNC) If TerminarCiclo Then Exit For End If Next If ListaNCDesc.Sum(Function(x) x.TotalRemNCAplicado) > LblSaldoMaximoUsados.Text.ToDecimal() Then Alert($"El importe no debe exceder el saldo maximo utilizable", TipoMensaje.MsgAdvertencia) ListaNCDesc.Clear() TmpDTRNCDetalleSelecciondas.Clear() Exit Sub End If Else For Each GvRow As GridViewRow In GvDescNCCargos.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim RemNC As New Modelos.Factura(UsuarioActual, GvRow.DataKey("CveVenta").ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) RemNC.TotalRemNCAplicado = GvRow.FCTextBox("TxtImporte").Text.ToDecimal() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaNCDesc.Clear() Exit Sub End If ListaNCDesc.Add(RemNC) End If End If Next End If 'SI TIENE ALGUN AJUSTE O GARANTIA If ListaNCDesc.Any(Function(RNC) RNC.Num2 = 1) Then For Each RNC In ListaNCDesc.Where(Function(x) x.Num2 = 1) Dim Salir As Boolean = False Dim NCAjuste As Integer = -1 Dim NCGarantiaTotal As Integer = -1 If ArrayNC.Length > 2 Then NCAjuste = ArrayNC(1).ToEntero() NCGarantiaTotal = ArrayNC(2).ToEntero() End If Using ObjAcum As New ClsAcumuladores If ObjAcum.GetGarantiasDetalle(RNC.CveVenta) Then 'SI ES GARANTIA TOTAL If ObjAcum.DtResultados.MAX("PorcentajeAjuste") = "1" Then DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=NCGarantiaTotal, AplicaParaVenta:=1).Rows(0) Salir = True Else DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=NCAjuste, AplicaParaVenta:=1).Rows(0) End If End If End Using If Salir Then Exit For End If Next End If 'VERIFICA EL LIMITE DE LOS USADOS If TotalRemNCAplicado > LimiteUsados Then Alert($"La suma de las remisiones de nota de crédito de tipo 'Cargo' no debe superar el total de Usados.
    Total RNC: {TotalRemNCAplicado:N2}.
    Total Usados: {LimiteUsados:N2}", TipoMensaje.MsgAdvertencia) ListaNCDesc.Clear() Exit Sub End If 'BONIFICACIONES If ChkMostarProductosRNCDesBonificacion.Checked Then TmpDTRNCBonificacionDetalleSeleccionadas.Clear() Me.AplicaRNCBonificacionXDetalle = True For Each GvRow As GridViewRow In GvDescNCBonDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim Rows = TmpDTRNCBonificacionDetalle.Select($"CveVentaDetalleRNC = {GvRow.DataKey("CveVentaDetalleRNC").ToEntero()}") For Each row In Rows If GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() > 0 Then row("Cantidad") = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() Dim TotalCalculableImpuestos As Decimal = row("Cantidad").ToString().ToDecimal() * row("PU").ToString().ToDecimal() Dim IVA As Decimal = (TotalCalculableImpuestos * row("PorcentajeIVA").ToString().ToDecimal()).RoundSQL() row("IVA") = IVA row("Total") = (TotalCalculableImpuestos + IVA).RoundSQL TmpDTRNCBonificacionDetalleSeleccionadas.Rows.Add(row.ItemArray) End If Next End If End If Next Dim TerminarCiclo As Boolean = False For Each Dr As DataRow In TmpDTRNCBonificacionDetalleSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows Dim RemNC As New Modelos.Factura(UsuarioActual, Dr("CveVenta").ToString().ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) Dim TotalRNC As Decimal = 0 For Each GvRow As GridViewRow In GvDescNCBonDetalle.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked AndAlso GvRow.DataKey("CveVenta").ToEntero() = Dr("CveVenta").ToString().ToEntero() Then Dim Cantidad As Decimal = GvRow.FCTextBox("TxtCantidadRNC").Text.ToDecimal() If Cantidad > 0 Then Dim PU = GvRow.DataKey("PU").ToDecimal() Dim PorcentajeIVA As Decimal = GvRow.DataKey("PorcentajeIVA").ToDecimal() Dim TotalCalculableImpuestos As Decimal = (Cantidad * PU) Dim ImporteIVA As Decimal = (TotalCalculableImpuestos * PorcentajeIVA).RoundSQL(2) Dim TotalRNCDetalle As Decimal = (TotalCalculableImpuestos + ImporteIVA) TotalRNC += TotalRNCDetalle If RemNC.CveVentaRNCCargo <= 0 Then RemNC.CveVentaRNCCargo = GvRow.DataKey("CveVenta").ToEntero() End If Else Alert($"La cantidad seleccionada debe ser mayor a 0.", TipoMensaje.MsgAdvertencia) ListaNCDesc.Clear() ListaNCBonificacion.Clear() Exit Sub End If End If End If Next RemNC.TotalRemNCAplicado = TotalRNC TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaNCBonificacion.Clear() Exit Sub End If ListaNCBonificacion.Add(RemNC) If TerminarCiclo Then Exit For End If Next Else For Each GvRow As GridViewRow In GvDescNCBonificaciones.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim RemNC As New Modelos.Factura(UsuarioActual, GvRow.DataKey("CveVenta").ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) RemNC.TotalRemNCAplicado = GvRow.FCTextBox("TxtImporte").Text.ToDecimal() RemNC.CveVentaRNCCargo = GvRow.DataKey("CveVentaRNCCargo").ToEntero() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaNCBonificacion.Clear() Exit Sub End If ListaNCBonificacion.Add(RemNC) End If End If Next End If ElseIf RblRNCTipoDesc.SelectedValue.Contiene("2") Then For Each GvRow As GridViewRow In GvDescNCBonificaciones.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim RemNC As New Modelos.Factura(UsuarioActual, GvRow.DataKey("CveVenta").ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) RemNC.TotalRemNCAplicado = GvRow.FCTextBox("TxtImporte").Text.ToDecimal() RemNC.CveVentaRNCCargo = GvRow.DataKey("CveVentaRNCCargo").ToEntero() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaNCBonificacion.Clear() Exit Sub End If ListaNCBonificacion.Add(RemNC) End If End If Next 'Dim LimiteBonficaciones As Decimal = LblSaldoMaximoBonificacion.Text.Trim().ToDecimal() ''VERIFICA EL LIMITE DE LOS USADOS 'If ListaNCBonificacion.Sum(Function(x) x.TotalRemNCAplicado) > LimiteBonficaciones Then ' Alert($"La suma de las remisiones de nota de crédito de tipo 'Bonificación' no debe superar el limite.
    Total RNC: {ListaNCBonificacion.Sum(Function(x) x.TotalRemNCAplicado):N2}.
    Total Usados: {LimiteUsados:N2}", TipoMensaje.MsgAdvertencia) ' ListaNCDesc.Clear() ' ListaNCBonificacion.Clear() ' Exit Sub 'End If 'SI SON SOLO BONIFICACIONES GENERA LA NC PRINCIPAL EN BASE A ESAS If RblRNCTipoDesc.SelectedValue.ToString() = "2" AndAlso ListaNCDesc.Count = 0 Then ListaNCDesc.AddRange(ListaNCBonificacion) ListaNCBonificacion.Clear() End If End If Dim TotalProntoPago As Decimal = 0 'SOLO APLICA SI EL PAGO ES DE CONTADO If RBLPago.SelectedValue = "2" Then TotalProntoPago = TmpDT.SUM("ImporteProntoPago").ToDecimal End If If TotalRemNCAplicado > TxtTotal.Text.ToDecimal() Then Alert($"La suma de las remisiones de nota de crédito no debe superar el total de la factura.
    Total RNC: {TotalRemNCAplicado:N2}.
    Total Factura: {TxtTotal.Text.ToDecimal():N2}", TipoMensaje.MsgAdvertencia) ListaNCDesc.Clear() ListaNCBonificacion.Clear() Exit Sub End If HdnTotalRNC.Value = TotalRemNCAplicado.ToString() LblDescuentosRNC.Text = TotalRemNCAplicado.FormatoNumero LblTotalAPagar.Text = (TxtTotal.Text.ToDecimal() - TotalRemNCAplicado - TotalProntoPago).FormatoNumero Dim CvePS = DrPS("CvePS").ToString().ToEntero() AplicarNC(CvePS, NCDescuento:=True) Catch ex As Exception OnError("Ocurrió un error al aplicar remisiones de nota de crédito", ex) End Try UpPS.Update() RegistraScript("$('#ModalAplicarDescuentoNC').modal('hide'); ") End Sub Protected Sub PreparaNCDescuento(ByRef factura As Modelos.Factura) If TmpDTDescNC IsNot Nothing Then factura.DtDetalle = TmpDTDescNC '**** IMPUESTOS LOCALES Dim TotalSubTotal As Decimal = TmpDTDescNC.SUM("TotalImporte").ToDecimal Dim TotalDescuentos As Decimal = TmpDTDescNC.SUM("Descuento").ToDecimal Dim TotalIVA As Decimal = TmpDTDescNC.SUM("ImporteIVA").ToDecimal Dim TotalIEPS As Decimal = TmpDTDescNC.SUM("ImporteIEPS").ToDecimal Dim TotalRetIVA As Decimal = TmpDTDescNC.SUM("ImporteRetIVA").ToDecimal Dim TotalRetISR As Decimal = TmpDTDescNC.SUM("ImporteRetISR").ToDecimal Dim Total As Decimal = 0 Dim TotalImpuestosLocales As Decimal = 0 Total = (TotalSubTotal - TotalDescuentos + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) factura.SubTotal = TotalSubTotal factura.Descuento = TotalDescuentos factura.IVA = TotalIVA factura.IEPS = TotalIEPS factura.RetIVA = TotalRetIVA factura.RetISR = TotalRetISR factura.Total = Total End If End Sub Protected Sub PreparaNCBonificacion(ByRef factura As Modelos.Factura) If ListaNCBonificacion IsNot Nothing AndAlso ListaNCBonificacion.Count > 0 Then factura.DtDetalle = Me.TmpDTDescNCBonificacion '**** IMPUESTOS LOCALES Dim TotalSubTotal As Decimal = TmpDTDescNCBonificacion.SUM("TotalImporte").ToDecimal Dim TotalDescuentos As Decimal = TmpDTDescNCBonificacion.SUM("Descuento").ToDecimal Dim TotalIVA As Decimal = TmpDTDescNCBonificacion.SUM("ImporteIVA").ToDecimal Dim TotalIEPS As Decimal = TmpDTDescNCBonificacion.SUM("ImporteIEPS").ToDecimal Dim TotalRetIVA As Decimal = TmpDTDescNCBonificacion.SUM("ImporteRetIVA").ToDecimal Dim TotalRetISR As Decimal = TmpDTDescNCBonificacion.SUM("ImporteRetISR").ToDecimal Dim Total As Decimal = 0 Dim TotalImpuestosLocales As Decimal = 0 Total = (TotalSubTotal - TotalDescuentos + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales) factura.SubTotal = TotalSubTotal factura.Descuento = TotalDescuentos factura.IVA = TotalIVA factura.IEPS = TotalIEPS factura.RetIVA = TotalRetIVA factura.RetISR = TotalRetISR factura.Total = Total End If End Sub #End Region Protected Sub BtnModalAplicarRemisionesNC_Click(sender As Object, e As EventArgs) ChkMostarProductosRNC_CheckedChanged(ChkMostarProductosRNC, EventArgs.Empty) RegistraScript("$('#ModalAplicarRemisionesNC').modal({backdrop: 'static', keyboard: false });") End Sub #Region "P O L I Z A - V I R T U A L" Private Sub CargaCodigoUnico() If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem") Then Dim ObjAcum As New ClsAcumuladores If ObjAcum.GetPolizasVirtuales(Me.CveVenta) AndAlso ObjAcum.DtResultados.Rows.Count > 0 Then Dim RowPoliza As DataRow = ObjAcum.DtResultados.Rows(0) If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then GvCodigosUnicos.DataSource = ObjAcum.DtResultados DivCodigosUnicos.Visible = True End If If Not CBool(RowPoliza("Enviada").ToString()) Then LnkEnviarPolizaVirtual.Visible = True End If End If ObjAcum.Dispose() GvCodigosUnicos.DataBind() End If End Sub Protected Sub GeneraPolizaVentaWS(ObjFactura As Modelos.Factura) Try If UsuarioActual.CveUsuario.Contiene(3491) Then Exit Sub End If 'TipoPoliza: 01 Venta, 02 Ajuste, 03 Garantía Dim TipoPoliza As Integer = 0 For Each Row As GridViewRow In GvCodigosUnicos.Rows If Row.RowType = DataControlRowType.DataRow Then Dim CvePolizaVirtual As Integer = Row.DataKey("CvePolizaVirtual").ToEntero() Dim obj As New Modelos.MPolizaVentaWS 'DATOS DEL CLIENTE obj.customer_name = ObjFactura.Cliente.Nombre obj.customer_last_name1 = "." obj.customer_last_name2 = "" obj.customer_birthday = Nothing obj.customer_phone = ObjFactura.Cliente.Telefono obj.customer_email = ObjFactura.Cliente.Mail obj.customer_gender = "03" 'OTRO GENERO obj.customer_advertising = False obj.customer_car_brand = Row.DataKey("IdMarcaAuto").ToString().Trim() obj.customer_car_model = Row.DataKey("IdModeloAuto").ToString().Trim() obj.customer_car_year = Row.DataKey("AnioVehiculo").ToString().ToEntero() 'DATOS DE VENTA obj.sale_date = ObjFactura.Fecha obj.sale_paidby = "01" obj.sale_type = "01" 'PISO obj.sale_type_service = "0" & Row.DataKey("TipoServicio").ToString().Trim() obj.sale_total = Row.DataKey("Total").ToString().ToDecimal() obj.sale_discount = Row.DataKey("Descuento").ToString().ToDecimal() obj.sale_id = ObjFactura.CveVenta.ToString() 'DATOS DEL PRODUCTO obj.product_code = Row.DataKey("IdProductoPolizaVirtual").ToString().Trim() obj.product_unique_code = Row.FCTextBox("TxtCodigoUnico").Text.Trim() 'se indique el código único de la batería. (SERIE LOTE) obj.product_sale_type = "0" & Row.DataKey("TipoPoliza").ToString().Trim() 'DATOS DE USADO obj.used_product = CBool(Row.DataKey("TieneUsado").ToString()) If obj.used_product Then Dim FechaUsado As DateTime = Row.DataKey("FechaUsado").ToString().ToDateTime() obj.used_brand = Row.DataKey("IdMarcaUsado").ToString().Trim() 'MARCAR DEL USADO obj.used_bci = Row.DataKey("IdBCI").ToString().Trim() 'VALOR DEL BCI obj.used_month = FechaUsado.Month obj.used_year = FechaUsado.Year obj.used_sale_date = FechaUsado End If EnviarPolizaVentaWS(obj, CvePolizaVirtual) End If Next Catch ex As Exception OnError("Ocurrió un error al generar la poliza virtual", ex) End Try End Sub Protected Function EnviarPolizaVentaWS(obj As Modelos.MPolizaVentaWS, CvePolizaVirtual As Integer) As Boolean Dim Retorno As Boolean = False Dim Respuesta As String = "[]" Dim User As String = "" Dim Password As String = "" If UsuarioActual.Empresa.FacturaProduccion Then User = "cslth.2809@jcilink.com" Password = "ff31580a95f36b51ad27f970428b77a5a9245076" Else User = "cslth.7777@lth.com" Password = "ff31580a95f36b51ad27f970428b77a5a9245076" End If Try Using wc As New HttpClient() Dim Url = New Uri("http://polizavirtual.com.mx/webservice/api/Venta") Dim Parametros = New List(Of KeyValuePair(Of String, String)) Parametros.Add(New KeyValuePair(Of String, String)("User", User)) Parametros.Add(New KeyValuePair(Of String, String)("password", Password)) Parametros.Add(New KeyValuePair(Of String, String)("customer_name", obj.customer_name)) Parametros.Add(New KeyValuePair(Of String, String)("customer_last_name1", obj.customer_last_name1)) Parametros.Add(New KeyValuePair(Of String, String)("customer_last_name2", obj.customer_last_name1)) Parametros.Add(New KeyValuePair(Of String, String)("customer_birthday", obj.customer_birthday.ToString("yyyy-MM-dd HH:mm:ss"))) Parametros.Add(New KeyValuePair(Of String, String)("customer_phone", obj.customer_phone)) Parametros.Add(New KeyValuePair(Of String, String)("customer_email", obj.customer_email)) Parametros.Add(New KeyValuePair(Of String, String)("customer_gender", obj.customer_gender)) Parametros.Add(New KeyValuePair(Of String, String)("customer_advertising", obj.customer_advertising.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("sale_date", obj.sale_date.ToString("yyyy-MM-dd HH:mm:ss"))) Parametros.Add(New KeyValuePair(Of String, String)("sale_paidby", obj.sale_paidby)) Parametros.Add(New KeyValuePair(Of String, String)("sale_type", obj.sale_type)) Parametros.Add(New KeyValuePair(Of String, String)("sale_type_service", obj.sale_type_service)) Parametros.Add(New KeyValuePair(Of String, String)("product_code", obj.product_code)) Parametros.Add(New KeyValuePair(Of String, String)("product_unique_code", obj.product_unique_code)) Parametros.Add(New KeyValuePair(Of String, String)("product_sale_type", obj.product_sale_type)) Parametros.Add(New KeyValuePair(Of String, String)("sale_total", obj.sale_total.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("used_product", obj.used_product.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("used_brand", obj.used_brand)) Parametros.Add(New KeyValuePair(Of String, String)("used_bci", obj.used_bci)) Parametros.Add(New KeyValuePair(Of String, String)("used_month", obj.used_month.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("used_year", obj.used_year.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("used_sale_date", obj.used_sale_date.ToString("yyyy-MM-dd HH:mm:ss"))) Parametros.Add(New KeyValuePair(Of String, String)("customer_car_brand", obj.customer_car_brand.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("customer_car_model", obj.customer_car_model.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("customer_car_year", obj.customer_car_year.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("sale_discount", obj.sale_discount.ToString())) Parametros.Add(New KeyValuePair(Of String, String)("sale_id", obj.sale_id.ToString())) Dim content As New FormUrlEncodedContent(Parametros) Dim response = wc.PostAsync(Url, content).Result Respuesta = response.Content.ReadAsStringAsync().Result Dim resp = JArray.Parse(Respuesta) If resp.Count > 0 Then Dim Msg As New StringBuilder() Msg.AppendFormat("Mensaje Póliza Virtual: {0} - Código: {1}", resp(0)("Descripcion").ToString(), resp(0)("Codigo")) If resp(0)("Codigo").ToString().Contiene("500", "501", "502", "503", "504", "505", "506", "507", "508", "510") Then Retorno = True Dim ObjAcum As New ClsAcumuladores If ObjAcum.UpdateEnvioPolizaVirtual(CvePolizaVirtual, True, Now, obj.product_unique_code, resp(0)("Descripcion").ToString()) Then Alert(Msg.ToString(), TipoMensaje.MsgInformacion) End If ObjAcum.Dispose() Else Dim ObjAcum As New ClsAcumuladores If ObjAcum.UpdateEnvioPolizaVirtual(CvePolizaVirtual, False, Now, obj.product_unique_code, resp(0)("Descripcion").ToString()) Then Alert(Msg.ToString(), TipoMensaje.MsgAdvertencia) End If ObjAcum.Dispose() End If Dim ObjEventos As New ClsOIEventos() If Not ObjEventos.AddEventoBitacora(Msg.ToString(), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Me.CveVenta) Then ErrorList.Add("Ocurrió un error al agregar la bitacora de Póliza Virtual.") End If ObjEventos.Dispose() Msg.Clear() Else Alert("No se envió la poliza virtual", TipoMensaje.MsgAdvertencia) End If End Using Catch ex As Exception ex.GuardaLog(ex.Message) End Try Return Retorno End Function Protected Sub LnkEnviarPolizaVirtual_Click(sender As Object, e As EventArgs) If UsuarioActual.Empresa.Funcionalidad(576) = "1" AndAlso DdlTipoComprobante.SelectedValue.Contains("Rem") Then CreaObjetosVenta() GeneraPolizaVentaWS(ObjFactura) End If 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 = 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("4") AndAlso CBool(RowServicio("EsOutSourcing").ToString()) Then tClienteRetIVA = 0.06D 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").ToDecimal().FormatoNumero(2) Dim PorcentajeRetIVA = (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 Protected Sub TxtFecha_TextChanged(sender As Object, e As EventArgs) 'SI USUARIO USA AMORTIZACIÓN CONTABLE, se carga las tablas para usarlas mas adelante If UsuarioActual.Empresa.TipoContabilidad = 2 AndAlso UsuarioActual.CveEmpresa = 48 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, TxtFecha.Text.ToDateTime().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 End Sub 'Protected Sub LnkDescargarFacturaPrueba_Click(sender As Object, e As EventArgs) ' 'Dim Hilo As New System.Threading.Thread(Sub() DescargarFactura(Me.CveVenta, UsuarioActual.CveEmpresa)) ' 'Hilo.Start() ' Dim facBytes = DescargarFactura(Me.CveVenta, UsuarioActual.CveEmpresa) ' ImprimirbytesPDF(facBytes, "Factura") 'End Sub 'Private Function DescargarFactura(CveVenta As Integer, CveEmpresa As Integer) As Byte() ' Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?P={1}", "https://sig.adssistemas.mx/", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta)))) ' Dim File As Byte() = Nothing ' Try ' Using httpClient = New HttpClient() ' httpClient.Timeout = New TimeSpan(0, 15, 0) ' Using request = New HttpRequestMessage(HttpMethod.Get, Url) ' request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CVEUSUARIO=100", CveEmpresa, DateTime.UtcNow.Ticks))) ' Dim response = httpClient.SendAsync(request).Result ' If 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 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 = 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 = New HttpClient() httpClient.Timeout = New TimeSpan(0, 2, 0) Using request = 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 LnkGenerarOC_Click(sender As Object, e As EventArgs) Response.Redirect($"~/OC/OC.aspx?CveCotizacion={Me.CveVenta}&Tipo=OC") End Sub 'Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ' Dim ObjVentas As New ClsVentas ' ObjVentas.IniciaTransacSQL() ' Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) ' Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) ' Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) ' Dim ObjAC As ClsContPAQi = Nothing ' If Not RegeneracionPolizas(ObjVentas, ObjAC, ObjConta, ObjBancos) Then ' ObjVentas.Commit() ' If ObjAC IsNot Nothing Then ObjAC.Commit() ' Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();") ' End If ' ObjVentas.Dispose() ' ObjConta.Dispose() ' ObjBancos.Dispose() ' If ObjAC IsNot Nothing Then ObjAC.Dispose() 'End Sub Partial Class Descuentos Public Consec As Integer Public ImporteDescuento As Decimal = 0 Public CvePromocionDetalle As Integer = -1 Public PU As Decimal = 0 Public EsPUModificado As Boolean = False Public ImporteProntoPago As Decimal = 0 Public NombrePromo As String = "" Public CveMarca As Integer = -1 Public ObsDescuento As String = "" End Class Protected Sub btnupEventoBitacora_Click(sender As Object, e As EventArgs) CargaEventoBitacora() End Sub Private Sub MostrarOpcionesPaqueteria() Dim mostrarOpcionesPaq As Boolean = DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") And UsuarioActual.Empresa.Funcionalidad(280) = "1" trPaqueteriaOpciones.Visible = mostrarOpcionesPaq trPaqueteriOpcionesLabel.Visible = mostrarOpcionesPaq trPaqueteriaDirectaLabel.Visible = False End Sub Private Sub NotificarPaqueteria() 'Dim DtVendedores As DataTable = GlobalDTVendedores(UsuarioActual.CveEmpresa) 'Dim CorreoVendedor As String = DtVendedores.FiltroPrimeroValor("Correo", String.Format("CveVendedor = {0}", DdlVendedor.SelectedValue)) 'Dim CorreoVendedorAdicional As String = DtVendedores.FiltroPrimeroValor("CorreoAdicionalNotificaciones", String.Format("CveVendedor = {0}", DdlVendedor.SelectedValue)) 'Dim CorreoCliente As String = Mail 'Dim CorreoClienteAlmacen As String = CorreoEntregaAlmacen 'Dim CorreoNotificacionCliente As String = MailCC 'Dim CorreosCC As String = String.Format("{0};{1};{2};{3}", CorreoVendedor, CorreoVendedorAdicional, CorreoCliente, CorreoNotificacionCliente) 'Dim LogCorreo As String = String.Format("{0} -- {1} --- {2}", "Tipo de entrega", CorreoClienteAlmacen, CorreosCC) 'LogCorreo.GuardaLog 'Dim MailCls As New ClsSisMail 'MailCls.SendMail(ClsPaginas.EmpresaNotificaciones, CorreoVendedor, "Entrega en mostrador", "Pendiente", CorreosCC) 'MailCls = Nothing 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 DdlVendedor.Enabled = True 'Observaciones TxtObsFact.Enabled = True TxtOrdenCompra.Enabled = True TxtPedidoContrato.Enabled = True TxtObsAlmacen.Enabled = True RblPaqueteria.Enabled = True DdlLineaAdicional.Enabled = True LnkUpdateLineaAdicional.Visible = True 'Acciones BtnEditar.Text = "Guardar" UpParametros.Update() UPObservaciones.Update() UpFacturar.Update() UPCondicionesPago.Update() End Sub Private Sub GuardarValoresEditados() Dim ObjVentas As New ClsVentas() If ObjVentas.UpdateObservacionesVenta(CveVenta, UsuarioActual.CveEmpresa, DdlVendedor.SelectedValue.ToEntero(), TxtObsFact.Text, RblPaqueteria.SelectedValue.ToEntero(), TxtCorreoNotificaciones.Text, TxtObsAlmacen.Text, TxtPedidoContrato.Text, TxtOrdenCompra.Text, TxtFechaPago.Text) Then CargaVenta() BtnEditar.Text = "Editar" Alert("Actualizado correctamente") UpParametros.Update() UPObservaciones.Update() UpFacturar.Update() End If ObjVentas.Dispose() 'REGENERAR EL PDF Try Dim strURLHOST = String.Format("{0}://{1}:{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port) Dim Hilo As New System.Threading.Thread(Sub() RegenerarPDF(CveVenta, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario, strURLHOST)) Hilo.Start() 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") Then LBNotaCredito.Visible = False UpnTools.Update() Retorno = True End If Return Retorno End Function #Region "Auxiliar" Private Sub CargarSaldoAuxiliar(CveCliente As Integer) CargaAuxiliarClienteCxC(CveCliente, CveVenta) End Sub Private Sub CargaAuxiliarClienteCxC(CveCliente As Integer, CveVenta As Integer) Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetCxCClienteAuxiliar(CveCliente, CveVenta) Then ' DTDatos = ObjMovtos.DtResultados GVAuxiliar.DataSource = ObjMovtos.DtResultados Else GVAuxiliar.DataSource = Nothing End If ObjMovtos.Dispose() GVAuxiliar.DataBind() End Sub ''Protected Sub BtnCancelarAux_Click(sender As Object, e As EventArgs) '' 'AgregaPolizaNegativo(CvePrePolizaNegativa) ''End Sub ''Private Sub AgregaPolizaNegativo(CvePrePoliza As Integer) '' Dim ObjContabilidad As New ClsContabilidad '' Dim TieneError As Boolean = False '' ObjContabilidad.IniciaTransacSQL() '' Dim CvePrePolizaNueva As Integer = ObjContabilidad.AddPrePolizasNegativa(CvePrePoliza, UsuarioActual.CveUsuario, TxtConceptoCancelacion.Text, UsuarioActual.CveEmpresa, TxtFechaCancelacion.Text.ToDate) '' If Not CvePrePolizaNueva > 0 Then '' TieneError = True '' End If '' If Not TieneError Then '' ObjContabilidad.Commit() '' Dim Str As New StringBuilder '' Str.Append("Se agrego la póliza de cancelación correctamente.
    ") '' RegistraScript(" $('#DivCancelar').modal('hide'); ") '' If UsuarioActual.Empresa.Funcionalidad(200) = "1" Then '' If ObjContabilidad.ContabilizarPrePoliza(CvePrePolizaNueva, UsuarioActual.CveUsuario, UsuarioActual.Empresa) Then '' Str.AppendFormat("Ver Poliza", ObjContabilidad.ContaIdPoliza) '' End If '' End If '' Alert(Str.ToString) '' Else '' ObjContabilidad.RollBack() '' End If '' ObjContabilidad.Dispose() '' CargarSaldoAuxiliar(CveCliente) ''End Sub Protected Sub GVAuxiliar_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAuxiliar.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex = 0 Then e.Row.BackColor = Drawing.Color.LightGray e.Row.FCLiteral("LtlFechaMovto").Text = "Totales: " e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(0).ColumnSpan = 2 e.Row.Cells(1).Visible = False e.Row.Cells(4).ColumnSpan = 3 e.Row.Cells(5).Visible = False e.Row.Cells(6).Visible = False e.Row.Cells(7).Visible = False e.Row.Cells(8).Visible = False ElseIf e.Row.RowIndex = 1 Then e.Row.Cells(0).Width = Unit.Pixel(95) e.Row.Cells(1).Width = Unit.Pixel(180) e.Row.Cells(2).Width = Unit.Pixel(80) e.Row.Cells(3).Width = Unit.Pixel(80) e.Row.Cells(4).Width = Unit.Pixel(83) e.Row.Cells(5).Width = Unit.Pixel(93) e.Row.Cells(6).Width = Unit.Pixel(85) e.Row.Cells(7).Width = Unit.Pixel(95) e.Row.Cells(8).Width = Unit.Pixel(70) End If e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Left e.Row.Cells(2).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Left If e.Row.FCLiteral("LtlContabilizado").Text = "Si" Then Dim Liga As String = String.Format("", e.Row.DBCampo("IdPoliza")) e.Row.FCLiteral("LtlPoliza").Text = String.Format("{0}{1}", Liga, e.Row.DBCampo("Poliza")) End If If e.Row.DBCampo("CveConceptoContable").ToEntero.Contiene(2) AndAlso e.Row.DBCampo("CvePersonal").ToEntero > 0 Then Dim Liga As String = String.Format("", e.Row.DBCampo("CvePersonal")) e.Row.FCLiteral("LtlConcepto").Text = String.Format("{0}{1}", Liga, e.Row.DBCampo("ConceptoContable")) End If If e.Row.DBCampo("TipoReferencia").ToEntero = 1 Then e.Row.FCHyperLink("HplReferencia").NavigateUrl = $"/Bancos/IE.aspx?CveIE={e.Row.DBCampo("CveReferencia").ToEntero}" ElseIf e.Row.DBCampo("TipoReferencia").ToEntero = 2 Then e.Row.FCHyperLink("HplReferencia").NavigateUrl = $"/Ventas/Ventas.aspx?CveVenta={e.Row.DBCampo("CveReferencia").ToEntero}" End If If e.Row.DBCampo("CveConceptoContable").ToEntero.Contiene(275) AndAlso e.Row.DBCampo("CveVenta").ToEntero > 0 Then e.Row.FCHyperLink("HplReferencia").NavigateUrl = $"/Ventas/Ventas.aspx?CveVenta={e.Row.DBCampo("CveVenta").ToEntero}" End If End If End Sub Function ValidaVentaContratoObra() As Boolean Dim Respuesta As Boolean = False If EscontratoObra AndAlso PorAmortizacionAnticipo > 0 Then ' si es contrato de obra y tiene amortización de anticipo If DdlTipoComprobante.SelectedValue = "Ing" Then If DdlEstimacionesObra.SelectedValue.ToEntero > 0 Then Dim ImporteAmortizarFinal As Decimal = 0 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 ImporteAmortizarFinal = ImporteAmortizarFinal + row2.FCTextBox($"TxtAnticipo{actualindex}").Text.ToDecimal End If actualindex = actualindex + 1 Next End If If ImporteAmortizarFinal > 0 Then Respuesta = True Else Respuesta = False Alert("Debe de seleccionar un importe de amortización.", TipoMensaje.MsgAdvertencia) End If Else Respuesta = False Alert("Se selecciono un contrato de obra, para continuar seleccione una estimación.", TipoMensaje.MsgAdvertencia) End If ElseIf DdlTipoComprobante.SelectedValue = "Ant" Or DdlTipoComprobante.SelectedValue = "Egs" Then Respuesta = True Else Alert("Tipo de documento no valido para contratos de obra.", TipoMensaje.MsgAdvertencia) Respuesta = False End If Else Respuesta = True End If Return Respuesta End Function #End Region Partial Class VentasBonificaciones Public CveVentaRNCCargo As Integer = -1 Public CveVentaBonificacion As Integer = -1 Public ImporteBonificacion As Decimal = 0 Public IVABonificacion As Decimal = 0 End Class #Region " N O T A - D E - C R E D I T O - P R O N T O - P A G O" Private Function GenerarNCProntoPago(SqlTransaccion As SqlClient.SqlTransaction, ByRef ObjCliente As ClsClientes, ByRef ObjConta As ClsContPAQi, ObjFactura As Modelos.Factura) As MensajeProntoPago Dim Retorno As New MensajeProntoPago Dim Resp As New Modelos.Factura.MMensajeFactura Dim ObjFacturaProntoPago As Modelos.Factura = Nothing Try ObjFacturaProntoPago = New Modelos.Factura(UsuarioActual) ObjFacturaProntoPago.TipoMensajeRespuesta = Modelos.TipoMensajeRespuesta.TextoLimpio ObjFacturaProntoPago.CveUsuario = UsuarioActual.CveUsuario ObjFacturaProntoPago.UsuarioCreo = UsuarioActual.Usuario Dim CveSubProyecto As Integer = ObjFactura.CveSubProyecto Dim CveMoneda As Integer = ObjFactura.CveMoneda Dim CveCliente As Integer = ObjFactura.CveCliente Dim Folio As Integer = -1 Dim Serie As String = "-1" ObjFacturaProntoPago.CveEmpresa = UsuarioActual.CveEmpresa ObjFacturaProntoPago.TipoCambio = If(CveMoneda = 1, 1, GlobalTipoCambio(Now).FormatoNumero(4).ToDecimal()) ObjFacturaProntoPago.ConvertirPesos = False ObjFacturaProntoPago.CveMoneda = CveMoneda ObjFacturaProntoPago.Moneda = GlobalDTMonedas.FiltroPrimeroValor("Moneda", $"CveMoneda = {CveMoneda}") ObjFacturaProntoPago.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {CveMoneda}") ObjFacturaProntoPago.Serie = Serie ObjFacturaProntoPago.Folio = Folio ObjFacturaProntoPago.Fecha = Now ObjFacturaProntoPago.CvePrePoliza = -1 ObjFacturaProntoPago.CveMetodoPago = 0 ObjFacturaProntoPago.CondicionesPago = 0 ' 0 - Contado, 1 - Credito (CHECAR) ObjFacturaProntoPago.FormaPago = 0 ObjFacturaProntoPago.TipoDocto = "Egs" ObjFacturaProntoPago.Fecha = Now If UsuarioActual.Empresa.Funcionalidad(350) = "1" Then ObjFacturaProntoPago.Version = "4.0" If ObjFacturaProntoPago.Cliente Is Nothing Then ObjFacturaProntoPago.Cliente = New Modelos.ClienteModel End If ObjFacturaProntoPago.Cliente.CodigoRegimenFiscal = ClienteCodigoRegimenFiscal ObjFacturaProntoPago.Cliente.RegimenFiscal = ClienteRegimenFiscal Else ObjFacturaProntoPago.Version = "3.3" End If ObjFacturaProntoPago.CveMetodoPago33 = 1 ObjFacturaProntoPago.MetodoPago33 = "Pago en una sola exhibición" ObjFacturaProntoPago.ClaveMetodoPagoSAT = "PUE" ObjFacturaProntoPago.CveFormaPago33 = 21 ObjFacturaProntoPago.FormaPago33 = "Aplicación de anticipos" ObjFacturaProntoPago.FormaPagoSAT33 = "30" ObjFacturaProntoPago.CveSubProyecto = CveSubProyecto ObjFacturaProntoPago.SetSubProyecto() ObjFacturaProntoPago.CveCliente = CveCliente ObjFacturaProntoPago.SetCliente() If ObjCliente.GetClientes(ObjFacturaProntoPago.CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, -1, TipoCliente:=-1) Then If ObjCliente.DtResultados.Rows.Count > 0 Then ObjFacturaProntoPago.CveUsoCFDI = ObjCliente.CveUsoCFDI ObjFacturaProntoPago.UsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("Descripcion", String.Format("CveUsoCFDI = {0}", ObjCliente.CveUsoCFDI)) ObjFacturaProntoPago.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", String.Format("CveUsoCFDI = {0}", ObjCliente.CveUsoCFDI)) ObjFacturaProntoPago.DtDetalle = CreaDTDetalleNCProntoPago() CargaImpuestosProntoPago(ObjFacturaProntoPago, ObjFactura, ObjCliente.DesglosaIEPS, ObjCliente.RetIVA.ToDecimal, ObjCliente.RetISR.ToDecimal) End If End If If ObjCliente.GetSucursales(CveCliente) Then If ObjCliente.DtResultados.Rows.Count > 0 Then ObjFacturaProntoPago.CveClienteSucursal = If(String.IsNullOrEmpty(ObjCliente.DtResultados.FiltroPrimeroValor("CveClienteSucursal", "Estatus = 'Activo'")), -1, ObjCliente.DtResultados.FiltroPrimeroValor("CveClienteSucursal", "Estatus = 'Activo'").ToEntero()) Else ObjFacturaProntoPago.CveClienteSucursal = -1 End If End If ObjFacturaProntoPago.CveTipoRelacion = 7 ObjFacturaProntoPago.TipoRelacion = "07" ObjFacturaProntoPago.UUIDRelacionados = New List(Of String) Select Case ObjFacturaProntoPago.TipoDocto Case "Ing" ObjFacturaProntoPago.TipoDocumento = "Factura" Case "REM" ObjFacturaProntoPago.TipoDocumento = "Remision" Case "Cot" ObjFacturaProntoPago.TipoDocumento = "Cotizacion" Case "Egs" ObjFacturaProntoPago.TipoDocumento = "Nota de Crédito" Case "Dev" ObjFacturaProntoPago.TipoDocumento = "Nota de Devolución" Case Else ObjFacturaProntoPago.TipoDocumento = "" End Select ObjFacturaProntoPago.FechaPago = Now ObjFacturaProntoPago.CveCorte = -1 ObjFacturaProntoPago.CveMesa = -1 ObjFacturaProntoPago.NumeroPersonas = 0 ObjFacturaProntoPago.CveContrato = -1 ObjFacturaProntoPago.DescripcionContrato = "" ObjFacturaProntoPago.CveClienteSucursal = -1 ObjFacturaProntoPago.Entrega = "" ObjFacturaProntoPago.CveAlmacen = -1 Dim DtVentasNC = InicializaDTVentasNCProntoPago() Dim TotalImporte As Decimal = ObjFacturaProntoPago.DtDetalle.SUMD("TotalImporte") Dim ImporteIVA As Decimal = ObjFacturaProntoPago.DtDetalle.SUMD("ImporteIVA") Dim ImporteRetIVA As Decimal = ObjFacturaProntoPago.DtDetalle.SUMD("ImporteRetIVA") Dim ImporteRetISR As Decimal = ObjFacturaProntoPago.DtDetalle.SUMD("ImporteRetISR") Dim ImporteIEPS As Decimal = ObjFacturaProntoPago.DtDetalle.SUMD("ImporteIEPS") Dim Descuento As Decimal = ObjFacturaProntoPago.DtDetalle.SUMD("Descuento") Dim Amortizacion As Decimal = 0 Dim Total As Decimal = (TotalImporte + ImporteIVA + ImporteIEPS) - (ImporteRetIVA + ImporteRetISR + Descuento + Amortizacion) 'DETALLES ObjFacturaProntoPago.SubTotal = TotalImporte ObjFacturaProntoPago.Descuento = Descuento ObjFacturaProntoPago.Amortizacion = Amortizacion ObjFacturaProntoPago.IVA = ImporteIVA ObjFacturaProntoPago.RetIVA = ImporteRetIVA ObjFacturaProntoPago.RetISR = ImporteRetISR ObjFacturaProntoPago.IEPS = ImporteIEPS ObjFacturaProntoPago.Total = Total ObjFacturaProntoPago.TotalOtrosConceptos = 0 Dim Drt = DtVentasNC.NewRow Drt("CveVenta") = ObjFactura.CveVenta Drt("Importe") = ObjFactura.DescuentoProntoPago Drt("FolioFiscal") = ObjFactura.FolioFiscal DtVentasNC.Rows.Add(Drt) DtVentasNC.AcceptChanges() ObjFacturaProntoPago.DtVentasRelacionadas = New DataTable ObjFacturaProntoPago.DtVentasRelacionadas.Columns.Add("CveVenta", GetType(Integer)) ObjFacturaProntoPago.DtVentasNC = DtVentasNC ObjFacturaProntoPago.Timbre = PreParaTimbre(ObjFacturaProntoPago) Resp = ObjFacturaProntoPago.EmitirFactura(False, Transac:=SqlTransaccion, ObjContPaqTransac:=ObjConta) Retorno.ObjFacturaProntoPago = ObjFacturaProntoPago Catch ex As Exception Resp.CveVenta = -1 Resp.TieneError = True OnError("Ocurrio un error al generar la nota de credito de pronto pago", ex) End Try Retorno.Mensaje = Resp Return Retorno End Function Private Sub AgregaTempDTNCProntoPago(ByRef TmpDT As DataTable, CvePS As Integer, PS As String, Codigo As String, CodigoPS As String, CveTipoPS As Integer, CveTipoInvPS As Integer, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CveProyecto As Integer, CveSubProyecto As Integer, Obs As String, Cantidad As Double, PU As Double, PorcentajeIVA As Double, ImporteIVA As Double, PorcentajeRetIVA As Double, ImporteRetIVA As Double, PorcentajeRetISR As Double, ImporteRetISR As Double, PorcentajeIEPS As Double, ImporteIEPS As Double, TipoDescuento As Integer, Descuento As Double, Total As Double, Serie As String, TiempoEntrega As String, CvePresupuestoIngreso As Integer, EntregaDirecta As Integer, SATClaveProdServ As String, SATClaveUM As String, CveContratoDetalle As Integer, CveVentaDetalle As Integer, CveMovimientoDetallePedido As Integer, CveOrdenCompraDetalle As Integer, CveVentaDetalleRemision As Integer, CveVentaDetalleCotizacion As Integer, CodigoObjetoImpuesto As String) Dim Row As DataRow = Nothing Row = TmpDT.NewRow() Row("Consec") = TmpDT.Rows.Count + 1 Row("Orden") = TmpDT.Rows.Count + 1 Row("CvePS") = CvePS Row("PS") = PS Row("Codigo") = Codigo Row("CodigoPS") = CodigoPS Row("CveTipoPS") = CveTipoPS Row("CveTipoInvPS") = CveTipoInvPS Row("CveUM") = CveUM Row("UM") = UM Row("CveClasificacion") = CveClasificacion Row("Clasificacion") = Clasificacion Row("CveProyecto") = CveProyecto Row("Proyecto") = "" Row("CveSubProyecto") = CveSubProyecto Row("SubProyecto") = "" Row("Obs") = Obs Row("Cantidad") = Cantidad Row("PU") = Math.Round(PU, 6) Row("PorcentajeIVA") = PorcentajeIVA Row("IVA") = PorcentajeIVA Row("ImporteIVA") = Math.Round(ImporteIVA, 2) Row("PorcentajeRetIVA") = PorcentajeRetIVA Row("ImporteRetIVA") = Math.Round(ImporteRetIVA, 2) Row("PorcentajeRetISR") = PorcentajeRetISR Row("ImporteRetISR") = Math.Round(ImporteRetISR, 2) Row("PorcentajeIEPS") = PorcentajeIEPS Row("ImporteIEPS") = Math.Round(ImporteIEPS, 2) Row("IEPS") = Math.Round(ImporteIEPS, 2) Row("TipoDescuento") = TipoDescuento Row("Descuento") = Math.Round(Descuento, 2) Row("Total") = Math.Round(Total, 2) Row("TotalImporte") = Math.Round(Total, 2) Row("Serie") = Serie Row("TiempoEntrega") = TiempoEntrega Row("CvePresupuestoIngreso") = CvePresupuestoIngreso Row("EntregaDirecta") = EntregaDirecta Row("SATClaveProdServ") = SATClaveProdServ Row("SATClaveUM") = SATClaveUM Row("CodigoObjetoImpuesto") = CodigoObjetoImpuesto 'Contratos Row("CveContratoDetalle") = CveContratoDetalle Row("CveVentaDetalle") = CveVentaDetalle Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle Row("CveVentaDetalleRemision") = CveVentaDetalleRemision Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion TmpDT.Rows.Add(Row) End Sub Private Sub CargaImpuestosProntoPago(ByRef ObjFacturaDevolucion As Modelos.Factura, ObjFactura As Modelos.Factura, ClienteDesglosaIEPS As Boolean, ClienteRetIVA As Decimal, ClienteRetISR As Decimal) Dim DtImpuestos As New DataTable DtImpuestos.Columns.Add("ImportePU", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteTotal", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeIVA", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteIVA", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteRetIVA", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeRetISR", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteRetISR", GetType(Decimal)) DtImpuestos.Columns.Add("PorcentajeIEPS", GetType(Decimal)) DtImpuestos.Columns.Add("ImporteIEPS", GetType(Decimal)) DtImpuestos.Columns.Add("CveSubProyecto", GetType(Integer)) DtImpuestos.AcceptChanges() Dim AcumuladoNC As Decimal = 0 DtImpuestos.Merge(CargaDtImpuestosNCProntoPago(ObjFactura.CveVenta, ObjFactura.DescuentoProntoPago), True, MissingSchemaAction.Ignore) DtImpuestos = CargaTotalesImpuestosProntoPago(DtImpuestos) Dim DrSubProyecto As DataRow = GlobalDTSubProyectos(-1, ObjFacturaDevolucion.CveSubProyecto).Rows(0) Dim Cantidad As Decimal = 1 Dim CveProyecto As Integer = DrSubProyecto("CveProyecto").ToString().ToEntero() Dim CveSubProyecto = DrSubProyecto("CveSubProyecto").ToString.ToEntero Dim SubProyecto = DrSubProyecto("SubProyecto").ToString Dim Proyecto = DrSubProyecto("Proyecto").ToString Dim CveSATNC As Integer Dim ArrayNC As String() = UsuarioActual.Empresa.Funcionalidad(591).Split(",".ToCharArray()) Dim NCBonificacion As Integer = 0 If ArrayNC.Length > 6 Then 'CONCEPTO DE PRONTO PAGO CveSATNC = ArrayNC(6).ToEntero() End If Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CveSATNC, AplicaParaVenta:=1).FiltroPrimero("") For Each Dr As DataRow In DtImpuestos.Rows AgregaTempDTNCProntoPago(ObjFacturaDevolucion.DtDetalle, DrPS("CvePS").ToString.ToEntero, DrPS("PS").ToString, DrPS("Codigo").ToString, DrPS("PSCodigo").ToString, DrPS("CveTipoPS").ToString.ToEntero, DrPS("Inv_CveMetodoInventario").ToString.ToEntero, DrPS("CveUM").ToString.ToEntero, DrPS("UnidadMedida").ToString, DrPS("CveClasificacion").ToString.ToEntero, DrPS("Clasificacion").ToString, CveProyecto, CveSubProyecto, "", Cantidad, Dr("ImportePU").ToString.ToDecimal, Dr("PorcentajeIVA").ToString.ToDecimal, Dr("ImporteIVA").ToString.ToDecimal, Dr("PorcentajeRetIVA").ToString.ToDecimal, Dr("ImporteRetIVA").ToString.ToDecimal, Dr("PorcentajeRetISR").ToString.ToDecimal, Dr("ImporteRetISR").ToString.ToDecimal, Dr("PorcentajeIEPS").ToString.ToDecimal, Dr("ImporteIEPS").ToString.ToDecimal, -1, 0.0, Dr("ImporteTotal").ToString.ToDecimal, "", "", -1, -1, DrPS("SATClavePS").ToString, DrPS("SATClaveUnidadMedida").ToString, -1, -1, -1, -1, -1, -1, DrPS("CodigoObjetoImpuesto").ToString()) Next End Sub Private Function CargaDtImpuestosNCProntoPago(CveVentaNC As Integer, Importe As Decimal) As DataTable Dim Total As Decimal = 0, SubTotal As Decimal = 0, Saldo As Decimal = 0 Dim TmpDT As DataTable = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVentaDetalle(CveVentaNC) Then TmpDT = ObjVentas.DtResultados TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) End If If ObjVentas.GetVenta(CveVentaNC, UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then Total = ObjVentas.DtResultados()(0)("Total").ToString.ToDecimal SubTotal = ObjVentas.DtResultados()(0)("SubTotal").ToString.ToDecimal End If End If ObjVentas.Dispose() Dim DtImpuestosLocal = TmpDT.FiltraParametros("", "", {"PorcentajeIVA", "PorcentajeRetIVA", "PorcentajeRetISR", "PorcentajeIEPS", "CveSubProyecto"}).Copy DtImpuestosLocal.Columns.Add("ImportePU", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteTotal", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteIVA", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteRetIVA", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteRetISR", GetType(Decimal)) DtImpuestosLocal.Columns.Add("ImporteIEPS", GetType(Decimal)) Dim ImporteReferencia As Decimal = Total Dim Porcentaje As Decimal = ((Importe * 100) / ImporteReferencia) / 100 Dim FiltroStr As String = "" Dim ImporteTotalConcepto As Decimal = 0 For Each Dr As DataRow In DtImpuestosLocal.Rows FiltroStr = String.Format("ISNULL(PorcentajeIVA,0) = {0} AND ISNULL(PorcentajeRetIVA,0) = {1} AND ISNULL(PorcentajeRetISR,0) = {2} AND ISNULL(PorcentajeIEPS,0) = {3} AND ISNULL(CveSubProyecto,0) = {4} ", Dr("PorcentajeIVA").ToString.ToDecimal, Dr("PorcentajeRetIVA").ToString.ToDecimal, Dr("PorcentajeRetISR").ToString.ToDecimal, Dr("PorcentajeIEPS").ToString.ToDecimal, Dr("CveSubProyecto")) ImporteTotalConcepto = Porcentaje * (TmpDT.SUMD("TotalImporte", FiltroStr) - TmpDT.SUMD("Descuento", FiltroStr)) Dr("ImportePU") = ImporteTotalConcepto.RoundSQL(6) Dr("ImporteTotal") = ImporteTotalConcepto.RoundSQL(2) Dr("ImporteIVA") = (ImporteTotalConcepto * Dr("PorcentajeIVA").ToString().ToDecimal()).RoundSQL(2) Dr("ImporteRetIVA") = (ImporteTotalConcepto * Dr("PorcentajeRetIVA").ToString().ToDecimal()).RoundSQL(2) Dr("ImporteRetISR") = (ImporteTotalConcepto * Dr("PorcentajeRetISR").ToString().ToDecimal()).RoundSQL(2) Dr("ImporteIEPS") = (ImporteTotalConcepto * Dr("PorcentajeIEPS").ToString().ToDecimal()).RoundSQL(2) 'Dr("ImporteIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIVA", FiltroStr), 2) 'Dr("ImporteRetIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetIVA", FiltroStr), 2) 'Dr("ImporteRetISR") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetISR", FiltroStr), 2) 'Dr("ImporteIEPS") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIEPS", FiltroStr), 2) '(Dr("ImporteTotal").ToString.ToDecimal - Dr("ImporteIVA").ToString.ToDecimal - Dr("ImporteRetIVA").ToString.ToDecimal - Dr("ImporteRetISR").ToString.ToDecimal - Dr("ImporteIEPS").ToString.ToDecimal) Next 'codigo para ajuste de centavo, si el importe total no cuadra con los totales Dim difTmp As Decimal = Importe - (DtImpuestosLocal.SUMD("ImporteTotal") + DtImpuestosLocal.SUMD("ImporteIVA") + DtImpuestosLocal.SUMD("ImporteIEPS") - DtImpuestosLocal.SUMD("ImporteRetIVA") - DtImpuestosLocal.SUMD("ImporteRetISR")) If Math.Abs(difTmp) >= 0.01 Then 'asusto la diferencia en el último concepto Dim ImporteAjustado As Decimal = DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal").ToString.ToDecimal + difTmp DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal") = ImporteAjustado DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImportePU") = ImporteAjustado End If 'CARGA FACTURA A LA CUAL SE APLICA LA NC 'CargaNCDT(CveVentaNC, Importe.ToDecimal) Return DtImpuestosLocal End Function Private Function CargaTotalesImpuestosProntoPago(DtImpuestos As DataTable) As DataTable Dim query = From dr In DtImpuestos Group By PorcentajeIVA = dr("PorcentajeIVA").ToString.ToDecimal, PorcentajeRetIVA = dr("PorcentajeRetIVA").ToString.ToDecimal, PorcentajeRetISR = dr("PorcentajeRetISR").ToString.ToDecimal, PorcentajeIEPS = dr("PorcentajeIEPS").ToString.ToDecimal Into x = Group Select ImportePU = x.Sum(Function(s) s("ImportePU").ToString.ToDecimal), ImporteTotal = x.Sum(Function(s) s("ImporteTotal").ToString.ToDecimal), ImporteIVA = x.Sum(Function(s) Math.Round(s("ImporteIVA").ToString.ToDecimal, 2)), ' Math.Round(s("ImporteIVA").ToString.ToDecimal, 2)) * (1 + PorcentajeIEPS) * PorcentajeIVA, ImporteRetIVA = x.Sum(Function(s) Math.Round(s("ImporteRetIVA").ToString.ToDecimal, 2)),' Math.Round(s("ImportePU").ToString.ToDecimal, 2)) * PorcentajeRetIVA, ImporteRetISR = x.Sum(Function(s) Math.Round(s("ImporteRetISR").ToString.ToDecimal, 2)),' Math.Round(s("ImportePU").ToString.ToDecimal, 2)) * PorcentajeRetISR, ImporteIEPS = x.Sum(Function(s) Math.Round(s("ImporteIEPS").ToString.ToDecimal, 2)), 'Math.Round(s("ImportePU").ToString.ToDecimal, 2)) * PorcentajeIEPS, PorcentajeIVA = PorcentajeIVA, PorcentajeRetIVA = PorcentajeRetIVA, PorcentajeRetISR = PorcentajeRetISR, PorcentajeIEPS = PorcentajeIEPS Return query.QueryToDataTable(False) End Function Protected Function CreaDTDetalleNCProntoPago() As DataTable Dim TmpDT = New DataTable TmpDT.Columns.Add("CveVenta", GetType(Integer)) TmpDT.Columns.Add("Consec", GetType(Integer)) TmpDT.Columns.Add("Cantidad", GetType(Decimal)) TmpDT.Columns.Add("Codigo", GetType(String)) TmpDT.Columns.Add("CveUM", GetType(Integer)) TmpDT.Columns.Add("UM", GetType(String)) TmpDT.Columns.Add("SATClaveUM", GetType(String)) TmpDT.Columns.Add("CveClasificacion", GetType(Integer)) TmpDT.Columns.Add("Clasificacion", GetType(String)) TmpDT.Columns.Add("CvePS", GetType(Integer)) TmpDT.Columns.Add("PS", GetType(String)) TmpDT.Columns.Add("CodigoPS", GetType(String)) TmpDT.Columns.Add("SATClaveProdServ", GetType(String)) TmpDT.Columns.Add("NoIdentificacion", GetType(String)) TmpDT.Columns.Add("CveTipoPS", GetType(Integer)) TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer)) TmpDT.Columns.Add("Serie", GetType(String)) TmpDT.Columns.Add("CuentaPredial", GetType(String)) TmpDT.Columns.Add("Obs", GetType(String)) TmpDT.Columns.Add("TiempoEntrega", GetType(String)) TmpDT.Columns.Add("PU", GetType(Decimal)) TmpDT.Columns.Add("IVA", GetType(Decimal)) TmpDT.Columns.Add("ImporteIVA", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeIVA", GetType(Decimal)) TmpDT.Columns.Add("ImporteRetIVA", GetType(Decimal)) TmpDT.Columns.Add("ImporteRetISR", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeRetISR", GetType(Decimal)) TmpDT.Columns.Add("ImporteIEPS", GetType(Decimal)) TmpDT.Columns.Add("IEPS", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeIEPS", GetType(Decimal)) TmpDT.Columns.Add("Descuento", GetType(Decimal)) TmpDT.Columns.Add("TipoDescuento", GetType(Integer)) TmpDT.Columns.Add("TotalImporte", GetType(Decimal)) TmpDT.Columns.Add("Total", GetType(Decimal)) 'Para uso del módulo contable TmpDT.Columns.Add("AsientoContableVentas", GetType(Integer)) TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer)) TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean)) TmpDT.Columns.Add("CveProyecto", GetType(Integer)) TmpDT.Columns.Add("Proyecto", GetType(String)) TmpDT.Columns.Add("CveSubProyecto", GetType(Integer)) TmpDT.Columns.Add("SubProyecto", GetType(String)) TmpDT.Columns.Add("CveVentaDetallePadre", GetType(Integer)) 'TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto TmpDT.Columns.Add("CvePresupuestoIngreso", GetType(Integer)) TmpDT.Columns.Add("CveFuenteRecaudacion", GetType(Integer)) 'Contratos TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer)) 'Remisiones a Facturas TmpDT.Columns.Add("CveVentaDetalle", GetType(Integer)) TmpDT.Columns.Add("CveVentaDetalleRemision", GetType(Integer)) TmpDT.Columns.Add("CveVentaDetalleCotizacion", GetType(Integer)) 'Pedido2 a Facturas TmpDT.Columns.Add("CveVentaDetallePedido2", GetType(Integer)) TmpDT.Columns.Add("Origen", GetType(Integer)) 'Ordenes Servicio TmpDT.Columns.Add("CveOS", GetType(Integer)) TmpDT.Columns.Add("CveOSDetalle", GetType(Integer)) TmpDT.Columns.Add("SeFacturara", GetType(Integer)) TmpDT.Columns.Add("Folio", GetType(Integer)) TmpDT.Columns.Add("Estatus", GetType(String)) 'Ordenamiento TmpDT.Columns.Add("Orden", GetType(Integer)) TmpDT.Columns.Add("TipoDocto", GetType(String)) 'OC TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer)) TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) TmpDT.Columns.Add("CantidadFacturadaCot", GetType(Decimal)) TmpDT.Columns.Add("CantidadFacturadaPed2", GetType(Decimal)) TmpDT.Columns.Add("CantidadInventario", GetType(Decimal)) TmpDT.Columns.Add("ClaveSATFraccionArancelaria", GetType(String)) TmpDT.Columns.Add("ClaveSATUnidadAduana", GetType(String)) TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", GetType(String)) TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", GetType(String)) TmpDT.Columns.Add("CodigoObjetoImpuesto", GetType(String)) TmpDT.Columns.Add("CveTamaño", GetType(Integer)) TmpDT.Columns.Add("EsCargo", GetType(Boolean)) TmpDT.Columns.Add("CveMarca", GetType(Integer)) Return TmpDT End Function Private Function InicializaDTVentasNCProntoPago() As DataTable Dim DtVentasNC = New DataTable DtVentasNC.Columns.Add("CveVenta", GetType(Integer)) DtVentasNC.Columns.Add("Importe", GetType(Decimal)) DtVentasNC.Columns.Add("FolioFiscal", GetType(String)) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TC", .DataType = GetType(Decimal), .DefaultValue = 1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TCCambioValuacion", .DataType = GetType(Decimal), .DefaultValue = 1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "CveEstatusFactura", .DataType = GetType(Integer), .DefaultValue = -1}) Return DtVentasNC End Function Public Class MensajeProntoPago Public Property ObjFacturaProntoPago As Modelos.Factura Public Property Mensaje As Modelos.Factura.MMensajeFactura End Class #End Region Protected Sub LnkAplicarRNCDevolucion_Click(sender As Object, e As EventArgs) Dim DtNC As DataTable = Nothing Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, CveMoneda:=-1) Then DtNC = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'RNC' AND TipoRNC = 3 AND CveVenta > 0 and Saldo > 0", "Moneda,Fecha,Folio") End If ObjMovtos.Dispose() GvRNCDevoluciones.DataSource = DtNC GvRNCDevoluciones.DataBind() UpRNCDevolucion.Update() RegistraScript("$('#ModalAplicaRNCDevolucion').modal('show');") End Sub Protected Sub BtnAplicarRNCDevoluciones_Click(sender As Object, e As EventArgs) Me.AplicaRNCXDetalle = False If ListaRemisionesNC Is Nothing Then ListaRemisionesNC = New List(Of Modelos.Factura) Else ListaRemisionesNC.Clear() End If If ListaNCBonificacion Is Nothing Then ListaNCBonificacion = New List(Of Modelos.Factura) Else ListaNCBonificacion.Clear() End If Dim TotalRemNCAplicado As Decimal = 0 For Each GvRow As GridViewRow In GvRNCDevoluciones.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("ChkAplicar").Checked Then Dim RemNC As New Modelos.Factura(UsuarioActual, GvRow.DataKey("CveVenta").ToEntero(), UsuarioActual.CveEmpresa, CargaDatosCliente:=False, CargaDatosRelacionados:=False) RemNC.TotalRemNCAplicado = GvRow.FCTextBox("TxtImporte").Text.ToDecimal() TotalRemNCAplicado += RemNC.TotalRemNCAplicado If RemNC.TotalRemNCAplicado <= 0 Then Alert($"Debe asignar un importe en la siguiente remisión: {RemNC.SerieFolio}", TipoMensaje.MsgAdvertencia) ListaRemisionesNC.Clear() Exit Sub End If ListaRemisionesNC.Add(RemNC) End If End If Next TxtImportesRemisionesNC.Text = TotalRemNCAplicado.FormatoNumero TxtNCImporte.Text = TotalRemNCAplicado.FormatoNumero UpModalRemisionesNC.Update() UpAplicarNC.Update() AplicarNC(-1, NCDescuento:=False, EsNCAmortizacion:=False, AplicaImpuestosLocales:=True, AplicaNuevoDocumento:=True, AplicoNCFacturaActual:=True, TipoDoctoNC:="Dev") RegistraScript("$('#ModalAplicaRNCDevolucion').modal('hide');") End Sub Protected Sub btnGuardarAdjunto_Click(sender As Object, e As System.EventArgs) Handles btnGuardarAdjunto.Click If Not txtAdjuntar.getfiles().Archivos.Count > 0 Then Alert("Tiene que cargar un archivo.", TipoMensaje.MsgAdvertencia) Exit Sub End If If LblSerie.Text = "" Or TxtFolio.Text = "" Then Alert("Debe asignar una serie un folio antes de subir el archivo.", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim FileExtension As String = "-1" Dim Filesgral As List(Of Archivo) = txtAdjuntar.getfiles().Archivos Dim Filename As String = "" Dim fileItem As Archivo = Filesgral(0) Try FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "") Adjunto = String.Format("{0}-{1}.{2}", LblSerie.Text, TxtFolio.Text, FileExtension) Dim objVentas As New ClsVentas Dim Path As String Path = String.Format("{0}Ventas", UsuarioActual.Empresa.Ruta) If Not Directory.Exists(Path) Then Directory.CreateDirectory(Path) End If Path += $"/{Adjunto}" If File.Exists(Path) Then File.Delete(Path) End If My.Computer.FileSystem.MoveFile(fileItem.FileUrl, Path) BtnAdjuntar.Visible = False BtnArchivoAdjunto.Text = Adjunto BtnArchivoAdjunto.Visible = True BtnEliminarAdjunto.Visible = True tdAdjuntar.Style.Item("display") = "none" tdAdjunto.Style.Item("display") = "block" UpAdjuntar.Update() Alert("Documento cargado", TipoMensaje.MsgInformacion) objVentas.Dispose() Catch ex As Exception OnError("Error al cargar archivo", ex) End Try End Sub Protected Sub BtnArchivoAdjunto_Click(sender As Object, e As System.EventArgs) Handles BtnArchivoAdjunto.Click Dim ruta As String = HttpContext.Current.Request.ApplicationPath ruta = String.Format("{0}Ventas", UsuarioActual.Empresa.Ruta) ruta += $"/{Adjunto}" Dim Archivo As New System.IO.FileInfo(ruta) Try If Archivo IsNot Nothing Then If Archivo.Exists Then HttpContext.Current.Response.Clear() HttpContext.Current.Response.ClearContent() HttpContext.Current.Response.ContentType = "application/octet-stream" HttpContext.Current.Response.AppendHeader("Content-disposition", String.Format("attachment; filename={0}", Archivo.Name)) HttpContext.Current.Response.AddHeader("Content-Length", Archivo.Length.ToString()) HttpContext.Current.Response.TransmitFile(ruta) Response.Flush() ' send it to the client to download HttpContext.Current.Response.SuppressContent = True HttpContext.Current.ApplicationInstance.CompleteRequest() Response.End() Else Alert("El archivo no existe", TipoMensaje.MsgAdvertencia) End If End If Catch ex As Exception End Try End Sub Protected Sub BtnEliminarAdjunto_Click(sender As Object, e As System.EventArgs) Handles BtnEliminarAdjunto.Click Dim objVentas As New ClsVentas Dim Path As String Path = String.Format("{0}Ventas/{1}", UsuarioActual.Empresa.Ruta, Adjunto) If File.Exists(Path) Then File.Delete(Path) End If BtnAdjuntar.Visible = True tdAdjuntar.Style.Item("display") = "block" BtnArchivoAdjunto.Text = "" BtnArchivoAdjunto.Visible = False tdAdjunto.Style.Item("display") = "none" BtnEliminarAdjunto.Visible = False UpAdjuntar.Update() End Sub Protected Sub LnkSolicitarCredito_Click(sender As Object, e As EventArgs) Handles LnkSolicitarCredito.Click If CveCliente <= 0 Then Alert("Debe seleccionar un cliente", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlVendedor.SelectedValue.ToEntero() <= 0 Then Alert("Debe seleccionar un vendedor", TipoMensaje.MsgAdvertencia) Exit Sub End If TxtImporteSolicitud.Text = "" RegistraScript("$('#DivModalSolicitarCredito').modal('show')") UpModalSolicitud.Update() End Sub Protected Sub BtnSolicitarCredito_Click(sender As Object, e As EventArgs) Handles BtnSolicitarCredito.Click Dim DiasVencidos As Integer = 0 Dim CveEstatus As Integer = 0 Dim TipoDocto As String = DdlTipoDocto.SelectedValue Dim CveTipoAutorizacion As Integer = DdlTipoAutorizacion.SelectedValue.ToEntero() If CveTipoAutorizacion <= 0 Then Alert("Debe seleccionar un tipo de autorización", TipoMensaje.MsgAdvertencia) Exit Sub End If If CveTipoAutorizacion = 2 Then DiasVencidos = TxtDiasVencidos.Text.ToEntero() End If Dim Motivo As String = TxtMotivoAutorizacion.Text Dim ObjPS As New ClsVentas If ObjPS.AddAutorizacionLimite(UsuarioActual.CveEmpresa, CveCliente, DdlVendedor.SelectedValue.ToEntero(), TxtImporteSolicitud.Text.ToDecimal(), CveEstatus, UsuarioActual.CveUsuario, CveTipoAutorizacion, TipoDocumento:=DdlTipoDocto.SelectedValue, DiasVencidos:=DiasVencidos, Motivo:=Motivo) Then RegistraScript("$('#DivModalSolicitarCredito').modal('hide')") Alert("La autorización se agregó correctamente.", TipoMensaje.MsgInformacion) End If ObjPS.Dispose() UpModalSolicitud.Update() End Sub Protected Sub DdlTipoAutorizacion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoAutorizacion.SelectedIndexChanged DivImporteSolicitud.Visible = DdlTipoAutorizacion.SelectedValue.ToEntero() = 1 DivDiasVencidos.Visible = DdlTipoAutorizacion.SelectedValue.ToEntero() = 2 UpModalSolicitud.Update() End Sub 'Protected Sub DdlTipoDocto_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoDocto.SelectedIndexChanged ' Dim TipoDocto As String = DdlTipoDocto.SelectedValue.ToString() ' Select Case TipoDocto ' Case "Ing" ' DivAutorizacion.Visible = True ' DivImporteSolicitud.Visible = True ' Case "Egs" ' DivAutorizacion.Visible = False ' DivImporteSolicitud.Visible = False ' End Select ' UpModalSolicitud.Update() 'End Sub Protected Sub DdlTipoDocto_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoDocto.SelectedIndexChanged Dim TipoDocto As String = DdlTipoDocto.SelectedValue.ToString() Select Case TipoDocto Case "Ing" If DdlTipoAutorizacion.Items.FindByValue("2") Is Nothing Then DdlTipoAutorizacion.Items.Insert(0, New ListItem("Vencimiento", "2")) DivMotivoAutorizacion.Visible = True End If Case "Egs" 'QUITAR LA DE VENCIMIENTO DdlTipoAutorizacion.Items.Remove(DdlTipoAutorizacion.Items.FindByValue("2")) DivMotivoAutorizacion.Visible = True End Select UpModalSolicitud.Update() End Sub 'Private Sub CargaVendedoresSubProyectos() ' DdlVendedor.Items.Clear() ' DdlVendedor.SelectedValue = Nothing ' Dim DtVendedoresSucursales = GlobalDTClientesVendedoresSubProyectos(UsuarioActual.CveEmpresa, CveCliente:=Me.CveCliente, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero()) ' If DtVendedoresSucursales IsNot Nothing AndAlso DtVendedoresSucursales.Rows.Count > 0 Then ' DdlVendedor.DataSource = DtVendedoresSucursales ' DtVendedoresSucursales.Dispose() ' Else ' If UsuarioActual.Empresa.Funcionalidad(302) = "1" AndAlso DdlSubProyectoDatos.SelectedValue.ToEntero() > 0 Then ' DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue)).FiltraParametros("VendedorTipo = 1") ' Else ' DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros("VendedorTipo = 1") ' End If ' End If ' DdlVendedor.DataBind() ' DdlVendedor.Items.Insert(0, New ListItem("Sin Asignar", "0")) ' UpParametros.Update() 'End Sub Public Class MAnticipoRelacionado Public Property CveVenta As Integer Public Property FolioFiscal As String End Class Protected Sub LnkEditarDir_Click(sender As Object, e As EventArgs) DdlDireccionEnvio.Enabled = True LnkEditarDir.Visible = False LnkAplicarDir.Visible = True End Sub Protected Sub LnkAplicarDir_Click(sender As Object, e As EventArgs) Dim ProcesoOK As Boolean = True Dim ObjVentas As New ClsVentas() If Not ObjVentas.UpdateDireccionEnvioVenta(CveVenta, DdlDireccionEnvio.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then ProcesoOK = False End If ObjVentas.Dispose() If ProcesoOK Then Alert("Dirección Actualizada correctamente.", ModExtensiones.TipoMensaje.ToastInformacion) LnkAplicarDir.Visible = False LnkEditarDir.Visible = True End If End Sub Protected Sub RdTipoPersona_SelectedIndexChanged(sender As Object, e As EventArgs) DVRegimenSociedad.Visible = False DivRazonSocial2.Attributes.Add("class", "col-md-12") If RdTipoPersona.SelectedValue.ToEntero = 1 And UsuarioActual.Empresa.Funcionalidad(350).Contiene("1", "2") Then DivRazonSocial2.Attributes.Add("class", "col-md-8") DVRegimenSociedad.Visible = True End If UpAgregarCliente.Update() End Sub #Region "C A R T A - P O R T E" Public Sub CargarCamiones() TxtFechaEntregaCP.Text = Now.Date.ToString("dd/MM/yyyy HH:mm") TxtFechaLlegadaCP.Text = Now.Date.ToString("dd/MM/yyyy HH:mm") 'Now.Date.AddDays(1).AddMinutes(-1).ToString("dd/MM/yyyy HH:mm") DdlConfigAuto.Items.Clear() DdlUnidadCamion.Items.Clear() DdlChofer.Items.Clear() DdlChofer.DataSource = GlobalDTChoferes(UsuarioActual.CveEmpresa) DdlChofer.DataBind() DdlChofer.Items.Insert(0, New ListItem("Seleccione Uno", "-1")) Using ObjInv As New ClsInventarios If ObjInv.GetCamiones(-1, UsuarioActual.CveEmpresa, 1, Estatus:=1) Then DdlUnidadCamion.DataSource = ObjInv.DtResultados End If If ObjInv.GetCamiones(-1, UsuarioActual.CveEmpresa, 2, Estatus:=1) Then DdlRemolque1.DataSource = ObjInv.DtResultados End If End Using DdlUnidadCamion.DataBind() DdlUnidadCamion.Items.Insert(0, New ListItem("Seleccione Uno", "-1")) DdlRemolque1.DataBind() DdlRemolque1.Items.Insert(0, New ListItem("Seleccione Uno", "-1")) Using ObjGrales As New ClsGenerales If ObjGrales.GetCartaPorteConfigAutoTransportes() Then DdlConfigAuto.DataSource = ObjGrales.DtResultados End If End Using DdlConfigAuto.DataBind() DdlConfigAuto.Items.Insert(0, New ListItem("Seleccione una", "-1")) UpEmitirTransitorio.Update() End Sub Protected Sub DdlUnidadCamionActivoFijo_SelectedIndexChanged(sender As Object, e As EventArgs) ChkEmitirCartaPorte.Checked = True DvRemolque1.Visible = False DvRemolque2.Visible = False DdlRemolque1.SelectedValueExist(-1) DdlRemolque2.SelectedValueExist(-1) If DdlUnidadCamion.SelectedValue.ToEntero > 0 Then Using ObjInv As New ClsInventarios If ObjInv.GetCamiones(DdlUnidadCamion.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, 1) Then DdlConfigAuto.SelectedValueExist(ObjInv.DtResultados.FiltroPrimeroValor("CveConfigAutoTransporte")) DdlConfigAuto_SelectedIndexChanged(Nothing, Nothing) End If End Using End If UpEmitirTransitorio.Update() End Sub Protected Sub DdlConfigAuto_SelectedIndexChanged(sender As Object, e As EventArgs) ValidaConfiguracionVehiculo() End Sub Public Sub CargaVentaCortePorte(CveVenta As Integer) Dim CveEntregaAlmacen As Integer = -1 Dim CveDireccionOrigen As Integer = -1 Dim CveDireccionDestino As Integer = -1 Dim CveCamionRemolque1 As Integer = -1 Dim CveCamionRemolque2 As Integer = -1 Dim CveConfigAutoTransporte As Integer = -1 Using ObjGral As New ClsGenerales If ObjGral.GetGralTimbre(-1, "Ing", MinFecha, MaxFecha, 0, UsuarioActual.CveEmpresa, -1, CveVenta:=CveVenta) AndAlso ObjGral.DtResultados.Rows.Count > 0 Then Dim RowCP As DataRow = ObjGral.DtResultados.Rows(0) Me.CveTimbreCartaPorteVenta = RowCP("CveTimbre").ToString().ToEntero() If CveTimbreCartaPorteVenta > 0 Then ChkEmitirCartaPorte.Checked = True CveEntregaAlmacen = RowCP("CveEntregaAlmacen").ToString().ToEntero() CveDireccionOrigen = RowCP("CveDireccionOrigen").ToString().ToEntero() CveDireccionDestino = RowCP("CveDireccionDestino").ToString().ToEntero() TxtFechaEntregaCP.Text = RowCP("FechaEntrega").ToString().ToDateTime().ToString("dd/MM/yyyy HH:mm") TxtFechaLlegadaCP.Text = RowCP("FechaLlegada").ToString().ToDateTime().ToString("dd/MM/yyyy HH:mm") TxtDistancia.Text = RowCP("Distancia").ToString() DdlChofer.SelectedValueExist(RowCP("CveChofer").ToString()) DdlUnidadCamion.SelectedValueExist(RowCP("CveCamion").ToString()) CveCamionRemolque1 = RowCP("CveCamionRemolque1").ToString().ToEntero() CveCamionRemolque2 = RowCP("CveCamionRemolque2").ToString().ToEntero() CveConfigAutoTransporte = RowCP("CveConfigAutoTransporte").ToString().ToEntero() End If End If If ChkEmitirCartaPorte.Checked AndAlso CveEntregaAlmacen > 0 AndAlso ObjGral.GetEntregaAlmacenRutaDetalle(CveEntregaAlmacen) Then DtMercancias = ObjGral.DtResultados End If End Using If ChkEmitirCartaPorte.Checked AndAlso CveCliente > 0 Then Dim ObjClientes As New ClsClientes If ObjClientes.DireccionEnvioGet(-1, CveCliente, -1) Then TmpDTDireccionCP = ObjClientes.DtResultados.FiltraParametros(String.Format("Estatus = 1")) End If ObjClientes.Dispose() DdlDireccionOrigen.DataSource = TmpDTDireccionCP DdlDireccionOrigen.DataBind() DdlDireccionDestino.DataSource = TmpDTDireccionCP DdlDireccionDestino.DataBind() DdlDireccionOrigen.SelectedValueExist(CveDireccionOrigen.ToString()) DdlDireccionDestino.SelectedValueExist(CveDireccionDestino.ToString()) GvMercanciasCP.DataSource = DtMercancias GvMercanciasCP.DataBind() If DdlUnidadCamion.SelectedValue.ToEntero() > 0 Then If CveConfigAutoTransporte > 0 Then DvRemolque1.Visible = False DvRemolque2.Visible = False DdlRemolque1.SelectedValueExist(-1) DdlRemolque2.SelectedValueExist(-1) DdlConfigAuto.SelectedValueExist(CveConfigAutoTransporte.ToString()) DdlConfigAuto_SelectedIndexChanged(DdlConfigAuto, EventArgs.Empty) If CveCamionRemolque1 > 0 Then DdlRemolque1.SelectedValueExist(CveCamionRemolque1.ToString()) DdlRemolque1_SelectedIndexChanged(DdlRemolque1, EventArgs.Empty) If CveCamionRemolque2 > 0 Then DdlRemolque2.SelectedValueExist(CveCamionRemolque2.ToString()) End If End If End If End If Else TmpDTDireccionCP = Nothing End If HabilitarControlesCartaPorte(False) UpEmitirTransitorio.Update() End Sub Private Sub HabilitarControlesCartaPorte(Habilitar As Boolean) ChkEmitirCartaPorte.Enabled = Habilitar TxtFechaEntregaCP.Enabled = Habilitar TxtFechaLlegadaCP.Enabled = Habilitar DdlChofer.Enabled = Habilitar DdlUnidadCamion.Enabled = Habilitar DdlConfigAuto.Enabled = Habilitar DdlRemolque1.Enabled = Habilitar DdlRemolque2.Enabled = Habilitar DdlDireccionOrigen.Enabled = Habilitar DdlDireccionDestino.Enabled = Habilitar TxtDistancia.Enabled = Habilitar LnkAgregarMercancia.Enabled = Habilitar GvMercanciasCP.Columns(3).Visible = Habilitar End Sub Private Sub ValidaConfiguracionVehiculo() DvRemolque1.Visible = False DvRemolque2.Visible = False DdlRemolque1.SelectedValueExist(-1) DdlRemolque2.SelectedValueExist(-1) If DdlConfigAuto.SelectedValue.ToEntero > 0 Then Using ObjGrales As New ClsGenerales If ObjGrales.GetCartaPorteConfigAutoTransportes() Then Dim Remolque As String = ObjGrales.DtResultados.FiltroPrimeroValor("Remolque", $" CveConfigAutoTransporte ='{DdlConfigAuto.SelectedValue}'") If Remolque = "1" Then RequiereRemolque = True MostrarRemolques = True End If If Remolque = "0, 1" Then RequiereRemolque = False MostrarRemolques = True End If If Remolque = "0" Then RequiereRemolque = False MostrarRemolques = False End If End If End Using Else RequiereRemolque = False MostrarRemolques = False End If If RequiereRemolque Or MostrarRemolques Then DvRemolque1.Visible = True End If If Not RequiereRemolque Then DvConfiguracionVeiculo.Visible = False Else DvConfiguracionVeiculo.Visible = True End If UpEmitirTransitorio.Update() End Sub Protected Sub DdlRemolque1_SelectedIndexChanged(sender As Object, e As EventArgs) DdlRemolque2.Items.Clear() If DdlRemolque1.SelectedValue.ToEntero > 0 Then DvRemolque2.Visible = True Using ObjInv As New ClsInventarios If ObjInv.GetCamiones(-1, UsuarioActual.CveEmpresa, 2, Estatus:=1) Then DdlRemolque2.DataSource = ObjInv.DtResultados.FiltraParametros($"CveCamion <> {DdlRemolque1.SelectedValue.ToEntero}") End If End Using DdlRemolque2.DataBind() Else DvRemolque2.Visible = False End If DdlRemolque2.Items.Insert(0, New ListItem("Seleccione uno", "-1")) UpEmitirTransitorio.Update() End Sub Private Function GuardarCartaPorte(ByRef ObjFactura As Modelos.Factura, ByRef ObjGral As ClsGenerales, ByRef ObjClientes As ClsClientes) As Integer Dim ErrorProceso As Boolean = False Dim CveTimbre As Integer = -1 Try Dim CveDireccionOrigen As Integer = DdlDireccionOrigen.SelectedValue.ToEntero Dim CveDireccionDestino As Integer = DdlDireccionDestino.SelectedValue.ToEntero 'If SucursalOrigenCP IsNot Nothing Then ' CveDireccionOrigen = ObjClientes.DireccionEnvioAdd(-1, SucursalOrigenCP.Direccion, SucursalOrigenCP.NoExt, SucursalOrigenCP.NoInt, SucursalOrigenCP.Colonia, SucursalOrigenCP.Municipio, SucursalOrigenCP.Estado, SucursalOrigenCP.CP.ToEntero(), "", UsuarioActual.CveUsuario, 1, -1, "", CveEstado:=SucursalOrigenCP.CveEstado, CvePais:=SucursalOrigenCP.CvePais, CveEmpresa:=UsuarioActual.CveEmpresa) 'End If 'If SucursalDestinoCP IsNot Nothing Then ' CveDireccionDestino = ObjClientes.DireccionEnvioAdd(-1, SucursalDestinoCP.Direccion, SucursalDestinoCP.NoExt, SucursalDestinoCP.NoInt, SucursalDestinoCP.Colonia, SucursalDestinoCP.Municipio, SucursalDestinoCP.Estado, SucursalDestinoCP.CP.ToEntero(), "", UsuarioActual.CveUsuario, 1, -1, "", CveEstado:=SucursalDestinoCP.CveEstado, CvePais:=SucursalDestinoCP.CvePais, CveEmpresa:=UsuarioActual.CveEmpresa) 'End If If Not (CveDireccionOrigen > 0 And CveDireccionDestino > 0) Then ErrorProceso = True Return -1 End If Dim Fechallegada As DateTime = TxtFechaLlegadaCP.Text.ToDateTime() Dim FechaEntrega As DateTime = TxtFechaEntregaCP.Text.ToDateTime() Dim Distancia As Integer = TxtDistancia.Text.ToEntero() Dim CveEntregaAlmacen As Integer = ObjGral.AddInvEntregaAlmacenRuta(DdlSubProyectoDatos.SelectedValue.ToEntero, CveDireccionOrigen, CveDireccionDestino, -1, DdlChofer.SelectedValue.ToEntero, DdlUnidadCamion.SelectedValue.ToEntero, FechaEntrega, Fechallegada, "I", "-1", "-1", Fechallegada, 1, 1, Distancia, CveConfigAutoTransporte:=DdlConfigAuto.SelectedValue.ToEntero, CveCamionRemolque1:=DdlRemolque1.SelectedValue.ToEntero, CveCamionRemolque2:=DdlRemolque2.SelectedValue.ToEntero) If CveEntregaAlmacen > 0 Then For Each RowPS As DataRow In ObjFactura.DtMercancias.Rows If Not ObjGral.AddEntregaAlmacenRutaDetalle(CveEntregaAlmacen, RowPS("CvePS").ToString().ToEntero, RowPS("Cantidad").ToString().ToDecimal, RowPS("CveUnidadMedida").ToString().ToEntero, UsuarioActual.CveUsuario) Then ErrorProceso = True Exit For End If Next CveTimbre = ObjGral.AddGralTimbre("Ing", DdlSubProyectoDatos.SelectedValue.ToEntero, TxtFecha.Text.ToDate, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveEntregaAlmacen:=CveEntregaAlmacen, AplicaCP:=True, CveVenta:=ObjFactura.CveVenta) If Not CveTimbre > 0 Then ErrorProceso = True End If Else ErrorProceso = True End If Catch ex As Exception ErrorProceso = True OnError("Ocurrió un error al guardar los datos de la carta porte", ex) End Try If Not ErrorProceso Then Return CveTimbre Else Return -1 End If End Function Property RequiereRemolque As Boolean Get If ViewState("RequiereRemolque") Is Nothing Then ViewState("RequiereRemolque") = False End If Return Boolean.Parse(ViewState("RequiereRemolque").ToString) End Get Set(value As Boolean) ViewState("RequiereRemolque") = value End Set End Property Property MostrarRemolques As Boolean Get If ViewState("MostrarRemolques") Is Nothing Then ViewState("MostrarRemolques") = False End If Return Boolean.Parse(ViewState("MostrarRemolques").ToString) End Get Set(value As Boolean) ViewState("MostrarRemolques") = value End Set End Property 'Property SucursalOrigenCP As Modelos.SucursalModel ' Get ' If ViewState("SucursalOrigenCP") Is Nothing Then ' Return Nothing ' End If ' Return DirectCast(ViewState("SucursalOrigenCP"), Modelos.SucursalModel) ' End Get ' Set(value As Modelos.SucursalModel) ' ViewState("SucursalOrigenCP") = value ' End Set 'End Property 'Property SucursalDestinoCP As Modelos.SucursalModel ' Get ' If ViewState("SucursalDestinoCP") Is Nothing Then ' Return Nothing ' End If ' Return DirectCast(ViewState("SucursalDestinoCP"), Modelos.SucursalModel) ' End Get ' Set(value As Modelos.SucursalModel) ' ViewState("SucursalDestinoCP") = value ' End Set 'End Property 'Private Sub CargaDireccionSucursalOrigen(Row As DataRow) ' If SucursalOrigenCP Is Nothing Then ' SucursalOrigenCP = New Modelos.SucursalModel ' Else ' SucursalOrigenCP = Nothing ' SucursalOrigenCP = New Modelos.SucursalModel ' End If ' Dim SBDomicilioSucursal As New StringBuilder() ' Try ' If Row IsNot Nothing Then ' SucursalOrigenCP.Direccion = Row("Calle").ToString() ' SucursalOrigenCP.NoExt = Row("NoExt").ToString() ' SucursalOrigenCP.NoInt = Row("NoInt").ToString() ' SucursalOrigenCP.Colonia = Row("Colonia").ToString() ' SucursalOrigenCP.CP = Row("CP").ToString() ' SucursalOrigenCP.Municipio = Row("Municipio").ToString() ' SucursalOrigenCP.CveEstado = Row("CveEstado").ToString().ToEntero() ' SucursalOrigenCP.Estado = Row("Estado").ToString() ' SucursalOrigenCP.CvePais = Row("CvePais").ToString().ToEntero() ' SucursalOrigenCP.Pais = Row("Pais").ToString() ' SBDomicilioSucursal.AppendFormat("{0}", Row("Calle").ToString()) ' If Row("NoInt").ToString().Length > 0 Then ' SBDomicilioSucursal.AppendFormat(", No.Int: {0}", Row("NoInt").ToString()) ' End If ' If Row("Colonia").ToString().Length > 0 Then ' SBDomicilioSucursal.AppendFormat(", Col: {0}", Row("Colonia").ToString()) ' End If ' If Row("CP").ToString().ToEntero > 0 Then ' SBDomicilioSucursal.AppendFormat(", CP: {0}", Row("CP").ToString()) ' End If ' If Row("NoExt").ToString().Length > 0 Then ' SBDomicilioSucursal.AppendFormat(" No.Ext: {0}", Row("NoExt").ToString()) ' End If ' Dim CiudadSucursal As String = String.Format("{0},{1}", Row("Municipio").ToString(), Row("Estado").ToString()) ' If CiudadSucursal.Length > 0 Then ' SBDomicilioSucursal.AppendFormat(", {0}", CiudadSucursal) ' End If ' If Row("Pais").ToString().Length > 0 Then ' SBDomicilioSucursal.AppendFormat(", {0}", Row("Pais").ToString()) ' End If ' If Not String.IsNullOrEmpty(Row("Telefono").ToString()) Then ' SucursalOrigenCP.TelefonoSucursal = Row("Telefono").ToString() ' End If ' End If ' Catch ex As Exception ' SBDomicilioSucursal.Clear() ' GuardaLog(ex.ToString()) ' End Try ' 'TxtOrigenCP.Text = SBDomicilioSucursal.ToString ' UpEmitirTransitorio.Update() 'End Sub Protected Sub DdlDireccionEnvio_SelectedIndexChanged(sender As Object, e As EventArgs) 'If SucursalDestinoCP Is Nothing Then ' SucursalDestinoCP = New Modelos.SucursalModel 'Else ' SucursalDestinoCP = Nothing ' SucursalDestinoCP = New Modelos.SucursalModel 'End If 'If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())).Rows.Count > 0 Then ' Dim Row As DataRow = TmpDTEnvioDireccion.FiltroPrimero(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero())) ' If Row IsNot Nothing Then ' SucursalDestinoCP.Direccion = Row("EnvioDireccion").ToString() ' SucursalDestinoCP.Colonia = Row("EnvioColonia").ToString() ' SucursalDestinoCP.Municipio = Row("EnvioCiudad").ToString() ' SucursalDestinoCP.CveEstado = Row("CveEstado").ToString().ToEntero() ' SucursalDestinoCP.Estado = Row("EnvioEstado").ToString() ' SucursalDestinoCP.CvePais = Row("CvePais").ToString().ToEntero() ' SucursalDestinoCP.Pais = Row("Pais").ToString() ' SucursalDestinoCP.CP = Row("EnvioCP").ToString() ' TxtDestinoCP.Text = String.Format("{0} col. {1},CP:{2}, {3},{4},{5}", SucursalDestinoCP.Direccion, SucursalDestinoCP.Colonia, SucursalDestinoCP.CP, SucursalDestinoCP.Municipio, SucursalDestinoCP.Estado, SucursalDestinoCP.Pais) ' Else ' TxtDestinoCP.Text = "" ' End If 'Else ' TxtDestinoCP.Text = "" 'End If UpEmitirTransitorio.Update() End Sub 'Protected Sub DdlDireccionOrigen_SelectedIndexChanged(sender As Object, e As EventArgs) ' If SucursalOrigenCP Is Nothing Then ' SucursalOrigenCP = New Modelos.SucursalModel ' Else ' SucursalOrigenCP = Nothing ' SucursalOrigenCP = New Modelos.SucursalModel ' End If ' If TmpDTDireccionCP IsNot Nothing AndAlso TmpDTDireccionCP.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionOrigen.SelectedValue.ToEntero())).Rows.Count > 0 Then ' Dim Row As DataRow = TmpDTDireccionCP.FiltroPrimero(String.Format("CveDireccionEnvio = {0}", DdlDireccionOrigen.SelectedValue.ToEntero())) ' If Row IsNot Nothing Then ' SucursalOrigenCP.Direccion = Row("EnvioDireccion").ToString() ' SucursalOrigenCP.Colonia = Row("EnvioColonia").ToString() ' SucursalOrigenCP.Municipio = Row("EnvioCiudad").ToString() ' SucursalOrigenCP.CveEstado = Row("CveEstado").ToString().ToEntero() ' SucursalOrigenCP.Estado = Row("EnvioEstado").ToString() ' SucursalOrigenCP.CvePais = Row("CvePais").ToString().ToEntero() ' SucursalOrigenCP.Pais = Row("Pais").ToString() ' SucursalOrigenCP.CP = Row("EnvioCP").ToString() ' 'TxtDestinoCP.Text = String.Format("{0} col. {1},CP:{2}, {3},{4},{5}", SucursalDestinoCP.Direccion, SucursalDestinoCP.Colonia, SucursalDestinoCP.CP, SucursalDestinoCP.Municipio, SucursalDestinoCP.Estado, SucursalDestinoCP.Pais) ' Else ' 'TxtDestinoCP.Text = "" ' End If ' Else ' 'TxtDestinoCP.Text = "" ' End If ' UpEmitirTransitorio.Update() 'End Sub 'Protected Sub DdlDireccionDestino_SelectedIndexChanged(sender As Object, e As EventArgs) ' If SucursalDestinoCP Is Nothing Then ' SucursalDestinoCP = New Modelos.SucursalModel ' Else ' SucursalDestinoCP = Nothing ' SucursalDestinoCP = New Modelos.SucursalModel ' End If ' If TmpDTDireccionCP IsNot Nothing AndAlso TmpDTDireccionCP.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionDestino.SelectedValue.ToEntero())).Rows.Count > 0 Then ' Dim Row As DataRow = TmpDTDireccionCP.FiltroPrimero(String.Format("CveDireccionEnvio = {0}", DdlDireccionDestino.SelectedValue.ToEntero())) ' If Row IsNot Nothing Then ' SucursalDestinoCP.Direccion = Row("EnvioDireccion").ToString() ' SucursalDestinoCP.Colonia = Row("EnvioColonia").ToString() ' SucursalDestinoCP.Municipio = Row("EnvioCiudad").ToString() ' SucursalDestinoCP.CveEstado = Row("CveEstado").ToString().ToEntero() ' SucursalDestinoCP.Estado = Row("EnvioEstado").ToString() ' SucursalDestinoCP.CvePais = Row("CvePais").ToString().ToEntero() ' SucursalDestinoCP.Pais = Row("Pais").ToString() ' SucursalDestinoCP.CP = Row("EnvioCP").ToString() ' 'TxtDestinoCP.Text = String.Format("{0} col. {1},CP:{2}, {3},{4},{5}", SucursalDestinoCP.Direccion, SucursalDestinoCP.Colonia, SucursalDestinoCP.CP, SucursalDestinoCP.Municipio, SucursalDestinoCP.Estado, SucursalDestinoCP.Pais) ' Else ' 'TxtDestinoCP.Text = "" ' End If ' Else ' 'TxtDestinoCP.Text = "" ' End If ' UpEmitirTransitorio.Update() 'End Sub Protected Sub LnkAgregarMercancia_Click(sender As Object, e As EventArgs) TxtCantidadMercancia.Text = "" 'DdlPSMercancia.SelectedValue = "" 'DdlPSMercancia.SelectedText = "Seleccione" UpAgregarMercancia.Update() RegistraScript("$('#DivAddMercancia').modal('show');", "M1") End Sub Private Sub CreaDTMercancias() DtMercancias = New DataTable() DtMercancias.Columns.Add(New DataColumn("Consec", GetType(Integer))) DtMercancias.Columns.Add(New DataColumn("Cantidad", GetType(Decimal))) DtMercancias.Columns.Add(New DataColumn("CvePS", GetType(Integer))) DtMercancias.Columns.Add(New DataColumn("CveUnidadMedida", GetType(Integer))) DtMercancias.Columns.Add(New DataColumn("CodigoPS", GetType(String))) End Sub Protected Sub LnkAddPSMercancia_Click(sender As Object, e As EventArgs) If DtMercancias Is Nothing Then CreaDTMercancias() End If Dim CvePS As Integer = DdlPSMercancia.SelectedValue.ToEntero() Dim DrPS As DataRow = GlobalDTPSSimplificado(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If DrPS Is Nothing Then Alert("No se encontró la mercancía", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim NewRow As DataRow = DtMercancias.NewRow NewRow("Consec") = DtMercancias.MAX("Consec").ToEntero() + 1 NewRow("Cantidad") = TxtCantidadMercancia.Text.ToDecimal() NewRow("CvePS") = DrPS("CvePS") NewRow("CveUnidadMedida") = DrPS("CveUnidadMedida") NewRow("CodigoPS") = DrPS("PSCodigo") DtMercancias.Rows.Add(NewRow) GvMercanciasCP.DataSource = DtMercancias GvMercanciasCP.DataBind() If ChkLimpiarPS.Checked Then If TmpDT IsNot Nothing Then TmpDT.Rows.Clear() End If End If Dim CvePSServicio As Integer = DdlPSFlete.SelectedValue.ToEntero() If CvePSServicio > 0 Then Dim Cantidad As Decimal = TxtCantidadMercancia.Text.ToDecimal Dim PU As Decimal = TxtPrecioMercancia.Text.Trim.ToDecimal Dim Descuento As Decimal = 0 Dim CveUM As Integer = -1 Dim UnidadMedida As String = "" Dim CveClasificacion As Integer = -1 Dim Clasificacion As String = "" Dim drPSFlete As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSServicio).FiltroPrimero("") If DrPS IsNot Nothing Then CveUM = drPSFlete("CveUnidadMedida").ToString().ToEntero() CveClasificacion = drPSFlete("CveClasificacion").ToString().ToEntero() UnidadMedida = drPSFlete("UnidadMedida").ToString() End If Dim CveSubProyecto As Integer = DdlSubProyectoDatos.SelectedValue.ToEntero() Dim CveProyecto = GlobalDTSubProyectos(-1, CveSubProyecto:=CveSubProyecto, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveProyecto", "").ToEntero() Dim Proyecto As String = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, CveProyecto, UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("Proyecto", "").ToString() AgregarProductoServicio(Cantidad, CveUM, UnidadMedida, CveClasificacion, Clasificacion, CvePSServicio, "", TxtObservacionesMercancia.Text.Trim, PU, Descuento, CveProyecto, Proyecto, CveSubProyecto, DdlSubProyectoDatos.SelectedItem.Text, Serie:="", TiempoEntrega:="", CuentaPredial:="", RegeneraIEPS:=ClienteDesglosaIEPS, CvePromocionDetalle:=-1, ImporteProntoPago:=0) CalculaTotalesVenta() Alert("Se agregó la mercancía correctamente") Else Alert("No se agregó el servicio", TipoMensaje.MsgAdvertencia) End If TxtCantidadMercancia.Text = "" TxtObservacionesMercancia.Text = "" TxtPrecioMercancia.Text = "" RegistraScript("$('#DivAddMercancia').modal('hide');", "A2") UpAgregarMercancia.Update() UpEmitirTransitorio.Update() End Sub Protected Sub GvMercanciasCP_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvMercanciasCP.RowDeleting Dim DbRow As DataRow = Nothing DbRow = DtMercancias.Rows(e.RowIndex) DtMercancias.Rows.Remove(DbRow) GvMercanciasCP.DataSource = DtMercancias GvMercanciasCP.DataBind() Alert("Eliminado Correctamente.", TipoMensaje.MsgInformacion) UpEmitirTransitorio.Update() End Sub #End Region Protected Sub BtnGenerarPoliza_Click(sender As Object, e As EventArgs) CreaObjetosVenta() If UsuarioActual.Empresa.TipoContabilidad = 2 Then Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) Dim Msgok As New StringBuilder If ObjFactura.TipoDocto.Contiene("Ing", "Egs", "OP", "Com") Then Dim IDPoliza As Modelos.RetornoPolizaConta = GenerarPolizaAC(ObjAC, ObjFactura) If IDPoliza.IdPoliza > 0 Then Dim ObjVentas As New ClsVentas If ObjVentas.UpdateVentaPrePoliza(IDPoliza.IdPoliza, IDPoliza.FolioPoliza, CvePrePoliza, CveVenta, UsuarioActual.CveEmpresa) Then 'Si se facturó la cotización hay que vincular la venta Msgok.AppendFormat("Abono Registrado Correctamente.

    Ver Poliza", IDPoliza) End If ObjVentas.Dispose() 'Si se facturó la cotización hay que vincular la venta Msgok.AppendFormat("Abono Registrado Correctamente.

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

    ") End If ObjAC.Dispose() End If End Sub Protected Sub ChkEmitirCartaPorte_CheckedChanged(sender As Object, e As EventArgs) If ChkEmitirCartaPorte.Checked AndAlso CveCliente > 0 Then Dim ObjClientes As New ClsClientes If ObjClientes.DireccionEnvioGet(-1, CveCliente, -1) Then TmpDTDireccionCP = ObjClientes.DtResultados.FiltraParametros(String.Format("Estatus = 1")) End If ObjClientes.Dispose() Else TmpDTDireccionCP = Nothing End If DdlDireccionOrigen.DataSource = TmpDTDireccionCP DdlDireccionOrigen.DataBind() DdlDireccionDestino.DataSource = TmpDTDireccionCP DdlDireccionDestino.DataBind() End Sub 'Protected Sub ChkAgregarFlete_CheckedChanged(sender As Object, e As EventArgs) ' DivServicioFlete.Visible = ChkAgregarFlete.Checked ' UpAgregarMercancia.Update() 'End Sub Protected Sub DdlPSFlete_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlPSFlete.selectedindexchange Dim CvePSParametro As Integer = DdlPSFlete.SelectedValue.ToEntero() If CvePSParametro > 0 Then Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSParametro).FiltroPrimero("") If drPS IsNot Nothing Then Dim CvePSMercancia As Integer = drPS("CvePSAdicionalVigencia").ToString().ToEntero() Dim CveClasificacion As Integer = drPS("CveClasificacion").ToString().ToEntero() If CvePSMercancia > 0 Then If UsuarioActual.Empresa.Funcionalidad(141).ToString() = "1" Then DdlPSMercancia.SelectedValue = CvePSMercancia.ToString() 'DdlPSMercancia.SelectedText = TxtPS.Text.Trim Else 'DdlPSMercancia.ddl.Items.Insert(2, New ListItem(TxtPS.Text.Trim, ObjProductosServicios.CvePS.ToString())) DdlPSMercancia.ddl.SelectedValueExist(CvePSMercancia.ToString()) End If End If 'SUGIERE PRECIO Dim PrecioSugerido As Decimal = 0 Dim tPrecioSugerido As Decimal = 0 tPrecioSugerido = drPS("Precio").ToString().ToDecimal If UsuarioActual.CveEmpresa.Contiene(1) Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPorcentajeProductos(CveCliente) Then Dim PrecioAplicado = ObjPS.DtResultados.FiltraParametros($"CvePS = {CvePSParametro}").FiltroPrimeroValor("PrecioA").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 End If If CvePrecioListaPS > 0 Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDecimal PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal End If ObjPS.Dispose() End If If PrecioSugerido = 0 Then Dim ObjInventarios As New ClsInventarios Dim CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidadMercancia.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero(), CveTipoAlmacen:=1) 'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidadMercancia.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1, CveTipoAlmacen:=1) ObjInventarios.Dispose() If CostoPS > 0 And PorcentajePrecio > 0 Then PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS End If End If CvePrecioLista = CvePrecioListaPS End If 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 If PrecioSugerido <= 0 Then PrecioSugerido = tPrecioSugerido TxtPrecioMercancia.Text = PrecioSugerido.ToString("#,###.####") ' que muestre hasta los 4 digitos si lo requiere End If End If UpAgregarMercancia.Update() End Sub Protected Sub LnkUUIDRelacionados_Click(sender As Object, e As EventArgs) Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, LblRFC.Text, TxtTotal.Text, True) Dim sb As New StringBuilder sb.AppendFormat("{0}
    ", Vigencia.EsCancelable) Dim Relacionados = Timbrado.ConsultarUUIDRelacionados(UsuarioActual.Empresa, FolioFiscal, UsuarioActual.Empresa.FacturaProduccion) If Relacionados IsNot Nothing Then Dim sbExtra As New StringBuilder() If Relacionados.Codigo = 500 Then sbExtra.Append("El servicio de verificación de documentos relacionados no esta disponible.") Else sbExtra.Append(Relacionados.Mensaje) Dim SbHijos = New StringBuilder() Dim SbPadres = New StringBuilder() If Relacionados.RelacionadosPadre IsNot Nothing Then For Each padre In Relacionados.RelacionadosPadre SbPadres.AppendFormat("{0};", padre.Uuid) Next If SbPadres.Length > 0 Then SbPadres.Remove(SbPadres.Length - 1, 1) End If End If Using ObjVentas As New ClsVentas If SbPadres.Length > 0 Then If ObjVentas.GetFacturasRelacionadasPorFolioFiscal(SbPadres.ToString(), UsuarioActual.CveEmpresa) Then Dim dtt As DataTable = ObjVentas.DtResultados.FiltraParametros($"CveVenta <> {CveVenta}") For Each dr As DataRow In dtt.Rows sb.AppendFormat("{0}-{1}-{2}
    ", dr("TipoDocto"), dr("SerieFolio"), dr("FolioFiscal")) Next End If End If End Using End If If sbExtra.Length > 0 Then LbExtraRefacturacion.Text = $"
    *{sbExtra.ToString()}" End If End If Alert(sb.ToString(), TipoMensaje.MsgInformacion) 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 Protected Sub ChkEmitirComercioExterior_CheckedChanged(sender As Object, e As EventArgs) End Sub Protected Sub DdlLineaAdicional_SelectedIndexChanged(sender As Object, e As EventArgs) If DdlLineaAdicional.SelectedValue.ToEntero() > 0 Then RBLPago.SelectedValue = "1" RBLPago.Enabled = False Using ObjVentas As New ClsVentas If ObjVentas.GetLineasAdicionalesSaldo(DdlLineaAdicional.SelectedValue.ToEntero(), CveCliente, -1, DdlMoneda.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) Then If ObjVentas.DtResultados.Rows.Count > 0 Then TxtFechaPago.Text = ObjVentas.DtResultados.Rows(0)("FechaVencimiento").ToString().ToDateTime().ToString("dd/MM/yyyy") Me.SaldoLineaAdicional = ObjVentas.DtResultados.Rows(0)("Saldo").ToString().ToDecimal() Me.CveClasificacionLineaAdicional = ObjVentas.DtResultados.Rows(0)("CveClasificacionPS").ToString().ToEntero() Me.CveMonedaLineaAdicional = ObjVentas.DtResultados.Rows(0)("CveMoneda").ToString().ToEntero() End If End If End Using Else Me.SaldoLineaAdicional = 0 Me.CveClasificacionLineaAdicional = 0 End If UPCondicionesPago.Update() End Sub Protected Sub LnkUpdateLineaAdicional_Click(sender As Object, e As EventArgs) 'VALIDAR LINEAS ADICIONALES If UsuarioActual.Empresa.Funcionalidad(705) = "1" AndAlso DdlLineaAdicional.SelectedValue.ToEntero() > 0 Then 'VERIFICA QUE LA CLASIFICACION DE LOS PRODUCTOS DEBE SER LA MISMA DE LA LINEA ADICIONAL If TmpDT IsNot Nothing AndAlso Me.CveClasificacionLineaAdicional > 0 Then For Each Row As DataRow In TmpDT.FiltraParametros("", DistinctColumns:={"CveClasificacion", "Clasificacion"}).Rows If Me.CveClasificacionLineaAdicional <> Row("CveClasificacion").ToString().ToEntero() Then Alert($"La clasificación '{Row("Clasificacion")}' no pertenece a la linea adicional.", TipoMensaje.MsgAdvertencia) Exit Sub End If Next End If If Me.SaldoLineaAdicional <= 0 Then Alert("El saldo de la linea adicional debe ser mayor a cero", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VERIFICA QUE EL SALDO DISPONIBLE SEA MENOR AL IMPORTE If Me.SaldoLineaAdicional <= TxtTotal.Text.ToDecimal() Then Alert("El saldo de la linea adicional debe ser mayor o igual al de la factura", TipoMensaje.MsgAdvertencia) Exit Sub End If 'VERIFICA QUE LA MONEDA DE LA LINEA ADICIONAL SEA LA MISMA QUE LA VENTA If Me.CveMonedaLineaAdicional <> DdlMoneda.SelectedValue.ToEntero() Then Alert("La moneda de la linea adicional de crédito debe ser la misma que la factura.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If Using ObjVentas As New ClsVentas If ObjVentas.UpdateVentaLineaAdicional(DdlLineaAdicional.SelectedValue.ToEntero(), Me.CveVenta, UsuarioActual.CveEmpresa) Then Alert("Se actualizo la linea adicional de crédito de la venta") End If End Using End Sub End Class