Files
SIG/Ventas/Ventas.aspx.vb

22647 lines
1.2 MiB

Option Explicit On
Option Strict On
Imports Extensiones
Imports System.Data
Imports System.IO
Imports System.Xml
Imports Microsoft.Reporting.WebForms
Imports System.Security.Cryptography.X509Certificates
Imports System.Globalization
Partial Class Ventas
Inherits ClsPaginas
#Region "Propiedades"
Private Const NumeroDecimales As Integer = 2
Dim ColumnaDescuento As Integer = 10
Dim ColumnaPredial As Integer = 11
Dim ColumnaIVA As Integer = 12
Dim ColumnaIEPS As Integer = 13
Dim ColumnaRetIVA As Integer = 14
Dim ColumnaRetISR As Integer = 15
Dim ColumnaEditar As Integer = 17
Dim ColumnaEliminar As Integer = 18
'Factura de ventas
Dim DTConceptos As DataTable
Private Property Version As String
Private Property Fecha As String
Private Property SerieXML As String
Private Property FolioXML As String
Private Property SubTotal As Decimal
Private Property Total As Decimal = 0
Private Property Descuentos As Decimal = 0
Private Property EmisorRFC As String
Private Property ReceptorRFC As String
Private Property TrasladoIVA As Decimal = 0
Private Property RetencionIVA As Decimal = 0
Private Property RetencionISR As Decimal = 0
Private Property TrasladoIEPS As Decimal = 0
Private Property TFDUUID As String = ""
Private Property Moneda As String = ""
Private Property TipoComprobante As String = ""
Private Property OtrosImpuestos As Decimal = 0
Private Property TotalRetenciones As Decimal = 0
Private Property SumaTotalRetenciones As Decimal = 0
Private Property TotalTraslados As Decimal = 0
Private Property SumaTotalTraslados As Decimal = 0
Private Property SubTotalConceptos As Decimal = 0
Private Property Redondeo As Decimal = 0
Private Property NumRow As Integer
Private Property EsSupervisor As Boolean = False
Private Property MandarCorreoSupervisor As Boolean = False
Private ReadOnly Property ExFolioFactura As Boolean
Get
Return CBool(ViewState("ExFolioFactura"))
End Get
End Property
Private Property CveFactura As Integer
Get
Return ViewState("CveFactura").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveFactura") = value
End Set
End Property
Private Property idCuentaContabilizacion As Integer
Get
Return ViewState("idCuentaContabilizacion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("idCuentaContabilizacion") = value
End Set
End Property
Private Property CuentasContablesInvalidas As StringBuilder
Get
Return CType(ViewState("CuentasContablesInvalidas"), StringBuilder)
End Get
Set(value As StringBuilder)
ViewState("CuentasContablesInvalidas") = value
End Set
End Property
'Local
Private Property TmpDT As DataTable
Get
Return If(IsNothing(ViewState("TmpDT")), Nothing, CType(ViewState("TmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDT") = value
End Set
End Property
Private Property TmpDTError As DataTable
Get
Return If(IsNothing(ViewState("TmpDTError")), Nothing, CType(ViewState("TmpDTError"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTError") = value
End Set
End Property
Private Property TmpDTImpuestos As DataTable
Get
Return If(IsNothing(ViewState("TmpDTImpuestos")), Nothing, CType(ViewState("TmpDTImpuestos"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTImpuestos") = value
End Set
End Property
Private Property TmpDTImpuestosIVAIEPS As DataTable
Get
Return If(IsNothing(ViewState("TmpDTImpuestosIVAIEPS")), Nothing, CType(ViewState("TmpDTImpuestosIVAIEPS"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTImpuestosIVAIEPS") = value
End Set
End Property
Private Property TmpDTDocumentosRelacionados As DataTable
Get
Return If(IsNothing(ViewState("TmpDTDocumentosRelacionados")), Nothing, CType(ViewState("TmpDTDocumentosRelacionados"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTDocumentosRelacionados") = value
End Set
End Property
Private Property TmpDTNCVinculadas As DataTable
Get
Return If(IsNothing(ViewState("TmpDTNCVinculadas")), Nothing, CType(ViewState("TmpDTNCVinculadas"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTNCVinculadas") = value
End Set
End Property
Private Property TmpDTEnvioDireccion As DataTable
Get
Return If(IsNothing(ViewState("TmpDTEnvioDireccion")), Nothing, CType(ViewState("TmpDTEnvioDireccion"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTEnvioDireccion") = value
End Set
End Property
Private Property IdPoliza As Integer
Get
Return ViewState("IdPoliza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("IdPoliza") = value
End Set
End Property
Private Property CveAlmacenDevolucion As Integer
Get
Return ViewState("CveAlmacenDevolucion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveAlmacenDevolucion") = value
End Set
End Property
Private Property EraCotizacion As Integer
Get
Return ViewState("EraCotizacion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("EraCotizacion") = value
End Set
End Property
Private Property FacturaMateriales As Integer
Get
Return ViewState("FacturaMateriales").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("FacturaMateriales") = value
End Set
End Property
Private Property TmpDTDeducciones As DataTable
Get
Return If(IsNothing(ViewState("TmpDTDeducciones")), Nothing, CType(ViewState("TmpDTDeducciones"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTDeducciones") = value
End Set
End Property
Private Property TmpDTComplementos As DataTable
Get
Return If(IsNothing(ViewState("TmpDTComplementos")), Nothing, CType(ViewState("TmpDTComplementos"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTComplementos") = value
End Set
End Property
Private Property DTmpC As DataTable
Get
Return If(IsNothing(ViewState("DTmpC")), Nothing, CType(ViewState("DTmpC"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTmpC") = value
End Set
End Property
Private Property DTmpF As DataTable
Get
Return If(IsNothing(ViewState("DTmpF")), Nothing, CType(ViewState("DTmpF"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTmpF") = value
End Set
End Property
Private Property DTSucursal As DataTable
Get
Return If(IsNothing(ViewState("DTSucursal")), Nothing, CType(ViewState("DTSucursal"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTSucursal") = value
End Set
End Property
Private Property DTOrdenesCompra As DataTable
Get
Return If(IsNothing(ViewState("DTOrdenesCompra")), Nothing, CType(ViewState("DTOrdenesCompra"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTOrdenesCompra") = value
End Set
End Property
Private Property DTOrdenesCompraPS As DataTable
Get
Return If(IsNothing(ViewState("DTOrdenesCompraPS")), Nothing, CType(ViewState("DTOrdenesCompraPS"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTOrdenesCompraPS") = value
End Set
End Property
Private Property DtOCTmpDT As DataTable
Get
Return If(IsNothing(ViewState("DtOCTmpDT")), Nothing, CType(ViewState("DtOCTmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtOCTmpDT") = value
End Set
End Property
Private Property DTRemisiones As DataTable
Get
Return If(IsNothing(ViewState("DTRemisiones")), Nothing, CType(ViewState("DTRemisiones"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTRemisiones") = value
End Set
End Property
Private Property RemisionesLista As List(Of Integer)
Get
Return If(IsNothing(ViewState("RemisionesLista")), Nothing, CType(ViewState("RemisionesLista"), List(Of Integer)))
End Get
Set(value As List(Of Integer))
ViewState("RemisionesLista") = value
End Set
End Property
Private Property Pedidos2Lista As List(Of Integer)
Get
Return If(IsNothing(ViewState("Pedidos2Lista")), Nothing, CType(ViewState("Pedidos2Lista"), List(Of Integer)))
End Get
Set(value As List(Of Integer))
ViewState("Pedidos2Lista") = value
End Set
End Property
Private Property DtRemisionesPS As DataTable
Get
Return If(IsNothing(ViewState("DtRemisionesPS")), Nothing, CType(ViewState("DtRemisionesPS"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtRemisionesPS") = value
End Set
End Property
Private Property DtCotizaciones As DataTable
Get
Return If(IsNothing(ViewState("DtCotizaciones")), Nothing, CType(ViewState("DtCotizaciones"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtCotizaciones") = value
End Set
End Property
Private Property CotizacionesLista As List(Of Integer)
Get
Return If(IsNothing(ViewState("CotizacionesLista")), Nothing, CType(ViewState("CotizacionesLista"), List(Of Integer)))
End Get
Set(value As List(Of Integer))
ViewState("CotizacionesLista") = value
End Set
End Property
Private Property DtCotizacionesPS As DataTable
Get
Return If(IsNothing(ViewState("DtCotizacionesPS")), Nothing, CType(ViewState("DtCotizacionesPS"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtCotizacionesPS") = value
End Set
End Property
Private Property DtCotizacionTmpDT As DataTable
Get
Return If(IsNothing(ViewState("DtCotizacionTmpDT")), Nothing, CType(ViewState("DtCotizacionTmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtCotizacionTmpDT") = value
End Set
End Property
Private Property DtRemisionesTmpDT As DataTable
Get
Return If(IsNothing(ViewState("DtRemisionesTmpDT")), Nothing, CType(ViewState("DtRemisionesTmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtRemisionesTmpDT") = value
End Set
End Property
Private Property DtPedidos2TmpDT As DataTable
Get
Return If(IsNothing(ViewState("DtPedidos2TmpDT")), Nothing, CType(ViewState("DtPedidos2TmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtPedidos2TmpDT") = value
End Set
End Property
Private Property DtRemConceptosSurtidos As DataTable
Get
Return If(IsNothing(ViewState("DtRemConceptosSurtidos")), Nothing, CType(ViewState("DtRemConceptosSurtidos"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtRemConceptosSurtidos") = value
End Set
End Property
Private Property HuboCambioRemi As Boolean
Get
Return If(IsNothing(ViewState("HuboCambioRemi")), False, CType(ViewState("HuboCambioRemi"), Boolean))
End Get
Set(value As Boolean)
ViewState("HuboCambioRemi") = value
End Set
End Property
Private Property AplicaGastoContrato As Boolean
Get
Return If(IsNothing(ViewState("AplicaGastoContrato")), False, CType(ViewState("AplicaGastoContrato"), Boolean))
End Get
Set(value As Boolean)
ViewState("AplicaGastoContrato") = value
End Set
End Property
Private Property EsCreaApartirDe As Boolean
Get
Return If(IsNothing(ViewState("EsCreaApartirDe")), False, CType(ViewState("EsCreaApartirDe"), Boolean))
End Get
Set(value As Boolean)
ViewState("EsCreaApartirDe") = value
End Set
End Property
Private Property RequiereAlmacenDestino As Boolean
Get
Return If(IsNothing(ViewState("RequiereAlmacenDestino")), False, CType(ViewState("RequiereAlmacenDestino"), Boolean))
End Get
Set(value As Boolean)
ViewState("RequiereAlmacenDestino") = value
End Set
End Property
Private Property RequiereAlmacenOrigen As Boolean
Get
Return If(IsNothing(ViewState("RequiereAlmacenOrigen")), False, CType(ViewState("RequiereAlmacenOrigen"), Boolean))
End Get
Set(value As Boolean)
ViewState("RequiereAlmacenOrigen") = value
End Set
End Property
Private Property EmpresaActual As Empresa
Get
Return CType(ViewState("EmpresaActual"), Empresa)
End Get
Set(value As Empresa)
ViewState("EmpresaActual") = value
End Set
End Property
Property CargaDocumentoOC As Boolean
Get
If ViewState("CargaDocumentoOC") Is Nothing Then
Return False
Else
Return DirectCast(ViewState("CargaDocumentoOC"), Boolean)
End If
End Get
Set(value As Boolean)
ViewState("CargaDocumentoOC") = value
End Set
End Property
Private Property DTFacNC As DataTable
Get
Return If(IsNothing(ViewState("DTFacNC")), Nothing, CType(ViewState("DTFacNC"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTFacNC") = value
End Set
End Property
Private Property DtPromociones As DataTable
Get
Return If(IsNothing(ViewState("DtPromociones")), Nothing, CType(ViewState("DtPromociones"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtPromociones") = value
End Set
End Property
Private ReadOnly Property CveCliente As Integer
Get
Return ViewState("CveCliente").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CveClienteAnterior As Integer
Get
Return ViewState("CveClienteAnterior").ToString.ToEntero
End Get
End Property
Private Property CveClienteSucursal As Integer
Get
If ViewState("CveClienteSucursal") Is Nothing Then
Return -1
Else
Return ViewState("CveClienteSucursal").ToString.ToEntero
End If
End Get
Set(value As Integer)
ViewState("CveClienteSucursal") = value
End Set
End Property
Private Property CveAnticipo As Integer
Get
If ViewState("CveAnticipo") Is Nothing Then
Return -1
Else
Return ViewState("CveAnticipo").ToString.ToEntero
End If
End Get
Set(value As Integer)
ViewState("CveAnticipo") = value
End Set
End Property
Private Property CveUsuarioActual As Integer
Get
Return ViewState("CveUsuarioActual").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveUsuarioActual") = value
End Set
End Property
Private ReadOnly Property Mail As String
Get
Return ViewState("Mail").ToString
End Get
End Property
Private ReadOnly Property MailCC As String
Get
Return ViewState("MailCC").ToString
End Get
End Property
Private ReadOnly Property CveVenta As Integer
Get
Return ViewState("CveVenta").ToString.ToEntero
End Get
End Property
Private Property CveVentaPadre As Integer
Get
Return If(IsNothing(ViewState("CveVentaPadre")), -1, ViewState("CveVentaPadre").ToString.ToEntero)
End Get
Set(value As Integer)
ViewState("CveVentaPadre") = value
End Set
End Property
Private Property CveEstatusFacturaPadre As Integer
Get
Return If(IsNothing(ViewState("CveEstatusFacturaPadre")), -1, ViewState("CveEstatusFacturaPadre").ToString.ToEntero)
End Get
Set(value As Integer)
ViewState("CveEstatusFacturaPadre") = value
End Set
End Property
Private Property CveMovimientoDetalle As Integer
Get
Return If(IsNothing(ViewState("CveMovimientoDetalle")), -1, ViewState("CveMovimientoDetalle").ToString.ToEntero)
End Get
Set(value As Integer)
ViewState("CveMovimientoDetalle") = value
End Set
End Property
Private ReadOnly Property CveDevolucion As Integer
Get
Return ViewState("CveDevolucion").ToString.ToEntero
End Get
End Property
Private Property CveVentaRelacion As Integer
Get
Return If(IsNothing(ViewState("CveVentaRelacion")), -1, ViewState("CveVentaRelacion").ToString.ToEntero)
End Get
Set(value As Integer)
ViewState("CveVentaRelacion") = value
End Set
End Property
Private Property ImporteRelacion As Double
Get
Return If(IsNothing(ViewState("ImporteRelacion")), 0, ViewState("ImporteRelacion").ToString.ToDouble)
End Get
Set(value As Double)
ViewState("ImporteRelacion") = value
End Set
End Property
Private Property IsTotalxConcepto As Boolean
Get
Return If(IsNothing(ViewState("IsTotalxConcepto")), False, CBool(ViewState("IsTotalxConcepto").ToString))
End Get
Set(value As Boolean)
ViewState("IsTotalxConcepto") = value
End Set
End Property
Private ReadOnly Property CveAlmacenTransitorio As Integer
Get
Return ViewState("CveAlmacenTransitorio").ToString.ToEntero
End Get
End Property
Private ReadOnly Property NuevaFactura As Integer
Get
Return ViewState("NuevaFactura").ToString.ToEntero
End Get
End Property
Private ReadOnly Property VentaFolio As String
Get
Return ViewState("VentaFolio").ToString
End Get
End Property
Private ReadOnly Property SelloCancelacion As String
Get
Return ViewState("SelloCancelacion").ToString
End Get
End Property
Private ReadOnly Property FechaCancelacion As DateTime
Get
Return ViewState("FechaCancelacion").ToString.ToDateTime
End Get
End Property
Private ReadOnly Property EstablecioFolio As Boolean
Get
Return CBool(ViewState("EstablecioFolio"))
End Get
End Property
Private ReadOnly Property FolioFiscal As String
Get
Return ViewState("FolioFiscal").ToString
End Get
End Property
Private ReadOnly Property Ruta As String
Get
Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\" & UsuarioActual.CveEmpresa & "\"
End Get
End Property
Private ReadOnly Property RutaPruebas As String
Get
Return AppDomain.CurrentDomain.BaseDirectory & "Empresas\1\"
End Get
End Property
Private ReadOnly Property TipoCambio As Decimal
Get
Return ViewState("TipoCambio").ToString.ToDecimal
End Get
End Property
Private ReadOnly Property ProcesoCorrecto As Boolean
Get
Return CBool(ViewState("ProcesoCorrecto"))
End Get
End Property
'FUENTES RECAUDACIÓN
Private Property DTPresupuestoIngresos As DataTable
Get
Return CType(ViewState("DTPresupuestoIngresos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTPresupuestoIngresos") = value
End Set
End Property
'Folios
Private ReadOnly Property CveFolio As Integer
Get
Return ViewState("CveFolio").ToString.ToEntero
End Get
End Property
Private ReadOnly Property NumAprobacion As Long
Get
Return CLng(ViewState("NumAprobacion").ToString)
End Get
End Property
Private ReadOnly Property FechaAprobacion As Date
Get
Return ViewState("FechaAprobacion").ToString.ToDate
End Get
End Property
Private ReadOnly Property FolioActual As String
Get
Return ViewState("FolioActual").ToString
End Get
End Property
'Sucursal
Private ReadOnly Property Serie As String
Get
Return ViewState("Serie").ToString
End Get
End Property
Private ReadOnly Property Folio As Integer
Get
Return ViewState("Folio").ToString.ToEntero
End Get
End Property
Private ReadOnly Property FormatoFactura As String
Get
Return ViewState("FormatoFactura").ToString
End Get
End Property
Private ReadOnly Property TipoFormato As String
Get
Return ViewState("TipoFormato").ToString
End Get
End Property
Private ReadOnly Property IVA As Decimal
Get
Return ViewState("IVA").ToString.ToDecimal
End Get
End Property
'Private ReadOnly Property SubProyectoPorcentajeIVA As Decimal
' Get
' Return ViewState("SubProyectoPorcentajeIVA").ToString.ToDecimal
' End Get
'End Property
Private ReadOnly Property ClienteRetIVA As Decimal
Get
Return ViewState("ClienteRetIVA").ToString.ToDecimal
End Get
End Property
Private ReadOnly Property ClienteRetISR As Decimal
Get
Return ViewState("ClienteRetISR").ToString.ToDecimal
End Get
End Property
Private ReadOnly Property ClienteDesglosaIEPS As Boolean
Get
Return CType(ViewState("ClienteDesglosaIEPS").ToString, Boolean)
End Get
End Property
'Cliente
Private ReadOnly Property NombreCliente As String
Get
Return ViewState("NombreCliente").ToString
End Get
End Property
Private ReadOnly Property Vendedor As String
Get
Return ViewState("Vendedor").ToString
End Get
End Property
Private ReadOnly Property CtaContable As String
Get
Return ViewState("CtaContable").ToString
End Get
End Property
Private ReadOnly Property IdCtaContClientes As Integer
Get
Return ViewState("IdCtaContClientes").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CveCuentaClientes As Integer
Get
Return ViewState("CveCuentaClientes").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContMonedaExtranjera As Integer
Get
Return ViewState("IdCtaContMonedaExtranjera").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContComplementaria As Integer
Get
Return ViewState("IdCtaContComplementaria").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContAnticipos As Integer
Get
Return ViewState("IdCtaContAnticipos").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CveCuentaAnticipos As Integer
Get
Return ViewState("CveCuentaAnticipos").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContRetIVA As Integer
Get
Return ViewState("IdCtaContRetIVA").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CveCuentaRetIVA As Integer
Get
Return ViewState("CveCuentaRetIVA").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContRetISR As Integer
Get
Return ViewState("IdCtaContRetISR").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CveCuentaRetISR As Integer
Get
Return ViewState("CveCuentaRetISR").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CodCliente As String
Get
Return ViewState("CodCliente").ToString
End Get
End Property
Private ReadOnly Property CliNoExt As String
Get
Return ViewState("CliNoExt").ToString
End Get
End Property
Private ReadOnly Property CliNoInt As String
Get
Return ViewState("CliNoInt").ToString
End Get
End Property
Private ReadOnly Property CliLocalidad As String
Get
Return ViewState("CliLocalidad").ToString
End Get
End Property
Private ReadOnly Property CliPais As String
Get
Return ViewState("CliPais").ToString
End Get
End Property
Private ReadOnly Property SucCalle As String
Get
Return ViewState("SucCalle").ToString
End Get
End Property
Private ReadOnly Property CliCorreoCot As String
Get
If ViewState("CliCorreoCot") Is Nothing Then
Return ""
Else
Return ViewState("CliCorreoCot").ToString
End If
End Get
End Property
Private ReadOnly Property SucNoExt As String
Get
Return ViewState("SucNoExt").ToString
End Get
End Property
Private ReadOnly Property SucNoInt As String
Get
Return ViewState("SucNoInt").ToString
End Get
End Property
Private ReadOnly Property SucColonia As String
Get
Return ViewState("SucColonia").ToString
End Get
End Property
Private ReadOnly Property SucLocalidad As String
Get
Return ViewState("SucLocalidad").ToString
End Get
End Property
Private ReadOnly Property SucMunicipio As String
Get
Return ViewState("SucMunicipio").ToString
End Get
End Property
Private ReadOnly Property SucEstado As String
Get
Return ViewState("SucEstado").ToString
End Get
End Property
Private ReadOnly Property SucPais As String
Get
Return ViewState("SucPais").ToString
End Get
End Property
Private ReadOnly Property SucCP As String
Get
Return ViewState("SucCP").ToString
End Get
End Property
Private ReadOnly Property MatCalle As String
Get
Return ViewState("MatCalle").ToString
End Get
End Property
Private ReadOnly Property MatNoExt As String
Get
Return ViewState("MatNoExt").ToString
End Get
End Property
Private ReadOnly Property MatNoInt As String
Get
Return ViewState("MatNoInt").ToString
End Get
End Property
Private ReadOnly Property MatColonia As String
Get
Return ViewState("MatColonia").ToString
End Get
End Property
Private ReadOnly Property MatLocalidad As String
Get
Return ViewState("MatLocalidad").ToString
End Get
End Property
Private ReadOnly Property MatMunicipio As String
Get
Return ViewState("MatMunicipio").ToString
End Get
End Property
Private ReadOnly Property MatEstado As String
Get
Return ViewState("MatEstado").ToString
End Get
End Property
Private ReadOnly Property MatPais As String
Get
Return ViewState("MatPais").ToString
End Get
End Property
Private ReadOnly Property MatCP As String
Get
Return ViewState("MatCP").ToString
End Get
End Property
Private Property ImprimeNombreSucursal As Boolean
Get
Return CBool(ViewState("ImprimeNombreSucursal"))
End Get
Set(value As Boolean)
ViewState("ImprimeNombreSucursal") = value
End Set
End Property
Private ReadOnly Property AplicaFEMSA As Boolean
Get
Return CBool(ViewState("AplicaFEMSA"))
End Get
End Property
Private ReadOnly Property AplicaComercioExterior As Boolean
Get
Return CBool(ViewState("AplicaComercioExterior"))
End Get
End Property
Private ReadOnly Property CveTipoOperacion As Integer
Get
Return CInt(ViewState("CveTipoOperacion"))
End Get
End Property
Private ReadOnly Property CvePedimento As Integer
Get
Return CInt(ViewState("CvePedimento"))
End Get
End Property
Private ReadOnly Property CveIncoterm As Integer
Get
Return CInt(ViewState("CveIncoterm"))
End Get
End Property
Private ReadOnly Property AplicaDetallista As Boolean
Get
Return CBool(ViewState("AplicaDetallista"))
End Get
End Property
Private ReadOnly Property AplicaFord As Boolean
Get
Return CBool(ViewState("AplicaFord"))
End Get
End Property
Private ReadOnly Property CveOS As Integer
Get
Return ViewState("CveOS").ToString.ToEntero
End Get
End Property
Private ReadOnly Property SaldoVenta As Decimal
Get
Return If(IsNothing(ViewState("SaldoVenta")), 0, ViewState("SaldoVenta").ToString.ToDecimal)
End Get
End Property
Private Property CvePSAmortizacion As Integer
Get
Return ViewState("CvePSAmortizacion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePSAmortizacion") = value
End Set
End Property
'Inventarios
Private Property DtInv As DataTable
Get
Return CType(ViewState("DtInv"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtInv") = value
End Set
End Property
Private Property CvePrePoliza As Integer
Get
Return ViewState("CvePrePoliza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePrePoliza") = value
End Set
End Property
Private ReadOnly Property SeGuardoPrePoliza As Boolean
Get
Return CBool(ViewState("SeGuardoPrePoliza"))
End Get
End Property
Private Property CveVentaFacturada As Integer
Get
Return ViewState("CveVentaFacturada").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveVentaFacturada") = value
End Set
End Property
Private ReadOnly Property AplicarVentaFacturada As Boolean
Get
Return CBool(ViewState("AplicarVentaFacturada"))
End Get
End Property
'Estimaciones
Private Property CveContrato As Integer
Get
Return ViewState("CveContrato").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveContrato") = value
End Set
End Property
Private Property CvePedido As Integer
Get
Return ViewState("CvePedido").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePedido") = value
End Set
End Property
Private Property CvePedido2 As Integer
Get
Return ViewState("CvePedido2").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePedido2") = value
End Set
End Property
Private Property TipoContrato As Integer
Get
Return ViewState("TipoContrato").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("TipoContrato") = value
End Set
End Property
Private Property Opcion As String
Get
Return ViewState("Opcion").ToString
End Get
Set(value As String)
ViewState("Opcion") = value
End Set
End Property
Private Property CorreoNotificacionPedDev As String
Get
Return If(IsNothing(ViewState("CorreoNotificacionDevPed")), "", ViewState("CorreoNotificacionDevPed").ToString())
End Get
Set(value As String)
ViewState("CorreoNotificacionDevPed") = value
End Set
End Property
'Presupuesto
Private Property CvePresupuesto As Integer
Get
Return ViewState("CvePresupuesto").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePresupuesto") = value
End Set
End Property
Private Property TotalOtrosConceptos As Decimal
Get
Return ViewState("TotalOtrosConceptos").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TotalOtrosConceptos") = value
End Set
End Property
Private Property TipoCambioFactura As Decimal
Get
Return ViewState("TipoCambioFactura").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TipoCambioFactura") = value
End Set
End Property
Private Property DtPagos As DataTable
Get
Return CType(ViewState("DtPagos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPagos") = value
End Set
End Property
Private Property DevolucionAlmacen As Integer
Get
Return ViewState("DevolucionAlmacen").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("DevolucionAlmacen") = value
End Set
End Property
Private ReadOnly Property TipoDoctoDevolucion As String
Get
Return ViewState("TipoDoctoDevolucion").ToString
End Get
End Property
Private Property PlazoCobranza As Integer
Get
Return ViewState("PlazoCobranza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("PlazoCobranza") = value
End Set
End Property
Private Property PlazoCobranzaRemision As Integer
Get
Return ViewState("PlazoCobranzaRemision").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("PlazoCobranzaRemision") = value
End Set
End Property
'CvePAC
Private Property CvePAC As Integer
Get
Return ViewState("CvePAC").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePAC") = value
End Set
End Property
Private Property AplicaDevolucion As Boolean
Get
Return If(IsNothing(ViewState("AplicaDevolucion")), False, CType(ViewState("AplicaDevolucion"), Boolean))
End Get
Set(value As Boolean)
ViewState("AplicaDevolucion") = value
End Set
End Property
Private Property CveVentaDevolucion As Integer
Get
Return If(IsNothing(ViewState("CveVentaDevolucion")), 0, CType(ViewState("CveVentaDevolucion"), Integer))
End Get
Set(value As Integer)
ViewState("CveVentaDevolucion") = value
End Set
End Property
Private Property SaldoVentaDevolucion As Decimal
Get
Return ViewState("SaldoVentaDevolucion").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("SaldoVentaDevolucion") = value
End Set
End Property
Private Property ContratoOC As Boolean
Get
Return If(IsNothing(ViewState("ContratoOC")), False, CType(ViewState("ContratoOC"), Boolean))
End Get
Set(value As Boolean)
ViewState("ContratoOC") = value
End Set
End Property
Private Property TieneAlmacen As Boolean
Get
Return If(IsNothing(ViewState("TieneAlmacen")), False, CType(ViewState("TieneAlmacen"), Boolean))
End Get
Set(value As Boolean)
ViewState("TieneAlmacen") = value
End Set
End Property
Private Property PorcentajeIVA As Decimal
Get
Return ViewState("PorcentajeIVA").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("PorcentajeIVA") = value
End Set
End Property
Private Property CveEstatusRefacturacion As Integer
Get
Return If(IsNothing(ViewState("CveEstatusRefacturacion")), 0, CType(ViewState("CveEstatusRefacturacion"), Integer))
End Get
Set(value As Integer)
ViewState("CveEstatusRefacturacion") = value
End Set
End Property
#End Region
#Region "Propiedades PuntoVenta"
Private Property CveCorte As Integer
Get
Return ViewState("CveCorte").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveCorte") = value
End Set
End Property
Private Property Entrega As String
Get
Return ViewState("Entrega").ToString
End Get
Set(value As String)
ViewState("Entrega") = value
End Set
End Property
Private Property Vigencia As String
Get
Return ViewState("Vigencia").ToString
End Get
Set(value As String)
ViewState("Vigencia") = value
End Set
End Property
Private Property DineroCaja As Double
Get
Return ViewState("DineroCaja").ToString.ToDouble
End Get
Set(value As Double)
ViewState("DineroCaja") = value
End Set
End Property
Private ReadOnly Property CveCicloComercial As Integer
Get
Return ViewState("CveCicloComercial").ToString.ToEntero
End Get
End Property
#End Region
#Region "Propiedades Contratos"
Private Property DtContratos As DataTable
Get
Return If(IsNothing(ViewState("DtContratos")), Nothing, CType(ViewState("DtContratos"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtContratos") = value
End Set
End Property
Private Property NumeroContrato As String
Get
Return ViewState("NumeroContrato").ToString
End Get
Set(value As String)
ViewState("NumeroContrato") = value
End Set
End Property
Private Property DescripcionContrato As String
Get
Return ViewState("DescripcionContrato").ToString
End Get
Set(value As String)
ViewState("DescripcionContrato") = value
End Set
End Property
Private Property NumeroLicitacion As String
Get
Return ViewState("NumeroLicitacion").ToString
End Get
Set(value As String)
ViewState("NumeroLicitacion") = value
End Set
End Property
Private Property CveAlmacenExistenciasContrato As Integer
Get
Return ViewState("CveAlmacenExistenciasContrato").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveAlmacenExistenciasContrato") = value
End Set
End Property
Private Property CveAlmacenOrigenContrato As Integer
Get
Return ViewState("CveAlmacenOrigenContrato").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveAlmacenOrigenContrato") = value
End Set
End Property
Private Property DtContratosSerieDetalle As DataTable
Get
Return If(IsNothing(ViewState("DtContratosSerieDetalle")), Nothing, CType(ViewState("DtContratosSerieDetalle"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtContratosSerieDetalle") = value
End Set
End Property
Private Property CvePSSerieLote As Integer
Get
Return CType(ViewState("CvePSSerieLote"), Integer)
End Get
Set(value As Integer)
ViewState("CvePSSerieLote") = value
End Set
End Property
Private Property CveUMSerieLote As Integer
Get
Return CType(ViewState("CveUMSerieLote"), Integer)
End Get
Set(value As Integer)
ViewState("CveUMSerieLote") = value
End Set
End Property
Private Property CveConsecSerieLote As Integer
Get
Return CType(ViewState("CveConsecSerieLote"), Integer)
End Get
Set(value As Integer)
ViewState("CveConsecSerieLote") = value
End Set
End Property
Private Property LimitaCantidadSerieLote As Integer
Get
Return CType(ViewState("LimitaCantidadSerieLote"), Integer)
End Get
Set(value As Integer)
ViewState("LimitaCantidadSerieLote") = value
End Set
End Property
#End Region
#Region " PROPIEDADES NUEVAS | GUARDAR - IMPRESION "
Private Property ErrorList As List(Of String)
Get
Return CType(ViewState("ErrorList"), List(Of String))
End Get
Set(value As List(Of String))
ViewState("ErrorList") = value
End Set
End Property
Private Property MensajeAlert As StringBuilder
Get
Return CType(ViewState("MensajeAlert"), StringBuilder)
End Get
Set(value As StringBuilder)
ViewState("MensajeAlert") = value
End Set
End Property
Private Property ObjFactura As Modelos.Factura
Get
Return CType(ViewState("ObjFactura"), Modelos.Factura)
End Get
Set(value As Modelos.Factura)
ViewState("ObjFactura") = value
End Set
End Property
Private Property ObjFacturaDevolucion As Modelos.Factura
Get
Return CType(ViewState("ObjFacturaDevolucion"), Modelos.Factura)
End Get
Set(value As Modelos.Factura)
ViewState("ObjFacturaDevolucion") = value
End Set
End Property
#End Region
#Region " PROPIEDADES NUEVAS "
Private Property CveOC As Integer
Get
Return ViewState("CveOC").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveOC") = value
End Set
End Property
Private Property EnviarCorreoCliente As Boolean
Get
Return CBool(ViewState("EnviarCorreoCliente").ToString)
End Get
Set(value As Boolean)
ViewState("EnviarCorreoCliente") = value
End Set
End Property
Private Property EstatusCliente As Boolean
Get
Return CBool(ViewState("EstatusCliente").ToString)
End Get
Set(value As Boolean)
ViewState("EstatusCliente") = value
End Set
End Property
Private Property CveMetodoPagoCliente As Integer
Get
Return ViewState("CveMetodoPagoCliente").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveMetodoPagoCliente") = value
End Set
End Property
Private Property Modalidad As String
Get
Return ViewState("Modalidad").ToString
End Get
Set(value As String)
ViewState("Modalidad") = value
End Set
End Property
Private Property Index As Integer
Get
Return ViewState("Index").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("Index") = value
End Set
End Property
Private Property TotAnt As Decimal
Get
Return ViewState("TotAnt").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TotAnt") = value
End Set
End Property
Private Property TotalOriginal As Double
Get
Return ViewState("TotalOriginal").ToString.ToDouble
End Get
Set(value As Double)
ViewState("TotalOriginal") = value
End Set
End Property
Private Property AplicaCancelarRemision As Boolean
Get
Return CBool(ViewState("AplicaCancelarRemision").ToString)
End Get
Set(value As Boolean)
ViewState("AplicaCancelarRemision") = value
End Set
End Property
Private Property TipoVentaSucursal As Integer
Get
Return ViewState("TipoVentaSucursal").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("TipoVentaSucursal") = value
End Set
End Property
Private Property MensajeCveSAT As StringBuilder
Get
If ViewState("MensajeCveSAT") Is Nothing Then ViewState("MensajeCveSAT") = New StringBuilder
Return CType(ViewState("MensajeCveSAT"), StringBuilder)
End Get
Set(value As StringBuilder)
ViewState("TipoVentaSucursal") = value
End Set
End Property
Private Property EditoRemision As Boolean
Get
Return CBool(ViewState("EditoRemision").ToString)
End Get
Set(value As Boolean)
ViewState("EditoRemision") = value
End Set
End Property
Private Property AplicaNC As Boolean
Get
Return CBool(ViewState("AplicaNC").ToString)
End Get
Set(value As Boolean)
ViewState("AplicaNC") = value
End Set
End Property
Private Property DtVentasNC As DataTable
Get
Return CType(ViewState("DtVentasNC"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtVentasNC") = value
End Set
End Property
Private Property AplicaNCMasiva As Boolean
Get
Return CBool(ViewState("AplicaNCMasiva").ToString)
End Get
Set(value As Boolean)
ViewState("AplicaNCMasiva") = value
End Set
End Property
Private Property RefacturacionGeneroNC As Boolean
Get
Return CBool(ViewState("RefacturacionGeneroNC").ToString)
End Get
Set(value As Boolean)
ViewState("RefacturacionGeneroNC") = value
End Set
End Property
Private Property ModalidadEdicion As Boolean
Get
Return CBool(ViewState("ModalidadEdicion").ToString)
End Get
Set(value As Boolean)
ViewState("ModalidadEdicion") = value
End Set
End Property
Private Property ConversionRemision As String
Get
Return ViewState("ConversionRemision").ToString
End Get
Set(value As String)
ViewState("ConversionRemision") = value
End Set
End Property
Private Property TipoCambioRemision As Decimal
Get
Return ViewState("TipoCambioRemision").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TipoCambioRemision") = value
End Set
End Property
Private Property TieneContrato As Boolean
Get
Return CBool(ViewState("TieneContrato").ToString)
End Get
Set(value As Boolean)
ViewState("TieneContrato") = value
End Set
End Property
Private Property CveOrdenCompraContrato As Integer
Get
Return ViewState("CveOrdenCompraContrato").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveOrdenCompraContrato") = value
End Set
End Property
Private Property ContratosConOC As StringBuilder
Get
If ViewState("ContratosConOC") Is Nothing Then ViewState("ContratosConOC") = New StringBuilder
Return CType(ViewState("ContratosConOC"), StringBuilder)
End Get
Set(value As StringBuilder)
ViewState("ContratosConOC") = value
End Set
End Property
Private Property RequiereOC As Boolean
Get
Return CBool(ViewState("RequiereOC").ToString)
End Get
Set(value As Boolean)
ViewState("RequiereOC") = value
End Set
End Property
Private Property PorcentajeCredito As Decimal
Get
Return ViewState("PorcentajeCredito").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("PorcentajeCredito") = value
End Set
End Property
Private Property CvePedidoA As Integer
Get
Return ViewState("CvePedidoA").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePedidoA") = value
End Set
End Property
Private Property CveEmpresaCRM As Integer
Get
Return ViewState("CveEmpresaCRM").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveEmpresaCRM") = value
End Set
End Property
Private Property CveAcercamientoCRM As Integer
Get
Return ViewState("CveAcercamientoCRM").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveAcercamientoCRM") = value
End Set
End Property
Private Property DtPedidos2 As DataTable
Get
Return CType(ViewState("DtPedidos2"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPedidos2") = value
End Set
End Property
Private Property DtPedidos2PS As DataTable
Get
Return CType(ViewState("DtPedidos2PS"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPedidos2PS") = value
End Set
End Property
Private Property CveEstatus As Integer
Get
Return ViewState("CveEstatus").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveEstatus") = value
End Set
End Property
Private Property DiasCredito As Integer
Get
Return ViewState("DiasCredito").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("DiasCredito") = value
End Set
End Property
Private Property EsDiasCreditoFijo As Boolean
Get
Return CBool(ViewState("EsDiasCreditoFijo").ToString)
End Get
Set(value As Boolean)
ViewState("EsDiasCreditoFijo") = value
End Set
End Property
Private Property VentaSaldoAlmacen As Decimal
Get
Return ViewState("VentaSaldoAlmacen").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("VentaSaldoAlmacen") = value
End Set
End Property
Private Property SeCancelaRemisionProceso As Boolean
Get
Return CBool(ViewState("SeCancelaRemisionProceso").ToString)
End Get
Set(value As Boolean)
ViewState("SeCancelaRemisionProceso") = value
End Set
End Property
#End Region
#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
Modalidad = ""
Opcion = ""
Index = 0
TotAnt = 0
'CargoComercioExterior = False
DdlBPPS.setEsWebService(True)
DdlBPPS.ddlWS.Attributes.Add("data-clear", "1")
ViewState("ProcesoCorrecto") = True
ViewState("NuevaFactura") = -1
ViewState("CveDevolucion") = -1
ViewState("CvePedido") = -1
ViewState("CvePedido2") = -1
ViewState("TipoContrato") = -1
ViewState("CveVenta") = -1
ViewState("CveCliente") = -1
ViewState("CveClienteAnterior") = -1
ViewState("CveOS") = -1
ViewState("CveOC") = -1
ViewState("CveAnticipo") = -1
ViewState("CveFactura") = -1
ViewState("CveCicloComercial") = -1
ViewState("Entrega") = ""
ViewState("Vigencia") = ""
ViewState("AplicarVentaFacturada") = False
ViewState("SeGuardoPrePoliza") = False
ViewState("TipoDoctoDevolucion") = ""
ViewState("EditoRemision") = False
ViewState("RequiereOC") = False
ViewState("ClienteDesglosaIEPS") = False
ViewState("ClienteRetIVA") = 0
ViewState("ClienteRetISR") = 0
idCuentaContabilizacion = 1
CveEmpresaCRM = 0
CveAcercamientoCRM = 0
EstatusCliente = False
RemisionesLista = New List(Of Integer)
Pedidos2Lista = New List(Of Integer)
CotizacionesLista = New List(Of Integer)
CuentasContablesInvalidas = New StringBuilder
CvePrePoliza = 0
TotalOtrosConceptos = 0
CveUsuarioActual = UsuarioActual.CveUsuario
EmpresaActual = UsuarioActual.Empresa
IdPoliza = 0
CveCorte = -1
CveContrato = -1
DevolucionAlmacen = 0
CvePSAmortizacion = 0
EraCotizacion = 0
FacturaMateriales = 0
CvePedidoA = 0
EsCreaApartirDe = False
RequiereAlmacenDestino = False
RequiereAlmacenOrigen = False
TmpDTComplementos = New DataTable
DtRemConceptosSurtidos = Nothing
TipoVentaSucursal = 0
PlazoCobranza = 0
PlazoCobranzaRemision = 0
TipoCambioFactura = 1
NumeroContrato = ""
DescripcionContrato = ""
NumeroLicitacion = ""
ImprimeNombreSucursal = False
RegistraScript("SetDisabledTxtTotal(true);")
TrVistaPrevia.Visible = False
CveMetodoPagoCliente = 1
CveAlmacenExistenciasContrato = -1
UpFacturar.Update()
'CargaTiposDocumentos()
TrEmitir.Visible = False
ViewState("EstablecioFolio") = False
'ViewState("SubProyectoPorcentajeIVA") = 0
RefacturacionGeneroNC = False
ModalidadEdicion = False
ConversionRemision = ""
TipoCambioRemision = 1
CveOrdenCompraContrato = -1
TieneContrato = False
AplicaNC = False
TieneAlmacen = False
CveEstatus = -1
PorcentajeIVA = 0
EsDiasCreditoFijo = False
DiasCredito = 0
AplicaCancelarRemision = False
SeCancelaRemisionProceso = False
TotalOriginal = 0
CveAlmacenDevolucion = 0
txtFechaICot.Text = Now.AddMonths(-3).ToShortDateString
TxtFechaIRem.Text = Now.AddMonths(-3).ToShortDateString
TxtFechaIPed.Text = Now.AddMonths(-3).ToShortDateString
TxtFechaIOC.Text = Now.AddMonths(-3).ToShortDateString
txtFechaFCot.Text = Now.ToShortDateString
TxtFechaFRem.Text = Now.ToShortDateString
TxtFechaFPedido.Text = Now.ToShortDateString
TxtFechaFOC.Text = Now.ToShortDateString
If UsuarioActual.TienePermisoProceso(177) Then
DdlTipoComprobante.Items.Insert(4, New ListItem("Pedido de Contrato", "Ped"))
End If
TrSinExistencia.Visible = UsuarioActual.TienePermisoProceso(276)
If UsuarioActual.CveEmpresa.Contiene(119, 1) Then
ImgDescPU.Visible = False
ImgDescConcepto.Visible = False
DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Autorización", "PA"))
End If
DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("Pedido", "Pd2"))
If UsuarioActual.Empresa.Funcionalidad(344).ToString = "1" Then
DdlTipoComprobante.Items.Insert(DdlTipoComprobante.Items.Count, New ListItem("NC de Remisión", "RNC"))
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(72, 80) Then ' PARA BUSCAR FOLIO DE OC, YA FACTURADA EN EL CAMPO ORDEN DE COMPRA
TxtOrdenCompra.Attributes.Add("onblur", "BuscarOCRegistrada();")
End If
If UsuarioActual.Empresa.Funcionalidad(561).ToString = "1" Then
thPoliza.Visible = True
thPoliza2.Visible = True
End If
DdlSATPS.setEsWebService(True) : DdlSATPS.Attributes.Add("data-metodo", "getpssat")
DivPSSAT.Visible = True
SetValues()
CvePresupuesto = 0
'MODALIDADES
If Request("Op") IsNot Nothing AndAlso Request("Op").ToString <> "" Then
Opcion = Request("Op").ToString
LblTitulo.Text = "Registro de Cotizaciones"
TrTipo.Visible = False
TabAlmacen.Visible = False
TabDetalleVentas.Visible = False
TabVentaAF.Visible = False
TabE.Visible = False
TabComplementos.Visible = False
divcondicionespago.Visible = UsuarioActual.Empresa.CvePlataforma = 1 'SI ES PLATAFORMA ERP SIEMPRE VSIBLE ESTE PORLET
ImgAntiPend.Visible = False
TrObsAlmacen.Visible = False
TrTxtObsAlmacen.Visible = False
TrPedido.Visible = False
TrOC.Visible = False
DdlTipoComprobante.SelectedValue = "Op"
Else
Opcion = "Ing"
DdlTipoComprobante.SelectedValue = "Ing"
End If
'DdlTipoComprobante.Attributes.Add("onChange", "ActivaReferencia(this)")
TxtFecha.Text = Now.ToShortDateString()
TxtFechaEjecucion.Text = Now.ToShortDateString
LblUsuario.Text = UsuarioActual.Usuario
LblFechaRegistro.Text = Now.ToShortDateString()
TxtPrecioPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();")
TxtCantidadPyME.Attributes.Add("onKeyUp ", "RecalculaPyME();")
ImgDescPU.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '0'; $get('LblPrecio1').style.display = ''; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';")
ImgDescConcepto.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '1'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = ''; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';")
ImgDescTotal.Visible = False
ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';")
ImgAntiPend.Attributes.Add("onclick", "$get('HdnTipoDescuento').value = '3'; MuestraAnticipos();")
ImgOtrosConceptos.Attributes.Add("onclick", "javascript:$('#ModalOtrosConceptos').modal();")
LkbAgregarComplementos.Attributes.Add("onclick", "javascript:$('#ModalComplementos').modal();")
'ImgCerrar.Attributes.Add("OnClick", "$('#DivAnticipos').hide();")
'LkbEstadodeCaja.Attributes.Add("OnClick", "MuestraEstadoCaja();")
'LkbIngreso.Attributes.Add("OnClick", "MuestraIngresoEgreso(1);")
'LkbRetiro.Attributes.Add("OnClick", "MuestraIngresoEgreso(0);")
TxtImporteEfectivo.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteCredito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteDebito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteCheque.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteTransferencia.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtEfectivoEnCaja.Attributes.Add("onKeyUp", "CalculaDiferencia();")
'ImgCerrarTerminoCorte.Attributes.Add("OnClick", "$('#DivTerminarCorte').hide();")
'ImgCerrarIE.Attributes.Add("OnClick", "$('#DivIngresoEgreso').hide();")DdlTipoComprobante
'ImgCerrarEstadoCaja.Attributes.Add("OnClick", "$('#DivEstadoCaja').hide();")
TabAlmacen.Enabled = UsuarioActual.Empresa.UsaInventarios
TxtPorDescP.Attributes.Add("onKeyUp", "CalculaDescuento();")
TxtDescP.Attributes.Add("onKeyUp", "CalculaDescuento();")
TxtCantidadPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')")
TxtObsPyME.Attributes.Add("onkeypress", "cambiaFoco('TxtPrecioPyME')")
TxtPrecioPyME.Attributes.Add("onkeypress", "CallServerMethod(event)")
CreaDTmpC()
CreaDTmpF()
CreaDTDocumentosRelacionados()
CargaDdlSubProyectos()
CargaProyecto()
CargaSucursales()
CargaClasificaciones()
CargaPS(-1, DdlPS)
CargaPSPyME(-1, DdlPSPyME)
CreaDTVentas()
CargaMetodosPago()
'CargaFormaPago(-1)
CargaUsoCFDI()
CargaTiposRelacion()
CargaMonedas()
CargaVendedores()
CargarAlmacenes()
CargaFormaEntrega()
CargaCuentasTerminal()
CargaDdlNCPS()
'SI USUARIO USA AMORTIZACIÓN CONTABLE, se carga las tablas para usarlas mas adelante
If UsuarioActual.Empresa.UsaAC Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot"))
DdlTipoComprobante.Items.Add(New ListItem("Compromisos", "Com"))
DdlTipoComprobante.Items.Add(New ListItem("Orden Pago", "OP"))
Dim AC As New ClsAC
If AC.GetPresupuestoIngresos(-1, Now.Year, True, UsuarioActual.CveEmpresa) Then
DdlFuenteRecaudacion.DataSource = AC.DtResultados()
DTPresupuestoIngresos = AC.DtResultados()
ViewState("DTFuenteRecaudacion") = AC.DtResultados()
'GenerarPolizasAC()
End If
AC.Dispose()
'columna de Fuente de recaudacion
GvPS.Columns(21).Visible = True
nomostrar.Visible = True
nomostrar2.Visible = True
'GvPS.Width = 1250
DdlFuenteRecaudacion.DataBind()
Else
TFuenteRecaudacion.Visible = False
End If
'Carga cliente
If Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 AndAlso Request("CveFactura") Is Nothing Then
ViewState("CveCliente") = Request("CveCliente")
HdnCveCliente.Value = Request("CveCliente")
CargaCliente(CveCliente)
VerificarContrato(True)
ElseIf Request("CveFactura") IsNot Nothing AndAlso IsNumeric(Request("CveFactura")) AndAlso Request("CveFactura").ToEntero > 0 AndAlso Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 Then
ViewState("CveCliente") = Request("CveCliente")
ViewState("CveFactura") = Request("CveFactura").ToEntero
Dim RFC As String = CargaFactura(CveFactura)
CargaCliente(CveCliente)
Else
ViewState("CveCliente") = -1
HdnCveCliente.Value = "-1"
End If
'Carga empresa CRM
If Request("CveEmpresaCRM") IsNot Nothing AndAlso IsNumeric(Request("CveEmpresaCRM")) AndAlso Request("CveEmpresaCRM").ToEntero > 0 Then
ViewState("CveEmpresaCRM") = Request("CveEmpresaCRM")
CargaEmpresaCRM(CveEmpresaCRM)
Else
ViewState("CveEmpresaCRM") = -1
End If
If Request("CveAcercamientoCRM") IsNot Nothing AndAlso IsNumeric(Request("CveAcercamientoCRM")) AndAlso Request("CveAcercamientoCRM").ToEntero > 0 Then
ViewState("CveAcercamientoCRM") = Request("CveAcercamientoCRM")
Else
ViewState("CveAcercamientoCRM") = -1
End If
'mensaje de confirmación al guardar
BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)},{If(HdnTieneAnticipos.Value = "1", 1, 0)});"
BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation")
BtnEmitirImprimir.Attributes.Add("data-popout", "true")
BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar")
BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar")
BtnEmitirImprimir.Attributes.Add("data-html", "true")
If UsuarioActual.CveEmpresa.Contiene(126) Then ' cuando la empresa se relaciona a ua orden de producción, Citrus Game
TrOP.Visible = True
CargaOrdenProduccion()
End If
'Carga Venta
If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero > 0 Then
ViewState("CveVenta") = Request("CveVenta")
If CargaVenta() Then
'DdlSucursal.Enabled = False
DdlSubProyectoDatos.Enabled = False
BtnEmitirImprimir.Visible = False
BtnCrearApartirDe.Visible = True
'DdlEstatus.Enabled = True
DivFechaAnticipoCliente.Visible = True
TxtFechaAnticipoCliente.Text = Now.ToShortDateString
ImgAddObs.Visible = True
CargaEventoBitacora()
ConfiguraTipoDocto()
TrFolioFiscal.Visible = True
' Si esta cancelado el compromiso/Pedido no se puede editar el estatus
'If DdlEstatus.SelectedValue.Contiene({"9", "14", "17"}) Then
' DdlEstatus.Enabled = False
'End If
'CargaDetalle de Almacen
If Not LblAlertRefacInv.Visible Then
If CveVentaPadre > 0 Then
InventarioMov(CveVentaPadre)
Else
InventarioMov()
End If
End If
'PERMISO PARA CANCELAR PEDIDO
If GvInv.Rows.Count = 0 Then
If DdlTipoComprobante.SelectedValue.Contiene("Ped") And Not CveEstatus = 14 Then
If UsuarioActual.TienePermisoProceso(186) Then
LBCancelarPedido.Visible = True
End If
End If
End If
'CARGA GV DE COMERCIO EXTERIOR SI NO ESTA TIMBRADA
If LblSeTimbro.Text = "No" Then
CargaGvComercioExterior()
End If
'HABILITA IMPRESION DE FORMATO CICOVISA
If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then
LnkImprimirFormatoCicovisa.Visible = True
End If
If UsuarioActual.TienePermisoProceso(269) AndAlso Not DevolucionAlmacen = 2 Then
DivDevAlm.Visible = True
End If
End If
Else
If Request("CveOS") IsNot Nothing AndAlso IsNumeric(Request("CveOS")) AndAlso Request("CveOS").ToEntero > 0 Then
ViewState("CveOS") = Request("CveOS")
CargaOS(CveOS)
Else
'Modalidad Devoluciones y Refacturacion
If Request("CveDevolucion") IsNot Nothing AndAlso IsNumeric(Request("CveDevolucion")) AndAlso Request("CveDevolucion").ToEntero > 0 Then
ViewState("CveDevolucion") = Request("CveDevolucion")
ViewState("CveVenta") = Request("CveDevolucion")
ViewState("NuevaFactura") = Request("NuevaFactura")
trNCFactura.Visible = True
DdlNCFactura.DataSource = Nothing
DdlNCFactura.DataBind()
CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString.ToEntero)
DdlNCFactura.SelectedValueExist(CveDevolucion)
If NuevaFactura = 0 Then
LbAgregar.Visible = False
If DdlTipoComprobante.SelectedValue = "Ing" Then
DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev"))
DdlTipoComprobante.SelectedValue = "Dev"
ElseIf DdlTipoComprobante.SelectedValue = "Ant" Then
DdlTipoComprobante.SelectedValueExist("Egs")
End If
DdlTipoComprobante.Enabled = False
CargaFolios()
DdlUsoCFDI.Enabled = True
DdlUsoCFDI.SelectedValueExist("2")
DdlMetodoPago33.Enabled = True
DdlMetodoPago33.SelectedValueExist("1")
DdlFormaPago33.Enabled = True
DdlFormaPago33.SelectedValueExist("20")
End If
If NuevaFactura = 1 Then
TrTipoRelacion.Visible = True
DdlTiposRelacion.SelectedValueExist("4")
Dim ObjInv As New ClsInventarios
If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjInv.DtResultados.Rows.Count > 0 Then
TieneAlmacen = True
End If
End If
ObjInv.Dispose()
End If
CargaNuevaFactura(Nothing)
'NOTA DE CREDITO
If NuevaFactura = 2 Then
DdlTipoComprobante.Items.Insert(0, New ListItem("Nota de Crédito", "Egs"))
DdlTipoComprobante.SelectedValue = "Egs"
DdlTipoComprobante.Enabled = False
CargaFolios()
DdlUsoCFDI.Enabled = True
DdlUsoCFDI.SelectedValueExist("2")
DdlMetodoPago33.Enabled = True
DdlMetodoPago33.SelectedValueExist("1")
DdlFormaPago33.Enabled = True
DdlFormaPago33.SelectedValueExist("20")
TrTipoRelacion.Visible = True
DdlTiposRelacion.SelectedValueExist("1")
End If
End If
'ENTREGA POR ADELANTADO
If DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ped", "PeC") Then
If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then
RequiereAlmacenDestino = True
If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then
TrAlmacenAsignado.Visible = True
End If
Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero
If CveAlmacenDestino > 0 Then
DdlAlmacenAsignado.Items.Clear()
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)")
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString))
DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString
Else
DdlAlmacenAsignado.Items.Clear()
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (10)")
DdlAlmacenAsignado.DataBind()
End If
UpParametros.Update()
Else
RequiereAlmacenDestino = False
TrAlmacenAsignado.Visible = False
End If
'ENVIO DE FACTURA
If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then
ChkEnviarFactura.Checked = EnviarCorreoCliente
ChkEnviarFactura.Visible = True
LblEnviarMail.Visible = True
End If
End If
'Modalidad Contrato
If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").Contiene("0", "1") Then
TrAlmacenOrigen.Visible = False
If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then
TrAlmacenAsignado.Visible = True
End If
UPCondicionesPago.Visible = False
RequiereAlmacenDestino = True
CveContrato = Request("CveContrato").ToEntero
TipoContrato = Request("Tipo").ToEntero
'DESACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto disabled")
TxtCodigo.ReadOnly = True
CargarContratoUrl()
UpParametros.Update()
End If
'Modalidad CveCicloComercial
If Request("CveCicloComercial") IsNot Nothing AndAlso IsNumeric(Request("CveCicloComercial")) AndAlso Request("CveCicloComercial").ToEntero > 0 Then
ViewState("CveCicloComercial") = Request("CveCicloComercial").ToEntero
CargaCicloComercialURL()
UpParametros.Update()
End If
'Modalidad Devolucion Pedido **REVISAR SI SE USA
If Request("CveContrato") IsNot Nothing AndAlso IsNumeric(Request("CveContrato")) AndAlso Request("CveContrato").ToEntero > 0 AndAlso Request("CvePedido") IsNot Nothing AndAlso IsNumeric(Request("CvePedido")) AndAlso Request("CvePedido").ToEntero > 0 AndAlso Request("Tipo") IsNot Nothing AndAlso IsNumeric(Request("Tipo")) AndAlso Request("Tipo").ToEntero = 2 Then
CveContrato = Request("CveContrato").ToEntero
CvePedido = Request("CvePedido").ToEntero
TipoContrato = Request("Tipo").ToEntero
''REQUIERE DEVOLUCION
'DdlDevolucionAlmacen.SelectedValue = "1"
'DdlDevolucionAlmacen.Enabled = False
'UpInvDev.Update()
CargarPedidoUrl()
End If
'MODALIDAD DEVOLUCION PEDIDO NUEVO
If Request("DevPed") IsNot Nothing AndAlso IsNumeric(Request("DevPed")) AndAlso Request("DevPed").ToEntero > 0 AndAlso Request("MovInv") IsNot Nothing AndAlso IsNumeric(Request("MovInv")) AndAlso Request("MovInv").ToEntero > 0 Then
ViewState("CveVenta") = Request("DevPed")
ViewState("MovInv") = Request("MovInv")
ViewState("CveMovimientoDetalle") = IfNull(Request("CveMovimientoDetalle"), "-1").ToString.ToEntero
DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe"))
DdlTipoComprobante.SelectedValue = "DPe"
DdlTipoComprobante.Enabled = False
CargaFacturaDevolucionPedido()
CargaFolios()
If CveContrato > 0 Then
CargaNotificacionContrato()
End If
End If
'Modalidad Cotizacion
If Opcion = "Cot" Then
DdlTipoComprobante.SelectedValueExist(Opcion)
DdlTipoComprobante.Enabled = False
DdlTipoComprobante_SelectedIndexChanged(sender, Nothing)
'Carga CvePresupuesto
If Request("CvePresupuesto") IsNot Nothing AndAlso IsNumeric(Request("CvePresupuesto")) AndAlso Request("CvePresupuesto").ToEntero > 0 Then
CvePresupuesto = Request("CvePresupuesto").ToEntero
'DdlEstatus.Enabled = False
End If
End If
CargaEstatusFactura(Opcion)
If Opcion = "Ing" Then
ObtenerFechaVencimientoCER()
'DdlEstatus.Enabled = False
If UsuarioActual.Empresa.TipoFacturacion = "CBB" Then
'DdlEstatus.SelectedValue = "3"
CveEstatus = 3
ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then
'DdlEstatus.SelectedValue = "2"
CveEstatus = 2
End If
End If
End If
End If
'CARGA PARA FACTURAR
ViewState("CveRemision") = IfNull(Request("CveRemision").ToEntero, 0)
ViewState("CveCotizacion") = IfNull(Request("CveCotizacion").ToEntero, 0)
If ViewState("CveCotizacion").ToString.ToEntero > 0 Then
EsCreaApartirDe = True
End If
If ViewState("CveRemision").ToString.ToEntero > 0 Or ViewState("CveCotizacion").ToString.ToEntero > 0 Then
'ViewState("CveRemision") = Request("CveRemision")
'Dim CveRemision As Integer = ViewState("CveRemision").ToString.ToEntero
CargaVenta()
'DdlSucursal.Enabled = False
BtnCrearApartirDe.Visible = True
'DdlEstatus.Enabled = True
ImgAddObs.Visible = True
CargaEventoBitacora()
DdlTipoComprobante.Enabled = False
DdlTipoComprobante.SelectedValue = "Ing"
CargaEstatusFactura()
'DdlEstatus.SelectedValueExist("2")
ConfiguraTipoDocto()
CargaFolios()
BtnEmitirImprimir.Text = "Facturar"
BtnEmitirImprimir.Visible = True
UpnTools.Update()
TxtFecha.Text = Now.ToShortDateString
'' Si esta cancelado el compromiso no se puede editar el estatus
'If DdlEstatus.SelectedValue = "9" Then
' DdlEstatus.Enabled = False
'End If
'CargaDetalle de Almacen
InventarioMov()
End If
If Not ExFolioFactura Then SetPermisos()
'SELECCIONA VENDEDOR DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE
If UsuarioActual.CveVendedor > 0 Then
If CveVenta = -1 AndAlso Not DdlVendedor.SelectedValue.ToEntero > 0 Then DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString)
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
'multiples vendedores visible
If UsuarioActual.TienePermisoProceso(153) Then
DdlVendedor.Enabled = True
End If
End If
If UsuarioActual.Empresa.Funcionalidad(301).ToEntero > 0 Then
TxtFecha.Enabled = False
ImgFecha.Visible = False
End If
CargarCodigo()
InicializaImprimirNew()
'RegistraScript("FnSuma()")
TxtSubTotal.Attributes.Add("onKeyUp", "FnSuma()")
TxtIVA.Attributes.Add("onKeyUp", "FnSuma()")
TxtIEPS.Attributes.Add("onKeyUp", "FnSuma()")
TxtRetIVA.Attributes.Add("onKeyUp", "FnSuma()")
TxtRetISR.Attributes.Add("onKeyUp", "FnSuma()")
'Permitir Edicion de Iva
If UsuarioActual.Empresa.Funcionalidad(509) = "1" Then
TxtIVA.Enabled = True
'TxtTotal.Enabled = True
RegistraScript("SetDisabledTxtTotal(false);")
TxtSubTotal.Enabled = True
TxtSubTotal2.Enabled = True
End If
'Cortes de Caja
If UsuarioActual.TienePermisoProceso(160) Then
CargaCorteCaja()
End If
'**********************************
'Complementos de Timbrado
Dim ObjVenta As New ClsVentas
If ObjVenta.GetVentaComplementos() Then
RblComplementos.DataSource = ObjVenta.DtResultados
RblComplementos.DataBind()
UpComplementos.Update()
End If
ObjVenta.Dispose()
CargaFormatoSucursal()
InicializaDevolucionAlmacen()
CargaOtrosConceptos()
CargaFacturaOC()
'SELECCIONA SUCURSAL DEL USUARIO CUANDO SEA VENTA NUEVA Y SIN CLIENTE
If Not (CveCliente > 0 Or CveVenta > 0) Then
DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto)
DdlSubProyectoEjecucion.SelectedValueExist(UsuarioActual.CveSubProyecto)
DdlSubProyectoCobranza.SelectedValueExist(UsuarioActual.CveSubProyecto)
If UsuarioActual.TienePermisoProceso(152) Then
DdlSubProyectoDatos.Enabled = False
End If
CambiaSucursal()
UpParametros.Update()
UpDetalle.Update()
End If
'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE
EnviarCorreoCliente = True
If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then
ChkEnviarFactura.Checked = False
ChkEnviarFactura.Visible = False
LblEnviarMail.Visible = False
Else
ChkEnviarFactura.Checked = EnviarCorreoCliente
ChkEnviarFactura.Visible = True
LblEnviarMail.Visible = True
End If
CargaFletes()
If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then
DdlProyecto.Visible = False
BrSubProyecto.Visible = False
DdlProyectoPyME.Visible = False
LblProyectoHeader.Text = "Sucursal"
LblSubProyecto.Text = ""
divProyectoPyME.Visible = False
LblSubProyectoPyME.InnerText = "Sucursal"
DdlSubProyecto.Items.Clear()
DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1)
'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"})
DdlSubProyecto.DataBind()
DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlSubProyectoPyME.Items.Clear()
DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1)
'DdlSubProyectoPyME.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"})
DdlSubProyectoPyME.DataBind()
DdlSubProyectoPyME.Items.Insert(0, New ListItem("Seleccione", "-1"))
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then
DdlProyecto.Visible = False
BrSubProyecto.Visible = False
DdlProyectoPyME.Visible = False
LblProyectoHeader.Text = "Proyecto"
LblSubProyecto.Text = ""
divProyectoPyME.Visible = False
LblSubProyectoPyME.InnerText = "Proyecto"
DdlSubProyecto.Items.Clear()
DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1)
'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"})
DdlSubProyecto.DataBind()
DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlSubProyectoPyME.Items.Clear()
DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1)
'DdlSubProyectoPyME.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"})
DdlSubProyectoPyME.DataBind()
DdlSubProyectoPyME.Items.Insert(0, New ListItem("Seleccione", "-1"))
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then
LblProyectoHeader.Text = "Sucursal"
LblSubProyecto.Text = "Proyecto"
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then
LblProyectoHeader.Text = "Proyecto"
LblSubProyecto.Text = "Sucursal"
End If
If UsuarioActual.Empresa.CvePlataforma = 2 Then
ImgOtrosConceptos.Visible = False
TrFormaEntrega.Visible = False
TabDetalleVentas.Visible = False
TabE.Visible = False
LnkOCs.Visible = False
GvPS.Columns(8).Visible = False
TrEdit.Visible = False
ThProyecto.Visible = False
For Each Gvr As GridViewRow In GvPS.Rows
Gvr.FCLinkButton("imgE").Visible = False
Gvr.FCLinkButton("imgEPyME").Visible = True
Next
LnkAddVenta.Visible = True
divproyectos.Visible = False
End If
TabVentaAF.Visible = False
'CARGA VALORES INICIALES PARA AGREGAR PS DESDE MODAL
CargaMetodosPSModal()
'CARGA VALORES DE ORDEN DE PRODUCCION
Dim CveOrdenProduccion = IfNull(Request("CveOrdenProduccion"), "-1").ToString.ToEntero
If CveOrdenProduccion > 0 And Not CveVenta > 0 Then
DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion)
If DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then
DdlTipoComprobante.SelectedValue = "Rem"
DdlMoneda.SelectedValue = "2"
Dim ObjCGame As New ClsCGame
If ObjCGame.GetAvance(DdlOrdenProduccion.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
For Each dt As DataRow In ObjCGame.DtResultados.Rows
If dt("Avance").ToString.ToEntero > 0 Then
AgregarProductoServicio(dt("Avance").ToString.ToDecimal, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString, dt("PU").ToString.ToDecimal, 0,
DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text)
'AddPS(dt("Avance").ToString.ToDouble, 29472, "No Aplica", 19588, "Ingresos por comercializadora", 308366, "Ventas", dt("Datos").ToString, dt("PU").ToString.ToDouble, 0, 0, 0, 1, 0, True,
' "", DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, 2, HdnTipoInv.Value.ToEntero)
End If
Next
GvPS.DataSource = TmpDT
End If
If ObjCGame.GetFlete(UsuarioActual.CveEmpresa) Then
TxtObsFact.Text = String.Format("Chofer: {0}; Remolque: {1}; Scat: {2};", ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Chofer"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("CodigoDescripcionRemolque"), ObjCGame.DtResultados.FiltraParametros(String.Format("CveOrdenProduccion = {0}", CveOrdenProduccion))(0)("Scat"))
End If
ObjCGame.Dispose()
GvPS.DataBind()
UPObservaciones.Update()
UpPS.Update()
CargaFolios()
End If
End If
If Request("CveVenta") IsNot Nothing AndAlso IsNumeric(Request("CveVenta")) AndAlso Request("CveVenta").ToEntero = -1 AndAlso UsuarioActual.CveTipoDocumento.Length = 3 Then
CargaDdlSubProyectos()
UpParametros.Update()
DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento)
CambiaTipoDocto()
LimpiaEscondeContado()
End If
InicializaAplicarNC()
If CveCliente > 0 Then
CargaRestriccionesCreditoCliente()
End If
If Not CveVenta > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(403).ToString = "1" Then
If (DdlTipoComprobante.Items.FindByValue("Ing") IsNot Nothing) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing"))
End If
End If
End If
''EN REALIDAD SE OCUPAN ESTAS COSAS DENTRO DEL POSTABCK ???
If Not CveVenta > 0 Then
'LbDescargarExcel.Visible = True
HlAgregarExcel.Visible = True
End If
If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then
' IPP 15 Julio 2017 - ERA FALSE
ImgAntiPend.Visible = False
UpPS.Update()
End If
If UsuarioActual.Empresa.Funcionalidad(517) <> "" Then
TxtFolio.Enabled = False
TxtFecha.Enabled = False
If LblSeTimbro.Text = "No" And DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev", "Ant") Then
TxtFecha.Text = Now.ToShortDateString
End If
ImgFecha.Visible = False
End If
'condición temporal por implementación JAM. usuario FernandaRomo
If UsuarioActual.CveUsuario.Contiene(11703, 1719) Then
TxtFecha.Enabled = True
ImgFecha.Visible = True
End If
End Sub
Private Sub ConfiguraEmpresa()
Select Case UsuarioActual.CveEmpresa
Case 119
TxtObsPS.Attributes.Add("onkeypress", "setFocus(event,'TxtPrecio');")
End Select
End Sub
#Region "Punto Venta"
Private Sub CargaCorteCaja()
'Checar si hay un Turno Abierto
Dim ObjPVenta As New ClsPuntoVenta
If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
CveCorte = ObjPVenta.CveCorte
LblEstatusCaja.Text = ObjPVenta.FechaInicial.ToShortDateString
TrEstatusCaja.Visible = True
BtnIniciarTurno.Visible = False
LkbEstadodeCaja.Visible = True
LkbIngreso.Visible = True
LkbRetiro.Visible = True
Else
'Ingresar un nuevo Turno
RegistraScript("window.onload = function MuestraCorteCaja() { document.getElementById(""C_btnShow"").click(); }")
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnIniciarTurno_Click(sender As Object, e As EventArgs) Handles BtnIniciarTurno.Click
Dim ObjPVenta As New ClsPuntoVenta
ObjPVenta.AddVtaCortes(Now, TxtDineroCaja.Text.ToDecimal, UsuarioActual.CveUsuario, TxtDescripcionCaja.Text, UsuarioActual.CveEmpresa)
CveCorte = ObjPVenta.CveCorte
LblEstatusCaja.Text = Now.ToShortDateString
TrEstatusCaja.Visible = True
LkbEstadodeCaja.Visible = True
LkbIngreso.Visible = True
LkbRetiro.Visible = True
BtnIniciarTurno.Visible = False
ObjPVenta.Dispose()
RegistraScript("$('#DivCorteDeCaja').hide();")
End Sub
Private Sub LkbEstadodeCaja_Click(sender As Object, e As EventArgs) Handles LkbEstadodeCaja.Click
CargaDatosCorte()
CargaVentasPago()
CargaEntradasSalidas()
RegistraScript("$('#DivEstadoCaja').modal()")
End Sub
Private Sub CargaDatosCorte()
Dim ObjPVenta As New ClsPuntoVenta
Dim Total As Double
If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
Total = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble + ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble + ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble + ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble - ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble
DineroCaja = Total
LblEfectivoEsperado.Text = Total.FormatoNumero(2)
Dim Dt As New DataTable
Dt.Columns.Add("Descripcion", GetType(String))
Dt.Columns.Add("Importe", GetType(Decimal))
Dim Dr1 = Dt.NewRow
Dr1("Descripcion") = "Fondo de Caja"
Dr1("Importe") = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble
Dt.Rows.Add(Dr1)
Dim Dr2 = Dt.NewRow
Dr2("Descripcion") = "Ventas en Efectivo"
Dr2("Importe") = ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble
Dt.Rows.Add(Dr2)
Dim Dr3 = Dt.NewRow
Dr3("Descripcion") = "Propinas"
Dr3("Importe") = ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble
Dt.Rows.Add(Dr3)
Dim Dr4 = Dt.NewRow
Dr4("Descripcion") = "Entradas"
Dr4("Importe") = ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble
Dt.Rows.Add(Dr4)
Dim Dr5 = Dt.NewRow
Dr5("Descripcion") = "Salidas"
Dr5("Importe") = ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble
Dt.Rows.Add(Dr5)
Dim Dr6 = Dt.NewRow
Dr6("Descripcion") = "Total"
Dr6("Importe") = Total
Dt.Rows.Add(Dr6)
GvDineroCaja.DataSource = Dt
GvDineroCaja.DataBind()
UpDineroCaja.Update()
UpTerminarCorte.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub CargaVentasPago()
Dim ObjPVenta As New ClsPuntoVenta
If ObjPVenta.GetVta_MetodosPago(CveCorte) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
GvMetodosPago.DataSource = ObjPVenta.DtResultados
GvMetodosPago.DataBind()
UpMetodosPago.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub CargaEntradasSalidas()
Dim ObjPVenta As New ClsPuntoVenta
'Salida
If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 0) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
GvEgresos.DataSource = ObjPVenta.DtResultados
GvEgresos.DataBind()
UpEgresos.Update()
End If
End If
'Entrada
If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 1) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
GvIngresos.DataSource = ObjPVenta.DtResultados
GvIngresos.DataBind()
UpIngresos.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnAceptarIE_Click(sender As Object, e As EventArgs) Handles BtnAceptarIE.Click
Dim ObjPVenta As New ClsPuntoVenta
If TxtCantidadIE.Text.ToEntero > 0 Then
If ObjPVenta.AddVta_MovimientosCajas(CveCorte, UsuarioActual.CveUsuario, TxtCantidadIE.Text.ToDouble, TxtDescripcionIE.Text, HdnTipoMovimiento.Value.ToEntero, Now) Then
TxtCantidadIE.Text = ""
TxtDescripcionIE.Text = ""
RegistraScript("$('#DivIngresoEgreso').modal('hide')", "divingresoegreso")
Alert("El movimiento se realizó correctamente")
UpIngresoEgreso.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnCerrarTurno_Click(sender As Object, e As EventArgs) Handles BtnCerrarTurno.Click
Dim ObjPVenta As New ClsPuntoVenta
If TxtEfectivoEnCaja.Text.Trim <> "" Then
If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoEnCaja.Text.ToDouble, LblDiferenciaCaja.Text.ToDouble, Now, UsuarioActual.CveEmpresa) Then
RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=CORT&CVECORTE={0}&FORMATO={1}", CveCorte, "PDF"))}'", "Imprimir")
Dim Liga = "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";"
Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga)
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnCancelar_Click(sender As Object, e As EventArgs) Handles BtnCancelar.Click
Response.Redirect("~/Inicio.aspx")
End Sub
Protected Sub BtnCerrarCaja_Click(sender As Object, e As EventArgs)
RegistraScript("$('#DivEstadoCaja').modal('hide')")
RegistraScript("$('#DivTerminarCorte').modal()", "divterminarcorte")
End Sub
Protected Sub LkbIngreso_Click(sender As Object, e As EventArgs)
CargaIngresoEgreso(1)
End Sub
Public Sub CargaIngresoEgreso(Opcion As Integer)
RegistraScript("$('#DivIngresoEgreso').modal()")
If Opcion = 1 Then
LblTituloIE.Text = "Ingreso de Efectivo: "
HdnTipoMovimiento.Value = "1"
ElseIf Opcion = 0 Then
LblTituloIE.Text = "Retiro de Efectivo: "
HdnTipoMovimiento.Value = "0"
End If
UpIngresoEgreso.Update()
End Sub
Protected Sub LkbRetiro_Click(sender As Object, e As EventArgs)
CargaIngresoEgreso(0)
End Sub
#End Region
#Region "Contratos"
Private Sub PresionarBotonModal(Boton As String)
Try
Dim script As String = $"document.getElementById(""{Boton}"").click();"
Dim Pag As Page = DirectCast(System.Web.HttpContext.Current.Handler, Page)
ScriptManager.RegisterStartupScript(Pag, Pag.GetType(), Boton, script, True)
Pag = Nothing
Catch ex As Exception
End Try
End Sub
Private Sub VerificarContrato(Optional AfterPageLoad As Boolean = False)
Dim ObjContratos As New ClsContratos
If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then
If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then
DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'")
If AfterPageLoad Then
RegistraScript("window.onload = function MuestraContratos() { document.getElementById(""C_BtnMostrarContrato"").click(); }")
Else
PresionarBotonModal("C_BtnMostrarContrato")
End If
End If
End If
ObjContratos.Dispose()
End Sub
Private Sub BtnIniciarContrato_Click(sender As Object, e As EventArgs) Handles BtnIniciarContrato.Click
DdlContratosModal.Items.Clear()
If RblOpcionContrato.SelectedValue = "2" Then
ContratoDetalles.Visible = True
DivEstimaciones.Visible = False
DdlContratosModal.DataSource = DtContratos
DdlContratosModal.DataBind()
DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0"))
DdlContratosOC.Items.Clear()
DdlContratosOC.DataSource = DtContratos
DdlContratosOC.DataBind()
'DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0"))
UPEstimaciones.Update()
Tab.ActiveTab = TabE
TabGenerales.Enabled = False
Updatetabs.Update()
'ESCONDE ACCIONES
LnkRemisiones.Visible = False
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
HlAgregarExcel.Visible = False
'VINCULARA LAS OC QUE TENGAN CONTRATO SOLAMENTE
TieneContrato = True
LnkOCs.Visible = True
UpnTools.Update()
Else
DdlContratosOC.Items.Clear()
DdlContratosOC.DataSource = DtContratos
DdlContratosOC.DataBind()
DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0"))
GvContratoDetalles.DataSource = Nothing
GvContratoDetalles.DataBind()
UpContratos.Update()
DivEstimaciones.Visible = True
ContratoDetalles.Visible = False
UPEstimaciones.Update()
Tab.ActiveTab = TabGenerales
TabGenerales.Enabled = True
Updatetabs.Update()
TieneContrato = False
End If
PresionarBotonModal("C_BtnCerrarContrato")
End Sub
Private Sub BtnCancelarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCancelarContratoDetalles.Click
DtContratos = Nothing
PresionarBotonModal("C_BtnCerrarContrato")
End Sub
Private Sub DdlContratosModal_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosModal.SelectedIndexChanged
DdlContratoModalSelectIndex()
End Sub
Protected Sub RBLTipoContrato_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaContratos()
End Sub
Private Sub CargaContratos()
Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}")
If DrContrato Is Nothing Then
Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError)
Exit Sub
End If
LbContratoImporteTotal.Text = DrContrato("ImporteTotal").ToString.FormatoNumero
LbContratoImporteMinimo.Text = DrContrato("ImporteMin").ToString.FormatoNumero
LbContratoImporteMaximo.Text = DrContrato("ImporteMax").ToString.FormatoNumero
LtContratoImporteSaldo.Text = DrContrato("ImporteSaldo").ToString.FormatoNumero
Dim ObjContrato As New ClsContratos
Dim NoId As Integer = 0
If ObjContrato.GetContratosDetalle(DdlContratosModal.SelectedValue.ToEntero) Then
'SI ES CONTRATO DE CONSIGNACION DE VENTA AGARRA LAS EXISTENCIAS DEL ALMACEN
CreaConsignacionSerieDetalle()
CveAlmacenExistenciasContrato = -1
CveAlmacenOrigenContrato = -1
GvContratoDetalles.Columns(8).Visible = False
If DrContrato("CveContratoTipo").ToString.Contiene("27") Then
CveAlmacenExistenciasContrato = If(DrContrato("CveAlmacenDestino").ToString.ToEntero > 0, DrContrato("CveAlmacenDestino").ToString.ToEntero, -1)
CveAlmacenOrigenContrato = If(DrContrato("CveAlmacenOrigen").ToString.ToEntero > 0, DrContrato("CveAlmacenOrigen").ToString.ToEntero, -1)
End If
NoId = ObjContrato.DtResultados.FiltraParametros("NoIdentificacion <> ''").Rows.Count 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA
Dim DtDetalle As DataTable = ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}")
GvContratoDetalles.DataSource = DtDetalle 'ObjContrato.DtResultados.FiltraParametros($"CveTipoPresupuesto = {RBLTipoContrato.SelectedValue}")
GvContratoDetalles.DataBind()
UpContratos.Update()
NumeroContrato = DrContrato("NumeroContrato").ToString
DescripcionContrato = DrContrato("DescripcionContrato").ToString
NumeroLicitacion = DrContrato("NumeroLicitacion").ToString.Trim
DdlVendedor.SelectedValueExist(DrContrato("CveVendedor"))
If DrContrato("CveSucursalCliente").ToString.ToEntero > 0 Then
DdlSucursalCliente.SelectedValueExist(DrContrato("CveSucursalCliente"))
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
If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}")
DdlAlmacenAsignado.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlAlmacenAsignado.SelectedValueExist(CveAlmacenDestino.ToString)
DdlAlmacenAsignado.DataBind()
End If
UpParametros.Update()
End If
If NoId > 0 Then 'PARA SABER SI ALGUN DETALLE TIENE ESTE CAMPO Y HACER VISIBLE LA COLUMNA
GvContratoDetalles.Columns(3).Visible = True 'NoIdentificacion
End If
ObjContrato.Dispose()
If CveOC > 0 Then
BtnCargarContratoDetalles.Enabled = True
For Each gvr As GridViewRow In GvContratoDetalles.Rows
gvr.FCTextBox("TxtCant").Enabled = False
Next
Dim EsValido = True
For Each Dr As DataRow In TmpDT.Rows
Dim CantidadActual = Dr("Cantidad").ToString.ToDouble
Dim CantidadDispo = 0.0
Dim CantidadAsignada = 0.0
For Each gvr As GridViewRow In GvContratoDetalles.Rows
If gvr.DataKey("CvePS").ToEntero = Dr("CvePS").ToString.ToEntero Then
CantidadDispo = gvr.DataKey("Cantidad").ToString.ToDouble - gvr.FCTextBox("TxtCant").Text.ToDouble
If CantidadDispo = 0 Then Continue For
CantidadAsignada = If(CantidadDispo > CantidadActual, CantidadActual, CantidadDispo)
gvr.FCTextBox("TxtCant").Text = (gvr.FCTextBox("TxtCant").Text.ToDouble + CantidadAsignada).ToString
CantidadActual = CantidadActual - CantidadAsignada
If CantidadActual = 0 Then
Exit For
End If
End If
Next
If CantidadActual > 0 Then
EsValido = False
Alert("No se cumple con la totalidad de la Orden de Compra. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
BtnCargarContratoDetalles.Enabled = False
Exit For
End If
Next
If EsValido Then
BtnCargarContratoDetalles_Click(BtnCargarContratoDetalles, EventArgs.Empty)
End If
End If
'LIMPIA TIPOS DOCTO
If (DdlTipoComprobante.Items.FindByValue("Ped") IsNot Nothing) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ped"))
End If
If (DdlTipoComprobante.Items.FindByValue("PeC") IsNot Nothing) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PeC"))
End If
If (DdlTipoComprobante.Items.FindByValue("Cot") IsNot Nothing) Then 'NO PUEDEN HACER COTIZACIÓN DE UN CONTRATO
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot"))
End If
Select Case RBLTipoContrato.SelectedValue.ToEntero
Case 1
DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped"))
DdlTipoComprobante.SelectedValue = "Ped"
DdlTipoComprobante.Enabled = False
Case 2
DdlTipoComprobante.Enabled = True
DdlTipoComprobante.SelectedValueExist("Ing")
Case 3
DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido de Consignación", "PeC"))
DdlTipoComprobante.SelectedValue = "PeC"
DdlTipoComprobante.Enabled = False
End Select
ChkPSOC.Checked = False
CambiaTipoDocto()
UpParametros.Update()
UPEstimaciones.Update()
UPOCFactura.Update()
End Sub
Private Sub BtnCargarContratoDetalles_Click(sender As Object, e As EventArgs) Handles BtnCargarContratoDetalles.Click
''SI LA VENTA ES TIPO VENTA DE CONTRATO Y EL CONTRATO TIENE LICITACION EL CLIENTE DEBE TENER IMPUESTOS LOCALES
'If RBLTipoContrato.SelectedValue = "2" Then
' Dim ObjClientes As New ClsClientes
' If NumeroLicitacion <> "" Then
' If ObjClientes.GetClienteImpuestosLocales(CveCliente) Then
' If Not ObjClientes.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then
' Alert("El contrato con licitación al que se hace referencia requiere impuestos locales.", TipoMensaje.MsgAdvertencia)
' ObjClientes.Dispose()
' Exit Sub
' End If
' End If
' End If
' ObjClientes.Dispose()
'End If
Dim DrContrato As DataRow = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue.ToEntero}")
Dim ps As New ClsInventarios
CveContrato = DdlContratosModal.SelectedValue.ToEntero
AplicaGastoContrato = If(DrContrato("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento
'VALIDA IMPORTE DEL CONTRATO
Dim SeleccionadoContrato = 0.0 '(From row As GridViewRow In GvContratoDetalles.Rows.Cast(Of GridViewRow)() Select row.FCLabel("LtlTotal").Text.ToDecimal).Sum
TmpDT.Clear()
TxtSubTotal.Text = "0"
LblDescuentos.Text = "0"
TxtIVA.Text = "0"
TxtRetIVA.Text = "0"
For Each Row As GridViewRow In GvContratoDetalles.Rows
If Row.FCTextBox("TxtCant").Text.ToEntero > 0 Then
'VALIDA EXISTENCIAS DE ALMACÉN
'Dim DrPS = GlobalDTProductosServicios(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero).FiltroPrimero("")
Dim DrPS = GlobalDTPS(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=Row.DataKey("CvePS").ToEntero).FiltroPrimero("")
If DrPS IsNot Nothing Then
Dim CveTipoPS As Integer = DrPS("CveTipoPS").ToString.ToEntero
Dim CveTipoInv As Integer = DrPS("Inv_CveMetodoInventario").ToString.ToEntero
Dim existencia As Decimal = ps.GetExistenciasPS(Row.DataKey("CvePS").ToEntero, Row.DataKey("CveUM").ToEntero, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1)
If (existencia < Row.FCTextBox("TxtCant").Text.ToEntero AndAlso CveTipoPS <> 1) AndAlso UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ped") Then ' And DdlContratosModal.SelectedValue.ToEntero <> 196 Then
Alert("No cuenta con la cantidad suficiente en inventario para el producto: <br/>" + Row.FCLiteral("LtlPS").Text + ".", TipoMensaje.MsgAdvertencia)
TmpDT.Clear()
GvPS.DataSource = Nothing
GvPS.DataBind()
UpPS.Update()
Exit Sub
Else
SeleccionadoContrato += Row.FCTextBox("TxtCant").Text.ToEntero * Row.FCLiteral("LtlPU").Text.ToDouble
AgregarProductoServicio(Row.FCTextBox("TxtCant").Text.ToEntero, Row.DataKey("CveUM").ToEntero, Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero,
Row.DataKey("Clasificacion"), Row.DataKey("CvePS").ToEntero, Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, Row.DataKey("Observaciones"), $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDecimal, 0,
DrContrato("CveProyecto").ToString.ToEntero, DrContrato("ProyectoContrato").ToString, DrContrato("CveSubProyecto").ToString.ToEntero, DrContrato("SubProyectoContrato").ToString, CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero)
'AddPS(Row.FCTextBox("TxtCant").Text.ToEntero, Row.DataKey("CveUM").ToEntero, Row.FCLiteral("LtlUM").Text, Row.DataKey("CveClasificacion").ToEntero, Row.DataKey("Clasificacion"),
' Row.DataKey("CvePS").ToEntero, Row.FCLiteral("LtlPS").Text, If(CveCicloComercial > 0, Row.DataKey("Observaciones"), $"/ {Row.FCLiteral("LtCveInterna").Text}"), Row.FCLiteral("LtlPU").Text.ToDouble, If(Row.DataKey("IVA").ToDouble = -1, ViewState("IVA").ToString.ToDouble, Row.DataKey("IVA").ToDouble), 0, 0, 1, 0, True, "",
' DrContrato("CveProyecto").ToString.ToEntero, DrContrato("ProyectoContrato").ToString, DrContrato("CveSubProyecto").ToString.ToEntero, DrContrato("SubProyectoContrato").ToString, CveTipoPS, CveTipoInv, CveContratoDetalle:=Row.DataKey("CveContratoDetalle").ToEntero, CodigoPS:=Row.FCLiteral("LtlPS").Text)
End If
Else
Alert("El producto presenta una inconsistencia en su información", TipoMensaje.MsgError)
TmpDT.Clear()
GvPS.DataSource = Nothing
GvPS.DataBind()
UpPS.Update()
Exit Sub
End If
End If
Next
'SI EL CONTRATO TIENE IMPUESTOS LOCALES SE CARGAN LOS DEL CONTRATO AHUEVO
If RBLTipoContrato.SelectedValue = "2" Then
Dim ObjContratos As New ClsContratos
If ObjContratos.GetContratoImpuestosLocales(CveContrato, UsuarioActual.CveEmpresa) Then
If ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1").Rows.Count > 0 Then
Dim DtContratoImpuesto As DataTable = ObjContratos.DtResultados.FiltraParametros("Seleccionado = 1", "Orden")
If DtContratoImpuesto IsNot Nothing AndAlso DtContratoImpuesto.Rows.Count > 0 Then
' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear()
TmpDTImpuestos = DtContratoImpuesto
GvImpuestosLocales2.DataSource = TmpDTImpuestos
GvImpuestosLocales2.DataBind()
If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then
TrOtros.Visible = True
GvImpuestosLocales2.Visible = True
TrOtros.Style.Add("display", "")
Else
TrOtros.Visible = False
GvImpuestosLocales2.Visible = False
End If
DtContratoImpuesto.Dispose()
End If
UpImpuestos.Update()
End If
End If
ObjContratos.Dispose()
End If
If Not CveCicloComercial > 0 Then
'SI EL IMPORTE MAX O EL IMPORTE FIJO DEL CONTRATO FLEXIBLE ES CERO, NO HAY LIMITE
If Not (DrContrato("Importe").ToString.ToDouble = 0 And DrContrato("ImporteMax").ToString.ToDouble = 0) Then
If DdlTipoComprobante.SelectedValue = "Ing" And (DrContrato("ModalidadDetalle").ToString = "1" Or DrContrato("ImporteMax").ToString.ToDouble > 0) AndAlso (DrContrato("ImporteTotal").ToString.ToDouble - DrContrato("Avance").ToString.ToDouble) < (SeleccionadoContrato) Then
Alert("Se excede el importe límite del contrato. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
TmpDT.Clear()
GvPS.DataSource = Nothing
GvPS.DataBind()
UpPS.Update()
Exit Sub
End If
End If
End If
CalculaTotalesVenta()
LbAgregar.Visible = False
UpPS.Update()
'restricciones para evitar cambios una vez seleccionado el contrato
If BtnEmitirImprimir.Visible = False Then BtnEmitirImprimir.Visible = True : TrVistaPrevia.Visible = True
'DESACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto disabled")
TxtCodigo.ReadOnly = True
Tab.ActiveTab = TabGenerales
TabGenerales.Enabled = True
Updatetabs.Update()
PresionarBotonModal("C_BtnCerrarContrato")
ps.Dispose()
UpFacturar.Update()
End Sub
Private Sub CargarContratoUrl()
Dim ObjContratos As New ClsContratos
If ObjContratos.GetContratos(CveContrato, UsuarioActual.CveEmpresa, -1, -1, 1) Then
If ObjContratos.DtResultados.Rows.Count > 0 Then
'Cargamos los datos del Cliente
DtContratos = ObjContratos.DtResultados
ViewState("CveCliente") = ObjContratos.DtResultados(0)("CveCliente").ToString.ToEntero
CorreoNotificacionPedDev = ObjContratos.DtResultados(0)("CorreoNotificacionPedDev").ToString
HdnCveCliente.Value = ObjContratos.DtResultados(0)("CveCliente").ToString
CargaCliente(CveCliente)
DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped"))
DdlTipoComprobante.SelectedValue = "Ped"
DdlTipoComprobante.Enabled = False
DdlAlmacenAsignado.Enabled = False
DdlSubProyectoDatos.SelectedValueExist(ObjContratos.DtResultados(0)("CveSubProyecto"))
AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento
If TipoContrato = 1 Then
'Cargamos los datos del Contrato
RblOpcionContrato.SelectedValue = "2"
BtnIniciarContrato_Click(Nothing, Nothing)
DdlContratosModal.SelectedValue = CveContrato.ToString
DdlContratosModal_SelectedIndexChanged(Nothing, Nothing)
ElseIf TipoContrato = 0 Then
'Mostramos los almacenes
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} {If(DdlTipoComprobante.SelectedValue = "Ped", "", "AND CveTipoAlmacen IN (4,10)")}")
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.Enabled = True
TrAlmacenAsignado.Visible = True
TrTipoPedido.Visible = True
TrObs.InnerText = "No. Serie"
SpObs.InnerText = "Contrato"
TrObsGenerales.InnerText = "Número de Contrato "
UpParametros.Update()
End If
If ObjContratos.CveAlmacen > 0 Then
If (DdlAlmacenAsignado.Items.FindByValue(ObjContratos.CveAlmacen.ToString) Is Nothing) Then
Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacen.ToString))
If dr IsNot Nothing Then
DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString))
End If
End If
DdlAlmacenAsignado.SelectedValue = ObjContratos.CveAlmacen.ToString
DdlAlmacenAsignado.Enabled = False
Else
If (DdlAlmacenAsignado.Items.FindByValue("89") Is Nothing) Then
Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", "89"))
If dr IsNot Nothing Then
DdlAlmacenAsignado.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString)) ' lo genera Obj.SelectedValue = Valor.ToString
DdlAlmacenAsignado.Enabled = False
End If
End If
DdlAlmacenAsignado.SelectedValue = "89"
End If
If ObjContratos.CveAlmacenOrigen > 0 AndAlso TipoContrato = 0 Then
DdlAlmacenOrigen.Visible = True
RequiereAlmacenOrigen = True
If (DdlAlmacenOrigen.Items.FindByValue(ObjContratos.CveAlmacenOrigen.ToString) Is Nothing) Then
Dim dr As DataRow = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveAlmacen = {0}", ObjContratos.CveAlmacenOrigen.ToString))
If dr IsNot Nothing Then
DdlAlmacenOrigen.Items.Insert(0, New ListItem(dr("Almacen").ToString, dr("CveAlmacen").ToString))
End If
End If
DdlAlmacenOrigen.SelectedValue = ObjContratos.CveAlmacenOrigen.ToString
DdlAlmacenOrigen.Enabled = False
End If
Else
Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
Else
Alert("Ocurrió un error al carga la información del Contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
ObjContratos.Dispose()
End Sub
Private Sub CargarPedidoUrl()
CargaVenta()
CargaFolios()
TrAlmacenOrigen.Visible = True
TrAlmacenAsignado.Visible = True
RequiereAlmacenDestino = True
BtnEmitirImprimir.Text = "Devolver Pedido"
BtnEmitirImprimir.Visible = True
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.Items.Insert(0, New ListItem("Productos Financieros Como Dato", "89"))
DdlAlmacenAsignado.Enabled = False
UpParametros.Update()
UpFacturar.Update()
End Sub
Private Sub GuardarContratoAvanceEstimaciones(ObjContrato As ClsContratos, factura As Modelos.Factura, ErrorList As List(Of String), Multiplicador As Integer, Optional CrearAvance As Boolean = False)
If (factura.CveContrato > 0 AndAlso ((DdlContratosModal.Items.Count > 0 AndAlso factura.CveContrato = DdlContratosModal.SelectedValue.ToEntero) OrElse DdlFiltroContrato.SelectedValue.ToEntero > 0 OrElse CrearAvance)) Or ContratoOC Then
Dim CveEstimacion As Integer = -1
If ObjContrato.AddEstimaciones(factura.CveContrato, factura.Fecha, -1, factura.CveVenta, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then
CveEstimacion = ObjContrato.DtResultados(0)("CveEstimacion").ToString.ToEntero
For Each row As DataRow In TmpDT.Rows
If row("CveContratoDetalle").ToString.ToEntero > 0 Then
If Not ObjContrato.AddContratosAvance(row("CveContratoDetalle").ToString.ToEntero, row("Cantidad").ToString.ToEntero * Multiplicador, factura.Fecha, UsuarioActual.CveUsuario, CveEstimacion:=CveEstimacion) Then
ErrorList.Add("Ocurrió un error al agregar los avances")
End If
End If
Next
Else
ErrorList.Add("Ocurrió un error al agregar las estimaciones")
End If
End If
End Sub
Private Sub GvContratoDetalles_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvContratoDetalles.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim CantidadDisponible = If(e.Row.DBCampo("Cantidad").ToDouble < 0, "0", e.Row.DBCampo("Cantidad"))
e.Row.FCLiteral("LtlCantDisp").Text = CantidadDisponible
If CveCicloComercial > 0 Then 'Si es un Ciclo Comercial quitamos el límite de CantidadDisponible
e.Row.Cells(1).Style.Add("display", "none")
CantidadDisponible = "10000000"
e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadContratada")
End If
'Si es contrato flexible le damos una cantidad alta de lo contrario lo maximo es lo estipulado en el contrato
If e.Row.DataKey("LimitarCantidad").ToString() = "True" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or e.Row.DataKey("ModalidadDetalle").ToString() = "1" Then
e.Row.FCRangeValidator("RVCant").MaximumValue = CantidadDisponible
LimitaCantidadSerieLote = 1
Else
e.Row.FCRangeValidator("RVCant").MaximumValue = "10000000"
LimitaCantidadSerieLote = 0
End If
'CONSIGNACION DE VENTA
If CveAlmacenExistenciasContrato > 0 And e.Row.DBCampo("Inv_CveMetodoInventario").ToString.ToEntero = 5 Then
GvContratoDetalles.Columns(8).Visible = True
e.Row.FCButton("BtnSerieConsignacion").Visible = True
e.Row.FCButton("BtnSerieConsignacion").CommandArgument = $"{e.Row.DBCampo("CveContratoDetalle")}°{e.Row.DBCampo("CvePS")}°{e.Row.DBCampo("CveUM")}°{e.Row.DBCampo("CodigoPS")}°{e.Row.DBCampo("Cantidad")}°{LimitaCantidadSerieLote}"
e.Row.FCTextBox("TxtCant").Enabled = False
End If
''Si viene de una OC Sin Facturar y tiene contrato
'If TieneContrato AndAlso ContratosConOC IsNot Nothing AndAlso ContratosConOC.ToString.Length > 0 Then
' e.Row.FCTextBox("TxtCant").Text = e.Row.DBCampo("CantidadOC").ToString
'End If
End If
End Sub
Private Sub BtnCalcularTotalesContrato_Click(sender As Object, e As EventArgs) Handles BtnCalcularTotalesContrato.Click
For Each row As GridViewRow In GvContratoDetalles.Rows
row.FCLiteral("LtlTotal").Text = (row.FCLiteral("LtlCantDisp").Text.ToEntero * row.FCTextBox("TxtCant").Text.ToDouble).FormatoNumero(2)
Next
UpContratos.Update()
End Sub
Private Sub DdlContratoModalSelectIndex()
If Not DdlContratosModal.SelectedValue.ToEntero > 0 Then
GvContratoDetalles.DataBind()
UpContratos.Update()
Exit Sub
End If
Dim DrContrato = DtContratos.FiltroPrimero($"CveContrato = {DdlContratosModal.SelectedValue}")
If DrContrato Is Nothing Then
Alert("Ocurrió un error al cargar la configuración del contrato. Por favor vuelva a intentar", TipoMensaje.MsgError)
Exit Sub
End If
CargaContratos()
DdlContratosOC.SelectedValue = DdlContratosModal.SelectedValue
UPOCFactura.Update()
End Sub
#End Region
#Region "C A R G A S"
Private Sub ClasificacionModal()
DdlClasificacionModal.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion")
DdlClasificacionModal.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlClasificacionModal.DataBind()
UpModal.Update()
End Sub
Private Sub CargaOrdenProduccion(Optional Opcion As Integer = 1, Optional CveVenta As Integer = -1)
DdlOrdenProduccion.Items.Clear()
Dim CveOrdenProduccion As String = "-1"
Dim ObjCGame As New ClsCGame
If ObjCGame.GetOrdenProduccion(-1, UsuarioActual.CveEmpresa, -1, "-1", MinFecha, MaxFecha, -1) Then
If Opcion = 1 Then
DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros(String.Format("CveVenta IS NULL "))
ElseIf Opcion = 2 Then
LnkActualizarOrdenProduccion.Visible = True
DdlOrdenProduccion.DataSource = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta} OR CveVenta IS NULL")
If ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows.Count > 0 Then
CveOrdenProduccion = ObjCGame.DtResultados.FiltraParametros($"CveVenta = {CveVenta}").Rows(0)("CveOrdenProduccion").ToString
End If
End If
DdlOrdenProduccion.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
ObjCGame.Dispose()
DdlOrdenProduccion.DataBind()
DdlOrdenProduccion.SelectedValueExist(CveOrdenProduccion)
End Sub
Private Sub CargaEstatusFactura(Optional TipoDocto As String = "Ing")
Dim FiltroCompromiso = If(TipoDocto = "Com", "And CveEstatusFactura In (2, 9)", "And CveEstatusFactura Not In (9)")
If TipoDocto.ToUpper.Contiene("EGS", "COM", "ANT") Then TipoDocto = "Ing"
'DdlEstatus.Items.Clear()
'DdlEstatus.Items.Insert(0, New ListItem("Seleccione", "-1"))
'DdlEstatus.SelectedValue = "-1"
'DdlEstatus.DataSource = GlobalDTEstatusFactura.FiltraParametros(String.Format("TipoDocto = '{0}' {1}", TipoDocto, FiltroCompromiso))
'DdlEstatus.DataBind()
''If DdlEstatus.Items.Count > 1 Then
'' DdlEstatus.SelectedIndex = 1
''End If
''permiso para poder cambiar estatus
'If CveVenta > 0 Then DdlEstatus.Enabled = UsuarioActual.TienePermisoProceso(116)
End Sub
Private Sub CargaOS(CveOS As Integer)
Dim OS As New ClsOS
Dim DtDetalle As DataTable = Nothing
Dim DtDetalleMateriales As DataTable = Nothing
If OS.GetOrdenesServicios(CveOS, -1, -1, -1, -1, UsuarioActual.CveEmpresa) Then
HdnCveCliente.Value = OS.CveCliente.ToString
ViewState("CveCliente") = OS.CveCliente
CargaCliente(CveCliente)
If OS.GetOrdenesServiciosDetalleAFacturar(CveOS) Then
Dim Cons As Integer = 1
For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows
AgregarProductoServicio(dr("Cantidad").ToString.ToDecimal, dr("CveUM").ToString.ToEntero, dr("UM").ToString, -1, "", dr("CvePS").ToString.ToEntero, "", dr("Obs").ToString, 0, 0, -1, "",
dr("CveSubProyecto").ToString.ToEntero, dr("SubProyecto").ToString)
'Dim drt As DataRow = TmpDT.NewRow
'drt("Consec") = Cons
'drt("CvePS") = dr("CvePS")
'drt("CveClasificacion") = dr("CveClasificacion")
'drt("Clasificacion") = dr("Clasificacion")
'drt("PS") = dr("PS")
'drt("CveOSDetalle") = dr("CveOSDetalle")
'drt("CodigoPS") = dr("CodigoPS")
'drt("Cantidad") = dr("Cantidad")
'drt("CveSubProyecto") = dr("CveSubProyecto")
'drt("SubProyecto") = dr("SubProyecto")
'drt("Obs") = dr("Obs")
'TmpDT.Rows.Add(drt)
'Cons = Cons + 1
Next
TmpDT.AcceptChanges()
DtDetalle = OS.DtResultados.FiltraParametros("SeFacturara = 1 ")
End If
For Each Row As DataRow In DtDetalle.Rows
If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString.ToEntero, CveOS) Then
If OS.DtResultados.FiltraParametros("SeFacturara = 1").Rows.Count > 0 Then
Alert("Hay materiales en la Orden de Servicio, ¿Desea facturar los materiales?", TipoMensaje.MsgConfirmacion, "BtnMateriales()")
End If
End If
Next
OS.Dispose()
TxtTotal.Text = TmpDT.SUM("Total").FormatoNumero()
GvPS.DataSource = TmpDT
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvPS.DataBind()
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
UpContado.Update()
UpPS.Update()
End If
End Sub
Private Function CargaVenta() As Boolean
Dim Retorno As Boolean = False
'CARGA PARA FACTURACION
Dim CveRemision As Integer = IfNull(ViewState("CveRemision"), 0).ToString.ToEntero
Dim CveCotizacion As Integer = IfNull(ViewState("CveCotizacion"), 0).ToString.ToEntero
Dim CveVenta As Integer = Me.CveVenta
CveVenta = If(CveRemision > 0, CveRemision, CveVenta)
CveVenta = If(CveCotizacion > 0, CveCotizacion, CveVenta)
CveVenta = If(CvePedido > 0, CvePedido, CveVenta)
Dim ObjVentas As New ClsVentas()
Dim SerieFolioPadre As String
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then
Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0)
Dim CveCliente As Integer = DbRowVenta("CveCliente").ToString.ToEntero
HdnCveVenta.Value = CveVenta.ToString
Me.CveEstatusFacturaPadre = DbRowVenta("CveEstatusFacturaPadre").ToString.ToEntero
'CargaEncabezado
If Not (CveRemision > 0 Or CveCotizacion > 0) Then
DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString
If UsuarioActual.TienePermisoProceso(274) Then
TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant"
End If
If TrAntEspecial.Visible Then
ChkAntEspecial.Enabled = False
ChkAntEspecial.Checked = If(DbRowVenta("AnticipoEspecial").ToString = "True", True, False)
End If
CargaEstatusFactura(DdlTipoComprobante.SelectedValue)
CveEstatus = DbRowVenta("CveEstatusFactura").ToString.ToEntero
LbEstatus.Text = DbRowVenta("EstatusFactura").ToString
ViewState("SaldoVenta") = DbRowVenta("Saldo").ToString
AplicaCancelarRemision = CBool(DbRowVenta("AplicaCancelarRemision").ToString)
If AplicaCancelarRemision AndAlso CveEstatus.Contiene(2, 3) AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then DivCanRem.Visible = True
VentaSaldoAlmacen = DbRowVenta("SaldoAlmacen").ToString.ToDecimal
If CveEstatus = 5 Then LbCancelarDocumento.Enabled = False
'If CveEstatus = 20 Then
' LbCancelarDocumentoManual.Visible = True
'End If
If Not CveEstatus.Contiene(4, 5, 12, 13, 20) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Ant") AndAlso UsuarioActual.TienePermisoProceso(159) Then
Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto")))
If TienePermiso <> "" Then
LkRefacturacion.Visible = True
End If
End If
If DbRowVenta("CveVentaRelacionada").ToString.ToEntero > 0 Then
TrRefacturadaa.Visible = True
HplRefacturadaEn.NavigateUrl = String.Format("/Ventas/Ventas.aspx?CveVenta={0}", DbRowVenta("CveVentaRelacionada"))
HplRefacturadaEn.Text = DbRowVenta("SerieFolioRelacionada").ToString
LblAlertRefacInv.Visible = True
End If
If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Ing", "Ant", "Dev", "Rem", "DPe") AndAlso Not CveEstatus.Contiene(4, 5, 12, 13, 20) Then
If UsuarioActual.TienePermisoProceso(159) Then
Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto")))
If TienePermiso <> "" Then
LbCancelarDocumento.Visible = True
'If UsuarioActual.CveEmpresa = 119 And Not UsuarioActual.CveUsuario.Contiene(100, 1703) Then '[IPP] AD y Jesus de JAM
' 'si es del mes anterior no permita cancelar
' If Not DdlTipoComprobante.SelectedValue.Contiene("Rem") Then
' If DbRowVenta("Fecha").ToString.ToDate <= Now.AddMonths(-1).LastDayOfMonth Then
' LbCancelarDocumento.Visible = False
' End If
' End If
'End If
End If
End If
End If
If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Ing", "Ant", "Dev") AndAlso LblFolioFiscal.Text.Trim = "" Then HplFolioFiscalModal.Visible = True
Select Case DbRowVenta("TipoDocto").ToString
Case "Ing"
Trsaldo.Visible = True
HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then
HLPagar.Visible = True
HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675"
HlCuentaTerminal.Visible = True
End If
Dim TienePermiso As String = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, -1).FiltroPrimeroValor("CveSubProyecto", String.Format("CveSubProyecto = {0}", DbRowVenta("CveSubProyecto")))
If TienePermiso <> "" Then ' si tiene acceso en el subproyecto
'LkNotaCredito.Visible = UsuarioActual.TienePermisoProceso(175)
If UsuarioActual.TienePermisoProceso(264) Then
LkDevolucion.Visible = True
InicializaAplicaDevolucion()
End If
End If
HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto"))))
Case "Egs"
HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto"))))
HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString
Trsaldo.Visible = True
HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
Case "Rem"
'IPP 15 Julio 2017
Trsaldo.Visible = True
HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
If SaldoVenta > 0 And UsuarioActual.TienePermisoProceso(100) Then
HLPagar.Visible = True
HLPagar.NavigateUrl = $"/Bancos/PopIEVentas.aspx?CveVenta={CveVenta}&TB_iframe=true&height=500&width=675"
HlCuentaTerminal.Visible = True
End If
If UsuarioActual.CveEmpresa = 80 Then
LtlImprimir.Text = String.Format("<li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}""><i class=""fa fa-print""></i> Imprimir</a></li>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta)))
End If
DiasCredito = DbRowVenta("DiasCredito").ToString.ToEntero
EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString)
Case "OP"
TdOrdenPago.Visible = True
DdlOrdenPago.SelectedValue = DbRowVenta("Num3").ToString
DdlOrdenPago.Enabled = False
Case "Cot"
TxtAtencionA.Text = DbRowVenta("AtencionA").ToString
TxtFechaVencimientoCotizacion.Text = DbRowVenta("Vigencia").ToString
PnlImprimir.Visible = True
HLOrdendeCompra.Visible = True
HLOrdendeCompra.NavigateUrl = String.Format("/OC/OC.aspx?Tipo=Req&CveCotizacion={0}", CveVenta)
Dim ObjOS As New ClsOS()
If ObjOS.GetCotizacionOS(CveVenta) Then
If ObjOS.DtResultados.Rows.Count > 0 Then
Dim DbRowOS As DataRow = ObjOS.DtResultados.Rows(0)
ViewState("CveOS") = DbRowOS("CveOS").ToString.ToEntero
CargaOS(CveOS)
End If
Else
HLOrdenServicio.Visible = True
HLOrdenServicio.NavigateUrl = String.Format("/OS/OrdenesServicios.aspx?CveCotizacion={0}", CveVenta)
End If
ObjOS.Dispose()
If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 145) Then PnlImprimir.Visible = True : LnkImprimir.OnClientClick = "javascript:ImprimirCotizacion();return false;"
'Deshabilitar impresión cuando no esté supervisada
If DbRowVenta("TipoEstatus").ToString.ToEntero = 2 Or UsuarioActual.Empresa.Funcionalidad(113) = "1" Then
PnlImprimir.Visible = True
Else
HplDownPDF.Visible = False
PnlImprimir.Visible = False
End If
'Verifico si tiene la funcionalidad (135)
If UsuarioActual.Empresa.Funcionalidad(135) = "1" Then
'Reviso cuales son los supervisores
Dim Objeto As New ClsVtaVendedores
If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then
Dim DTVendedores As New DataTable
DTVendedores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString)).FiltraParametros(String.Format("CveSupervisor = {0}", UsuarioActual.CveVendedor))
'Verifico si es su supervisor asignado
If DTVendedores.Rows.Count > 0 Then
LkCotizacionAutorizar.Visible = True
End If
DTVendedores.Dispose()
End If
Objeto.Dispose()
End If
String.Format("CveVendedor = {0}", DbRowVenta("CveVendedor").ToString)
Case "Ant"
Trsaldo.Visible = True
HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
'LkNotaCredito.Visible = True
HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto"))))
Case "Dev"
DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev"))
HplDownXML.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto"))))
HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString
ViewState("CveDevolucion") = DbRowVenta("CveVentaPadre").ToString.ToEntero
Trsaldo.Visible = True
HplSaldoAuxiliar.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
HplPagado.NavigateUrl = String.Format("/Contabilidad/PopUpAuxiliar.aspx?Tipo=CxCClientes&CveCliente={0}&CveVenta={1}&TB_iframe=true&height=550&width=920", DbRowVenta("CveCliente"), DbRowVenta("CveVenta"))
Case "Ped"
DdlTipoComprobante.Items.Insert(0, New ListItem("Pedido", "Ped"))
Case "DPe"
DdlTipoComprobante.Items.Insert(5, New ListItem("Devolución de perdido", "DPe"))
Case "PeC"
DdlTipoComprobante.Items.Insert(5, New ListItem("Pedido de Consignación", "PeC"))
Case "PA"
BtnGenerarRemision.Visible = If(CveEstatus = 16, True, False)
CvePedidoA = CveVenta
DiasCredito = DbRowVenta("DiasCredito").ToString.ToEntero
EsDiasCreditoFijo = CBool(DbRowVenta("EsDiasCreditoFijo").ToString)
Case "Pd2"
CvePedido2 = CveVenta
BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False)
BtnGenerarRemision.Visible = If(CveEstatus <> 21, True, False)
End Select
DdlTipoComprobante.SelectedValue = DbRowVenta("TipoDocto").ToString
End If
'contado 0, credito 1, terminal 2
If ObjVentas.DtResultados(0)("CondicionesPago").ToString.ToEntero = 1 Then
RBLPago.SelectedValue = "1"
RBLPago_SelectedIndexChanged(Nothing, Nothing)
UPCondicionesPago.Update()
ElseIf ObjVentas.DtResultados(0)("CondicionesPago").ToString.ToEntero = 0 Then
RBLPago.SelectedValue = "2"
RBLPago.Items(0).Enabled = False
RBLPago_SelectedIndexChanged(Nothing, Nothing)
UPCondicionesPago.Update()
Else
DdlCuentasTerminal.SelectedValue = DbRowVenta("CveCuentaTerminal").ToString
RBLPago.SelectedValue = "3"
RBLPago.Items(0).Enabled = False
RBLPago_SelectedIndexChanged(Nothing, Nothing)
UPCondicionesPago.Update()
End If
'CargaDetalle
If ObjVentas.GetVentaDetalle(CveVenta) Then
TmpDT = ObjVentas.DtResultados
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
GvPS.DataSource = ObjVentas.DtResultados
GvPS.DataBind()
'IEPS A NIVEL DETALLE
'TxtIEPS.Text = If(TmpDT.SUM("IEPS") > 0, TmpDT.SUM("IEPS").FormatoNumero, TxtIEPS.Text)
End If
'ESCONDE ACCIONES
LnkRemisiones.Visible = False
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
LnkOCs.Visible = False
UpnTools.Update()
DivEstatusFac.Visible = True
HdnCveCliente.Value = CveCliente.ToString
ViewState("CveCliente") = CveCliente
ViewState("CveEmpresaCRM") = DbRowVenta("CveEmpresaCRM").ToString.ToEntero
ViewState("CveAcercamientoCRM") = DbRowVenta("CveAcercamientoCRM").ToString.ToEntero
Entrega = DbRowVenta("Entrega").ToString
Vigencia = DbRowVenta("Vigencia").ToString.ToDate.ToShortDateString
HplSaldoAuxiliar.Text = DbRowVenta("Saldo").ToString.FormatoNumero(2)
If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then
HplSaldoAuxiliar.Visible = False
HplPagado.Visible = True
If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString.ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then
ImgAntiPend.Visible = True
Else
ImgAntiPend.Visible = False
End If
End If
HdnPagado.Value = DbRowVenta("Pagado").ToString
TxtTotal.Text = DbRowVenta("Total").ToString.FormatoNumero(2)
HdnVentaSaldo.Value = (SaldoVenta).ToString
CvePrePoliza = DbRowVenta("CvePrePoliza").ToString.ToEntero
CveVentaFacturada = DbRowVenta("CveVentaFacturada").ToString.ToEntero
CveVentaRelacion = DbRowVenta("CveVentaRelacion").ToString.ToEntero
ImporteRelacion = DbRowVenta("ImporteRelacion").ToString.ToDouble
DdlMoneda.SelectedValue = DbRowVenta("CveMoneda").ToString
CambiaMoneda()
If DbRowVenta("TipoDocto").ToString = "Pd2" Then
'CANTIDAD FACTURADA
If TmpDT.SUM("CantidadFacturadaPed2") > 0 Then
GvPS.Columns(7).Visible = True
ThCantidadFacturada.Visible = True
ThCantidadFacturada2.Visible = True
Else
GvPS.Columns(7).Visible = False
ThCantidadFacturada.Visible = False
ThCantidadFacturada2.Visible = False
End If
''ACTIVA EDITAR
''SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA
'If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString.ToEntero Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad")
' BtnPermisoEditarCotizacion.Visible = True
'End If
'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR
'If TmpDT.SUM("CantidadFacturadaPed2") < TmpDT.SUM("Cantidad") Then
' BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True)
' BtnsFacturar.Visible = True
'End If
End If
If CveEmpresaCRM > 0 And Not CveCliente > 0 Then
CargaEmpresaCRM(CveEmpresaCRM)
Else
CveEmpresaCRM = IIf(CveEmpresaCRM > 0, CveEmpresaCRM, 0).ToString().ToEntero()
CargaCliente(CveCliente, -1) 'Estatus activo, se requiere para cargar una factura en la que el cliente a sido eliminado
End If
ViewState("CveAlmacenTransitorio") = DbRowVenta("CveAlmacenTraspasoDestino").ToString.ToEntero
DevolucionAlmacen = DbRowVenta("EsDevolucionVenta").ToString.ToEntero
'sino esta cargada la información del metodo de pago que le corresponde, la recarga para que se le pueda asignar
If DdlMetodoPago33.SelectedValue <> DbRowVenta("CveMetodoPago33").ToString Then
CargaFormaPago(DbRowVenta("CveMetodoPago33").ToString.ToEntero)
End If
DdlMetodoPago33.SelectedValueExist(DbRowVenta("CveMetodoPago33").ToString)
DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString.ToEntero)
If DdlFormaPago33.SelectedValue <> DbRowVenta("CveFormaPago33").ToString And DbRowVenta("CveFormaPago33").ToString <> "" Then
'sino está seleccionada la asginada la debe de cargar
Dim Nombre As String = GlobalDTVtaFormaPago().FiltroPrimeroValor("FormaPagoSAT", String.Format("CveFormaPago={0}", DbRowVenta("CveFormaPago33")))
DdlFormaPago33.Items.Add(New ListItem(Nombre, DbRowVenta("CveFormaPago33").ToString))
DdlFormaPago33.SelectedValueExist(DbRowVenta("CveFormaPago33").ToString.ToEntero)
End If
DdlUsoCFDI.SelectedValueExist(DbRowVenta("CveUsoCFDI").ToString)
If UsuarioActual.CveEmpresa = 126 Then CargaOrdenProduccion(2, CveVenta)
If DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then
TrTipoRelacion.Visible = True
DdlTiposRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion").ToString.ToEntero)
HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString
End If
If DbRowVenta("Saldo").ToString.ToDouble < 0.01 Then
If ViewState("CveCotizacion") IsNot Nothing AndAlso ViewState("CveCotizacion").ToString.ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then
ImgAntiPend.Visible = True
Else
ImgAntiPend.Visible = False
End If
ElseIf Opcion <> "Op" Then
ImgAntiPend.Visible = True
End If
If UsuarioActual.CveRol.Contiene(1, 1155) Then LiLnkGuias.Visible = True
LiComplementoPago.Visible = True
ViewState("FolioFiscal") = DbRowVenta("FolioFiscal").ToString
LblSerie.Text = DbRowVenta("Serie").ToString
ViewState("Serie") = DbRowVenta("Serie").ToString
ViewState("Folio") = DbRowVenta("Folio").ToString.ToEntero
TxtFolio.Text = DbRowVenta("Folio").ToString
'TxtDocto.Text = DbRowVenta("Ref").ToString
'TxtNumCtaPago.Text = DbRowVenta("NumeroCuenta").ToString
LblFolioFiscal.Text = DbRowVenta("FolioFiscal").ToString
TxtFecha.Text = DbRowVenta("Fecha").ToString
TxtSubTotal.Text = DbRowVenta("SubTotal").ToString.FormatoNumero(2)
LblDescuentos.Text = DbRowVenta("Descuento").ToString.FormatoNumero(2)
LblAmortizacion.Text = DbRowVenta("Amortizacion").ToString.FormatoNumero(2)
TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2)
TxtIVA.Text = DbRowVenta("IVA").ToString.FormatoNumero(2)
TxtRetIVA.Text = DbRowVenta("RetIVA").ToString.FormatoNumero(2)
TxtRetISR.Text = DbRowVenta("RetISR").ToString.FormatoNumero(2)
TxtIEPS.Text = DbRowVenta("IEPS").ToString.FormatoNumero(2)
TrIEPS.Visible = TxtIEPS.Text.ToDouble > 0
TxtTotal.Text = DbRowVenta("Total").ToString.FormatoNumero(2)
HdnTotalVenta.Value = DbRowVenta("Total").ToString.FormatoNumero(2)
TxtMotivoDescuento.Text = DbRowVenta("MotivoDescuento").ToString
TxtObsFact.Text = DbRowVenta("Observaciones").ToString
LblUsuario.Text = DbRowVenta("Nombre").ToString
LblFechaRegistro.Text = DbRowVenta("FechaIng").ToString.ToDate.ToShortDateString
LblSeTimbro.Text = DbRowVenta("SeTimbro").ToString
LblMail.Text = DbRowVenta("EnvioMail").ToString
TxtFechaPago.Text = DbRowVenta("FechaVencimiento").ToString
TxtFechaVencimientoCotizacion.Text = Vigencia
TxtDet_OrdenCompra.Text = DbRowVenta("Det_OrdenCompra").ToString
TxtDet_FechaOrdenCompra.Text = DbRowVenta("Det_FechaOrdenCompra").ToString
HdnIVAOriginal.Value = TxtIVA.Text
TxtPedidoContrato.Text = DbRowVenta("PedidoContrato").ToString
TxtPedidoContrato.Enabled = False
HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString
HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2)
'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString
'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString = "True"
DdlTipoAmortizacionAnticipo.SelectedValueExist(DbRowVenta("CveTipoAmortizacionAnticipo"))
DdlTipoRelacion.SelectedValueExist(DbRowVenta("CveTipoRelacion"))
'HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString
'HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2)
'DdlAmortizacionConceptos.SelectedValue = DbRowVenta("AnticipoPosicion").ToString
'ChkAnticipoEnSubTotal.Checked = DbRowVenta("AnticipoEnSubTotal").ToString = "True"
If DbRowVenta("CveTipoRelacion").ToString.ToEntero > 0 Then
TrTipoRelacion2.Visible = True
LblTipoRelacion.Text = DbRowVenta("TipoRelacion").ToString
HdnFolioFiscalNC.Value = DbRowVenta("FolioFiscalPadre").ToString
End If
TxtOrdenCompra.Text = DbRowVenta("OrdenCompra").ToString
TxtOrdenCompra.Enabled = False
TxtObsAlmacen.Text = DbRowVenta("ObservacionesAlmacen").ToString
CvePAC = DbRowVenta("CvePAC").ToString.ToEntero
If DbRowVenta("Saldo").ToString.ToDecimal > 0 AndAlso UsuarioActual.TienePermisoProceso(204) AndAlso Not UsuarioActual.CveEmpresa.Contiene(119) Then
TxtFechaSaldarVenta.Text = TxtFecha.Text
CEFechaSaldarVenta.StartDate = TxtFecha.Text.ToDate
HLSaldarVenta.Visible = True
End If
If (UsuarioActual.TienePermisoProceso(166) Or UsuarioActual.CveRol = 1) AndAlso (LblFolioFiscal.Text = "" Or LblFolioFiscal.Text = "test") Then
LkEliminarFactura.Visible = True
End If
'Envio Direccion
If DbRowVenta("CveDireccionEnvio").ToString.ToEntero > 0 AndAlso DbRowVenta("CveDireccionEnvio").ToString IsNot Nothing Then
ChkDireccionEnvio.Checked = True
DdlDireccionEnvio.SelectedValueExist(DbRowVenta("CveDireccionEnvio").ToString.ToEntero)
DdlDireccionEnvio.Enabled = False
ChkDireccionEnvio.Enabled = False
DdlDireccionEnvio.Visible = True
trDireccionEnvio.Visible = True
End If
'ESTATUS FACTURA
If Not (CveRemision > 0 Or CveCotizacion > 0) Then
CveEstatus = DbRowVenta("CveEstatusFactura").ToString.ToEntero
End If
TxtTipoCambio.Text = DbRowVenta("TipoCambio").ToString
If DbRowVenta("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("<a Class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"" target=""_blank"">{1}</a>", CveVentaPadre, SerieFolioPadre)
End If
TxtFechaEjecucion.Text = DbRowVenta("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy")
'DdlSucursalEjecucion.SelectedValueExist(DbRowVenta("CveSucursalEjecucion").ToString)
'DdlSucursalCobranza.SelectedValueExist(DbRowVenta("CveSucursalCobranza").ToString)
DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").ToString)
'DdlSucursal.SelectedValueExist(DbRowVenta("CveSucursal").ToString)
'DdlSubProyectoDatos.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString)
If DdlSubProyectoDatos.Items.Count = 0 Then
DdlSubProyectoDatos.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
DdlSubProyectoDatos.SelectedValueExistInsert(DbRowVenta("CveSubProyecto").ToString, DbRowVenta("SubProyecto").ToString)
If DdlSubProyectoCobranza.Items.Count = 0 Then
DdlSubProyectoCobranza.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
DdlSubProyectoCobranza.SelectedValueExistInsert(DbRowVenta("CveSubProyectoCobranza").ToString, GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoCobranza").ToString.ToEntero).FiltroPrimeroValor("SubProyecto").ToString)
If DdlSubProyectoEjecucion.Items.Count = 0 Then
DdlSubProyectoEjecucion.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
DdlSubProyectoEjecucion.SelectedValueExistInsert(DbRowVenta("CveSubProyectoEjecucion").ToString, GlobalDTSubProyectos(-1, DbRowVenta("CveSubProyectoEjecucion").ToString.ToEntero).FiltroPrimeroValor("SubProyecto").ToString)
CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString.ToEntero)
If DbRowVenta("CveContrato").ToString.ToEntero > 0 Then
CveContrato = DbRowVenta("CveContrato").ToString.ToEntero
NumeroContrato = DbRowVenta("NumeroContrato").ToString
DescripcionContrato = DbRowVenta("DescripcionContrato").ToString
DdlContrato.Visible = False
HLContrato.Text = $"{DbRowVenta("NumeroContrato")} - {DbRowVenta("DescripcionContrato")}"
HLContrato.NavigateUrl = $"/Contratos/Contrato.aspx?CveContrato={CveContrato}"
'trPresupuesto.Visible = True
'HplPresupuesto.NavigateUrl = String.Format(" / Presupuestos / Presupuesto.aspx?CvePresupuesto={0}", DbRowVenta("CveContrato").ToString)
Else
NumeroContrato = ""
DescripcionContrato = ""
End If
'DdlEstatus.Items.Remove(DdlEstatus.Items.FindByText("Cotización"))
If DbRowVenta("SeTimbro").ToString <> "No" Then
HplDownXML.Visible = True
'If HLImprimir.Visible = False Then
HplDownPDF.Visible = True
'End If
ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" OrElse DdlTipoComprobante.SelectedValue = "Cot" Then
'If drv("TipoEstatus").ToString.ToEntero = 2 AndAlso drv("TipoDocto").ToString = "Cot" Then
' ImgDownPDF.Visible = True
'Else
HplDownPDF.Visible = False
'End If
ElseIf UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso DbRowVenta("SeTimbro").ToString = "No" AndAlso DbRowVenta("CveEstatusFactura").ToString = "2" AndAlso DbRowVenta("TipoDocto").ToString.Contiene("Ing", "Egs", "Dev", "Ant") Then
TrEmitir.Visible = True
If TxtFecha.Text.ToDate < Now.AddDays(-3) Then
TxtFecha.Enabled = True
End If
End If
If DbRowVenta("SeTimbro").ToString = "Si" Then
TrEmitir.Visible = False
End If
'CargaAcuseCancelacion
If DbRowVenta("CveEstatusFactura").ToString = "5" Then
ImgDownCancelacion.Visible = True
ImgDownCancelacion.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=CAN&CVEVTA={0}", CveVenta)))
End If
IdPoliza = DbRowVenta("IdPoliza").ToString.ToEntero
'Carga si es Contabilizada
If IdPoliza > 0 Then
HLContabilizada.Text = "Si"
HLContabilizada.NavigateUrl = $"/Contabilidad/RegPoliza.aspx?IdPoliza={DbRowVenta("IdPoliza")}"
trContabilizada.Visible = True
If UsuarioActual.TienePermisoProceso(107) Then BtnDescontabilizar.Visible = True
Else
'cuando no este contabilizada y usa AC, habilita el boton para generar la poliza
If UsuarioActual.Empresa.UsaAC AndAlso UsuarioActual.CveRol = 1 Then
BtnGenerarPoliza.Visible = True
End If
If UsuarioActual.Empresa.Funcionalidad(200) = "1" Then
BtnContabilizar.Visible = True
End If
End If
If DbRowVenta("IdPolizaCancelacion").ToString.ToEntero > 0 Then
HPLContaCancelacion.Text = "Cancelación"
HPLContaCancelacion.NavigateUrl = String.Format("/Contabilidad/RegPoliza.aspx?IdPoliza={0}", DbRowVenta("IdPolizaCancelacion"))
trContabilizada.Visible = True
End If
If UsuarioActual.Empresa.UsaOS AndAlso DbRowVenta("CveOS").ToString.ToEntero = 0 Then
BtnGenerarOS.Visible = True
BtnGenerarOS.OnClientClick = String.Format("javascriptwindow.location.href = '/OS/OrdenesServicios.aspx?CveVenta={0}'; return false;", CveVenta)
' BtnGenerarOS.OnClientClick = String.Format("/OS/OrdenesServicios.aspx?CveVenta={0}", CveVenta)
End If
'[IPP] COMENTADO 12/MARZO/2018 -SABRA QUE SE QUERIA ESCONDER
'If DbRowVenta("TipoDocto").ToString = "Rem" Then
' GvPS.Columns(11).Visible = False
' GvPS.Columns(12).Visible = False
'End If
'Ocultamos los botones Clonar y Ordenar
GvPS.Columns(19).Visible = False
GvPS.Columns(20).Visible = False
'CargaFirmas
If ObjVentas.GetVentasFirmas(CveVenta) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
DTmpF = ObjVentas.DtResultados
GvFirmas.DataSource = ObjVentas.DtResultados
GvFirmas.DataBind()
Else
GvFirmas.DataSource = Nothing
End If
End If
'CARGA IMPUESTOS LOCALES
If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
TrOtros.Visible = True
TmpDTImpuestos = ObjVentas.DtResultados
GvImpuestosLocales2.DataSource = ObjVentas.DtResultados
GvImpuestosLocales2.DataBind()
GvImpuestosLocales2.Enabled = False
GvImpuestosLocales2.Visible = True
End If
End If
DdlVendedor.SelectedValue = DbRowVenta("CveVendedor").ToString
DdlTipoComprobante.Enabled = False
'TxtDocto.Enabled = False
'PORLET CLIENTE
'DESACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto disabled")
TxtCodigo.ReadOnly = True
ChkEnviarFactura.Enabled = False
ChkDireccionEnvio.Enabled = False
TxtAtencionA.Enabled = False
TxtFechaVencimientoCotizacion.Enabled = False
TxtCantidad.Enabled = False
DdlClasificacion.Enabled = False
DdlPS.Enabled = False
TxtObsPS.Enabled = False
DdlProyecto.Enabled = False
DdlSubProyecto.Enabled = False
TxtPrecio.Enabled = False
ImgDescPU.Attributes.Clear()
ImgDescTotal.Attributes.Clear()
ImgDescConcepto.Attributes.Clear()
LbAgregar.Enabled = False
LnkAgregarPyME.Enabled = False
DdlCuentasTerminal.Enabled = False
For Each Row As GridViewRow In GvPS.Rows
Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString()
Next
GvPS.Columns(ColumnaEditar).HeaderText = ""
GvPS.Columns(ColumnaEliminar).HeaderText = ""
'GvPS.Columns(ColumnaEliminar).Visible = False
TxtObsFact.Enabled = False
TxtObsAlmacen.Enabled = False
TxtMotivoDescuento.Enabled = False
'GvLeyendasFiscales.Enabled = False
TxtSubTotal.ReadOnly = True
TxtIVA.ReadOnly = True
TxtRetIVA.ReadOnly = True
TxtRetISR.ReadOnly = True
TxtIEPS.ReadOnly = True
TxtTotal.ReadOnly = True
'Sección Detalle
DdlMoneda.Enabled = False
TxtFechaEjecucion.ReadOnly = True
ImgCalendarFechaEje.Enabled = False
'DdlSucursalEjecucion.Enabled = False
'DdlSucursalCobranza.Enabled = False
DdlVendedor.Enabled = False
DdlSucursalCliente.Enabled = False
TxtTiempoEntrega.Enabled = False
TxtAlfa1.ReadOnly = True
TxtAlfa2.ReadOnly = True
TxtAlfa3.ReadOnly = True
TxtNum1.ReadOnly = True
TxtNum2.ReadOnly = True
TxtNum3.ReadOnly = True
TxtFech1.ReadOnly = True : ImgFech1.Enabled = False
TxtFech2.ReadOnly = True : ImgFech2.Enabled = False
TxtFech3.ReadOnly = True : ImgFech3.Enabled = False
ChkConvertirDoctoPesos.Enabled = False
ChkConvertirDolares.Enabled = False
TxtTipoCambio.Enabled = False
TxtTipoCambioDlls.Enabled = False
'Condiciones de Pago
RBLPago.Enabled = False
DdlFormaPago33.Enabled = False
DdlUsoCFDI.Enabled = False
DdlMetodoPago33.Enabled = False
'TxtNumCtaPago.Enabled = False
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then
TxtFechaPago.ReadOnly = Not UsuarioActual.TienePermisoProceso(260)
LnkUpdateFechaVencimiento.Visible = UsuarioActual.TienePermisoProceso(260)
Else
TxtFechaPago.ReadOnly = False
End If
imgCalendario.Enabled = False
DdlFuenteRecaudacion.Enabled = False
TrVistaPrevia.Visible = False
BtnEmitirImprimir.Visible = False
'CargaLeyendasFiscales
ViewState("VentaFolio") = If(LblSerie.Text.Trim.Length = 0, TxtFolio.Text.Trim, LblSerie.Text.Trim & "-" & TxtFolio.Text.Trim)
CalculaTotalesVenta(False)
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
'CARGA ANTICIPOS
If Not (CveRemision > 0 Or CveCotizacion > 0) Then
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then
'carga as notas de credito vinculadas
If ObjVentas.GetVentasAntNC(CveVenta, -1) Then
GvAntNC.DataSource = ObjVentas.DtResultados
TmpDTDocumentosRelacionados = ObjVentas.DtResultados
GvAntNC.Caption = " <table width='100%'><tr><td style='text-align:center'>(Anticipos/NC/IxC) Vinculados</td></tr></table>"
GvAntNC.DataBind()
End If
End If
If DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev", "Ant") Then
If ObjVentas.GetVentasAntNC(-1, CveVenta) Then
GvNC.DataSource = ObjVentas.DtResultados
TmpDTNCVinculadas = ObjVentas.DtResultados
GvNC.Caption = " <table width='100%'><tr><td style='text-align:center'>Ventas Aplicadas</td></tr></table>"
GvNC.DataBind()
InicializaDTVentasNC()
For Each Dr As DataRow In ObjVentas.DtResultados.Rows
If Dr("CveConceptoContable").ToString.ToEntero = 91 Then
CargaNCDT(Dr("CveVenta").ToString.ToEntero, Dr("Importe").ToString.ToDecimal, Dr("FolioFiscal").ToString, TC:=Dr("TipoCambio").ToString.ToDecimal)
End If
Next
End If
End If
End If
If GvNC.Rows.Count > 0 Then
ImgAntiPend.Visible = False
End If
'CARGA REMISIONES
If ObjVentas.GetRemisionesRelacionadas(CveVenta, DdlTipoComprobante.SelectedValue) Then
GvRemisiones.Caption = " <table width='100%'><tr><td style='text-align:center'>Remisiones/Facturas</td></tr></table>"
GvRemisiones.DataSource = ObjVentas.DtResultados
GvCancelarRemisiones.DataSource = ObjVentas.DtResultados
GvRemisiones.DataBind()
GvCancelarRemisiones.DataBind()
'[IPP] SI ES REMISION PARA CANCELARLA NO DEBE TENER NINGUNA FACTURADA RELACIONADA - 24Abril2018
If DdlTipoComprobante.SelectedValue.Contiene("Rem") And GvRemisiones.Rows.Count > 0 Then
LbCancelarDocumento.Visible = False
End If
End If
tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
If DbRowVenta("TipoDocto").ToString = "Rem" Then
'CANTIDAD FACTURADA
If TmpDT.SUM("CantidadFacturadaRem") > 0 Then
GvPS.Columns(6).Visible = True
ThCantidadFacturadaRem.Visible = True
ThCantidadFacturadaRem2.Visible = True
Else
GvPS.Columns(6).Visible = False
ThCantidadFacturadaRem.Visible = False
ThCantidadFacturadaRem2.Visible = False
End If
'ACTIVA EDITAR
'SOLO LA PUEDE EDITAR CON PROCESO | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR
If UsuarioActual.TienePermisoProceso(202) And TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then
BtnPermisoEditarRemision.Visible = True
End If
'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR
If TmpDT.SUM("CantidadFacturadaRem") < TmpDT.SUM("Cantidad") Then
BtnsFacturar.Visible = True
'ACTIVA CONVERSION DE MONEDA
If DdlMoneda.SelectedValue.ToEntero = 1 Then
TrConversionDolares.Visible = True
ChkConvertirDolares.Enabled = True
TxtTipoCambioDlls.Enabled = True
Else
TrConversionTipoCambio.Visible = True
ChkConvertirDoctoPesos.Enabled = True
TxtTipoCambio.Enabled = True
End If
End If
End If
If DbRowVenta("TipoDocto").ToString.Contiene("Cot", "Pd2") Then
'CANTIDAD FACTURADA
If TmpDT.SUM("CantidadFacturadaCot") > 0 Then
GvPS.Columns(7).Visible = True
ThCantidadFacturada.Visible = True
ThCantidadFacturada2.Visible = True
Else
GvPS.Columns(7).Visible = False
ThCantidadFacturada.Visible = False
ThCantidadFacturada2.Visible = False
End If
'ACTIVA EDITAR
'SOLO LA PUEDE EDITAR USUATIOACTUAL-VENDEDOR | NO DEBE ESTAR FACTURADA
If (UsuarioActual.CveUsuario = DbRowVenta("CveUsuario").ToString.ToEntero Or UsuarioActual.CveVendedor = DdlVendedor.SelectedValue.ToEntero) And TmpDT.SUM("CantidadFacturadaCot") = 0 Then 'And TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad")
BtnPermisoEditarCotizacion.Visible = True
End If
'ACTIVA BOTONERA | DEBE TENER CONCEPTOS PENDIENTES DE FACTURAR
If TmpDT.SUM("CantidadFacturadaCot") < TmpDT.SUM("Cantidad") AndAlso DdlTipoComprobante.SelectedValue.Contiene("Cot") Then
BtnGenerarRemision.Visible = If(CveEstatus = 10, False, True)
BtnsFacturar.Visible = True
End If
End If
UpPS.Update()
UpContado.Update()
UpEstatus.Update()
Retorno = True
Else
CveVenta = -1
Alert("El documento solicitado no existe, favor de revisar su búsqueda.", TipoMensaje.MsgAdvertencia)
End If
End If
ObjVentas.Dispose()
Return Retorno
End Function
Private Sub CargaTiposDocumentos()
DdlTipoComprobante.DataSource = GlobalDTTiposDocumentos()
DdlTipoComprobante.DataBind()
End Sub
Private Sub CargaNuevaFactura(OVenta As ClsVentas)
Dim ObjVentas As ClsVentas
If OVenta IsNot Nothing Then
ObjVentas = OVenta
Else
ObjVentas = New ClsVentas()
End If
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then
Dim drv As DataRow = ObjVentas.DtResultados.Rows(0)
'CargaCliente
Dim CveCliente As Integer = drv("CveCliente").ToString.ToEntero
HdnCveCliente.Value = CveCliente.ToString
ViewState("CveCliente") = CveCliente
CargaCliente(CveCliente)
'Carga Detalle Sucursal
TxtFechaEjecucion.Text = drv("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy")
TxtFechaPago.Text = drv("FechaVencimiento").ToString.ToDateTime.ToString("dd/MM/yyyy")
'DdlSucursalEjecucion.SelectedValueExist(drv("CveSucursalEjecucion").ToString)
'DdlSucursalCobranza.SelectedValueExist(drv("CveSucursalCobranza").ToString)
DdlSucursalCliente.SelectedValueExist(drv("CveClienteSucursal").ToString)
'DdlSucursal.SelectedValueExist(drv("CveSucursal").ToString)
DdlSubProyectoDatos.SelectedValueExist(drv("CveSubProyecto").ToString)
DdlSubProyectoEjecucion.SelectedValueExist(drv("CveSubProyectoEjecucion").ToString)
DdlSubProyectoCobranza.SelectedValueExist(drv("CveSubProyectoCobranza").ToString)
If CveDevolucion > 0 Then
CambiaSucursalGeneral()
End If
CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero)
'CargaDetalle
If ObjVentas.GetVentaDetalle(CveVenta) Then
TmpDT = ObjVentas.DtResultados
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
'TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal))
GvPS.DataSource = ObjVentas.DtResultados
GvPS.DataBind()
End If
'CARGA IMPUESTOS LOCALES
If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
TrOtros.Visible = True
TmpDTImpuestos = ObjVentas.DtResultados
GvImpuestosLocales2.DataSource = ObjVentas.DtResultados
GvImpuestosLocales2.DataBind()
GvImpuestosLocales2.Enabled = False
GvImpuestosLocales2.Visible = True
End If
End If
'Carga Totales
ViewState("TipoDoctoDevolucion") = drv("TipoDocto").ToString
TxtSubTotal.Text = drv("SubTotal").ToString.FormatoNumero(2)
LblDescuentos.Text = drv("Descuento").ToString.FormatoNumero(2)
LblAmortizacion.Text = drv("Amortizacion").ToString.FormatoNumero(2)
TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2)
TxtIVA.Text = drv("IVA").ToString.FormatoNumero(2)
TxtRetIVA.Text = drv("RetIVA").ToString.FormatoNumero(2)
TxtRetISR.Text = drv("RetISR").ToString.FormatoNumero(2)
TxtTotal.Text = drv("Total").ToString.FormatoNumero(2)
TotalOriginal = Math.Round(drv("Total").ToString.ToDouble, 2)
HdnVentaSaldo.Value = drv("Total").ToString
TxtMotivoDescuento.Text = drv("MotivoDescuento").ToString
TxtObsFact.Text = drv("Observaciones").ToString
DdlMoneda.SelectedValue = drv("CveMoneda").ToString
CambiaMoneda()
TxtTipoCambio.Text = drv("TipoCambio").ToString
DdlVendedor.SelectedValue = drv("CveVendedor").ToString
CvePAC = drv("CvePAC").ToString.ToEntero
DdlUsoCFDI.SelectedValueExist(drv("CveUsoCFDI").ToString)
DdlMetodoPago33.SelectedValueExist(drv("CveMetodoPago33").ToString)
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
DdlFormaPago33.SelectedValueExist(drv("CveFormaPago33").ToString)
DdlTipoComprobante.SelectedValueExist(drv("TipoDocto").ToString)
DdlTipoComprobante.Enabled = False
HdnIVAOriginal.Value = TxtIVA.Text
HdnAmortizacion.Value = LblAmort.Text.ToDouble.ToString
HdnSubTotalDescuestos.Value = (TxtSubTotal.Text.Replace(",", "").ToDouble - LblDescuentos.Text.Replace(",", "").ToDouble - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble - TxtRetISR.Text.Replace(",", "").ToDouble).FormatoNumero(2)
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
CveContrato = drv("CveContrato").ToString.ToEntero
TabAlmacen.Enabled = False
TabDetalleVentas.Enabled = False
TabComplementos.Enabled = False
'HplDownPDF.Visible = True
'HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}", CveVenta)))
Updatetabs.Update()
UpPS.Update()
UpContado.Update()
If CveDevolucion > 0 Then
HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString
'CALCULA IMPUESTOS LOCALES CON LOS DATOS DEL CLIENTE AL MOMENTO DE LA NUEVA FACTURA NO LA VIEJA
'CalculaTotalesImpuestosLocales()
'CalculaTotales(CBool(ViewState("RetIVAFletes")))
CalculaTotalesVenta() ' al hacer una refacturación que regenere los importes, sino vienen correctos
''CARGA IMPUESTOS LOCALES DE LA VENTA ANTERIOR
'If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then
' If ObjVentas.DtResultados.Rows.Count > 0 Then
' GvImpuestosLocales2.DataSource = ObjVentas.DtResultados
' GvImpuestosLocales2.DataBind()
' GvImpuestosLocales2.Enabled = False
' GvImpuestosLocales2.Visible = True
' End If
'End If
'cuando es refacturacion, la fecha de pago debe de ser la misma
If UsuarioActual.Empresa.Funcionalidad(526) = "1" Then
' Dim ObjVenta As New ClsVentas
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
TxtFechaPago.Text = ObjVentas.DtResultados(0)("FechaVencimiento").ToString.ToDate.ToShortDateString
End If
End If
'ObjVenta.Dispose()
Else
TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString
End If
CreaObjetosVentaDevolucion()
End If
TabComplementos.Enabled = True
End If
End If
If OVenta Is Nothing Then
ObjVentas.Dispose()
End If
End Sub
Private Sub CargaSucursales()
If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.Enabled = False : DdlSubProyectoEjecucion.Enabled = False : DdlSubProyectoCobranza.Enabled = False
End Sub
Private Sub CargaMetodosPago()
'FACTURACION 3.3
DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago
DdlMetodoPago33.DataBind()
DdlMetodoPago33.SelectedValue = "3"
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
'End If
End Sub
Private Sub CargaFormaPago(CveMetodoPago As Integer)
'FACTURACION 3.3
Dim dtt As DataTable = Nothing
If CveMetodoPago > 0 Then
dtt = GlobalDTVtaFormaPago.FiltraParametros(If(CveMetodoPago = 1, " CveFormaPago <> 20 ", "CveFormaPago = 20"))
Else
dtt = GlobalDTVtaFormaPago
End If
DdlFormaPago33.Items.Clear()
'DdlFormaPago33.ClearSelection()
'DdlFormaPago33.DataBind()
DdlFormaPago33.DataSource = dtt
DdlFormaPago33.SelectedValue = dtt.FiltroPrimeroValor("CveFormaPago", "")
DdlFormaPago33.DataBind()
'End If
End Sub
Private Sub CargaUsoCFDI()
DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica)
DdlUsoCFDI.DataBind()
End Sub
Private Sub CargaTiposRelacion()
DdlTiposRelacion.DataSource = GlobalDTVtaTiposRelacion
DdlTiposRelacion.DataBind()
DdlTiposRelacion.Items.Insert(0, New ListItem("-", "-1"))
End Sub
Private Sub CargaFormaEntrega()
TrFormaEntrega.Visible = True
DdlFormaEntrega.DataSource = GlobalDTVtaCondicionesEntrega(UsuarioActual.CveEmpresa)
DdlFormaEntrega.DataBind()
DdlFormaEntrega.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub CargaMonedas()
DdlMoneda.DataSource = GlobalDTMonedas
DdlMoneda.DataBind()
End Sub
Private Sub CargaProyecto()
Dim CveSubProyecto As Integer = 0
Dim dtt As DataTable = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1)
DdlProyecto.DataSource = dtt
DdlProyecto.DataBind()
DdlProyectoPyME.DataSource = dtt
DdlProyectoPyME.DataBind()
CveSubProyecto = GetSubProyectoSucursal()
CargaSubProyecto(CveSubProyecto)
End Sub
Private Function GetSubProyectoSucursal() As Integer
Dim Retorno As Integer = 0
Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}")
'Dim dr As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero($"CveSubProyecto = {If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)}")
'si hay un proyecto relacionado con el subproyecto
If dr IsNot Nothing AndAlso dr("CveSubProyecto").ToString.ToEntero > 0 Then
DdlProyecto.SelectedValueExist(dr("CveProyecto"))
Retorno = dr("CveSubProyecto").ToString.ToEntero
End If
Return Retorno
End Function
Private Sub CargarAlmacenes()
If CveVenta > 0 Then
DivAlmacen.Visible = False
Else
ddlAlmacen.Items.Clear()
ddlAlmacen.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}")
ddlAlmacen.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
ddlAlmacen.SelectedValue = "-1"
ddlAlmacen.DataBind()
If GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").Rows.Count > 0 Then
ddlAlmacen.SelectedValueExist(UsuarioActual.CveAlmacen)
End If
End If
'SI TIENE CONTRATO NO SE MUEVE
If Not CveContrato > 0 Then
DdlAlmacenAsignado.Items.Clear()
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (4,10)")
DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
DdlAlmacenAsignado.SelectedValue = "-1"
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").ToString.ToEntero)
End If
If CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}")
DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
DdlAlmacenAsignado.SelectedValue = "-1"
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString.ToEntero)
End If
UpINV.Update()
End Sub
Private Sub CargaSubProyecto(Optional CveSubProyecto As Integer = -1)
DdlSubProyecto.Items.Clear()
DdlSubProyecto.SelectedValue = Nothing
If DdlProyecto.SelectedValue.ToEntero > 0 Then
DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1)
'DdlSubProyecto.DataSource = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("", "", {"CveSubProyecto", "SubProyecto"})
End If
DdlSubProyecto.DataBind()
DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1"))
If CveSubProyecto > 0 Then DdlSubProyecto.SelectedValueExist(CveSubProyecto)
End Sub
Private Sub CargaEmpresaCRM(CveEmpresaCRM As Integer)
Dim ObjCRM As New ClsCRM
If ObjCRM.GetEmpresasCRM(UsuarioActual.CveEmpresa, CveEmpresaCRM) Then
If ObjCRM.DtResultados.Rows.Count > 0 Then
ViewState("CveCliente") = IIf(ObjCRM.DtResultados.Rows(0)("CveCliente").ToString().ToEntero() > 0, ObjCRM.DtResultados.Rows(0)("CveCliente"), -1)
HdnCveCliente.Value = CveCliente.ToString()
If (CveCliente > 0) Then
CargaCliente(CveCliente)
VerificarContrato(True)
'DESACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto disabled")
TxtCodigo.ReadOnly = True
UpCliente.Visible = True
UpEmpresaCRM.Visible = False
Else
LblEmpresaCRM.Text = ObjCRM.DtResultados.Rows(0)("Empresa").ToString
LblRFCCRM.Text = ObjCRM.DtResultados.Rows(0)("RFC").ToString
LblMedioCaptacionCRM.Text = ObjCRM.DtResultados.Rows(0)("MedioCaptacion").ToString
ChkEnviarFactura.Checked = False
ChkEnviarFactura.Visible = False
LblEnviarMail.Visible = False
UPCondicionesPago.Visible = True
UpCliente.Visible = False
UpEmpresaCRM.Visible = True
End If
DdlVendedor.SelectedValueExist(ObjCRM.DtResultados.Rows(0)("CveVendedorAsignado").ToString)
DdlVendedor.Enabled = False
LbAgregar.Enabled = True
End If
End If
ObjCRM.Dispose()
End Sub
Private Sub CargaCliente(CveCliente As Integer, Optional Estatus As Integer = -1)
RBLPago.Items(0).Enabled = True
Dim ObjCliente As New ClsClientes()
If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus, TipoCliente:=-1) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
TxtCodigo.Text = ObjCliente.Codigo
DdlFormaEntrega.SelectedValueExist(ObjCliente.DtResultados(0)("CveCondicionEntrega").ToString)
LblCliente.Text = String.Format("<a Class=""Texto"" href=""/Ventas/Clientes.aspx?CveCliente={0}"">{1}</a>", CveCliente, ObjCliente.Nombre)
ViewState("NombreCliente") = ObjCliente.Nombre
LtlCliente.Text = ObjCliente.Nombre
ViewState("RequiereOC") = ObjCliente.RequiereOC
EnviarCorreoCliente = ObjCliente.EnviarFactura
EstatusCliente = ObjCliente.Estatus
ClienteEsDistribuidor = Boolean.Parse(ObjCliente.DtResultados.Rows(0)("EsDistribuidor").ToString)
If EstatusCliente = False And Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") And (CveVenta <= 0 Or EsCreaApartirDe) Then
Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia)
End If
'CUANDO SEA COTIZACION Y SEA COMPUPROVEEDORES (EMPRESA 72) NO DEBE ENVIAR CORREO AL CLIENTE
If UsuarioActual.CveEmpresa = 72 AndAlso DdlTipoComprobante.SelectedValue = "Cot" Then
ChkEnviarFactura.Checked = False
ChkEnviarFactura.Visible = False
LblEnviarMail.Visible = False
Else
ChkEnviarFactura.Visible = True
ChkEnviarFactura.Checked = EnviarCorreoCliente
LblEnviarMail.Visible = True
End If
ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail)
ViewState("MailCC") = ObjCliente.NotificarA
LblDireccion.Text = ObjCliente.Direccion
LblColonia.Text = ObjCliente.Colonia
LblCiudad.Text = ObjCliente.Ciudad
LblEstado.Text = ObjCliente.Estado
LblCP.Text = ObjCliente.CP
LblRFC.Text = ObjCliente.RFC
LblTelefono.Text = ObjCliente.Telefono
LblRetIVA.Text = ObjCliente.RetIVA.ToString.FormatoNumero(5)
LblRetISR.Text = ObjCliente.RetISR.ToString.FormatoNumero(5)
ViewState("ClienteRetIVA") = ObjCliente.RetIVA / 100
ViewState("ClienteRetISR") = ObjCliente.RetISR / 100
ViewState("RetIVAFletes") = ObjCliente.RetieneIVAFletes
If ObjCliente.RetieneIVAFletes Then
TrRetIVA.Style.Add("display", "")
UsuarioActual.Empresa.MostrarRetIVA = True
End If
ViewState("Vendedor") = ObjCliente.Vendedor
ViewState("CtaContable") = ObjCliente.CuentaContable
ViewState("IdCtaContClientes") = ObjCliente.IdCtaContClientes
ViewState("CveCuentaClientes") = ObjCliente.CveCuentaClientes
ViewState("IdCtaContMonedaExtranjera") = ObjCliente.IdCtaContMonedaExtranjera
ViewState("IdCtaContComplementaria") = ObjCliente.IdCtaContComplementaria
ViewState("IdCtaContAnticipos") = ObjCliente.IdCtaContAnticipos
ViewState("CveCuentaAnticipos") = ObjCliente.CveCuentaAnticipos
ViewState("IdCtaContRetIVA") = ObjCliente.IdCtaContRetIVA
ViewState("CveCuentaRetIVA") = ObjCliente.CveCuentaRetIVA
ViewState("IdCtaContRetISR") = ObjCliente.IdCtaContRetISR
ViewState("CveCuentaRetISR") = ObjCliente.CveCuentaRetISR
ViewState("CodCliente") = ObjCliente.Codigo
ViewState("CliNoExt") = ObjCliente.NoExt
ViewState("CliNoInt") = ObjCliente.NoInt
ViewState("CliLocalidad") = If(ObjCliente.Localidad.Trim.Length = 0, ObjCliente.Ciudad.Trim, ObjCliente.Localidad.Trim)
ViewState("CliPais") = ObjCliente.Pais
ImprimeNombreSucursal = ObjCliente.ImprimeNombreSucursal
'ViewState("NumCtaPago") = ObjCliente.NumCtaPago
ViewState("ClienteDesglosaIEPS") = ObjCliente.DesglosaIEPS
If Not ClienteDesglosaIEPS Then
DivClienteMsg.Visible = True
LtlClienteMsg.Text = "Cálculo sin desglose de IEPS"
End If
Dim dr As DataRow = Nothing
dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal = 1 And Estatus = 'Activo' AND CveEmpresa = " & UsuarioActual.CveEmpresa)
If dr IsNot Nothing Then
ViewState("MatCalle") = dr("Calle")
ViewState("MatNoExt") = dr("NoExt")
ViewState("MatNoInt") = dr("NoInt")
ViewState("MatColonia") = dr("Colonia")
ViewState("MatLocalidad") = dr("Localidad")
ViewState("MatMunicipio") = dr("Municipio")
ViewState("MatEstado") = dr("Estado")
ViewState("MatPais") = dr("Pais")
ViewState("MatCP") = dr("CP")
End If
'HABILITA LA OPCION DE DIRECCION DE ENVIO
If UsuarioActual.CveEmpresa.Contiene(1, 72, 119) Then
trDireccionEnvio.Visible = True
CargaDireccionesEnvio()
End If
If CveCliente = 239903 AndAlso UsuarioActual.CveEmpresa = 119 Then
DdlMetodoPago33.Enabled = False
ObjCliente.CveMetodoPago = 1 ' PUE, y que no se pueda modificar
Else
DdlMetodoPago33.Enabled = True
End If
If CveVenta <= 0 Or EsCreaApartirDe Or NuevaFactura = 1 Then
CveMetodoPagoCliente = ObjCliente.CveMetodoPago
DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33)
CambiaMetodoPago33()
DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33)
DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI)
End If
PlazoCobranza = ObjCliente.PlazoCobranza
PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then
TxtFechaPago.ReadOnly = True
Calendario.Enabled = False
imgCalendario.Visible = False
End If
'funcionalidad EnviarSMSTimbrado
If CveVenta <= 0 And UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue = "Ing" Then
If ObjCliente.CobranzaTelefono <> "" Then
LblMensaje.Text = $"Se enviará mensaje SMS a {ObjCliente.CobranzaTelefono}"
Else
LblMensaje.Text = $"El Cliente no tiene teléfono para envío SMS "
End If
LblMensaje.Visible = True
End If
'If Not ObjCliente.RFC = "XAXX010101000" Then
' TxtNumCtaPago.Text = ObjCliente.NumCtaPago
'End If
'Complementos
'COMERCIO EXTERIOR
ViewState("AplicaComercioExterior") = ObjCliente.AplicaComercioExterior
ViewState("CveTipoOperacion") = ObjCliente.CveTipoOperacion
ViewState("CvePedimento") = ObjCliente.CvePedimento
ViewState("CveIncoterm") = ObjCliente.CveIncoterm
LblTipoOperacion.Text = ObjCliente.ClaveSATTipoOperacionDescripcion
LblClavePedimento.Text = ObjCliente.ClaveSATPedimentoDescripcion
If ObjCliente.AplicaComercioExterior Then
DdlSATMotivoTraslado.DataSource = GlobalDTSATMotivoTraslado
DdlSATMotivoTraslado.DataBind()
DdlSATMotivoTraslado.SelectedValueExist(ObjCliente.CveMotivoTraslado)
DdlIncoterm.Items.Clear()
DdlIncoterm.DataSource = GlobalDTIncoterm()
DdlIncoterm.DataBind()
DdlIncoterm.SelectedValueExist(ObjCliente.CveIncoterm)
CargaPais()
DdlComExtPais.SelectedValueExist(ObjCliente.CvePais)
CargaEstado()
DdlComExtEstado.SelectedValueExist(ObjCliente.CveEstado)
If ObjCliente.ClaveSATPais = "MEX" Then
CargaMunicipio()
CargaColonia()
Else
If ObjCliente.ClaveSATPais.Contiene("USA", "CAN") Then
DdlComExtEstado.Visible = True
Else
TxtComExtEstado.Visible = True : DdlComExtEstado.Visible = False
End If
TxtComExtMunicipio.Text = ObjCliente.ComExtMunicipio
TxtComExtColonia.Text = ObjCliente.ComExtColonia
TxtComExtMunicipio.Visible = True : TxtComExtColonia.Visible = True
End If
TxtNumRegIdTrib.Text = ObjCliente.NumRegIdTrib
TxtDestinatarioNombre.Text = ObjCliente.Nombre
TxtComExtCalle.Text = ObjCliente.Direccion
TxtComExtNumero.Text = ObjCliente.NoExt
TxtComExtCP.Text = ObjCliente.CP
End If
'FEMSA
ViewState("AplicaFEMSA") = ObjCliente.AplicaFEMSA
TxtFEMSA_NumSociedad.Text = ObjCliente.FEMSA_NumSociedad
TxtFEMSA_NumProveedor.Text = ObjCliente.FEMSA_NumProveedor
TxtFEMSA_Mail.Text = ObjCliente.FEMSA_Mail
'DETALLISTA
ViewState("AplicaDetallista") = ObjCliente.AplicaDetallista
TxtDet_GLNComprador.Text = ObjCliente.Detallista_GLNComprador
TxtDet_Departamento.Text = ObjCliente.Detallista_Departamento
TxtDet_GLNVendedor.Text = ObjCliente.Detallista_GLNVendedor
TxtDet_NumProv.Text = ObjCliente.Detallista_NumProveedor
Txt7ElevenNumProveedor.Text = ObjCliente.SevenEleven_NumProveedor.Trim
ViewState("AplicaFord") = ObjCliente.AplicaFord
TxtFordGSDB.Text = ObjCliente.Ford_GSDB
'SELECIONAMOS VENDEDOR - SI ESTA EN MODO EDICIÓN SE QUEDA EL VENDEDOR ORIGINAL
If Not ModalidadEdicion Then
If ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero > 0 Then
DdlVendedor.SelectedValueExist(ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero)
End If
'SI EL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO
If Not DdlVendedor.SelectedValue.ToEntero > 0 Then
DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString)
End If
End If
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
UpFacturar.Update()
'SI LA VENTA YA ESTA REGISTRADA NO DEBE HABILITAR ACCIONES
If CveVenta <= 0 Then
LnkRemisiones.Visible = If(UsuarioActual.TienePermisoProceso(199), True, False) : LnkOCs.Visible = True : LnkCotizaciones.Visible = True : LnkPedido2SinFacturar.Visible = True : InicializaAplicarNCMasiva()
End If
If UsuarioActual.Empresa.CvePlataforma = 2 Then LnkOCs.Visible = False
If UsuarioActual.Empresa.UsaInventarios Then
RblTipo.Items.Remove(RblTipo.Items.FindByValue("1"))
RblTipo.Items.Remove(RblTipo.Items.FindByValue("2"))
End If
UpnTools.Update()
'UpRemisionesFacturas.Update()
If Not CveVenta > 0 Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
If UsuarioActual.TienePermisoProceso(152) Then
DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto)
DdlSubProyectoDatos.Enabled = False
Else
DdlSubProyectoDatos.SelectedValueExist(ObjCliente.CveSubProyecto)
End If
'RECARGA LOS VALORES DE LA SUCURSAL
CambiaSucursal()
UpParametros.Update()
End If
End If
DdlSucursalCliente.Items.Clear()
If ObjCliente.GetSucursales(CveCliente) Then
DdlSucursalCliente.DataSource = ObjCliente.DtResultados
If ObjCliente.DtResultados.Rows.Count > 0 Then
trsucursalciente.Visible = True
Else
trsucursalciente.Visible = False
End If
Else
trsucursalciente.Visible = False
DdlSucursalCliente.DataSource = Nothing
End If
DdlSucursalCliente.Items.Insert(0, New ListItem("Matriz", "-1"))
DdlSucursalCliente.DataBind()
'CargaFolios()
CargaDatosEstimaciones(CveCliente)
If ObjCliente.GetClienteImpuestosLocales(CveCliente) Then
'se cargan impuestos locales
Dim DtClienteImpuesto As DataTable = ObjCliente.DtResultados.FiltraParametros("Seleccionado = 1", "Orden")
If DtClienteImpuesto IsNot Nothing AndAlso DtClienteImpuesto.Rows.Count > 0 Then
' If TmpDTImpuestos Is Nothing Then CreaDTImpuestos() Else TmpDTImpuestos.Rows.Clear()
TmpDTImpuestos = DtClienteImpuesto
GvImpuestosLocales2.DataSource = TmpDTImpuestos
GvImpuestosLocales2.DataBind()
If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then
TrOtros.Visible = True
GvImpuestosLocales2.Visible = True
TrOtros.Style.Add("display", "")
Else
TrOtros.Visible = False
GvImpuestosLocales2.Visible = False
End If
DtClienteImpuesto.Dispose()
End If
UpImpuestos.Update()
End If
If DdlTipoComprobante.SelectedValue.Contiene("Cot") Then
TrAtencionA.Visible = True
TrDireccion.Visible = False
TrCiudad.Visible = False
TrRFC.Visible = False
tdTelefonoGen.Visible = False
tdTxtTelefonoGen.Visible = False
ElseIf ObjCliente.RFC = "XAXX010101000" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ret") Then
TrAtencionA.Visible = True
TrDireccion.Visible = False
TrCiudad.Visible = False
TrRFC.Visible = False
tdTelefonoGen.Visible = True
tdTxtTelefonoGen.Visible = True
Else
'TrAtencionA.Visible = False
TrDireccion.Visible = True
TrCiudad.Visible = True
TrRFC.Visible = True
tdTelefonoGen.Visible = False
tdTxtTelefonoGen.Visible = False
TxtAtencionA.Text = ""
TxtTelefonoGenerico.Text = ""
End If
TrAtencionA.Visible = True
tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
LbAgregar.Enabled = True
LnkAgregarPyME.Enabled = True
CargarAlmacenes()
CargaDocumentacionCliente()
If UsuarioActual.CveEmpresa.Contiene(72, 80, 1, 119) Then
BtnEmitirImprimir.OnClientClick = $"ValidaGuardar({ If(ImprimeNombreSucursal = True, 1, 0)});"
BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation")
BtnEmitirImprimir.Attributes.Add("data-popout", "true")
BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar")
BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar")
BtnEmitirImprimir.Attributes.Add("data-html", "true")
End If
'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO
If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO
BtnEmitirImprimir.Visible = True
TrVistaPrevia.Visible = True
'Else
' BtnEmitirImprimir.Visible = EstatusCliente
' TrVistaPrevia.Visible = EstatusCliente
End If
TrVistaPrevia.Visible = True
If Not (ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem") Then
CargaRestriccionesCreditoCliente(True)
End If
UpFacturar.Update()
UpEstatus.Update()
UpPS.Update()
UpParametros.Update()
UPCondicionesPago.Update()
UpDetalle.Update()
UpComplementos.Update()
UpCliente.Update()
UpAplicarNC.Update()
UpINV.Update()
UPPVentas.Update()
UPComplementosSAT.Update()
UpnTools.Update()
Else
Alert("Ocurrió un error al cargar los datos del cliente. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
End If
ObjCliente.Dispose()
If CveCliente > 0 Then CargaAnticipos(CveCliente) : UpAnticipos.Update()
If RequiereOC Then
Dim Documentacion As String = ""
'RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });", "ModalArchivos")
Dim Count = 0
For Each GvRow As GridViewRow In GvDocumentosCliente.Rows
If GvRow.DataKey("Orden").ToEntero = 1 Then
IndexDocumentoCliente = Count
Documentacion = GvRow.DataKey("Documentacion").ToString
AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString
Exit For
End If
Count = +1
Next
LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion
BtnModalClienteDocumentoCancelar.Visible = False
If CveVenta <= 0 Then
LnkUploadDocumentacionCliente.Visible = True
End If
UpModalTitleUploadDocumentoCliente.Update()
UpModalButtonUploadDocumentoCliente.Update()
UPObservaciones.Update()
' RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});", "modalOC")
End If
End Sub
Private Sub CargaRestriccionesCreditoCliente(Optional Alertas As Boolean = False)
Dim ObjCliente As New ClsClientes()
If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
If UsuarioActual.CveEmpresa.Contiene(72, 119) AndAlso ObjCliente.DtResultados.Rows(0)("PermiteCredito").ToString = "False" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") AndAlso CveVenta < 1 Then
RBLPago.SelectedValue = "2"
RBLPago.Items(0).Enabled = False
RBLPago_SelectedIndexChanged(Nothing, Nothing)
If UsuarioActual.CveEmpresa.Contiene(119) AndAlso Not UsuarioActual.TienePermisoProceso(268) Then
DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización")
DdlTipoComprobante.SelectedValue = "PA"
TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString
'si llegó por la opción de cotización no debe de restringuir
If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot"
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem"))
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
End If
UPCondicionesPago.Update()
ElseIf UsuarioActual.CveEmpresa.Contiene(72, 119) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "Cot", "PA") AndAlso CveVenta < 1 Then
RBLPago.SelectedValue = "1"
RBLPago_SelectedIndexChanged(Nothing, Nothing)
UPCondicionesPago.Update()
Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero)
If CreditoDispo > 0 Then
TrCreditoDisponible.Visible = True
LblCreditoDisponible.Text = CreditoDispo.FormatoNumero
If PorcentajeCredito > 80 Then TrPorcentajeCredito.Visible = True : LblPorcentajeCredito.Text = $"{PorcentajeCredito.FormatoNumero}%"
If UsuarioActual.CveEmpresa = 119 AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem", "PA") Then
If LblRFC.Text.Trim <> "XAXX010101000" Then
Dim Vta As New ClsVentas
Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa)
Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón: <br> <br> {0}", Vta.SerieVenta)
Vta.Dispose()
If Opcion > 0 Then
'si la cotización no debe de existir este canddado
If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia)
'RBLPago.SelectedValue = "2"
'RBLPago.Items(0).Enabled = False
RBLPago_SelectedIndexChanged(Nothing, Nothing)
UPCondicionesPago.Update()
DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización")
DdlTipoComprobante.SelectedValue = "PA"
TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString
'si llegó por la opción de cotización no debe de restringuir
If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot"
'quito remisión y factura
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem"))
If Opcion = 1 Then
BtnEmitirImprimir.Visible = False
BtnsFacturar.Visible = False
BtnGenerarRemision.Visible = False
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
LnkOCs.Visible = False
End If
Else
' el cliente tiene crédito disponible, no tiene bloqueo
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("PA"))
If UsuarioActual.TienePermisoProceso(60) Then DdlTipoComprobante.SelectedValueExistInsert("Ing", "Ingresos") 'puede facturar
If UsuarioActual.TienePermisoProceso(199) Then DdlTipoComprobante.SelectedValueExistInsert("Rem", "Remisión") ' puede remisionar
DdlTipoComprobante.SelectedValueExist(UsuarioActual.CveTipoDocumento)
TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString
End If
Else
'que no de crédito, solo contado
RBLPago.SelectedValue = "2"
RBLPago.Items(0).Enabled = False
End If
End If
Else
If UsuarioActual.CveEmpresa = 119 AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "Ant", "PA") Then
Dim Vta As New ClsVentas
Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa)
Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón: <br> <br> {0}", Vta.SerieVenta)
Vta.Dispose()
If Opcion > 0 Then
If Opcion = 1 Then
BtnEmitirImprimir.Visible = False
End If
If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia)
Else
If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia)
End If
'RBLPago.SelectedValue = "2"
'RBLPago.Items(0).Enabled = False
RBLPago_SelectedIndexChanged(Nothing, Nothing)
UPCondicionesPago.Update()
DdlTipoComprobante.SelectedValueExistInsert("PA", "Autorización")
DdlTipoComprobante.SelectedValue = "PA"
TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString
'si llegó por la opción de cotización no debe de restringuir
If IfNull(Request("Op"), "").ToString = "Cot" Then DdlTipoComprobante.SelectedValue = "Cot"
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem"))
BtnsFacturar.Visible = False
BtnGenerarRemision.Visible = False
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
LnkOCs.Visible = False
End If
End If
UPPCreditoDisponible.Update()
ElseIf UsuarioActual.CveEmpresa.Contiene(119, 1) AndAlso Not UsuarioActual.TienePermisoProceso(268) AndAlso CveVenta > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Pd2", "Cot") Or (DdlTipoComprobante.SelectedValue = "Rem" And ModalidadEdicion And ViewState("CveClienteAnterior").ToString.ToEntero > 0 And LblRFC.Text.Trim <> "XAXX010101000")) Then
Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero)
If CreditoDispo > 0 Then
Dim Vta As New ClsVentas
Dim Opcion As Integer = Vta.ObtenerClienteLimitesVenta(CveCliente, UsuarioActual.CveEmpresa)
Dim OpcionMsg As String = String.Format("El Cliente se encuentra bloqueado por la siguiente razón: <br> <br> {0}", Vta.SerieVenta)
Vta.Dispose()
If Opcion > 0 Then
If ModalidadEdicion AndAlso ViewState("CveCliente").ToString.ToEntero <> ViewState("CveClienteAnterior").ToString.ToEntero And DdlTipoComprobante.SelectedValue = "Rem" And ViewState("CveClienteAnterior").ToString.ToEntero > 0 And LblRFC.Text.Trim <> "XAXX010101000" Then
ViewState("CveCliente") = ViewState("CveClienteAnterior").ToString.ToEntero
ObjCliente.Dispose()
CargaCliente(ViewState("CveCliente").ToString.ToEntero)
If Opcion > 0 Then
If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia)
Else
If Alertas Then Alert("El cliente tiene su límite de crédito agotado.", TipoMensaje.MsgAdvertencia)
End If
BtnEmitirImprimir.Visible = False
BtnVistaPrevia.Visible = False
UpFacturar.Update()
Exit Sub
ElseIf DdlTipoComprobante.SelectedValue.Contiene("Cot") AndAlso EsCreaApartirDe Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Pd2"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs"))
BtnGenerarRemision.Visible = False
BtnGenerarOS.Visible = False
BtnEmitirImprimir.Visible = True
BtnsFacturar.Visible = False
Else
If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then
BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False)
End If
BtnGenerarRemision.Visible = False
BtnGenerarOS.Visible = False
BtnEmitirImprimir.Visible = False
BtnsFacturar.Visible = False
If ViewState("CveCliente").ToString.ToEntero <> ViewState("CveClienteAnterior").ToString.ToEntero Then
If Opcion > 0 Then
If Alertas Then Alert(OpcionMsg, TipoMensaje.MsgAdvertencia)
Else
If Alertas Then Alert("El cliente tiene límite de crédito agotado.", TipoMensaje.MsgAdvertencia)
End If
End If
End If
Else
BtnGeneraAutorizacion.Visible = False
If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then
BtnGenerarRemision.Visible = If(CveEstatus <> 21, True, False)
End If
End If
Else
BtnGenerarRemision.Visible = False
If DdlTipoComprobante.SelectedValue.Contiene("Pd2") Then
BtnGeneraAutorizacion.Visible = If(CveEstatus <> 21, True, False)
End If
End If
End If
End If
End If
ObjCliente.Dispose()
End Sub
Private Sub CargaClienteSucursal(CveClienteSuc As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing)
Dim ObjCliente As New ClsClientes
If CveClienteSuc > 0 Then
If ObjCliente.GetSucursales(CveCliente, CveClienteSuc) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
Dim Correo = ObjCliente.DtResultados.Rows(0)("Correo").ToString
If Correo.Trim.Length > 0 Then
ViewState("Mail") = Correo
End If
LblDireccion.Text = ObjCliente.DtResultados.Rows(0)("Direccion").ToString
LblColonia.Text = ObjCliente.DtResultados.Rows(0)("Colonia").ToString
LblCiudad.Text = ObjCliente.DtResultados.Rows(0)("Ciudad").ToString
LblEstado.Text = ObjCliente.DtResultados.Rows(0)("Estado").ToString
'TxtNumCtaPago.Text = ObjCliente.DtResultados.Rows(0)("NumCtaPago").ToString
LblTelefono.Text = ObjCliente.DtResultados.Rows(0)("Telefono").ToString
LblCP.Text = ObjCliente.DtResultados.Rows(0)("CP").ToString
ViewState("CliLocalidad") = ObjCliente.DtResultados.Rows(0)("Localidad").ToString
ViewState("CliPais") = ObjCliente.DtResultados.Rows(0)("Pais").ToString
ViewState("CliNoExt") = ObjCliente.DtResultados.Rows(0)("NoExt").ToString
ViewState("CliNoInt") = ObjCliente.DtResultados.Rows(0)("NoInt").ToString
DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString)
ViewState("CveClienteSucursal") = ObjCliente.DtResultados(0)("CveClienteSucursal").ToString
ViewState("CliCorreoCot") = ObjCliente.DtResultados.Rows(0)("CorreoCotizacion").ToString
If ObjCliente.DtResultados.Rows(0)("Estatus").ToString <> "Activo" Then
RBLPago.Items(0).Enabled = False
Alert("La Sucursal/Departamento del cliente se encuentra inactivo", TipoMensaje.MsgAdvertencia)
Else
RBLPago.Items(0).Enabled = True
Dim CreditoDispo As Decimal = CargaCreditoDisponible(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero, ObjVentas)
TrCreditoDisponible.Visible = True
LblCreditoDisponible.Text = CreditoDispo.FormatoNumero
UPPCreditoDisponible.Update()
UpParametros.Update()
End If
If CveVenta <= 0 Then
CveMetodoPagoCliente = ObjCliente.DtResultados.Rows(0)("CveMetodoPago").ToString.ToEntero
DdlMetodoPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago33").ToString)
DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty)
DdlFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString)
DdlUsoCFDI.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveUsoCFDI").ToString)
End If
If CveVenta < 0 Then TxtAtencionA.Text = ObjCliente.DtResultados.Rows(0)("Contacto").ToString
End If
Else
Alert("No se pudieron cargar los datos de la sucursal", TipoMensaje.MsgAdvertencia)
End If
Else
If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail)
LblDireccion.Text = ObjCliente.Direccion
LblColonia.Text = ObjCliente.Colonia
LblCiudad.Text = ObjCliente.Ciudad
LblEstado.Text = ObjCliente.Estado
LblCP.Text = ObjCliente.CP
LblTelefono.Text = ObjCliente.Telefono
DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString)
ViewState("CliNoExt") = ObjCliente.NoExt
ViewState("CliNoInt") = ObjCliente.NoInt
PlazoCobranza = ObjCliente.PlazoCobranza
If CveVenta <= 0 Then
CveMetodoPagoCliente = ObjCliente.CveMetodoPago
DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33)
DdlMetodoPago33_SelectedIndexChanged(DdlMetodoPago33, EventArgs.Empty)
DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33)
DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI)
End If
End If
End If
End If
'SI LA SUCURSAL DEL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO
If Not DdlVendedor.SelectedValue.ToEntero > 0 Then
DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString)
End If
UPPVentas.Update()
UpEstatus.Update()
UPCondicionesPago.Update()
ObjCliente.Dispose()
End Sub
Private Function CargaCreditoDisponible(tCveCliente As Integer, tCveSucursalCliente As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing) As Decimal
Dim Retorno As Decimal = 0
If UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then
Dim ObjVentasAplciar As ClsVentas = Nothing
If ObjVentas IsNot Nothing Then
ObjVentasAplciar = ObjVentas
Else
ObjVentasAplciar = New ClsVentas
End If
If ObjVentasAplciar.ObtenerCreditoRestante(tCveCliente, tCveSucursalCliente) Then
If ObjVentasAplciar.DtResultados.Rows.Count > 0 Then
If tCveSucursalCliente > 0 Then
Retorno = ObjVentasAplciar.DtResultados(0)("LimiteRestanteSucursal").ToString.ToDecimal
PorcentajeCredito = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoSucursal").ToString.ToDecimal
Else
Retorno = ObjVentasAplciar.DtResultados(0)("LimiteRestanteCliente").ToString.ToDecimal
PorcentajeCredito = ObjVentasAplciar.DtResultados(0)("PorcentajeSaldoCliente").ToString.ToDecimal
End If
End If
End If
If ObjVentas Is Nothing Then
ObjVentasAplciar.Dispose()
End If
End If
Return Retorno
End Function
Private Sub CargaDdlSubProyectos()
DdlSubProyectoDatos.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ")
DdlSubProyectoDatos.DataBind()
DdlSubProyectoCobranza.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ")
DdlSubProyectoCobranza.DataBind()
DdlSubProyectoEjecucion.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ")
DdlSubProyectoEjecucion.DataBind()
DdlSubProyectoPyME.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1)
DdlSubProyectoPyME.DataBind()
End Sub
Private Sub CargaClasificaciones()
If UsuarioActual.Empresa.UsaAC Then
DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
Else
DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("Estado = 1", Orderby:="Clasificacion")
DdlClasificacionPyME.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion")
End If
'DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa)
DdlClasificacion.DataBind()
DdlClasificacionPyME.DataBind()
End Sub
Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost)
Objeto.setEsWebService(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1")
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
Objeto.ddl.Items.Clear()
'Objeto.ddl.DataSource = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1)
Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, Estatus:=1, AplicaParaVenta:=1)
Objeto.ddl.DataBind()
Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2"))
Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1"))
Else
Objeto.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue)
Objeto.ddlWS.Attributes.Add("data-cveclasificacion", CveClasificacion.ToString)
Objeto.ddlWS.Attributes.Add("data-pagina", "ventas/ventas")
Objeto.ddlWS.Attributes.Add("data-Estatus", "1")
End If
End Sub
Private Sub CargaNC(pCveVenta As Integer)
If pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then
If IsNothing(Request("CveDevolucion")) AndAlso IsNumeric(Request("CveDevolucion")) Then
trNCFactura.Visible = True
End If
If DdlNCFactura.Items.Count = 0 Then
Dim ObjClientes As New ClsVentas()
If ObjClientes.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then
DTFacNC = ObjClientes.DtResultados
Dim drvv As DataRow = DTFacNC.FiltroPrimero("")
DTFacNC.Columns.Add("Factura", GetType(String), " Folio + ' - ' + Fecha + ' $' + Total")
HdnFolioFiscalNC.Value = drvv("FolioFiscal").ToString
If DTFacNC IsNot Nothing AndAlso DTFacNC.Rows.Count > 0 Then
Me.CveEstatusRefacturacion = DTFacNC.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero()
HdnRFCVenta.Value = DTFacNC.Rows(0)("ClienteRFC").ToString()
End If
Else
DTFacNC = Nothing
End If
ObjClientes.Dispose()
DdlNCFactura.DataSource = DTFacNC
DdlNCFactura.DataBind()
DdlNCFactura.SelectedValueExist(pCveVenta)
DdlNCFactura.Enabled = False
End If
Else
trNCFactura.Visible = False
End If
End Sub
Private Sub CargaCuentasTerminal()
DdlCuentasTerminal.Items.Clear()
DdlCuentaTerminalModal.Items.Clear()
DdlCuentasTerminal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"})
DdlCuentaTerminalModal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"})
DdlCuentasTerminal.DataBind()
DdlCuentaTerminalModal.DataBind()
DdlCuentasTerminal.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlCuentaTerminalModal.Items.Insert(0, New ListItem("Seleccione", "-1"))
UPTarjetaTermminal.Update()
UpCuentaTerminal.Update()
End Sub
Public Sub CargaDdlNCPS()
Dim CveSATNC = "84111506"
DdlNCPS.DataSource = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC
DdlNCPS.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlNCPS.DataBind()
DdlNCPSAnt.DataSource = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC
DdlNCPSAnt.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlNCPSAnt.DataBind()
End Sub
#End Region
#Region "G R I D V I E W S"
#Region "GvPS"
Protected Sub GvPS_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvPS.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("id") = e.Row.RowIndex.ToString
If e.Row.RowIndex = 0 Then
End If
If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then
'MODO EDICION
e.Row.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(e.Row.DBCampo("CvePS").ToEntero, -1)
e.Row.FCDropDownList("DdlUnidadMedida").DataBind()
e.Row.FCDropDownList("DdlUnidadMedida").SelectedValueExist(e.Row.DBCampo("CveUM"))
e.Row.FCDropDownList("DdlClasificacion").DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1)
e.Row.FCDropDownList("DdlClasificacion").DataBind()
e.Row.FCDropDownList("DdlClasificacion").SelectedValue = e.Row.DBCampo("CveClasificacion")
CargaPS(e.Row.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero, e.Row.FCDropDownLost("DdlPS"))
e.Row.FCDropDownLost("DdlPS").SelectedText = e.Row.DBCampo("PS")
e.Row.FCDropDownLost("DdlPS").SelectedValue = e.Row.DBCampo("CvePS")
If e.Row.DBCampo("CveSubProyecto") = "-1" Then
'cargo todos las opciones para
e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1)
e.Row.FCDropDownList("DdlProyecto").DataBind()
e.Row.FCDropDownList("DdlProyecto").Items.Insert(0, New ListItem("Sin Proyecto Asignado", "-1"))
e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, DdlProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, -1, 1)
'e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectos.FiltraParametros("CveEmpresa = " & UsuarioActual.CveEmpresa & " AND CveProyecto = '" & DdlProyecto.SelectedValue & "'")
e.Row.FCDropDownList("DdlSubProyecto").DataBind()
'e.Row.FCDropDownList("DdlSubProyectoEdit").SelectedValue = e.Row.DBCampo("CveSubProyecto")
e.Row.FCDropDownList("DdlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1"))
Else
Dim dr As DataRow = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, e.Row.DBCampo("CveSubProyecto").ToEntero, 1).FiltroPrimero("")
If dr IsNot Nothing Then
e.Row.FCDropDownList("DdlProyecto").DataSource = GlobalDTProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1)
e.Row.FCDropDownList("DdlProyecto").DataBind()
e.Row.FCDropDownList("DdlProyecto").SelectedValue = dr("CveProyecto").ToString
e.Row.FCDropDownList("DdlSubProyecto").DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, dr("CveProyecto").ToString.ToEntero, UsuarioActual.CveEmpresa, -1, 1)
e.Row.FCDropDownList("DdlSubProyecto").DataBind()
e.Row.FCDropDownList("DdlSubProyecto").SelectedValue = e.Row.DBCampo("CveSubProyecto")
End If
End If
'Si es una devolucion
If NuevaFactura = 0 Then
e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False
e.Row.FCDropDownList("DdlClasificacion").Enabled = False
e.Row.FCDropDownLost("DdlPS").Enabled = False
e.Row.FCDropDownList("DdlProyecto").Enabled = False
e.Row.FCDropDownList("DdlSubProyecto").Enabled = False
e.Row.FCTextBox("TxtPrecio").Enabled = False
ElseIf NuevaFactura = 1 Or CveContrato > 0 Then
e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False
e.Row.FCDropDownList("DdlClasificacion").Enabled = False
e.Row.FCDropDownLost("DdlPS").Enabled = False
e.Row.FCTextBox("TxtCantidad").Enabled = False
e.Row.FCTextBox("TxtPrecio").Enabled = False
e.Row.FCTextBox("TxtDescuento").Enabled = False
If TieneAlmacen Then e.Row.FCLinkButton("imgD").Visible = False
If UsuarioActual.TienePermisoProceso(222) Then
e.Row.FCDropDownList("DdlUnidadMedida").Enabled = True
e.Row.FCDropDownList("DdlClasificacion").Enabled = True
e.Row.FCDropDownLost("DdlPS").Enabled = True
e.Row.FCTextBox("TxtCantidad").Enabled = True
e.Row.FCTextBox("TxtPrecio").Enabled = True
e.Row.FCTextBox("TxtDescuento").Enabled = True
End If
End If
'Si es facturacion de OC o Contrato
If CveContrato > 0 AndAlso Not CveVenta > 0 AndAlso Not CveCicloComercial > 0 Then
e.Row.FCLinkButton("imgClone").Visible = False
e.Row.FCTextBox("TxtOrden").Visible = True
e.Row.FCTextBox("TxtCantidad").Enabled = False
e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False
e.Row.FCDropDownList("DdlClasificacion").Enabled = False
e.Row.FCDropDownLost("DdlPS").Enabled = False
e.Row.FCDropDownList("DdlProyecto").Enabled = False
e.Row.FCDropDownList("DdlSubProyecto").Enabled = False
e.Row.FCTextBox("TxtPrecio").Enabled = False
End If
If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then
e.Row.FCLinkButton("imgClone").Visible = False
e.Row.FCTextBox("TxtOrden").Visible = True
e.Row.FCTextBox("TxtCantidad").Enabled = False
e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False
e.Row.FCDropDownList("DdlClasificacion").Enabled = False
e.Row.FCDropDownList("DdlProyecto").Enabled = False
e.Row.FCDropDownList("DdlSubProyecto").Enabled = False
e.Row.FCLiteral("LtlPSEdit").Visible = True
e.Row.FCDropDownLost("DdlPS").Visible = False
e.Row.FCDropDownLost("DdlPS").Enabled = False
e.Row.FCTextBox("TxtPrecio").Enabled = True
End If
If CveCicloComercial > 0 Then
e.Row.FCTextBox("TxtPrecio").Enabled = True
End If
'CUANDO SE QUIERE FACTURAR UNA REMISIÓN NO PERMITE EDITAR SU PRECIO
If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso (e.Row.DBCampo("CveVentaDetalle").ToEntero > 0 Or e.Row.DBCampo("CveVentaDetalleRemision").ToEntero > 0) Then
e.Row.FCTextBox("TxtPrecio").Enabled = False
End If
'PERMISO EDITAR REM
If e.Row.DBCampo("TipoDocto") = "Rem" And ModalidadEdicion Then
'LO PERMITIDO MODIFICAR
e.Row.FCTextBox("TxtPrecio").Enabled = True
e.Row.FCTextBox("TxtObsPS").Enabled = True
e.Row.FCTextBox("TxtCantidad").Attributes.Add("onblur", $"ValidarCantidadMenor(this,{e.Row.DBCampo("CantidadInventario").ToDouble})")
'LO NO PERMITIDO MODIFICAR
e.Row.FCDropDownList("DdlUnidadMedida").Enabled = False
'e.Row.FCDropDownList("DdlClasificacion").Enabled = False
'e.Row.FCDropDownLost("DdlPS").Enabled = False
e.Row.FCTextBox("TxtTiempoEntrega").Enabled = False
e.Row.FCDropDownList("DdlProyecto").Enabled = False
e.Row.FCDropDownList("DdlSubProyecto").Enabled = False
e.Row.FCLinkButton("imgD").Visible = False
End If
'If UsuarioActual.CveEmpresa = 119 Then
' e.Row.FCTextBox("TxtDescuento").Enabled = False
'End If
Else
'MODO NORMAL
If UsuarioActual.Empresa.UsaAC Then
e.Row.FCDropDownList("DdlFR").DataSource = DTPresupuestoIngresos
e.Row.FCDropDownList("DdlFR").DataBind()
e.Row.FCDropDownList("DdlFR").SelectedValue = e.Row.DBCampo("CvePresupuestoIngreso")
'e.Row.FCDropDownList("DdlFR").Enabled = False
End If
If e.Row.DataKey("IEPS").ToDouble > 0 Then : TrIEPS.Visible = True : End If
If NuevaFactura = 1 Then
If Not UsuarioActual.TienePermisoProceso(222) Then
e.Row.FCLinkButton("imgD").Visible = False
e.Row.FCLinkButton("imgE").Visible = False
End If
If TieneAlmacen Then
e.Row.FCLinkButton("imgD").Visible = False
End If
End If
If (CveContrato > 0 AndAlso Not CveVenta > 0) Then
e.Row.FCLinkButton("imgD").Visible = False
End If
If DdlContratosModal.DataSource IsNot Nothing AndAlso CveCicloComercial <= 0 Then
e.Row.FCLinkButton("imgE").Visible = False
End If
'Si es Cotizacíon
If e.Row.DBCampo("TipoDocto") = "Cot" Then
ThTiempoEntrega.Visible = True
ThTiempoEntrega2.Visible = True
GvPS.Columns(5).Visible = True
End If
'Si es facturacion de OC
If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 Then
e.Row.FCLinkButton("imgClone").Visible = False
e.Row.FCTextBox("TxtOrden").Visible = True
End If
If UsuarioActual.Empresa.CvePlataforma = 2 Then
e.Row.FCLinkButton("imgE").Visible = False
e.Row.FCLinkButton("imgEPyME").Visible = True
End If
If UsuarioActual.Empresa.Tipo_CentroCosto = 2 Or UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then
e.Row.FCLabel("LblProyecto").Visible = False
End If
If CveVenta > 0 Then 'And e.Row.DBCampo("TipoDocto") = "Rem"
If ModalidadEdicion Then
e.Row.FCLinkButton("imgE").Visible = Not e.Row.DBCampo("CantidadFacturadaRem").ToDouble > 0
e.Row.FCLinkButton("imgD").Visible = Not e.Row.DBCampo("CantidadInventario").ToDouble > 0
ElseIf Not CveDevolucion > 0 Then
e.Row.FCLinkButton("imgE").Visible = False
e.Row.FCLinkButton("imgD").Visible = False
End If
End If
'CANTIDAD FACTURADA
Select Case e.Row.DBCampo("TipoDocto")
Case "Cot"
e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaCot").ToDecimal.ToString("#,##0.##")
Case "Pd2"
e.Row.FCLiteral("LtCantidadFacturada").Text = e.Row.DBCampo("CantidadFacturadaPed2").ToDecimal.ToString("#,##0.##")
End Select
'If GvInv.Rows.Count > 0 AndAlso ModalidadEdicion AndAlso DdlTipoComprobante.SelectedValue = "Rem" AndAlso e.Row.DataKey("CveVentaDetalle").ToString.ToEntero > 0 Then
' e.Row.FCLinkButton("imgE").Enabled = False
' e.Row.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen."
'End If
End If
End If
End Sub
Protected Sub GvPS_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvPS.RowEditing
GvPS.EditIndex = e.NewEditIndex
GvPS.DataSource = TmpDT
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvPS.DataBind()
End Sub
Protected Sub GvPS_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvPS.RowCancelingEdit
GvPS.EditIndex = -1
GvPS.DataSource = TmpDT
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvPS.DataBind()
End Sub
Protected Sub GvPS_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvPS.RowUpdating
'Dim TipoDescuento As Integer
Dim Cantidad, PU, Descuento As Decimal
Dim CuentaPredial As String
Cantidad = GvPS.Rows(e.RowIndex).FCTextBox("TxtCantidad").Text.ToDecimal
PU = Math.Round(GvPS.Rows(e.RowIndex).FCTextBox("TxtPrecio").Text.ToDecimal, 6)
Descuento = Math.Round(GvPS.Rows(e.RowIndex).FCTextBox("TxtDescuento").Text.ToDecimal, NumeroDecimales)
CuentaPredial = GvPS.Rows(e.RowIndex).FCTextBox("TxtPredial").Text.Trim
Dim DatarowPS As DataRow = Nothing
DatarowPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero).FiltroPrimero("") ' Estado = -1
'verifica si tiene ventaminima
If Cantidad > 0 AndAlso DatarowPS("VentaMinima").ToString.ToDecimal > 0 AndAlso (DdlTipoComprobante.SelectedValue = "Rem" Or DdlTipoComprobante.SelectedValue = "Ing") Then
'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15...
If Cantidad Mod DatarowPS("VentaMinima").ToString.ToDecimal <> 0 Then
Alert(String.Format("El producto se vende solo en cantidades de {0}", DatarowPS("VentaMinima").ToString))
Exit Sub
End If
End If
If TmpDT.Rows(e.RowIndex)("CvePS").ToString <> GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue Then
'eliminar y cargar el ps ***
Dim DdlUM As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida")
Dim DdlCla As DropDownList = GvPS.Rows(e.RowIndex).FCDropDownList("DdlClasificacion")
TmpDT.Rows.Remove(TmpDT.Rows(e.RowIndex))
CalculaUsados()
AgregarProductoServicio(Cantidad, DdlUM.SelectedValue.ToEntero, DdlUM.SelectedItem.Text, DdlCla.SelectedValue.ToEntero, DdlCla.SelectedItem.Text,
GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownLost("DdlPS").SelectedText,
GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.Trim, PU, Descuento,
GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text,
GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue.ToEntero, GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text,
CuentaPredial:=CuentaPredial, CveVentaDetalle:=GvPS.Rows(e.RowIndex).DataKey("CveVentaDetalle").ToString.ToEntero, SeActualiza:=True)
' TmpDT.Rows(e.RowIndex)("CveUM") = Ddl.SelectedValue
' TmpDT.Rows(e.RowIndex)("UM") = Ddl.SelectedItem.Text
If UsuarioActual.Empresa.Funcionalidad(533).ToEntero > 0 Then
GvPS.EditIndex = -1
GvPS.DataSource = TmpDT
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvPS.DataBind()
CargaGVInv(DtInv)
CalculaUsados()
End If
Else
If Not ClienteDesglosaIEPS Then
Dim DrPS As DataRow = Nothing
'DrPS = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero, Estatus:=-1).FiltroPrimero("")
DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=TmpDT.Rows(e.RowIndex)("CvePS").ToString.ToEntero).FiltroPrimero("")
PU = PU * (1 + DrPS("IEPSPorcentaje").ToString.ToDecimal)
TmpDT.Rows(e.RowIndex)("PorcentajeIEPS") = 0
End If
Dim TotalCalculableImpuestos As Decimal = ((Cantidad * PU) - (Descuento))
TmpDT.Rows(e.RowIndex)("CveUM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedValue.ToEntero
TmpDT.Rows(e.RowIndex)("UM") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlUnidadMedida").SelectedItem.Text
TmpDT.Rows(e.RowIndex)("Cantidad") = Cantidad
TmpDT.Rows(e.RowIndex)("Obs") = GvPS.Rows(e.RowIndex).FCTextBox("TxtObsPS").Text.Trim
TmpDT.Rows(e.RowIndex)("TiempoEntrega") = GvPS.Rows(e.RowIndex).FCTextBox("TxtTiempoEntrega").Text.Trim
TmpDT.Rows(e.RowIndex)("PU") = PU
TmpDT.Rows(e.RowIndex)("Descuento") = Descuento
TmpDT.Rows(e.RowIndex)("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales)
TmpDT.Rows(e.RowIndex)("ImporteIVA") = Math.Round(TmpDT.Rows(e.RowIndex)("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
TmpDT.Rows(e.RowIndex)("ImporteIEPS") = Math.Round(TmpDT.Rows(e.RowIndex)("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
TmpDT.Rows(e.RowIndex)("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
TmpDT.Rows(e.RowIndex)("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
TmpDT.Rows(e.RowIndex)("PorcentajeRetIVA") = ClienteRetIVA
TmpDT.Rows(e.RowIndex)("PorcentajeRetISR") = ClienteRetISR
TmpDT.Rows(e.RowIndex)("CuentaPredial") = CuentaPredial
If GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").Items.Count = 0 Then
TmpDT.Rows(e.RowIndex)("Proyecto") = "Sin Proyecto Asignado"
TmpDT.Rows(e.RowIndex)("CveSubProyecto") = -1
Else
TmpDT.Rows(e.RowIndex)("Proyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlProyecto").SelectedItem.Text
End If
If GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").Items.Count = 0 Then
TmpDT.Rows(e.RowIndex)("SubProyecto") = "Sin SubProyecto Asignado"
Else
TmpDT.Rows(e.RowIndex)("SubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedItem.Text
TmpDT.Rows(e.RowIndex)("CveSubProyecto") = GvPS.Rows(e.RowIndex).FCDropDownList("DdlSubProyecto").SelectedValue
End If
GvPS.EditIndex = -1
GvPS.DataSource = TmpDT
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvPS.DataBind()
CargaGVInv(DtInv)
CalculaUsados()
End If
CalculaTotalesVenta()
'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW
If AplicaComercioExterior Then
CargaGvComercioExterior()
End If
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
UpPS.Update()
UpContado.Update()
End Sub
Protected Sub GvPS_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvPS.RowDeleting
Dim DbRow As DataRow = Nothing
DbRow = TmpDT.Rows(e.RowIndex)
TmpDT.Rows.Remove(DbRow)
CalculaUsados()
GvPS.DataSource = TmpDT
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvPS.DataBind()
CargaGVInv(DtInv)
CalculaTotalesVenta()
Alert("Eliminado Correctamente.", TipoMensaje.MsgInformacion)
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
UpContado.Update()
End Sub
#End Region
#Region "GvINV"
Private Sub GvInv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvInv.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'SERIE ALMACEN
If e.Row.DBCampo("CveTipoInvPS").ToEntero = 5 Then
If CveVenta > 0 Then
e.Row.FCLiteral("LtlSerie").Visible = True
Else
e.Row.FCTextBox("TxtSerie").Visible = True
e.Row.FCTextBox("TxtSerie").Attributes.Remove("onkeypress")
e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeypress", String.Format("SeriePS(event,{0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID))
e.Row.FCTextBox("TxtSerie").Attributes.Remove("onblur")
e.Row.FCTextBox("TxtSerie").Attributes.Add("onblur", String.Format("SeriePSBlur({0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID))
End If
'e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID))
'e.Row.FCTextBox("LblCodigo").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID))
'e.Row.FCTextBox("LblCodigo").Attributes.Add("onblur", String.Format("LimpiaAF(1, '{0}'); AFBlurEdit(this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID))
End If
If e.Row.DBCampo("CvePS") = "" Then
e.Row.FCLiteral("LtlPS").Text = String.Format("<a Class=""Texto"" target='_blank' href=""/Inventarios/EntradasSalidas.aspx?CveMovimiento={0}"">Folio: {1} Fecha: {2} -- {3} -- {4}</a>", e.Row.DBCampo("CveMovimiento"), e.Row.DBCampo("Folio"), e.Row.DBCampo("Fecha").ToString.ToDate.ToShortDateString, e.Row.DBCampo("Almacen").ToString, e.Row.DBCampo("Concepto").ToString)
e.Row.FCCheckBox("cbInv").Visible = False
e.Row.FCCheckBox("cbInv").Enabled = False
If e.Row.DataKey("Origen").ToEntero > 0 Then
e.Row.BackColor = Drawing.Color.FromArgb(224, 130, 131)
e.Row.ForeColor = Drawing.Color.White
e.Row.Font.Bold = True
Else
e.Row.CssClass = "SubTotales"
End If
Else
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left
e.Row.FCCheckBox("cbInv").Visible = True
e.Row.FCCheckBox("cbInv").Enabled = True
'SI ES REMISION O VENTA DEBE SALIR DE ALMACEN
If UsuarioActual.TienePermisoProceso(157) AndAlso e.Row.DBCampo("CvePS").ToEntero > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") AndAlso UsuarioActual.CveEmpresa <> 72 Then
e.Row.FCCheckBox("cbInv").Checked = True
e.Row.FCCheckBox("cbInv").Enabled = False
End If
End If
If CveVenta > 0 Then
If e.Row.DBCampo("CveConcepto").ToEntero = 3 Then CveAlmacenDevolucion = e.Row.DBCampo("CveAlmacen").ToEntero
e.Row.FCCheckBox("cbInv").Visible = False
End If
End If
End Sub
Protected Sub GVINV_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvInv.RowEditing
GvInv.EditIndex = e.NewEditIndex
CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2"))
End Sub
Protected Sub GVINV_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvInv.RowCancelingEdit
GvInv.EditIndex = -1
CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2"))
End Sub
Protected Sub GVINV_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvInv.RowUpdating
Dim Cantidad As Double = DirectCast(GvInv.Rows(e.RowIndex).FindControl("txtECantidad"), TextBox).Text.ToDouble
DtInv.Rows.Item(e.RowIndex)("Cantidad") = Cantidad
GvInv.DataSource = DtInv.FiltraParametros("CveTipoPS=2")
End Sub
#End Region
#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
EmitirImprimir()
End Sub
Private Sub EmitirImprimir()
DtRemisionesTmpDT = TmpDT.Copy
DtPedidos2TmpDT = TmpDT.Copy
DtCotizacionTmpDT = TmpDT.Copy
DtOCTmpDT = TmpDT.Copy
TmpDTError = TmpDT.Copy
'CUANDO ES PEDIDO SE DEBE ESPECIFICAR EL NUMERO DE CONTRATO
If TrTipoPedido.Visible AndAlso DdlTipoPedido.SelectedIndex = 2 Then
If String.IsNullOrEmpty(TxtObsFact.Text.Trim()) Then
Alert("Se debe especificar el Número de contrato.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
'CUANDO ES COTIZACION Y SE VA A FACTURAR SE HACE INGRESO
If DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar" Then
DdlTipoComprobante.SelectedValue = "Ing"
EraCotizacion = 1
TxtFecha.Text = Now.ToString
TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranza), Now.AddDays(PlazoCobranza)).ToShortDateString
TxtFechaEjecucion.Text = Now.ToString
'debo de regenerar los folios, para facturar
CargaFolios()
End If
'VALIDACIONES
If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If TmpDT Is Nothing OrElse TmpDT.Rows.Count = 0 Then
Alert("Es necesario tener al menos un concepto registrado.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'Subproyecto Obligatorio
If UsuarioActual.Empresa.Funcionalidad(120) = "1" AndAlso TmpDT.FiltraParametros("ISNULL(CveSubProyecto,0) <= 0").Rows.Count > 0 Then
Alert("El Subproyecto de los conceptos es obligatorio, Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'SI TIENE ANTICIPOS Y ESTA AMORTIZADO AL 100% EL DOCUMENTO (SALDO = 0) | NO VALIDA PU DEL CONCEPTO
If Not (LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0) Then
If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then
If TmpDT.FiltraParametros($"TotalImporte = 0").Rows.Count > 0 Then
Alert("El importe de cada concepto debe ser mayor a cero. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
End If
Dim CveContratoTipo As Integer = 0
If CveContrato > 0 Then
Dim ObjContrato As New ClsContratos
If ObjContrato.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then
If ObjContrato.DtResultados.Rows.Count > 0 Then
CveContratoTipo = ObjContrato.DtResultados.Rows(0)("CveContratoTipo").ToString.ToEntero
End If
End If
ObjContrato.Dispose()
End If
'No exceder el limite de credito, Si no tiene contrato limita el credito, si tiene no hace nada. Si no tiene remisiones tampoco hace nada.
If (Not CveContrato > 0 Or CveContratoTipo.Contiene(28)) AndAlso (Not NuevaFactura = 1) AndAlso RBLPago.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso RemisionesLista.Count <= 0 AndAlso TxtTotal.Text.ToDecimal > 0 AndAlso Not CvePedidoA > 0 Then
If UsuarioActual.Empresa.Funcionalidad(518) = "1" AndAlso Not UsuarioActual.TienePermisoProceso(185) Then
Dim ObjVentas As New ClsVentas
If ObjVentas.ObtenerCreditoRestante(CveCliente, DdlSucursalCliente.SelectedValue.ToEntero) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
If DdlSucursalCliente.SelectedValue.ToEntero > 0 Then
If ObjVentas.DtResultados(0)("LimiteRestanteSucursal").ToString.ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then
ObjVentas.Dispose()
Alert("Se está excediendo el límite de credito permitido de la Sucursal del Cliente.", TipoMensaje.MsgInformacion)
Exit Sub
End If
Else
If ObjVentas.DtResultados(0)("LimiteRestanteCliente").ToString.ToDecimal - If(TxtTipoCambio.Visible, TxtTotal.Text.ToDecimal * TxtTipoCambio.Text.ToDecimal, TxtTotal.Text.ToDecimal) < 0 Then
ObjVentas.Dispose()
Alert("Se está excediendo el límite de credito permitido del Cliente.", TipoMensaje.MsgInformacion)
Exit Sub
End If
End If
Else
ObjVentas.Dispose()
Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError)
Exit Sub
End If
Else
ObjVentas.Dispose()
Alert("Ocurrio un error al obtener el limite de credito del cliente", TipoMensaje.MsgError)
Exit Sub
End If
ObjVentas.Dispose()
End If
End If
'VALIDA PRECIO AL AGREGAR A ALMACEN
If Not UsuarioActual.TienePermisoProceso(169) Then
If (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") AndAlso NuevaFactura <> 1) Or (DdlTipoComprobante.SelectedValue = "Cot" AndAlso BtnEmitirImprimir.Text = "Facturar") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119)) Then
Dim MensajeCosto As New StringBuilder
Dim CostoMenor = 0.0D
Dim CostoMayor = 0.0D
Dim Costo = 0.0D
Dim EsValido = False 'BANDERA
Dim EsValidoMayor = False
Dim EsValidoPU = True 'SOLO SE VALIDA CUANDO EL TXTPU = 0 Y LO INVALIDA ALGUNA PROMOCION
'VALIDA PROMOCIONES Y EXISTENCIAS
Dim ObjVentas As New ClsVentas
If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero, CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
DtPromociones = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
Dim ObjInventarios As New ClsInventarios
Dim PU = 0.0D
Dim Cantidad As Double
Dim CveUnidad As Integer
Dim CveProducto As Integer
Dim Existencia As Double
Dim CveAlmacen = ddlAlmacen.SelectedValue.ToEntero
For Each dr As DataRow In TmpDT.Rows
'SI ES SERVICIO NO VALIDA
'GlobalDTProductosServicios
If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=dr("CvePS").ToString.ToEntero).FiltroPrimeroValor("CveTipoPS").ToString.ToEntero = 1 Then
Continue For
End If
If DdlTipoComprobante.SelectedValue <> "Cot" And ChkSinExistencia.Checked = False Then
'VALIDA EXISTENCIA
CveProducto = dr("CvePS").ToString.ToEntero
CveUnidad = dr("CveUM").ToString.ToEntero
Cantidad = TmpDT.SUM("Cantidad", $"CvePS = {CveProducto}") 'VALIDA CONTRA LA SUMA DEL MISMO PS
If UsuarioActual.CveEmpresa.Contiene({72, 80, 119}) AndAlso RemisionesLista.Count < 1 AndAlso dr("EntregaDirecta").ToString.ToEntero < 1 Then
Existencia = ObjInventarios.GetExistenciasPS(CveProducto, CveUnidad, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1)
If Existencia < Cantidad Then
MensajeCosto.AppendFormat("<br/>El Producto <b>{0}</b>. No cuenta con la cantidad suficiente en inventario. Cuenta con {1}.", dr("CodigoPS").ToString, Existencia.FormatoNumero(2))
Continue For
End If
End If
End If
EsValido = False
EsValidoMayor = False
EsValidoPU = True
PU = dr("PU").ToString.ToDecimal * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal)
Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString.ToEntero, dr("Cantidad").ToString.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero)
Dim PrecioMinimo As Decimal = 0
'RMF. condicion temporal, para reubicación, precio mínimo
If UsuarioActual.CveEmpresa = 119 Then
'Dim CvePrecioLista As Integer = 38
Dim objPS As New ClsProductosServicios
If objPS.GetPSSucursalesALL(dr("CvePS").ToString.ToEntero, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then
PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal
If PrecioMinimo > 0 Then
Costo = PrecioMinimo
End If
End If
objPS.Dispose()
End If
'COSTO ALMACEN
If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo)
'SI EL PRECIO ES MAYOR AL COSTO, SI PASA
If PrecioMinimo > 0 Then CostoMenor = PrecioMinimo
If Math.Round(PU, 4) >= Math.Round(CostoMenor, 4) Then
EsValido = True
End If
Else
EsValido = True
End If
If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo)
'SI EL PRECIO ES MAYOR AL COSTO, SI PASA
If PU <= CostoMayor Then
EsValidoMayor = True
End If
Else
EsValidoMayor = True
End If
'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR
If Not EsValido Or PU = 0 Then
If DtPromociones.FiltraParametros($"CvePS = {dr("CvePS").ToString.ToEntero}").Rows.Count > 0 Then
If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {dr("CvePS").ToString.ToEntero}").ToDecimal Then
EsValido = True
Else
EsValidoPU = False ' SI NO ENTRA DENTRO DE LA PROMOCION NO SE PUEDE VENDER A 0
End If
Else
EsValidoPU = False ' SI NO TIENE PROMOCION NO SE PUEDE VENDER A 0
End If
End If
'NO DEJA REGISTRAR CON VALIDACION DE COSTO ALMACEN O PROMOCION
Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201)
If Not EsValido Then
MensajeCosto.AppendFormat("El Producto <b>{0}</b>. No se puede vender a un precio menor de su Costo ni a un precio mayor de su rango aceptado<br/>", dr("PS").ToString)
If TienePermisoImportes Then
MensajeCosto.AppendFormat("El costo del producto es: <b>{0}$</b> <br/>", Costo)
MensajeCosto.AppendFormat("El rango menor aceptado es: {0} <b>{1}$</b> <br/>", UsuarioActual.Empresa.Funcionalidad(129).ToEntero, CostoMenor)
MensajeCosto.AppendFormat("El precio indicado es: <b>{0}$</b> ({1}% de ganancia) <br/>", PU.FormatoNumero, If(Costo > 0, ((PU - Costo) * 100) / Costo, 0))
End If
End If
If Not EsValidoMayor Then
MensajeCosto.AppendFormat("El Producto <b>{0}</b>. No se puede vender a un precio mayor de su rango aceptado<br/>", dr("PS").ToString)
If TienePermisoImportes Then
MensajeCosto.AppendFormat("El costo del producto es: <b>{0}$</b> <br/>", Costo)
MensajeCosto.AppendFormat("El rango mayor aceptado es: {0} <b>{1}$</b> <br/>", UsuarioActual.Empresa.Funcionalidad(133).ToEntero, CostoMayor)
MensajeCosto.AppendFormat("El precio indicado es: <b>{0}$</b> ({1}% de ganancia) <br/>", 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 <b>{dr("PS").ToString}</b>. No se puede vender a un importe de cero ($0)", TipoMensaje.MsgAdvertencia)
End If
End If
Next
ObjInventarios.Dispose()
If MensajeCosto.ToString.Length > 1 Then
Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
If UsuarioActual.Empresa.Funcionalidad(135) = "1" And DdlTipoComprobante.SelectedValue = "Cot" Then
Alert("Se mando autorización al supervisor.", TipoMensaje.MsgInformacion)
MandarCorreoSupervisor = True
Dim CorreoSupervisor As String = ""
Dim Objeto As New ClsVtaVendedores
Dim DTSupervisores As New DataTable
If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then
DTSupervisores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DdlVendedor.SelectedValue.ToEntero))
'Verifico si el supervisor tiene correo para proceder
If DTSupervisores.Rows.Count > 0 Then
CorreoSupervisor = DTSupervisores.Rows(0)("CorreoSupervisor").ToString
End If
End If
DTSupervisores.Dispose()
Objeto.Dispose()
If MandarCorreoSupervisor = True And CorreoSupervisor <> "" Then
ViewState("Mail") = CorreoSupervisor
End If
MandarCorreoSupervisor = False
End If
If RequiereOC AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Ing") AndAlso Not CveDevolucion > 0 Then
If Not CargaDocumentoOC Then
Alert("Tiene que cargar un archivo de orden de compra", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If TxtOrdenCompra.Text.Trim = "" Then
Alert("Tiene que especificar un folio de orden de compra", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked) > 0 AndAlso ddlAlmacen.SelectedValue.ToEntero() <= 0 Then
Alert("Tiene que seleccionar un almacen", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
EmitirImprimirNew()
End Sub
#End Region
#Region " NNNNEEEEEEEWWWWWW "
Private Sub InicializaImprimirNew()
Dim Archivo As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta))
Dim Archivo2 As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta))
LnkImprimir.Visible = False
'If (UsuarioActual.CveEmpresa.Contiene(1, 4, 5, 7, 11, 12, 72, 80, 81, 83) And UsuarioActual.CveUsuario = 100) Or UsuarioActual.CveEmpresa.Contiene(80, 83) Or UsuarioActual.CveUsuario = 100 Then
If (Archivo.Exists Or Archivo2.Exists) And IfNull(CveVenta, 0).ToString.ToEntero > 0 Then
HplDownPDF.Visible = True
HplDownPDF.NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta)))
End If
UpnTools.Update()
End Sub
Protected Sub EmitirImprimirNew()
If ValidaPagosContado() Then
Exit Sub
End If
CreaObjetosVenta()
'Verifica versión 3.3.()
If ObjFactura.Version = "3.3" AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then
Dim dttsat As DataTable = TmpDT.FiltraParametros("ISNULL(SATClaveProdServ,'') = '' OR ISNULL(SATClaveUM,'') = '' ")
If dttsat IsNot Nothing AndAlso dttsat.Rows.Count > 0 Then
Dim str As New StringBuilder
str.Append("Los siguientes productos no tiene asignado la clave Producto SAT o Unidad Medida SAT<br/><br/>")
For Each drt As DataRow In dttsat.Rows
str.AppendFormat("{0} <br/>", drt("CodigoPS"))
Next
Alert(str.ToString, TipoMensaje.MsgAdvertencia)
dttsat.Dispose()
Exit Sub
End If
dttsat.Dispose()
End If
If ObjFactura Is Nothing Or (ObjFactura.Cliente Is Nothing And Not CveEmpresaCRM > 0) Then
Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError)
ObjFactura = Nothing
Exit Sub
End If
'If Not CveEmpresaCRM > 0 Then
' If ObjFactura.Cliente.AplicaComercioExterior Then
' If Not ValidaComercioExterior() Then
' ObjFactura = Nothing
' Exit Sub
' End If
' End If
'End If
'VALIDA TOTAL DE LA NOTA DE CREDITO Y LA FACTURA VINCULADA *** ESTABA TRONANDO EN COMPU 11/01/17 ***
'If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then
' If SubTotalFacturaVinNC() > 0 Then 'pendiente
' If GvInvNC.Rows.Count > 0 Then 'pendiente
' If Not (SubTotalFacturaVinNC() = TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio)) Then
' Alert(String.Format("El sub-total debe ser igual a '{0}'", SubTotalFacturaVinNC().FormatoNumero))
' Exit Sub
' End If
' Else
' If SubTotalFacturaVinNC() < TxtSubTotal.Text.ToDouble(ObjFactura.TipoCambio) Then 'pendiente
' Alert(String.Format("El sub-total no puede exceder a : {0}", SubTotalFacturaVinNC().FormatoNumero))
' Exit Sub
' End If
' End If
' End If
'End If
If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant", "DPe") Then
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then
If ObjFactura.SubTotal <= 0 Then
Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
'VALIDA CUENTAS CONTABLES DE AC
If UsuarioActual.Empresa.UsaAC Then
If ObjFactura.Cliente.IdCtaContClientes <= 0 Then
Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError)
Exit Sub
End If
'If ViewState("IdCtaContClientes").ToString.ToEntero <= 0 Then 'GetClientes ObjCliente.IdCtaContClientes
' Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError)
' Exit Sub
'End If
If ObjFactura.SubTotal <= 0 Then
Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'If TxtSubTotal.Text.ToDouble <= 0 Then
' Alert("Especifique importe en conceptos", TipoMensaje.MsgError)
' Exit Sub
'End If
End If
'cuando es contado debe de tener especificado la forma de pago
'If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") AndAlso ObjFactura.Total > 0 AndAlso RBLPago.SelectedValue = "2" AndAlso ObjFactura.Total - If(DtPagos Is Nothing, 0, DtPagos.SUM("Importe")) > 0 Then ' AndAlso ObjFactura.CveCorte > 0
' Alert("No se han especificado las formas de pago. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia)
' Exit Sub
'End If
If ObjFactura.CveCliente > 0 Or CveEmpresaCRM > 0 Then
If TmpDT.Rows.Count > 0 Then
Dim ObjVentas As New ClsVentas()
Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL())
Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL())
Dim ObjContr As New ClsContratos(ObjVentas.IniciaTransacSQL())
Dim ObjOS As New ClsOS(ObjVentas.IniciaTransacSQL())
Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL())
Dim ObjClientes As New ClsClientes(ObjVentas.IniciaTransacSQL())
Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL())
Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL())
Dim ObjDocCliente As New ClsEdocumentacion(ObjVentas.IniciaTransacSQL())
Dim ObjContPaq As ClsContPAQi = Nothing
'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL())
ErrorList = New List(Of String)
MensajeAlert = New StringBuilder
'CONTABILIDAD AUTOMATICA Y AC
If UsuarioActual.Empresa.UsaAC OrElse UsuarioActual.Empresa.Funcionalidad(200) = "1" Then
ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa)
End If
'VERIFICA QUE EL FOLIO NO SEA IGUAL AL DE LA FACTURA ANTERIOR
'If ObjFactura.Folio = TxtFolio.Text.ToEntero Then
' If ObjFolios.GetFolios(ObjFactura.TipoDocto, UsuarioActual.CveEmpresa) Then
' Dim DtFolios As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSucursal = {0} And Estado = 'Activo'", ObjFactura.CveSucursal))
' If DtFolios.Rows.Count > 0 Then
' 'ViewState("CveFolio") = DtFolios.Rows(0)("CveFolio").ToString.ToEntero
' 'ViewState("NumAprobacion") = CLng(DtFolios.Rows(0)("Aprobacion").ToString)
' 'ViewState("FechaAprobacion") = DtFolios.Rows(0)("FechaAprobacion").ToString.ToDate
' 'ViewState("FolioActual") = DtFolios.Rows(0)("FActual").ToString
' 'LblSerie.Text = DtFolios.Rows(0)("Serie").ToString
' If UsuarioActual.CveEmpresa <> 72 Then
' ObjFactura.Folio = DtFolios.Rows(0)("FActual").ToString.ToEntero
' End If
' End If
' End If
'End If
'GUARDA VENTA
Dim TieneAnticipo As Boolean = False
Dim CveAnticipoPadre As Integer = 0 ' vinculación con anticipo
Dim FolioFiscalRelacionado As String = ""
If GVAnticipos.Rows.Count > 0 Then
Dim actualindex As Integer = 0
For Each row2 As GridViewRow In GVAnticipos.Rows
If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then
TieneAnticipo = True
CveAnticipoPadre = row2.DataKey("CveVenta").ToEntero
ObjFactura.CveVentaRelacion = CveAnticipoPadre 'relaciona al anticipo
CveAnticipo = CveAnticipoPadre
ObjFactura.ImporteRelacion = row2.FCTextBox($"TxtAnticipo{actualindex}").Text.ToDecimal
FolioFiscalRelacionado = row2.DataKey("FolioFiscal")
ObjFactura.CveVentaPadre = row2.DataKey("CveVenta").ToEntero
End If
actualindex = actualindex + 1
Next
End If
GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjFactura, TmpDT, ObjFactura.CveNCaVincular, ObjContPaq, ObjBancos, ObjOS, ObjEventos, ObjCGame, ObjClientes)
'SI ES REFACTURACION
Dim ObjNC As List(Of Object) = Nothing
If ErrorList.Count = 0 Then
If NuevaFactura = 1 Then
'Si directamente como cancelada sin aceptación, debe de generar la cancelacion aquí
If Me.CveEstatusRefacturacion = 0 Then ' cuando es refacturación sin aceptación debe de cancelar y reducir saldo
ObjNC = generaNC(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, ObjEventos)
If ObjNC Is Nothing Then
ErrorList.Add("No se pudo Cancelar la Factura")
End If
End If
'Esquema viejo, evitamos que aparezca por surtir
If ErrorList.Count = 0 Then
If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then
ErrorList.Add("No se pudo Cancelar el movimiento de almacen de la Factura")
End If
End If
End If
End If
''[IPP]
''DATATABLES A USAR
'Dim DtSites As New DataTable
'Dim DtExcel As New DataTable
''CARGAS EXCEL EN DATATABLE
'DtExcel = TmpDT
''CARGAS LOS SITES REGISTRADOS
'If ObjBancos.GetBancos() Then
' DtSites = ObjBancos.DtResultados
'End If
''PROCESAS EXCEL
'Dim CveSiteActual = -1
'For Each Row As DataRow In TmpDT.Rows
' 'VALIDA QUE EXISTA EL SITE
' If DtExcel.Select($"Site = {Row("SITE")}").Count = 0 Then 'SI NO EXISTE AGREGA EL SITE
' CveSiteActual = ObjBancos.AddComplementoPago(-1, -1, "", -1, -1, -1)
' 'VALIDAS QUE SE HALLA AGREGADO
' If CveSiteActual > 0 Then
' 'AGREGA NUEVO SITE AL DATATABLE TEMPORAL DE SITES
' Dim DrNuevoSite = DtExcel.NewRow
' DrNuevoSite("CVE") = CveSiteActual
' DrNuevoSite("SITE") = Row("SITE")
' Else
' Alert("ERROR AL AGREGAR EL SITE")
' Exit For
' End If
' ElseIf DtExcel.Select($"Site = {Row("SITE")}").Count = 1 Then 'SI EXISTE OBTIENES CVE
' CveSiteActual = DtExcel.Select($"Site = {Row("SITE")}")(0)("Cve").ToString.ToEntero
' Else
' Alert("ERROR SOLO DEBE DAR RESULTADO 0 ó 1")
' Exit For
' End If
' 'AGREGA A TABLA CON LA DE MAS INFORMACION
' If Not ObjBancos.AddBancos_EstatusIE(CveSiteActual, Row("CAMPOS").ToString, Row("CAMPOS_EXTRA").ToString.ToEntero) Then
' Alert("ERROR AL GUARDAR")
' Exit For
' End If
'Next
'SI ES amortizacion 3.3
Dim Obj2 As New List(Of Object)
If ErrorList.Count = 0 Then
' cambiar la condicion para saber si hay seleccionado
If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then
If TieneAnticipo Then
CreaObjetosVentaAmortizacion(ObjVentas, FolioFiscalRelacionado, CveAnticipoPadre)
Try
If RegistrarNCAmortizacion(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, Nothing, Nothing) Then
Obj2.Add(ObjFacturaDevolucion)
End If
Catch ex As Exception
ErrorList.Add("No se pudo generarse la nota de crédito de amortización")
End Try
End If
If Obj2 Is Nothing AndAlso Obj2.Count = 0 Then
ErrorList.Add("No se pudo generarse la nota de crédito de amortización")
End If
End If
End If
'MARCA PARA NO SURTIR VENTA DE COTNRATO DE CONSIGNACION DE VENTA | [IPP] : PARCHE
If ErrorList.Count = 0 Then
If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then
If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then
ErrorList.Add("No se pudo cancelar el movimiento de almacen de la Factura de consignación")
End If
End If
End If
If ErrorList.Count = 0 Then
If ObjFactura.CveVenta > 0 And CveAlmacenExistenciasContrato > 0 And DdlTipoComprobante.SelectedValue = "Ing" Then
If Not RegistraAlmacenConsignacionVenta(ObjInventario, ObjFactura) Then
ErrorList.Add("Ocurrió un error al registrar los movimientos de almacén del contrato de consignación")
End If
End If
End If
If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 Then
'ACTUALIZA VENTA COTIZACIÓN
If EraCotizacion = 1 And BtnEmitirImprimir.Text = "Facturar" Then
If Not ObjVentas.UpdateVentaCotizacion(ObjFactura.CveVenta, Request("CveVenta").ToEntero) Then
ErrorList.Add("Ocurrió un error al actualizar la cotización")
End If
End If
'ACTUALIZA VENTAPADRE PEDIDO
If Request("DevPed").ToEntero > 0 AndAlso ErrorList.Count = 0 Then
If Not ObjVentas.UpdateVentaCotizacion(Request("DevPed").ToEntero, ObjFactura.CveVenta) Then
ErrorList.Add("Ocurrió un error al actualizar la devolución de pedido")
End If
End If
'ACTUALIZA LA COLUMNA CveVentaFacturada
If (Request("CveRemision") IsNot Nothing AndAlso ViewState("CveRemision").ToString.ToEntero > 0) AndAlso (Request("Op") IsNot Nothing AndAlso Request("Op") = "Rem") AndAlso ErrorList.Count = 0 Then
If Not ObjVentas.UpdateVentaRemision(ViewState("CveRemision").ToString.ToEntero, ObjFactura.CveVenta) Then
ErrorList.Add("Ocurrió un error al actualizar la remision")
End If
End If
'Agregamos las OCs a la tabla
If DTOrdenesCompraPS IsNot Nothing AndAlso DTOrdenesCompraPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then
Dim CveVentaDetalle As Integer = 0
Dim CveOrdenCompraDetalle As Integer = 0
Dim Cantidad As Decimal = 0
For Each row As DataRow In TmpDT.Rows
Cantidad = row("Cantidad").ToString.ToDecimal
CveVentaDetalle = row("CveVentaDetalle").ToString.ToEntero
CveOrdenCompraDetalle = row("CveOrdenCompraDetalle").ToString.ToEntero
If Not ObjVentas.AgregarVentaOCDetalle(CveVentaDetalle, CveOrdenCompraDetalle, Cantidad) Then
ErrorList.Add("Ocurrió un Error al agregar el detalle de la Remision")
End If
Next
End If
'Agregamos las Cotizaciones a la tabla
If DtCotizacionesPS IsNot Nothing AndAlso DtCotizacionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then
Dim CveVentaDetalle As Integer = 0
Dim CveVentaDetallePadre As Integer = 0
Dim Cantidad As Decimal = 0
Dim CvePS As Integer = 0
Dim PU As Decimal = 0
For Each row As DataRow In DtCotizacionesPS.Rows
Cantidad = DtCotizacionTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal
CvePS = DtCotizacionTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero
PU = DtCotizacionTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToDecimal
CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleCotizacion={row("CveVentaDetalle")}").ToEntero
CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero
If Not ObjVentas.AgregaCotizacionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then
ErrorList.Add("Ocurrió un Error al agregar el detalle de la Cotización.")
End If
Next
End If
'Marcamos las ventas anteriores a febrero como surtidas - Ajuste Compu
If ErrorList.Count = 0 Then
If Not ObjVentas.MarcarRemisionesSinSurtir(ObjVentas.CveVenta) Then
ErrorList.Add("Ocurrió un Error al marcar la factura")
End If
End If
If CveOS > 0 And FacturaMateriales = 1 AndAlso ErrorList.Count = 0 Then
If SalidaAlmacenMateriales(ObjInventario, CveOS, ObjConta, True, 3) Then
ErrorList.Add("Ocurrió un Error al dar salida de materiales de almacen")
End If
End If
If CveFactura > 0 AndAlso ErrorList.Count = 0 Then
If Not ObjVentas.UpdateVentaFacturas(CveFactura, ObjVentas.CveVenta, UsuarioActual.CveEmpresa) Then
ErrorList.Add("No se pudo actualizar la Factura")
End If
End If
If CveCicloComercial > 0 AndAlso ErrorList.Count = 0 Then
If Not ObjContr.CicloComercialUpdate(CveCicloComercial, True, UsuarioActual.CveEmpresa) Then
ErrorList.Add("No se pudo actualizar ")
End If
End If
If ErrorList.Count = 0 AndAlso ObjFactura.CveVenta > 0 AndAlso DtDocumentacionCliente IsNot Nothing Then
' si se cargó algun documento
If DtDocumentacionCliente.FiltraParametros("RutaArchivo <> ''").Rows.Count > 0 Then
GuardaVentaDocumentosCliente(ObjFactura.CveVenta, ObjDocCliente)
End If
End If
If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 AndAlso (SeGuardoPrePoliza Or ObjFactura.TipoDocto.Contiene("Ped", "Cot", "DPe", "PeC", "PA", "Pd2")) Then
ObjVentas.Commit()
'ContPAQ El movimiento 1 es el de Venta
Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1"
If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ant", "Rem", "RNC", "Cot", "Ped", "Pd2", "PA", "Egs", "Dev") Then
AutoConta = False
End If
If AutoConta Then
If idCuentaContabilizacion > 0 Then
If ObjConta.ContabilizarPrePoliza(ObjFactura.CvePrePoliza, ObjFactura.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then
Else
Alert("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico", TipoMensaje.MsgError)
End If
Else
Alert(String.Format("Falta asignación de las siguientes cuentas contables: {0}", CuentasContablesInvalidas), TipoMensaje.MsgAdvertencia)
End If
End If
If ObjContPaq IsNot Nothing Then ObjContPaq.Commit()
'If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack()
'RMF, cuando es pedido, se manda autorización.
If ObjFactura.TipoDocto.Contiene("PA") Then
Dim Titulo As String = "Solicitud de autorización" 'usuarios de crédito y cobranza
Dim Msg As String = String.Format("{0} - Folio {1} ", DdlSubProyectoDatos.SelectedItem.Text, TxtFolio.Text)
If UsuarioActual.CveEmpresa = 119 Then
ClsSisNotificaciones.SendNotificacionERP(1715, Titulo, Msg, 1)
ClsSisNotificaciones.SendNotificacionERP(1815, Titulo, Msg, 1)
ClsSisNotificaciones.SendNotificacionERP(1830, Titulo, Msg, 1)
End If
End If
ViewState("CveVenta") = ObjFactura.CveVenta
GVAnticipos.DataBind()
Try
Dim DirectoriArchivoXML As String = System.IO.Path.Combine(Server.MapPath("/"), "Empresas", UsuarioActual.CveEmpresa.ToString, ObjFactura.TipoDocto)
If Not Directory.Exists(DirectoriArchivoXML) Then
Directory.CreateDirectory(DirectoriArchivoXML)
End If
Catch ex As Exception
End Try
Dim SeTimbro As Boolean = False
Dim SeTimbroNC As Boolean = False
Dim EstatusSMS = 0
'TIMBRADO Y CASO ESPECIAL NOTA DE CREDITO
If (TipoDoctoDevolucion = "" OrElse Not TipoDoctoDevolucion.Contiene("Rem", "RNC", "Cot", "Ped", "DPe", "PA", "Pd2")) Then
Dim DebeTimbrar As Boolean = True
If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then
'si tiene anticipos seleccionados y el total es cero, que no se timbre(previo empresa72)
If LblAmortizacion.Text.ToDouble > 0 And TxtTotal.Text.ToDouble <= 0 Then
DebeTimbrar = False
End If
End If
If ObjFactura.TipoDocto.Contiene("Ing", "Egs", "Ant", "Dev") Then
If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then
'FACTURA INGRESO/EGRESO
Dim ObjTimbrado As New Timbrado
Dim FM As New Modelos.FemsaFactura
Dim TmpDT7Eleven As New DataTable
Dim TmpDTComplementosTimbrado As New DataTable
PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado)
'DOCUMENTO ACTUAL
If DebeTimbrar Then
SeTimbro = ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura)
'NOTA DE CREDITO - REFACTURADA - CASO ESPECIAL, TIMBRADO E IMPRESION
If Not IsNothing(Obj2) AndAlso Obj2.Count > 0 AndAlso SeTimbro Then
Dim ofa As Modelos.Factura = CType(Obj2(0), Modelos.Factura)
'asigna el foliofiscal del ingreso que se acaba de timbrar, cuando es amortización de anticipo con NC
If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then
ofa.Timbre.CFDIRelacionados.UUID.Clear()
ofa.Timbre.CFDIRelacionados.UUID.Add(ObjTimbrado.UUID)
End If
ObjTimbrado.TimbrarFactura(UsuarioActual, ofa)
GeneraPDFFactura(ChkEnviarFactura.Checked)
End If
If SeTimbro AndAlso ObjFactura.TipoDocto.Contiene("Ing") Then
EstatusSMS = EnviarSMSTimbrado(ObjEventos)
End If
If Not SeTimbro Then
Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgError)
End If
End If
'NOTA DE CREDITO DE REFACTURACION
If RefacturacionGeneroNC Then
If Not IsNothing(ObjNC) AndAlso ObjNC.Count > 0 Then
Dim ofa As Modelos.Factura = CType(ObjNC(0), Modelos.Factura)
SeTimbroNC = ObjTimbrado.TimbrarFactura(UsuarioActual, ofa)
End If
End If
ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then
GeneraPDFCBB(ObjFactura.Fecha, Nothing, ObjFactura.SerieFolio, False)
End If
End If
End If
'VERIFICAR 100% AVANCE A IMPORTE Y CANTIDAD
If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso CveContrato > 0 Then
If ObjContr.GetContratos(CveContrato, UsuarioActual.CveEmpresa) Then
If ObjContr.DtResultados.Rows.Count > 0 Then
' si es flexible que notifique el monto maximo, si no lo es que notifique el porcentaje alcanzado... flexible = 2, no flexible = 1
Dim PorcentajeAvance As Double = ObjContr.DtResultados.Rows(0)("ContratoAvance").ToString.ToDouble
If ObjContr.DtResultados.Rows(0)("ModalidadDetalle").ToString() = "1" Then
If PorcentajeAvance >= 100 Then
EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString())
End If
Else
Dim MontoMaximo As Double = ObjContr.DtResultados.Rows(0)("ImporteMax").ToString.ToDouble
If PorcentajeAvance >= 100 And MontoMaximo > 0 Then
EnviarNotificacionAvance(ObjContr.DtResultados.Rows(0)("NumeroContrato").ToString(), ObjContr.DtResultados.Rows(0)("DescripcionContrato").ToString(), ObjContr.DtResultados.Rows(0)("ContratoTipo").ToString(), ObjContr.DtResultados.Rows(0)("NombreComercial").ToString(), ObjContr.DtResultados.Rows(0)("CorreoVendedor").ToString(), MontoMaximo)
End If
End If
End If
End If
End If
'MENSAJE PRINCIPAL
MensajeAlert.AppendFormat(String.Format("<br/>La {0}: <b>{1}</b> se generó correctamente.<br/><br/>", 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("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar XML</a></li></ul>", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", ObjFactura.SerieFolio, ObjFactura.TipoDocto)))
End If
GeneraPDFFactura(ChkEnviarFactura.Checked) 'MANDA CORREO
End If
'DESCARGA PDF
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant", "Egs", "Dev", "Pd2") Then
'If Not ImprimeAlert Then
Dim ArchivoIngPyMe As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.mrt", UsuarioActual.Empresa.Ruta))
Dim ArchivoIng As New System.IO.FileInfo(String.Format("{0}Formatos/Factura.rdlc", UsuarioActual.Empresa.Ruta))
Dim ArchivoRem As New System.IO.FileInfo(String.Format("{0}Formatos/Remision.rdlc", UsuarioActual.Empresa.Ruta))
Dim ArchivoEgs As New System.IO.FileInfo(String.Format("{0}Formatos/NotaCredito.rdlc", UsuarioActual.Empresa.Ruta))
If ArchivoIng.Exists Or ArchivoRem.Exists Or ArchivoIngPyMe.Exists Or ArchivoEgs.Exists Then
MensajeAlert.AppendFormat("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar PDF</a></li></ul><br/>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta)))
Else
MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ")
End If
End If
'ERROR DE NO TIMBRADO
If Not SeTimbro And (DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Or DdlTipoComprobante.SelectedValue = "Ant") Then
MensajeAlert.AppendFormat("La factura no se pudo timbrar.</b> 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("<br/>La NC <b>#{0}</b> no se pudo timbrar.</b> 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("<br/><b>Notificación SMS:</b> enviado con éxito al cliente al celular: <b>{0}</b>", ObjFactura.Cliente.CobranzaTelefono)
Case 2
MensajeAlert.AppendFormat("<br/><b>Notificación SMS:</b> sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.")
Case 3
MensajeAlert.AppendFormat("<br/><b>Notificación SMS:</b> sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.")
End Select
'AUTO DESCARGAR PDF
If UsuarioActual.CveEmpresa.Contiene(72, 1) Then
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ant") Then
RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta))}'", "Imprimir")
End If
End If
'DESCARGAR PDF DE CICOVISA
'If UsuarioActual.CveEmpresa = 72 And CveCliente = 70381 Then
' If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") Then
' MensajeAlert.AppendFormat("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar Formato CICOVISA</a></li></ul><br/>", Encripta(String.Format("OP=CIC&CVEVENTA={0}", CveVenta)))
' End If
'End If
If DdlTipoComprobante.SelectedValue = "Cot" Then
If Not CveEmpresaCRM > 0 Then
If CveVenta > 0 Then MensajeAlert = New StringBuilder
Dim ArchivoCotizacion As New System.IO.FileInfo(String.Format("{0}Formatos/Cotizacion.rdlc", UsuarioActual.Empresa.Ruta))
If ArchivoCotizacion.Exists Then
MensajeAlert.AppendFormat("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar PDF</a></li></ul><br/>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=0", CveVenta)))
Else
MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ")
End If
GeneraPDFCotizacion(ChkEnviarFactura.Checked) ' MANDA CORREO
End If
ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then
If UsuarioActual.CveEmpresa.Contiene(81, 109) Then
EnviaPDFRemision(ChkEnviarFactura.Checked)
End If
End If
'ENVIA CORREO CON DETALLE DEL CONTRATO
If DdlTipoComprobante.SelectedValue.Contiene("DPe", "Ped") Then
If Not String.IsNullOrEmpty(CorreoNotificacionPedDev) Then
EnviarCorreoDevPed()
End If
End If
'MOVIMIENTO DE ALMACEN
If ObjFactura.Inv_CveMovimiento > 0 Then
MensajeAlert.AppendFormat("<br/><br/><b><a target='_blank' class='Texto' href=""/Inventarios/EntradasSalidas.aspx?CveMovimiento={0}"">Movimiento de Almacén</a></b><br/>", ObjFactura.Inv_CveMovimiento)
End If
If TieneAnticipo AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then
MensajeAlert.AppendFormat("<br/><br/><b> Se generó una Nota de crédito Folio: {0} amortizando el anticipo </b><br/>", ObjFacturaDevolucion.Folio)
End If
'MUESTA ALERT OK
' si es elrol 1165-Ventas,EMp:80, o la empresa 119, recarga ventas, para seguir registrando-.
Dim Liga = If(UsuarioActual.CveRol = 1165 Or UsuarioActual.CveEmpresa = 119, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", If(CveEmpresaCRM > 0, $"document.location.href=""/CRM/EmpresaCRM.aspx?CveEmpresaCRM={CveEmpresaCRM}"";", $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}&Opt=3"";"))
Alert(MensajeAlert.ToString, TipoMensaje.MsgInformacion, Liga)
'LIMPIA CONDICIONES DE PAGO - CONTADO
RBLPago.SelectedValue = "1"
LimpiaEscondeContado()
BtnEmitirImprimir.Visible = False
ObjFactura = Nothing
Else
ObjVentas.RollBack()
If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack()
For Each ErrorItem In ErrorList
Alert(ErrorItem, TipoMensaje.MsgAdvertencia)
Next
'MUESTA ALERT ERROR
Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError)
End If
ObjVentas.Dispose()
ObjConta.Dispose()
ObjInventario.Dispose()
ObjCGame.Dispose()
ObjContr.Dispose()
ObjDocCliente.Dispose()
'ObjFolios.Dispose()
ErrorList = Nothing
MensajeAlert = Nothing
If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose()
TmpDT = TmpDTError.Copy
Else
ObjVentas.RollBack()
If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack()
For Each ErrorItem In ErrorList
Alert(ErrorItem, TipoMensaje.MsgAdvertencia)
Next
'MUESTA ALERT ERROR
Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError)
ObjVentas.Dispose()
ObjConta.Dispose()
ObjInventario.Dispose()
ObjCGame.Dispose()
ObjContr.Dispose()
ObjDocCliente.Dispose()
'ObjFolios.Dispose()
ErrorList = Nothing
MensajeAlert = Nothing
If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose()
TmpDT = TmpDTError.Copy
End If
End If
End If
End Sub
Private Sub CreaObjetosVentaAmortizacion(ObjVentas As ClsVentas, FolioFiscalRelacionado As String, CveAnticipoPadre As Integer, Optional CveVentasPadre As Integer = -1)
ObjFacturaDevolucion = New Modelos.Factura
ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario
ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero
If CveVentasPadre > 0 Then
ObjFacturaDevolucion.CveVentaPadre = CveVentasPadre
ObjFacturaDevolucion.CveVentaRelacion = CveVentasPadre
Else
ObjFacturaDevolucion.CveVentaPadre = ObjVentas.CveVenta
ObjFacturaDevolucion.CveVentaRelacion = ObjVentas.CveVenta
End If
ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa
ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal)
ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked
ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero
ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text
ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}")
'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim
'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1)
ObjFacturaDevolucion.Serie = LblSerie.Text
ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second)
ObjFacturaDevolucion.CvePrePoliza = -1
ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero
ObjFacturaDevolucion.MetodoPago = ""
ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}")
ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim
' ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1)
' ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "")
'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim
'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim
ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito
ObjFacturaDevolucion.FormaPago = 0
ObjFacturaDevolucion.TipoDocto = "Egs"
ObjFacturaDevolucion.Fecha = Now
ObjFacturaDevolucion.Version = "3.3"
ObjFacturaDevolucion.CveMetodoPago33 = 1
ObjFacturaDevolucion.MetodoPago33 = "Pago en una sola exhibición"
ObjFacturaDevolucion.ClaveMetodoPagoSAT = "PUE"
ObjFacturaDevolucion.CveFormaPago33 = 21
ObjFacturaDevolucion.FormaPago33 = "Aplicación de anticipos"
ObjFacturaDevolucion.FormaPagoSAT33 = "30"
ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero
ObjFacturaDevolucion.UsoCFDI = DdlUsoCFDI.SelectedItem.Text
ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}")
ObjFacturaDevolucion.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero
ObjFacturaDevolucion.TipoRelacion = "07"
Dim Fol As New List(Of String)
Fol.Add(FolioFiscalRelacionado)
ObjFacturaDevolucion.UUIDRelacionados = Fol
Select Case ObjFacturaDevolucion.TipoDocto
Case "Ing"
ObjFacturaDevolucion.TipoDocumento = "Factura"
Case "REM"
ObjFacturaDevolucion.TipoDocumento = "Remision"
Case "Cot"
ObjFacturaDevolucion.TipoDocumento = "Cotizacion"
Case "Egs"
ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito"
Case "Dev"
ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución"
Case Else
ObjFacturaDevolucion.TipoDocumento = ""
End Select
If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then
ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto
End If
ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate
ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate
ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate
ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim
ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim
ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim
ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble
ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble
ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble)
ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate
ObjFacturaDevolucion.CveCorte = CveCorte
ObjFacturaDevolucion.CveMesa = -1
ObjFacturaDevolucion.NumeroPersonas = 0
ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto)
ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "")
ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero
ObjFacturaDevolucion.Entrega = Entrega
ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate
ObjFacturaDevolucion.CveVentaPadre = CveAnticipoPadre
ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate
ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero
ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero
ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1")
ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim
ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim
ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim
ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim
ObjFacturaDevolucion.MonedaAbreviatura = ""
'Totales, Y se llena TmpDTImpuestos
ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal
ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal
ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal
ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal
ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal
ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal
ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal
ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal
'ObjFactura.BZDescripcion = TxtBZDescripcion.Text.Trim
'ObjFactura.BZNombreCorto = TxtBZNombreCorto.Text.Trim
'ObjFactura.BZTotalLetra = TxtBZTotalLetra.Text.Trim
If TmpDTImpuestos Is Nothing Then
CreaDTImpuestos()
Else
TmpDTImpuestos.Clear()
End If
Dim DR As DataRow = TmpDTImpuestos.NewRow()
If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
'If DdlFormatoImpresion.SelectedValue.ToEntero = 3 Or DdlFormatoImpresion.SelectedValue.ToEntero = 4 Then
' DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (TxtSubTotal.Text.ToDecimal + TxtIVA.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal) : DR("Orden") = 55 : TmpDTImpuestos.Rows.Add(DR)
' DR = TmpDTImpuestos.NewRow()
'End If
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim Orden As Integer = 80
If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then
DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestos.Rows.Add(DR)
DR = TmpDTImpuestos.NewRow()
Orden = Orden + 1
End If
End If
Next
If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestos.Rows.Add(DR)
ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC")
'otros
ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim
ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim
ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero
If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then
ObjFacturaDevolucion.TipoCambio = 1
ObjFacturaDevolucion.CveMoneda = 1
End If
'DETALLES
ObjFacturaDevolucion.DtDetalle = TmpDT
ObjFacturaDevolucion.DtFirmas = DTmpF
'CLIENTE
ObjFacturaDevolucion.CveCliente = CveCliente
ObjFacturaDevolucion.SetCliente()
''SUCURSAL
'ObjFacturaDevolucion.CveSucursal = DdlSucursal.SelectedValue.ToEntero
'ObjFacturaDevolucion.SetSucursalMatriz(Me)
'ObjFacturaDevolucion.SetSucursal(Me)
ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel
ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt
ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt
ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad
ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text
ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text
ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text
ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text
ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text
ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais
ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString
ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text
ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "")
ObjFacturaDevolucion.SetSubProyectoMatriz(Me)
ObjFacturaDevolucion.SetSubProyecto(Me)
'ENVIO DIRECCION
ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel
If ChkDireccionEnvio.Checked Then
If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then
For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows
ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero
ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString
ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString
ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString
ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString
ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString
Next
End If
End If
If DtVentasNC Is Nothing Then InicializaDTVentasNC()
Dim Drt = DtVentasNC.NewRow
Drt("CveVenta") = ObjFactura.CveVenta
Drt("Importe") = 0
Drt("FolioFiscal") = ObjFactura.FolioFiscal
DtVentasNC.Rows.Add(Drt)
DtVentasNC.AcceptChanges()
End Sub
Private Function RegistrarNCAmortizacion(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean
Dim ProcesoCorrecto As Boolean = True
'Generamos el nuevo folio
Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL())
If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then
Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue.ToEntero))
If DT.Rows.Count > 0 Then
factura.Folio = DT.Rows(0)("FActual").ToString.ToEntero
Else
ProcesoCorrecto = False
End If
DT.Dispose()
End If
'** genero los datos de la NC
Dim tmpcon As DataTable = TmpDT.Clone
tmpcon.Clear()
Dim drpss As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlNCPSAnt.SelectedValue.ToEntero).FiltroPrimero("")
If drpss IsNot Nothing Then
Dim ii As Integer = 1
Dim CveVentaP As Integer = 0
For Each gvrt As GridViewRow In GVAnticipos.Rows
If gvrt.FCCheckBox(String.Format("Chk{0}", gvrt.RowIndex)).Checked Then
Dim CveSub As Integer = TmpDT.FiltroPrimeroValor("CveSubProyecto").ToEntero
Dim dr As DataRow = tmpcon.NewRow
Dim Cantidad As Decimal = 1
Dim PU As Decimal = gvrt.FCTextBox(String.Format("TxtAnticipo{0}", gvrt.RowIndex)).Text.ToDecimal
Dim TotalCalculableImpuestos As Decimal = (Cantidad * (PU))
dr("CvePS") = drpss("CvePS")
dr("PS") = drpss("PS")
dr("OBS") = drpss("PS")
dr("PU") = PU
dr("Cantidad") = Cantidad
dr("CveUM") = drpss("CveUnidadMedida")
dr("SATClaveProdServ") = "84111506"
dr("SATClaveUM") = "ACT"
dr("Consec") = ii
If drpss("IVA").ToString = "-1" Then
dr("PorcentajeIVA") = PorcentajeIVA ' GlobalDTSubProyectos(-1,cves DrPS("IVA")
Else
dr("PorcentajeIVA") = drpss("IVA")
End If
dr("IVA") = dr("PorcentajeIVA")
dr("ImporteIVA") = Math.Round(dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
dr("PorcentajeRetIVA") = ClienteRetIVA
dr("PorcentajeRetISR") = ClienteRetISR
If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then
dr("PorcentajeIEPS") = drpss("IEPSPorcentaje")
dr("ImporteIEPS") = Math.Round(drpss("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Else
dr("PorcentajeIEPS") = 0 ' DrPS("IEPSPorcentaje")
dr("ImporteIEPS") = 0 'Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
End If
dr("IEPS") = dr("ImporteIEPS")
dr("Descuento") = Math.Round(0, NumeroDecimales)
dr("TipoDescuento") = HdnTipoDescuento.Value
dr("Total") = (Cantidad * PU)
dr("CveClasificacion") = drpss("CveClasificacion")
dr("CveSubProyecto") = CveSub
dr("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales)
CveVentaP = gvrt.DataKey("CveVenta").ToEntero
tmpcon.Rows.Add(dr)
ii += 1
End If
Next
'**** impuestos locales
factura.DtDetalle = tmpcon
Dim TotalSubTotal As Decimal = tmpcon.SUM("TotalImporte").ToDecimal
Dim TotalDescuentos As Decimal = tmpcon.SUM("Descuento").ToDecimal
Dim TotalIVA As Decimal = tmpcon.SUM("ImporteIVA").ToDecimal
Dim TotalIEPS As Decimal = tmpcon.SUM("ImporteIEPS").ToDecimal
Dim TotalRetIVA As Decimal = tmpcon.SUM("ImporteRetIVA").ToDecimal
Dim TotalRetISR As Decimal = tmpcon.SUM("ImporteRetISR").ToDecimal
Dim Total As Decimal = 0
Dim TotalImpuestosLocales As Decimal = 0
Total = (TotalSubTotal - TotalDescuentos + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales)
factura.SubTotal = TotalSubTotal
factura.Descuento = 0
factura.IVA = TotalIVA
factura.IEPS = TotalIEPS
factura.RetIVA = TotalRetIVA
factura.RetISR = TotalRetISR
factura.Total = Total
factura.CveVentaPadre = CveVentaP
If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then
DtVentasNC.Rows(0)("Importe") = Total
End If
ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion)
'Registramos la venta
GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, tmpcon, -1, ObjContPaq, ObjBancos)
''Timbramos
'If factura.TipoDocto.Contiene("Ing", "Egs", "Ant") Then
' If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then
' Dim sw As New Diagnostics.Stopwatch
' sw.Start()
' ''factura INGRESO / EGRESO
' Dim ObjTimbrado As New Modelos.Timbrado
' Dim FM As New Modelos.FemsaFactura
' Dim TmpDT7Eleven As New DataTable
' Dim TmpDTComplementosTimbrado As New DataTable
' 'PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado)
' '**
' ObjTimbrado.TimbrarFactura(UsuarioActual, factura, FM, TmpDT, TmpDTImpuestos, TmpDT7Eleven, TmpDTComplementosTimbrado, Ruta, LstFordASN, TxtFordGSDB.Text)
' sw.Stop()
' 'GuardaLogTimbrado(sw.ElapsedMilliseconds.ToString, UsuarioActual.Empresa.CvePAC)
' End If
'End If
Else
ErrorList.Add("No se encontró un producto para generar la nota de crédito")
End If
Return ProcesoCorrecto
End Function
Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False)
If Me.CveVenta > 0 Then
ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa)
Else
ObjFactura = New Modelos.Factura
End If
ObjFactura.Version = "3.3"
ObjFactura.CveUsuario = UsuarioActual.CveUsuario
ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa
ObjFactura.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal)
ObjFactura.TipoCambioDolares = TxtTipoCambioDlls.Text.Trim.ToDecimal
ObjFactura.ConvertirPesos = ChkConvertirDoctoPesos.Checked
ObjFactura.ConvertirDolares = ChkConvertirDolares.Checked
ObjFactura.CveMoneda = DdlMoneda.SelectedValue.ToEntero
ObjFactura.Moneda = DdlMoneda.SelectedItem.Text
ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}")
ObjFactura.TipoDocto = If(IfNull(ViewState("CveRemision"), 0).ToString.ToEntero > 0, "Ing", DdlTipoComprobante.SelectedValue)
'ObjFactura.RefDocto = TxtDocto.Text.Trim
ObjFactura.Folio = If(EstablecioFolio Or VistaPrevia Or (CveVenta > 0 And (NuevaFactura.Contiene(0, 2))), TxtFolio.Text.Trim.ToEntero, -1)
'ObjFactura.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1)
ObjFactura.Serie = If(VistaPrevia, "VistaPrevia", LblSerie.Text)
ObjFactura.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second)
ObjFactura.CvePrePoliza = -1
ObjFactura.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero
ObjFactura.MetodoPago = "" ' DdlMetodoPago.SelectedItem.Text
ObjFactura.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}")
ObjFactura.FechaVencimiento = TxtFechaPago.Text.ToDate
' If ObjFactura.TipoDocto = "Cot" Then
ObjFactura.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero
ObjFactura.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero > 0, DdlMetodoPago33.SelectedItem.Text, "")
ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}")
ObjFactura.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero
ObjFactura.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero > 0, DdlFormaPago33.SelectedItem.Text, "")
ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}")
ObjFactura.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero
ObjFactura.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero > 0, DdlUsoCFDI.SelectedItem.Text, "")
ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}")
' End If
ObjFactura.UsuarioCreo = LblUsuario.Text.Trim
ObjFactura.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1)
ObjFactura.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "")
'ObjFactura.NumeroCuenta = TxtNumCtaPago.Text.Trim
'ObjFactura.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim
ObjFactura.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, If(RBLPago.SelectedValue = "1", 1, 2)) ' 0 - Contado, 1 - Credito, 2 - termianl
ObjFactura.FormaPago = 0 'DdlFormaPago.SelectedValue.ToEntero
'ObjFactura.AnticipoPosicion = DdlAmortizacionConceptos.SelectedValue.ToEntero
'ObjFactura.AnticipoEnSubTotal = If(ChkAnticipoEnSubTotal.Checked, True, False)
'ObjFactura.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero
'ObjFactura.CveTipoAmortizacionAnticipo = DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero
'ObjFactura.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text)
'ObjFactura.PedidoContrato = TxtPedidoContrato.Text.Trim
ObjFactura.AtnA = TxtAtencionA.Text
ObjFactura.FordGSDB = ""
ObjFactura.NumeroContrato = NumeroContrato
ObjFactura.DescripcionContrato = DescripcionContrato
ObjFactura.NumeroDescripcionContrato = If($"{NumeroContrato} - {NumeroLicitacion}" = " - ", "", $"{NumeroContrato} {If(NumeroLicitacion = "", "", $" - Licitación: {NumeroLicitacion}")}")
ObjFactura.PedidoContrato = If(TxtPedidoContrato.Text.Trim = "", ObjFactura.NumeroDescripcionContrato, $"{TxtPedidoContrato.Text.Trim} {If(ObjFactura.NumeroDescripcionContrato = "", "", $" / {ObjFactura.NumeroDescripcionContrato}") }")
ObjFactura.OrdenCompra = TxtOrdenCompra.Text.Trim
Select Case ObjFactura.TipoDocto
Case "Ing"
ObjFactura.TipoDocumento = "Factura"
Case "Rem"
ObjFactura.TipoDocumento = "Remision"
Case "Cot"
ObjFactura.TipoDocumento = "Cotizacion"
Case "Egs"
ObjFactura.TipoDocumento = "Nota de Crédito"
Case "Dev"
ObjFactura.TipoDocumento = "Nota de Devolución"
Case "DPe"
ObjFactura.TipoDocumento = "Devolución de pedido"
Case "PeC"
ObjFactura.TipoDocumento = "Consignación de Pedido"
Case Else
ObjFactura.TipoDocumento = ""
End Select
ObjFactura.Fech1 = TxtFech1.Text.Trim.ToDate
ObjFactura.Fech2 = TxtFech2.Text.Trim.ToDate
ObjFactura.Fech3 = TxtFech3.Text.Trim.ToDate
ObjFactura.Alfa1 = TxtAlfa1.Text.Trim
ObjFactura.Alfa2 = TxtAlfa2.Text.Trim
ObjFactura.Alfa3 = TxtAlfa3.Text.Trim
ObjFactura.Num1 = TxtNum1.Text.Trim.ToDouble
ObjFactura.Num2 = TxtNum2.Text.Trim.ToDouble
ObjFactura.Num3 = If(ObjFactura.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble)
If divcondicionespago.Visible Then
ObjFactura.FechaPago = TxtFechaPago.Text.ToDate
Else
ObjFactura.FechaPago = Now
End If
ObjFactura.DiasCredito = DiasCredito
ObjFactura.EsDiasCreditoFijo = EsDiasCreditoFijo
ObjFactura.CveCorte = CveCorte
ObjFactura.CveMesa = -1
ObjFactura.NumeroPersonas = 0
ObjFactura.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto)
ObjFactura.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero
ObjFactura.Entrega = Entrega
ObjFactura.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate
ObjFactura.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, If(CvePedido2 > 0, CvePedido2, CvePedido))
If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then
ObjFactura.CveVentaPadre = DtVentasNC.Rows(0)("CveVenta").ToString.ToEntero
ObjFactura.SerieFolioPadre = DtVentasNC.Rows(0)("FolioFiscal").ToString
End If
ObjFactura.CveVendedor = DdlVendedor.SelectedValue.ToEntero
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
ObjFactura.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate
ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFactura.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero
ObjFactura.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero
ObjFactura.AtencionA = If(ObjFactura.TipoDocto = "Cot" Or (ObjFactura.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1")
ObjFactura.MotivoDescuento = TxtMotivoDescuento.Text.Trim
ObjFactura.Observaciones = TxtObsFact.Text.Trim
ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim
ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim
ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim
ObjFactura.MonedaAbreviatura = ""
'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS
If (ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble * ObjFactura.TipoCambio, 6)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Next
Dim ImpuestosLocales As Double = 0
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio).FormatoNumero
If gvr.DataKey("TipoImpuesto").ToString = "5" Then
ImpuestosLocales -= Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Else
ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
End If
End If
Next
ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal
ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal
ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales)
ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal
ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal
ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal
ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal
ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal
TipoCambioRemision = ObjFactura.TipoCambio
ObjFactura.TipoCambio = 1
ObjFactura.ConvertirPesos = False
ConversionRemision = "/"
'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES
ElseIf (ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True AndAlso ObjFactura.TipodeComprobante = "Ingresos" AndAlso RemisionesLista.Count > 0) Then
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble / ObjFactura.TipoCambioDolares, 6)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Next
Dim ImpuestosLocales As Double = 0
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero
ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
End If
Next
ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal
ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal
ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales)
ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal
ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal
ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal
ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal
ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal
TipoCambioRemision = ObjFactura.TipoCambioDolares
ObjFactura.TipoCambioDolares = 1
ObjFactura.ConvertirDolares = False
ConversionRemision = "*"
'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS REGISTRO DIRECTO SIN VENTA
ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 2 AndAlso ObjFactura.ConvertirPesos = True) Then
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble * ObjFactura.TipoCambio, 6)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
Next
Dim ImpuestosLocales As Double = 0
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio).FormatoNumero
ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * ObjFactura.TipoCambio, NumeroDecimales)
End If
Next
ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal
ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal
ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * ObjFactura.TipoCambio, NumeroDecimales)
ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal
ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal
ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal
ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal
ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal
TipoCambioRemision = ObjFactura.TipoCambio
ObjFactura.TipoCambio = 1
ObjFactura.ConvertirPesos = False
ConversionRemision = "/"
'CONVERTIR REMISION - TIPO MONEDA -PESOS A DOLARES REGISTRO DIRECTO SIN VENTA
ElseIf (EditoRemision = False AndAlso ObjFactura.CveMoneda = 1 AndAlso ObjFactura.ConvertirDolares = True) Then
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble / ObjFactura.TipoCambioDolares, 6)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
Next
Dim ImpuestosLocales As Double = 0
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares).FormatoNumero
ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / ObjFactura.TipoCambioDolares, NumeroDecimales)
End If
Next
ObjFactura.SubTotal = TmpDT.SUM("Total").ToDecimal
ObjFactura.Descuento = TmpDT.SUM("Descuento").ToDecimal
ObjFactura.Amortizacion = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / ObjFactura.TipoCambioDolares, NumeroDecimales)
ObjFactura.IVA = TmpDT.SUM("ImporteIVA").ToDecimal
ObjFactura.RetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal
ObjFactura.RetISR = TmpDT.SUM("ImporteRetISR").ToDecimal
ObjFactura.IEPS = TmpDT.SUM("ImporteIEPS").ToDecimal
ObjFactura.Total = (ObjFactura.SubTotal - ObjFactura.Descuento - ObjFactura.Amortizacion + ObjFactura.IVA + ObjFactura.IEPS - ObjFactura.RetIVA - ObjFactura.RetISR - ImpuestosLocales).ToDecimal
TipoCambioRemision = ObjFactura.TipoCambioDolares
ObjFactura.TipoCambioDolares = 1
ObjFactura.ConvertirDolares = False
ConversionRemision = "*"
Else
'Totales, Y se llena TmpDTImpuestos
ObjFactura.SubTotal = TxtSubTotal.Text.ToDecimal
ObjFactura.Descuento = LblDescuentos.Text.Trim.ToDecimal
ObjFactura.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal
ObjFactura.IVA = TxtIVA.Text.ToDecimal
ObjFactura.RetIVA = TxtRetIVA.Text.ToDecimal
ObjFactura.RetISR = TxtRetISR.Text.ToDecimal
ObjFactura.IEPS = TxtIEPS.Text.ToDecimal
ObjFactura.Total = TxtTotal.Text.ToDecimal
End If
Dim TmpSubtotal As Decimal = TxtSubTotal.Text.ToDecimal - ObjFactura.Descuento
Dim TmpAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal
ObjFactura.DtDetalle = TmpDT
If AplicaFord Then
ObjFactura.FordGSDB = TxtFordGSDB.Text
Dim SB As New StringBuilder
For Each li As ListItem In LstFordASN.Items
SB.AppendFormat("{0}, ", li.Text)
Next
ObjFactura.FordASN = SB.ToString
End If
If TmpDTImpuestos Is Nothing Then CreaDTImpuestos()
Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone()
Dim DR As DataRow = TmpDTImpuestosVista.NewRow()
If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = ObjFactura.SubTotal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = ObjFactura.Descuento : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = ObjFactura.Amortizacion : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
'If TxtIVA.Text.ToDecimal <> 0 Then
DR("ImpuestoLocal") = "IVA" : DR("Importe") = ObjFactura.IVA : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = ObjFactura.RetIVA : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = ObjFactura.RetISR : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtIEPS.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IEPS" : DR("Importe") = ObjFactura.IEPS : DR("Orden") = 80 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim Orden As Integer = 80
If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then
DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
Orden = Orden + 1
End If
End If
Next
If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = ObjFactura.Total : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
ObjFactura.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC")
'TmpDT DESGLOSE DE IMPUESTOS 3.3
If UsuarioActual.CveEmpresa.Contiene(119) Then
If TmpDTDocumentosRelacionados IsNot Nothing Then
ObjFactura.DtDocumentosRelacionados = TmpDTDocumentosRelacionados
End If
If TmpDTNCVinculadas IsNot Nothing Then
ObjFactura.DtNCVinculadas = TmpDTNCVinculadas
End If
End If
CreaDTImpuestosIVAIEPS()
For Each DrImpuestos33 As DataRow In TmpDT.Rows
Dim DrIVA As DataRow = Nothing
Dim DrIEPS As DataRow = Nothing
Try
DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0)
Catch ex As Exception
DrIVA = Nothing
End Try
If DrIVA IsNot Nothing Then
DrIVA("Importe") = DrIVA("Importe").ToString.ToDouble + DrImpuestos33("ImporteIVA").ToString.ToDouble
TmpDTImpuestosIVAIEPS.AcceptChanges()
Else
Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow()
If DrImpuestos33("PorcentajeIVA").ToString.ToDecimal > 0 Then
DR2("Impuesto") = "IVA" : DR2("tasa") = DdlIVA.SelectedItem.ToString : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString.ToDecimal : DR2("Orden") = "1"
TmpDTImpuestosIVAIEPS.Rows.Add(DR2)
TmpDTImpuestosIVAIEPS.AcceptChanges()
End If
End If
Try
DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString.ToDecimal * 100} %'")(0)
Catch ex As Exception
DrIEPS = Nothing
End Try
If DrIEPS IsNot Nothing Then
DrIEPS("Importe") = DrIEPS("Importe").ToString.ToDouble + DrImpuestos33("ImporteIEPS").ToString.ToDouble
TmpDTImpuestosIVAIEPS.AcceptChanges()
Else
Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow()
If DrImpuestos33("PorcentajeIEPS").ToString.ToDouble > 0 Then
DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString.ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.09", "5", "0"))))
TmpDTImpuestosIVAIEPS.Rows.Add(DR2)
TmpDTImpuestosIVAIEPS.AcceptChanges()
End If
End If
Next
ObjFactura.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC")
'otros
ObjFactura.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim
ObjFactura.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim
ObjFactura.Det_ContraRecibo = TxtDet_ContraRecibo.Text.Trim
ObjFactura.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero
If ObjFactura.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then
ObjFactura.TipoCambio = 1
ObjFactura.CveMoneda = 1
ObjFactura.Moneda = "Pesos"
ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}")
End If
If ObjFactura.CveMoneda <> 2 AndAlso ChkConvertirDolares.Checked Then
ObjFactura.TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal
ObjFactura.CveMoneda = 2
ObjFactura.Moneda = "Dólares"
ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}")
End If
'Se agrega CveVenta -1
For Each Row As DataRow In TmpDT.Rows
Row("CveVenta") = ObjFactura.CveVenta
Next
'DETALLES
ObjFactura.DtDetalle = TmpDT.Copy
ObjFactura.DtFirmas = DTmpF.Copy
'CLIENTE
ObjFactura.CveCliente = CveCliente
ObjFactura.SetCliente()
'SUCURSAL
'ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFactura.SetSubProyectoMatriz(Me)
ObjFactura.SetSubProyecto(Me)
ObjFactura.ClienteSucursal = New Modelos.SucursalModel
If Not CveEmpresaCRM > 0 Then
ObjFactura.ClienteSucursal.NoExt = CliNoExt
ObjFactura.ClienteSucursal.NoInt = CliNoInt
ObjFactura.ClienteSucursal.Localidad = CliLocalidad
ObjFactura.ClienteSucursal.Direccion = LblDireccion.Text
ObjFactura.ClienteSucursal.Colonia = LblColonia.Text
ObjFactura.ClienteSucursal.Municipio = LblCiudad.Text
ObjFactura.ClienteSucursal.Estado = LblEstado.Text
ObjFactura.ClienteSucursal.CP = LblCP.Text
ObjFactura.ClienteSucursal.Pais = CliPais
ObjFactura.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString
ObjFactura.ClienteSucursal.TelefonoSucursal = LblTelefono.Text
ObjFactura.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "")
ObjFactura.ClienteSucursal.ImprimeNombreSucursal = ImprimeNombreSucursal.ToString
End If
'ENVIO DIRECCION
ObjFactura.EnviarA = New Modelos.EnviarAModel
If ChkDireccionEnvio.Checked Then
If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then
For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows
ObjFactura.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero
ObjFactura.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString
ObjFactura.EnviarA.EnvioNoExt = Row("EnvioNoExt").ToString
ObjFactura.EnviarA.EnvioNoInt = Row("EnvioNoInt").ToString
ObjFactura.EnviarA.EnvioColonia = Row("EnvioColonia").ToString
ObjFactura.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString
ObjFactura.EnviarA.EnvioEstado = Row("EnvioEstado").ToString
ObjFactura.EnviarA.EnvioCP = Row("EnvioCP").ToString
ObjFactura.EnviarA.EnvioTel = Row("EnvioTel").ToString
ObjFactura.EnviarA.EnvioContacto = Row("EnvioContacto").ToString
ObjFactura.EnviarA.EnvioDepartamento = Row("EnvioDepartamento").ToString
'ObjFactura.EnviarA.EnvioPedidoContrato = Row("EnvioPedidoContrato").ToString
Next
End If
End If
'Amortizacion
ObjFactura.CveTipoRelacion = DdlTipoRelacion.SelectedValue.ToEntero
If ObjFactura.CveTipoRelacion > 0 Then
Select Case ObjFactura.CveTipoRelacion
Case 7
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07"
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo"
ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value)
End Select
End If
ObjFactura.AplicaDevolucion = Me.AplicaDevolucion
ObjFactura.CveTipoAmortizacionAnticipo = DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero
If ObjFactura.Timbre.Comprobante.TipoComprobante = "E" Then
If ObjFactura.TipoDocumento.Contiene("Nota de Crédito") Then
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "01"
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso"
End If
If ObjFactura.TipoDocumento.Contiene("Nota de Devolución") Then
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "03"
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso"
End If
ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value)
End If
' cuando es refacturacoin es cfdirelacionado, con relacion 04
If ObjFactura.Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "04"
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso"
ObjFactura.Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value)
End If
If ObjFactura.TipoDocto = "Egs" Then
ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero
End If
If ObjFactura.TipoDocto = "Dev" Then
ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero
End If
If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso NuevaFactura = 1 Then ' refacturación
ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero
End If
If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso DdlTiposRelacion.SelectedValue.ToEntero > 0 Then ' refacturación
ObjFactura.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero
If GVAnticipos.Rows.Count > 0 Then
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox(String.Format("Chk{0}", gvr.RowIndex)).Checked AndAlso gvr.DataKey("CveConceptoContable") = "12" Then ' solo notas de crédito
If DtVentasNC Is Nothing Then InicializaDTVentasNC()
Dim Drt = DtVentasNC.NewRow
Drt("CveVenta") = gvr.DataKey("CveVenta")
Drt("Importe") = gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text
Drt("FolioFiscal") = gvr.DataKey("FolioFiscal")
DtVentasNC.Rows.Add(Drt)
End If
Next
End If
End If
If Not CveEmpresaCRM > 0 Then ObjFactura.Timbre = PreParaTimbre(ObjFactura)
'RMF. faltan impuestos locales
If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 1").Rows.Count > 0 Then
For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 1").Rows
If DrImpuestosLocales("Importe").ToString.ToDecimal > 0 Then
Dim ret As New CFDIRetencionesLocales With {.TasaRetencion = DrImpuestosLocales("Porcentaje").ToString.ToDecimal, .ImpuestoLocalRetenido = DrImpuestosLocales("ImpuestoLocal").ToString, .Importe = DrImpuestosLocales("Importe").ToString.ToDecimal(If(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1))}
ObjFactura.Timbre.RetencionesLocales.Add(ret)
End If
Next
End If
If TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows.Count > 0 Then
For Each DrImpuestosLocales As DataRow In TmpDTImpuestos.FiltraParametros("TipoImpuesto = 5").Rows
If DrImpuestosLocales("Importe").ToString.ToDecimal > 0 Then
Dim ret As New CFDITrasladosLocales With {.TasaTraslado = DrImpuestosLocales("Porcentaje").ToString.ToDecimal, .ImpuestoLocalTraslado = DrImpuestosLocales("ImpuestoLocal").ToString, .Importe = DrImpuestosLocales("Importe").ToString.ToDecimal(If(ObjFactura.ConvertirPesos, ObjFactura.TipoCambio, 1))}
ObjFactura.Timbre.TrasladosLocales.Add(ret)
End If
Next
End If
'INE COMPLEMENTO
If RblComplementos.SelectedValue.ToEntero > 0 Then
ObjFactura.CveComplementoTimbrado = RblComplementos.SelectedValue.ToEntero
Dim INE As New Modelos.ComplementoINE
Select Case RblComplementos.SelectedValue.ToEntero
Case 5
INE.INEIdContabilidad = TxtIdConta.Text.ToEntero
INE.INETipoProceso = "Ordinario"
INE.INETipoComite = "Directivo Estatal"
INE.INEEntidad = DdlINEEntidad.SelectedValue
Case 6
INE.INEIdContabilidad = TxtIdConta.Text.ToEntero
INE.INETipoProceso = "Ordinario"
INE.INETipoComite = "Ejecutivo Estatal"
INE.INEEntidad = DdlINEEntidad.SelectedValue
Case 7
INE.INEIdContabilidad = TxtIdConta.Text.ToEntero
INE.INETipoProceso = "Ordinario"
INE.INETipoComite = "Ejecutivo Nacional"
Case 8
INE.INEIdContabilidad = TxtIdConta.Text.ToEntero
INE.INETipoProceso = DdlTipoCampaña.SelectedValue
INE.INETipoComite = DdlAmbitoComplemento.SelectedValue
INE.INEEntidad = DdlINEEntidad.SelectedValue
Case Else
INE.INEIdContabilidad = 0
INE.INETipoProceso = ""
INE.INETipoComite = ""
INE.INEEntidad = ""
End Select
ObjFactura.ComplementoINE = INE
End If
End Sub
Private Sub CreaObjetosVentaDevolucion()
ObjFacturaDevolucion = New Modelos.Factura
ObjFacturaDevolucion.CveUsuario = UsuarioActual.CveUsuario
ObjFacturaDevolucion.CveEmpresa = UsuarioActual.CveEmpresa
ObjFacturaDevolucion.TipoCambio = If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.Trim.ToDecimal)
ObjFacturaDevolucion.ConvertirPesos = ChkConvertirDoctoPesos.Checked
ObjFacturaDevolucion.CveMoneda = DdlMoneda.SelectedValue.ToEntero
ObjFacturaDevolucion.Moneda = DdlMoneda.SelectedItem.Text
ObjFacturaDevolucion.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}")
'ObjFacturaDevolucion.RefDocto = TxtDocto.Text.Trim
'ObjFacturaDevolucion.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1)
ObjFacturaDevolucion.Serie = LblSerie.Text
ObjFacturaDevolucion.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second)
ObjFacturaDevolucion.CvePrePoliza = -1
ObjFacturaDevolucion.CveMetodoPago = 0 'DdlMetodoPago.SelectedValue.ToEntero
ObjFacturaDevolucion.MetodoPago = "" 'DdlMetodoPago.SelectedItem.Text
ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}")
ObjFacturaDevolucion.UsuarioCreo = LblUsuario.Text.Trim
ObjFacturaDevolucion.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1)
ObjFacturaDevolucion.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "")
'ObjFacturaDevolucion.NumeroCuenta = TxtNumCtaPago.Text.Trim
'ObjFacturaDevolucion.Cliente.NumCtaPago = TxtNumCtaPago.Text.Trim
ObjFacturaDevolucion.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, 1) ' 0 - Contado, 1 - Credito
ObjFacturaDevolucion.FormaPago = 0
'ObjFacturaDevolucion.SerieFolio = String.Format("{0}-{1}", LblSerie.Text, TxtFolio.Text)
ObjFacturaDevolucion.TipoDocto = "Egs"
ObjFacturaDevolucion.Fecha = Now
'VALORES DEFAULT DE NC-DEV
Dim CveUsoCFDIOld = DdlUsoCFDI.SelectedValue
Dim MetodoPago33Old = DdlMetodoPago33.SelectedValue
Dim FormaPago33Old = DdlFormaPago33.SelectedValue
DdlUsoCFDI.SelectedValueExist("2")
DdlMetodoPago33.SelectedValueExist("1")
DdlFormaPago33.SelectedValueExist("20")
ObjFacturaDevolucion.SerieFolioPadre = HdnFolioFiscalNC.Value.ToString
ObjFacturaDevolucion.Version = "3.3"
ObjFacturaDevolucion.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero
ObjFacturaDevolucion.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero > 0, DdlMetodoPago33.SelectedItem.Text, "")
ObjFacturaDevolucion.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}")
ObjFacturaDevolucion.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero
ObjFacturaDevolucion.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero > 0, DdlFormaPago33.SelectedItem.Text, "")
ObjFacturaDevolucion.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}")
ObjFacturaDevolucion.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero
ObjFacturaDevolucion.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero > 0, DdlUsoCFDI.SelectedItem.Text, "")
ObjFacturaDevolucion.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}")
DdlUsoCFDI.SelectedValueExist(CveUsoCFDIOld)
DdlMetodoPago33.SelectedValueExist(MetodoPago33Old)
DdlFormaPago33.SelectedValueExist(FormaPago33Old)
Select Case ObjFacturaDevolucion.TipoDocto
Case "Ing"
ObjFacturaDevolucion.TipoDocumento = "Factura"
Case "Rem"
ObjFacturaDevolucion.TipoDocumento = "Remision"
Case "Cot"
ObjFacturaDevolucion.TipoDocumento = "Cotizacion"
Case "Egs"
ObjFacturaDevolucion.TipoDocumento = "Nota de Crédito"
Case "Dev"
ObjFacturaDevolucion.TipoDocumento = "Nota de Devolución"
Case Else
ObjFacturaDevolucion.TipoDocumento = ""
End Select
If ObjFacturaDevolucion.TipoDocto IsNot Nothing Then
ViewState("TipoDoctoDevolucion") = ObjFacturaDevolucion.TipoDocto
End If
ObjFacturaDevolucion.CveTipoRelacion = DdlTiposRelacion.SelectedValue.ToEntero
ObjFacturaDevolucion.Fech1 = TxtFech1.Text.Trim.ToDate
ObjFacturaDevolucion.Fech2 = TxtFech2.Text.Trim.ToDate
ObjFacturaDevolucion.Fech3 = TxtFech3.Text.Trim.ToDate
ObjFacturaDevolucion.Alfa1 = TxtAlfa1.Text.Trim
ObjFacturaDevolucion.Alfa2 = TxtAlfa2.Text.Trim
ObjFacturaDevolucion.Alfa3 = TxtAlfa3.Text.Trim
ObjFacturaDevolucion.Num1 = TxtNum1.Text.Trim.ToDouble
ObjFacturaDevolucion.Num2 = TxtNum2.Text.Trim.ToDouble
ObjFacturaDevolucion.Num3 = If(ObjFacturaDevolucion.TipoDocto = "OP", DdlOrdenPago.SelectedValue.ToDouble, TxtNum3.Text.Trim.ToDouble)
ObjFacturaDevolucion.FechaPago = TxtFechaPago.Text.ToDate
ObjFacturaDevolucion.CveCorte = CveCorte
ObjFacturaDevolucion.CveMesa = -1
ObjFacturaDevolucion.NumeroPersonas = 0
ObjFacturaDevolucion.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto)
ObjFacturaDevolucion.DescripcionContrato = If(DdlContratosModal.SelectedItem IsNot Nothing, DdlContratosModal.SelectedItem.Text, "")
ObjFacturaDevolucion.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero
ObjFacturaDevolucion.Entrega = Entrega
ObjFacturaDevolucion.Vigencia = TxtFechaVencimientoCotizacion.Text.ToDate
ObjFacturaDevolucion.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, CvePedido)
ObjFacturaDevolucion.CveVendedor = DdlVendedor.SelectedValue.ToEntero
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
ObjFacturaDevolucion.FechaEjecucion = TxtFechaEjecucion.Text.Trim.ToDate
'ObjFacturaDevolucion.CveSucursalEjecucion = DdlSucursalEjecucion.SelectedValue.ToEntero
'ObjFacturaDevolucion.CveSucursalCobranza = DdlSucursalCobranza.SelectedValue.ToEntero
ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFacturaDevolucion.CveSubProyectoCobranza = DdlSubProyectoCobranza.SelectedValue.ToEntero
ObjFacturaDevolucion.CveSubProyectoEjecucion = DdlSubProyectoEjecucion.SelectedValue.ToEntero
ObjFacturaDevolucion.AtencionA = If(ObjFacturaDevolucion.TipoDocto = "Cot" Or (ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem") AndAlso LblRFC.Text = "XAXX010101000"), TxtAtencionA.Text, "-1")
ObjFacturaDevolucion.MotivoDescuento = TxtMotivoDescuento.Text.Trim
ObjFacturaDevolucion.Observaciones = TxtObsFact.Text.Trim
ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim
ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim
ObjFacturaDevolucion.MonedaAbreviatura = ""
'Totales, Y se llena TmpDTImpuestos
ObjFacturaDevolucion.SubTotal = TxtSubTotal.Text.ToDecimal
ObjFacturaDevolucion.Descuento = LblDescuentos.Text.Trim.ToDecimal
ObjFacturaDevolucion.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal
ObjFacturaDevolucion.IVA = TxtIVA.Text.ToDecimal
ObjFacturaDevolucion.RetIVA = TxtRetIVA.Text.ToDecimal
ObjFacturaDevolucion.RetISR = TxtRetISR.Text.ToDecimal
ObjFacturaDevolucion.IEPS = TxtIEPS.Text.ToDecimal
ObjFacturaDevolucion.Total = TxtTotal.Text.ToDecimal
If TmpDTImpuestos Is Nothing Then
CreaDTImpuestos()
End If
Dim TmpDTImpuestosVista As DataTable = TmpDTImpuestos.Clone()
Dim DR As DataRow = TmpDTImpuestosVista.NewRow()
If TxtSubTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "SubTotal" : DR("Importe") = TxtSubTotal.Text.ToDecimal : DR("Orden") = 10 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If LblDescuentos.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = LblDescuentos.Text.Trim.ToDecimal : DR("Orden") = 20 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If LblAmortizacion.Text.Trim.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = LblAmortizacion.Text.Trim.ToDecimal : DR("Orden") = 30 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtSubTotal2.Text.ToDecimal <> TxtSubTotal.Text.ToDecimal Then DR("ImpuestoLocal") = "SubTotal 2" : DR("Importe") = TxtSubTotal2.Text.ToDecimal : DR("Orden") = 40 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = TxtIVA.Text.ToDecimal : DR("Orden") = 50 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtRetIVA.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = TxtRetIVA.Text.ToDecimal : DR("Orden") = 60 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
If TxtRetISR.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = TxtRetISR.Text.ToDecimal : DR("Orden") = 70 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim Orden As Integer = 80
If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble > 0 Then
DR("ImpuestoLocal") = gvr.DataKey("ImpuestoLocal").ToString : DR("Importe") = gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble : DR("Orden") = Orden : DR("Porcentaje") = gvr.DataKey("Porcentaje").ToString : DR("TipoImpuesto") = gvr.DataKey("TipoImpuesto").ToString : DR("IdCtaContable") = gvr.DataKey("IdCtaContable").ToString.ToEntero : TmpDTImpuestosVista.Rows.Add(DR)
DR = TmpDTImpuestosVista.NewRow()
Orden = Orden + 1
End If
End If
Next
If TxtTotal.Text.ToDecimal <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = TxtTotal.Text.ToDecimal : DR("Orden") = 100 : DR("TipoImpuesto") = "0" : TmpDTImpuestosVista.Rows.Add(DR)
ObjFacturaDevolucion.DtDeduccion = TmpDTImpuestosVista.FiltraParametros("", Orderby:="Orden ASC")
CreaDTImpuestosIVAIEPS()
For Each DrImpuestos33 As DataRow In TmpDT.Rows
Dim DrIVA As DataRow = Nothing
Dim DrIEPS As DataRow = Nothing
Try
DrIVA = TmpDTImpuestosIVAIEPS.Select("Impuesto = 'IVA'")(0)
Catch ex As Exception
DrIVA = Nothing
End Try
If DrIVA IsNot Nothing Then
DrIVA("Importe") = DrIVA("Importe").ToString.ToDouble + DrImpuestos33("ImporteIVA").ToString.ToDouble
TmpDTImpuestosIVAIEPS.AcceptChanges()
Else
Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow()
If DrImpuestos33("PorcentajeIVA").ToString.ToDouble >= 0 Then
DR2("Impuesto") = "IVA" : DR2("tasa") = "16 %" : DR2("Importe") = DrImpuestos33("ImporteIVA").ToString.ToDouble : DR2("Orden") = "1"
TmpDTImpuestosIVAIEPS.Rows.Add(DR2)
TmpDTImpuestosIVAIEPS.AcceptChanges()
End If
End If
Try
DrIEPS = TmpDTImpuestosIVAIEPS.Select($"Impuesto = 'IEPS' AND tasa = '{DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100} %'")(0)
Catch ex As Exception
DrIEPS = Nothing
End Try
If DrIEPS IsNot Nothing Then
DrIEPS("Importe") = DrIEPS("Importe").ToString.ToDouble + DrImpuestos33("ImporteIEPS").ToString.ToDouble
TmpDTImpuestosIVAIEPS.AcceptChanges()
Else
Dim DR2 As DataRow = TmpDTImpuestosIVAIEPS.NewRow()
If DrImpuestos33("PorcentajeIEPS").ToString.ToDouble > 0 Then
DR2("Impuesto") = "IEPS" : DR2("tasa") = String.Format("{0} {1}", DrImpuestos33("PorcentajeIEPS").ToString.ToDouble * 100, "%") : DR2("Importe") = DrImpuestos33("ImporteIEPS").ToString.ToDouble : DR2("Orden") = If(DrImpuestos33("PorcentajeIEPS").ToString = "0.03", "2", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.06", "3", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.07", "4", If(DrImpuestos33("PorcentajeIEPS").ToString = "0.09", "5", ""))))
TmpDTImpuestosIVAIEPS.Rows.Add(DR2)
TmpDTImpuestosIVAIEPS.AcceptChanges()
End If
End If
Next
ObjFacturaDevolucion.DtDesgloseImpuestos = TmpDTImpuestosIVAIEPS.FiltraParametros("", Orderby:="Orden ASC")
'otros
ObjFacturaDevolucion.Det_FechaOrdenCompra = TxtDet_FechaOrdenCompra.Text.Trim
ObjFacturaDevolucion.Det_OrdenCompra = TxtDet_OrdenCompra.Text.Trim
ObjFacturaDevolucion.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero
If ObjFacturaDevolucion.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then
ObjFacturaDevolucion.TipoCambio = 1
ObjFacturaDevolucion.CveMoneda = 1
End If
'DETALLES
ObjFacturaDevolucion.DtDetalle = TmpDT
ObjFacturaDevolucion.DtFirmas = DTmpF
'CLIENTE
ObjFacturaDevolucion.CveCliente = CveCliente
ObjFacturaDevolucion.SetCliente()
'SUCURSAL
ObjFacturaDevolucion.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFacturaDevolucion.SetSubProyectoMatriz(Me)
ObjFacturaDevolucion.SetSubProyecto(Me)
ObjFacturaDevolucion.ClienteSucursal = New Modelos.SucursalModel
ObjFacturaDevolucion.ClienteSucursal.NoExt = CliNoExt
ObjFacturaDevolucion.ClienteSucursal.NoInt = CliNoInt
ObjFacturaDevolucion.ClienteSucursal.Localidad = CliLocalidad
ObjFacturaDevolucion.ClienteSucursal.Direccion = LblDireccion.Text
ObjFacturaDevolucion.ClienteSucursal.Colonia = LblColonia.Text
ObjFacturaDevolucion.ClienteSucursal.Municipio = LblCiudad.Text
ObjFacturaDevolucion.ClienteSucursal.Estado = LblEstado.Text
ObjFacturaDevolucion.ClienteSucursal.CP = LblCP.Text
ObjFacturaDevolucion.ClienteSucursal.Pais = CliPais
ObjFacturaDevolucion.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString
ObjFacturaDevolucion.ClienteSucursal.TelefonoSucursal = LblTelefono.Text
ObjFacturaDevolucion.ClienteSucursal.Sucursal = If(DdlSucursalCliente.SelectedValue.ToEntero > 0, DdlSucursalCliente.SelectedItem.Text, "")
'ENVIO DIRECCION
ObjFacturaDevolucion.EnviarA = New Modelos.EnviarAModel
If ChkDireccionEnvio.Checked Then
If TmpDTEnvioDireccion IsNot Nothing AndAlso TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows.Count > 0 Then
For Each Row As DataRow In TmpDTEnvioDireccion.FiltraParametros(String.Format("CveDireccionEnvio = {0}", DdlDireccionEnvio.SelectedValue.ToEntero)).Rows
ObjFacturaDevolucion.EnviarA.CveDireccionEnvio = Row("CveDireccionEnvio").ToString.ToEntero
ObjFacturaDevolucion.EnviarA.EnvioDireccion = Row("EnvioDireccion").ToString
ObjFacturaDevolucion.EnviarA.EnvioColonia = Row("EnvioColonia").ToString
ObjFacturaDevolucion.EnviarA.EnvioCiudad = Row("EnvioCiudad").ToString
ObjFacturaDevolucion.EnviarA.EnvioEstado = Row("EnvioEstado").ToString
ObjFacturaDevolucion.EnviarA.EnvioCP = Row("EnvioCP").ToString
Next
End If
End If
ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion)
End Sub
Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre
Dim Timbre As New CFDITimbre
Timbre.Comprobante.TipoComprobante = If(Obj.TipoDocto.Contiene("Ing", "Ant"), "I", If(Obj.TipoDocto.Contiene("Egs", "Dev"), "E", ""))
Timbre.Comprobante.Folio = Obj.Folio.ToString
Timbre.Comprobante.Serie = Obj.Serie
Timbre.Comprobante.Fecha = Obj.Fecha
Timbre.Comprobante.FormadePago = Obj.FormaPagoSAT33
Timbre.Comprobante.CondicionesdePago = Obj.FormaPago33
Timbre.Comprobante.MetodoPago = Obj.ClaveMetodoPagoSAT
Timbre.Comprobante.Subtotal = Obj.SubTotal
Timbre.Comprobante.Descuentos = Obj.Descuento
Timbre.Comprobante.Moneda = Obj.MonedaSAT
Timbre.Comprobante.TipoCambio = If(Obj.CveMoneda = 1, "1", Obj.TipoCambio.ToString)
Timbre.Comprobante.Total = Obj.Total
Try
Obj.SetSubProyecto(Me)
Timbre.Comprobante.LugarExpedicion = Obj.SubProyecto.CP
Catch ex As Exception
End Try
Timbre.Comprobante.Confirmacion = ""
Timbre.Receptor.RFC = Obj.Cliente.RFC
Timbre.Receptor.Nombre = Obj.Cliente.Nombre
Timbre.Receptor.ResidenciaFiscal = ""
Timbre.Receptor.NumeroRegistroTributario = ""
Timbre.Receptor.UsoCFDI = Obj.ClaveUsoCFDI
If HdnTipoDescuento.Value = "3" And DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero > 0 Then
Timbre.CFDIRelacionados.TipoRelacion = "07"
Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo"
'If Timbre.Comprobante.TipoComprobante = "E" Then
' If Obj.TipoDocumento.Contiene("Nota de Crédito") Then
' Timbre.CFDIRelacionados.TipoRelacion = "01"
' Timbre.CFDIRelacionados.TipoRelacionTexto = "Nota de Crédito aplicada a Ingreso"
' End If
' If Obj.TipoDocumento.Contiene("Nota de Devolución") Then
' Timbre.CFDIRelacionados.TipoRelacion = "03"
' Timbre.CFDIRelacionados.TipoRelacionTexto = "Devolución aplicada a Ingreso"
' End If
' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value)
'End If
'' cuando es refacturacoin es cfdirelacionado, con relacion 04
'If Timbre.Comprobante.TipoComprobante = "I" AndAlso NuevaFactura = 1 Then
' Timbre.CFDIRelacionados.TipoRelacion = "04"
' Timbre.CFDIRelacionados.TipoRelacionTexto = "Refacturación de Ingreso"
' Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value)
'End If
Else
'SI LA FACTURA VIENE DE SER CANCELADA SISTEMA CUANDO SE REFACTURO NO HAY QUE RELACIONAR
If (CveEstatusFacturaPadre > 0 AndAlso CveEstatusFacturaPadre <> 4) OrElse (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Then
If Obj.CveTipoRelacion > 0 Then
Select Case Obj.CveTipoRelacion
Case 1
Timbre.CFDIRelacionados.TipoRelacion = "01"
Timbre.CFDIRelacionados.TipoRelacionTexto = "01-Nota de Crédito aplicada a Ingreso"
Case 2
Timbre.CFDIRelacionados.TipoRelacion = "02"
Timbre.CFDIRelacionados.TipoRelacionTexto = "02-Nota de débito de los documentos relacionados"
Case 3
Timbre.CFDIRelacionados.TipoRelacion = "03"
Timbre.CFDIRelacionados.TipoRelacionTexto = "03-Devolución aplicada a Ingreso"
Case 4
Timbre.CFDIRelacionados.TipoRelacion = "04"
Timbre.CFDIRelacionados.TipoRelacionTexto = "04-Refacturación de Ingreso"
Case 7
Timbre.CFDIRelacionados.TipoRelacion = "07"
Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo"
Case 8
Timbre.CFDIRelacionados.TipoRelacion = "08"
Timbre.CFDIRelacionados.TipoRelacionTexto = "08-Factura generada por pagos en parcialidades "
Case 9
Timbre.CFDIRelacionados.TipoRelacion = "09"
Timbre.CFDIRelacionados.TipoRelacionTexto = "09-Factura generada por pagos diferidos"
End Select
If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then
For Each Dr As DataRow In DtVentasNC.Rows
Timbre.CFDIRelacionados.UUID.Add(Dr("FolioFiscal").ToString)
Next
Else
If Not String.IsNullOrEmpty(HdnFolioFiscalNC.Value.Trim()) Then
Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value)
End If
End If
End If
End If
End If
Dim totSubTotal As Decimal = Obj.SubTotal
Dim totIVA As Decimal = Obj.IVA
Dim totRetIVA As Decimal = Obj.RetIVA
Dim totRetISR As Decimal = Obj.RetISR
Dim TasaRetIVA As Decimal = LblRetIVA.Text.ToDecimal / 100
Dim TasaRetISR As Decimal = LblRetISR.Text.ToDecimal / 100
Dim i As Integer = 1
'detalles
Dim tPS As String = ""
For Each drr As DataRow In Obj.DtDetalle.Rows
If drr("PS").ToString.Length = 1 Then
tPS = drr("Obs").ToString
Else
If drr("PS").ToString.Length = 0 Then
tPS = ""
Else
tPS = String.Format("{0} {1}", drr("PS"), drr("Obs"))
End If
End If
'condicionante, especial
If UsuarioActual.CveEmpresa = 15 Then drr("UM") = "" ' les comentan que no debe de ir la etiqueta de "unidad" en el producto
Dim concepto As New CFDIConceptos With {.Cantidad = drr("Cantidad").ToString.ToDecimal,
.Descripcion = tPS,
.ValorUnitario = drr("PU").ToString.ToDecimal,
.Importe = drr("TotalImporte").ToString.ToDecimal,
.Descuento = drr("Descuento").ToString.ToDecimal,
.Unidad = drr("UM").ToString,
.ClaveUnidad = drr("SATClaveUM").ToString,
.ClaveProdServ = drr("SATClaveProdServ").ToString,
.Noidentificacion = drr("Noidentificacion").ToString,
.CuentaPredial = drr("CuentaPredial").ToString}
'verifica suma subtotales
If i = Obj.DtDetalle.Rows.Count AndAlso totSubTotal <> concepto.Importe Then 'proceso de ajusta de decimales
concepto.Importe = totSubTotal
End If
totSubTotal = totSubTotal - concepto.Importe
'siempre estaremos agregando el iva, auqnue sea en importe cero o tasa cero, para que se emita la factura
' If drr("ImporteIVA").ToString.ToDouble > 0 Then
'si es ingreso amortizado por la totalidad, y arroja el valor total de cero, no debe de impuestos
If Timbre.Comprobante.Total > 0 Then
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteIVA").ToString.ToDecimal})
End If
If drr("ImporteIEPS").ToString.ToDouble > 0 Then
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIEPS").ToString.ToDecimal, .Impuesto = "003", .Importe = drr("ImporteIEPS").ToString.ToDecimal})
End If
If drr("ImporteRetIVA").ToString.ToDouble > 0 Then 'si hay retenciones
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetIVA, .Impuesto = "002", .Importe = drr("ImporteRetIVA").ToString.ToDecimal})
End If
If drr("ImporteRetISR").ToString.ToDouble > 0 Then 'retención de ISR
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetISR, .Impuesto = "001", .Importe = drr("ImporteRetISR").ToString.ToDecimal})
End If
Timbre.Conceptos.Add(concepto)
i += 1
Next
Dim AplicaComercioExteriorSubProyecto As Boolean = If(GlobalDTSubProyectos(-1, Obj.CveSubProyecto)(0)("AplicaComercioExterior").ToString = "True", True, False)
Timbre.Complementos.ComercioExterior11.AplicaComercioExteriorSubProyecto = AplicaComercioExteriorSubProyecto
If Obj.Cliente.AplicaComercioExterior And AplicaComercioExteriorSubProyecto Then
'DATOS GENERALES
Timbre.Complementos.ComercioExterior11.TipoOperacion = GlobalDTTipoOperacion().FiltraParametros($"CveTipoOperacion={CveTipoOperacion}")(0)("ClaveSATTipoOperacion").ToString
Timbre.Complementos.ComercioExterior11.ClavedePedimento = GlobalDTClavePedimento().FiltraParametros($"CvePedimento={CvePedimento}")(0)("ClaveSATPedimento").ToString
Timbre.Complementos.ComercioExterior11.CertificadoOrigen = "0"
Timbre.Complementos.ComercioExterior11.Incoterm = GlobalDTIncoterm.FiltroPrimeroValor("ClaveSATIncoterm", $"CveIncoterm={DdlIncoterm.SelectedValue}")
Timbre.Complementos.ComercioExterior11.Subdivision = "0"
Timbre.Complementos.ComercioExterior11.TipoCambioUSD = If(Obj.CveMoneda = 1, 1, Obj.TipoCambio.ToString.ToDecimal)
Timbre.Complementos.ComercioExterior11.MotivoTraslado = GlobalDTSATMotivoTraslado.FiltroPrimeroValor("ClaveSATMotivoTraslado", $"CveMotivoTraslado={DdlSATMotivoTraslado.SelectedValue}")
'EMISOR
Dim Dr As DataRow
Dr = Nothing
If GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero).Rows.Count > 0 Then
Dr = GlobalDTSubProyectos(-1, DdlSubProyectoDatos.SelectedValue.ToEntero)(0)
End If
Timbre.Complementos.ComercioExterior11.Emisor.CURP = UsuarioActual.Empresa.CURP
Timbre.Complementos.ComercioExterior11.Emisor.Calle = Dr("Calle").ToString
Timbre.Complementos.ComercioExterior11.Emisor.NumeroExterior = Dr("NoExt").ToString
Timbre.Complementos.ComercioExterior11.Emisor.NumeroInterior = Dr("NoInt").ToString
Timbre.Complementos.ComercioExterior11.Emisor.Colonia = Dr("ClaveSATColonia").ToString
Timbre.Complementos.ComercioExterior11.Emisor.Localidad = ""
Timbre.Complementos.ComercioExterior11.Emisor.Municipio = Dr("ClaveSATMunicipio").ToString
Timbre.Complementos.ComercioExterior11.Emisor.Estado = Dr("ClaveSATEstado").ToString
Timbre.Complementos.ComercioExterior11.Emisor.Pais = Dr("ClaveSATPais").ToString
Timbre.Complementos.ComercioExterior11.Emisor.CP = Dr("ClaveSATCP").ToString
'RECEPTOR
Timbre.Complementos.ComercioExterior11.Receptor.NumRegIdTrib = "" ' EN LA VERSION 3.3 NO DEBE DE REGISTRARSE ESTE VALOR
Timbre.Complementos.ComercioExterior11.Receptor.Calle = Obj.Cliente.Direccion
Timbre.Complementos.ComercioExterior11.Receptor.NumeroExterior = Obj.Cliente.NoExt
Timbre.Complementos.ComercioExterior11.Receptor.NumeroInterior = Obj.Cliente.NoInt
Timbre.Complementos.ComercioExterior11.Receptor.Colonia = Obj.Cliente.ClaveSATColonia
Timbre.Complementos.ComercioExterior11.Receptor.Localidad = ""
Timbre.Complementos.ComercioExterior11.Receptor.Referencia = Obj.Cliente.ReferenciaFiscal
Timbre.Complementos.ComercioExterior11.Receptor.Municipio = Obj.Cliente.Ciudad
Timbre.Complementos.ComercioExterior11.Receptor.CP = Obj.Cliente.CP
Timbre.Complementos.ComercioExterior11.Receptor.Estado = Obj.Cliente.ClaveSATEstado
Timbre.Complementos.ComercioExterior11.Receptor.Pais = Obj.Cliente.ClaveSATPais
Timbre.Receptor.ResidenciaFiscal = Obj.Cliente.ClaveSATPais
Timbre.Receptor.NumeroRegistroTributario = Obj.Cliente.NumRegIdTrib
Dim ComExtPais, ComExtEstado, ComExtMunicipio, ComExtColonia, ComExtCalle, ComExtNumero, ComExtCP As String
ComExtColonia = "" : ComExtMunicipio = ""
ComExtPais = GlobalDTPais.FiltroPrimeroValor("ClaveSATPais", $"CvePais={DdlComExtPais.SelectedValue}")
ComExtCalle = TxtComExtCalle.Text.Trim
ComExtNumero = TxtComExtNumero.Text.Trim
ComExtCP = TxtComExtCP.Text.Trim
If ComExtPais = "MEX" Then
ComExtEstado = GlobalDTEstado(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}")
ComExtMunicipio = GlobalDTMunicipio(ComExtEstado).FiltroPrimeroValor("ClaveSATMunicipio", $"CveMunicipio={DdlComExtMunicipio.SelectedValue}")
ComExtColonia = GlobalDTColonia(ComExtMunicipio).FiltroPrimeroValor("ClaveSATColonia", $"CveColonia={DdlComExtColonia.SelectedValue}")
Else
If ComExtPais.Contiene("USA", "CAN") Then
ComExtEstado = GlobalDTEstado(ComExtPais).FiltroPrimeroValor("ClaveSATEstado", $"CveEstado={DdlComExtEstado.SelectedValue}")
Else
ComExtEstado = TxtComExtEstado.Text.Trim
End If
ComExtMunicipio = TxtComExtMunicipio.Text.Trim
ComExtColonia = TxtComExtColonia.Text.Trim
End If
'DESTINATARIO
Timbre.Complementos.ComercioExterior11.Destinatario.Nombre = TxtDestinatarioNombre.Text.Trim
Timbre.Complementos.ComercioExterior11.Destinatario.Calle = ComExtCalle
Timbre.Complementos.ComercioExterior11.Destinatario.NumeroExterior = ComExtNumero
Timbre.Complementos.ComercioExterior11.Destinatario.NumeroInterior = ""
Timbre.Complementos.ComercioExterior11.Destinatario.Colonia = ComExtColonia
Timbre.Complementos.ComercioExterior11.Destinatario.Localidad = ""
Timbre.Complementos.ComercioExterior11.Destinatario.Referencia = Obj.Cliente.ReferenciaFiscal
Timbre.Complementos.ComercioExterior11.Destinatario.Municipio = ComExtMunicipio
Timbre.Complementos.ComercioExterior11.Destinatario.CP = ComExtCP
Timbre.Complementos.ComercioExterior11.Destinatario.Estado = ComExtEstado
Timbre.Complementos.ComercioExterior11.Destinatario.Pais = ComExtPais
Timbre.Complementos.ComercioExterior11.Destinatario.NumRegIdTrib = TxtNumRegIdTrib.Text.Trim
'MERCANCIAS
For Each Gvr As GridViewRow In GvComercioExterior.Rows
Dim mercancia As New CFDIComercioExterior11Mercancias With {.CantidadAduana = Gvr.FCTextBox("TxtCantidad").Text.ToDecimal,
.FraccionArancelaria = Gvr.DataKey("ClaveSATFraccionArancelaria").ToString,
.UnidadAduana = Gvr.DataKey("ClaveSATUnidadAduana").ToString,
.ValorDolares = Math.Round(Gvr.FCTextBox("TxtCantidad").Text.ToDecimal * Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal, 2),
.ValorUnitarioAduana = Gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal,
.NoIdentificacion = Gvr.DataKey("Codigo")}
If Gvr.FCTextBox("TxtMarca").Text <> "" Then
mercancia.DescripcionesEspecificas.Marca = Gvr.FCTextBox("TxtMarca").Text
End If
Timbre.Complementos.ComercioExterior11.Mercancias.Add(mercancia)
i += 1
Next
End If
Return Timbre
End Function
Private Sub PrepararTimbrado(ByRef FM As Modelos.FemsaFactura, ByRef TmpDT7Eleven As DataTable, ByRef TmpDTComplementosTimbrado As DataTable)
FM.AplicaFEMSA = AplicaFEMSA
FM.FEMSA_NumSociedad = TxtFEMSA_NumSociedad.Text.Trim
FM.FEMSA_NumProveedor = TxtFEMSA_NumProveedor.Text.Trim
FM.FEMSA_Mail = TxtFEMSA_Mail.Text.Trim
FM.FEMSA_Version = TxtFEMSA_Version.Text.ToEntero
FM.FEMSA_NumPedido = TxtFEMSA_NumPedido.Text.Trim.ToLong
FM.FEMSA_NumEntrada = TxtFEMSA_NumEntrada.Text.Trim
FM.FEMSA_NumRemision = TxtFEMSA_NumRemision.Text.Trim
FM.FEMSA_NumSocio = TxtFEMSA_NumSocio.Text.Trim
FM.FEMSA_CentroCosto = TxtFEMSA_CentroCosto.Text.Trim
FM.FEMSA_IPeriodoLiquidacion = TxtFEMSA_IPeriodoLiquidacion.Text.Trim
FM.FEMSA_FPeriodoLiquidacion = TxtFEMSA_FPeriodoLiquidacion.Text.Trim
FM.FEMSA_CodRetencion1 = TxtFEMSA_CodRetencion1.Text.Trim
FM.FEMSA_CodRetencion2 = TxtFEMSA_CodRetencion2.Text.Trim
TmpDT7Eleven.Columns.Add("sevenElevenNumProveedor")
TmpDT7Eleven.Columns.Add("sevenElevenFolio")
TmpDT7Eleven.Columns.Add("sevenElevenTienda")
TmpDT7Eleven.Columns.Add("sevenElevenFecha")
Dim Row As DataRow = TmpDT7Eleven.NewRow
Row("sevenElevenNumProveedor") = Txt7ElevenNumProveedor.Text.Trim()
Row("sevenElevenFolio") = Txt7ElevenFolio.Text.Trim()
Row("sevenElevenTienda") = Txt7ElevenTienda.Text.Trim()
Row("sevenElevenFecha") = Txt7ElevenFecha.Text.Trim()
TmpDT7Eleven.Rows.Add(Row)
TmpDTComplementosTimbrado.Columns.Add("CveComplemento")
TmpDTComplementosTimbrado.Columns.Add("IdContabilidad")
TmpDTComplementosTimbrado.Columns.Add("TipoProceso")
TmpDTComplementosTimbrado.Columns.Add("TipoAmbito")
TmpDTComplementosTimbrado.Columns.Add("Entidad")
Dim Row2 As DataRow = TmpDTComplementosTimbrado.NewRow
If RblComplementos.SelectedValue.ToEntero > 0 Then
Select Case RblComplementos.SelectedValue.ToEntero
Case 5
Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero
Row2("IdContabilidad") = TxtIdConta.Text.ToEntero
Row2("TipoProceso") = "Ordinario"
Row2("TipoAmbito") = "Directivo Estatal"
Row2("Entidad") = DdlINEEntidad.SelectedValue
Case 6
Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero
Row2("IdContabilidad") = TxtIdConta.Text.ToEntero
Row2("TipoProceso") = "Ordinario"
Row2("TipoAmbito") = "Ejecutivo Estatal"
Row2("Entidad") = DdlINEEntidad.SelectedValue
Case 7
Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero
Row2("IdContabilidad") = TxtIdConta.Text.ToEntero
Row2("TipoProceso") = "Ordinario"
Row2("TipoAmbito") = "Ejecutivo Nacional"
Row2("Entidad") = ""
Case 8
Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero
Row2("IdContabilidad") = TxtIdConta.Text.ToEntero
Row2("TipoProceso") = DdlTipoCampaña.SelectedValue
Row2("TipoAmbito") = DdlAmbitoComplemento.SelectedValue
Row2("Entidad") = DdlINEEntidad.SelectedValue
End Select
Else
Row2("CveComplemento") = ""
Row2("IdContabilidad") = ""
Row2("TipoProceso") = ""
Row2("TipoAmbito") = ""
Row2("Entidad") = ""
End If
TmpDTComplementosTimbrado.Rows.Add(Row2)
End Sub
#End Region
#Region "Ordenes de Compra Sin Facurar"
Private Sub CargaOCs()
Dim ObjVentas As New ClsVentas
If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 1) Then
If DdlContratosOC.SelectedValue.ToEntero > 0 Then
DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"CveContratoVinculado = '{DdlContratosOC.SelectedValue}'")
Else
DTOrdenesCompra = ObjVentas.DtResultados
End If
GVOC.DataSource = DTOrdenesCompra
End If
If DTOrdenesCompra IsNot Nothing AndAlso Not DTOrdenesCompra.Columns.Contains("Aplicado") Then
DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean"))
End If
ObjVentas.Dispose()
GVOC.DataBind()
UPOCFactura.Update()
End Sub
Private Sub CargaOCsxProducto()
Dim ObjVentas As New ClsVentas
If ObjVentas.GetOCSinFacturar(TxtFechaIOC.Text, TxtFechaFOC.Text, CveCliente, 2) Then
If DdlContratosOC.SelectedValue.ToEntero > 0 Then
DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0 AND CveContratoVinculado = '{DdlContratosOC.SelectedValue}'")
Else
DTOrdenesCompra = ObjVentas.DtResultados.FiltraParametros($"Cantidad > 0")
End If
GvOCPS.DataSource = DTOrdenesCompra
End If
If Not DTOrdenesCompra.Columns.Contains("Aplicado") Then
DTOrdenesCompra.Columns.Add("Aplicado", Type.GetType("System.Boolean"))
End If
ObjVentas.Dispose()
GvOCPS.DataBind()
UPOCFactura.Update()
End Sub
Private Sub ChkOCProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkPSOC.CheckedChanged
CargaOCSinFacturar()
End Sub
Private Sub VerificaOrdenesCompra(ByRef dt As DataTable)
If ChkPSOC.Checked Then
For Each Gvr As GridViewRow In GvOCPS.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
If Gvr.FCCheckBox("Chk").Checked Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveOrdenCompraDetalle As Integer = Gvr.DataKey("CveOrdenCompraDetalle").ToEntero
Dim Drs As DataRow() = dt.Select($"CveOrdenCompraDetalle = {CveOrdenCompraDetalle}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
End If
Next
Else
For Each Gvr As GridViewRow In GVOC.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
If Gvr.FCCheckBox("Chk").Checked Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveOrdenCompra As Integer = Gvr.DataKey("CveOrdenCompra").ToEntero
Dim Drs As DataRow() = dt.Select($"CveOrdenCompra = {CveOrdenCompra}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
End If
Next
End If
End Sub
Protected Sub BtnCargarOC_Click(sender As Object, e As EventArgs) Handles BtnCargarOC.Click
If GVOC.Rows.Count > 0 Or GvOCPS.Rows.Count > 0 Then
'Checa las facturas selecionadas
VerificaOrdenesCompra(DTOrdenesCompra)
Dim dtSeleccionadas As DataTable = DTOrdenesCompra.FiltraParametros("Aplicado = True")
If GvPS.Rows.Count > 0 Then
TmpDT.Rows.Clear()
TxtSubTotal.Text = "0.00"
TxtSubTotal2.Text = "0.00"
TxtIVA.Text = "0.00"
TxtTotal.Text = "0.00"
HdnIVAOriginal.Value = TxtIVA.Text
End If
If dtSeleccionadas.Rows.Count > 0 Then
If TieneContrato Then
ContratoDetalles.Visible = True
DivEstimaciones.Visible = False
DdlContratosModal.DataSource = DtContratos
DdlContratosModal.DataBind()
DdlContratosModal.Items.Insert(0, New ListItem("Seleccione", "0"))
DdlContratosModal.SelectedValue = DdlContratosOC.SelectedValue
DdlContrato.SelectedValue = DdlContratosOC.SelectedValue
UPEstimaciones.Update()
End If
IsTotalxConcepto = True
Dim ObjClientes As New ClsClientes
Dim sb As New StringBuilder
If ChkPSOC.Checked Then
For Each row As DataRow In dtSeleccionadas.Rows
sb.Append($"{row("CveOrdenCompraDetalle").ToString},")
Next
Else
For Each row As DataRow In dtSeleccionadas.Rows
sb.Append($"{row("CveOrdenCompra").ToString},")
Next
End If
sb.Remove(sb.Length - 1, 1)
If ObjClientes.GetVentasOCTotales(CveCliente, sb.ToString, If(ChkPSOC.Checked, 2, 1)) Then
DTOrdenesCompraPS = ObjClientes.DtResultados
Dim tCantidad As Decimal = 0
For Each Dr As DataRow In DTOrdenesCompraPS.Select()
tCantidad = If(ChkPSOC.Checked, GvOCPS.Rows(IndiceGVDataKey(GvOCPS, "CveOrdenCompraDetalle", $"{Dr("CveOrdenCompraDetalle")}")).FCTextBox("TxtCantidadOC").Text, Dr("Cantidad")).ToString.ToDecimal
AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString,
Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PUCon").ToString.ToDecimal, 0,
Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString,
CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero,
EntregaDirecta:=1)
Next
CveContrato = DTOrdenesCompraPS.FiltroPrimeroValor("CveContrato").ToString.ToEntero
If CveContrato > 0 Then ContratoOC = True
CalculaTotalesVenta()
GvPS.DataSource = TmpDT
GvPS.DataBind()
End If
ObjClientes.Dispose()
BtnEmitirImprimir.Text = "Facturar"
DdlTipoComprobante.SelectedValue = "Ing"
DdlTipoComprobante.Enabled = False
Tab.ActiveTab = TabGenerales
TabGenerales.Enabled = True
Updatetabs.Update()
'Else
' If TieneContrato Then
' GvContratoDetalles.DataSource = Nothing
' GvContratoDetalles.DataBind()
' UPEstimaciones.Update()
' End If
End If
End If
ChkPSOC.Checked = False
UPOCFactura.Update()
UpFacturar.Update()
UpPS.Update()
UpParametros.Update()
RegistraScript("$('#DivOrdenesCompra').modal('hide');")
End Sub
Private Sub DdlContratosOC_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlContratosOC.SelectedIndexChanged
CargaOCSinFacturar()
End Sub
Private Sub CargaOCSinFacturar()
If ChkPSOC.Checked Then
GvOCPS.Visible = True
GVOC.Visible = False
DivFiltroOCPS.Visible = True
GVOC.DataSource = Nothing
GVOC.DataBind()
CargaOCsxProducto()
Else
GvOCPS.Visible = False
GVOC.Visible = True
DivFiltroOCPS.Visible = False
GvOCPS.DataSource = Nothing
GvOCPS.DataBind()
CargaOCs()
End If
End Sub
Private Sub LnkOCs_Click(sender As Object, e As EventArgs) Handles LnkOCs.Click
Dim ObjContratos As New ClsContratos
If Not TieneContrato Then
If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1, 1) Then
If ObjContratos.DtResultados.FiltraParametros("Estatus = True").Rows.Count > 0 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "Ped") Or DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev")) Then
DtContratos = ObjContratos.DtResultados.FiltraParametros($"Estatus = True AND FechaFinal >= '{Now.ToShortDateString}' AND FechaInicial <= '{Now.ToShortDateString}'")
DdlContratosOC.DataSource = DtContratos
DdlContratosOC.DataBind()
If Not TieneContrato Then
DdlContratosOC.Items.Insert(0, New ListItem("Seleccione", "0"))
End If
End If
End If
GvContratoDetalles.DataSource = Nothing
GvContratoDetalles.DataBind()
UpContratos.Update()
DivEstimaciones.Visible = True
ContratoDetalles.Visible = False
UPEstimaciones.Update()
Tab.ActiveTab = TabGenerales
TabGenerales.Enabled = True
Updatetabs.Update()
End If
ObjContratos.Dispose()
ChkPSOC.Checked = False
UPOCFactura.Update()
CargaOCSinFacturar()
RegistraScript("$('#DivOrdenesCompra').modal('show');")
End Sub
Private Sub BtnConsultarOC_Click(sender As Object, e As EventArgs) Handles BtnConsultarOC.Click
CargaOCSinFacturar()
End Sub
#End Region
#Region " GUARDAR - VENTA, PREPOLIZAS, INV, ESTIMACIONES, AC, NOTA DE CRÉDITO "
Private Sub GuardarVenta(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, factura As Modelos.Factura, TmpDTDetalle As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, Optional ByRef ObjOS As ClsOS = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, ByRef Optional ObjCGame As ClsCGame = Nothing, ByRef Optional ObjCliente As ClsClientes = Nothing)
Dim Msgok As New StringBuilder
Dim CveAlmacenTraspasoOrigen As Integer = -1
Dim CveAlmacenTraspasoDestino As Integer = -1
Dim EsDevolucionVenta = -1
Dim EsInterno As Integer = -1
If DdlAlmacenAsignado.Visible Or RequiereAlmacenDestino Then
CveAlmacenTraspasoDestino = DdlAlmacenAsignado.SelectedValue.ToEntero
End If
If DdlAlmacenOrigen.Visible Or RequiereAlmacenOrigen Then
CveAlmacenTraspasoOrigen = DdlAlmacenOrigen.SelectedValue.ToEntero
End If
If TrTipoPedido.Visible Then
EsInterno = DdlTipoPedido.SelectedValue.ToEntero()
End If
'Si es devolucion revertimos los almacenes
If CvePedido > 0 And TipoContrato = 2 Then
EsDevolucionVenta = 1
CveAlmacenTraspasoOrigen = DdlAlmacenAsignado.SelectedValue.ToEntero
CveAlmacenTraspasoDestino = DdlAlmacenOrigen.SelectedValue.ToEntero
End If
'VALIDA ENTREGA POR ADELANTADO
If UsuarioActual.Empresa.Funcionalidad(145) = "1" Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then
'INCRUSTAMOS ALMACEN ENTREGA POR ADELANTADO CUANDO SEA REMISION Y NO TRAIGA ASIGNADO POR EL USUARIO
If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then
CveAlmacenTraspasoDestino = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString.ToEntero
End If
'SI LA SUCURSAL NO TIENE ENTREGA POR ADELANTADO
If CveAlmacenTraspasoDestino <= 0 And factura.TipoDocto = "Rem" Then
ErrorList.Add("Ocurrió un error al seleccionar el almacen de entrega por adelantado de la sucursal.")
End If
End If
Dim TotalImpuestoLocal As Double = 0
If GvImpuestosLocales2.Rows.Count > 0 Then
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then
If gvr.DataKey("TipoImpuesto") = "5" Then ' cuando es traslado local
TotalImpuestoLocal -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble
Else ' cuando es retención
TotalImpuestoLocal += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble
End If
End If
End If
Next
End If
factura.CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardarVenta", factura.CvePlantillaPoliza, factura.Total, factura.Total, factura.CveMoneda, factura.Fecha, If(CveEmpresaCRM > 0, LblEmpresaCRM.Text, factura.Cliente.Nombre), factura.CveUsuario, factura.CveEmpresa)
If Not ObjVentas.AddVenta(factura.TipoDocto, factura.Folio, factura.CveCliente, factura.CveClienteSucursal, factura.SubTotalTC, factura.DescuentoTC,
factura.AmortizacionTC, factura.IVATC, factura.RetIVATC, factura.RetISRTC,
factura.TotalTC, factura.CveMoneda, factura.TipoCambio, factura.CveMetodoPago, factura.CondicionesPago, factura.FormaPago, factura.FechaPago, factura.Fecha, factura.MotivoDescuento,
factura.Observaciones, factura.FechaEjecucion, factura.CveVendedor,
factura.Alfa1, factura.Alfa2, factura.Alfa3, factura.Num1, factura.Num2, factura.Num3,
factura.Fech1, factura.Fech2, factura.Fech3, factura.CveCorte, factura.CveMesa, factura.NumeroPersonas, factura.CvePrePoliza, factura.CveUsuario, factura.CveEmpresa,
AtencionA:=factura.AtencionA, TelefonoGenerico:=TxtTelefonoGenerico.Text.Trim, CveContrato:=factura.CveContrato, CveVentaPadre:=If(AplicaDevolucion, CveVentaDevolucion, factura.CveVentaPadre), Det_FechaOrdenCompra:=factura.Det_FechaOrdenCompra, Det_OrdenCompra:=factura.Det_OrdenCompra, otros:=factura.Otros,
Entrega:=TxtEntrega.Text, Vigencia:=If(DdlTipoComprobante.SelectedValue = "Cot", TxtFechaVencimientoCotizacion.Text.ToDate, MinFecha),
CveAlmacenTraspasoDestino:=CveAlmacenTraspasoDestino, CveAlmacenTraspasoOrigen:=CveAlmacenTraspasoOrigen, CveDireccionEnvio:=If(DdlDireccionEnvio.Visible, DdlDireccionEnvio.SelectedValue.ToEntero, -1), CveOC:=CveOC, IEPS:=factura.IEPSTC, Serie:=factura.Serie, CveCondicionEntrega:=DdlFormaEntrega.SelectedValue.ToEntero,
PedidoContrato:=TxtPedidoContrato.Text, ObservacionesAlmacen:=TxtObsAlmacen.Text, CveSubProyecto:=factura.CveSubProyecto, CveSubProyectoCobranza:=factura.CveSubProyectoCobranza, CveSubProyectoEjecucion:=factura.CveSubProyectoEjecucion, CveFormaPago33:=factura.CveFormaPago33,
CveMetodoPago33:=factura.CveMetodoPago33, CveUsoCFDI:=factura.CveUsoCFDI, OrdenCompra:=TxtOrdenCompra.Text, CveCuentaTerminal:=DdlCuentasTerminal.SelectedValue.ToEntero, CveTipoRelacion:=factura.CveTipoRelacion, ImpuestoLocal:=TotalImpuestoLocal,
CveVentaRelacion:=(If(factura.CveVentaRelacion.ToEntero > 0, factura.CveVentaRelacion, -1)), ImporteRelacion:=(If(factura.ImporteRelacion <> Nothing, factura.ImporteRelacion, -1)),
CveTipoAmortizacionAnticipo:=factura.CveTipoAmortizacionAnticipo, CveEmpresaCRM:=CveEmpresaCRM, EsInterno:=EsInterno, CveAcercamientoCRM:=CveAcercamientoCRM,
DiasCredito:=factura.DiasCredito, EsDiasCreditoFijo:=factura.EsDiasCreditoFijo, AnticipoEspecial:=If(TrAntEspecial.Visible, ChkAntEspecial.Checked, False)) Then
ErrorList.Add("Ocurrió un error al Generar la Venta.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico")
End If
If Not GuardarUsados(ObjVentas.IniciaTransacSQL, ObjVentas.CveVenta) Then
ErrorList.Add("Error al guardar usados")
End If
If ErrorList.Count = 0 AndAlso ObjVentas.CveVenta > 0 Then
factura.CveVenta = ObjVentas.CveVenta
factura.Serie = ObjVentas.Serie
factura.Folio = ObjVentas.Folio
ViewState("VentaFolio") = ObjVentas.SerieFolio
factura.Timbre.Comprobante.Serie = ObjVentas.Serie
factura.Timbre.Comprobante.Folio = ObjVentas.Folio.ToString
If factura.TipoDocto = "Egs" AndAlso NuevaFactura = 1 Then
If DtVentasNC Is Nothing Then
InicializaDTVentasNC()
End If
CargaNCDT(factura.CveVentaPadre, factura.Total, NuevaFactura:=NuevaFactura, ObjVentas:=ObjVentas)
End If
'Se agregan los PS
For Each Row As DataRow In TmpDTDetalle.Rows
If Not ObjVentas.AddVentaDetalle(ObjVentas.CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero,
Row("PU").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)))), 6),
Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero,
TiempoEntrega:=Row("TiempoEntrega").ToString, CveVentaDetallePadre:=Row("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CvePromocionDetalle:=If(DtPromociones IsNot Nothing, DtPromociones.FiltroPrimeroValor("CvePromocionDetalle", $"CvePS={Row("CvePS").ToString}").ToEntero, -1),
IEPS:=Row("ImporteIEPS").ToString.ToDouble, CveMovimientoDetallePedido:=Row("CveMovimientoDetallePedido").ToString.ToEntero,
ImporteRetIVA:=Row("ImporteRetIVA").ToString.ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString.ToDouble,
PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString.ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString.ToDouble, CuentaPredial:=Row("CuentaPredial").ToString) Then
ErrorList.Add("Ocurrió un error al agregar un Producto o Servicio a la Factura.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico")
Exit For
Else
'Agregamos el gasto de contrato
If CveContrato > 0 AndAlso factura.TipoDocto = "Rem" AndAlso AplicaGastoContrato Then
Dim ObjContrato As New ClsContratos
If Not ObjContrato.AddContratoGasto(CveContrato, Row("PS").ToString, Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, factura.Fecha, UsuarioActual.CveUsuario, CveVenta:=ObjVentas.CveVenta) Then
ErrorList.Add("Ocurrió un error al agregar el gasto de la Factura.")
Exit For
End If
ObjContrato.Dispose()
End If
'Si es devolucion se agregan a la tabla de Vta_VentasDetalleDevolucion
If factura.AplicaDevolucion Then
If Not ObjVentas.AddVentaDetalleDevolucion(Row("CveVentaDetalle").ToString.ToEntero, ObjVentas.CveVentaDetalle, Row("Cantidad").ToString.ToDouble) Then
ErrorList.Add("Ocurrió un error al agregar la venta detalle devolucion.")
End If
End If
Dim TmpDr As DataRow = TmpDT.Select($"Consec = {Row("Consec").ToString}")(0)
TmpDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle
Try
Dim InvDr As DataRow = DtInv.Select($"Consec = {Row("Consec").ToString}")(0)
InvDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle
Catch ex As Exception
End Try
End If
Next
'Orden Produccion'
If UsuarioActual.CveEmpresa.Contiene(126) Then
If ObjVentas.CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then
If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), ObjVentas.CveVenta) Then
ErrorList.Add("Ocurrió un error al actualizar la orden de producción")
End If
End If
End If
'PedidoA'
If ObjVentas.CveVenta > 0 And CvePedidoA > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem") Then
If Not ObjCliente.UpdateEstatusPedido(CvePedidoA, 18, -1, UsuarioActual.CveUsuario) Then
ErrorList.Add("Ocurrió un error al actualizar el estatus del pedidoA")
End If
End If
'Actualiar el estatus de la venta refacturada
If ObjVentas.CveVenta > 0 AndAlso NuevaFactura = 1 AndAlso CveDevolucion > 0 Then
'If CveEstatusRefacturacion = 1 Then CveEstatusRefacturacion = 2 'cuando viene del proceso de refacturación con aceptació
If Not ObjVentas.UpdateEstatusRefacturacion(CveDevolucion, 2) Then ' se marca como refacturada
ErrorList.Add("Ocurrió un error al actualizar el estatus de la refacturacion")
End If
End If
'Pedido2'
If ObjVentas.CveVenta > 0 And CvePedido2 > 0 And DdlTipoComprobante.SelectedValue.Contiene("Rem", "PA") Then
If Not ObjCliente.UpdateEstatusPedido(CvePedido2, 21, -1, UsuarioActual.CveUsuario) Then
ErrorList.Add("Ocurrió un error al actualizar el estatus del pedido2")
End If
End If
'Si viene de OS, Se guarda CveVenta en OS
If CveOS > 0 Then
If Not ObjOS.UpdateVentaOS(factura.CveVenta, CveOS) Then
ErrorList.Add("Ocurrió un error al guardar la venta en Ordenes de Servicio")
End If
End If
'Contratos
If factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing") Then
GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, 1)
ElseIf factura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then
GuardarContratoAvanceEstimaciones(ObjContr, factura, ErrorList, -1)
End If
'Impuestos Locales
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble <> 0 Then
If Not ObjVentas.AddVentaImpuestoLocales(factura.CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1))) Then
ErrorList.Add("Ocurrió un error al Guardar Impuestos Locales")
End If
End If
End If
Next
If DTmpF.Rows.Count > 0 Then
For Each Row As DataRow In DTmpF.Rows
If Not ObjVentas.AddVentasFirmas(factura.CveVenta, Row("Titulo").ToString, Row("Nombre").ToString, Row("Puesto").ToString, Row("Lado").ToString.ToEntero) Then
ErrorList.Add("Ocurrio un error al Guardar Firmas")
End If
Next
End If
'registro los metodos de pago, cuando hay corte.
If factura.CveCorte > 0 Then
'cuando es contado
If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then
For Each DrPago As DataRow In DtPagos.Rows
If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, DrPago("CveMetodoPago").ToString.ToEntero, DrPago("Importe").ToString.ToDouble) Then
ErrorList.Add("Ocurrio un error al guardar los metodos de pago")
End If
Next
Else
'cuando es crédito o terminal
If Not ObjVentas.AddVta_VentaPago(factura.CveVenta, 7, TxtTotal.Text.ToDouble) Then
ErrorList.Add("Ocurrio un error al guardar los metodos de pago")
End If
End If
End If
'cuando es contado
'If factura.CveCorte > 0 Then
' If RBLPago.SelectedValue = "2" AndAlso DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then
' For Each DrPago As DataRow In DtPagos.Rows
' If ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, TxtFechaPago.Text.ToDate, DrPago("Folio").ToString, "", DrPago("Importe").ToString.ToDouble, DdlMoneda.SelectedValue.ToEntero, If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then
' ErrorList.Add("Ocurrio un error al guardar los metodos de pago")
' End If
' Next
' 'Else
' ' 'cuando es crédito o terminal
' ' If ObjBancos.AddBancos_IE(, 7, TxtFechaPago.Text.ToDate, TxtFolio.Text.ToString, "", TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDouble), "", "", True, False, -1, factura.CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) = -1 Then
' ' ErrorList.Add("Ocurrio un error al guardar los metodos de pago")
' ' End If
' End If
'End If
'INE COMPLEMENTOS
If ObjFactura.ComplementoINE IsNot Nothing Then
If Not ObjVentas.UpdateVentasComplementos(ObjFactura.CveVenta, ObjFactura.ComplementoINE.INETipoProceso, ObjFactura.ComplementoINE.INETipoComite, ObjFactura.ComplementoINE.INEIdContabilidad.ToString) Then
ErrorList.Add("Ocurrio un error al guardar los complementos")
End If
End If
If ErrorList.Count = 0 Then
'Agregamos las remisiones a la tabla
If DtRemisionesPS IsNot Nothing AndAlso DtRemisionesPS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then
Dim CveVentaDetalle As Integer = 0
Dim CveVentaDetallePadre As Integer = 0
Dim Cantidad As Decimal = 0
Dim CvePS As Integer = 0
Dim PU As Decimal = 0
For Each row As DataRow In DtRemisionesPS.Rows
Cantidad = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal
CvePS = DtRemisionesTmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero
PU = DtRemisionesTmpDT.FiltroPrimeroValor("PU", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToDecimal
CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetalleRemision={row("CveVentaDetalle")}").ToEntero
CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero
If Not ObjVentas.AgregarRemisionDetalle(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then
ErrorList.Add("Ocurrió un error al agregar el detalle de la Remision")
End If
Next
End If
If DTRemisiones IsNot Nothing AndAlso DTRemisiones.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then
Dim dt As DataTable = DTRemisiones.FiltraParametros("Aplicado = True")
If dt.Rows.Count > 0 Then
For Each row As DataRow In dt.Rows
If Not ObjVentas.UpdateVentaRemision(row("CveVenta").ToString.ToEntero, ObjFactura.CveVenta) Then
ErrorList.Add("Ocurrió un error al actualizar la remisión")
End If
Next
End If
End If
End If
If ErrorList.Count = 0 Then
'Agregamos los pedidos2 a la tabla
If DtPedidos2PS IsNot Nothing AndAlso DtPedidos2PS.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then
Dim CveVentaDetalle As Integer = 0
Dim CveVentaDetallePadre As Integer = 0
Dim Cantidad As Decimal = 0
Dim CvePS As Integer = 0
Dim PU As Decimal = 0
For Each row As DataRow In DtPedidos2PS.Rows
Cantidad = DtPedidos2TmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal
CvePS = DtPedidos2TmpDT.FiltroPrimeroValor("CvePS", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero
PU = DtPedidos2TmpDT.FiltroPrimeroValor("PU", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToDecimal
CveVentaDetalle = TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"CveVentaDetallePedido2={row("CveVentaDetalle")}").ToEntero
CveVentaDetallePadre = row("CveVentaDetalle").ToString.ToEntero
If Not ObjVentas.AddVentaDetallePedido2(CveVentaDetalle, CveVentaDetallePadre, Cantidad) Then
ErrorList.Add("Ocurrió un error al agregar el detalle del Pedido2")
End If
Next
End If
If DtPedidos2 IsNot Nothing AndAlso DtPedidos2.Rows.Count > 0 AndAlso ErrorList.Count = 0 Then
Dim dt As DataTable = DtPedidos2.FiltraParametros("Aplicado = True")
If dt.Rows.Count > 0 Then
For Each row As DataRow In dt.Rows
If Not ObjVentas.UpdateVentaPedido2(row("CveVenta").ToString.ToEntero, ObjFactura.CveVenta) Then
ErrorList.Add("Ocurrió un error al actualizar el Pedido2")
End If
Next
End If
End If
End If
If ErrorList.Count = 0 Then
'prepoliza
GuardarVentaPrePolizas(ObjConta, factura, TmpDTDetalle, CveNCaVincular, objContPaqi, ObjBancos, ObjVentas, ObjEventos:=ObjEventos)
If ErrorList.Count = 0 Then
'inventarios
If GuardarVentaInventarios(ObjInventario, ObjConta, factura) Then
ErrorList.Add("Ocurrio un error al Guardar Inventario")
End If
If ErrorList.Count = 0 Then
'estimaciones
GuardarVentaEstimaciones(ObjContr, factura)
If ErrorList.Count = 0 Then
'armonizaccionContable
GuardarVentaAC(ObjVentas, factura, Msgok, objContPaqi)
If ErrorList.Count = 0 Then
'Impuestos Locales
If GuardarVentaImpuestosLocales(ObjVentas, ObjConta, factura) Then
ErrorList.Add("Ocurrio un error al Guardar Impuestos Locales")
End If
End If
End If
End If
End If
End If
End If
End Sub
Private Sub GuardarVentaPrePolizas(ByRef ObjConta As ClsContabilidad, factura As Modelos.Factura, TmpDTDetalleMovimientos As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing)
Dim CveIE As Integer = -1
Dim DT As DataTable = Nothing
Dim CveConceptoAfectacion As Integer = 1 'Cliente
Dim CveConceptoAntCli As Integer = 3 'Anticipo Cliente
Dim CveConceptoVenta As Integer = 4 'Venta
Dim CveConceptoCanAnt As Integer = 11 'Cancelacion Anticipos
Dim CveConceptoDSV As Integer = 12 ' DSV
Dim CveConceptoIVA As Integer = 13 'IVA Trasladado
Dim CveConceptoRetIVA As Integer = 8 'Ret IVA
Dim CveConceptoRetISR As Integer = 9 'Ret ISR
'P R E P O L I Z A S
If DdlTipoComprobante.SelectedValue <> "Cot" Then
If factura.CvePrePoliza > 0 Then
If ProcesoPrepolizas(ObjConta, factura, CveIE, TmpDTDetalleMovimientos, objContPaqi, 1, ObjBancos, ObjVentas, ObjEventos:=ObjEventos) Then
ErrorList.Add("Ocurrió un error al agregar los Movimientos de la prepoliza.<br />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.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico")
End If
End If
End Sub
Private Function ProcesoPrepolizas(ByRef ObjConta As ClsContabilidad, ObjFactura As Modelos.Factura, CveIE As Integer, TmpDTDetalle As DataTable, ByRef objContPaqi As ClsContPAQi, Optional ValorMultiplicador As Integer = 1, ByRef Optional ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing) As Boolean
Try
Dim DT As DataTable
Dim CvePlantilaPoliza As Integer
Dim PorcentajeAmortizacion As Decimal = 0
Dim sumaAmorticaciones As Decimal = 0
Dim ErrorPrepoliza As Boolean = False
Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:<br><br>"
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
tipoCambio = GlobalTipoCambio(ObjFactura.Fecha).ToString.ToDecimal
Else
tipoCambio = 1
End If
Dim ConceptoContable As Integer
Dim TipoMovimiento As Boolean
Dim importeMovimiento As Decimal
Dim FechaMovimiento As Date = ObjFactura.Fecha
Dim IdCtaContable As Integer
Dim CveCuenta As Integer
Dim IdCtaContableCliente As Integer
Dim CveCuentaCliente As Integer
Dim Concepto As String = ViewState("VentaFolio").ToString
Dim Referencia As String = ViewState("VentaFolio").ToString
Dim Fecha = TxtFecha.Text.Trim.ToDate
Dim importeMX As Decimal
Dim Multiplicador As Integer
Dim CveIEPago As Integer
Dim FolioIE As Long
Dim CveIEAnticipo As Integer
Dim CveSubProyectoVenta = DdlSubProyectoDatos.SelectedValue.ToEntero
Dim CveSubProyectoContabilizar As Integer
Dim IdCtaIVAXTrasladar As Integer = 0
Dim IdCtaIVATrasladado As Integer = 0
Dim CveCuentaIVAxTrasladar As Integer = 0
Dim CveCuentaIVATrasladado As Integer = 0
Dim SeContabiliza As Boolean = True
If (UsuarioActual.Empresa.Funcionalidad(343) = "1" AndAlso ObjFactura.TipoDocto = "Ant") Or (ChkAntEspecial.Checked AndAlso ObjFactura.TipoDocto = "Ant") Then
SeContabiliza = False
End If
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then
IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero
CveCuentaIVAxTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVAXTrasladar").ToString.ToEntero
IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero
CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero
End If
Dim UsaComplementariaClientes As Boolean = False
If UsuarioActual.CveEmpresa.Contiene(1, 119) Then UsaComplementariaClientes = True
If ObjConta.GetPlantillaConceptos(ObjFactura.CveEmpresa, CvePlantilaPoliza) Then
Dim dtt As DataTable = ObjConta.DtResultados
If ValorMultiplicador = -1 Then dtt = ObjConta.DtResultados.FiltraParametros("", "Orden DESC") ' se ordena contrario al registro para llevar los saldos correctos
For Each Row As DataRow In dtt.Rows
ConceptoContable = Row("CveConcepto").ToString.ToEntero
TipoMovimiento = If(Row("TipoMovto").ToString = "True", True, False)
importeMovimiento = 0
IdCtaContable = 0
CveCuenta = 0
CveSubProyectoContabilizar = 0
Multiplicador = (Row("Multiplicador").ToString.ToEntero)
Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, ConceptoContable, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", "")
Dim PorcentajeImpuesto As Decimal = 0
Select Case ConceptoContable
Case 1 'Cliente
If Not ObjFactura.TipoDocto.Contiene("Egs", "Rem", "RNC") Then
importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador
importeMX = importeMovimiento * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
CveSubProyectoContabilizar = CveSubProyectoVenta
'If ObjFactura.TipoDocto.Contiene("Ant") Then
' TipoMovimiento = Not TipoMovimiento 'lo contrario a ingreso, en este caso es anticipo
'End If
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
If tipoCambio = 1 Then
IdCtaContable = ObjFactura.Cliente.IdCtaContClientes
CveCuenta = ObjFactura.Cliente.CveCuentaClientes
Else
IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria
CveCuenta = 0
If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsaComplementariaClientes) Then
importeMX = importeMovimiento
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
End If
End If
IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera
CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera
End If
IdCtaContableCliente = IdCtaContable
CveCuentaCliente = CveCuenta
End If
Case 3 'Cliente
If ObjFactura.TipoDocto = "Ant" Then
ConceptoContable = If(UsuarioActual.CveEmpresa.Contiene(1, 119), 95, ConceptoContable)
importeMovimiento = ObjFactura.SubTotal * ValorMultiplicador
importeMX = importeMovimiento * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
IdCtaContable = ObjFactura.Cliente.IdCtaContAnticipos
CveCuenta = ObjFactura.Cliente.CveCuentaAnticipos
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
End If
Case 190 'Remisión del cliente
If ObjFactura.TipoDocto = "Rem" Then
importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador
importeMX = importeMovimiento * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
If tipoCambio = 1 Then
IdCtaContable = ObjFactura.Cliente.IdCtaContClientes
CveCuenta = ObjFactura.Cliente.CveCuentaClientes
Else
IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera
CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera
End If
IdCtaContableCliente = IdCtaContable
CveCuentaCliente = CveCuenta
If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 190, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 193, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
Else
ErrorPrepoliza = True
End If
importeMovimiento = 0
ViewState("SeGuardoPrePoliza") = True
End If
Case 277 'Remisión del cliente
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
CveCuenta = ObjFactura.Cliente.CveCuentaClientes
Else
IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera
CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera
End If
IdCtaContableCliente = IdCtaContable
CveCuentaCliente = CveCuenta
If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 277, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 278, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
Else
ErrorPrepoliza = True
End If
importeMovimiento = 0
ViewState("SeGuardoPrePoliza") = True
End If
Case 12 'Nota de Credito
If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then
importeMovimiento = ObjFactura.Total * ValorMultiplicador
importeMX = (importeMovimiento * tipoCambio * Multiplicador).RoundSQL
FechaMovimiento = ObjFactura.FechaPago
Dim ImporteConcepto12 As Decimal = 0
Dim ImporteAcumulado91 As Decimal = 0
Dim CveUltimaVenta As Integer = 0
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
If tipoCambio = 1 Then
IdCtaContable = ObjFactura.Cliente.IdCtaContClientes
CveCuenta = ObjFactura.Cliente.CveCuentaClientes
ElseIf UsaComplementariaClientes Then
IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria
CveCuenta = 0
If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsaComplementariaClientes) Then
importeMX = importeMovimiento
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
End If
IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera
CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera
End If
CveSubProyectoContabilizar = CveSubProyectoVenta
ImporteConcepto12 = importeMX.RoundSQL
If importeMovimiento <> 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
importeMovimiento = 0
If ValorMultiplicador = 1 Then
Dim IdCtaContableClienteComplementaria As Integer = ObjFactura.Cliente.IdCtaContComplementaria
Dim TipoCambioNC As Decimal = 1
If tipoCambio > 1 Then
TipoCambioNC = tipoCambio
Else
TipoCambioNC = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal
End If
'APLICA NC SALDOS DIRECTOS
If DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0 Then
For Each Dr As DataRow In DtVentasNC.Rows
Dim Importe91 As Decimal = 0
Dim ImporteMN91 As Decimal = 0
Dim Importe251 As Decimal = 0
Dim ImporteMN251 As Decimal = 0
If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
Importe251 = Dr("Importe").ToString.ToDecimal
Importe91 = Dr("Importe").ToString.ToDecimal
ImporteMN91 = Dr("Importe").ToString.ToDecimal
TipoCambioNC = 1
ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
Importe251 = Dr("Importe").ToString.ToDecimal
Importe91 = Dr("Importe").ToString.ToDecimal
ImporteMN91 = Dr("Importe").ToString.ToDecimal * TipoCambioNC
ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
Importe251 = Dr("Importe").ToString.ToDecimal
Importe91 = Dr("Importe").ToString.ToDecimal
ImporteMN91 = Dr("Importe").ToString.ToDecimal * TipoCambioNC
ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
Importe251 = Dr("Importe").ToString.ToDecimal
Importe91 = Dr("Importe").ToString.ToDecimal
ImporteMN91 = Dr("Importe").ToString.ToDecimal
End If
Dim TCFluctuacion As Decimal = Dr("TCCambioValuacion").ToString.ToDecimal
If TCFluctuacion = 1 AndAlso TipoCambioNC > 1 Then
TCFluctuacion = GlobalTipoCambio(TxtFecha.Text.ToDate).ToDecimal
End If
If DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Not Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
ImporteMN251 = Dr("Importe").ToString.ToDecimal * TCFluctuacion
ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
ImporteMN251 = Dr("Importe").ToString.ToDecimal * TCFluctuacion
ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
ImporteMN251 = Dr("Importe").ToString.ToDecimal / TipoCambioNC
Else
ImporteMN251 = Dr("Importe").ToString.ToDecimal
End If
Importe251 = (Importe251 * Multiplicador).RoundSQL
Importe91 = (Importe91 * ValorMultiplicador).RoundSQL
ImporteMN91 = (ImporteMN91 * Multiplicador).RoundSQL
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${Importe91.FormatoNumero(2)}"
CveUltimaVenta = Dr("CveVenta").ToString.ToEntero
Dim ImporteComplementarioIngreso As Decimal = 0
If UsaComplementariaClientes = True AndAlso tipoCambio > 1 Then
ImporteMN91 = Importe91
ImporteComplementarioIngreso = ((Importe91 * tipoCambio) - Importe91).RoundSQL
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteComplementarioIngreso, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=Dr("TCCambioValuacion").ToString.ToDecimal) Then
ErrorPrepoliza = True
Exit For
End If
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, Importe91, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteMN91, ImporteME:=If(tipoCambio = 1, 0, Importe91), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then
ErrorPrepoliza = True
Exit For
End If
ImporteAcumulado91 += (ImporteMN91).RoundSQL
If UsaComplementariaClientes = True AndAlso Dr("TCCambioValuacion").ToString.ToDecimal > 1 Then
ImporteMN251 = Importe251
Dim ImporteComplementarioNC As Decimal = ((Importe251 * Dr("TCCambioValuacion").ToString.ToDecimal) - Importe251).RoundSQL
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=Dr("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementarioNC, ImporteME:=If(Dr("TCCambioValuacion").ToString.ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString.ToDecimal) Then
ErrorPrepoliza = True
Exit For
End If
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, Importe251, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=Dr("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteMN251, ImporteME:=If(Dr("TCCambioValuacion").ToString.ToDecimal = 1, 0, Importe251), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=Dr("TCCambioValuacion").ToString.ToDecimal, TipoCambioPago:=tipoCambio) Then
ErrorPrepoliza = True
Exit For
End If
'considero fluctuación.
If TipoCambioNC <> TCFluctuacion AndAlso TCFluctuacion > 1 AndAlso TipoCambioNC > 1 Then
Dim difFluctuacion As Decimal = TipoCambioNC - TCFluctuacion
Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida
Dim TipoMovtoFluctua As Boolean = True
Dim IdCtaContableFluctua As Integer
If difFluctuacion < 0 Then
CveConceptoFluctua = 65
TipoMovtoFluctua = False
IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria
CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria
Else
CveConceptoFluctua = 64
TipoMovtoFluctua = True
IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria
CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria
End If
Dim ImporteFluctuacion As Decimal = Math.Abs((Importe251 * difFluctuacion).RoundSQL)
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=Dr("CveVenta").ToString.ToEntero, ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=TipoCambioNC, TipoCambioPago:=Dr("TCCambioValuacion").ToString.ToDecimal, CveCuenta:=CveCuenta) Then
ErrorPrepoliza = True
Exit For
End If
End If
Next
If ImporteConcepto12 < ImporteAcumulado91 Then
Dim ImporteOtrosIngresos As Decimal = ImporteConcepto12 - ImporteAcumulado91
If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ImporteOtrosIngresos, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveUltimaVenta, ImporteMX:=ImporteOtrosIngresos, ImporteME:=0, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio) Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ImporteOtrosIngresos, Referencia, 211, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteME:=0, ImporteMX:=ImporteOtrosIngresos, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
Else
ErrorPrepoliza = True
End If
End If
If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 5) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
'ErrorPrepoliza = True
GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas")
'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA
'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then
' Dim DtTest = ObjConta.DtResultados
'End If
End If
End If
If ErrorPrepoliza Then
Exit For
End If
End If
'APLICA DEVOLUCION SALDOS DIRECTOS
If AplicaDevolucion Then
Dim importeMovimientoDev = TxtTotal.Text.ToDecimal
importeMovimientoDev = If(SaldoVentaDevolucion < importeMovimientoDev, SaldoVentaDevolucion, importeMovimientoDev)
If importeMovimientoDev > 0 Then
Dim importeMXDev = importeMovimientoDev * tipoCambio * Multiplicador
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimientoDev.FormatoNumero(2)}"
If UsaComplementariaClientes AndAlso tipoCambio > 1 Then
importeMXDev = importeMovimientoDev
Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * tipoCambio) - importeMovimientoDev).RoundSQL
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 203, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteComplementaria, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura) Then
ErrorPrepoliza = True
Exit For
End If
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimientoDev, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
Exit For
End If
If UsaComplementariaClientes AndAlso TipoCambioFactura > 1 Then
importeMXDev = importeMovimientoDev
Dim ImporteComplementaria As Decimal = ((importeMovimientoDev * TipoCambioFactura) - importeMovimientoDev).RoundSQL
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 207, Concepto, FechaMovimiento, IdCtaContableClienteComplementaria, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, ImporteMX:=ImporteComplementaria, ImporteME:=If(TipoCambioFactura = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar, CveVentaAmortizacion:=ObjFactura.CveVenta, TipoCambio:=TipoCambioFactura) Then
ErrorPrepoliza = True
Exit For
End If
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimientoDev, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVentaDevolucion, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMXDev, ImporteME:=If(tipoCambio = 1, 0, importeMovimientoDev), CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
Exit For
End If
If tipoCambio <> TipoCambioFactura Then
Dim difFluctuacion As Decimal = tipoCambio - TipoCambioFactura
Dim CveConceptoFluctua As Integer = 64 '64.ganacia, 65.perdida
Dim TipoMovtoFluctua As Boolean = True
Dim IdCtaContableFluctua As Integer
If difFluctuacion < 0 Then
CveConceptoFluctua = 65
TipoMovtoFluctua = False
IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria
CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria
Else
CveConceptoFluctua = 64
TipoMovtoFluctua = True
IdCtaContableFluctua = UsuarioActual.Empresa.IdCuentaGananciaCambiaria
CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria
End If
Dim ImporteFluctuacion As Decimal = Math.Abs((importeMovimientoDev * difFluctuacion).RoundSQL)
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovtoFluctua, ImporteFluctuacion, Referencia, CveConceptoFluctua, Concepto, FechaMovimiento, IdCtaContableFluctua, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=CveVentaDevolucion, ImporteMX:=ImporteFluctuacion, ImporteME:=ImporteFluctuacion, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, TipoCambioPago:=TipoCambioFactura, CveCuenta:=CveCuenta) Then
ErrorPrepoliza = True
Exit For
End If
End If
If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 5) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
'ErrorPrepoliza = True
GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas")
'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA
'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then
' Dim DtTest = ObjConta.DtResultados
'End If
End If
End If
End If
End If
End If
End If
Case 136 'Otros Conceptos Dinamicos
For Each row2 As GridViewRow In GVOtrosConceptos.Rows
If row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal > 0 Then
importeMovimiento = row2.FCTextBox("TxtCantidadConcepto").Text.ToDecimal * ValorMultiplicador
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
If row2.DataKey("IdCtaContable").ToEntero > 0 Then
IdCtaContable = row2.DataKey("IdCtaContable").ToEntero
Else
If ObjConta.GetRetCuenta(row2.DataKey("CveConceptoContable").ToEntero, ObjFactura.CveCliente) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContFondoGarantia").ToString.ToEntero
End If
End If
End If
If importeMovimiento <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, If(row2.DataKey("TipoMovto").ToString = "True", True, False), importeMovimiento, Referencia, row2.DataKey("CveConceptoContable").ToEntero, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
End If
End If
Next
importeMovimiento = 0
Case 11 'Anticipo
'[IPP] SI ES REFACTURACION LOS ANTICIPOS NO LOS DEBE APLICAR EN EL INGRESO REFACTURADO (VIEJO)
If NuevaFactura = 1 And ObjFactura.CveVenta = CveDevolucion Then
Exit Select
End If
If ObjFactura.TipoDocto = "Ing" AndAlso ValorMultiplicador = -1 Then
For Each row2 As GridViewRow In GvAntNC.Rows
If row2.DataKey("CveConceptoContable").ToString().ToEntero = 11 Then
importeMovimiento = row2.DataKey("Importe").ToString().ToDecimal * ValorMultiplicador '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal)
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
IdCtaContable = IdCtaContAnticipos
CveCuenta = CveCuentaAnticipos
CveSubProyectoContabilizar = CveSubProyectoVenta
If importeMovimiento <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
End If
Next
End If
'cuando es anticipo
' cuando es amortización de nota de crédito, y es la nc
' cuando es amortización por descuento, y es el ingreso
' cuando es amortización en cero
If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 2 AndAlso ObjFactura.TipoDocto.Contiene("Egs") OrElse
DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 1 AndAlso ObjFactura.TipoDocto.Contiene("Ing") OrElse
DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero = 3 Then
For Each row2 As GridViewRow In GVAnticipos.Rows
If row2.DataKey("CveConceptoContable").ToString().ToEntero = 3 Then
If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then
CveIEAnticipo = row2.DataKey("CveIE").ToString.ToEntero
importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal '- ((row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal / row2.DataKey("TotalAnticipo").ToDecimal) * row2.DataKey("IVAAnticipo").ToDecimal)
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
IdCtaContable = IdCtaContAnticipos
CveCuenta = CveCuentaAnticipos
CveSubProyectoContabilizar = CveSubProyectoVenta
If importeMovimiento <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Exit For
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
End If
End If
Next
End If
'Cuando la funcionalidad de amortizacion en PS esta activa
If Not ErrorPrepoliza Then
DT = TmpDTDetalle.FiltraParametros($"CvePS = {CvePSAmortizacion}")
If DT.Rows.Count > 0 Then
For Each Row2 As DataRow In DT.Rows
importeMovimiento = Math.Abs(Row2("PU").ToString.ToDecimal)
IdCtaContable = IdCtaContAnticipos
CveCuenta = CveCuentaAnticipos
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
If importeMovimiento <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveVentaAmortizacion:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
Next
End If
End If
'PorcentajeAmortizacion = sumaAmorticaciones / TxtTotal.Text.ToDecimal
importeMovimiento = 0
Case 91 'Amortizacion Nota de Credito
Dim Contabilizable = If(UsuarioActual.CveEmpresa = 119, False, True)
If ValorMultiplicador = -1 Then
'cuando es cancelación
For Each row2 As GridViewRow In GvNC.Rows
If row2.DataKey("CveConceptoContable").ToString().ToEntero = 91 Then
importeMovimiento = row2.DataKey("Importe").ToDecimal * ValorMultiplicador
sumaAmorticaciones += importeMovimiento
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
'CTACONTABLE
'IdCtaContable = IdCtaContAnticipos
'CveCuenta = CveCuentaAnticipos
IdCtaContable = ObjFactura.Cliente.IdCtaContClientes
CveCuenta = ObjFactura.Cliente.CveCuentaClientes
CveSubProyectoContabilizar = CveSubProyectoVenta
If importeMovimiento <> 0 Then
If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, importeMovimiento, Referencia, 251, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVentaNC").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, importeMovimiento, Referencia, 91, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString.ToEntero, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then
ErrorPrepoliza = True
Exit For
End If
Else
ErrorPrepoliza = True
Exit For
End If
'If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=row2.DataKey("CveVentaNC").ToString.ToEntero, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then
' ErrorPrepoliza = True
'End If
End If
End If
Next
Else
For Each row2 As GridViewRow In GVAnticipos.Rows
If row2.DataKey("CveConceptoContable").ToString().ToEntero = 12 Then
If row2.FCCheckBox("Chk" & row2.RowIndex).Checked Then
importeMovimiento = row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal
sumaAmorticaciones += importeMovimiento
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
IdCtaContable = IdCtaContAnticipos
CveCuenta = CveCuentaAnticipos
CveSubProyectoContabilizar = CveSubProyectoVenta
If importeMovimiento <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=row2.DataKey("CveVenta").ToString.ToEntero, CveCliente:=ObjFactura.CveCliente, CveVentaAmortizacion:=ObjFactura.CveVenta, ImporteMX:=importeMovimiento * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then
ErrorPrepoliza = True
End If
End If
End If
End If
Next
If sumaAmorticaciones <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, sumaAmorticaciones, Referencia, 251, Concepto, FechaMovimiento, IdCtaContClientes, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=sumaAmorticaciones * tipoCambio, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=Contabilizable) Then
ErrorPrepoliza = True
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
End If
importeMovimiento = 0
Case 4 'Venta Clasificacion
If Not ObjFactura.TipoDocto.Contiene("Rem", "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
' If UsuarioActual.CveEmpresa = 119 Then
'código fijo en base el porcentaje iva, que se afecten las clasificaciones
For i = 0 To TmpDTDetalle.Rows.Count - 1
'se excluyen las clasificaciones anteriores para que se asignen las de ingreso
If Not TmpDTDetalle(i)("CveClasificacion").ToString.Contiene("19958", "19933", "18097") Then
'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then
' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then
' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8%
' Else
' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16%
' End If
' Else
' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0%
' End If
'reclasifica la clasificación del producto, por la del ingreso correspondiente a su iva
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal).Rows.Count > 0 Then
TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal).Rows(0)("CveClasificacion").ToString
End If
End If
Next
' End If
DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto"})
If DT.Rows.Count > 0 Then
'Se agrega movimiento separado por la cuenta de ventas (ER)
For Each Row2 As DataRow In DT.Rows
importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal) * ValorMultiplicador
importeMX = importeMovimiento * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
Concepto = $"{ViewState("VentaFolio").ToString} {If(Row2("CveClasificacion").ToString.ToEntero > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"), "")} - {If(Row2("CveSubProyecto").ToString.ToEntero > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString}"), "Sin SubProyecto Asignado")}"
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas
If ObjFactura.TipoDocto.Contiene("Egs") Then
IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero
Else
IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero
End If
CveCuenta = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresosSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero
If importeMovimiento <> 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"))
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"))
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta) Then
ErrorPrepoliza = True
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
Next
End If
End If
importeMovimiento = 0
Case 150 'Descuento sobre ventas
If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then
Dim ConceptoContableAplicar = 150
Dim CveVentaAplicar = ObjFactura.CveVenta
Dim CveVentaAmortizacionAplicar = -1
'cuando es NC, por amortización de anticipo, no debe de registrar el concepto 11,
'pero cuando es NC y se aplicó anticipo, debe de restarle el importe
If ObjFactura.TipoDocto.Contiene("Egs") And CveAnticipo > 0 Then
ConceptoContableAplicar = 11
CveVentaAplicar = CveAnticipo
CveVentaAmortizacionAplicar = ObjFactura.CveVenta
End If
If UsuarioActual.CveEmpresa = 119 Then
'código fijo en base el porcentaje iva, que se afecten las clasificaciones
For i = 0 To TmpDTDetalle.Rows.Count - 1
'se excluyen las clasificaciones anteriores para que se asignen las de ingreso
If Not TmpDTDetalle(i)("CveClasificacion").ToString.Contiene("19958", "19933", "18097") Then
'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then
' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then
' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8%
' Else
' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16%
' End If
'Else
' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0%
'End If
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then
TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveClasificacion").ToString
End If
End If
Next
End If
DT = TmpDTDetalle.FiltraParametros($"CvePS <> {CvePSAmortizacion}", "", {"CveClasificacion", "CveSubProyecto"})
If DT.Rows.Count > 0 Then
'Se agrega movimiento separado por la cuenta de ventas (ER)
For Each Row2 As DataRow In DT.Rows
importeMovimiento = (TmpDTDetalle.SUM("TotalImporte", String.Format("CveClasificacion = {0} And CveSubProyecto = {1}", Row2("CveClasificacion"), Row2("CveSubProyecto"))).ToString.ToDecimal) * ValorMultiplicador
importeMX = importeMovimiento * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
Concepto = $"{ViewState("VentaFolio").ToString} {If(Row2("CveClasificacion").ToString.ToEntero > 0, GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"), "")} - {If(Row2("CveSubProyecto").ToString.ToEntero > 0, GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimeroValor("SubProyecto", $"CveSubProyecto = {Row2("CveSubProyecto").ToString}"), "Sin SubProyecto Asignado")}"
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
'Nota cuando es Nota de crédiot, debe de tomar el devoluciones y rebajas
If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then
IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero
Else
IdCtaContable = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresos", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero
End If
If UsuarioActual.CveEmpresa = 119 Then
If Row2("CveClasificacion").ToString = "19930" Then IdCtaContable = 1141
If Row2("CveClasificacion").ToString = "19929" Then IdCtaContable = 1142
End If
CveCuenta = GlobalDTClasificaciones(ObjFactura.CveEmpresa).FiltroPrimeroValor("IdCuentaIngresosSIG", String.Format("CveClasificacion = {0}", Row2("CveClasificacion"))).ToEntero
If importeMovimiento <> 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"))
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString + GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("Clasificacion", $"CveClasificacion = {Row2("CveClasificacion").ToString}"))
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContableAplicar, Concepto, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVentaAplicar, CveVentaAmortizacion:=CveVentaAmortizacionAplicar, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, CveClasificacion:=Row2("CveClasificacion").ToString.ToEntero, CveSubProyecto:=Row2("CveSubProyecto").ToString.ToEntero, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta) Then
ErrorPrepoliza = True
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
Next
End If
End If
importeMovimiento = 0
Case 103 'Descuento
If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") AndAlso DdlTipoAmortizacionAnticipo.SelectedValue = "-1" Then
importeMovimiento = ObjFactura.Descuento * ValorMultiplicador
importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
CveSubProyectoContabilizar = CveSubProyectoVenta
If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString.ToEntero
'CveCuenta = ObjConta.DtResultados.Rows(0)("Conta_IdCuentaDescuentoVenta").ToString.ToEntero
End If
End If
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
If importeMovimiento > 0 AndAlso UsuarioActual.CveEmpresa = 119 Then
'código fijo en base el porcentaje iva, que se afecten las clasificaciones
For i = 0 To TmpDTDetalle.Rows.Count - 1
'If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal > 0 Then
' If TmpDTDetalle(i)("PorcentajeIVA").ToString.ToDecimal = 0.08 Then
' TmpDTDetalle(i)("CveClasificacion") = 20242 'clasif: ventas tasa 8%
' Else
' TmpDTDetalle(i)("CveClasificacion") = 19929 'clasif: ventas tasa 16%
' End If
'Else
' TmpDTDetalle(i)("CveClasificacion") = 19930 'clasif: ventas tasa 0%
'End If
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then
TmpDTDetalle(i)("CveClasificacion") = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveClasificacion").ToString
End If
Next
End If
End If
Case 103 'Descuento
'si se amortiza anticipo por concepto de descuento, no debe de registrar esta partida.
If DdlTipoAmortizacionAnticipo.SelectedValue <> "1" Then
importeMovimiento = ObjFactura.Descuento * ValorMultiplicador
importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
IdCtaContable = 0
End If
Case 8 'Ret IVA por Trasladar
If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") Then
importeMovimiento = ObjFactura.RetIVA * ValorMultiplicador
importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
'Contabilidad ContPAQ
If IdCtaContRetIVA > 0 Then
IdCtaContable = IdCtaContRetIVA
Else
If ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero
End If
End If
End If
'Contabilidad SIG
If CveCuentaRetIVA > 0 Then
CveCuenta = CveCuentaRetIVA
Else
If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero
End If
End If
End If
End If
Case 9 'Ret ISR por Trasladar
If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") Then
importeMovimiento = ObjFactura.RetISR * ValorMultiplicador
importeMX = Math.Round(importeMovimiento, 2) * tipoCambio * Multiplicador
FechaMovimiento = ObjFactura.FechaPago
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
'Contabilidad ContPAQ
If IdCtaContRetISR > 0 Then
IdCtaContable = IdCtaContRetISR
Else
If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero
End If
End If
End If
'Contabilidad SIG
If CveCuentaRetISR > 0 Then
CveCuenta = CveCuentaRetISR
Else
If ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero
End If
End If
End If
End If
Case 13 'Iva por Trasladar
If Not ObjFactura.TipoDocto.Contiene("Rem", "RNC") Then
importeMovimiento = ObjFactura.IVA * ValorMultiplicador
importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2)
FechaMovimiento = ObjFactura.FechaPago
PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal
IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar)
CveCuenta = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar)
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
End If
Case 38 'IEPS por Trasladar
If Not ObjFactura.TipoDocto.Contiene("Rem") Then
importeMovimiento = ObjFactura.IEPS * ValorMultiplicador
importeMX = Math.Round(importeMovimiento * tipoCambio * Multiplicador, 2)
FechaMovimiento = ObjFactura.Fecha
CveSubProyectoContabilizar = CveSubProyectoVenta
If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}"
If importeMovimiento <> 0 AndAlso ObjConta.GetRetCuenta(ConceptoContable, ObjFactura.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxTrasladar").ToString.ToEntero
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaIEPSxTrasladarSIG").ToString.ToEntero
End If
End If
End If
Case 30 'PAGO - BANCOS
If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then
For Each DrPago As DataRow In DtPagos.Rows
CveIEPago = -1
FolioIE = -1
FolioIE = ObjBancos.GetNextFolio(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero)
If Not FolioIE > 0 Then
ErrorPrepoliza = True
Exit For
End If
CveIEPago = ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, Fecha, FolioIE.ToString, String.Format("PAGO: {0}", TxtFolio.Text), DrPago("Importe").ToString.ToDouble, DdlMoneda.SelectedValue.ToEntero, tipoCambio, DrPago("Observaciones").ToString, "", False, False, -1, ObjFactura.CvePrePoliza, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte)
If CveIEPago > 0 Then
importeMovimiento = DrPago("Importe").ToString.ToDecimal * ValorMultiplicador
importeMX = importeMovimiento * tipoCambio * Multiplicador
IdCtaContable = 0
CveCuenta = 0
CveSubProyectoContabilizar = CveSubProyectoVenta
Dim PorcentajeImpuestoPago As Decimal = TmpDT.MAX("PorcentajeIVA").ToDecimal
If GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows.Count = 1 Then
IdCtaContable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContable").ToString.ToEntero
CveCuenta = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContableSIG").ToString.ToEntero
End If
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.AppendFormat("<br> {0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.AppendFormat("<br> {0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero)
CveCuentaContabilizacion = 0
End If
'BANCOS
Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString)
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then
ErrorPrepoliza = True
Exit For
End If
'CLIENTES
Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 2, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString)
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 2, Concepto, Fecha, IdCtaContableCliente, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
Exit For
End If
'IVA X TRASLADAR
IdCtaIVAXTrasladar = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar)
CveCuentaIVAxTrasladar = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar)
Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString)
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 13, Concepto, Fecha, IdCtaIVAXTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVAxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then
ErrorPrepoliza = True
Exit For
End If
'IVA PAGADO
IdCtaIVATrasladado = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado)
CveCuentaIVATrasladado = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado)
Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString)
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 61, Concepto, Fecha, IdCtaIVATrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVATrasladado, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then
ErrorPrepoliza = True
Exit For
End If
'IEPS X TRASLADAR
Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString)
If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
Exit For
End If
'IEPS PAGADO
Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, NombreCliente, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString)
If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSTrasladado, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
Exit For
End If
Else
ErrorPrepoliza = True
Exit For
End If
Next
importeMovimiento = 0
End If
End Select
If importeMovimiento <> 0 And Not ErrorPrepoliza Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, TipoCambio:=tipoCambio, PorcentajeImpuesto:=PorcentajeImpuesto, Contabilizable:=SeContabiliza) Then
ErrorPrepoliza = True
Else
ViewState("SeGuardoPrePoliza") = True
End If
End If
If ErrorPrepoliza Then
Exit For
End If
Next
End If
'Si es Facturacion de una remision cancelamos, traspasamos saldos y agregamos evento a la bitacora
If RemisionesLista.Count > 0 Then
'se verifica que el documento que se está generando sea "Ing", "Ant"
If Not ObjFactura.TipoDocto.Contiene("Ing", "Ant") Then
ErrorPrepoliza = True
ErrorList.Add("No se pueden facturar las remisiones, con ese tipo de comprobante seleccionado")
Else
For Each CveRemision As Integer In RemisionesLista
If Not ObjConta.TraspasarSaldosRemision(CveRemision, ObjFactura.CvePrePoliza, ObjFactura.CveVenta) Then
ErrorPrepoliza = True
End If
'Factura
If Not ObjEventos.AddEventoBitacora($"Sustituye a: <a href='/Ventas/Ventas.aspx?CveVenta={CveRemision}' target='_blank' class='Texto'>Folio Factura</a>", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then
ErrorPrepoliza = True
End If
'Remision
If Not ObjEventos.AddEventoBitacora($"Refacturacion en: <a href='/Ventas/Ventas.aspx?CveVenta={ObjFactura.CveVenta}' target='_blank' class='Texto'>{ObjFactura.Folio}</a>", "-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: <a href='/Ventas/Ventas.aspx?CveVenta={ObjFactura.CveVenta}' target='_blank' class='Texto'>{TxtFolio.Text}</a>", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Dr("CveVenta").ToString.ToEntero) Then
ErrorPrepoliza = True
End If
End If
Next
End If
End If
If NuevaFactura = 1 AndAlso TotalOriginal > TxtTotal.Text.ToDouble AndAlso ObjEventos IsNot Nothing Then
If Not ObjEventos.AddEventoBitacora($"Factura a menor precio de la factura origen.", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then
ErrorPrepoliza = True
Else
Alert("Factura a menor precio de la factura origen.", TipoMensaje.MsgAdvertencia)
End If
End If
If ObjConta.ValidacionPrePolizaCuadre(ObjFactura.CvePrePoliza, 2) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
If ObjConta.ValorPolizaDescuadre = 2 Then
ErrorPrepoliza = True
Alert(ObjConta.MensajePolizaDescuadre, TipoMensaje.MsgError)
End If
'ErrorPrepoliza = True
GuardaLogAD($"Ventas/Ventas-ProcesoPrePolizas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{ObjFactura.CvePrePoliza}", "LogPrePolizas")
'SIRVE PARA VER LA PREPOLIZA QUE SE VALIDA
'If ObjConta.GetPrePolizasDetalle(ObjFactura.CvePrePoliza) Then
' Dim DtTest = ObjConta.DtResultados
'End If
End If
End If
'Simplificacion de PrePolizas
If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then
If Not ObjConta.PrePolizaSimplificacion(ObjFactura.CvePrePoliza, UsuarioActual.CveEmpresa) Then
Alert("No se pudo simplificar los movimientos", TipoMensaje.MsgError)
End If
End If
'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) Then
ErrorPrepoliza = True
End If
End If
Return ErrorPrepoliza
Catch ex As Exception
GuardaLog(ex.ToString())
Return True
End Try
End Function
Private Function GuardarVentaInventarios(ObjInventario As ClsInventarios, ObjConta As ClsContabilidad, factura As Modelos.Factura) As Boolean
Dim OcurrioError As Boolean = False
Try
If UsuarioActual.Empresa.UsaInventarios AndAlso factura.TipoDocto.Contiene("Ing", "Egs", "Rem") Then
If RemisionesLista.Count > 0 Then
For Each CveRemision As Integer In RemisionesLista
'El almacen general es el Primer Almacen de Material en la Sucursal
If Not TraspasoAlmacen(ObjInventario, CveRemision, ObjConta, True, 9) Then
OcurrioError = True
Exit For
End If
Next
End If
If GvInv.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("cbInv").Checked) > 0 Then
Dim CveAlmacen = ddlAlmacen.SelectedValue.ToEntero
Dim CveMovimientoInventario As Integer = ObjInventario.AddMovimiento(CveAlmacen, 3, factura.CveMoneda, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1)
If CveMovimientoInventario <= 0 Then
OcurrioError = True
ErrorList.Add("Ocurrió un error al agregar los Movimientos de salida al Inventario.<br />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 Double
'DtInv.Clone()
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
If Dr("CveTipoInvPS").ToString.ToEntero = 5 And Dr("SerieLote").ToString = "" Then
OcurrioError = True
ErrorList.Add("Se deben especificar las Series de los productos de almacén")
Exit For
End If
If UsuarioActual.CveEmpresa.Contiene({72, 80, 119}) AndAlso DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") 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)
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
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, Cantidad, CveUnidad, CveProducto, 0, -1, SerieLote:=Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then
OcurrioError = True
ErrorList.Add("Ocurrió un error al agregar los Movimientos de salida al Inventario.<br />")
Exit For
End If
Else
OcurrioError = True
ErrorList.Add("Ocurrió un error al agregar los Movimientos de salida al Inventario.<br />")
Exit For
End If
End If
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
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, False, 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, True, 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
End If
End If
factura.Inv_CveMovimiento = CveMovimientoInventario
factura.Inv_ValorInventario = ValorInventario
End If
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.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico")
End If
End If
End Sub
Private Sub GuardarVentaAC(ObjVentas As ClsVentas, factura As Modelos.Factura, Msgok As StringBuilder, ObjAC As ClsContPAQi)
If UsuarioActual.Empresa.UsaAC Then
If factura.TipoDocto.Contiene("Ing", "Egs", "OP", "Com") Then
'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL()
Dim IDPoliza As Integer = GenerarPolizaAC(ObjAC, factura)
If IDPoliza > 0 Then
If ObjVentas.UpdateVentaPrePoliza(IDPoliza, factura.CvePrePoliza, factura.CveVenta, factura.CveEmpresa) Then
'Si se facturó la cotización hay que vincular la venta
Msgok.AppendFormat("Abono Registrado Correctamente.<br/><br/> <a href='/Contabilidad/RegPoliza.aspx?IdPoliza={0}' target='_blank' class='Texto'>Ver Poliza</a>", IDPoliza)
End If
Else
ErrorList.Add("Ocurrió un error al generar A.C. en la Factura.<br />Revise su factura y cualquier detalle comuníquese a Soporte Técnico")
End If
Else
Msgok.Append("Movimiento Registrado Correctamente.<br/><br/> ")
End If
End If
End Sub
Private Function GuardarVentaImpuestosLocales(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, Factura As Modelos.Factura, Optional ValorMultiplicador As Integer = 1) As Boolean
Dim ErrorPrepoliza As Boolean = False
If TmpDTImpuestos IsNot Nothing AndAlso Factura.CvePrePoliza > 0 AndAlso Not DdlTipoComprobante.SelectedValue.Contiene("Cot", "Rem") Then
Dim Importe As Decimal
Dim IdCtaContable, CveCuenta As Integer
Dim Concepto As String
Dim tipoCambio As Decimal
Dim CveSubProyectoContabilizar = DdlSubProyectoDatos.SelectedValue.ToEntero
For Each RowIL As DataRow In TmpDTImpuestos.Rows
If RowIL("TipoImpuesto").ToString.ToEntero > 0 Then
Importe = RowIL("Importe").ToString.ToDecimal * ValorMultiplicador
IdCtaContable = RowIL("IdCtaContable").ToString.ToEntero
CveCuenta = RowIL("IdCtaContable").ToString.ToEntero
Concepto = ViewState("VentaFolio").ToString
If ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio > 0 Then
tipoCambio = Factura.TipoCambio
ElseIf ObjFactura.CveMoneda = 2 AndAlso ObjFactura.TipoCambio <= 1 Then
tipoCambio = GlobalTipoCambio(Factura.Fecha).ToString.ToDecimal
Else
tipoCambio = 1
End If
Select Case RowIL("TipoImpuesto").ToString
Case "1"
If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
Case "3"
If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 116, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
Case "4"
If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, False, Importe, Concepto, 58, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
Case "5"
If Not ObjConta.AddPrePolizasDetalle(Factura.CvePrePoliza, True, Importe, Concepto, 27, Concepto, Factura.Fecha, IdCtaContable:=IdCtaContable, IdSegmentoNegocio:=-1, CveVenta:=Factura.CveVenta, CveCliente:=Factura.CveCliente, ImporteMX:=Importe * tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then
ErrorPrepoliza = True
End If
End Select
End If
Next
End If
Return ErrorPrepoliza
End Function
Private Function generaNC(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, ByRef ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ByRef ObjBancos As ClsBancos, ByRef ObjEventos As ClsOIEventos) As List(Of Object)
Dim Obj As New List(Of Object)
Dim CveVentaNueva As Integer = ObjVentas.CveVenta
Dim BanderaGeneraNC As Boolean = True
'If UsuarioActual.CveEmpresa.Contiene(1, 119) Then BanderaGeneraNC = True
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then
Dim drv As DataRow = ObjVentas.DtResultados.Rows(0)
Dim TmpDTconceptos As DataTable = Nothing
Dim CveNCaVincular As Integer = DdlNCFactura.SelectedValue.ToEntero
'CargaCliente
Dim CveCliente As Integer = drv("CveCliente").ToString.ToEntero
If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then
Return Nothing
ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then
Return Nothing
End If
factura.TipoDocto = drv("TipoDocto").ToString
factura.Serie = drv("Serie").ToString
factura.FechaEjecucion = drv("FechaEjecucion").ToString.ToDateTime
factura.Fecha = drv("Fecha").ToString.ToDateTime
factura.CveSubProyectoEjecucion = drv("CveSubProyectoEjecucion").ToString.ToEntero
factura.CveSubProyectoCobranza = drv("CveSubProyectoCobranza").ToString.ToEntero
factura.CveClienteSucursal = drv("CveClienteSucursal").ToString.ToEntero
factura.CveSubProyecto = drv("CveSubProyecto").ToString.ToEntero
'Carga Detalle Sucursal
CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero, ObjVentas)
'CargaDetalle
If ObjVentas.GetVentaDetalle(CveVenta) Then
TmpDTconceptos = ObjVentas.DtResultados
TmpDTconceptos.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
GvPS.DataSource = TmpDTconceptos
GvPS.DataBind()
End If
'Carga Totales
factura.SubTotal = drv("SubTotal").ToString.ToDecimal
factura.Descuento = drv("Descuento").ToString.ToDecimal
factura.Amortizacion = drv("Amortizacion").ToString.ToDecimal
factura.IVA = drv("IVA").ToString.ToDecimal
factura.RetIVA = drv("RetIVA").ToString.ToDecimal
factura.RetISR = drv("RetISR").ToString.ToDecimal
factura.Total = drv("Total").ToString.ToDecimal
factura.MotivoDescuento = drv("MotivoDescuento").ToString
factura.Observaciones = drv("Observaciones").ToString
factura.CveMoneda = drv("CveMoneda").ToString.ToEntero
factura.TipoCambio = drv("TipoCambio").ToString.ToDecimal
factura.CveVendedor = drv("CveVendedor").ToString.ToEntero
factura.RefDocto = drv("Ref").ToString
'factura.SerieFolioPadre = drv("SerieFolio").ToString
HdnFolioFiscalNC.Value = drv("FolioFiscal").ToString
ViewState("FolioFiscal") = drv("FolioFiscal").ToString
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
UpContado.Update()
If factura.CveCliente > 0 Then
If Not IsNothing(TmpDTconceptos) AndAlso TmpDTconceptos.Rows.Count > 0 Then
If Not drv("Total").ToString.ToDecimal = factura.Total Then
Return Nothing
End If
If FolioFiscal = "" Then
CveEstatus = 4
Else
CveEstatus = 5
End If
'[IPP] - CANCELA INVENTARIO DE VENTA NUEVA Y NO TRASPASA MOVTOS DE ALMACEN
'If UsuarioActual.CveEmpresa.Contiene(1) Then
'QUEMA DOCUMENTO NUEVO
If Not ObjInventario.ActualizarEsDevolucionVenta(CveVentaNueva, 2) Then
Return Nothing
End If
'Else
' 'TRASPASA ALMACEN A DOCUMENTO NUEVO
' If Not CancelarMovimientoInventario(ObjInventario, ObjConta, CveVentaNueva, CveDevolucion) Then
' Return Nothing
' End If
'End If
'CANCELA PAGOS
If ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Ant") Then
If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, ObjFactura.CvePrePoliza) Then
Return Nothing
End If
End If
'CANCELA FACTURA
BanderaGeneraNC = True
'2019.05.10- RMF. se activa la bandera a true, para que siempre se cancele, y no genere la NC
If Month(factura.Fecha) = Month(Now) OrElse BanderaGeneraNC = True Then
If CancelarFactura(ObjVentas, ObjConta, ObjContPaq, ObjBancos) Then
Obj.Add(factura)
Else
Return Nothing
End If
Else
ObjFacturaDevolucion.TipoDocto = "Egs"
ObjFacturaDevolucion.Fecha = Now
If RegistrarNC(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjContPaq, ObjFacturaDevolucion, ObjBancos, TmpDTconceptos, ObjEventos) Then
Obj.Add(ObjFacturaDevolucion)
Else
Return Nothing
End If
End If
'TRASPASA PAGADO
If Not ObjConta.TraspasarSaldosPrePolizas(CveDevolucion, ObjFactura.CveVenta, ObjFactura.CvePrePoliza) Then
Return Nothing
End If
If Not ObjInventario.TraspasaEntregaDirectaOCInv(ObjFactura.CveVenta, UsuarioActual.CveEmpresa) Then
Return Nothing
End If
End If
End If
End If
End If
If Obj.Count > 0 Then
Return Obj
Else
Return Nothing
End If
End Function
Private Function RegistrarNC(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean
Dim ProcesoCorrecto As Boolean = True
RefacturacionGeneroNC = True
''Generamos el nuevo folio
'Dim ObjFolios As New ClsGralFolios(ObjVentas.IniciaTransacSQL())
'If ObjFolios.GetFolios(factura.TipoDocto, UsuarioActual.CveEmpresa) Then
' Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue))
' If DT.Rows.Count > 0 Then
' factura.Folio = DT.Rows(0)("FActual").ToString.ToEntero
' Else
' ProcesoCorrecto = False
' End If
' DT.Dispose()
'End If
factura.Folio = -1
'Registramos la venta
GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, factura, TmpDTconceptos, -1, ObjContPaq, ObjBancos)
'CargaNCDT(factura.CveVentaPadre, factura.Total)
'ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion)
''Timbramos
'If factura.TipoDocto.Contiene("Ing", "Egs", "Ant") AndAlso FolioFiscal <> "" Then
' If UsuarioActual.Empresa.TipoFacturacion = "CFDi" AndAlso UsuarioActual.Empresa.FacturaProduccion Then
' Dim sw As New Diagnostics.Stopwatch
' sw.Start()
' 'FACTURA INGRESO/EGRESO
' Dim ObjTimbrado As New Modelos.Timbrado
' Dim FM As New Modelos.FemsaFactura
' Dim TmpDT7Eleven As New DataTable
' Dim TmpDTComplementosTimbrado As New DataTable
' PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado)
' ObjTimbrado.TimbrarFactura(UsuarioActual, factura, FM, TmpDT, TmpDTImpuestos, TmpDT7Eleven, TmpDTComplementosTimbrado, Ruta, LstFordASN, TxtFordGSDB.Text, ObjVentas)
' sw.Stop()
' GuardaLogTimbrado(sw.ElapsedMilliseconds.ToString, UsuarioActual.Empresa.CvePAC)
' ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then
' GeneraPDFCBB(ObjFactura.Fecha, Nothing, ObjFactura.SerieFolio, False)
' End If
'End If
If ErrorList.Count > 0 Then
ProcesoCorrecto = False
End If
Return ProcesoCorrecto
End Function
#End Region
#Region " VISTA PREVIA NEW "
Private Sub VistaPreviaNew()
If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")")
Exit Sub
End If
CreaObjetosVenta(True)
If ObjFactura Is Nothing Or ObjFactura.Cliente Is Nothing Then
Alert("Ocurrió un error al procesar los datos para la vista previa. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgError)
ObjFactura = Nothing
Exit Sub
End If
If UsuarioActual.Empresa.CvePlataforma = 2 Then
PdfFacturaPyME(ObjFactura, TmpDT)
Else
'REINICIA VALORES DE CONVERSION DE MONEDA
'If Not ObjFactura.ConvertirPesos And ChkConvertirDoctoPesos.Checked Then
' For Each Row As DataRow In TmpDT.Rows
' Row("PU") = Row("PU").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal
' Row("Total") = Row("Cantidad").ToString.ToDouble / Row("PU").ToString.ToDouble
' Row("Descuento") = Row("Descuento").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal
' Row("IEPS") = Row("IEPS").ToString.ToDouble / TxtTipoCambio.Text.Trim.ToDecimal
' Next
'End If
Select Case ConversionRemision
Case "*"
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Next
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TipoCambioRemision, NumeroDecimales)).FormatoNumero
End If
Next
Case "/"
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Next
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TipoCambioRemision, NumeroDecimales)).FormatoNumero
End If
Next
Case Else
End Select
ImprimirbytesPDF(PdfFactura(ObjFactura), "Factura", "PDF")
Select Case ConversionRemision
Case "*"
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble * TipoCambioRemision, NumeroDecimales)
Next
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TipoCambioRemision, NumeroDecimales)).FormatoNumero
End If
Next
Case "/"
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDouble / TipoCambioRemision, NumeroDecimales)
Next
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TipoCambioRemision, NumeroDecimales)).FormatoNumero
End If
Next
Case Else
End Select
'PdfFacturaPyME(ObjFactura, TmpDT)
End If
End Sub
#End Region
#Region "¡ P D F R E P O R T V I E W E R !"
Private Sub GeneraPDFFactura(EnviaCorreo As Boolean)
'CASO ESPECIAL
If UsuarioActual.CveEmpresa = 8 AndAlso ObjFactura.TipoDocto.Contiene("Cot") Then
Dim params As New List(Of ReportParameter)
params.Add(New ReportParameter("Sucursal", DdlSubProyectoDatos.SelectedItem.Text))
'params.Add(New ReportParameter("Fecha", FechaCotizacion.ToString))
params.Add(New ReportParameter("Folio", ObjFactura.Folio.ToString))
params.Add(New ReportParameter("Cliente", LtlCliente.Text))
params.Add(New ReportParameter("PersonaDirige", TxtAtencionA.Text))
params.Add(New ReportParameter("Total", TxtTotal.Text))
params.Add(New ReportParameter("Observaciones", TxtObsFact.Text))
params.Add(New ReportParameter("Vendedor", DdlVendedor.SelectedItem.Text))
params.Add(New ReportParameter("PersonaDirige", TxtAtencionA.Text.Trim))
'params.Add(New ReportParameter("Folio", ""))
ImprimirPDF(String.Format("{0}Formatos\Cotizacion.rdlc", UsuarioActual.Empresa.Ruta), TmpDT, params, "Cotización", RDSName:="DsCotizacion")
End If
'Dim pdf As Byte() = Nothing
'GUARDA PDF
Dim LocalSerieFolio As String = String.Empty
Dim LocalTipoDocto As String = String.Empty
'TIMBRADO NUEVO
Try
PdfFactura(ObjFactura)
'If DdlTipoComprobante.SelectedValue = "Ing" Or DdlTipoComprobante.SelectedValue = "Ant" Then
' PdfFactura(ObjFactura)
' 'Else
' ' pdf = PdfFactura(ObjFactura)
'End If
Catch ex As Exception
Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError)
End Try
LocalSerieFolio = ObjFactura.SerieFolio
LocalTipoDocto = ObjFactura.TipoDocto
'End If
'MANDA CORREO
If EnviaCorreo Then
Dim ArchivoXML = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio)
Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio)
Try
' BytesPdfCotizacion(CveVenta)
Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF))
Hilo.Start()
Catch ex As Exception
OnError("Ocurrió error al mandar Mail", ex)
Dim ObjVentas As New ClsVentas
If ChkEnviarFactura.Checked Then
ObjVentas.UpdateVentaMail(3, CveVenta)
Else
ObjVentas.UpdateVentaMail(0, CveVenta)
End If
ObjVentas.Dispose()
End Try
End If
End Sub
Private Sub GeneraPDFCotizacion(EnviaCorreo As Boolean)
Dim pdf As Byte() = Nothing
'GUARDA PDF
Dim LocalSerieFolio As String = String.Empty
Dim LocalTipoDocto As String = String.Empty
If CveVenta > 0 Then CreaObjetosVenta()
'TIMBRADO NUEVO
Try
pdf = PdfFactura(ObjFactura)
Catch ex As Exception
Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError)
End Try
LocalSerieFolio = ObjFactura.SerieFolio
LocalTipoDocto = ObjFactura.TipoDocto
'MANDA CORREO
If EnviaCorreo Then
Dim ArchivoXML = ""
Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio)
Try
' BytesPdfCotizacion(CveVenta)
Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF))
Hilo.Start()
Catch ex As Exception
OnError("Ocurrió error al mandar Mail", ex)
Dim ObjVentas As New ClsVentas
If ChkEnviarFactura.Checked Then
ObjVentas.UpdateVentaMail(3, CveVenta)
Else
ObjVentas.UpdateVentaMail(0, CveVenta)
End If
ObjVentas.Dispose()
End Try
End If
End Sub
Private Sub EnviaPDFRemision(EnviaCorreo As Boolean)
'MANDA CORREO
If EnviaCorreo Then
'GUARDA PDF
Dim pdf As Byte() = Nothing
Dim LocalSerieFolio As String = String.Empty
Dim LocalTipoDocto As String = String.Empty
'TIMBRADO NUEVO
Try
pdf = PdfFactura(ObjFactura)
Catch ex As Exception
Alert("Ocurrió un error al generar el PDF", TipoMensaje.MsgError)
End Try
LocalSerieFolio = ObjFactura.SerieFolio
LocalTipoDocto = ObjFactura.TipoDocto
Dim ArchivoXML = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio)
Dim ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio)
Try
' BytesPdfCotizacion(CveVenta)
Dim Hilo As New System.Threading.Thread(Sub() MandaMails(CveVenta, ChkEnviarFactura.Checked, ArchivoXML, ArchivoPDF))
Hilo.Start()
Catch ex As Exception
OnError("Ocurrió error al mandar Mail", ex)
Dim ObjVentas As New ClsVentas
If ChkEnviarFactura.Checked Then
ObjVentas.UpdateVentaMail(3, CveVenta)
Else
ObjVentas.UpdateVentaMail(0, CveVenta)
End If
ObjVentas.Dispose()
End Try
End If
End Sub
#End Region
#Region " ANTICIPOS "
Private Sub CargaAnticipos(CveCliente As Integer)
HdnTieneAnticipos.Value = "0"
If CveCliente > 0 Then
HdnIVACalculado.Value = "0"
HdnFolioFiscalNC.Value = "0"
LblAntAplicados.Text = ""
LblAntAplicados.Visible = False
LblAmortizacion.Text = "0.00"
HdnTipoDescuento.Value = "-1"
HdnTieneAnticiposVinculados.Value = "0"
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, DdlMoneda.SelectedValue.ToEntero) Then
GVAnticipos.DataSource = ObjMovtos.DtResultados.FiltraParametros($"Saldo > 0 AND SaldoSubtotal > 0 {If(CveVenta < 0, "AND Tipo = 'Ant'", "")} {If(DdlTipoComprobante.SelectedValue = "Ant", "AND Tipo = 'NC'", "")}")
If ObjMovtos.DtResultados.SUM("Saldo", "Saldo > 0 AND SaldoSubtotal > 0 AND Tipo = 'Ant'") > 0 Then
HdnTieneAnticipos.Value = "1"
End If
Else
GVAnticipos.DataSource = Nothing
End If
ObjMovtos.Dispose()
If CveVenta <= 0 OrElse (EsCreaApartirDe Or CveDevolucion > 0) Then
divAmortizacionTipo.Visible = True
divAmortizacionTipoRelacion.Visible = True
End If
If UsuarioActual.CveEmpresa.Contiene(1, 72, 80) Then
DdlTipoAmortizacionAnticipo.Items.Add(New ListItem("Amortización anticipo sobre factura en cero", "3"))
End If
If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then
DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1"))
End If
GVAnticipos.Columns(4).Visible = False
GVAnticipos.Columns(7).Visible = False
GVAnticipos.DataBind()
End If
UpAnticipos.Update()
End Sub
Protected Sub GVAnticipos_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowCreated
If e.Row.RowType = DataControlRowType.Header Then
e.Row.ClientIDMode = ClientIDMode.Static
e.Row.ID = String.Format("TrH{0}", e.Row.RowIndex)
ElseIf e.Row.RowType = DataControlRowType.DataRow Then
e.Row.ClientIDMode = ClientIDMode.Static
e.Row.ID = String.Format("Tr{0}", e.Row.RowIndex)
e.Row.FCCheckBox("Chk").ID = "Chk" & e.Row.RowIndex
e.Row.FCTextBox("TxtAnticipo").ID = "TxtAnticipo" & e.Row.RowIndex
e.Row.FCTextBox("TxtTC").ID = "TxtTC" & e.Row.RowIndex
DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ID = "CVAmortAnti" & e.Row.RowIndex
DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).ID = "VCOAmortAnti" & e.Row.RowIndex
DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ControlToValidate = "TxtAnticipo" & e.Row.RowIndex
DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).TargetControlID = "CVAmortAnti" & e.Row.RowIndex
End If
End Sub
Protected Sub GVAnticipos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Cells(1).Width = Unit.Pixel(60)
e.Row.Cells(2).Width = Unit.Pixel(100)
e.Row.Cells(3).Width = Unit.Pixel(80)
e.Row.Cells(4).Width = Unit.Pixel(80)
End If
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right
If e.Row.DataKey("Saldo").ToDouble < 0 Then e.Row.Cells(3).ForeColor = Drawing.Color.Red
If e.Row.DataKey("Saldo").ToDouble = 0 Then e.Row.FCLiteral("LtlAnticipos").Text = ""
Dim saldo As Decimal = 0
Dim tipoCambio As Decimal = 0
Dim total As Decimal = TxtTotal.Text.ToString.ToDecimal
If CveVentaRelacion > 0 Then ' dejo seleccionado el la venta relacionado en anticipo
If e.Row.DataKey("CveVenta").ToEntero = CveVentaRelacion Then
e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Checked = True
e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Text = ImporteRelacion.ToString
End If
End If
If e.Row.DBCampo("Tipo").ToString = "NC" And e.Row.DataKey("CveVenta").ToString.ToEntero > 0 Then
If e.Row.DBCampo("CveMoneda").ToString.ToEntero = 2 Then
tipoCambio = e.Row.DataKey("TipoCambio").ToString.ToDecimal
Else
tipoCambio = GlobalTipoCambio(e.Row.DataKey("Fecha").ToString.ToDate).ToDecimal
End If
e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Text = tipoCambio.FormatoNumero(4)
If DdlMoneda.SelectedValue.ToEntero = 1 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 1 Then
saldo = e.Row.DataKey("Saldo").ToDecimal
ElseIf DdlMoneda.SelectedValue.ToEntero = 2 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 1 And tipoCambio > 0 Then
saldo = (e.Row.DataKey("Saldo").ToString.ToDecimal / tipoCambio)
ElseIf DdlMoneda.SelectedValue.ToEntero = 1 And e.Row.DBCampo("CveMoneda").ToString.ToEntero = 2 Then
saldo = (e.Row.DataKey("Saldo").ToString.ToDecimal * tipoCambio)
Else
saldo = e.Row.DataKey("Saldo").ToDecimal
End If
Else
saldo = e.Row.DataKey("Saldo").ToString.ToDecimal
If CveVenta <= 0 Then
saldo = e.Row.DataKey("SaldoSubTotal").ToString.ToDecimal
e.Row.FCLiteral("LtlAnticipos").Text = saldo.FormatoNumero
End If
End If
Dim maxsaldo As Decimal
If total > saldo Then
maxsaldo = saldo
Else
maxsaldo = total
End If
e.Row.FCLiteral("MonedaVenta").Text = saldo.FormatoNumero(4)
e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Attributes.Add("onclick", String.Format("chkAnt(this,{0},{1});", e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, saldo))
e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, saldo))
e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("CambioTipoMoneda({0},{1},{2},{3},{4});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, e.Row.DataKey("Saldo"), e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).ClientID, e.Row.DataKey("CveMoneda")))
If e.Row.DataKey("CveIE").ToString.ToEntero > 0 Then
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Bancos/IE.aspx?CveIE={0}"">{1}</a>", e.Row.DataKey("CveIE"), e.Row.DataKey("Folio"))
Else
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a>", e.Row.DataKey("CveVenta"), e.Row.DataKey("Folio"))
End If
If e.Row.DataKey("ISTotal") = "1" Then
e.Row.Cells(0).Visible = False
e.Row.Cells(1).ColumnSpan = 3
e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Right
e.Row.FCLiteral("LtlFactura").Text = String.Format("Total {0} ", e.Row.DataKey("Tipo"))
e.Row.BackColor = Drawing.Color.LightGray
e.Row.Cells(2).Visible = False
e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Visible = False
e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False
e.Row.FCLabel("LblTotalAnticipos").Visible = True
e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right
End If
'SI UN REGISTRO ES DE DIFERENTE MONEDA AL DOCUMENTO SE MUESTRAN LAS COLUMNAS
If e.Row.DBCampo("CveMoneda").ToString.ToEntero > 0 And e.Row.DBCampo("CveMoneda").ToString.ToEntero <> DdlMoneda.SelectedValue.ToEntero Then
GVAnticipos.Columns(4).Visible = True
GVAnticipos.Columns(6).Visible = True
End If
If e.Row.DBCampo("CveMoneda").ToString.ToEntero = DdlMoneda.SelectedValue.ToEntero Then
e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False
End If
End If
End Sub
Protected Sub BtnAceptarAnticipos_Click(sender As Object, e As System.EventArgs) Handles BtnAceptarAnticipos.Click
Anticipos()
End Sub
Private Sub Anticipos()
If CveVenta > 0 And CveCliente > 0 And Not EsCreaApartirDe And CveDevolucion <= 0 Then
'Dim TotalAnticipo As Decimal = 0
'Dim DescuentoTotal As Decimal = LblDescuentos.Text.ToDecimal
'Dim CveSubProyecto As Integer = -1
'If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then
' CveSubProyecto = TmpDT.FiltroPrimeroValor("CveSubProyecto").ToEntero
'End If
Dim EsAnticipo2017Jam As Boolean = False
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then
If gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal > SaldoVenta Then
Alert("No puede ingresar un importe mayor al saldo", TipoMensaje.MsgAdvertencia)
Exit Sub
ElseIf UsuarioActual.CveEmpresa = 119 AndAlso gvr.DataKey("Tipo").ToString = "NC" AndAlso gvr.DataKey("Fecha").ToDate.Year <= 2017 Then
EsAnticipo2017Jam = True
End If
End If
Next
Dim ObjConta As New ClsContabilidad
Dim ObjVenta As New ClsVentas(ObjConta.IniciaTransacSQL())
Dim 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 = 0
Dim sumaAmorticaciones As Decimal = 0
Dim alertaContabilizacion As String = "Se enviaron correctamente las siguientes pólizas:<br><br>"
Dim CveCuentaContabilizacion As Integer = 1
Dim CuentasContablesInvalidas As New StringBuilder
Dim CuentasContablesInvalidasSIG As New StringBuilder
Dim ContaIdPoliza As Integer = 0
Dim ConceptoAmortizacion As Integer = 0
Dim UsaComplementariaClientes As Boolean = False
If UsuarioActual.CveEmpresa.Contiene(1, 119) Then UsaComplementariaClientes = True
'Dim FechaMaxima As Date = MinFecha
'For Each gvr As GridViewRow In GVAnticipos.Rows
' If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then
' If gvr.FCLiteral("LtlFecha").Text.ToDate > FechaMaxima Then
' FechaMaxima = gvr.FCLiteral("LtlFecha").Text.ToDate
' End If
' End If
'Next
''[IPP] PARCHE TEMPORAL PARA ANTICIPOS DE JAM
'If FechaMaxima < "01/01/2018".ToDate And UsuarioActual.CveEmpresa = 119 Then
' FechaMaxima = "01/01/2018".ToDate
'End If
CvePrepoliza = ObjConta.AddPrePolizas("Ventas/Anticipos", CvePlantillaPoliza, TxtTotal.Text.ToDecimal, TxtTotal.Text.ToDecimal, DdlMoneda.SelectedValue.ToEntero, TxtFechaAnticipoCliente.Text.ToDate, String.Format("{0} {1} {2}-{3}", If(EsAnticipo2017Jam, "Aplicación Anticipo 2017", ""), NombreCliente, Serie, TxtFolio.Text), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If CvePrepoliza > 0 Then
Dim tipoCambioPago As Decimal = 1
Dim tipoCambioVenta As Decimal = 1
Dim 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 CveCuentaIVAXTrasladar As Integer = 0
Dim CveCuentaIVATrasladado As Integer = 0
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then
Dim Dr As DataRow = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=TmpDT.MAX("PorcentajeIVA").ToDouble).FiltroPrimero("")
IdCtaIVAXTrasladar = Dr("IdCtaIVAXTrasladar").ToString.ToEntero
IdCtaIVATrasladado = Dr("IdCtaIVATrasladado").ToString.ToEntero
CveCuentaIVAXTrasladar = Dr("CveCuentaIVAXTrasladar").ToString.ToEntero
CveCuentaIVATrasladado = Dr("CveCuentaIVATrasladado").ToString.ToEntero
End If
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then
Dim FechaUltimaFluctuacion As Date = MinFecha
Dim TipoCambioFluctuacion As Decimal = 1
If ObjIE.GetFluctuacionesBitacora(UsuarioActual.CveEmpresa) Then
If ObjIE.DtResultados.Rows.Count > 0 Then
Dim tFecha As Date = gvr.DataKey("Fecha").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
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 = 1 Then 'Si la venta viene en pesos y se va a pagar en DOLARES
tipoCambioPago = gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal
tipoCambioVenta = 1
tipoCambioVentaValuacion = 1
PorcentajePago = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal) / gvr.DataKey("Original").ToDecimal
End If
If dtConceptos IsNot Nothing Then
For Each Row As DataRow In dtConceptos.Rows
Dim ConceptoContable = Row("CveConcepto").ToString.ToEntero
Dim TipoMovimiento As Boolean = If(Row("TipoMovto").ToString = "True", True, False)
Dim importeMovimiento As Decimal = 0
Dim importeMX As Decimal = 0
Dim IdCtaContable As Integer = 0
Dim CveCuenta As Integer = 0
Dim FechaMovimiento As Date = Now
Dim Concepto As String = ViewState("VentaFolio").ToString
Dim FuncionalidadFluctuacionImpuestos As Boolean = If(UsuarioActual.Empresa.Funcionalidad(159) = "1", True, False)
Dim TipoCambioGeneral As Decimal = 1
Dim PorcentajeImpuesto As Decimal = 0
Select Case ConceptoContable
Case 2 'Cliente
If Not (gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66) Then
If DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal
importeMX = importeMovimiento
ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 1 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal
importeMX = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVentaValuacion
ElseIf DdlMoneda.SelectedValue.ToEntero = 2 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal
importeMX = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioVentaValuacion
ElseIf DdlMoneda.SelectedValue.ToEntero = 1 AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal
importeMX = importeMovimiento
End If
importeMovimiento = Math.Round(importeMovimiento, 2)
importeMX = Math.Round(importeMX, 2)
TipoCambioGeneral = tipoCambioVentaValuacion
If CveMonedaVenta = 1 Then
IdCtaContable = IdCtaContClientes
CveCuenta = CveCuentaClientes
Else
IdCtaContable = IdCtaContComplementaria
CveCuenta = 0 'If(ObjFactura.Cliente IsNot Nothing AndAlso ObjFactura.Cliente.CveCuentaComplementaria > 0, ObjFactura.Cliente.CveCuentaComplementaria, -1)
If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or UsaComplementariaClientes) Then
'Conta ContPAQ
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
'Conta SIG
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, 0, Concepto, 207, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioVentaValuacion) Then
ErrorConta = True
End If
importeMX = importeMovimiento
IdCtaContable = IdCtaContMonedaExtranjera
CveCuenta = 0
End If
End If
ConceptoContable = 251 ' cambia para dejar el concepto 2, solamente para pago en banco
End If
Case 11 'Anticipo
If gvr.DataKey("CveConceptoContable").ToString().ToEntero = 3 Then
CveIEAnticipo = gvr.DataKey("CveIE").ToString.ToEntero
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal)
'Mantenemos la integridad de la suma para el pagocliente
'SumaAnticipos += row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal
'sumaAmorticaciones += row2.FCTextBox("TxtAnticipo" & row2.RowIndex).Text.ToDecimal
TipoCambioGeneral = tipoCambioPago
IdCtaContable = IdCtaContAnticipos
CveCuenta = CveCuentaAnticipos
If importeMovimiento <> 0 Then
'Conta ContPAQ
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
'Conta SIG
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToEntero, CveVentaAmortizacion:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento * tipoCambioPago, ImporteME:=If(tipoCambioPago = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then
ErrorConta = True
End If
End If
' PorcentajeAmortizacion = SumaAnticipos / TxtTotal.Text.ToDecimal
'Los Anticipos solo ocupan los ivas por trasladar
If PorcentajePago > 0 Then
Dim Importe13 = gvr.DataKey("IVA").ToDecimal
Dim Importe8 = gvr.DataKey("RetIVA").ToDecimal
Dim Importe9 = gvr.DataKey("RetISR").ToDecimal
If Not AgregarPrePolizasXTrasladar(ObjConta, CvePrepoliza, PorcentajePago, tipoCambioPago, CuentasContablesInvalidas, idCuentaContabilizacion, CuentasContablesInvalidasSIG, CveCuentaContabilizacion, Importe13, Importe8, Importe9) Then
ErrorConta = True
End If
End If
End If
importeMovimiento = 0
Case 91 'Amortizacion Nota de Credito
If gvr.DataKey("CveConceptoContable").ToString().ToEntero = 12 Then
If CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 1 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal
importeMX = importeMovimiento
ElseIf CveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 2 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal
importeMX = importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal
ElseIf CveMonedaVenta = 1 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 2 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal
importeMX = importeMovimiento * gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal
ElseIf CveMonedaVenta = 2 And gvr.DataKey("CveMoneda").ToString.ToDecimal = 1 Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * gvr.FCTextBox("TxtTC" & gvr.RowIndex).Text.ToDecimal
importeMX = importeMovimiento
End If
importeMovimiento = Math.Round(importeMovimiento, 2)
importeMX = Math.Round(importeMX, 2)
If ObjConta.GetRetCuenta(ConceptoContable, CveCliente) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCtaContable").ToString.ToEntero
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCtaContableSIG").ToString.ToEntero
End If
End If
If importeMovimiento <> 0 Then
'Conta ContPAQ
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
Dim ImporteComplementaria As Decimal = 0
If UsaComplementariaClientes = True AndAlso gvr.DataKey("CveMoneda").ToString.ToDecimal > 1 Then
IdCtaContable = IdCtaContComplementaria
CveCuenta = 0
importeMX = importeMovimiento
ImporteComplementaria = ((importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal) - importeMovimiento).RoundSQL
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, False, importeMovimiento, Concepto, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=ImporteComplementaria, ImporteME:=If(gvr.DataKey("TipoCambio").ToString.ToDecimal = 1, 0, importeMovimiento), TipoCambio:=gvr.DataKey("TipoCambio").ToString.ToDecimal) Then
ErrorConta = True
Exit For
End If
IdCtaContable = IdCtaContMonedaExtranjera
CveCuenta = 0
End If
If CveMonedaVenta > 1 AndAlso IdCtaContMonedaExtranjera > 0 Then
IdCtaContable = IdCtaContMonedaExtranjera
CveCuenta = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=gvr.DataKey("TipoCambio").ToString.ToDecimal) Then
ErrorConta = True
Exit For
End If
'AMORTIZA NC CONTRA ANTICIPO A CLIENTES
If Not ErrorConta And DdlTipoComprobante.SelectedValue = "Ant" Then
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("Original").ToDecimal) * gvr.DataKey("IVA").ToDecimal)
If ObjConta.AddPrePolizasDetalle(CvePrepoliza, False, importeMovimiento, Concepto, 11, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveVentaAmortizacion:=gvr.DataKey("CveVenta").ToString.ToEntero, ImporteMX:=importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal, CveCuenta:=CveCuenta) Then
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, True, importeMovimiento, Concepto, 4, Concepto, FechaMovimiento, gvr.DataKey("IdCtaContableNC").ToEntero, -1, CveClasificacion:=gvr.DataKey("CveClasificacionNC").ToEntero, CveVenta:=gvr.DataKey("CveVenta").ToString.ToEntero, CveCliente:=CveCliente, CveVentaAmortizacion:=CveVenta, ImporteMX:=importeMovimiento * gvr.DataKey("TipoCambio").ToString.ToDecimal, CveCuenta:=gvr.DataKey("IdCtaContableNCSIG").ToEntero) Then
ErrorConta = True
Exit For
End If
Else
ErrorConta = True
Exit For
End If
End If
End If
End If
importeMovimiento = 0
Case 92 'Amortizacion Ingreso X Comprobar
If gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66 Then
CveIEAnticipo = gvr.DataKey("CveIE").ToString.ToEntero
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal
IdCtaContable = IdCtaContClientes
CveCuenta = CveCuentaClientes
If importeMovimiento <> 0 Then
' Agregamos el 2
If tipoCambioPago = 1 Then
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContClientes, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento) Then
ErrorConta = True
End If
Else 'Cuando son dolares
If importeMovimiento <> 0 Then
If IdCtaContComplementaria > 0 Or 0 > 0 Then
'Agregamos la Complementaria
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, 0, Concepto, 207, Concepto, FechaMovimiento, IdCtaContComplementaria, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then
ErrorConta = True
End If
'Agregamos la Extranjera
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMovimiento, ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then
ErrorConta = True
End If
Else
'Agregamos la Extranjera
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 2, Concepto, FechaMovimiento, IdCtaContMonedaExtranjera, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=Math.Round(importeMovimiento * tipoCambioVenta, 2, MidpointRounding.AwayFromZero), ImporteME:=importeMovimiento, CveCuenta:=0, TipoCambio:=tipoCambioVenta) Then
ErrorConta = True
End If
End If
End If
End If
importeMovimiento = ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / TxtTotal.Text.ToDecimal) * TxtIVA.Text.ToDecimal)
importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero)
If importeMX <> 0 Then
'Agregamos el 13
IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar)
CveCuenta = If(CveCuentaIVAXTrasladar > 0, CveCuentaIVAXTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar)
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, 13, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then
ErrorConta = True
End If
'Agregamos el 61
IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado)
CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado)
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then
ErrorConta = True
End If
End If
'IEPS
importeMovimiento = ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / TxtTotal.Text.ToDecimal) * TxtIEPS.Text.ToDecimal)
importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero)
If importeMX <> 0 Then
'Agregamos el 38
IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSxTrasladar
CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSxTrasladar
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, 38, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then
ErrorConta = True
End If
'Agregamos el 39
IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSTrasladado
CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSTrasladado
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, Not TipoMovimiento, importeMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=tipoCambioPago, PorcentajeImpuesto:=PorcentajeImpuestoAmortizacion) Then
ErrorConta = True
End If
End If
'Agregamos el 92
importeMovimiento = gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal 'gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo" & gvr.RowIndex).ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal)
importeMX = Math.Round(importeMovimiento * tipoCambioPago, 2, MidpointRounding.AwayFromZero)
IdCtaContable = IdCtaContAnticipos
CveCuenta = CveCuentaAnticipos
If 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, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveIE:=CveIEAnticipo, ImporteMX:=importeMX, CveCuenta:=-1, TipoCambio:=tipoCambioPago) Then
ErrorConta = True
End If
End If
End If
importeMovimiento = 0
Case 64 'Ganancia
If CveMonedaVenta <> 1 OrElse gvr.DataKey("CveMoneda").ToEntero <> 1 Then
IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria
CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria
Dim TipoCambioGanancia As Decimal = If(Not (gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66), tipoCambioVentaValuacion, tipoCambioVenta)
If tipoCambioPago > TipoCambioGanancia AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then
importeMovimiento = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioPago) - (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * TipoCambioGanancia) 'Añadimos la diferencia de ganancia en la venta
importeMovimiento = Math.Abs(Math.Round(importeMovimiento, 2))
importeMX = importeMovimiento
End If
Dim TCImpuestos As Decimal = If(FuncionalidadFluctuacionImpuestos, TipoCambioGanancia, tipoCambioPago)
TipoCambioGeneral = TCImpuestos
Else
importeMovimiento = 0
End If
Case 65 'Perdida
If CveMonedaVenta <> 1 OrElse gvr.DataKey("CveMoneda").ToEntero <> 1 Then
IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria
CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria
Dim TipoCambioPerdida As Decimal = If(Not (gvr.DataKey("CveIE").ToString.ToEntero > 0 AndAlso gvr.DataKey("CveConceptoContable").ToString().ToEntero = 66), tipoCambioVentaValuacion, tipoCambioVenta)
If tipoCambioPago < TipoCambioPerdida AndAlso gvr.DataKey("CveMoneda").ToEntero = 2 Then
importeMovimiento = (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * TipoCambioPerdida) - (gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal * tipoCambioPago) 'Añadimos la diferencia de perdida en la venta
importeMovimiento = Math.Abs(Math.Round(importeMovimiento, 2))
importeMX = importeMovimiento
End If
Dim TCImpuestos As Decimal = If(FuncionalidadFluctuacionImpuestos, TipoCambioPerdida, tipoCambioPago)
TipoCambioGeneral = TCImpuestos
Else
importeMovimiento = 0
End If
Case Else
importeMovimiento = 0
End Select
If importeMovimiento <> 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", ConceptoContable))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrepoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=TipoCambioGeneral) Then
ErrorConta = True
End If
End If
Next
End If
End If
Next
Else
ErrorConta = True
End If
If ObjConta.ValidacionPrePolizaCuadre(CvePrepoliza, 3) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
GuardaLogAD($"Ventas/Ventas-Anticipos | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrepoliza}", "LogPrePolizas")
ErrorConta = True
End If
End If
If ErrorConta Then
Alert("Ocurrió un error al amortizar el documento. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError)
ObjConta.RollBack()
If ObjContpaq IsNot Nothing Then ObjContpaq.RollBack()
Else
Dim Msg As New StringBuilder
Msg.Append("Se ha amortizado correctamente")
'AJUSTA POLIZA
If ContaIdPoliza > 0 Then
Msg.AppendFormat("<br/><br/><a class=""Texto"" target='_blank' href=""/Contabilidad/RegPoliza.aspx?IdPoliza={0}"">Ver Póliza</a>", 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
HdnIVACalculado.Value = HdnIVAOriginal.Value
For Each gvr As GridViewRow In GVAnticipos.Rows
If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked AndAlso gvr.DataKey("CveConceptoContable").ToEntero.Contiene(3) Then
Amortizacion += gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal ' - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal)
HdnIVACalculado.Value = (HdnIVACalculado.Value.ToDouble - ((gvr.FCTextBox("TxtAnticipo" & gvr.RowIndex).Text.ToDecimal / gvr.DataKey("TotalAnticipo").ToDecimal) * gvr.DataKey("IVAAnticipo").ToDecimal)).FormatoNumero(2)
HdnFolioFiscalNC.Value = gvr.DataKey("FolioFiscal")
'CvePSAmortizacion = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePS", "CveConceptoContable = 11").ToEntero
End If
Next
'Amortizacion += TmpDTImpuestos.SUM("Importe").ToDecimal 'RMF. 2018.12.20- saque de la jugada en la amortización los impuestos locales
LtlTitDescuentos.Text = "Descuentos:"
'cuando es amortización DESCUENTO POR CONCEPTO
If DdlTipoAmortizacionAnticipo.SelectedValue = "1" AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Cot") Then
LtlTitDescuentos.Text = "Amortización:"
'If Amortizacion <> LblDescuentos.Text.ToDecimal Then
' Alert("El importe registrado como descuento no coincide con el importe seleccionado de anticipo.", TipoMensaje.MsgAdvertencia)
' Exit Sub
'End If
Dim TotalCalculableImpuestos As Decimal = 0
Dim Cantidad, PU, Descuento As Decimal
For Each dr As DataRow In TmpDT.Rows
Cantidad = dr("Cantidad").ToString.ToDecimal
PU = dr("PU").ToString.ToDecimal
'proporcional la mortización al concepto
Descuento = PU * Cantidad / LblSubTotal1.Text.ToDecimal * Amortizacion
TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento
dr("Descuento") = Descuento
dr("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales)
dr("ImporteIVA") = Math.Round(dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
dr("ImporteIEPS") = Math.Round(dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
dr("PorcentajeRetIVA") = ClienteRetIVA
dr("PorcentajeRetISR") = ClienteRetISR
Next
GvPS.DataSource = TmpDT
GvPS.DataBind()
Amortizacion = 0
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
RegistraScript("BorraDescuentos();")
LblAntAplicados.Text = "Amortización por descuento" : LblAntAplicados.Visible = True
RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal")
UpPS.Update()
End If
If DdlTipoComprobante.SelectedValue = "Rem" Then
DdlTipoComprobante.Enabled = False
TrAlmacenAsignado.Visible = False
UpParametros.Update()
End If
'cuando es amortización por NOTA DE CREDITO
If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then
LblAntAplicados.Text = "Amortización por Nota de Crédito" : LblAntAplicados.Visible = True
Amortizacion = 0
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
RegistraScript("BorraDescuentos();")
HdnTieneAnticiposVinculados.Value = "1"
End If
'cuando es AMORTIZACIÓN CON FACTURA EN CERO
If DdlTipoAmortizacionAnticipo.SelectedValue = "3" Then
If Amortizacion < TxtSubTotal.Text.ToDecimal Then
'[IPP] LIMPIA LO SELECCIONADO EN CASO DE QUE NO SEA AMORTIZACIÓN DEL 100% 15Junio2018
Amortizacion = 0
For Each gvr As GridViewRow In GVAnticipos.Rows
gvr.FCCheckBox($"Chk{gvr.RowIndex}").Checked = False
Next
If CveVenta <= 0 Then
Alert("La amortización no se pudo realizar ya que los importes no cubren la totalidad del documento. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
End If
End If
LblAmortizacion.Text = Amortizacion.FormatoNumero(2)
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
RegistraScript("BorraDescuentos();")
HdnTieneAnticiposVinculados.Value = "1"
End If
CalculaTotalesVenta()
End If
End If
System.Threading.Thread.Sleep(5)
RegistraScript("$('#DivAnticipos').modal('hide');", "jsClose")
End Sub
Private Function AgregarPrePolizasXTrasladar(ObjConta As ClsContabilidad, CvePrePoliza As Integer, PorcentajeAmortizacion As Decimal, TipoCambio As Decimal, ByRef CuentasContablesInvalidas As StringBuilder, ByRef idCuentaContabilizacion As Integer, ByRef CuentasContablesInvalidasSIG As StringBuilder, ByRef CveCuentaContabilizacion As Integer, Importe13 As Decimal, Importe8 As Decimal, Importe9 As Decimal) As Boolean
Dim ImporteMovimiento As Decimal
Dim ImporteMX As Decimal
Dim IdCtaContable, CveCuenta As Integer
Dim FechaMovimiento As Date = Now
Dim Concepto As String = ViewState("VentaFolio").ToString
Dim PrePolizaCorrecta = True
Dim PorcentajeImpuesto As Decimal = 0
Dim IdCtaIVAXTrasladar As Integer = 0
Dim CveCuentaIVAxTrasladar As Integer = 0
'13 Iva x Trasladar
ImporteMovimiento = Importe13 * PorcentajeAmortizacion
ImporteMX = Math.Round(ImporteMovimiento, 2) * TipoCambio
PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then
IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero
CveCuentaIVAxTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVAXTrasladar").ToString.ToEntero
End If
IdCtaContable = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar)
CveCuenta = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar)
If ImporteMovimiento > 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 13))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 13))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 13, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then
PrePolizaCorrecta = False
End If
End If
'8 RetIVA x Trasladar
ImporteMovimiento = Importe8 * PorcentajeAmortizacion
ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2)
If IdCtaContRetIVA <> 0 Then
IdCtaContable = IdCtaContRetIVA
CveCuenta = CveCuentaRetIVA
Else
If ObjConta.GetRetCuenta(8, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero
End If
End If
End If
If ImporteMovimiento > 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 8))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 8))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 8, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then
PrePolizaCorrecta = False
End If
End If
'9 RetISR x Trasladar
ImporteMovimiento = Importe9 * PorcentajeAmortizacion
ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2)
'Conta ContPAQ
If IdCtaContRetISR <> 0 Then
IdCtaContable = IdCtaContRetISR
Else
If ObjConta.GetRetCuenta(9, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero
End If
End If
End If
'ContaSIG
If CveCuentaRetISR <> 0 Then
CveCuenta = CveCuentaRetISR
Else
If ObjConta.GetRetCuenta(9, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero
End If
End If
End If
If ImporteMovimiento > 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 9))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If IdCtaContable <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 9))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 9, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then
PrePolizaCorrecta = False
End If
End If
Return PrePolizaCorrecta
End Function
'Charlie
Private Function AgregarPrePolizasTrasladadas(ObjConta As ClsContabilidad, CvePrePoliza As Integer, PorcentajeAmortizacion As Decimal, TipoCambio As Decimal, ByRef CuentasContablesInvalidas As StringBuilder, ByRef idCuentaContabilizacion As Integer, Optional ByRef CuentasContablesInvalidasSIG As StringBuilder = Nothing, Optional ByRef CveCuentaContabilizacion As Integer = Nothing) As Boolean
Dim ImporteMovimiento As Decimal
Dim ImporteMX As Decimal
Dim IdCtaContable, CveCuenta As Integer
Dim FechaMovimiento As Date = Now
Dim Concepto As String = ViewState("VentaFolio").ToString
Dim PrePolizaCorrecta = True
Dim PorcentajeImpuesto As Decimal = 0
Dim IdCtaIVATrasladado As Integer = 0
Dim CveCuentaIVATrasladado As Integer = 0
'61 Iva Trasladado
ImporteMovimiento = TxtIVA.Text.ToDecimal * PorcentajeAmortizacion
ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2)
PorcentajeImpuesto = TmpDT.MAX("PorcentajeIVA").ToDecimal
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then
IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero
CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero
End If
IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado)
CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado)
If ImporteMovimiento > 0 Then
'ContaContPAQ
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 61))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
'ContaSIG
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 61))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, ImporteMovimiento, Concepto, 61, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto) Then
PrePolizaCorrecta = False
End If
End If
'62 Ret IVA Trasladado
ImporteMovimiento = TxtRetIVA.Text.ToDecimal * PorcentajeAmortizacion
ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2)
'Conta ContPAQ
If IdCtaContRetIVA <> 0 Then
IdCtaContable = IdCtaContRetIVA
Else
If ObjConta.GetRetCuenta(62, UsuarioActual.CveEmpresa) Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacion").ToString.ToEntero
End If
End If
'Conta SIG
If CveCuentaRetIVA <> 0 Then
CveCuenta = CveCuentaRetIVA
Else
If ObjConta.GetRetCuenta(62, UsuarioActual.CveEmpresa) Then
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetIVACirculacionSIG").ToString.ToEntero
End If
End If
If ImporteMovimiento > 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 62))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 62))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 62, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then
PrePolizaCorrecta = False
End If
End If
'63 Ret ISR Trasladado
ImporteMovimiento = TxtRetISR.Text.ToDecimal * PorcentajeAmortizacion
ImporteMX = Math.Round(ImporteMovimiento * TipoCambio, 2)
If IdCtaContRetISR <> 0 Then
IdCtaContable = IdCtaContRetISR
Else
If ObjConta.GetRetCuenta(63, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
IdCtaContable = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacion").ToString.ToEntero
End If
End If
End If
If CveCuentaRetISR <> 0 Then
CveCuenta = CveCuentaRetISR
Else
If ObjConta.GetRetCuenta(63, UsuarioActual.CveEmpresa) Then
If ObjConta.DtResultados.Rows.Count > 0 Then
CveCuenta = ObjConta.DtResultados.Rows(0)("IdCuentaRetISRCirculacionSIG").ToString.ToEntero
End If
End If
End If
If ImporteMovimiento > 0 Then
If IdCtaContable <= 0 Then
CuentasContablesInvalidas.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 63))("ConceptoContable").ToString)
idCuentaContabilizacion = 0
End If
If CveCuenta <= 0 Then
CuentasContablesInvalidasSIG.Append("<br>" & GlobalDTContaConceptosContables(-1).FiltroPrimero(String.Format("CveConceptoContable = {0}", 63))("ConceptoContable").ToString)
CveCuentaContabilizacion = 0
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, ImporteMovimiento, Concepto, 63, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, ImporteMX:=ImporteMX, CveCuenta:=CveCuenta) Then
PrePolizaCorrecta = False
End If
End If
Return PrePolizaCorrecta
End Function
#End Region
#Region " BTN ELIMINAR "
Protected Sub BtnEmitir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitir.Click
If CveVenta <= 0 Then
Alert("Ocurrió un error al emitir la factura", TipoMensaje.MsgError)
Exit Sub
End If
If UsuarioActual.Empresa.TipoFacturacion = "CFDi" Then
If UsuarioActual.Empresa.EstatusFacturacion Then
CreaObjetosVenta()
'PARA CUANDO YA ESTA GUARDADA LA VENTA
ObjFactura.CveVenta = CveVenta
ObjFactura.Serie = Serie
ObjFactura.Folio = Folio
ObjFactura.Timbre.Comprobante.Serie = Serie
ObjFactura.Timbre.Comprobante.Folio = Folio.ToString
Dim ObjTimbrado As New Timbrado
Dim FM As New Modelos.FemsaFactura
Dim TmpDT7Eleven As New DataTable
Dim TmpDTComplementosTimbrado As New DataTable
PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado)
If ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) Then
'MENSAJE PRINCIPAL
MensajeAlert = New StringBuilder
MensajeAlert.AppendFormat(String.Format("<br/>La {0}: <b>{1}</b> se generó correctamente.<br/><br/>", 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("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar XML</a></li></ul>", 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("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar PDF</a></li></ul><br/>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", CveVenta)))
Else
MensajeAlert.Append("Ocurrió un error al generar el PDF. Por favor vuelva a entrar a la factura para imprimir el PDF. ")
End If
End If
'IMPRESION
GeneraPDFFactura(ChkEnviarFactura.Checked)
If ObjFactura.TipoDocto = "Ing" AndAlso ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" Then
CreaObjetosVentaAmortizacion(Nothing, ObjTimbrado.UUID, ObjFactura.CveVentaRelacion, CveVenta)
For Each Gvr As GridViewRow In GvAntNC.Rows
If Gvr.DataKey("FolioFiscal").ToString = "" AndAlso Gvr.DataKey("TipoDocto") = "Egs" Then
ObjFacturaDevolucion.CveVenta = Gvr.DataKey("CveVenta").ToEntero
ObjFacturaDevolucion.Serie = Gvr.DataKey("Serie").ToString
ObjFacturaDevolucion.Folio = Gvr.DataKey("Folio").ToEntero
ObjFacturaDevolucion.Timbre = PreParaTimbre(ObjFacturaDevolucion)
End If
Exit For
Next
If ObjFacturaDevolucion.CveVenta.ToEntero > 0 Then
Dim Obj2 As New List(Of Object)
Obj2.Add(ObjFacturaDevolucion)
If Not IsNothing(Obj2) AndAlso Obj2.Count > 0 Then
Dim ofa As Modelos.Factura = CType(Obj2(0), Modelos.Factura)
ofa.Timbre.CFDIRelacionados.UUID.Clear()
ofa.Timbre.CFDIRelacionados.UUID.Add(ObjTimbrado.UUID)
If ObjTimbrado.TimbrarFactura(UsuarioActual, ofa) Then
MensajeAlert.AppendFormat(String.Format("<br/>La {0}: <b>{1}</b> se timbro correctamente.<br/><br/>", ofa.TipoDocumento, ofa.SerieFolio))
Else
MensajeAlert.AppendFormat(String.Format("<br/>La {0}: <b>{1}</b> no se timbro correctamente.<br/><br/>", 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("<b>Notificación SMS:</b> enviado con éxito al cliente al celular: <b>{0}</b>", ObjFactura.Cliente.CobranzaTelefono)
Case 2
MensajeAlert.AppendFormat("<b>Notificación SMS:</b> sin enviar. Ocurrió un error en el envío, por favor verifique la información del cliente.")
Case 3
MensajeAlert.AppendFormat("<b>Notificación SMS:</b> sin enviar. No se pudo cargar el celular del cliente, por favor verifique la información del cliente.")
End Select
'MUESTA Alert OK
'MensajeAlert.Append("El Documento se generó correctamente")
Dim Liga = If(UsuarioActual.CveRol = 1165, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=-1"";", $"document.location.href=""/Ventas/Clientes.aspx?CveCliente={CveCliente}&Opt=3"";")
Alert(MensajeAlert.ToString, TipoMensaje.MsgInformacion, Liga)
TrEmitir.Visible = False
Else
Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgError)
End If
Else
Me.OnError("El SAT regresó el siguiente mensaje: Crédito insuficiente.", New Exception)
End If
ElseIf UsuarioActual.Empresa.TipoFacturacion = "CBB" Then
End If
End Sub
#End Region
#Region " DESCUENTOS "
Protected Sub BtnAplicarDescG_Click(sender As Object, e As System.EventArgs) Handles BtnAplicarDescG.Click
If HdnTipoDescuento.Value = "2" Then
If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then
Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2)
Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble
If IVAPromedio <> IVA Then
Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError)
Else
'Dim Descuento As Double = HdnDescuento.Value.Trim.Replace(",", "").ToDouble
CalculaTotalesVenta()
'LblDescuentos.Text = Descuento.FormatoNumero(2)
'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Descuento - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2)
'HdnIVAOriginal.Value = TxtIVA.Text
'CalculaTotales(True)
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
RegistraScript("BorraDescuentos();")
End If
End If
ElseIf HdnTipoDescuento.Value = "3" Then
If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then
Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2)
Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble
If IVAPromedio <> IVA Then
Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError)
Else
'Dim Amortizacion As Decimal = HdnDescuento.Value.Trim.Replace(",", "").ToDecimal
'LblAmortizacion.Text = Amortizacion.FormatoNumero(2)
'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Amortizacion - LblDescuentos.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2)
'HdnIVAOriginal.Value = TxtIVA.Text
'CalculaTotales(True)
CalculaTotalesVenta()
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
RegistraScript("BorraDescuentos();")
HdnTieneAnticiposVinculados.Value = "1"
End If
End If
End If
RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal")
UpPS.Update()
End Sub
Private Sub BtnAplicarOtrosConceptos_Click(sender As Object, e As EventArgs) Handles BtnAplicarOtrosConceptos.Click
TotalOtrosConceptos = 0
For Each row As GridViewRow In GVOtrosConceptos.Rows
TotalOtrosConceptos += row.FCTextBox("TxtCantidadConcepto").Text.ToDecimal
Next
RegistraScript("$('#ModalOtrosConceptos').modal('hide')", "hidemodal")
End Sub
Private Sub BtnAplicarComplementos_Click(sender As Object, e As EventArgs) Handles AplicarComplementosTimbrado.Click
LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs green"
UpPS.Update()
RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal")
End Sub
Private Sub BtnCancelarComplementos_Click(sender As Object, e As EventArgs) Handles CancelarComplementosTimbrado.Click
trEntidad.Visible = False
trContaComplementos.Visible = False
trAmbito.Visible = False
trTipoCampaña.Visible = False
RblComplementos.SelectedIndex = -1
TxtIdConta.Text = ""
DdlTipoCampaña.SelectedIndex = -1
DdlAmbitoComplemento.SelectedIndex = -1
DdlINEEntidad.SelectedIndex = -1
LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs gray"
UpComplementos.Update()
UpDatosComplementos.Update()
UpPS.Update()
RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal")
End Sub
'2019-07-31 OSCAR Nuevo cancela usando el metodo de cancelacion de facturas
Protected Sub LnkCancelarComplemetno_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).BindingContainer, GridViewRow)
Dim ObjCancelacion As New Timbrado
Dim ObjBanco As New ClsBancos
Dim CveComplementoPago As Integer = GvRow.DataKey("CveComplementoPago").ToEntero
Dim FolioFiscal As String = GvRow.DataKey("FolioFiscal").ToString
Dim RFCEmisor As String = UsuarioActual.Empresa.RFC
Dim RFCReceptor As String = GvRow.DataKey("RFCReceptor")
Dim CvePACCancelacion As Integer = GvRow.DataKey("CvePAC").ToEntero
If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, 0, RFCReceptor, RFCEmisor, CvePACCancelacion) Then
If ObjBanco.UpdateComplementoPago(CveComplementoPago, "-1", -1, UsuarioActual.CveEmpresa, 2, CvePACCancelacion, FechaCancelacion:=ObjCancelacion.CancelacionFecha, SelloCancelacion:=ObjCancelacion.CancelacionAcuse) Then
CargaComplementosPago()
Alert("El complemento se cancelo correctamente.")
End If
Else
Alert("Se presento un error al cancelar el complemento.")
End If
ObjBanco.Dispose()
End Sub
#End Region
#Region " VISTA PREVIA "
Protected Sub BtnVistaPrevia_Click(sender As Object, e As System.EventArgs) Handles BtnVistaPrevia.Click
VistaPreviaNew()
End Sub
#End Region
#Region "I M A G E - B U T T O N S"
Protected Function CancelarMovimientoInventario(ByRef ObjInventario As ClsInventarios, ByRef ObjConta As ClsContabilidad, CveVentaNueva As Integer, CveVentaVieja As Integer) As Boolean
'SI YA ESTA QUEMADA DE ALMACEN LA VENTA, NO SE CANCELAN LOS MOVIMIENTOS DE INVENTARIO
If ObjInventario.GetEstatusVentaPorSurir(CveVentaVieja) Then
If ObjInventario.EsDevolucionVenta = 2 Then
Return True
End If
Else
Return False
End If
Dim DtMovimientos As DataTable
Dim DTMovimientosDetalles As DataTable
Dim OcurrioError As Boolean = False
'Verificamos que la venta tenga movimientos
If ObjInventario.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjInventario.DtResultados.Rows.Count > 0 Then
DtMovimientos = ObjInventario.DtResultados.FiltraParametros("CveConcepto = 3", DistinctColumns:={"CveMovimiento"})
DTMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0")
For Each Mov As DataRow In DtMovimientos.Rows
If ObjInventario.GetMovimientos(Mov("CveMovimiento").ToString.ToEntero, 3, -1, UsuarioActual.CveEmpresa) Then
If ObjInventario.DtResultados.Rows.Count > 0 Then
Dim CveAlmacen As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero
Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero
Dim Fecha As Date = Now
'Creamos el movimiento de entrada y el movimiento de salida
Dim CveMovimientoInventarioEntrada As Integer = ObjInventario.AddMovimiento(CveAlmacen, 18, CveMoneda, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveDevolucion, -1, -1, MovimientoFijo:=True)
Dim CveMovimientoInventarioSalida As Integer = ObjInventario.AddMovimiento(CveAlmacen, 3, CveMoneda, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVentaNueva, -1, -1, MovimientoFijo:=True)
If CveMovimientoInventarioEntrada > 0 AndAlso CveMovimientoInventarioSalida > 0 Then
'Creamos sus detalles
For Each MovDet As DataRow In DTMovimientosDetalles.FiltraParametros($"CveMovimiento = {Mov("CveMovimiento")}").Rows
Dim Cantidad As Double = MovDet("Cantidad").ToString.ToDouble
Dim CveUnidad As Integer = MovDet("CveUM").ToString.ToEntero
Dim PU As Double = MovDet("PU").ToString.ToDouble
Dim CveProducto As Integer = MovDet("CvePS").ToString.ToEntero
Dim SerieLote As String = MovDet("SerieLote").ToString
Dim CveVentaDetalle = MovDet("CveVentaDetalle").ToString.ToEntero
'Entrada
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventarioEntrada, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then
OcurrioError = True
Exit For
End If
'Salida
CveVentaDetalle = ObjInventario.VentaDetallePadreGet(CveVentaDetalle).ToString.ToEntero
If CveVentaDetalle > 0 Then
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoInventarioSalida, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then
OcurrioError = True
Exit For
End If
Else
OcurrioError = True
Exit For
End If
Next
'Creamos sus prepolizas
If Not OcurrioError Then
Dim tmpCostos As DataTable = DTMovimientosDetalles.FiltraParametros($"CveMovimiento = {Mov("CveMovimiento")}", "", {"CveClasificacion"})
Dim IdCtaContable As Integer = 0
Dim CveCuenta As Integer = 0
Dim ValorInventario As Decimal = 0
For Each RowInv As DataRow In tmpCostos.Rows
ValorInventario = DTMovimientosDetalles.SUM("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).ToString.ToDecimal.RoundSQL()
IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGasto", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero
CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero
If ValorInventario <> 0 Then
'Entrada
If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveDevolucion, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventarioEntrada, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then
'Salida
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventarioSalida, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then
OcurrioError = True
Exit For
End If
Else
OcurrioError = True
Exit For
End If
End If
Next
If OcurrioError Then
Exit For
End If
IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {ddlAlmacen.SelectedValue}").ToEntero
CveCuenta = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {ddlAlmacen.SelectedValue}").ToEntero
ValorInventario = DTMovimientosDetalles.SUMD("Total", $"CveMovimiento = {Mov("CveMovimiento")}").RoundSQL()
If ValorInventario <> 0 Then
'Entrada
If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveDevolucion, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=-1, CveMovimientoAlmacen:=CveMovimientoInventarioEntrada, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta) Then
'Salida
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, ValorInventario, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=-1, CveMovimientoAlmacen:=CveMovimientoInventarioSalida, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta) Then
OcurrioError = True
Exit For
End If
Else
OcurrioError = True
Exit For
End If
End If
End If
Else
OcurrioError = True
Exit For
End If
Else
'Si no tiene Movimientos de Salida no ocupamos mas
Return Not OcurrioError
End If
Else
OcurrioError = True
Exit For
End If
Next
End If
Else
OcurrioError = True
End If
Return Not OcurrioError
End Function
Protected Function CancelarFactura(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjAC As ClsContPAQi, ByRef ObjBancos As ClsBancos) As Boolean
Dim IDPoliza As Integer = -1
Dim CvePrePoliza As Integer
Dim CvePlantillaPoliza As Integer
Dim ErrorCancelar As Boolean = False
Dim Mensaje As String = ""
Try
ObjFacturaDevolucion.TipoDocto = ObjFactura.TipoDocto
If ObjFacturaDevolucion.TipoDocto.Contiene("Egs", "Dev") Then
CvePlantillaPoliza = 7
ElseIf ObjFacturaDevolucion.TipoDocto.Contiene("Ing", "Rem", "Ant") Then
CvePlantillaPoliza = 4
End If
CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
ObjFacturaDevolucion.CveVenta = CveVenta
ObjFacturaDevolucion.CvePrePoliza = CvePrePoliza
If NuevaFactura = 1 AndAlso UsuarioActual.TienePermisoProceso(222) Then
If ObjVentas.GetVentaDetalle(ObjFacturaDevolucion.CveVenta) Then
TmpDT = ObjVentas.DtResultados
End If
ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas)
Else
ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFacturaDevolucion, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas)
End If
If Not ErrorCancelar Then
ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFacturaDevolucion, -1)
End If
If CveEstatus = 4 Then
If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then
Mensaje = "El nuevo estatus se guardó correctamente"
Else
ErrorCancelar = True
End If
'Si se está mandando a Cancelada SAT
ElseIf CveEstatus = 5 Then
Dim DT As DataTable = Nothing
If FolioFiscal = "" Then
Dim XmlDoc As New XmlDocument
XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml")
ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText
End If
Dim ObjCancelacion As New Timbrado
Dim Total As Decimal = TxtTotal.Text.ToDecimal
Dim RFCReceptor As String = HdnRFCVenta.Value
If Not ObjVentas.UpdateEstatusFactura(13, FolioFiscal, "", Now, CveVenta, IDPoliza) Then 'Marcamos la factura como refacturada, si no se cancelo en el SAT el estatus nos dejara cancelarla despues
ErrorCancelar = True
End If
If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, Total, RFCReceptor, UsuarioActual.Empresa.RFC) Then
'falta verificar traer el acuse y reenviarlo
If UsuarioActual.Empresa.UsaAC Then
IDPoliza = GenerarPolizaAC(ObjAC, True)
If IDPoliza <= 0 Then
Mensaje = "No se pudo generar la poliza"
ErrorCancelar = True
End If
End If
If Not ErrorCancelar Then
If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, ObjCancelacion.CancelacionAcuse, Now, CveVenta, IDPoliza, CvePAC:=UsuarioActual.Empresa.CvePAC) Then
Mensaje = "El nuevo estatus se guardó correctamente"
Else
ErrorCancelar = True
End If
End If
Else
ErrorCancelar = True
End If
ObjCancelacion = Nothing
End If
Catch ex As Exception
GuardaLog(ex.ToString())
ErrorCancelar = True
End Try
Return Not ErrorCancelar
End Function
Protected Function CancelarFactura2(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjAC As ClsContPAQi, ObjBancos As ClsBancos) As Boolean
Dim IDPoliza As Integer = -1
Dim CvePrePoliza As Integer
Dim CvePlantillaPoliza As Integer
Dim ErrorCancelar As Boolean = False
Dim Mensaje As String = ""
CreaObjetosVenta()
If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then
CvePlantillaPoliza = 7
ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem") Then
CvePlantillaPoliza = 4
End If
CvePrePoliza = ObjConta.AddPrePolizas("Ventas/GuardaEstatus", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.Replace(",", "").ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
ObjFactura.CveVenta = CveVenta
ObjFactura.CvePrePoliza = CvePrePoliza
If HplSaldoAuxiliar.Text.ToDecimal > 0 Then
ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas)
End If
If Not ErrorCancelar Then
ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, -1)
End If
If CveEstatus = 4 Then
If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta, IDPoliza) Then
Mensaje = "El nuevo estatus se guardó correctamente"
Else
ErrorCancelar = True
End If
'Si se está mandando a Cancelada SAT
ElseIf CveEstatus = 5 Then
Dim DT As DataTable = Nothing
If FolioFiscal = "" Then
Dim XmlDoc As New XmlDocument
XmlDoc.Load(Ruta & "XML\" & DdlTipoComprobante.SelectedValue & "\" & VentaFolio & ".xml")
ViewState("FolioFiscal") = XmlDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText
End If
'Si es cancelar en el SAT:
Dim CFDi As New ClbNegBICFDv3_2.ClsNegEDI
Dim Respuesta As New ClbNegBICFDv3_2.ClsNegRespuesta
Respuesta = CFDi.CancelaCFdi(UsuarioActual.Empresa.BIUsuario, UsuarioActual.Empresa.BIContraseña, Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoPfx, UsuarioActual.Empresa.ContraseñaKey, UsuarioActual.Empresa.RFC, FolioFiscal, "http://208.43.160.178/srvCFDi/service1.asmx")
If Respuesta Is Nothing Then
'Alert("La factura no se pudo cancelar. <br />Posbiles causas:<br />&nbsp;&nbsp;- Los servicios del SAT están ocupados.<br />&nbsp;&nbsp;- El Folio Fiscal no ha quedado registrado.", TipoMensaje.MsgError)
Me.GuardaLog(CFDi.MsgError)
ErrorCancelar = True
Mensaje = "La factura no se pudo cancelar. <br />Posbiles causas:<br />&nbsp;&nbsp;- Los servicios del SAT están ocupados.<br />&nbsp;&nbsp;- El Folio Fiscal no ha quedado registrado."
ElseIf Respuesta.NoCertificadoSAT <> String.Empty Then
If UsuarioActual.Empresa.UsaAC Then
IDPoliza = GenerarPolizaAC(ObjAC, True)
If IDPoliza <= 0 Then
Mensaje = "No se pudo generar la poliza"
ErrorCancelar = True
End If
End If
If Not ErrorCancelar Then
If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, Respuesta.NoCertificadoSAT, Respuesta.FechaTimbrado, CveVenta, IDPoliza) Then
Mensaje = "El nuevo estatus se guardó correctamente"
Else
ErrorCancelar = True
End If
End If
End If
End If
Return Not ErrorCancelar
End Function
Protected Sub ImgBtnAddC_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddC.Click
Dim Row As DataRow = Nothing
Row = DTmpC.NewRow
Row("Descripcion") = tbDescC.Text
DTmpC.Rows.Add(Row)
tbDescC.Text = ""
tbDescC.Focus()
GvConceptos.DataSource = DTmpC
GvConceptos.DataBind()
UPCD.Update()
End Sub
Protected Sub ImgBtnAddF_Click(sender As Object, e As ImageClickEventArgs) Handles ImgBtnAddF.Click
Dim Row As DataRow = Nothing
Dim ObjVentas As New ClsVentas
Row = DTmpF.NewRow
Row("CveVenta") = 0
Row("Titulo") = tbTituloF.Text
Row("Nombre") = tbNmbF.Text
Row("Puesto") = tbPuesF.Text
Row("Lado") = ddlPos.SelectedValue.ToEntero
DTmpF.Rows.Add(Row)
tbNmbF.Text = ""
tbPuesF.Text = ""
tbTituloF.Text = ""
ddlPos.SelectedValue = CStr(0)
GvFirmas.DataSource = DTmpF
GvFirmas.DataBind()
UPFirmas.Update()
tbTituloF.Focus()
End Sub
#End Region
#Region "D R O P - D O W N - L I S T"
Private Sub DdlPSIndexChange(CvePSParametro As Integer, Ddl As ADServerControl.Dropdownlost)
If Not CveCliente > 0 And Not CveEmpresaCRM > 0 Then
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")")
Exit Sub
End If
If CvePSParametro > 0 Then
Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePSParametro).FiltroPrimero("")
If drPS IsNot Nothing Then
'HdnUnidadMedida.Value = PS.Rows(0)("CveUnidadMedida").ToString
HdnPS.Value = drPS("PS").ToString
HdnCodigoPS.Value = drPS("PSCodigo").ToString
HdnTipoPS.Value = drPS("CveTipoPS").ToString
HdnTipoInv.Value = drPS("Inv_CveMetodoInventario").ToString
HdnAplicaIEPS.Value = drPS("AplicaIEPS").ToString
HdnPorcentajeIEPS.Value = drPS("IEPSPorcentaje").ToString
DdlUnidadMedida.Items.Clear()
If UsuarioActual.Empresa.UsaInventarios Then
DdlUnidadMedida.DataSource = GlobalDTProductosServiciosEquivalencias(CvePSParametro, -1)
Else
DdlUnidadMedida.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
End If
DdlUnidadMedida.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlUnidadMedida.SelectedValue = "-1"
DdlUnidadMedida.DataBind()
DdlUnidadMedida.SelectedValueExist(drPS("CveUnidadMedida").ToString)
If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count = 0 Then
DdlMoneda.SelectedValueExist(drPS("CveMoneda").ToString)
CambiaMoneda()
End If
'SUGIERE PRECIO
Dim PrecioSugerido = 0.0
PrecioSugerido = drPS("Precio").ToString.ToDouble
If UsuarioActual.CveEmpresa.Contiene(1) Then
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPorcentajeProductos(CveCliente) Then
Dim PrecioAplicado = ObjPS.DtResultados.FiltraParametros($"CvePS = {CvePSParametro}").FiltroPrimeroValor("PrecioA").ToDouble
If PrecioAplicado > 0 Then
PrecioSugerido = PrecioAplicado
End If
End If
ObjPS.Dispose()
End If
If UsuarioActual.Empresa.Funcionalidad(404).ToString = "1" Then
Dim CvePrecioListaPS As Integer = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePrecioLista", "").ToEntero
If CvePrecioListaPS > 0 Then
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then
PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble
End If
ObjPS.Dispose()
End If
Dim PorcentajePrecio As Double = 0
If PrecioSugerido = 0 Then
CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero
If CvePrecioListaPS > 0 Then
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then
PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble
PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDouble
End If
ObjPS.Dispose()
End If
End If
If PrecioSugerido = 0 Then
Dim ObjInventarios As New ClsInventarios
Dim CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero)
'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal
If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1)
ObjInventarios.Dispose()
If CostoPS > 0 And PorcentajePrecio > 0 Then
PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS
End If
End If
End If
If PrecioSugerido > 0 Then
TxtPrecio.Text = PrecioSugerido.ToString("#,###.####") ' que muestre hasta los 4 digitos si lo requiere
End If
If IsNumeric(TxtCantidad.Text.Trim) Then
LblTotalPS.Text = (TxtCantidad.Text.Trim.ToDouble * TxtPrecio.Text.ToDouble).ToString.FormatoNumero(2)
Else
LblTotalPS.Text = "0.00"
End If
HdnIVAPS.Value = If(drPS("IVA").ToString = "-1", ViewState("IVA"), drPS("IVA").ToString).ToString
HdnIVARetAPS.Value = drPS("RetIVA").ToString
HdnAsientoContable.Value = drPS("AsientoContableVentas").ToString
HdnCtaContable.Value = drPS("IdCtaContVentas").ToString
HdnAplicaParaConcepto.Value = drPS("AplicaParaConcepto").ToString
HdnCodigo.Value = drPS("Codigo").ToString
If DdlClasificacion.SelectedIndex = 0 Then
If drPS("CveClasificacion").ToString IsNot Nothing Then
DdlClasificacion.SelectedValueExist(drPS("CveClasificacion").ToString)
Else
Alert("El Productos/Servicio no tiene asignada una Clasificación.", TipoMensaje.MsgInformacion)
End If
End If
End If
ElseIf CvePSParametro = -2 Then
CargaPS(DdlClasificacion.SelectedValue.ToEntero, Ddl)
End If
UPPPS.Update()
UpPS.Update()
End Sub
Protected Sub DdlPS_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DdlPS.selectedindexchange
DdlPSIndexChange(DdlPS.SelectedValue.ToEntero, DdlPS)
End Sub
Protected Sub DdlClasificacion_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlClasificacion.SelectedIndexChanged
CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS)
UpPS.Update()
End Sub
Protected Sub DdlNCFactura_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlNCFactura.SelectedIndexChanged
Dim objcompras As New ClsCompras
If objcompras.GetCompraDetallealmacen(0, DdlNCFactura.SelectedValue.ToEntero) Then
GvInvNC.DataSource = objcompras.DtResultados
If objcompras.DtResultados.Rows.Count > 0 Then
Tab.ActiveTabIndex = 1
Updatetabs.Update()
End If
Else
GvInvNC.DataSource = Nothing
End If
GvInvNC.DataBind()
UpINVNC.Update()
objcompras.Dispose()
End Sub
Protected Sub DdlTipoComprobante_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlTipoComprobante.SelectedIndexChanged
CambiaTipoComprobante()
End Sub
Private Sub CambiaTipoComprobante()
CambiaTipoDocto()
LimpiaEscondeContado()
End Sub
Private Sub CambiaTipoDocto()
CargaNC(IfNull(Request("CveDevolucion"), "-1").ToString.ToEntero)
ConfiguraTipoDocto()
CargaFolios()
CargaEstatusFactura(DdlTipoComprobante.SelectedValue)
UpEstatus.Update()
If UsuarioActual.TienePermisoProceso(274) Then
TrAntEspecial.Visible = DdlTipoComprobante.SelectedValue = "Ant"
End If
'REINICIALIZA VALORES DE ENTREGA POR ADELANTADO
RequiereAlmacenDestino = False
TrAlmacenAsignado.Visible = False
If DdlTipoComprobante.SelectedValue = "Cot" And UsuarioActual.Empresa.Funcionalidad(135) = "1" Then
Alert("Se ocupa una autorización.", TipoMensaje.MsgAdvertencia)
TrDireccion.Visible = False
TrCiudad.Visible = False
TrRFC.Visible = False
'RBLPago.Enabled = False
RBLPago.SelectedValue = "2"
TxtFechaVencimientoCotizacion.Text = Now.ToString
GvPS.Columns(5).Visible = True
ThTiempoEntrega.Visible = True
ThTiempoEntrega2.Visible = True
ChkEnviarFactura.Checked = True
UpnTools.Update()
tdTelefonoGen.Visible = False
tdTxtTelefonoGen.Visible = False
If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then
ChkEnviarFactura.Checked = False
End If
Else
If DdlTipoComprobante.SelectedValue = "Cot" Then
TrDireccion.Visible = False
TrCiudad.Visible = False
TrRFC.Visible = False
'RBLPago.Enabled = False
'RBLPago.SelectedValue = "2"
TxtFechaVencimientoCotizacion.Text = Now.ToString
GvPS.Columns(5).Visible = True
ThTiempoEntrega.Visible = True
ThTiempoEntrega2.Visible = True
tdTelefonoGen.Visible = False
tdTxtTelefonoGen.Visible = False
'CUANDO SEA COMPUPROVEEDORES NO MANDA COTIZACIONES
If UsuarioActual.CveEmpresa = 72 Then
ChkEnviarFactura.Checked = False
ChkEnviarFactura.Visible = False
LblEnviarMail.Visible = False
End If
If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122, 145) Then
ChkEnviarFactura.Checked = False
End If
Else
TrDireccion.Visible = True
TrCiudad.Visible = True
TrRFC.Visible = True
GvPS.Columns(5).Visible = False
ThTiempoEntrega.Visible = False
ThTiempoEntrega2.Visible = False
RBLPago.Enabled = True
LblMensaje.Visible = UsuarioActual.Empresa.Funcionalidad(152) <> "" And DdlTipoComprobante.SelectedValue.Contiene("Ing")
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Egs", "Dev") Then
ChkEnviarFactura.Checked = EnviarCorreoCliente
ChkEnviarFactura.Visible = True
LblEnviarMail.Visible = True
ObtenerFechaVencimientoCER()
If DdlTipoComprobante.SelectedValue.Contiene("Egs") Then
'se cargan las facturas timbradas
'CargaFacturasRelacionar()
'RegistraScript("$('#DivRelacionarFacturasNC').modal('show');")
End If
End If
If DdlTipoComprobante.SelectedValue.Contiene("Rem", "PeC", "PA", "Pd2") Then
'ENTREGA POR ADELANTADO
If UsuarioActual.Empresa.Funcionalidad(145) = "1" And Not DdlTipoComprobante.SelectedValue.Contiene("PA") Then 'If UsuarioActual.CveEmpresa.Contiene(4, 72, 80, 119) Then
RequiereAlmacenDestino = True
'If DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then
' TrAlmacenAsignado.Visible = True
'End If
Dim CveAlmacenDestino As Integer = DtContratos.FiltroPrimeroValor("CveAlmacenDestino", $"CveContrato = {If(DdlContratosModal.Items.Count > 0, DdlContratosModal.SelectedValue, "0")}").ToEntero
If CveAlmacenDestino > 0 Then
DdlAlmacenAsignado.Items.Clear()
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} And CveTipoAlmacen In (4,10)")
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.Items.Insert(0, New ListItem(DtContratos.FiltroPrimeroValor("Almacen", $"CveContrato = {DdlContratosModal.SelectedValue}"), CveAlmacenDestino.ToString))
DdlAlmacenAsignado.SelectedValue = CveAlmacenDestino.ToString
Else
DdlAlmacenAsignado.Items.Clear()
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (10)")
DdlAlmacenAsignado.DataBind()
End If
UpParametros.Update()
Else
RequiereAlmacenDestino = False
TrAlmacenAsignado.Visible = False
End If
'ENVIO DE FACTURA
If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then
ChkEnviarFactura.Checked = EnviarCorreoCliente
ChkEnviarFactura.Visible = True
LblEnviarMail.Visible = True
End If
End If
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem", "PA", "Pd2") AndAlso (ReceptorRFC = "XAXX010101000" Or LblRFC.Text = "XAXX010101000") Then
TrDireccion.Visible = False
TrCiudad.Visible = False
TrRFC.Visible = False
tdTelefonoGen.Visible = True
tdTxtTelefonoGen.Visible = True
Else
TxtAtencionA.Text = ""
TxtTelefonoGenerico.Text = ""
End If
End If
End If
If DdlTipoComprobante.SelectedValue.Contiene("Rem") Then
' IPP 15 Julio 2017 - ERA FALSE
ImgAntiPend.Visible = False
ElseIf Opcion <> "Op" Then
ImgAntiPend.Visible = True
End If
TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString
TabAlmacen.Enabled = DdlTipoComprobante.SelectedValue <> "Ant"
'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO
If DdlTipoComprobante.SelectedValue.Contiene("Cot", "DPe") Or TipoContrato >= 0 Then 'SI VIENE DE PEDIDO DE AF DESDE CONTRATO NO BLOQUEA CUANDO EL CLIENTE ESTA INACTIVO
BtnEmitirImprimir.Visible = True
TrVistaPrevia.Visible = True
Else
If LblCliente.Text <> "Cliente" And Not EstatusCliente Then
Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia)
End If
BtnEmitirImprimir.Visible = EstatusCliente
TrVistaPrevia.Visible = EstatusCliente
End If
TrAtencionA.Visible = True
tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
Updatetabs.Update()
UPCondicionesPago.Update()
UpCliente.Update()
UpPS.Update()
End Sub
Protected Sub DdlSucursalCliente_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSucursalCliente.SelectedIndexChanged
CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero)
End Sub
Protected Sub DdlCCEdit_SelectedIndexChanged(sender As Object, e As System.EventArgs)
Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow)
Dim CveProyecto As String = DirectCast(sender, DropDownList).SelectedValue
gvr.FCDropDownList("DDlSubProyecto").Items.Clear()
gvr.FCDropDownList("DDlSubProyecto").DataSource = GlobalDTSubProyectos(CveProyecto.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa)
gvr.FCDropDownList("DDlSubProyecto").DataBind()
gvr.FCDropDownList("DDlSubProyecto").Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1"))
End Sub
Protected Sub DdlClasificacion_SelectedIndexChanged1(sender As Object, e As EventArgs)
Dim gvr As GridViewRow = DirectCast(DirectCast(sender, DropDownList).BindingContainer, GridViewRow)
CargaPS(gvr.FCDropDownList("DdlClasificacion").SelectedValue.ToEntero, gvr.FCDropDownLost("DdlPS"))
End Sub
Protected Sub BtnEstimacion_Click(sender As Object, e As EventArgs) Handles BtnEstimacion.Click
Dim Contrato As String = ""
Dim Importe As Decimal = 0
Dim CvePS As Integer
Dim PS As String
Dim PSCodigo As String
Dim CveUM As Integer
Dim UM As String
Dim CveClasificacion As Integer
Dim Clasificacion As String
Dim CveProyecto As Integer
Dim Proyecto As String
Dim CveSubProyecto As Integer
Dim SubProyecto As String
Dim FechaInicial As String = ""
TmpDT.Rows.Clear()
For Each Row As GridViewRow In GvEst.Rows
If Row.FCCheckBox("Chk").Checked Then
Importe += Row.FCLiteral("LtlImporte").Text.ToDecimal
Contrato = Row.DataKey("NumeroContrato")
CveContrato = Row.DataKey("CveContrato").ToEntero
FechaInicial = Row.DataKey("FechaInicial").ToString.ToDate.ToString("dd MMMM yyyy")
CveSubProyecto = Row.DataKey("CveSubProyecto").ToEntero
End If
Next
If Importe > 0 Then
CvePS = UsuarioActual.Empresa.Funcionalidad(106).ToEntero
If CvePS > 0 Then
Dim rowPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("")
If rowPS IsNot Nothing Then
PS = rowPS("PS").ToString
PSCodigo = rowPS("PSCodigo").ToString
CveUM = rowPS("CveUM").ToString.ToEntero
UM = rowPS("UnidadMedida").ToString
CveClasificacion = rowPS("CveClasificacion").ToString.ToEntero
Clasificacion = rowPS("Clasificacion").ToString
Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto={0}", CveSubProyecto))
Proyecto = rowSP("Proyecto").ToString
CveProyecto = rowSP("CveProyecto").ToString.ToEntero
SubProyecto = rowSP("SubProyecto").ToString
AgregarProductoServicio(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero),
Importe, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto)
'AddPS(1, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, String.Format("{0} - {1}, con un importe de {2}", Contrato, FechaInicial, Importe.FormatoNumero), Importe, 0.16, 0, 0, 1, 0, True, "", CveProyecto, Proyecto, CveSubProyecto, SubProyecto, rowPS("CveTipoPS").ToString.ToEntero, rowPS("Inv_CveMetodoInventario").ToString.ToEntero, CodigoPS:=PSCodigo)
DdlTipoComprobante.SelectedValue = "Rem"
DdlTipoComprobante_SelectedIndexChanged(DdlTipoComprobante, Nothing)
End If
UpParametros.Update()
Tab.ActiveTab = TabGenerales
Else
Alert("La empresa no contiene un producto asignado a la estimació", TipoMensaje.MsgInformacion)
End If
Updatetabs.Update()
End If
End Sub
Protected Sub DdlProyecto_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlProyecto.SelectedIndexChanged
CargaSubProyecto()
End Sub
#End Region
#Region " SUCURSAL FACTURACION "
Private Sub DdlSubProyectoDatos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSubProyectoDatos.SelectedIndexChanged
CambiaSucursalGeneral()
End Sub
Private Sub CambiaSucursalGeneral()
Dim ObjSubProyectos As New ClsSubProyectos
'Dim ObjSucursal As New ClsSucursales
If ObjSubProyectos.GetSubProyectos() Then
DTSucursal = ObjSubProyectos.DtResultados.FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue.ToEntero))
'Dim drc As DataRow
'drc = DTSucursal(0)
DdlSubProyecto.Items.Clear()
DdlSubProyecto.DataSource = DTSucursal
DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlSubProyecto.SelectedValue = "-1"
DdlSubProyecto.DataBind()
DdlSubProyecto.SelectedValueExist(DdlSubProyectoDatos.SelectedValue)
CambiaSucursal()
DdlSubProyectoEjecucion.SelectedValueExist(DdlSubProyectoDatos.SelectedValue)
DdlSubProyectoCobranza.SelectedValueExist(DdlSubProyectoDatos.SelectedValue)
UpDetalle.Update()
'If ObjSucursal.GetSucursales(UsuarioActual.CveEmpresa) Then
' DTSucursal = ObjSucursal.DtResultados.FiltraParametros(String.Format("CveSucursal = {0}", drc("CveSucursal").ToString.ToEntero))
' Dim dre As DataRow
' dre = DTSucursal(0)
' DdlSucursal.SelectedValue = dre("CveSucursal").ToString
' CambiaSucursal()
'End If
End If
ObjSubProyectos.Dispose()
End Sub
Private Sub CambiaSucursal()
CargaFormatoSucursal()
CargaFolios()
CargaVendedores()
CargarAlmacenes()
DdlPS.Attributes.Remove("data-cvesubproyecto")
DdlPS.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue)
UpPS.Update()
End Sub
Private Sub CargaFolios()
If ExFolioFactura Then
Exit Sub
End If
If DdlSubProyectoDatos.SelectedValue.ToEntero <= 0 Then
Alert("No se tienen asignadas sucursales", TipoMensaje.MsgError)
Exit Sub
End If
'If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue <> "Cot" AndAlso (CveVenta <= 0 Or (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Or CveDevolucion > 0) Then
' TxtFolio.Text = ""
'Else
Dim ObjFolios As New ClsGralFolios()
Dim TipoDoctoConsulta As String = If(DdlTipoComprobante.SelectedValue = "Ant", "Ing", If(DdlTipoComprobante.SelectedValue = "PA", "Rem", DdlTipoComprobante.SelectedValue))
If ObjFolios.GetFolios(TipoDoctoConsulta, UsuarioActual.CveEmpresa) Then
Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue))
If DT.Rows.Count > 0 Then
ViewState("CveFolio") = DT.Rows(0)("CveFolio").ToString.ToEntero
'ViewState("NumAprobacion") = CLng(DT.Rows(0)("Aprobacion").ToString)
'ViewState("FechaAprobacion") = DT.Rows(0)("FechaAprobacion").ToString.ToDate
ViewState("FolioActual") = DT.Rows(0)("FActual").ToString
LblSerie.Text = DT.Rows(0)("Serie").ToString
TxtFolio.Text = DT.Rows(0)("FActual").ToString
BtnCrearApartirDe.Enabled = True
BtnEmitirImprimir.Visible = True
TrVistaPrevia.Visible = True
UpFacturar.Update()
Else
Alert("No tiene registrados Folios para " & DdlTipoComprobante.SelectedItem.Text & " en esta sucursal.", TipoMensaje.MsgAdvertencia)
TrEmitir.Visible = False
TrVistaPrevia.Visible = False
BtnCrearApartirDe.Enabled = False
BtnEmitirImprimir.Visible = False
UpFacturar.Update()
End If
DT.Dispose()
End If
ObjFolios.Dispose()
'End If
End Sub
Private Sub CargaFormatoSucursal()
Dim dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)))
If dr IsNot Nothing Then
ViewState("SucCalle") = dr("Calle")
ViewState("SucNoExt") = dr("NoExt")
ViewState("SucNoInt") = dr("NoInt")
ViewState("SucColonia") = dr("Colonia")
ViewState("SucLocalidad") = dr("Localidad")
ViewState("SucMunicipio") = dr("Municipio")
ViewState("SucEstado") = dr("Estado")
ViewState("SucPais") = dr("Pais")
ViewState("SucCP") = dr("CP")
ViewState("FormatoFactura") = dr("FormatoFactura")
ViewState("IVA") = dr("IVA")
DdlIVA.Visible = False
Select Case ViewState("IVA").ToString.ToDouble
Case 0
DdlIVA.SelectedValue = "1"
PorcentajeIVA = ViewState("IVA").ToString.ToDecimal
Case 0.08
DdlIVA.SelectedValue = If(EsCreaApartirDe, $"{(TmpDT.MAX("PorcentajeIVA").ToDecimal + 1).ToString}", "1.08")
PorcentajeIVA = If(EsCreaApartirDe, TmpDT.MAX("PorcentajeIVA").ToDecimal, ViewState("IVA").ToString.ToDecimal)
DdlIVA.Visible = If(Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0, True, False)
Case 0.16
DdlIVA.SelectedValue = "1.16"
PorcentajeIVA = ViewState("IVA").ToString.ToDecimal
End Select
If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 AndAlso (Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0) Then RecalculaIVA()
'ViewState("SubProyectoPorcentajeIVA") = dr("IVA")
ViewState("TipoFormato") = dr("TipoFormato")
ViewState("Serie") = dr("Serie")
LblSerie.Text = dr("Serie").ToString
If SerieXML <> "" Then LblSerie.Text = SerieXML
Dim CveSubProyecto As Integer = GetSubProyectoSucursal()
If CveSubProyecto > 0 Then CargaSubProyecto(CveSubProyecto)
UPPProy.Update()
TipoVentaSucursal = dr("TipoVenta").ToString.ToEntero
If dr("TipoVenta").ToString = "1" Then
LiBuscarPrecio.Visible = True
UpnTools.Update()
'activa el modo de pago efectivo directamente, y es venta nueva
If ViewState("CveVenta").ToString.ToEntero < 0 Then InicializaCondicionesPago()
RBLPago.SelectedValue = "2"
LimpiaEscondeContado()
If DdlCuentaEfectivo.Items.Count = 2 Then
DdlCuentaEfectivo.SelectedIndex = 0
End If
End If
End If
UpFacturar.Update()
UpPS.Update()
UpParametros.Update()
End Sub
Private Sub CargaVendedores()
Dim CveVendedorActual = DdlVendedor.SelectedValue
DdlVendedor.Items.Clear()
If UsuarioActual.Empresa.Funcionalidad(302) = "1" AndAlso DdlSubProyectoDatos.SelectedValue.ToEntero > 0 Then
DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue)).FiltraParametros("VendedorTipo = 1")
Else
DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros("VendedorTipo = 1")
End If
DdlVendedor.SelectedValue = "0"
DdlVendedor.Items.Insert(0, New ListItem("Sin Asignar", "0"))
DdlVendedor.DataBind()
DdlVendedor.SelectedValueExist(CveVendedorActual)
If Not DdlVendedor.SelectedValue.ToEntero > 0 Then
DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString)
End If
End Sub
#End Region
#Region " AGREGAR PS "
Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click
AgregarPS()
End Sub
Private Function ValidaAgregarPS(CvePS As Integer, CveUM As Integer, PU As Double, CveTipoPS As Integer) As Boolean 'NO TOCAR - IPP
'VALIDA PARAMETROS
If CvePS <= 0 Or CveUM <= 0 Then
Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia)
Return False
End If
If HdnPS.Value = "" Or HdnPS.Value = "-1" Then
Alert("Es necesario seleccionar el Producto o Servicio a facturar.", TipoMensaje.MsgAdvertencia)
Return False
End If
'SI USA CONTABILIDAD LA CLASIFICACION ES OBLIGATORIA
If DdlClasificacion.SelectedValue.ToEntero <= 0 AndAlso UsuarioActual.Empresa.UsaContabilidad Then
Alert("La Clasificación es obligatoria, favor de seleccionarla", TipoMensaje.MsgAdvertencia)
Return False
End If
'SUBPROYECTO OBLIGATORIO
If DdlSubProyecto.SelectedValue.ToEntero <= 0 AndAlso UsuarioActual.Empresa.Funcionalidad(120) = "1" Then
Alert("El Subproyecto es obligatorio, favor de seleccionarlo", TipoMensaje.MsgAdvertencia)
Return False
End If
If CveCliente <= 0 And Not CveEmpresaCRM > 0 Then
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact', 800, 547, 'N', 'PopUpBuscar')")
Return False
End If
'VALIDA PROMOCIONES
Dim ObjVentas As New ClsVentas
If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero, CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
DtPromociones = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
'VALIDA PRECIO CERO (0)
If UsuarioActual.Empresa.Funcionalidad(139).ToString.ToEntero > 0 And PU = 0 And DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {CvePS}").ToDecimal > 0 Then
Alert($"El producto <b>{HdnPS.Value}</b>. No se puede vender a un importe de cero ($0)", TipoMensaje.MsgAdvertencia)
Return False
End If
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
If Not UsuarioActual.TienePermisoProceso(169) Then ' NO VALIDA EXISTENCIAS NI COSTO - PERMISO PARA NO VALIDAR
'SOLO VALIDA EXISTENCIAS Y COSTO: SI USA INVENTARIOS, SOLO PRODUCTOS TIPO PRODUCTO, SOLO REMISIONES E INGRESOS
If UsuarioActual.Empresa.UsaInventarios AndAlso CveTipoPS = 2 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119))) Then
Dim ObjInventarios As New ClsInventarios
Dim Existencia As Decimal = ObjInventarios.GetExistenciasPS(CvePS, CveUM, UsuarioActual.CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1)
Dim Costo As Decimal = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero)
'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal
If Costo = 0 Then Costo = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, -1)
ObjInventarios.Dispose()
Dim PrecioMinimo As Decimal = 0
'RMF. condicion temporal, para reubicación, precio mínimo
If UsuarioActual.CveEmpresa = 119 Then
'Dim CvePrecioLista As Integer = 38
Dim objPS As New ClsProductosServicios
If objPS.GetPSSucursalesALL(CvePS, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then
PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal
If PrecioMinimo > 0 Then
Costo = PrecioMinimo
End If
End If
objPS.Dispose()
End If
If DdlTipoComprobante.SelectedValue <> "Cot" And ChkSinExistencia.Checked = False Then
'VALIDA EXISTENCIA
If UsuarioActual.CveEmpresa.Contiene({72, 80, 119}) Then
If Existencia - TmpDT.SUM("Cantidad", $"CvePS = {CvePS}") < TxtCantidad.Text.ToDouble Then
Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia)
Return False
End If
End If
End If
'VALIDA COSTOS
If Not CveContrato > 0 Then
'BANDERAS PARA VALIDACIONES
Dim EsValido = False
Dim EsValidoMayor = False
Dim CostoMenor = 0.0D
Dim CostoMayor = 0.0D
'PRECIO MINIMO
If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo)
If PrecioMinimo > 0 Then CostoMenor = PrecioMinimo
'SI EL PRECIO ES MAYOR AL COSTO, SI PASA
If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= CostoMenor Then
EsValido = True
End If
Else
EsValido = True
End If
'PRECIO MAXIMO
If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo)
'SI EL PRECIO ES MAYOR AL COSTO MAXIMO, SI PASA
If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) <= CostoMayor Then
EsValidoMayor = True
End If
Else
EsValidoMayor = True
End If
'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR
'SIRVE PARA VALIDAR PRECIOS DEBAJO DEL PRECIO MINIMO PERMITIDO
If Not EsValido Then
If DtPromociones.FiltraParametros($"CvePS = {CvePS}").Rows.Count > 0 Then
If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {CvePS}").ToDecimal Then
EsValido = True
End If
End If
End If
'NO DEJA REGISTRAR MENOS AL PRECIO MINIMO
Dim MensajeCosto As New StringBuilder
Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201)
If Not EsValido Then
MensajeCosto.AppendFormat("El Producto <b>{0}</b>. No se puede vender a un precio menor de su Costo <br/>", HdnPS.Value)
If TienePermisoImportes Then
MensajeCosto.AppendFormat("El costo del producto es: <b>${0}</b> <br/>", Costo)
MensajeCosto.AppendFormat("El rango menor aceptado es: {0}% <b>${1}</b> <br/>", UsuarioActual.Empresa.Funcionalidad(129).ToEntero, CostoMenor)
MensajeCosto.AppendFormat("El precio indicado es: <b>${0}</b> ({1}% de ganancia) <br/>", 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 <b>{0}</b>. No se puede vender a un precio mayor de su rango aceptado<br/>", HdnPS.Value)
If TienePermisoImportes Then
MensajeCosto.AppendFormat("El costo del producto es: <b>${0}</b> <br/>", Costo)
MensajeCosto.AppendFormat("El rango mayor aceptado es: {0}% <b>${1}</b> <br/>", UsuarioActual.Empresa.Funcionalidad(133).ToEntero, CostoMayor)
MensajeCosto.AppendFormat("El precio indicado es: <b>${0}</b> ({1}% de ganancia) <br/>", PU.FormatoNumero, (If(Costo > 0, ((PU - Costo) * 100) / Costo, 0)).FormatoNumero)
End If
Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia)
Return False
End If
End If
End If
End If
Return True
End Function
Private Sub AgregarPS()
'SELECCIONA EL PS DEPENDIENDO LA MODALIDAD (CODIGO BARRAS - DDL)
Dim CvePS = -1
If DIVCod.Visible Then
CvePS = HdnCvePS.Value.ToEntero
Else
CvePS = DdlPS.SelectedValue.ToEntero
End If
If ValidaAgregarPS(CvePS, DdlUnidadMedida.SelectedValue.ToEntero, TxtPrecio.Text.Trim.ToDouble, HdnTipoPS.Value.ToEntero) Then
If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then
CvePSAmortizacion = DdlPS.SelectedValue.ToEntero.ToEntero
End If
Dim Descuento As Decimal = HdnDescuento.Value.ToDecimal
If HdnTipoDescuento.Value = "0" Then
Descuento = HdnDescuento.Value.ToDecimal * TxtCantidad.Text.ToDecimal
End If
AgregarProductoServicio(TxtCantidad.Text.ToDecimal, DdlUnidadMedida.SelectedValue.ToEntero, DdlUnidadMedida.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero, DdlClasificacion.SelectedItem.Text,
CvePS, "", TxtObsPS.Text.Trim, If(CvePSAmortizacion > 0, TxtPrecio.Text.Trim.ToDecimal * -1, TxtPrecio.Text.Trim.ToDecimal), Descuento,
DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text,
SerieLote:=If(DIVCod.Visible, TxtCodigoSerie.Text.Trim, ""), TiempoEntrega:=TxtTiempoEntrega.Text, CuentaPredial:=TxtCuentaPredial.Text.Trim, RegeneraIEPS:=ClienteDesglosaIEPS)
CalculaUsados()
CalculaTotalesVenta()
LimpiaAgregar()
'SI EL PORLET DE COMERCIO EXTERIOR EXTERIOR ESTA VISIBLE SE ACTUALIZAN LOS PRODUCTOS DEL GRIDVIEW
If AplicaComercioExterior Then
CargaGvComercioExterior()
End If
End If
''NO SIRVE PARA NADA - NO SE USAN LAS VARIABLES - IPP 28 AGOSTO 2017
'For Each gvr As GridViewRow In GVAnticipos.Rows
' Dim total As Decimal = TxtTotal.Text.ToString.ToDecimal
' Dim saldo As Decimal = gvr.DataKey("Saldo").ToDecimal
' Dim maxsaldo As Decimal
' If total > saldo Then
' maxsaldo = saldo
' Else
' maxsaldo = total
' End If
'Next
End Sub
Private Sub AgregarPSPYME()
If Modalidad = "A" Then
Dim CveProyecto As Integer = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedValue, "0").ToString.ToEntero
Dim Proyecto As String = IIf(DdlProyectoPyME.SelectedValue <> "-1", DdlProyectoPyME.SelectedItem.Text, "").ToString
Dim CveSubProyecto As Integer = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedValue, "0").ToString.ToEntero
Dim SubProyecto As String = IIf(DdlSubProyectoPyME.SelectedValue <> "-1", DdlSubProyectoPyME.SelectedItem.Text, "").ToString
AgregarProductoServicio(TxtCantidadPyME.Text.ToDecimal, DdlUMPyME.SelectedValue.ToEntero, DdlUMPyME.SelectedItem.Text, DdlClasificacionPyME.SelectedValue.ToEntero, DdlClasificacionPyME.SelectedItem.Text,
DdlPSPyME.SelectedValue.ToEntero, DdlPSPyME.SelectedText, TxtObsPyME.Text, TxtPrecioPyME.Text.ToDecimal, 0, CveProyecto, Proyecto, CveSubProyecto, SubProyecto)
CalculaTotalesVenta()
ElseIf Modalidad = "U" Then
Dim ErrorEdit As Boolean = True
Dim Contador As Integer = 0
For Each row As DataRow In TmpDT.Rows
If row("Consec").ToString.ToEntero = Index Then
ErrorEdit = False
Exit For
End If
Contador = Contador + 1
Next
If ErrorEdit = True Then
Exit Sub
Else
TmpDT.AcceptChanges()
TmpDT.Rows.RemoveAt(Contador)
TmpDT.AcceptChanges()
End If
End If
End Sub
Private Sub LimpiaAgregar()
TxtCantidad.Text = ""
HdnPS.Value = "-1"
HdnCodigoPS.Value = "-1"
HdnTipoPS.Value = "-1"
HdnTipoInv.Value = "-1"
DdlClasificacion.SelectedIndex = 0
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPS.SelectedValue = "-1"
Else
DdlPS.SelectedValue = ""
DdlPS.SelectedText = ""
End If
TxtObsPS.Text = ""
TxtPrecio.Text = ""
LblTotalPS.Text = "0.00"
HdnIVAPS.Value = "-1"
HdnIVARetAPS.Value = "-1"
HdnAplicaIEPS.Value = "False"
HdnPorcentajeIEPS.Value = "0"
HdnAsientoContable.Value = "-1"
HdnCtaContable.Value = "-1"
HdnAplicaParaConcepto.Value = "False"
HdnCodigo.Value = "-1"
TxtCuentaPredial.Text = ""
' codigo comentado RMF. 2016.06.13, esto paa que respete el que tenga selecionado e nla sucursal
'DdlProyecto.SelectedIndex = 0
'DdlSubProyecto.Items.Clear()
'DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1"))
TxtCantidad.Focus()
'Limpia descuentos
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
LblPrecio1.Text = "0.00"
LblTotalPS1.Text = "0.00"
TxtPorDescP.Text = "0"
TxtDescP.Text = "0"
LblDescuento.Text = "0.00"
LblPrecioFinal.Text = "0.00"
'CODIGO BARRAS
TxtCodigoBarras.Text = ""
TxtCodigoSerie.Text = ""
'FOCUS DEPENDIENDO MODALIDAD DE CODIGO BARRAS
If DIVCod.Visible Then
TxtCodigoBarras.Focus()
Else
TxtCantidad.Focus()
End If
UPPDescuento.Update()
UpINV.Update()
UPPPS.Update()
End Sub
Private Function AgregarProductoServicio(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String,
PU As Decimal, Descuento As Decimal,
CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String,
Optional SerieLote As String = "", Optional TiempoEntrega As String = "", Optional EntregaDirecta As Integer = 0,
Optional CveContratoDetalle As Integer = 0, Optional CveVentaDetalle As Integer = 0, Optional CveMovimientoDetallePedido As Integer = 0,
Optional CveOrdenCompraDetalle As Integer = 0, Optional CveVentaDetalleRemision As Integer = 0, Optional CveVentaDetalleCotizacion As Integer = 0,
Optional CuentaPredial As String = "", Optional RegeneraIEPS As Boolean = True, Optional CveVentaDetallePedido2 As Integer = 0,
Optional SeActualiza As Boolean = False) As Boolean
Dim Retorno As Boolean = False
If Not CvePS > 0 Then
Alert("Ocurrió un error al cargar la información del producto a agregar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError)
Return False
End If
If (Obs.Length + PS.Length > 1000) AndAlso DdlTipoComprobante.SelectedValue <> "Cot" Then
Alert(String.Format("El Nombre y observación del producto tiene longitud de {0} caracteres y excede los 1000 caracteres permitidos.", Obs.Length + PS.Length), TipoMensaje.MsgAdvertencia)
Return False
End If
'VALIDA CONCEPTOS EN CERO - YA SE VALIDA ANTES CON FUNCIONALIDAD - A MIRAS DE ELIMINAR - IPP 28 AGOSTO 2017
If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "Ant") Then
If UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso CveOrdenCompraDetalle = 0 Then ' si viene de una oc, se permiten valores en cero
If Cantidad * PU <= 0 Then
If Not DdlTipoComprobante.SelectedValue = "DPe" Then
Alert("El importe del concepto debe ser mayor a cero. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return False
End If
End If
End If
End If
Dim Row As DataRow = Nothing
Dim TotalCalculableImpuestos As Decimal = 0
PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos
Row = TmpDT.NewRow()
Row("CveProyecto") = CveProyecto
Row("Proyecto") = Proyecto
Row("CveSubProyecto") = CveSubProyecto
Row("SubProyecto") = SubProyecto
Row("SerieLote") = SerieLote
Row("TiempoEntrega") = TiempoEntrega
Row("Orden") = TmpDT.Rows.Count + 1
Row("Cantidad") = Cantidad
Row("CveUM") = CveUM
Row("UM") = UM
Row("CveClasificacion") = CveClasificacion
Row("Clasificacion") = Clasificacion
Row("CvePS") = CvePS
Row("Obs") = Obs
Dim DrPS As DataRow = Nothing
DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") ' Estado = -1
If DrPS Is Nothing Then
Alert("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.", TipoMensaje.MsgError)
Return False
End If
If (DrPS("SATClaveUnidadMedida").ToString = "" Or DrPS("SATClavePS").ToString = "") Then
'VALIDA CLAVESAT
If Not DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then 'DOCUMENTOS DONDE NO SE VALIDA
If DrPS("SATClavePS").ToString = "" Then
MensajeCveSAT.AppendFormat("<b>{0}-{1}</b>: Sin producto SAT<br/>", DrPS("Codigo").ToString, DrPS("PS").ToString)
Return False
ElseIf DrPS("SATClaveUnidadMedida").ToString = "" Then
MensajeCveSAT.AppendFormat("<b>{0}-{1}</b>: Sin Unidad Medida SAT<br/>", DrPS("Codigo").ToString, DrPS("PS").ToString)
Return False
End If
End If
End If
If Not ClienteDesglosaIEPS Then
If Not RegeneraIEPS Then
PU = PU * (1 + DrPS("IEPSPorcentaje").ToString.ToDecimal)
End If
DrPS("IEPSPorcentaje") = 0
End If
'verifica si tiene ventaminima
If Cantidad > 0 AndAlso DrPS("VentaMinima").ToString.ToDecimal > 0 Then
'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15...
If Cantidad Mod DrPS("VentaMinima").ToString.ToDecimal <> 0 Then
Alert(String.Format("El producto se vende solo en cantidades de {0}", DrPS("VentaMinima").ToString))
Return False
End If
End If
TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento
Row("PU") = PU
Row("Codigo") = DrPS("Codigo")
Row("NoIdentificacion") = DrPS("Codigo")
Row("ClaveSATFraccionArancelaria") = DrPS("ClaveSATFraccionArancelaria")
Row("ClaveSATUnidadAduana") = DrPS("ClaveSATUnidadAduana")
Row("ClaveSATFraccionArancelariaDescripcion") = DrPS("ClaveSATFraccionArancelariaDescripcion")
Row("ClaveSATUnidadAduanaDescripcion") = DrPS("ClaveSATUnidadAduanaDescripcion")
If Modalidad = "U" Then
Row("Consec") = Index
Else
Row("Consec") = TmpDT.Rows.Count + 1
End If
Row("PS") = DrPS("PS")
Row("CodigoPS") = DrPS("PSCodigo").ToString
Row("CveTipoPS") = DrPS("CveTipoPS")
Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario")
Row("CveTamaño") = DrPS("CveTamaño")
If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion")
If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion")
If DrPS("IVA").ToString.Contiene("-1", "") Then
Row("PorcentajeIVA") = PorcentajeIVA
Else
Row("PorcentajeIVA") = DrPS("IVA")
End If
Row("IVA") = Row("PorcentajeIVA")
Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
Row("PorcentajeRetIVA") = ClienteRetIVA
Row("PorcentajeRetISR") = ClienteRetISR
Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje")
Row("ImporteIEPS") = Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Row("IEPS") = Row("ImporteIEPS")
Row("Descuento") = Math.Round(Descuento, NumeroDecimales)
Row("TipoDescuento") = HdnTipoDescuento.Value
Row("Total") = (Cantidad * PU)
Row("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales)
'Row("AsientoContableVentas") = DrPS("AsientoContableVentas")
' Row("IdCtaContVentas") = IdCtaContable
' Row("AplicaParaConcepto") = AplicaParaConcepto
Row("SATClaveProdServ") = DrPS("SATClavePS")
Row("SATClaveUM") = DrPS("SATClaveUnidadMedida")
If UsuarioActual.Empresa.UsaAC Then
Row("CvePresupuestoIngreso") = Me.DdlFuenteRecaudacion.SelectedValue
End If
Row("EntregaDirecta") = EntregaDirecta
'Contratos
Row("CveContratoDetalle") = CveContratoDetalle
Row("CveVentaDetalle") = CveVentaDetalle
Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
Row("CveVentaDetalleRemision") = CveVentaDetalleRemision
Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion
Row("CveVentaDetallePedido2") = CveVentaDetallePedido2
Row("CuentaPredial") = CuentaPredial
If UsuarioActual.CveEmpresa = 119 Then
If Not RemisionesLista.Count > 0 Then 'SI VIENE DE REMISION NO SE CONSIDERA
'MONEDA DIFERENTE DEL PS AL PRIMER PS AGREGADO
If DdlMoneda.Enabled = False And CveVenta < 0 And TmpDT.Rows.Count > 0 Then
If DdlMoneda.SelectedValue <> DrPS("CveMoneda").ToString Then
Alert($"La moneda base del producto: <b>{DrPS("PSCodigo").ToString}</b> es diferente a la moneda del documento.", TipoMensaje.MsgAdvertencia)
Return False
End If
End If
'ACTIVA PRODUCTOS DE LA MISMA MONEDA
If TmpDT.Rows.Count = 0 And CveVenta < 0 Then
DdlMoneda.SelectedValueExist(DrPS("CveMoneda").ToString)
CambiaMoneda()
DdlMoneda.Enabled = False
End If
End If
End If
'RECARGAR GV
TmpDT.Rows.Add(Row)
'AGREGA PS ADICIONAL
If UsuarioActual.Empresa.Funcionalidad(561).ToString = "1" AndAlso GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows.Count > 0 AndAlso ChkPoliza.Checked AndAlso Not SeActualiza Then
For Each Dr As DataRow In GlobalDTPSAdicionales(CvePS, UsuarioActual.CveEmpresa).Rows
Dim CvePSAdicional As Integer = Dr("CvePSAdicional").ToString.ToEntero
Dim DrPoliza As DataRow = TmpDT.NewRow()
DrPoliza.ItemArray = Row.ItemArray
Dim DrPSAdicional = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSAdicional).Rows(0)
If DrPSAdicional IsNot Nothing Then
DrPoliza("CvePS") = CvePSAdicional
DrPoliza("PS") = DrPSAdicional("PS").ToString
DrPoliza("CveUM") = DrPSAdicional("CveUM").ToString.ToEntero
DrPoliza("UM") = DrPSAdicional("UnidadMedida").ToString
DrPoliza("CveClasificacion") = DrPSAdicional("CveClasificacion").ToString.ToEntero
DrPoliza("Clasificacion") = DrPSAdicional("Clasificacion").ToString
DrPoliza("CodigoPS") = DrPSAdicional("PSCodigo").ToString
DrPoliza("CveTipoPS") = DrPSAdicional("CveTipoPS")
DrPoliza("CveTipoInvPS") = DrPSAdicional("Inv_CveMetodoInventario")
DrPoliza("NoIdentificacion") = DrPSAdicional("Codigo")
If Modalidad = "U" Then
DrPoliza("Consec") = Index
Else
DrPoliza("Consec") = TmpDT.Rows.Count + 1
End If
Row("Orden") = TmpDT.Rows.Count + 1
DrPoliza("Cantidad") = If(Dr("Cantidad").ToString.ToDecimal > 0, Dr("Cantidad").ToString.ToDecimal, Cantidad)
PU = 0
Dim PrecioSugerido As Decimal = 0
Dim CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero
If CvePrecioListaPS > 0 Then
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSAdicional) Then
PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDecimal
If PrecioSugerido = 0 Then
Dim ObjInventarios As New ClsInventarios
Dim CostoPS = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString.ToDecimal, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero)
'si el costo es cero, puede ser que no halla movimientos del producto, en esa sucursal. y se volverá a sacar sin especificar sucursal
If CostoPS = 0 Then CostoPS = ObjInventarios.GetCostoPS(CvePSAdicional, DrPoliza("Cantidad").ToString.ToDecimal, -1, "-1", TxtFecha.Text.ToDate, -1)
ObjInventarios.Dispose()
Dim PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDecimal
If CostoPS > 0 And PorcentajePrecio > 0 Then
PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS
End If
End If
ObjPS.Dispose()
End If
End If
If PrecioSugerido > 0 Then
PU = PrecioSugerido
End If
PU = Math.Round(PU, 6)
DrPoliza("PU") = PU
TotalCalculableImpuestos = (DrPoliza("Cantidad").ToString.ToDecimal * (PU)) - Descuento
If DrPSAdicional("IVA").ToString.Contiene("-1", "") Then
DrPoliza("PorcentajeIVA") = PorcentajeIVA
Else
DrPoliza("PorcentajeIVA") = DrPSAdicional("IVA")
End If
DrPoliza("IVA") = DrPoliza("PorcentajeIVA")
DrPoliza("ImporteIVA") = Math.Round(DrPoliza("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
DrPoliza("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
DrPoliza("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
DrPoliza("PorcentajeRetIVA") = ClienteRetIVA
DrPoliza("PorcentajeRetISR") = ClienteRetISR
DrPoliza("PorcentajeIEPS") = DrPSAdicional("IEPSPorcentaje")
DrPoliza("ImporteIEPS") = Math.Round(DrPSAdicional("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
DrPoliza("IEPS") = DrPoliza("ImporteIEPS")
DrPoliza("Descuento") = Math.Round(Descuento, NumeroDecimales)
DrPoliza("TipoDescuento") = HdnTipoDescuento.Value
DrPoliza("Total") = (DrPoliza("Cantidad").ToString.ToDecimal * PU)
DrPoliza("TotalImporte") = Math.Round(DrPoliza("Cantidad").ToString.ToDecimal * PU, NumeroDecimales)
DrPoliza("SATClaveProdServ") = DrPSAdicional("SATClavePS")
DrPoliza("SATClaveUM") = DrPSAdicional("SATClaveUnidadMedida")
TmpDT.Rows.Add(DrPoliza)
End If
Next
End If
Retorno = True
Return Retorno
End Function
#End Region
#Region "D A T A - T A B L E S"
Private Sub CreaDTVentas()
TmpDT = New DataTable
TmpDT.Columns.Add("CveVenta", GetType(Integer))
TmpDT.Columns.Add("Consec", GetType(Integer))
TmpDT.Columns.Add("Cantidad", GetType(Decimal))
TmpDT.Columns.Add("Codigo", GetType(String))
TmpDT.Columns.Add("CveUM", GetType(Integer))
TmpDT.Columns.Add("UM", GetType(String))
TmpDT.Columns.Add("SATClaveUM", GetType(String))
TmpDT.Columns.Add("CveClasificacion", GetType(Integer))
TmpDT.Columns.Add("Clasificacion", GetType(String))
TmpDT.Columns.Add("CvePS", GetType(Integer))
TmpDT.Columns.Add("PS", GetType(String))
TmpDT.Columns.Add("CodigoPS", GetType(String))
TmpDT.Columns.Add("SATClaveProdServ", GetType(String))
TmpDT.Columns.Add("NoIdentificacion", GetType(String))
TmpDT.Columns.Add("CveTipoPS", GetType(Integer))
TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer))
TmpDT.Columns.Add("SerieLote", GetType(String))
TmpDT.Columns.Add("CuentaPredial", GetType(String))
TmpDT.Columns.Add("Obs", GetType(String))
TmpDT.Columns.Add("TiempoEntrega", GetType(String))
TmpDT.Columns.Add("PU", GetType(Decimal))
TmpDT.Columns.Add("IVA", GetType(Decimal))
TmpDT.Columns.Add("ImporteIVA", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeIVA", GetType(Decimal))
TmpDT.Columns.Add("ImporteRetIVA", GetType(Decimal))
TmpDT.Columns.Add("ImporteRetISR", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeRetIVA", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeRetISR", GetType(Decimal))
TmpDT.Columns.Add("ImporteIEPS", GetType(Decimal))
TmpDT.Columns.Add("IEPS", GetType(Decimal))
TmpDT.Columns.Add("PorcentajeIEPS", GetType(Decimal))
TmpDT.Columns.Add("Descuento", GetType(Decimal))
TmpDT.Columns.Add("TipoDescuento", GetType(Integer))
TmpDT.Columns.Add("TotalImporte", GetType(Decimal))
TmpDT.Columns.Add("Total", GetType(Decimal))
'Para uso del módulo contable
TmpDT.Columns.Add("AsientoContableVentas", GetType(Integer))
TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer))
TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean))
TmpDT.Columns.Add("CveProyecto", GetType(Integer))
TmpDT.Columns.Add("Proyecto", GetType(String))
TmpDT.Columns.Add("CveSubProyecto", GetType(Integer))
TmpDT.Columns.Add("SubProyecto", GetType(String))
TmpDT.Columns.Add("CveVentaDetallePadre", GetType(Integer))
'TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto
TmpDT.Columns.Add("CvePresupuestoIngreso", GetType(Integer))
TmpDT.Columns.Add("CveFuenteRecaudacion", GetType(Integer))
'Contratos
TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer))
'Remisiones a Facturas
TmpDT.Columns.Add("CveVentaDetalle", GetType(Integer))
TmpDT.Columns.Add("CveVentaDetalleRemision", GetType(Integer))
TmpDT.Columns.Add("CveVentaDetalleCotizacion", GetType(Integer))
'Pedido2 a Facturas
TmpDT.Columns.Add("CveVentaDetallePedido2", GetType(Integer))
TmpDT.Columns.Add("Origen", GetType(Integer))
'Ordenes Servicio
TmpDT.Columns.Add("CveOS", GetType(Integer))
TmpDT.Columns.Add("CveOSDetalle", GetType(Integer))
TmpDT.Columns.Add("SeFacturara", GetType(Integer))
TmpDT.Columns.Add("Folio", GetType(Integer))
TmpDT.Columns.Add("Estatus", GetType(String))
'Ordenamiento
TmpDT.Columns.Add("Orden", GetType(Integer))
TmpDT.Columns.Add("TipoDocto", GetType(String))
'OC
TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer))
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal))
TmpDT.Columns.Add("CantidadFacturadaCot", GetType(Decimal))
TmpDT.Columns.Add("CantidadFacturadaPed2", GetType(Decimal))
TmpDT.Columns.Add("CantidadInventario", GetType(Decimal))
TmpDT.Columns.Add("ClaveSATFraccionArancelaria", GetType(String))
TmpDT.Columns.Add("ClaveSATUnidadAduana", GetType(String))
TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", GetType(String))
TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", GetType(String))
TmpDT.Columns.Add("CveTamaño", GetType(Integer))
End Sub
Private Sub CreaDTmpC()
DTmpC = New DataTable
DTmpC.Columns.Add("Descripcion", GetType(String))
End Sub
Private Sub CreaDTmpF()
DTmpF = New DataTable
DTmpF.Columns.Add("CveVenta", GetType(Integer))
DTmpF.Columns.Add("Titulo", GetType(String))
DTmpF.Columns.Add("Nombre", GetType(String))
DTmpF.Columns.Add("Puesto", GetType(String))
DTmpF.Columns.Add("Lado", GetType(Integer))
End Sub
Private Sub CreaDTImpuestos()
TmpDTImpuestos = New DataTable
TmpDTImpuestos.Columns.Add("CveImpuestoLocal", GetType(Integer))
TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String))
TmpDTImpuestos.Columns.Add("Porcentaje", GetType(Decimal))
TmpDTImpuestos.Columns.Add("Importe", GetType(Decimal))
TmpDTImpuestos.Columns.Add("TipoImpuesto", GetType(Integer))
TmpDTImpuestos.Columns.Add("IdCtaContable", GetType(Integer))
TmpDTImpuestos.Columns.Add("CveCuenta", GetType(Integer))
TmpDTImpuestos.Columns.Add("Orden", GetType(Integer))
End Sub
Private Sub CreaDTImpuestosIVAIEPS()
TmpDTImpuestosIVAIEPS = New DataTable
TmpDTImpuestosIVAIEPS.Columns.Add("Impuesto", GetType(String))
TmpDTImpuestosIVAIEPS.Columns.Add("tasa", GetType(String))
TmpDTImpuestosIVAIEPS.Columns.Add("Importe", GetType(Decimal))
TmpDTImpuestosIVAIEPS.Columns.Add("Orden", GetType(Integer))
End Sub
Private Sub CreaDTDocumentosRelacionados()
TmpDTDocumentosRelacionados = New DataTable
TmpDTDocumentosRelacionados.Columns.Add("SerieFolio", GetType(String))
TmpDTDocumentosRelacionados.Columns.Add("Fecha", GetType(String))
TmpDTDocumentosRelacionados.Columns.Add("Importe", GetType(Decimal))
TmpDTDocumentosRelacionados.Columns.Add("FolioFiscal", GetType(Integer))
End Sub
#End Region
#Region "P D F"
#End Region
#Region "A C T U A L I Z A "
#Region "New"
'Private Function ActualizaTimbrado(Timbro As Boolean, CveVenta As Integer) As Boolean
' Dim Retorno = False
' Dim ObjVentas As New ClsVentas()
' 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 Integer
Dim Retorno As Integer = 0
Dim IDPoliza As Integer = 0
Dim ErrorAC As Boolean = False
'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL()
Dim Fecha As Date = factura.Fecha
Dim Concepto As String = String.Format("GD {0}", factura.Cliente.Nombre)
Dim Paridad As Integer = 1
Dim TipoMovto As Boolean = False
If CancelacionIngreso Then
Concepto = String.Format("Cancelación GD {0}", factura.Cliente.Nombre)
Paridad = -1
TipoMovto = True
End If
Dim TipoPoliza = If(factura.TipoDocto = "OP" Or factura.TipoDocto = "Com", 3, 1)
IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, factura.Total * 2, factura.Total * 2, factura.CveUsuario, Fecha)
Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue))
'Dim Importe As Double = TxtTotal.Text.ToDouble
Dim CtaCliente As Integer = factura.Cliente.IdCtaContClientes
Dim CtaISSSTESON As Integer = 643
Dim CtaISPT As Integer = 1745
' Dim NombreCliente As String = ViewState("NombreCliente").ToString
If IDPoliza > 0 Then
'Orden de PAGO
If factura.TipoDocto = "OP" Then
If DdlOrdenPago.SelectedValue.ToEntero = 1 Then
'ISSSTESON
If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then
If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then
ErrorAC = True
End If
Else
ErrorAC = True
End If
Else
'ISPT
If ObjAC.AddMovimiento(IDPoliza, factura.Cliente.IdCtaContClientes, False, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then
If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * factura.Total, "", Concepto, 0, Fecha, "") Then
ErrorAC = True
End If
Else
ErrorAC = True
End If
End If
' NORMAL
Else
Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)()
Group gvr By Grp = New With {
Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero
} Into Group
Select Grp.CvePresupuestoIngreso,
TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble)
'Select Case TipoComprobante
' Case "Ing", "Egs"
For Each grp In Detalles
dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso))
Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString, TxtFolio.Text)
If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString.ToEntero, False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
'CARGO la deuda del cliente
If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
'abono,
If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString.ToEntero, Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
ErrorAC = True
End If
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
Next
'Case "OP", "Com"
' Dim Importe As Decimal = 0
' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then
' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then
' End If
' End If
'End Select
End If
Else
ErrorAC = True
End If
If Not ErrorAC Then
ObjAC.AjustaPoliza(IDPoliza)
Retorno = IDPoliza
Else
Alert("Error al agregar la Póliza de AC.", TipoMensaje.MsgError)
End If
' ObjAC.Dispose()
Return Retorno
End Function
Private Function GenerarPolizaAC(ObjAC As ClsContPAQi, Optional CancelacionIngreso As Boolean = False) As Integer
Dim Retorno As Integer = 0
Dim IDPoliza As Integer = 0
Dim ErrorAC As Boolean = False
'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL()
Dim Fecha As Date = TxtFecha.Text.ToDate
Dim Concepto As String = String.Format("GD {0}", NombreCliente)
Dim Paridad As Integer = 1
Dim TipoMovto As Boolean = False
If CancelacionIngreso Then
Concepto = String.Format("Cancelación GD {0}", NombreCliente)
Paridad = -1
TipoMovto = True
End If
Dim TipoPoliza = If(DdlTipoComprobante.SelectedValue.ToString = "OP" Or DdlTipoComprobante.SelectedValue.ToString = "Com", 3, 1)
IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, TxtTotal.Text.ToDouble * 2, TxtTotal.Text.ToDouble * 2, UsuarioActual.CveUsuario, Fecha)
Dim dr As DataRow ' = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", DdlFuenteRecaudacion.SelectedValue))
'Dim Importe As Double = TxtTotal.Text.ToDouble
Dim CtaCliente As Integer = ViewState("IdCtaContClientes").ToString.ToEntero
Dim CtaISSSTESON As Integer = 643
Dim CtaISPT As Integer = 1745
' Dim NombreCliente As String = ViewState("NombreCliente").ToString
If IDPoliza > 0 Then
'Orden de PAGO
If DdlTipoComprobante.SelectedValue.ToString = "OP" Then
If DdlOrdenPago.SelectedValue.ToEntero = 1 Then
'ISSSTESON
If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then
If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then
ErrorAC = True
End If
Else
ErrorAC = True
End If
Else
'ISPT
If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then
If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * TxtTotal.Text.ToDecimal, "", Concepto, 0, Fecha, "") Then
ErrorAC = True
End If
Else
ErrorAC = True
End If
End If
' NORMAL
Else
Dim Detalles = From gvr As GridViewRow In GvPS.Rows.Cast(Of GridViewRow)()
Group gvr By Grp = New With {
Key .CvePresupuestoIngreso = gvr.FCDropDownList("DdlFR").SelectedValue.ToEntero
} Into Group
Select Grp.CvePresupuestoIngreso,
TotalImporte = Group.Sum(Function(r) r.FCLiteral("LtlTotal").Text.ToDouble)
'Select Case TipoComprobante
' Case "Ing", "Egs"
For Each grp In Detalles
dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp.CvePresupuestoIngreso))
Concepto = String.Format("{0} - {1}: {2}", NombreCliente, DdlTipoComprobante.SelectedItem.Text.ToString, TxtFolio.Text)
If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString.ToEntero, False, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, Paridad * grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
'CARGO la deuda del cliente
If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
'abono,
If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString.ToEntero, Not TipoMovto, grp.TotalImporte, "", Concepto, 0, Fecha, "") Then
ErrorAC = True
End If
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
Else
ErrorAC = True
End If
Next
'Case "OP", "Com"
' Dim Importe As Decimal = 0
' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, False, Importe, "", Concepto, 0, Fecha, "") Then
' If ObjAC.AddMovimiento(123456, IDPoliza, CtaCliente, True, Importe, "", Concepto, 0, Fecha, "") Then
' End If
' End If
'End Select
End If
Else
ErrorAC = True
End If
If Not ErrorAC Then
ObjAC.AjustaPoliza(IDPoliza)
Retorno = IDPoliza
Else
Alert("Error al Agregar la Póliza de AC.", TipoMensaje.MsgError)
End If
' ObjAC.Dispose()
Return Retorno
End Function
Private Sub SetValues()
ViewState("TipoCambio") = 1
If UsuarioActual.Empresa.MostrarRetIVA Then TrRetIVA.Style.Add("display", "")
If UsuarioActual.Empresa.MostrarRetISR Then TrRetISR.Style.Add("display", "")
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then ' agregar en el modal de PS. que forme el código del producto
TxtPS.Enabled = False
DivDdlTipo.Visible = True
DivTxtModelo.Visible = True
DivTxtAdicional.Visible = True
DdlTipo.Attributes.Add("onChange", "CreaDescripcionPS();")
DdlMarcaPSDes.Attributes.Add("onChange", "CreaDescripcionPS();")
TxtModelo.Attributes.Add("onKeyUp ", "CreaDescripcionPS();")
TxtAdicional.Attributes.Add("onKeyUp ", "CreaDescripcionPS();")
CargaClasificacionesDetalles()
ClasificacionModal()
End If
If Not UsuarioActual.CveEmpresa.Contiene(1, 119) Then 'PAGO CON TERMINAL PARA JAM
RBLPago.Items.RemoveAt(2)
End If
End Sub
Private Sub SetPermisos()
If CveVenta < 1 Then
'Puede cotizar
If Not UsuarioActual.TienePermisoProceso(59) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Cot"))
End If
'Puede Hacer NC
If Not UsuarioActual.TienePermisoProceso(175) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs"))
End If
'Puede Hacer Devolución
If Not UsuarioActual.TienePermisoProceso(264) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev"))
End If
'Puede facturar
If Not UsuarioActual.TienePermisoProceso(60) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ing"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Ant"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Egs"))
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Dev"))
End If
'Puede remisionar
If Not UsuarioActual.TienePermisoProceso(199) Then
DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem"))
LnkFacturarRemision.Visible = False
LnkRemisiones.Visible = False
End If
'[IPP]: FALTA CONFIGURAR Y DAR PERMISO A TODOS LOS QUE TENGAN ACCESO A VENTAS
''Puede remisionar
'If Not UsuarioActual.TienePermisoProceso(199) Then
' DdlTipoComprobante.Items.Remove(DdlTipoComprobante.Items.FindByValue("Rem"))
'End If
''MODO SOLO LECTURA
'If DdlTipoComprobante.Items.Count = 0 Then
' DdlTipoComprobante.Items.Insert(0, New ListItem("Solo lectura", "-1"))
' TrBotones.Visible = False
'End If
ConfiguraTipoDocto()
End If
End Sub
Private Sub CalculaTotalesVenta(Optional RecalculaImpuestosLocales As Boolean = True)
Dim TotalSubTotal As Decimal = TmpDT.SUM("TotalImporte").ToDecimal
Dim TotalDescuentos As Decimal = TmpDT.SUM("Descuento").ToDecimal
Dim TotalAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal
Dim TotalIVA As Decimal = TmpDT.SUM("ImporteIVA").ToDecimal
Dim TotalIEPS As Decimal = TmpDT.SUM("ImporteIEPS").ToDecimal
Dim TotalRetIVA As Decimal = TmpDT.SUM("ImporteRetIVA").ToDecimal
Dim TotalRetISR As Decimal = TmpDT.SUM("ImporteRetISR").ToDecimal
Dim Total As Decimal = 0
Dim TotalImpuestosLocales As Decimal = 0
If TotalAmortizacion > 0 AndAlso TotalSubTotal = TotalAmortizacion Then ' si se amortizó completa la factura, debe de limpiar los impuestos
If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("3") Then
For Each dr As DataRow In TmpDT.Rows
dr("ImporteIVA") = 0 : dr("ImporteIEPS") = 0 : dr("ImporteRetIVA") = 0 : dr("ImporteRetISR") = 0 : dr("PorcentajeIVA") = 0 : dr("IVA") = 0
Next
If TmpDTImpuestos IsNot Nothing Then
For Each dr2 As DataRow In TmpDTImpuestos.Rows
dr2("Importe") = 0
Next
TmpDTImpuestos.AcceptChanges()
End If
TmpDT.AcceptChanges()
TotalIVA = TmpDT.SUM("ImporteIVA").ToDecimal
TotalIEPS = TmpDT.SUM("ImporteIEPS").ToDecimal
TotalRetIVA = TmpDT.SUM("ImporteRetIVA").ToDecimal
TotalRetISR = TmpDT.SUM("ImporteRetISR").ToDecimal
TotalImpuestosLocales = TmpDTImpuestos.SUM("Importe").ToDecimal
End If
End If
If RecalculaImpuestosLocales AndAlso TmpDTImpuestos IsNot Nothing AndAlso TmpDTImpuestos.Rows.Count > 0 Then
If TotalSubTotal <> TotalAmortizacion Then
For Each drt As DataRow In TmpDTImpuestos.Rows
drt("Importe") = drt("Porcentaje").ToString.ToDecimal * TotalSubTotal / 100
Next
End If
GvImpuestosLocales2.DataSource = TmpDTImpuestos
GvImpuestosLocales2.DataBind()
End If
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal > 0 Then
If gvr.DataKey("TipoImpuesto") = "5" Then ' traslado de imp local
TotalImpuestosLocales -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal
Else
TotalImpuestosLocales += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal
End If
End If
End If
Next
'If TotalDescuentos > 0 Then GvPS.Columns(ColumnaDescuento).Visible = True : thEncDesc1.Visible = True : thEncDesc2.Visible = True Else GvPS.Columns(ColumnaDescuento).Visible = False : thEncDesc1.Visible = False : thEncDesc2.Visible = False
If TotalIEPS > 0 Then TrIEPS.Visible = True : GvPS.Columns(ColumnaIEPS).Visible = True : thEncIEPS1.Visible = True : thEncIEPS2.Visible = True Else TrIEPS.Visible = False : GvPS.Columns(ColumnaIEPS).Visible = False : thEncIEPS1.Visible = False : thEncIEPS2.Visible = False
If TotalRetIVA > 0 Then GvPS.Columns(ColumnaRetIVA).Visible = True Else GvPS.Columns(ColumnaRetIVA).Visible = False
If TotalRetISR > 0 Then GvPS.Columns(ColumnaRetISR).Visible = True Else GvPS.Columns(ColumnaRetISR).Visible = False
If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero.Contiene(2, 1) Then
TotalAmortizacion = 0
End If
Total = (TotalSubTotal - TotalDescuentos - TotalAmortizacion + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales)
LblSubTotal1.Text = TotalSubTotal.FormatoNumero(2)
TxtSubTotal.Text = TotalSubTotal.FormatoNumero(2)
LblDescuentos.Text = TotalDescuentos.FormatoNumero
TxtSubTotal2.Text = (TotalSubTotal - TotalDescuentos - TotalAmortizacion).FormatoNumero(2)
TxtRetIVA.Text = TotalRetIVA.FormatoNumero(2)
TxtRetISR.Text = TotalRetISR.FormatoNumero(2)
TxtIVA.Text = TotalIVA.FormatoNumero
TxtIEPS.Text = TotalIEPS.FormatoNumero
TxtTotal.Text = Total.FormatoNumero
LblAmort.Text = TxtSubTotal.Text
If CveVenta <= 0 OrElse (CveDevolucion > 0 And NuevaFactura = 1) Then
HdnVentaSaldo.Value = Total.ToString
Else
HdnVentaSaldo.Value = SaldoVenta.ToString
End If
HdnIVAOriginal.Value = TxtIVA.Text
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
CVImporteContado.ValueToCompare = Total.ToString
If MensajeCveSAT IsNot Nothing AndAlso MensajeCveSAT.ToString.Length > 0 Then
Alert($"Los siguientes conceptos hace falta especificar clave SAT <br/><br/> {MensajeCveSAT.ToString}", TipoMensaje.MsgAdvertencia)
MensajeCveSAT.Clear()
End If
Dim view As DataView = New DataView(TmpDT)
view.Sort = "Consec"
GvPS.DataSource = view
GvPS.DataBind()
'RECARGA GV INVENTARIO
If Not CveVenta > 0 Then
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
CargaGVInv(DtInv)
End If
UpContado.Update()
UpPS.Update()
RegistraScript("BorraDescuentos();", "BorraDescuentos")
End Sub
Private Function ValidaAdendaFEMSA() As Boolean
Dim Retorno As Boolean = False
If Not AplicaFEMSA Then
Retorno = True
Else
If TxtFEMSA_Version.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_Version.Text.Trim) Then
Retorno = False
Alert("La versión de la Adenda es requerida y debe ser numérica. Por favor corrija.", TipoMensaje.MsgAdvertencia)
ElseIf TxtFEMSA_NumSociedad.Text.Trim.Length = 0 Then
Retorno = False
Alert("El número de Sociedad para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia)
ElseIf TxtFEMSA_NumProveedor.Text.Trim.Length = 0 Then
Retorno = False
Alert("El número de Proveedor para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia)
ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumPedido.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumPedido.Text.Trim)) Then
Retorno = False
Alert("El número de Pedido para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia)
ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso (TxtFEMSA_NumEntrada.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtFEMSA_NumEntrada.Text.Trim)) Then
Retorno = False
Alert("El número de Entrada para la Adenda es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia)
ElseIf DdlTipoComprobante.SelectedValue = "Ing" AndAlso TxtFEMSA_NumRemision.Text.Trim.Length = 0 Then
Retorno = False
Alert("El número de Remisión para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia)
ElseIf TxtFEMSA_Mail.Text.Trim.Length = 0 Then
Retorno = False
Alert("El Mail para la Adenda es requerido. Por favor capture uno.", TipoMensaje.MsgAdvertencia)
Else
Retorno = True
End If
End If
Return Retorno
End Function
Private Function ValidaComplementoDetallista() As Boolean
Dim Retorno As Boolean = False
If Not AplicaDetallista Then
Retorno = True
Else
If TxtDet_OrdenCompra.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_OrdenCompra.Text.Trim) Then
Retorno = False
Alert("El campo Orden de Compra es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia, "")
ElseIf TxtDet_FechaOrdenCompra.Text.Trim.Length = 0 OrElse Not IsDate(TxtDet_FechaOrdenCompra.Text.Trim) Then
Retorno = False
Alert("El campo Fecha de Orden de Compra es requerido y debe de contar con un formato válido de fecha. Por favor corrija.", TipoMensaje.MsgAdvertencia)
ElseIf TxtDet_GLNComprador.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNComprador.Text.Trim) Then
Retorno = False
Alert("El campo GLN-Comprador es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia)
ElseIf TxtDet_Departamento.Text.Trim.Length = 0 Then
Retorno = False
Alert("El campo Departamento es requerido. Por favor ingrese uno.", TipoMensaje.MsgAdvertencia)
ElseIf TxtDet_GLNVendedor.Text.Trim.Length = 0 OrElse Not IsNumeric(TxtDet_GLNVendedor.Text.Trim) Then
Retorno = False
Alert("El campo GLN-Vendedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia)
ElseIf TxtDet_NumProv.Text.Trim.Length = 0 Then
Retorno = False
Alert("El campo Número de Proveedor es requerido y debe ser numérico. Por favor corrija.", TipoMensaje.MsgAdvertencia)
Else
Retorno = True
End If
End If
Return Retorno
End Function
Private Function ValidaComplementoFord() As Boolean
Dim Retorno As Boolean = False
If Not AplicaFord Then
Retorno = True
Else
If TxtFordGSDB.Text.Trim.Length = 0 Then
Retorno = False
Alert("El campo GSDB es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia)
Else
If LstFordASN.Items.Count = 0 Then
Retorno = True
'Alert("El campo ASN es requerido. Por favor corrija.", TipoMensaje.MsgAdvertencia)
Else
Retorno = True
End If
End If
End If
Return Retorno
End Function
Private Sub VinculaCotizacionVenta()
Dim ObjVentas As New ClsVentas()
ObjVentas.UpdateVentaCotizacion(CveVenta, Request("CveVenta").ToEntero)
ObjVentas.Dispose()
End Sub
Private Sub GeneraAddenda7Eleven(Archivo As String)
Dim cfdi As String = ""
Dim SB As New StringBuilder
Try
Using sr As New StreamReader(Archivo)
cfdi = sr.ReadToEnd()
End Using
Catch e As Exception
Alert("The file could not be read:", TipoMensaje.MsgError)
End Try
cfdi = cfdi.Replace("</cfdi:Comprobante>", "")
SB.Append(cfdi)
SB.Append("<cfdi:Addenda xmlns:xsi="" http://www.w3.org/2001/XMLSchema-instance"" xmlns:cfdi=""https://edixcfisecure.ekomercio.com/esquemas"" schemaLocation=""https://edixcfisecure.ekomercio.com/esquemas https:/edixcfdisecure.ekomercio.com/esquemas/7Eleven.xsd"">")
SB.AppendFormat("<cfdi:Proveedor Clave="" {0}""/>", Txt7ElevenNumProveedor.Text.Trim)
SB.AppendFormat("<cfdi:Recepciones><cfdi:Recepcion folio="" {0}"" tienda=""{1}"" fecha=""{2}""><cfdi:Productos>", Txt7ElevenFolio.Text.Trim, Txt7ElevenTienda.Text.Trim, Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-MM-dd"))
For Each Row As DataRow In TmpDT.Rows
SB.AppendFormat("<cfdi:Producto codigo="" {0}"" descripcion=""{1}"" cantidad=""{2}"" precio=""{3}"" />", Row("Codigo"), Row("PS"), Row("Cantidad").ToString.ToDouble.FormatoNumero(), Row("PU").ToString.ToDouble.FormatoNumero())
Next
SB.Append("</cfdi:Productos></cfdi:Recepcion></cfdi:Recepciones></cfdi:Addenda></cfdi:Comprobante>")
Using outfile As New StreamWriter(Archivo)
outfile.Write(SB.ToString())
End Using
'Exit Sub
'Dim MyXmlDocument As New XmlDocument()
'MyXmlDocument.Load("C:/Temp/aaa.xml")
'Dim nsmgr = New XmlNamespaceManager(MyXmlDocument.NameTable)
'nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3")
'Dim ParentElement As XmlElement = MyXmlDocument.CreateElement("cfdi:Addenda", "https://edixcfisecure.ekomercio.com/esquemas")
'ParentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
'ParentElement.SetAttribute("xsi:schemaLocation", "https://edixcfisecure.ekomercio.com/esquemas https:/edixcfdisecure.ekomercio.com/esquemas/7Eleven.xsd")
'Dim Prov As XmlElement = MyXmlDocument.CreateElement("cfdi:Proveedor", "")
'Prov.SetAttribute("Clave", "3125")
'Dim ns As String = "cfdi" 'MyXmlDocument.DocumentElement.GetNamespaceOfPrefix("cfdi")
'Dim Recepciones As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepciones")
'Recepciones.Prefix = "cfdi"
'Dim Recepcion As XmlElement = MyXmlDocument.CreateElement("cfdi:Recepcion")
'Recepcion.SetAttribute("folio", Txt7ElevenFolio.Text.Trim)
'Recepcion.SetAttribute("tienda", Txt7ElevenTienda.Text.Trim)
'Recepcion.SetAttribute("fecha", Txt7ElevenFecha.Text.Trim.ToDate.ToString("yyyy-dd-MM"))
'Dim Productos As XmlElement = MyXmlDocument.CreateElement("cfdi:Productos")
''dentro de un ciclo
'Dim Producto As XmlElement = MyXmlDocument.CreateElement("cfdi:Producto")
'Producto.SetAttribute("codigo", "cod1")
'Producto.SetAttribute("descripcion", "prod1")
'Producto.SetAttribute("cantidad", "99")
'Producto.SetAttribute("precio", "2000")
'Productos.AppendChild(Producto)
''fin de ciclo
'Recepcion.AppendChild(Productos)
'Recepciones.AppendChild(Recepcion)
'ParentElement.AppendChild(Prov)
'ParentElement.AppendChild(Recepciones)
'MyXmlDocument.DocumentElement.AppendChild(ParentElement)
'MyXmlDocument.Save("C:/Temp/aa.xml")
End Sub
Protected Sub DdlFuenteRecaudacion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFuenteRecaudacion.SelectedIndexChanged
For Each dr As DataRow In TmpDT.Rows
dr("CvePresupuestoIngreso") = DdlFuenteRecaudacion.SelectedValue
Next
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
End Sub
Protected Sub DdlFR_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim DdlFR_Gv As DropDownList = CType(sender, DropDownList)
Dim index As Integer = CType(DdlFR_Gv.NamingContainer, GridViewRow).FCLiteral("LtlConsecutivo").Text.ToString.ToEntero
If UsuarioActual.Empresa.UsaAC Then
TmpDT(index - 1)("CvePresupuestoIngreso") = DdlFR_Gv.SelectedValue
End If
TmpDT.AcceptChanges()
End Sub
Protected Sub LnkASN_Click(sender As Object, e As EventArgs) Handles LnkASN.Click
If TxtFordASN.Text.Trim.Length > 20 Then Alert("Maximo 20 Caracteres", TipoMensaje.MsgAdvertencia) : Exit Sub
LstFordASN.Items.Add(New ListItem(TxtFordASN.Text.Trim))
TxtFordASN.Text = ""
TxtFordASN.Focus()
End Sub
Protected Sub LnkFordQuitar_Click(sender As Object, e As EventArgs) Handles LnkFordQuitar.Click
LstFordASN.Items.RemoveAt(LstFordASN.SelectedIndex)
End Sub
Private Sub LnkImprimir_Click(sender As Object, e As EventArgs) Handles LnkImprimir.Click
GeneraPDFCot(TxtFecha.Text.Trim.ToDate, Nothing, VentaFolio, False, False)
End Sub
Protected Sub TxtCodigo_TextChanged(sender As Object, e As System.EventArgs) Handles TxtCodigo.TextChanged
Dim ObjClientes As New ClsClientes()
Dim Nombre As String = "-1"
Dim Codigo As String = "-1"
Dim NombreCorto As String = "-1"
Dim RFC As String = "-1"
Dim Telefono As String = "-1"
Dim Mail As String = "-1"
If TxtCodigo.Text.Trim <> String.Empty Then Codigo = TxtCodigo.Text.Trim
If Codigo <> "-1" Then
If ObjClientes.GetClientes(-1, Nombre, Codigo, NombreCorto, RFC, Telefono, Mail, -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then
If ObjClientes.DtResultados.Rows.Count > 0 Then
If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not ObjClientes.CveCliente.Contiene(10450, 10460, 10458) Then
TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False
UpFacturar.Update()
Exit Sub
ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not ObjClientes.CveCliente.Contiene(27448) Then
TrEmitir.Visible = False : BtnCrearApartirDe.Enabled = False : LbAgregar.Enabled = False : LnkAgregarPyME.Enabled = False : BtnBuscarCliente.Enabled = False : BtnEmitirImprimir.Visible = False : TrVistaPrevia.Visible = False
UpFacturar.Update()
Exit Sub
Else
HdnCveCliente.Value = ObjClientes.CveCliente.ToString
End If
BtnBuscarCliente_Click(sender, e)
Else
Alert("No se encontró el cliente con el código: " & TxtCodigo.Text.Trim & ".", Extensiones.TipoMensaje.MsgAdvertencia)
TxtCodigo.Text = ""
LblCliente.Text = "Cliente"
LblDireccion.Text = "Dirección"
LblColonia.Text = "Colonia"
LblCiudad.Text = "Ciudad"
LblEstado.Text = "Estado"
LblCP.Text = "00000"
LblRFC.Text = "AAA010101AAA"
LblTelefono.Text = "9999999999"
trsucursalciente.Visible = False
End If
End If
ObjClientes.Dispose()
End If
End Sub
Protected Sub TxtFolio_TextChanged(sender As Object, e As System.EventArgs) Handles TxtFolio.TextChanged
ViewState("EstablecioFolio") = True
End Sub
Private Sub ConfiguraTipoDocto()
'Esconde Todo
TdOrdenPago.Visible = False
Tr33.Visible = False
'si tiene la funcionalidad que se active independiente del tipo de documento RMF 15-10-2017
Tr33.Visible = True
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then
BtnEmitirImprimir.Text = "Emitir e Imprimir"
'TdReferencia.Style.Add("display", "none")
ElseIf DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then
BtnEmitirImprimir.Text = "Emitir e Imprimir"
'TdReferencia.Style.Remove("display")
ElseIf DdlTipoComprobante.SelectedValue = "Rem" Then
BtnEmitirImprimir.Text = "Registrar"
'TdReferencia.Style.Add("display", "none")
ElseIf DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC", "PA", "Pd2") Then
BtnEmitirImprimir.Text = "Registrar"
'TdReferencia.Style.Add("display", "none")
ElseIf DdlTipoComprobante.SelectedValue = "Cot" Then
BtnEmitirImprimir.Text = "Cotizar"
'TdReferencia.Style.Add("display", "none")
'FACTURACION 3.3
Tr33.Visible = True
ElseIf DdlTipoComprobante.SelectedValue = "Com" Then
BtnEmitirImprimir.Text = "Registrar"
'TdReferencia.Style.Add("display", "none")
ElseIf DdlTipoComprobante.SelectedValue.ToString = "OP" Then
BtnEmitirImprimir.Text = "Registrar"
TdOrdenPago.Visible = True
End If
UpFacturar.Update()
End Sub
Private Sub EliminaPoliza()
Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa)
ObjAC.IniciaTransacSQL()
Dim ObjConta As New ClsContabilidad
ObjConta.IniciaTransacSQL()
Dim ErrorMovimiento = False
'Elimina la poliza
If (UsuarioActual.Empresa.UsaAC Or UsuarioActual.Empresa.UsaContabilidad) AndAlso IdPoliza > 0 Then
If Not ObjAC.RemovePoliza(IdPoliza) Then
ErrorMovimiento = True
End If
End If
'Desasocia la poliza
If Not ErrorMovimiento Then
If Not ObjConta.DesasociarPoliza(IdPoliza, UsuarioActual.CveEmpresa) Then
ErrorMovimiento = True
End If
End If
If Not ErrorMovimiento Then
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 Sub
Protected Sub DdlPS_SelectedIndexChanged1(sender As Object, e As EventArgs)
Dim Ddl As DropDownList = CType(sender, DropDownList)
Dim gvr As GridViewRow = CType(Ddl.BindingContainer, GridViewRow)
gvr.FCDropDownList("DdlUnidadMedida").DataSource = GlobalDTProductosServiciosEquivalencias(Ddl.SelectedValue.ToEntero, -1)
gvr.FCDropDownList("DdlUnidadMedida").DataBind()
End Sub
Private Function TraspasoAlmacen(ByRef ObjInventario As ClsInventarios, CveRemision As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer) As Boolean
Dim OcurrioError As Boolean = False
Try
Dim DtMovimientos As DataTable
Dim DtMovimientosDetalles As DataTable
DtRemConceptosSurtidos = Nothing
'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 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
DtMovimientosDetalles = resultados.CopyToDataTable
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}")
DtMovimientosDetalles = New DataTable
End Try
Else
DtMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0")
End If
If DtMovimientos.Rows.Count > 0 Then
Dim GeneroMovimientoAlmacen As Boolean = False
For Each dr As DataRow In DtMovimientos.Rows
'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
If RemisionesLista.Count > 0 Then
MovDetalle = CuadrarFacturaMovimientos(DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")} AND TieneSalidaxFactura IS NULL"))
Else
MovDetalle = DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}")
End If
If ErrorList.Count = 0 AndAlso MovDetalle.Rows.Count > 0 Then
Dim CveMovimientoSalidaPorTraspaso As Integer = -1
'Le damos salida de apartado por traspaso
CveMovimientoSalidaPorTraspaso = GenerarMovimientoAlmacen(ObjInventario, MovDetalle, CveAlmacenSalida, 8, CveMoneda, CveRemision)
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) > 0
If Not GeneroMovimientoAlmacen Then
OcurrioError = True
Exit For
End If
End If
'Le damos salida normal
If ConSalida AndAlso Not OcurrioError Then
GeneroMovimientoAlmacen = GenerarMovimientoAlmacen(ObjInventario, MovDetalle, CveAlmacenEntrada, 3, CveMoneda, ObjFactura.CveVenta, MovimientoPrePoliza:=True, ObjConta:=ObjConta) > 0
If Not GeneroMovimientoAlmacen Then
OcurrioError = True
Exit For
End If
End If
Else
OcurrioError = True
End If
MovDetalle.Dispose()
End If
End If
ElseIf ObjInventario.GetMovimientos(dr("CveMovimiento").ToString.ToEntero, 3, -1, UsuarioActual.CveEmpresa) Then
'Esquema viejo, evitamos que aparezca por surtir
If Not ObjInventario.ActualizarEsDevolucionVenta(ObjFactura.CveVenta, 2) Then
OcurrioError = True
Exit For
End If
End If
Next
OcurrioError = Not GeneroMovimientoAlmacen
End If
End If
Else
OcurrioError = True
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(MovDetalle As DataTable) As DataTable
Dim MovDTCuadrados As New DataTable
MovDTCuadrados = MovDetalle.Clone
MovDTCuadrados.Clear()
'Llenamos el DT solo si es primera llamada
If DtRemConceptosSurtidos Is Nothing Then
DtRemConceptosSurtidos = New DataTable
DtRemConceptosSurtidos.Columns.Add("CveVentaDetalle", GetType(Integer))
DtRemConceptosSurtidos.Columns.Add("Cantidad", GetType(Decimal))
DtRemConceptosSurtidos.Columns.Add("Surtido", GetType(Decimal))
For Each dr As DataRow In DtRemisionesTmpDT.Rows
Dim dtr As DataRow = DtRemConceptosSurtidos.NewRow
dtr("CveVentaDetalle") = dr("CveVentaDetalle")
dtr("Cantidad") = dr("Cantidad")
dtr("Surtido") = 0
DtRemConceptosSurtidos.Rows.Add(dtr)
Next
End If
For Each dr As DataRow In MovDetalle.Rows
Dim rowSurtidos As DataRow = DtRemConceptosSurtidos.FiltroPrimero($"CveVentaDetalle={dr("CveVentaDetalle")}")
Dim rowSurtidosP As DataRow = DtRemConceptosSurtidos.Select($"CveVentaDetalle={dr("CveVentaDetalle")}").FirstOrDefault
Dim Indice As Integer = DtRemConceptosSurtidos.Rows.IndexOf(rowSurtidosP)
'Si no se ha terminado de surtir agregamos el movimiento
If Indice >= 0 Then
' rowSurtidos("Surtido").ToString.ToDouble < rowSurtidos("Cantidad").ToString.ToDouble AndAlso (dr("CantidadDisponible").ToString.ToDouble - rowSurtidos("Surtido").ToString.ToDouble > 0 Or dr("SerieLote").ToString <> "")
If rowSurtidos("Surtido").ToString.ToDecimal < rowSurtidos("Cantidad").ToString.ToDecimal Then
Dim CantidadSurtida As Double = If(dr("CantidadDisponible").ToString.ToDecimal < rowSurtidos("Cantidad").ToString.ToDouble, dr("CantidadDisponible").ToString.ToDecimal, rowSurtidos("Cantidad").ToString.ToDecimal)
MovDTCuadrados.ImportRow(dr)
MovDTCuadrados(MovDTCuadrados.Rows.Count - 1)("Cantidad") = CantidadSurtida
DtRemConceptosSurtidos(Indice)("Surtido") = rowSurtidos("Surtido").ToString.ToDecimal + CantidadSurtida
End If
Else
ErrorList.Add("Ocurrió un error al traspasar el inventario de la remisión")
Exit For
End If
Next
Return MovDTCuadrados
End Function
Private Function SalidaEntradaAlmacen(ByRef ObjInventario As ClsInventarios, CveRemision As Integer, ByRef ObjConta As ClsContabilidad) As Boolean
Dim OcurrioError As Boolean = False
Dim DtMovimientos As DataTable
Dim DtMovimientosDetalles As DataTable
'Obtenemos los movimientos detalle
If ObjInventario.GetInv_Mov(CveRemision, UsuarioActual.CveEmpresa) Then
If ObjInventario.DtResultados.Rows.Count > 0 Then
DtMovimientos = ObjInventario.DtResultados.FiltraParametros("", DistinctColumns:={"CveMovimiento"})
DtMovimientosDetalles = ObjInventario.DtResultados.FiltraParametros("CvePS > 0")
For Each dr As DataRow In DtMovimientos.Rows
'Obtenemos los Movimientos de salida
If ObjInventario.GetMovimientos(dr("CveMovimiento").ToString.ToEntero, 3, -1, UsuarioActual.CveEmpresa) Then
Dim CveAlmacenSalida As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero
Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero
'Le damos entrada
If Not GenerarMovimientoAlmacen(ObjInventario, DtMovimientosDetalles.FiltraParametros($"CveMovimiento = {dr("CveMovimiento")}"), CveAlmacenSalida, 2, CveMoneda, CveRemision) > 0 Then
OcurrioError = True
End If
End If
Next
End If
End If
Return Not OcurrioError
End Function
Private Function GenerarMovimientoAlmacen(ByRef ObjInventario As ClsInventarios, DtMovDetalle As DataTable, CveAlmacen As Integer, ConceptoEntrada As Integer, CveMoneda As Integer, CveVenta As Integer, Optional MovimientoPrePoliza As Boolean = False, Optional ByRef ObjConta As ClsContabilidad = Nothing, Optional CveMovimientoRelacionado As Integer = -1) As Integer
Dim OcurrioError As Boolean = False
Dim ContadorMovtosDetalles = 0
'Creamos el movimiento
Dim CveMovimientoInventario As Integer = ObjInventario.AddMovimiento(CveAlmacen, ConceptoEntrada, CveMoneda, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, CveMovimientoRelacionado:=CveMovimientoRelacionado)
If CveMovimientoInventario > 0 Then
'Agregamos los detalles
For Each MovDet As DataRow In DtMovDetalle.Rows
Dim Cantidad = 0.0
Dim CantidadRemision = DtRemisionesTmpDT.FiltroPrimeroValor("Cantidad", $"CveVentaDetalleRemision={MovDet("CveVentaDetalle").ToString}").ToDouble
Dim CantidadInventario = MovDet("Cantidad").ToString.ToDecimal
If RemisionesLista.Count > 0 AndAlso ChkRemProductos.Checked AndAlso CantidadInventario >= CantidadRemision Then
Cantidad = CantidadRemision
Else
Cantidad = CantidadInventario
End If
Dim CveUnidad As Integer = MovDet("CveUM").ToString.ToEntero
Dim PU As Decimal = MovDet("PU").ToString.ToDecimal
Dim CveProducto As Integer = MovDet("CvePS").ToString.ToEntero
Dim SerieLote As String = MovDet("SerieLote").ToString
Dim Consec As Integer = DtRemisionesTmpDT.FiltroPrimeroValor("Consec", $"CveVentaDetalle = {MovDet("CveVentaDetalle").ToString}").ToEntero
'COMIENZA: VENTADETALLE
'CUANDO SEA SALIDA VA POR LA VENTA DETALLE DE LA FACTURA DE LA REMISION - OJO!! SOLO FUNCIONA HASTA ORITA QUE SE HACE SALIDA SOLO CUANDO SE FACTURA LA REMISION
Dim CveVentaDetalle = If(ConceptoEntrada = 3, TmpDT.FiltroPrimeroValor("CveVentaDetalle", $"Consec={Consec}").ToEntero, MovDet("CveVentaDetalle").ToString.ToEntero)
'CUANDO LA VENTADETALLE NO TENGA VALOR DEBE MARCAR ERROR, NUEVA RESTRICCION DE ALMACEN
If CveVentaDetalle < 0 Then
OcurrioError = True
Exit For
End If
'TERMINA: VENTADETALLE
If Cantidad < 0 Then
Alert("Ocurrió un Error al generar los movimientos de almacén. Por favor comuniquese con atención SIG.", TipoMensaje.MsgError)
OcurrioError = True
Exit For
End If
If ObjInventario.AddMovimientoDetalle(CveMovimientoInventario, Cantidad, CveUnidad, CveProducto, PU, -1, SerieLote:=SerieLote, CveVentaDetalle:=CveVentaDetalle) Then
ContadorMovtosDetalles += 1
Else
OcurrioError = True
Exit For
End If
Next
'Agregamos las PrePolizas
If Not OcurrioError Then
If MovimientoPrePoliza AndAlso CveMovimientoInventario > 0 Then
If ObjInventario.GetMovimientosDetalle(CveMovimientoInventario, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then
Dim DtCostos = ObjInventario.DtResultados.Copy
Dim DtCostosDistinct As DataTable = ObjInventario.DtResultados.FiltraParametros("", "", {"CveClasificacion"})
Dim IdCtaContable As Integer = 0
Dim CveCuenta As Integer = 0
Dim ValorInventario As Decimal
Dim TotalCostoAcumulado As Decimal = 0D
Dim Cont As Integer = 1
Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL
For Each RowInv As DataRow In DtCostosDistinct.Rows
ValorInventario = DtCostos.SUMD("Total", String.Format("CveClasificacion = {0}", RowInv("CveClasificacion"))).RoundSQL
IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero
CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaGastoSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero
TotalCostoAcumulado += ValorInventario
'cuando es el último movimiento y hay diferencias en los importes
If Cont = DtCostosDistinct.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then
ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado)
End If
Try
'If ValorInventario <> 0 Then
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, False, ValorInventario, ObjFactura.SerieFolio, 69, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=ValorInventario, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then
OcurrioError = True
Exit For
End If
'End If
Catch ex As Exception
OcurrioError = True
End Try
Cont += 1
Next
If Not OcurrioError Then
IdCtaContable = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", String.Format("CveAlmacen = {0}", CveAlmacen)).ToEntero
If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, True, TotalCosto, ObjFactura.SerieFolio, 68, ObjFactura.SerieFolio, ObjFactura.Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=ObjFactura.CveCliente, CveMovimientoAlmacen:=CveMovimientoInventario, ImporteMX:=TotalCosto, CveCuenta:=CveCuenta, CveSubProyecto:=ObjFactura.CveSubProyecto) Then
OcurrioError = True
End If
End If
Else
OcurrioError = True
End If
End If
End If
'VALIDA QUE SE HALLAN AGREGADO DETALLES AL MOVIMIENTO
If ContadorMovtosDetalles = 0 Then
OcurrioError = True
End If
Else
OcurrioError = True
End If
If OcurrioError Then
Return -1
Else
Return CveMovimientoInventario
End If
'Return Not OcurrioError
End Function
Private Function SalidaAlmacenMateriales(ByRef ObjInventario As ClsInventarios, CveOS As Integer, ByRef ObjConta As ClsContabilidad, ConSalida As Boolean, ConceptoMovimiento As Integer) As Boolean
Dim TieneError As Boolean = False
Dim CveMovimientoSalida = 0
Dim CveMovimientoEntrada = 0
Dim CveMovimientoSalida2 = 0
Dim CveMovimientoEntrada2 = 0
Dim CveMovimientoSalida3 = 0
Dim CveMovimientoEntrada3 = 0
Dim AlmacenEntrada = -1
Dim FolioSalida = 0
Dim FolioEntrada = 0
Dim TextoError = ""
Dim TextoExistencia As StringBuilder = New StringBuilder
'Obtenemos los movimientos detalle
If ObjInventario.GetMovimientosOS(9, CveOS, UsuarioActual.CveEmpresa) Then
If ObjInventario.DtResultados.Rows.Count > 0 Then
Dim CveMovimiento As Integer = ObjInventario.DtResultados(0)("CveMovimiento").ToString.ToEntero
Dim CveAlmacenOrigen As Integer = ObjInventario.DtResultados(0)("CveAlmacen").ToString.ToEntero
Dim CveAlmacenDestino As Integer = ObjInventario.DtResultados(0)("AlmacenDestino2").ToString.ToEntero
Dim CveMoneda As Integer = ObjInventario.DtResultados(0)("CveMoneda").ToString.ToEntero
Dim CveTipoAlmacen As Integer = ObjInventario.DtResultados(0)("CveTipoAlmacen").ToString.ToEntero
'AGREGAMOS LA ENTRADA Movto 1
If Not TieneError Then
AlmacenEntrada = CveAlmacenOrigen
CveMovimientoEntrada = ObjInventario.AddMovimiento(AlmacenEntrada, 8, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida, CveOS:=CveOS)
FolioEntrada = ObjInventario.Folio
If CveMovimientoEntrada <= 0 Then
TextoError = "No se pudo generar el movimiento de entrada correctamente"
TieneError = True
Else
If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then
For Each Dr As DataRow In ObjInventario.DtResultados.Rows
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then
TieneError = True
TextoError = "Ocurrió un Error al guardar los movimientos de entrada"
Exit For
End If
Next
End If
End If
End If
'AGREGAMOS LA ENTRADA Movto 2
If Not TieneError Then
AlmacenEntrada = CveAlmacenDestino
CveMovimientoEntrada2 = ObjInventario.AddMovimiento(AlmacenEntrada, 9, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida2, CveOS:=CveOS)
FolioEntrada = ObjInventario.Folio
If CveMovimientoEntrada2 <= 0 Then
TextoError = "No se pudo generar el movimiento de entrada correctamente"
TieneError = True
Else
If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada, UsuarioActual.CveEmpresa) Then
For Each Dr As DataRow In ObjInventario.DtResultados.Rows
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada2, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then
TieneError = True
TextoError = "Ocurrió un Error al guardar los movimientos de entrada"
Exit For
End If
Next
End If
End If
End If
'AGREGAMOS LA ENTRADA Movto 3
If Not TieneError Then
AlmacenEntrada = CveAlmacenDestino
CveMovimientoEntrada3 = ObjInventario.AddMovimiento(AlmacenEntrada, 3, 1, TxtFecha.Text.ToDate, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, CveAlmacenDestino:=-1, CveMovimientoRelacionado:=CveMovimientoSalida3, CveOS:=CveOS)
FolioEntrada = ObjInventario.Folio
If CveMovimientoEntrada3 <= 0 Then
TextoError = "No se pudo generar el movimiento de entrada correctamente"
TieneError = True
Else
If ObjInventario.GetMovimientosDetalle(CveMovimientoEntrada2, UsuarioActual.CveEmpresa) Then
For Each Dr As DataRow In ObjInventario.DtResultados.Rows
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada3, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, -1, -1) Then
TieneError = True
TextoError = "Ocurrió un Error al guardar los movimientos de entrada"
Exit For
End If
Next
End If
End If
End If
End If
End If
Return TieneError
End Function
'Protected Sub LbVerInventario_Click(sender As Object, e As EventArgs) Handles LbVerInventario.Click
' RegistraScript(String.Format("AbrirVentana('/Inventarios/PopUpExistenciasAlmacen.aspx?CvePS={0}',800,547,'N');", DdlPS.SelectedValue))
'End Sub
#End Region
#Region " MANDA CORREO "
Private Sub MandaMails(CveVenta As Integer, EnviarFactura As Boolean, XML As String, PDF As String)
Dim ObjMail As New ClsSisMail()
Dim ObjVentas As New ClsVentas
Try
Dim Asunto As String = String.Empty
Dim Cuerpo As String = String.Empty
Dim ResultadoMail As Integer = 0
Dim TipoComprobante = ""
If DdlTipoComprobante.SelectedValue.ToString = "Ing" Then TipoComprobante = "Factura"
If DdlTipoComprobante.SelectedValue.ToString = "Egs" Then TipoComprobante = "Nota de Crédito"
If DdlTipoComprobante.SelectedValue.ToString = "Dev" Then TipoComprobante = "Nota de Devolución"
If DdlTipoComprobante.SelectedValue.ToString = "Rem" Then TipoComprobante = "Remisión"
If DdlTipoComprobante.SelectedValue.ToString = "Cot" Then TipoComprobante = "Cotización"
If DdlTipoComprobante.SelectedValue.ToString = "Ant" Then TipoComprobante = "Anticipo"
If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then
Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta
Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa)
Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim)
Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante)
Cuerpo = Cuerpo.Replace("{""Fecha""}", TxtFecha.Text)
Cuerpo = Cuerpo.Replace("{""Total""}", TxtTotal.Text)
Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", TxtFechaPago.Text)
Cuerpo = Cuerpo.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}")
End If
If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then
Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta
Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante)
Asunto = Asunto.Replace("{""Sucursal""}", DdlSubProyectoDatos.SelectedItem.Text)
Asunto = Asunto.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}")
End If
If Not EnviarFactura Then
ObjVentas.UpdateVentaMail(0, CveVenta)
End If
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
If DdlTipoComprobante.SelectedValue = "Cot" Then
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
Else
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML})
End If
Dim DisplayName As String = ""
If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM"
If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then
ResultadoMail = 1
Else
ResultadoMail = 3
End If
ObjVentas.UpdateVentaMail(ResultadoMail, CveVenta)
'CASO ESPECIAL
If CveUsuarioActual = 1446 Then ' Flora
Dim str As String = "Flora Envio: Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString
str.GuardaLog()
ElseIf CveUsuarioActual = 1513 Then ' Flora
Dim str As String = "Flora Envio (secundario): Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString
str.GuardaLog()
End If
'Next
Catch ex As Exception
OnError("Ocurrió error al mandar el Mail", ex)
ObjVentas.UpdateVentaMail(3, CveVenta)
Finally
ObjVentas.Dispose()
End Try
End Sub
#End Region
#Region " 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
End Sub
Private Sub CargaDatosEstimaciones(CveCliente As Integer)
If CveVenta > 0 Then
Exit Sub
End If
Dim Con As New ClsContratos
If Con.GetEstimacionesPorFacturar(-1, CveCliente, DdlContrato.SelectedValue.ToEntero, 0, UsuarioActual.CveEmpresa) Then
GvEst.DataSource = Con.DtResultados
If Con.DtResultados.Rows.Count > 0 Then
'BtnEstimacion.Visible = True
DdlContrato.Items.Clear()
DdlContrato.Items.Add(New ListItem("Todos", "-1"))
DdlContrato.DataSource = Con.DtResultados.FiltraParametros("CveContrato > 0", "NumeroContrato", DistinctColumns:={"CveContrato", "NumeroContrato"})
End If
End If
UPEstimaciones.Update()
Con.Dispose()
DdlContrato.DataBind()
GvEst.DataBind()
End Sub
Protected Sub GVEst_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvEst.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Cells(0).Width = Unit.Pixel(30)
e.Row.Cells(1).Width = Unit.Pixel(300) 'Seccion
e.Row.Cells(2).Width = Unit.Pixel(100) 'Cantidad
e.Row.CssClass = "Totales"
Else
If e.Row.DBCampo("CveContratoAvance").ToString.ToEntero > 0 Then
' e.Row.FCCheckBox("Chk").Visible = True
Else
If e.Row.DBCampo("CveSubFamilias").ToString.ToEntero > 0 Then
e.Row.CssClass = "SubTotales3"
Else
If e.Row.DBCampo("CveFamilias").ToString.ToEntero > 0 Then
e.Row.CssClass = "SubTotales2"
Else
e.Row.CssClass = "SubTotales"
End If
End If
End If
End If
End If
End Sub
Private Sub ObtenerFechaVencimientoCER()
Try
Dim CerFile As New FileStream(Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoCer, FileMode.Open, FileAccess.Read)
Dim Size As Integer = CerFile.Length.ToString.ToEntero()
Dim Data As Byte() = New Byte(Size - 1) {}
Size = CerFile.Read(Data, 0, Size)
CerFile.Close()
CerFile.Dispose()
Dim x509 As New X509Certificate2()
x509.Import(Data)
If x509.NotAfter <= Now() Then
TrVistaPrevia.Visible = False
TrEmitir.Visible = False
BtnEmitirImprimir.Visible = False
BtnCrearApartirDe.Enabled = False
Alert("La fecha del certificado ha expirado", TipoMensaje.MsgAdvertencia)
End If
Catch ex As Exception
Alert("No se pudo verificar la fecha del certificado", TipoMensaje.MsgError)
End Try
End Sub
#End Region
#Region "E V E N T O - B I T A C O R A"
Protected Sub GvEB_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvEB.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Cells(0).Width = Unit.Pixel(200)
e.Row.Cells(1).Width = Unit.Pixel(200)
e.Row.Cells(2).Width = Unit.Pixel(100)
e.Row.Cells(3).Width = Unit.Pixel(500)
End If
If e.Row.DBCampo("Archivo").ToString <> "" Then
e.Row.FCLinkButton("LinkArchivo").Visible = True
e.Row.FCLinkButton("LinkArchivo").CommandArgument = String.Format("OI\{0}", e.Row.DBCampo("Archivo").ToString)
ScriptManager.GetCurrent(Me).RegisterPostBackControl(e.Row.FCLinkButton("LinkArchivo")) 'Registro un evento Postbacktrigger, que recargue toda la pagina para que funcione
End If
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left
End If
End Sub
Protected Sub BtnGuardarEventoBitacora_Click(sender As Object, e As EventArgs) Handles BtnGuardarEventoBitacora.Click
Dim FileExtension As String = "-1"
Dim filesgral As List(Of Archivo) = Anexo.getfiles().Archivos
Dim Filename As String = ""
For Each fileItem As Archivo In filesgral
FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
Filename = fileItem.filename
Next
Dim ObjEventos As New ClsOIEventos()
If ObjEventos.AddEventoBitacora(TxtEventoDescripcion.Text.Trim, String.Format(".{0}", FileExtension), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then
If Filename <> "" Then
Filename.FilesMove(String.Format("OI{0}", ObjEventos.CveEvento.ToString), String.Format("Empresas\{0}\OI", UsuarioActual.CveEmpresa))
End If
End If
ObjEventos.Dispose()
CargaEventoBitacora()
UPEventoBitacora.Update()
End Sub
Private Sub CargaEventoBitacora()
If CveVenta <= 0 Then Exit Sub
Dim ObjEventoBitacora As New ClsOIEventos()
If ObjEventoBitacora.GetAgendaBitacora(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then
GvEB.DataSource = ObjEventoBitacora.DtResultados.FiltraParametros("CveTipoEvento = 6 OR CveTipoEvento = 2")
Else
GvEB.DataSource = Nothing
End If
ObjEventoBitacora.Dispose()
GvEB.DataBind()
End Sub
Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
Dim filePath As String = String.Format("{0}{1}", UsuarioActual.Empresa.Ruta, CType(sender, LinkButton).CommandArgument)
Dim Archivo As New System.IO.FileInfo(filePath)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(filePath))
HttpContext.Current.Response.AddHeader("Content-Length", Archivo.Length.ToString())
HttpContext.Current.Response.TransmitFile(filePath)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
Archivo = Nothing
End Sub
#End Region
#Region "BTN 'S"
Protected Sub LnkActualizarOrdenProduccion_Click(sender As Object, e As EventArgs)
If DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then
Dim ObjCGame As New ClsCGame
If ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero, CveVenta) Then
Alert("La orden de producción fue actualizada con exito.")
End If
ObjCGame.Dispose()
Else
Alert("Tiene que seleccionar una orden de producción.", TipoMensaje.MsgAdvertencia)
End If
End Sub
Protected Sub LnkContratoAcptar_Click(sender As Object, e As EventArgs) Handles LnkContratoAcptar.Click
Dim objcontra As New ClsContratos
objcontra.IniciaTransacSQL()
If objcontra.AddContratosAceptados(ViewState("CveVenta").ToString.ToEntero, TxtNombreContrato.Text, 13, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then '-----------------------------------------------Falata la CveContrato!!!!!!!!!!!!!!
objcontra.Commit()
Alert("La cotización fue aceptada" & objcontra.CveContrato, TipoMensaje.MsgInformacion)
Else
objcontra.RollBack()
Alert("La cotización no fue aceptada", TipoMensaje.MsgError)
End If
objcontra.Dispose()
End Sub
Private Sub BtnGarantia_Click(sender As Object, e As EventArgs) Handles LkGarantia.Click
Dim s As String = ""
'Nos vamos a la nueva factura
Dim url As String = String.Format("/RMA/Garantias.aspx?CveVenta={0}", CveVenta)
Response.Redirect(url)
End Sub
Private Sub BtnGenerarNC_Click(sender As Object, e As EventArgs) Handles LkDevolucion.Click
Dim url As String = String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=0", CveVenta)
Response.Redirect(url)
End Sub
'Private Sub LkNotaCreditoC_Click(sender As Object, e As EventArgs) Handles LkNotaCredito.Click
' Dim url As String = String.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=2", CveVenta)
' Response.Redirect(url)
'End Sub
Private Sub BtnNuevaFactura_Click(sender As Object, e As EventArgs) Handles LkRefacturacion.Click
'Nos vamos a la nueva factura
Dim script As String = ""
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then
Dim sb As New StringBuilder()
If Not String.IsNullOrEmpty(FolioFiscal) Then
sb.Append("La factura se encuentra en el siguiente estatus del SAT:<br/>")
Dim TotalT As Decimal = TxtTotal.Text.ToDecimal
Dim RFCReceptor As String = LblRFC.Text.Trim
Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True)
If Vigencia IsNot Nothing Then
If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then
Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If Vigencia.EsCancelable = "Cancelable sin aceptación" Then
script = "BtnRefacturacionConfirmarAceptacion();"
sb.AppendFormat("<b>{0}</b> <br/>", Vigencia.EsCancelable)
sb.Append("Está seguro de realizar la refacturación?.")
End If
If Vigencia.EsCancelable = "Cancelable con aceptación" OrElse String.IsNullOrEmpty(Vigencia.EsCancelable) Then
script = "BtnRefacturacionConfirmar();"
sb.AppendFormat("<b>{0}</b> <br/>", "Cancelable con aceptación")
sb.Append("Está seguro de cancelar el documento para realizar la refacturación?.")
End If
Else
sb.Append("<b>No encontrado</b> <br/>")
End If
Else
sb.Append("¿Desea realizar la refacturación?<br/>")
script = "BtnRefacturacionConfirmarAceptacion();"
End If
Alert(sb.ToString(), TipoMensaje.MsgConfirmacion, JSBtnAceptar:=script, TextoConfirmacion:="&nbsp;&nbsp;&nbsp;&nbsp;Si&nbsp;&nbsp;&nbsp;&nbsp;", TextoCancelacion:="&nbsp;&nbsp;&nbsp;&nbsp;No&nbsp;&nbsp;&nbsp;&nbsp;")
End If
End Sub
'BtnRefacturacionConfirmar
Private Sub BtnRefacturacionConfirmar_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmar.Click
CancelarDocumento(True)
End Sub
Private Sub BtnRefacturacionConfirmarAceptacion_Click(sender As Object, e As System.EventArgs) Handles BtnRefacturacionConfirmarAceptacion.Click
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:<br><br>"
'If ObjMov.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.Empresa, 2) Then
' Alert(alertaContabilizacion & ObjMov.AlertaMensaje, ModExtensiones.TipoMensaje.MsgInformacion)
'Else
' Alert(String.Format("Ocurrio un error al contabilizar {0}", ObjMov.AlertaMensaje))
'End If
'ObjMov.Dispose()
End Sub
Protected Sub BtnDescontabilizar_Click(sender As Object, e As EventArgs)
'Alert("Hola entre", TipoMensaje.MsgError)
'Exit Sub
Dim ObjConta As New ClsContabilidad
Dim Movimientos = ObjConta.GetMovimientosPoliza(IdPoliza, UsuarioActual.CveEmpresa)
'Verifica que solo exista 1 compra asociada
If Movimientos = 1 Then
EliminaPoliza()
Else
RegistraScript("ConfirmEliminarPolizaMultiple();")
End If
ObjConta.Dispose()
End Sub
Private Sub BtnMateriales_Click(sender As Object, e As EventArgs) Handles BtnMateriales.Click
Dim OS As New ClsOS
Dim DtDetalle As DataTable = Nothing
Dim DtDetalleMateriales As DataTable = Nothing
DtDetalle = TmpDT.Copy
For Each Row As DataRow In DtDetalle.Rows
If OS.GetDetalleMateriales(Row("CveOSDetalle").ToString.ToEntero, CveOS) Then
Dim Cons As Integer = TmpDT.Rows.Count + 1
For Each dr As DataRow In OS.DtResultados.FiltraParametros("SeFacturara = 1 ").Rows
Dim drt As DataRow = TmpDT.NewRow
FacturaMateriales = 1
drt("Consec") = Cons
drt("CveClasificacion") = dr("CveClasificacion")
drt("Clasificacion") = dr("Clasificacion")
drt("CvePS") = dr("CvePS")
drt("PS") = dr("PS")
drt("CodigoPS") = dr("CodigoPS")
drt("Cantidad") = dr("Cantidad")
drt("CveOSDetalle") = dr("CveOSDetalle")
drt("CveSubProyecto") = dr("CveSubProyecto")
drt("SubProyecto") = dr("SubProyecto")
TmpDT.Rows.Add(drt)
Cons = Cons + 1
Next
End If
DtDetalleMateriales = OS.DtResultados.FiltraParametros("SeFacturara = 1 ")
Next
OS.Dispose()
GvPS.DataSource = TmpDT
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvPS.DataBind()
UpPS.Update()
End Sub
Private Sub BtnPermisoEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarRemision.Click
BtnEditarRemision.Visible = True
BtnPermisoEditarRemision.Visible = False
BtnCrearApartirDe.Visible = False
TxtObsFact.Enabled = True
TxtOrdenCompra.Enabled = True
TxtPedidoContrato.Enabled = True
TxtObsAlmacen.Enabled = True
ModalidadEdicion = True
ViewState("CveClienteAnterior") = CveCliente
'SI EL DETALLE NO TIENE MOVIMIENTOS DE INVENTARIO ES VISIBLE
Dim CantidadFacturadaRemision = 0.0
For Each Gvr As GridViewRow In GvPS.Rows
Gvr.FCLinkButton("imgE").Visible = Not Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble > 0
Gvr.FCLinkButton("imgD").Visible = Not Gvr.DataKey("CantidadInventario").ToString.ToDouble > 0
CantidadFacturadaRemision += Gvr.DataKey("CantidadFacturadaRem").ToString.ToDouble
'If GvInv.Rows.Count > 0 Then
' Gvr.FCLinkButton("imgE").Enabled = False
' Gvr.FCLinkButton("imgE").ToolTip = "No se puede editar debido a que ya hay un movimiento de almacen."
'End If
Next
'ACTIVA CAMBIO DE CLIENTE - SI NO TIENE NADA FACTURADO
If Not CantidadFacturadaRemision > 0 Then
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto")
TxtCodigo.ReadOnly = False
End If
TxtCantidad.Enabled = True
DdlClasificacion.Enabled = True
DdlPS.Enabled = True
TxtObsPS.Enabled = True
DdlProyecto.Enabled = True
DdlSubProyecto.Enabled = True
TxtPrecio.Enabled = True
LbAgregar.Enabled = True
LnkAgregarPyME.Enabled = True
ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';")
LblSubTotal1.Text = TxtSubTotal.Text
LblAmort.Text = TxtSubTotal.Text
UpPS.Update()
UpCliente.Update()
UPObservaciones.Update()
End Sub
Private Sub BtnEditarRemision_Click(sender As Object, e As EventArgs) Handles BtnEditarRemision.Click
Dim OcurrioError As Boolean = False
Dim ObjVentas As New ClsVentas
Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL())
Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL())
Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL())
Dim ObjAC As ClsContPAQi = Nothing
Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero
Dim TipoCambio As Double = TxtTipoCambio.Text.ToDouble
EditoRemision = True
'Dim SubTotal, Descuento, IVA, RetIVA, RetISR, IEPS, Total As Decimal
ObjVentas.IniciaTransacSQL()
'CONVERTIR REMISION - TIPO MONEDA -DOLARES A PESOS
If DdlMoneda.SelectedValue.ToEntero <> 2 AndAlso ChkConvertirDolares.Checked Then
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, 6)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales)
Next
Dim ImpuestosLocales As Double = 0
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal).FormatoNumero
ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales)
End If
Next
TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero
LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero
LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal / TxtTipoCambioDlls.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero
TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero
TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero
TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero
TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero
TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero
TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal
Moneda = 2
End If
'CONVERTIR REMISION - TIPO MONEDA -PESO A DOLARES
If DdlMoneda.SelectedValue.ToEntero <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then
For Each Row As DataRow In TmpDT.Rows
Row("PU") = Math.Round(Row("PU").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, 6)
Row("Total") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales)
Row("TotalImporte") = Math.Round(Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal, NumeroDecimales)
Row("Descuento") = Math.Round(Row("Descuento").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteIEPS") = Math.Round(Row("ImporteIEPS").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteIVA") = Math.Round(Row("ImporteIVA").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(Row("ImporteRetIVA").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(Row("ImporteRetISR").ToString.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales)
Next
Dim ImpuestosLocales As Double = 0
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
gvr.FCTextBox("TxtImpuestoLocalPS").Text = (gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal).FormatoNumero
ImpuestosLocales += Math.Round(gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales)
End If
Next
TxtSubTotal.Text = TmpDT.SUM("Total").ToDecimal.FormatoNumero
LblDescuentos.Text = TmpDT.SUM("Descuento").ToDecimal.FormatoNumero
LblAmortizacion.Text = Math.Round(LblAmortizacion.Text.Trim.ToDecimal * TxtTipoCambio.Text.Trim.ToDecimal, NumeroDecimales).FormatoNumero
TxtIVA.Text = TmpDT.SUM("ImporteIVA").ToDecimal.FormatoNumero
TxtRetIVA.Text = TmpDT.SUM("ImporteRetIVA").ToDecimal.FormatoNumero
TxtRetISR.Text = TmpDT.SUM("ImporteRetISR").ToDecimal.FormatoNumero
TxtIEPS.Text = TmpDT.SUM("ImporteIEPS").ToDecimal.FormatoNumero
TxtTotal.Text = (TxtSubTotal.Text.ToDecimal - LblDescuentos.Text.ToDecimal - LblAmortizacion.Text.ToDecimal + TxtIVA.Text.ToDecimal + TxtIEPS.Text.ToDecimal - TxtRetIVA.Text.ToDecimal - TxtRetISR.Text.ToDecimal - ImpuestosLocales).ToDecimal.FormatoNumero
TipoCambio = 1
Moneda = 1
End If
'Actualizo los parametros de la venta
If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDecimal, LblDescuentos.Text.ToDecimal, TxtIVA.Text.ToDecimal, TxtIEPS.Text.ToDecimal, TxtTotal.Text.ToDecimal, Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim,
UsuarioActual.CveEmpresa, CveVenta, 0, 0,
Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1),
PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero, TipoDocto:="Rem", CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal) Then
OcurrioError = True
End If
'Cargo de nueva cuenta el detalle de Ventas (Conceptos)
If Not OcurrioError Then
Dim index As Integer = 0
For Each Row As DataRow In TmpDT.Rows
Dim CveVentaDetalle As Integer = Row("CveVentaDetalle").ToString.ToEntero()
If CveVentaDetalle > 0 Then
If Not ObjVentas.UpdateVentaDetalleRemision(Row("CveVentaDetalle").ToString.ToEntero, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDecimal, Row("PU").ToString.ToDecimal(), Row("ImporteIEPS").ToString.ToDecimal(), Row("Obs").ToString, UsuarioActual.CveUsuario) Then
OcurrioError = True
Exit For
End If
Else
If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero,
Row("PU").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)))), 6),
Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, IEPS:=Row("IEPS").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString,
CveVentaDetallePadre:=Row("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CvePromocionDetalle:=If(DtPromociones IsNot Nothing, DtPromociones.FiltroPrimeroValor("CvePromocionDetalle", $"CvePS={Row("CvePS").ToString}").ToEntero, -1),
ImporteRetIVA:=Row("ImporteRetIVA").ToString.ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString.ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString.ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString.ToDouble, CuentaPredial:=Row("CuentaPredial").ToString) Then
OcurrioError = True
Exit For
Else
TmpDT.Rows(index)("CveVentaDetalle") = ObjVentas.CveVentaDetalle
End If
End If
index = index + 1
Next
End If
'ELIMINA LOS DETALLES
If Not OcurrioError Then
Dim DtEliminados As New DataTable
If ObjVentas.GetVentaDetalle(CveVenta) Then
DtEliminados = ObjVentas.DtResultados.FiltraParametros("", "", {"CveVentaDetalle"})
For Each Dr1 As DataRow In DtEliminados.Rows
If TmpDT.FiltraParametros($"CveVentaDetalle = {Dr1("CveVentaDetalle")}").Rows.Count = 0 Then
If Not ObjVentas.RemoveVentasDetalle(CveVenta, Dr1("CveVentaDetalle").ToString.ToEntero) Then
OcurrioError = True
End If
End If
Next
Else
OcurrioError = True
End If
End If
'OcurrioError = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, 1, ObjBancos, ObjVentas)
'Actualizo impuestos locales
If Not OcurrioError Then
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal) Then
OcurrioError = True
End If
End If
Next
End If
'Orden Produccion'
If Not OcurrioError Then
If UsuarioActual.CveEmpresa.Contiene(126) Then
If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then
If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then
OcurrioError = True
End If
End If
End If
End If
If ObjConta.ValidacionPrePolizaCuadre(-1, 2, CveVenta) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
If ObjConta.ValorPolizaDescuadre = 2 Then
OcurrioError = True
Alert(ObjConta.MensajePolizaDescuadre, TipoMensaje.MsgError)
End If
End If
End If
If Not OcurrioError Then
If RegeneracionPolizas(ObjVentas, ObjAC) Then
OcurrioError = True
End If
End If
If OcurrioError Then
ObjVentas.RollBack()
Alert("Ocurrió un error al guardar los cambios. Por favor intente de nuevo.", TipoMensaje.MsgError)
Else
ObjVentas.Commit()
If ObjAC IsNot Nothing Then ObjAC.Commit()
Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();")
End If
ObjVentas.Dispose()
ObjConta.Dispose()
ObjBancos.Dispose()
If ObjAC IsNot Nothing Then ObjAC.Dispose()
End Sub
Private Sub BtnActualizarCuentaTerminal_Click(sender As Object, e As EventArgs) Handles BtnActualizarCuentaTerminal.Click
Dim ObjVentas As New ClsVentas
ObjVentas.IniciaTransacSQL()
Dim TieneError = False
If Not ObjVentas.UpdateVentaCuentaTerminal(DdlCuentaTerminalModal.SelectedValue.ToEntero, CveVenta) Then
TieneError = True
End If
If TieneError Then
ObjVentas.RollBack()
Else
ObjVentas.Commit()
RegistraScript("$('#ModalCuentaTerminal').modal('hide')")
Alert("Se asignó correctamente la cuenta terminal", JSBtnAceptar:="BtnRefrescarPagina();")
End If
ObjVentas.Dispose()
End Sub
#End Region
#Region "CODIGO DE BARRAS"
Protected Sub ChkClasificacion_CheckedChanged(sender As Object, e As EventArgs)
If ChkClasificacion.Checked Then
DIVClasificacion.Visible = False
DIVClasif.Visible = False
DIVCodBarras.Visible = True
DIVCod.Visible = True
TxtCodigoBarras.Focus()
Else
DIVClasificacion.Visible = True
DIVClasif.Visible = True
DIVCodBarras.Visible = False
DIVCod.Visible = False
End If
End Sub
Protected Sub CargarCodigo()
Dim TipoVenta As Integer = 0
Dim drSucursal As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)))
If drSucursal IsNot Nothing Then TipoVenta = drSucursal("TipoVenta").ToString.ToEntero
If TipoVenta = 1 Then
ChkClasificacion.Checked = True
DIVClasif.Visible = False
DIVClasificacion.Visible = False
DIVCodBarras.Visible = True
DIVCod.Visible = True
TxtCodigoBarras.Focus()
'RegistraScript(String.Format("$( document ).ready(function() {{$('#{0}').focus()}});", TxtCodigoBarras.ClientID), "cb")
Else
ChkClasificacion.Visible = False
End If
End Sub
Protected Sub BtnCodigoBarras_Click(sender As Object, e As EventArgs) Handles BtnCodigoBarrasSerie.Click
Dim DrProducto As DataRow = Nothing
If TxtCantidad.Text.Trim.ToDouble <= 0 Then TxtCantidad.Text = "1"
Dim SerieLote As String = ""
Dim CodigoBarras As String = ""
Dim CvePS As Integer
'LIMPIA "PROPIEDAD"
HdnCvePS.Value = ""
'BUSCA POR SERIE E IGNORA CODIGO DE BARRAS (LIMPIA)
If TxtCodigoSerie.Text.Trim <> "" Then
SerieLote = TxtCodigoSerie.Text.Trim().ToUpper()
Dim Objinventarios As New ClsInventarios
Dim Existencia = Objinventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, -1, SerieLote:=SerieLote, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero)
Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", SerieLote))
CvePS = Objinventarios.CvePS
Objinventarios.Dispose()
If Existencia - ExistenciaActual > 0 Then
If CvePS > 0 Then
DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("")
If DrProducto IsNot Nothing Then
HdnCvePS.Value = CvePS.ToString
TxtCantidad.Text = "1"
Else
Alert($"No se encontró un producto con la serie: <b>{SerieLote}</b>. 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: <b>{0}</b>. Por favor rectifique y vuelva a intentar", SerieLote), TipoMensaje.MsgAdvertencia)
TxtCodigoSerie.Focus()
RegistraScript($"$('#{TxtCodigoSerie.ClientID}').select();")
Exit Sub
End If
End If
'BUSCA POR CODIGO DE BARRAS
If Not CvePS > 0 Then
CodigoBarras = TxtCodigoBarras.Text.Trim()
DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero($"CodigoBarras = '{CodigoBarras}'")
If DrProducto IsNot Nothing Then
If DrProducto("Inv_CveMetodoInventario").ToString = "5" Then 'si es serielote
TxtCodigoSerie.Focus()
Exit Sub
Else
CvePS = DrProducto("CvePS").ToString.ToEntero
HdnCvePS.Value = CvePS.ToString
End If
Else
TxtCodigoBarras.Focus()
RegistraScript($"$('#{TxtCodigoBarras.ClientID}').select();")
Alert($"No se encontró un producto con el código de barras: <b>{SerieLote}</b>. Por favor verifique y vuelva a intentar ", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If DrProducto Is Nothing Then
Alert("El producto no fue encontrado", TipoMensaje.MsgAdvertencia)
End If
'CARGA VALORES DEL PS
DdlPSIndexChange(CvePS, DdlPS)
If Not TxtCantidad.Text.ToDouble > 0 Then TxtCantidad.Text = "1"
TxtPrecio.Focus()
RegistraScript($"$('#{TxtPrecio.ClientID}').select();")
'LO DE ABAJO YA NO SE USA - ES VIEJO
Exit Sub
'PARA AGREGAR PS DIRECTO
If DrProducto IsNot Nothing Then
TxtObsPS.Text = ""
If UsuarioActual.CveEmpresa = 80 Then
'BUSCA EL PRECIO DE LA SUCURSAL
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSSucursales(DrProducto("CvePS").ToString.ToEntero, UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero) Then
Dim dtt As DataTable = ObjPS.DtResultados
Dim drPrecio As DataRow = dtt.FiltroPrimero("")
If drPrecio IsNot Nothing And TxtPrecio.Enabled = False Then
TxtPrecio.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4")
End If
dtt.Dispose()
End If
ObjPS.Dispose()
'SI NO CARGA PRECIO DE LA SUCURSAL TOMA EL DEL PS
If TxtPrecio.Text.ToDouble <= 0 Then
TxtPrecio.Text = DrProducto("Precio").ToString.ToDouble.ToString("N4")
End If
HdnPS.Value = DrProducto("PS").ToString
HdnCodigoPS.Value = DrProducto("PSCodigo").ToString
HdnTipoPS.Value = DrProducto("CveTipoPS").ToString
HdnTipoInv.Value = DrProducto("Inv_CveMetodoInventario").ToString
HdnAplicaIEPS.Value = DrProducto("AplicaIEPS").ToString
HdnPorcentajeIEPS.Value = DrProducto("IEPSPorcentaje").ToString
HdnIVAPS.Value = If(DrProducto("IVA").ToString = "-1", ViewState("IVA"), DrProducto("IVA").ToString).ToString
HdnIVARetAPS.Value = DrProducto("RetIVA").ToString
HdnAsientoContable.Value = DrProducto("AsientoContableVentas").ToString
HdnCtaContable.Value = DrProducto("IdCtaContVentas").ToString
HdnAplicaParaConcepto.Value = DrProducto("AplicaParaConcepto").ToString
HdnCodigo.Value = DrProducto("Codigo").ToString
If ValidaAgregarPS(DrProducto("CvePS").ToString.ToEntero, DrProducto("CveUM").ToString.ToEntero, TxtPrecio.Text.Trim.ToDouble, DrProducto("CveTipoPS").ToString.ToEntero) Then
If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then
CvePSAmortizacion = DdlPS.SelectedValue.ToEntero.ToEntero
End If
AgregarProductoServicio(TxtCantidad.Text.Trim.ToDecimal, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString,
DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDecimal, 0,
DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text)
'AddPS(TxtCantidad.Text.Trim.ToDouble, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString,
' DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDouble, HdnIVAPS.Value.ToDouble, 0, 0,
' -1, -1, True, DrProducto("Codigo").ToString, DdlProyecto.SelectedValue.ToEntero,
' DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, DrProducto("CveTipoPS").ToString.ToEntero, DrProducto("Inv_CveMetodoInventario").ToString.ToEntero, SerieLote:=SerieLote, CodigoPS:=DrProducto("PSCodigo").ToString)
LimpiaAgregar()
End If
End If
Else
Alert("El producto no fue encontrado.", TipoMensaje.MsgAdvertencia)
End If
End Sub
Private Sub DdlMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMoneda.SelectedIndexChanged
CambiaMoneda()
End Sub
Private Sub CambiaMoneda()
TrConversionTipoCambio.Visible = False
TrConversionDolares.Visible = False
Select Case DdlMoneda.SelectedValue
Case "1"
TxtTipoCambio.Text = "1"
TxtTipoCambioDlls.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString
TrConversionDolares.Visible = True
Case "2"
TxtTipoCambioDlls.Text = "1"
TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString
TrConversionTipoCambio.Visible = True
Case Else
TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString
TrConversionTipoCambio.Visible = True
End Select
UpPS.Update()
If CveCliente > 0 Then
CargaAnticipos(CveCliente)
End If
End Sub
Private Sub btnBuscarPrecio_Click(sender As Object, e As EventArgs) Handles btnBuscarPrecio.Click
Dim Codigo, CodigoBarras As String
Dim CvePS As Integer
CvePS = If(DdlBPPS.SelectedValue.ToEntero > 0, DdlBPPS.SelectedValue.ToEntero, -1)
Codigo = If(TxtBPCodigo.Text.Trim.Length = 0, "", TxtBPCodigo.Text)
CodigoBarras = If(TxtBPCodigoBarras.Text.Trim.Length = 0, "", TxtBPCodigoBarras.Text)
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSSucursalesALL(DdlPS.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, Codigo:=Codigo, CodigoBarras:=CodigoBarras) Then
GVBuscarPrecio.DataSource = ObjPS.DtResultados
Else
GVBuscarPrecio.DataSource = Nothing
End If
ObjPS.Dispose()
GVBuscarPrecio.DataBind()
UpBuscarPrecio.Update()
End Sub
#End Region
#Region " CONDICIONES DE PAGO "
Private Sub InicializaCondicionesPago()
DtPagos = New DataTable
DtPagos.Columns.Add("CveTipoMovimiento", GetType(String))
DtPagos.Columns.Add("TipoMovimiento", GetType(String))
DtPagos.Columns.Add("CveCuenta", GetType(String))
DtPagos.Columns.Add("Cuenta", GetType(String))
DtPagos.Columns.Add("Folio", GetType(String))
DtPagos.Columns.Add("Importe", GetType(Decimal))
DtPagos.Columns.Add("Observaciones", GetType(String))
DtPagos.Columns.Add("Tipo", GetType(String))
DtPagos.Columns.Add("CveMetodoPago", GetType(Integer))
CargaCuentas()
End Sub
Private Sub LimpiaContado()
CargaCuentas()
DdlCuentaEfectivo.SelectedValueExist(-1)
TxtImporteEfectivo.Text = "0.00"
TxtImporteCredito.Text = "0.00"
TxtImporteDebito.Text = "0.00"
TxtImporteCheque.Text = "0.00"
TxtImporteTransferencia.Text = "0.00"
TxtImporteContado.Text = "0.00"
End Sub
Private Sub LimpiaEscondeContado()
'LIMPIA
DivContado.Visible = False
DivTerminal.Visible = False
If DtPagos IsNot Nothing Then DtPagos.Rows.Clear()
CargaGridContado()
Select Case RBLPago.SelectedValue.ToEntero
Case 1 'CREDITO
TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString
Case 2 'CONTADO
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then
DivContado.Visible = True
TxtImporteContado.Text = TxtTotal.Text
End If
TxtFechaPago.Text = Now.ToShortDateString
Case 3 ' TERMINAL
DivTerminal.Visible = True
TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString
End Select
LimpiaContado()
UpContado.Update()
End Sub
Private Sub CargaCuentas()
DdlCuentaEfectivo.Items.Clear()
DdlCuentaTarjetaCredito.Items.Clear()
DdlCuentaTarjetaDebito.Items.Clear()
DdlCuentaCheque.Items.Clear()
DdlCuentaTransferencia.Items.Clear()
DdlCuentaEfectivo.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero)))
DdlCuentaTarjetaCredito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero)))
DdlCuentaTarjetaDebito.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero)))
DdlCuentaCheque.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero)))
DdlCuentaTransferencia.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(DdlMoneda.SelectedValue.ToEntero <= 0, 1, DdlMoneda.SelectedValue.ToEntero)))
DdlCuentaEfectivo.DataBind()
DdlCuentaTarjetaCredito.DataBind()
DdlCuentaTarjetaDebito.DataBind()
DdlCuentaCheque.DataBind()
DdlCuentaTransferencia.DataBind()
End Sub
Private Function CargaFolioContado(CveCuenta As Integer, TipoTransaccion As Integer) As Long
Dim Folio As Long
If CveCuenta > 0 And TipoTransaccion > 0 Then
Dim Banco As New ClsBancos
Folio = Banco.GetNextFolio(CveCuenta, TipoTransaccion)
Banco.Dispose()
Else
Folio = -1
End If
Return Folio
End Function
Private Sub CargaGridContado()
GvPagos.DataSource = DtPagos
GvPagos.DataBind()
End Sub
Protected Sub GvPagos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles GvPagos.RowDeleting
DtPagos.Rows.RemoveAt(e.RowIndex)
'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P.
Dim abonado = DtPagos.SUM("Importe")
Dim saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado
CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString
CargaGridContado()
UpContado.Update()
End Sub
Private Sub BtnAgregarPago_Click(sender As Object, e As EventArgs) Handles BtnAgregarPago.Click
Dim abonado, saldo As Double
Dim total As Decimal = TxtImporteEfectivo.Text.ToDecimal + TxtImporteCredito.Text.ToDecimal + TxtImporteDebito.Text.ToDecimal + TxtImporteCheque.Text.ToDecimal + TxtImporteTransferencia.Text.ToDecimal
DtPagos = Nothing
InicializaCondicionesPago()
If total <= 0 Then Alert("No se ha ingresado importe", TipoMensaje.MsgAdvertencia) : Exit Sub
If DtPagos.SUM("Importe").ToString.ToDecimal + total > TxtTotal.Text.ToDecimal Then
Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor rectifique.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'Pago en Efectivo
If TxtImporteEfectivo.Text.ToDecimal > 0 Then
If DdlCuentaEfectivo.Items.Count > 0 Then
Dim DrEfectivo = DtPagos.NewRow
DrEfectivo("CveTipoMovimiento") = 13
DrEfectivo("TipoMovimiento") = "Pago en Efectivo"
DrEfectivo("CveCuenta") = DdlCuentaEfectivo.SelectedValue
DrEfectivo("Cuenta") = DdlCuentaEfectivo.SelectedItem.Text
DrEfectivo("Importe") = TxtImporteEfectivo.Text
DrEfectivo("Folio") = CargaFolioContado(DdlCuentaEfectivo.SelectedValue.ToEntero, 6)
DrEfectivo("Observaciones") = ""
DrEfectivo("Tipo") = "Caja Chica"
DrEfectivo("CveMetodoPago") = 1
DtPagos.Rows.Add(DrEfectivo)
Else
Alert("Debe seleccionar una cuenta válida de caja", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Tarjeta Credito
If TxtImporteCredito.Text.ToDecimal > 0 Then
If DdlCuentaTarjetaCredito.Items.Count > 0 Then
Dim DrCredito = DtPagos.NewRow
DrCredito("CveTipoMovimiento") = 12
DrCredito("TipoMovimiento") = "Tarjeta de Crédito"
DrCredito("CveCuenta") = DdlCuentaTarjetaCredito.SelectedValue
DrCredito("Cuenta") = DdlCuentaTarjetaCredito.SelectedItem.Text
DrCredito("Importe") = TxtImporteCredito.Text
DrCredito("Folio") = CargaFolioContado(DdlCuentaTarjetaCredito.SelectedValue.ToEntero, 12)
DrCredito("Observaciones") = ""
DrCredito("Tipo") = "Tarjeta de Crédito"
DrCredito("CveMetodoPago") = 4
DtPagos.Rows.Add(DrCredito)
Else
Alert("Debe seleccionar una cuenta válida de crédito", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Tarjeta Debito
If TxtImporteDebito.Text.ToDecimal > 0 Then
If DdlCuentaTarjetaDebito.Items.Count > 0 Then
Dim DrDebito = DtPagos.NewRow
DrDebito("CveTipoMovimiento") = 11
DrDebito("TipoMovimiento") = "Tarjeta de Debito"
DrDebito("CveCuenta") = DdlCuentaTarjetaDebito.SelectedValue
DrDebito("Cuenta") = DdlCuentaTarjetaDebito.SelectedItem.Text
DrDebito("Importe") = TxtImporteDebito.Text
DrDebito("Folio") = CargaFolioContado(DdlCuentaTarjetaDebito.SelectedValue.ToEntero, 11)
DrDebito("Observaciones") = ""
DrDebito("Tipo") = "Tarjeta de Débito"
DrDebito("CveMetodoPago") = 5
DtPagos.Rows.Add(DrDebito)
Else
Alert("Debe seleccionar una cuenta válida de débito", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Tarjeta Debito
If TxtImporteCheque.Text.ToDecimal > 0 Then
If DdlCuentaCheque.Items.Count > 0 Then
Dim DrCheque = DtPagos.NewRow
DrCheque("CveTipoMovimiento") = 3
DrCheque("TipoMovimiento") = "Cheque"
DrCheque("CveCuenta") = DdlCuentaCheque.SelectedValue
DrCheque("Cuenta") = DdlCuentaCheque.SelectedItem.Text
DrCheque("Importe") = TxtImporteCheque.Text
DrCheque("Folio") = CargaFolioContado(DdlCuentaCheque.SelectedValue.ToEntero, 3)
DrCheque("Observaciones") = ""
DrCheque("Tipo") = "Cheque"
DrCheque("CveMetodoPago") = 2
DtPagos.Rows.Add(DrCheque)
Else
Alert("Debe seleccionar una cuenta de cheque", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Transferencia
If TxtImporteTransferencia.Text.ToDecimal > 0 Then
If DdlCuentaTransferencia.Items.Count > 0 Then
Dim DrCheque = DtPagos.NewRow
DrCheque("CveTipoMovimiento") = 8
DrCheque("TipoMovimiento") = "Transferencia"
DrCheque("CveCuenta") = DdlCuentaTransferencia.SelectedValue
DrCheque("Cuenta") = DdlCuentaTransferencia.SelectedItem.Text
DrCheque("Importe") = TxtImporteTransferencia.Text
DrCheque("Folio") = CargaFolioContado(DdlCuentaTransferencia.SelectedValue.ToEntero, 8)
DrCheque("Observaciones") = ""
DrCheque("Tipo") = "Transferencia"
DrCheque("CveMetodoPago") = 3
DtPagos.Rows.Add(DrCheque)
Else
Alert("Debe seleccionar una cuenta de transferencia", TipoMensaje.MsgAdvertencia)
End If
End If
'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P.
abonado = DtPagos.SUM("Importe")
saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado
CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString
CargaGridContado()
UpContado.Update()
End Sub
Private Sub RBLPago_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLPago.SelectedIndexChanged
LimpiaEscondeContado()
End Sub
Private Function ValidaPagosContado() As Boolean
Dim Retorno = False
If DtPagos.SUM("Importe").ToString.ToDecimal > TxtTotal.Text.ToDecimal Then
Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor verifique.", TipoMensaje.MsgAdvertencia)
Retorno = True
End If
Return Retorno
End Function
#End Region
#Region " SERIE ALMACEN "
Protected Sub BtnSerie_Click(sender As Object, e As EventArgs)
Dim Row = CType(CType(sender, Button).NamingContainer, GridViewRow)
If Row.FCTextBox("TxtSerie").Text.Trim = "" Then Exit Sub
Dim Index = Row.RowIndex
Dim ObjInventarios As New ClsInventarios
Dim Existencia = ObjInventarios.GetExistenciasPSSerie(Row.FCTextBox("TxtSerie").Text.ToString, ddlAlmacen.SelectedValue.ToEntero, UsuarioActual.CveEmpresa)
Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Row.FCTextBox("TxtSerie").Text.ToString))
'Valida Existencia
If Existencia - ExistenciaActual <= 0 Then
Alert(String.Format("No hay existencia suficiente del producto con la Serie: <b>{0}</b>. Por favor rectifique y vuelva a intentar", Row.FCTextBox("TxtSerie").Text.ToString), TipoMensaje.MsgAdvertencia)
Row.FCTextBox("TxtSerie").Text = ""
Row.FCHiddenField("HdnSerie").Value = ""
TmpDT.Rows(Index)("SerieLote") = ""
Else
Row.FCHiddenField("HdnSerie").Value = Row.FCTextBox("TxtSerie").Text
TmpDT.Rows(Index)("SerieLote") = Row.FCTextBox("TxtSerie").Text
End If
TmpDT.AcceptChanges()
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
ObjInventarios.Dispose()
UpINV.Update()
End Sub
Private Function ValidaSerieINV() As Boolean
Dim Retorno = False
Dim Existencia = 0.0
Dim ExistenciaActual = 0.0
Dim ObjInventarios As New ClsInventarios
For Each Gvr As GridViewRow In GvInv.Rows
If Gvr.FCCheckBox("cbInv").Checked Then
'VACIO
If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim = "" Then
Alert("Algun producto con salida de inventario no tiene especificada la SERIE. Por favor verifique.", TipoMensaje.MsgAdvertencia)
Retorno = True
Exit For
End If
'SIN EXISTENCIA
If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim <> "" Then
Existencia = ObjInventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, ddlAlmacen.SelectedValue.ToEntero, SerieLote:=Gvr.FCTextBox("TxtSerie").Text.ToString, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1)
ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Gvr.FCTextBox("TxtSerie").Text.Trim))
'Valida Existencia
If Existencia - ExistenciaActual < 0 Then
Alert(String.Format("No hay existencia suficiente del producto con la Serie: <b>{0}</b>. 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
#End Region
#Region " INVENTARIO POR ENTREGA"
Private Sub InventarioMov(Optional CveVentaPadre As Integer = -1)
If CveVentaPadre > 0 Then
Dim ObjVentas As New ClsVentas()
If ObjVentas.GetVenta(CveVentaPadre, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados.Rows.Count > 0 AndAlso ObjVentas.DtResultados.Rows(0)("TipoDocto").ToString() = "Ing" AndAlso DdlTipoComprobante.SelectedValue = "Ing" Then
' Dim CveEstatusRefacturacion As Integer = ObjVentas.DtResultados.Rows(0)("CveEstatusRefacturacion").ToString().ToEntero()
' If CveEstatusRefacturacion = 2 Then
CargaInventario(Me.CveVenta)
'End If
Else
CargaInventario(Me.CveVenta)
End If
End If
ObjVentas.Dispose()
Else
CargaInventario(Me.CveVenta)
End If
End Sub
Private Sub CargaInventario(CveVenta As Integer)
Dim ObjInv As New ClsInventarios
If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjInv.DtResultados.Rows.Count > 0 Then
CargaGVInv(ObjInv.DtResultados)
End If
End If
ObjInv.Dispose()
End Sub
Private Sub CargaGVInv(DtTemporal As DataTable)
If Not DtTemporal.Columns.Contains("Lote") Then
DtTemporal.Columns.Add("Lote", Type.GetType("System.String"))
End If
If Not DtTemporal.Columns.Contains("Batch") Then
DtTemporal.Columns.Add("Batch", Type.GetType("System.String"))
End If
GvInv.Columns(4).Visible = DtTemporal.MAX("SerieLote", "SerieLote <> ''") <> "" Or CveVenta <= 0
GvInv.Columns(5).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> ""
GvInv.Columns(6).Visible = DtTemporal.MAX("Lote", "Lote <> ''") <> ""
GvInv.DataSource = DtTemporal
GvInv.DataBind()
UpINV.Update()
End Sub
#End Region
#Region "IMPUESTOS LOCALES"
Private Sub GvImpuestosLocales2_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvImpuestosLocales2.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'e.Row.FCTextBox("TxtImpuestoLocalPS").Text = (TxtSubTotal.Text.ToDouble - (TxtSubTotal.Text.ToDouble * (e.Row.DBCampo("Porcentaje").ToString.ToDouble) / 100)).ToString
e.Row.FCTextBox("TxtImpuestoLocalPS").Attributes.Add("onKeyUp", String.Format("FnSuma();"))
End If
End Sub
Private Function RegeneracionPolizas(ByRef ObjVentas As ClsVentas, ByRef ObjAC As ClsContPAQi) As Boolean
Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL())
Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL())
Dim CvePlantillaPoliza As Integer
Dim ErrorCancelar As Boolean = False
Dim Mensaje As String = ""
CreaObjetosVenta()
If UsuarioActual.Empresa.UsaAC Then
ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL()
End If
If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then
CvePlantillaPoliza = 7
ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem", "Ant") Then
CvePlantillaPoliza = 4
Else
CvePlantillaPoliza = 4
End If
'Removemos los conceptos de la prepoliza
ObjConta.RemovePrePolizasDetalle(CvePrePoliza, -1, CveVenta, 2)
ObjFactura.CveVenta = CveVenta
ObjFactura.CvePrePoliza = CvePrePoliza
ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, 1, ObjBancos, ObjVentas)
If Not ErrorCancelar Then ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, 1)
Return ErrorCancelar
End Function
#End Region
#Region " DEVOLUCION ALMACEN "
Private Sub InicializaDevolucionAlmacen()
If Not GvInv.Rows.Count > 0 Then
Exit Sub
End If
If CveVenta > 0 AndAlso SaldoVenta = TxtTotal.Text.ToDecimal Then 'And (DdlTipoComprobante.SelectedValue.Contiene({"Rem", "Ped"}) Or (DdlTipoComprobante.SelectedValue.Contiene({"Ing"}) And TxtFecha.Text.ToDate.Month = Now.Month And TxtFecha.Text.ToDate.Year = Now.Year)) Then
If Not DevolucionAlmacen = 2 Then
'If UsuarioActual.Empresa.Funcionalidad(555) = "1" Then
LiDevolucionAlmacen.Visible = True
'End If
End If
If DevolucionAlmacen = 1 Then
LBDevolucionAlmacen.Text = "<i class='fa fa-pencil'></i> Cancelar Devolución Almacén"
LBDevolucionAlmacen.ToolTip = "¿Está seguro de Cancelar la Devolución de Almacén?"
Else
LBDevolucionAlmacen.Text = "<i class='fa fa-pencil'></i> Solicitar Devolución Almacén"
LBDevolucionAlmacen.ToolTip = "¿Está seguro de Solicitar la Devolución de Almacén?"
End If
End If
'UpInvDev.Update()
End Sub
Protected Sub LBDevolucionAlmacen_Click(sender As Object, e As EventArgs)
Dim ObjVentas As New ClsVentas
Dim EstatusDevolucion = If(DevolucionAlmacen = 0, 1, 0)
If ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then
Alert("La solicitud de Devolución de Almacén se guardó correctamente")
End If
DevolucionAlmacen = EstatusDevolucion
InicializaDevolucionAlmacen()
UpnTools.Update()
ObjVentas.Dispose()
End Sub
#End Region
#Region "D I R E C C I O N E N V I O"
Private Sub CargaDireccionesEnvio()
Dim ObjClientes As New ClsClientes
Dim TieneError = False
DdlDireccionEnvio.Items.Clear()
If ObjClientes.DireccionEnvioGet(-1, CveCliente, CveClienteSucursal) Then
DdlDireccionEnvio.DataSource = ObjClientes.DtResultados.FiltraParametros(String.Format("Estatus = 1"))
DdlDireccionEnvio.DataBind()
'DdlDireccionEnvio.Items.Insert(0, New ListItem("Seleccione", "-1"))
TmpDTEnvioDireccion = ObjClientes.DtResultados
Else
TieneError = True
End If
If TieneError Then
Alert("Ocurrió un error al obtener las direcciones de envío", TipoMensaje.MsgError)
End If
ObjClientes.Dispose()
UpCliente.Update()
End Sub
Private Sub ChkDireccionEnvio_CheckedChanged(sender As Object, e As EventArgs) Handles ChkDireccionEnvio.CheckedChanged
If ChkDireccionEnvio.Checked Then
DdlDireccionEnvio.Visible = True
LnkOtraDireccion.Visible = True
Else
DdlDireccionEnvio.Visible = False
LnkOtraDireccion.Visible = False
End If
End Sub
Private Sub BtnAgregarDireccion_Click(sender As Object, e As EventArgs) Handles BtnAgregarDireccion.Click
Dim ObjClientes As New ClsClientes
Dim TieneError = False
Dim CveDireccionEnvio As Integer
CveDireccionEnvio = ObjClientes.DireccionEnvioAdd(CveCliente, TxtDireccion.Text.Trim, TxtNoExt.Text.Trim, TxtNoInt.Text.Trim, TxtColonia.Text.Trim, TxtCiudad.Text.Trim, TxtEstado.Text.Trim, TxtCP.Text.ToEntero, TxtContacto.Text.Trim, UsuarioActual.CveUsuario, 1, CveClienteSucursal:=CveClienteSucursal, EnvioDepartamento:=If(TxtDepartamento.Text.Trim = "", "-1", TxtDepartamento.Text.Trim))
If CveDireccionEnvio < 0 Then
TieneError = True
End If
If Not TieneError Then
TxtDireccion.Text = ""
TxtColonia.Text = ""
TxtCiudad.Text = ""
TxtEstado.Text = ""
TxtCP.Text = ""
TxtNoExt.Text = ""
TxtNoInt.Text = ""
TxtContacto.Text = ""
TxtDepartamento.Text = ""
CargaDireccionesEnvio()
DdlDireccionEnvio.SelectedValueExist(CveDireccionEnvio)
End If
ObjClientes.Dispose()
RegistraScript("$('#divAddDireccionEnvio').modal('hide');LimpiaModal();")
End Sub
Private Sub LnkOtraDireccion_Click(sender As Object, e As EventArgs) Handles LnkOtraDireccion.Click
TxtDireccion.Text = LblDireccion.Text.Trim
TxtNoExt.Text = CliNoExt.Trim
TxtNoInt.Text = CliNoInt.Trim
TxtColonia.Text = LblColonia.Text.Trim
TxtCiudad.Text = LblCiudad.Text.Trim
TxtEstado.Text = LblEstado.Text.Trim
TxtCP.Text = LblCP.Text.Trim
UpBodyDireccion.Update()
RegistraScript("$('#divAddDireccionEnvio').modal();")
End Sub
#End Region
#Region " CARGA FACTURA OC "
Private Sub CargaFacturaOC()
CveOC = IfNull(Request("CveOC"), -1).ToString.ToEntero
If CveOC > 0 Then
Dim tDT As DataTable = Nothing
Dim ObjOC As New ClsOC
If ObjOC.GetOCFacturacion(CveOC, UsuarioActual.CveEmpresa) Then
tDT = ObjOC.DtResultados
'tTmpDT.Columns.Add("TipoDocto", GetType(String))
'tTmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
'tTmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal))
Else
Alert("Ocurrió un error al obtener los detalles de la orden de compra. Por favor vuelva a intentar.", TipoMensaje.MsgError)
End If
ObjOC.Dispose()
If tDT IsNot Nothing AndAlso tDT.Rows.Count > 0 Then
ViewState("CveCliente") = ObjOC.DtResultados.Rows(0)("CveCliente")
HdnCveCliente.Value = CveCliente.ToString
CargaCliente(CveCliente)
For Each Dr As DataRow In tDT.Rows
AgregarProductoServicio(Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString,
Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal,
Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString,
CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveOrdenCompraDetalle:=Dr("CveOrdenCompraDetalle").ToString.ToEntero)
Next
'GvPS.DataSource = TmpDT
'GvPS.DataBind()
'TxtSubTotal.Text = TmpDT.SUM("Total").FormatoNumero(2)
'TxtIVA.Text = (TxtSubTotal.Text.ToDecimal * ViewState("IVA").ToString.ToDecimal).ToString
'CalculaTotalesImpuestosLocales()
'CalculaTotales(False)
UpPS.Update()
VerificarContrato(True)
If UsuarioActual.TienePermisoProceso(175) Then
DdlTipoComprobante.Items.FindByText("Egresos").Enabled = False
End If
DdlTipoComprobante.Items.FindByText("Cotización").Enabled = False
DdlTipoComprobante.Items.FindByText("Anticipos").Enabled = False
'DESACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto disabled")
TxtCodigo.ReadOnly = True
UpCliente.Update()
tDT.Dispose()
Else
Alert("No se encontró la orden de compra especificada. Por favor verifique y vuelta a intentar.", TipoMensaje.MsgAdvertencia)
End If
CalculaTotalesVenta()
End If
End Sub
#End Region
#Region "CargaFactura"
Private Function CargaFactura(CveFactura As Integer) As String
Dim RFC As String = ""
Dim XMLDoc As New XmlDocument
Dim Archivo As String = String.Format("{0}Empresas\{1}\Ventas\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Request("RFC"), $"{Request("CveFactura")}.xml")
If IO.File.Exists(Archivo) Then
Dim Validada As Boolean = True
LbAgregar.Visible = False
If Validada Then
XMLDoc.Load(Archivo)
CreaDTConceptos()
CargaConceptosXML(XMLDoc)
CargaComprobanteXML(XMLDoc)
Select Case TipoComprobante
Case "ingreso" : DdlTipoComprobante.SelectedValue = "Ing"
Case "egreso" : DdlTipoComprobante.SelectedValue = "Egs"
End Select
RFC = ReceptorRFC
TxtFecha.Text = Fecha
TxtFolio.Text = FolioXML.ToString
If (FolioXML <> "") Then
ViewState("ExFolioFactura") = True
End If
Dim IVA As Decimal
IVA = TrasladoIVA
If Not UsuarioActual.TienePermisoProceso(130) Then
TxtFolio.Enabled = False
End If
DdlTipoComprobante.Enabled = False
TxtFecha.Enabled = False
ImgFecha.Enabled = False
TxtSubTotal.Enabled = False
TxtSubTotal2.Enabled = False
TxtIVA.Enabled = False
'TxtTotal.Enabled = False
RegistraScript("SetDisabledTxtTotal(true);")
If TxtFolio.Text.Trim = "" Then TxtFolio.Enabled = True
If UsuarioActual.TienePermisoProceso(112) Then
TxtSubTotal.Enabled = True
TxtSubTotal2.Enabled = True
TxtIVA.Enabled = True
'TxtTotal.Enabled = True
RegistraScript("SetDisabledTxtTotal(false);")
End If
TxtIVA.Text = IVA.FormatoNumero
TxtRetIVA.Text = RetencionIVA.FormatoNumero
LblDescuentos.Text = Descuentos.FormatoNumero
TxtFecha.Text = Fecha.ToDate.ToShortDateString
Dim Msg As String = ""
'PRUEBA
'http://rm/Compras/Compras.aspx?CveFactura=122518 Emp: 48
'tTotal = Math.Round(SubTotal2 + IVA - RetencionIVA - RetencionISR + IEPS + OtrosImpuestos, 2)
Dim AjustaUltimoConcepto = False
'en otro impuesto lo esta registrando en ajuste en automatico
If OtrosImpuestos > 0 Then
AjustaUltimoConcepto = True
End If
If RFC = "CFE370814QI0" Then ' RFC de CFE, se hace un ajuste por diferencia para sacar el DAP
'OtrosImpuestos = Total - (SubTotal2 + IVA)
'este importe lo vamos a meter al gasto
'AjustaImporteUltimoConcepto(OtrosImpuestos)
OtrosImpuestos = 1
AjustaUltimoConcepto = True
'SubTotal2 = SubTotal
End If
Dim SubTotalReal As Decimal = Math.Round(Total + RetencionISR + RetencionIVA - IVA + Descuentos, 2) ' NO se incluye otros impuestos para ajustar esa cifra
Dim DiferenciaTotales As Decimal = SubTotalReal - Math.Round(SubTotalConceptos, 2)
ViewState("Folio") = FolioXML
End If
Else
Alert("No se encontró la factura", TipoMensaje.MsgAdvertencia)
End If
'GvPS.DataSource = 'DTConceptos
'GvPS.DataBind()
Return RFC
End Function
Private Sub CreaDTConceptos()
DTConceptos = New DataTable
DTConceptos.Columns.Add("Consec", GetType(Integer))
DTConceptos.Columns.Add("Cantidad", GetType(Decimal))
DTConceptos.Columns.Add("UM", GetType(String))
DTConceptos.Columns.Add("CveClasificacion", GetType(Integer))
DTConceptos.Columns.Add("PS", GetType(String))
DTConceptos.Columns.Add("PU", GetType(Decimal))
DTConceptos.Columns.Add("Descuento", GetType(Decimal))
DTConceptos.Columns.Add("IVA", GetType(Decimal))
DTConceptos.Columns.Add("Total", GetType(Decimal))
End Sub
Private Sub CargaConceptosXML(XMLDoc As XmlDocument)
Dim i As Integer = 0
Dim node As XmlNode
Dim PU As Decimal = 0
Dim Descuento As Double = 0
Dim CveUM As Integer = 0
Dim UMM As String = "No Aplica"
Dim tCvePS As Integer = 0
Dim TipoPS As Integer = 0
Dim tCveClasif As Integer = -1
Dim Clasif As String = "Sin Clasificación"
Dim tPSCodigo As String = "-"
Dim tPSDescripcion As String = "-"
Dim PSS As String = ""
Dim Obs As String = ""
Dim SubTotalTemp = 0.0D
'GLOBALS
Dim DtUM = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa).AsEnumerable
Dim DtUMAlias = GlobalDTUnidadesMedidaAlias(UsuarioActual.CveEmpresa).AsEnumerable
'Dim DtPS = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).AsEnumerable
Dim DtPS = GlobalDTPS(UsuarioActual.CveEmpresa).AsEnumerable
Dim DtPSAlias = GlobalDTProductosServiciosAlias(UsuarioActual.CveEmpresa).AsEnumerable
''AGREGA EN TABLA TEMPORAL
'Dim DtPSTemp = TmpDT.Clone
'Dim Row As DataRow = Nothing
For i = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1
' INICIALIZA VALORES
PU = 0
Descuento = 0
CveUM = 0
UMM = "No Aplica"
tCvePS = 0
TipoPS = 0
tCveClasif = -1
Clasif = "Sin Clasificación"
tPSCodigo = "-"
tPSDescripcion = "-"
PSS = ""
Obs = ""
Total = 0
'CARGA NODO ACTUAL
node = XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i)
'CARGA PU
PU = ValorXML(node, "valorUnitario").ToDecimal
'SI PU >= TOTAL AND CANTIDAD > 0 : PU / CANTIDAD, por si tiene descuento en el importe y el valor unitario es mayor, lo ajusta
If ValorXML(node, "cantidad").ToDecimal > 0 AndAlso ValorXML(node, "valorUnitario").ToDecimal >= (ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal) Then
PU = ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal
End If
If ValorXML(node, "cantidad").ToDecimal > 0 AndAlso ValorXML(node, "valorUnitario").ToDouble <= 0 And ValorXML(node, "importe").ToDouble > 0 Then
PU = ValorXML(node, "importe").ToDecimal / ValorXML(node, "cantidad").ToDecimal
End If
'OBTIENE DESCUENTO
If ValorXML(node, "descuento") IsNot Nothing Then Descuento = ValorXML(node, "descuento").Trim.ToDouble
'OBTIENE TOTAL
If ValorXML(node, "importe") IsNot Nothing Then Total = ValorXML(node, "importe").Trim.ToDecimal
'OBTIENE SUBTOTAL
SubTotalTemp += If(Total > 0, Total, PU * ValorXML(node, "cantidad").ToDecimal)
'OBTIENE UM
If ValorXML(node, "unidad") IsNot Nothing Then UMM = ValorXML(node, "unidad").Trim
'BUSCA UM EN CATALOGO
UMM = UMM.ToUpper.Replace(".", "").Replace(",", "")
Dim fUM = (From u In DtUM
Where String.Compare(u!UnidadMedida.ToString.ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0 OrElse
String.Compare(u!Abreviatura.ToString.ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select CveUnidadMedida = u!CveUnidadMedida, UnidadMedida = u!UnidadMedida).FirstOrDefault()
If fUM IsNot Nothing AndAlso fUM.CveUnidadMedida.ToString.ToEntero > 0 Then
CveUM = fUM.CveUnidadMedida.ToString.ToEntero
UMM = fUM.UnidadMedida.ToString
Else
'BUSCA UM EN ALIAS
Dim fUMAlias = (From u In DtUMAlias
Where String.Compare(u!UnidadMedidaAlias.ToString.ToUpper.Trim, UMM, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select u!CveUnidadMedida, u!UnidadMedida).FirstOrDefault()
If fUMAlias IsNot Nothing Then
CveUM = fUMAlias.CveUnidadMedida.ToString.ToEntero
UMM = fUMAlias.UnidadMedida.ToString
End If
End If
'se le puso una condicion de que ignorara los acentos, porque en la bd, marcaria error porque no distingue acentos
'CONCEPTO PRUEBA "TRABAJOS DE CONSTRUCCION", RM/Compras/Compras.aspx?CveFactura=13402&RFC=ECO061206QW7
'' u!PS.ToString.ToUpper.Trim = PSS
'BUSCA PS
PSS = ValorXML(node, "descripcion").ToUpper.Trim.Replace(vbCrLf, " ").Replace(vbLf, " ").Replace("'", "''").Replace(" ", " ")
If PSS.Length > 844 Then
PSS = PSS.Substring(0, 844) '844,por ser el numero de caracteres aceptados en la columna de la BD
End If
tPSCodigo = PSS
'BUSCA PS EN CATALOGO
Dim fPS = (From u In DtPS
Where String.Compare(u!PS.ToString.ToUpper.Trim, PSS, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select u!CvePS, u!CveClasificacion, u!Clasificacion, u!CveTipoPS, u!PSCodigo).FirstOrDefault()
If fPS IsNot Nothing Then
PSS = fPS.PSCodigo.ToString
tCvePS = fPS.CvePS.ToString.ToEntero
TipoPS = fPS.CveTipoPS.ToString.ToEntero
tCveClasif = fPS.CveClasificacion.ToString.ToEntero
Clasif = fPS.Clasificacion.ToString
tPSCodigo = fPS.PSCodigo.ToString
Else
'BUSCA PS EN ALIAS
Dim fPSAlias = (From u In DtPSAlias
Where String.Compare(u!PSAlias.ToString.ToUpper.Trim, PSS, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) = 0
Select u!CvePS, u!PS, u!CveClasificacion, u!Clasificacion, u!CveTipoPS, u!PSCodigo).FirstOrDefault()
If fPSAlias IsNot Nothing Then
Obs = PSS
PSS = fPSAlias.PS.ToString
tCvePS = fPSAlias.CvePS.ToString.ToEntero
TipoPS = fPSAlias.CveTipoPS.ToString.ToEntero
tCveClasif = fPSAlias.CveClasificacion.ToString.ToEntero
Clasif = fPSAlias.Clasificacion.ToString
tPSCodigo = fPSAlias.PSCodigo.ToString
Else
tCvePS = 20168
End If
End If
'PARA GLUYAS
If UsuarioActual.CveEmpresa = 66 Then
tPSCodigo = String.Format("{1} - {0}", ValorXML(node, "descripcion").ToUpper.Trim.Replace(vbCrLf, " ").Replace(vbLf, " ").Replace("'", "''"), ValorXML(node, "noIdentificacion").Trim)
End If
'' AGREGA PS
'AGREGA A TMPDT
'AddPS(ValorXML(node, "cantidad").ToDouble, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, TipoPS, "-1", "SE", "SE", Obs, PU, Total, 0, 0, PSCodigo:=tPSCodigo, TCalculaTotales:=False)
AgregarProductoServicio(ValorXML(node, "cantidad").ToDecimal, CveUM, UMM, tCveClasif, Clasif, tCvePS, PSS, Obs, PU, 0, 0, "", 0, "")
Next
CalculaTotalesVenta()
'AddPS2(False)
'Dim SubTotalConceptos = Math.Round(SubTotalTemp, 2)
'TmpDT = DtPSTemp.Copy
'DtPSTemp.Dispose()
End Sub
Private Sub CargaComprobanteXML(XMLDoc As XmlDocument)
Dim nodo As XmlNode = XMLDoc.DocumentElement
_SerieXML = ValorXML(nodo, "serie")
If _SerieXML <> "" Then _SerieXML = _SerieXML
_Version = ValorXML(nodo, "version")
_FolioXML = ValorXML(nodo, "folio")
_Fecha = ValorXML(nodo, "fecha")
SubTotal = ValorXML(nodo, "subTotal").ToDecimal
Total = ValorXML(nodo, "total").ToDecimal
Descuentos = ValorXML(nodo, "descuento").ToDecimal
_Moneda = ValorXML(nodo, "Moneda")
_TipoComprobante = ValorXML(nodo, "tipoDeComprobante")
Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix)
Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3"
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
If Prefijo.ToLower <> "cfdi" Then cfdVer = "http://www.sat.gob.mx/cfd/2"
namespaces.AddNamespace(Prefijo, cfdVer)
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
Dim node As XmlNode
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
EmisorRFC = ValorXML(node, "RFC")
'EmisorNombre = ValorXML(node, "nombre")
End If
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
ReceptorRFC = ValorXML(node, "RFC")
End If
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces)
TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDecimal
For Each retencion As XmlNode In nodeRetenciones
If retencion.Attributes("impuesto").Value = "IVA" Then
RetencionIVA += retencion.Attributes("importe").Value.ToDecimal
End If
If retencion.Attributes("impuesto").Value = "ISR" Then
RetencionISR += retencion.Attributes("importe").Value.ToDecimal
End If
' Do something.
Next
SumaTotalRetenciones += RetencionIVA
SumaTotalRetenciones += RetencionISR
TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDecimal
Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces)
For Each traslado As XmlNode In nodeTraslados
If traslado.Attributes("impuesto").Value = "IVA" Then
TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal
End If
If traslado.Attributes("impuesto").Value = "IEPS" Then
TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal
End If
'If traslado.Attributes("impuesto").Value = "ISR" Then
' TrasladoISR = traslado.Attributes("importe").Value
'End If
' Do something.
Next
SumaTotalTraslados += TrasladoIVA
SumaTotalTraslados += TrasladoIEPS
End If
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
_TFDUUID = ValorXML(nodeTFD, "UUID", "")
Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces)
If nodeRF IsNot Nothing Then
_FolioXML = ValorXML(nodeRF, "folio").TrimStart("0"c)
End If
node = node.SelectSingleNode(String.Format("//{0}:ImpuestosLocales", "implocal"), namespaces)
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
OtrosImpuestos = ValorXML(node, "TotaldeTraslados", "0").ToDecimal
If RetencionIVA <= 0 AndAlso ValorXML(node, "TotaldeRetenciones", "0").ToDouble > 0 Then RetencionIVA = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal
'For Each retencion As XmlNode In nodeImpLocales
' If retencion.Attributes("impuesto").Value = "IVA" Then
' RetencionIVA += retencion.Attributes("importe").Value.ToDouble
' End If
' If retencion.Attributes("impuesto").Value = "ISR" Then
' RetencionISR += retencion.Attributes("importe").Value.ToDouble
' End If
' ' Do something.
'Next
' SumaTotalRetenciones += RetencionIVA
' SumaTotalRetenciones += RetencionISR
'TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble
'Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces)
'For Each traslado As XmlNode In nodeTraslados
' If traslado.Attributes("impuesto").Value = "IVA" Then
' TrasladoIVA += traslado.Attributes("importe").Value.ToDouble
' End If
' If traslado.Attributes("impuesto").Value = "IEPS" Then
' TrasladoIEPS += traslado.Attributes("importe").Value.ToDouble
' End If
' 'If traslado.Attributes("impuesto").Value = "ISR" Then
' ' TrasladoISR = traslado.Attributes("importe").Value
' 'End If
' ' Do something.
'Next
'SumaTotalTraslados += TrasladoIVA
'SumaTotalTraslados += TrasladoIEPS
End If
End If
End Sub
Private Function ValorXML(n As XmlNode, Campo As String, Optional Retorno As String = "") As String
Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, True) = 0)
If o Is Nothing Then
Return Retorno
Else
Return o.Value
End If
End Function
#End Region
#Region "Metodos Viejos"
Private Sub GeneraPDF(FechaFactura As DateTime, FolioFiscal As String, NoSerieCertificado As String, FechaCertificacion As DateTime, NoSerieCertificadoContribuyente As String,
DTConceptos As DataTable, SelloCFDi As String, SelloSAT As String, CBB As String, Folio As String, RutaXML As String, EsVistaPrevia As Boolean, MuestraAlert As Boolean, Optional MR As ReportViewer = Nothing)
Alert("No se pudo generar el PDF", TipoMensaje.MsgError)
End Sub
Private Sub GeneraPDFCBB(FechaFactura As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean)
End Sub
Private Sub GeneraPDFCot(FechaCotizacion As DateTime, DTConceptos As DataTable, Folio As String, EsVistaPrevia As Boolean, GeneraDescarga As Boolean)
End Sub
Private Sub LkEliminarFactura_Click(sender As Object, e As EventArgs) Handles LkEliminarFactura.Click
If HdnPagado.Value.ToDecimal = 0 Then
Dim ObjVentas As New ClsVentas
ObjVentas.IniciaTransacSQL()
If ObjVentas.EliminarVenta(CveVenta) Then
ObjVentas.Commit()
Alert("La venta ha sido eliminada correctamente.", TipoMensaje.MsgInformacion)
Else
ObjVentas.RollBack()
End If
ObjVentas.Dispose()
Else
Alert("La venta no se puede eliminar ya que tiene pagos vinculados.", TipoMensaje.MsgError)
End If
End Sub
Private Sub RblComplementos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblComplementos.SelectedIndexChanged
If RblComplementos.SelectedValue.Contiene("5", "6") Then 'Directivo/Ejecutivo Estatal
trEntidad.Visible = True
trContaComplementos.Visible = True
trAmbito.Visible = False
trTipoCampaña.Visible = False
ElseIf RblComplementos.SelectedValue = "7" Then 'Ejecutivo Nacional
trEntidad.Visible = False
trContaComplementos.Visible = True
trAmbito.Visible = False
trTipoCampaña.Visible = False
ElseIf RblComplementos.SelectedValue = "8" Then 'Campaña/PreCampaña
trEntidad.Visible = True
trContaComplementos.Visible = True
trAmbito.Visible = True
trTipoCampaña.Visible = True
End If
UpDatosComplementos.Update()
End Sub
Private Sub GvPS_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPS.RowCommand
If e.CommandName = "Clonar" Then
Dim RowNum As Integer = Convert.ToInt32(e.CommandArgument)
Dim GvRow As GridViewRow = GvPS.Rows(RowNum)
TxtCantidad.Text = GvPS.Rows(RowNum).FCLiteral("LtlCantidad").Text
DdlClasificacion.SelectedValue = GvRow.DataKey("CveClasificacion")
DdlPS.SelectedValue = GvRow.DataKey("CvePS")
DdlPS_SelectedIndexChanged(Nothing, Nothing)
DdlUnidadMedida.SelectedValue = GvRow.DataKey("CveUM")
TxtObsPS.Text = GvRow.FCLiteral("LtlObsPS").Text
DdlProyecto.SelectedValue = GvRow.DataKey("CveProyecto")
DdlProyecto_SelectedIndexChanged(Nothing, Nothing)
DdlSubProyecto.SelectedValue = GvRow.DataKey("CveSubProyecto")
TxtPrecio.Text = GvRow.FCLiteral("LtlPU").Text
RegistraScript("Recalcula();")
LbAgregar_Click(Nothing, Nothing)
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
GeneraPDFCotizacion(True)
Alert("La cotización ha sido enviada al correo de nuestro cliente:" & Mail)
End Sub
#End Region
#Region "Cancelar, Generar y mandar por correo el acuse de cancelación."
Private Sub BtnEnviarMailCancelacion_Click(sender As Object, e As EventArgs) Handles BtnEnviarMailCancelacion.Click
ImprimeCancelacion(CveVenta)
End Sub
Public Sub ImprimeCancelacion(CveVenta As Integer)
Dim ObjVentas As New ClsVentas
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
Dim drv As DataRow = ObjVentas.DtResultados.Rows(0)
Dim FolioFiscal = drv("FolioFiscal").ToString
Dim SelloCancelacion = drv("SelloCancelacion").ToString
Dim FechaCancelacion = drv("FechaCancelacion").ToString.ToDateTime.ToString("dd/MM/yyyy HH:mm:ss")
Dim RFC = UsuarioActual.Empresa.RFC
Dim Archivo As New System.IO.FileInfo("Empresas\Grales\Formatos\AcuseCancelacion.rdlc")
Dim params As New List(Of ReportParameter)
params.Add(New ReportParameter("FechaCancelacion", FechaCancelacion.ToString))
params.Add(New ReportParameter("FolioFiscal", FolioFiscal))
params.Add(New ReportParameter("RFCEmisor", RFC))
params.Add(New ReportParameter("SelloCancelacion", SelloCancelacion))
Dim ObjetoPDF As Byte() = StreamPDF("Empresas\Grales\Formatos\AcuseCancelacion.rdlc", ObjVentas.DtResultados, params, "AcuseCancelacion" & CveVenta)
Dim ObjMail As New ClsSisMail
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
Dim Asunto As String = String.Empty
Dim Cuerpo As String = String.Empty
Dim ResultadoMail As Integer
Dim sb As New StringBuilder()
If UsuarioActual.CveEmpresa = 119 Then
sb.Append("<!DOCTYPE html>")
sb.Append("<html>")
sb.Append("<head>")
sb.Append("<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8""/>")
sb.Append(" <title>Acuse De Cancelación</title>")
sb.Append(" <meta charset=""utf-8"" />")
sb.Append("</head>")
sb.Append("<body>")
sb.Append(" <font face=""calibri"">")
sb.Append($" Estimado Cliente <b>{NombreCliente}</b>,<br /><br />")
sb.Append($" Le informamos que Agroquímicos JAM, S.A. DE C.V ha cancelado el CFDI <b>{Serie}-{Folio}</b>, el cual ha quedado sin Efectos Fiscales y encontrará adjunto en este correo el Acuse de <br />")
sb.Append($" cancelación del SAT.<br />")
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 <br /> ")
sb.Append(" EN SU CONTABILIDAD. </font> ")
sb.Append(" <font face=""calibri"" size=""2"">")
sb.Append(" <br /><br /><br /><br /><br />")
sb.Append(" <i>Este correo se generó automaticamente, favor de no responder este mensaje.</i>")
sb.Append(" </font>")
sb.Append("</body>")
sb.Append("</html>")
Else
sb.Append("<!DOCTYPE html>")
sb.Append("<html>")
sb.Append("<head>")
sb.Append("<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8""/>")
sb.Append(" <title>Acuse De Cancelación</title>")
sb.Append(" <meta charset=""utf-8"" />")
sb.Append("</head>")
sb.Append("<body>")
sb.Append(" <font face=""calibri"">")
sb.Append($" Estimado Cliente <b>{NombreCliente}</b>,<br /><br />")
sb.Append($" A través del presente medio la Empresa <b>{UsuarioActual.Empresa.Empresa} - {RFC}</b>, canceló el documento tipo <b>{DdlTipoComprobante.SelectedItem.Text}</b> <br />")
sb.Append($" con folio <b>{Serie}-{Folio}</b> y el Importe de <b>${TxtTotal.Text}</b>. <br /><br />")
sb.Append(" Le hacemos llegar el acuse de cancelación. </font> ")
sb.Append(" <font face=""calibri"" size=""2"">")
sb.Append(" <br /><br /><br /><br /><br />")
sb.Append(" <i>Este correo se generó automaticamente, favor de no responder este mensaje.</i>")
sb.Append(" </font>")
sb.Append("</body>")
sb.Append("</html>")
End If
Asunto = $"Acuse de Cancelacion {Serie}-{Folio}"
Cuerpo = sb.ToString
Dim DisplayName As String = ""
If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM"
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.ArchivoBinario = ObjetoPDF, .NombreArchivo = $"AcuseCancelacion{Serie}-{Folio}.pdf"})
If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then
ResultadoMail = 1
Alert("El acuse de cancelación ha sido envíado correctamente.")
Else
ResultadoMail = 0
End If
End If
End Sub
Private Sub LbCancelarDocumento_Click(sender As Object, e As EventArgs) Handles LbCancelarDocumento.Click
If VentaSaldoAlmacen > 0 Then
Alert("El pedido no se puede cancelar ya que tiene movimientos de almacén.<br/>Nota: Primero hay que hacer la devolución al almacén", TipoMensaje.MsgAdvertencia)
Else
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then
Dim sb As New StringBuilder()
sb.Append("La factura se encuentra en el siguiente estatus del SAT:<br/>")
Dim TotalT As Decimal = TxtTotal.Text.ToDecimal
Dim RFCReceptor As String = LblRFC.Text.Trim
Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), True)
If Vigencia IsNot Nothing Then
If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then
Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If String.IsNullOrEmpty(Vigencia.EsCancelable) Then
sb.Append("<b>No encontrado</b> <br/>")
Else
sb.AppendFormat("<b>{0}</b> <br/>", Vigencia.EsCancelable)
End If
Else
sb.Append("<b>No encontrado</b> <br/>")
End If
sb.Append("Está seguro de cancelar el documento?.")
LblCancelarDocumento.Text = sb.ToString()
RegistraScript("$('#ModalCancelarDocumento').modal();")
UpCancelarDocumento.Update()
'Alert(sb.ToString(), TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnCancelarDocumentoConfirmar()", TextoConfirmacion:="&nbsp;&nbsp;&nbsp;&nbsp;Si&nbsp;&nbsp;&nbsp;&nbsp;", TextoCancelacion:="&nbsp;&nbsp;&nbsp;&nbsp;No&nbsp;&nbsp;&nbsp;&nbsp;")
Else
CancelarDocumento()
End If
End If
End Sub
Protected Sub BtnCancelarDocumento_Click(sender As Object, e As EventArgs)
CancelarDocumento()
RegistraScript("$('#ModalCancelarDocumento').modal('hide');")
End Sub
Private Sub CancelarRefacturada()
Dim CancelacionFecha As Date
Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL()
Dim CancelacionAcuse As String = ""
Dim Mensaje As String = ""
Dim ObjCancelacion As New Timbrado
Dim TotalT As Decimal = TxtTotal.Text.ToDecimal
Dim RFCReceptor As String = LblRFC.Text.Trim
Dim CvePACCancelacion As Integer = CvePAC
Dim CveEstatus As Integer = 4
Try
If FolioFiscal <> "" Then
If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then
'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017
CancelacionFecha = ObjCancelacion.CancelacionFecha
CancelacionAcuse = ObjCancelacion.CancelacionAcuse
CveEstatus = 5
Else
Alert("La factura no se pudo cancelar ante el SAT", TipoMensaje.MsgError)
Exit Sub
End If
Else
CancelacionFecha = Now.Date
CancelacionAcuse = ""
End If
If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IdPoliza, CvePAC:=CvePACCancelacion) Then
ObjVentas.Commit()
Alert("El nuevo estatus se guardó correctamente")
Else
ObjVentas.RollBack()
Alert("Ocurrió un error al intentar cancelar la factura")
End If
Catch ex As Exception
ObjVentas.RollBack()
Mensaje = "Ocurrio un error al Cancelar la factura"
GuardaLog($"{ex.Message}")
End Try
ObjVentas.Dispose()
End Sub
Private Function DecodeBase64(ByVal strXMLCodificado As String) As String
Try
Dim decbuff As Byte() = Convert.FromBase64String(strXMLCodificado)
Return System.Text.Encoding.UTF8.GetString(decbuff)
Catch
Return ""
End Try
End Function
'Private Sub ActualizaEstatusVentaCancelada(Optional CveEstatusCancelacion As Integer = 5)
' Me.CveEstatus = CveEstatusCancelacion
' Dim ObjVentas As New ClsVentas()
' If CveEstatusCancelacion = 5 Then
' Dim IDPoliza As Integer = -1
' Dim ErrorCancelar As Boolean = False
' Dim MensajeError As String = ""
' Dim CvePACCancelacion As Integer = CvePAC
' Dim ObjAC As ClsContPAQi = Nothing
' ObjVentas.IniciaTransacSQL()
' Try
' If UsuarioActual.Empresa.UsaAC Then
' ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL()
' IDPoliza = GenerarPolizaAC(ObjAC, True)
' If IDPoliza <= 0 Then
' ErrorCancelar = True
' MensajeError = "Ocurrió un error al generar la poliza de cancelación."
' End If
' End If
' Dim solicitud = New WSGF.Service1SoapClient()
' Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal)
' If acuse.Estado = 0 Then
' Dim xmlAcuse = New System.Xml.XmlDocument()
' xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64))
' Dim CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText
' Dim CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate()
' If Not ObjVentas.UpdateEstatusFactura(Me.CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion) Then
' ErrorCancelar = True
' MensajeError = "Ocurrió un error al guardar el estatus de cancelación."
' End If
' Else
' 'sino se pudo sacar el acuse, porque se canceló en el SAT, debe de marcarlo
' End If
' Catch ex As Exception
' ErrorCancelar = True
' Alert("Ocurrió un error al actualizar el estatus", TipoMensaje.MsgError)
' Finally
' If Not ErrorCancelar Then
' ObjVentas.Commit()
' If Me.CveEstatus = 5 Then
' Dim MensajeAlert As New StringBuilder
' MensajeAlert.Append("El Documento se canceló correctamente.")
' MensajeAlert.Append($"</br> <a href='/Compras/PopUpVerFactura.aspx?P={Encripta($"OP=CAN&CVEVTA={CveVenta}")}' class='Texto' target='_blank'>Imprimir Acuse</a>")
' MensajeAlert.Append("</br></br> ¿Desea enviar el Acuse de Cancelación al Cliente?")
' Alert(MensajeAlert.ToString, TipoMensaje.MsgConfirmacion, "BtnEnviarMailCancelacion()", TextoConfirmacion:="&nbsp;&nbsp;&nbsp;&nbsp;Si&nbsp;&nbsp;&nbsp;&nbsp;", TextoCancelacion:="&nbsp;&nbsp;&nbsp;&nbsp;<a onclick='Recargar()'>No</>&nbsp;&nbsp;&nbsp;&nbsp;")
' Else
' Alert("El documento se canceló exitosamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="location.reload();")
' End If
' LbCancelarDocumento.Enabled = False
' If ObjAC IsNot Nothing Then ObjAC.Commit()
' Else
' Alert(MensajeError, TipoMensaje.MsgError)
' ObjVentas.RollBack()
' If ObjAC IsNot Nothing Then ObjAC.RollBack()
' End If
' ObjVentas.Dispose()
' If ObjAC IsNot Nothing Then ObjAC.Dispose()
' End Try
' ElseIf CveEstatusCancelacion = 20 Then
' If ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, "", Now, CveVenta) Then
' Alert("El estatus de la factura fue cambiado a 'Cancelación en Proceso'")
' End If
' ObjVentas.Dispose()
' End If
'End Sub
Private Sub CancelarDocumento(Optional EsRefacturacion As Boolean = False)
'Si es cancelacion de una refactura ignoramos las condiciones
If Me.CveEstatus = 13 Then
CancelarRefacturada()
End If
CreaObjetosVenta()
Dim resp As Modelos.Factura.MCancelacionVentaMensaje = Nothing
If ObjFactura IsNot Nothing AndAlso ObjFactura.CveVenta > 0 Then
If EsRefacturacion Then
resp = ObjFactura.CancelarPorRefacturacion()
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
If ChkDevAlm.Checked Then
ObjFactura.CveAlmacenDevolucion = CveAlmacenDevolucion
End If
resp = ObjFactura.CancelarFactura(ChkDevAlm.Checked, ListaRemisionesCancelar)
End If
If resp.CveEstatus = 5 AndAlso Not EsRefacturacion Then
Alert(resp.Mensaje, resp.TipoMensaje, JSBtnAceptar:="BtnEnviarMailCancelacion();", TextoConfirmacion:="&nbsp;&nbsp;&nbsp;&nbsp;Si&nbsp;&nbsp;&nbsp;&nbsp;", TextoCancelacion:="&nbsp;&nbsp;&nbsp;&nbsp;<a onclick='Recargar()'>No</>&nbsp;&nbsp;&nbsp;&nbsp;")
Else
If EsRefacturacion Then
If resp.CveEstatus = 20 Then
Response.Redirect($"/Ventas/RepCancelacionesPorRespuesta.aspx?CveVenta={CveVenta}")
ElseIf resp.CveEstatus.Contiene(4, 5) Then
Response.Redirect($"Ventas.aspx?CveDevolucion={CveVenta}&NuevaFactura=1")
Else
Alert(resp.Mensaje, resp.TipoMensaje, JSBtnAceptar:="BtnRefrescarPagina();")
End If
Else
Alert(resp.Mensaje, resp.TipoMensaje, JSBtnAceptar:="BtnRefrescarPagina();")
End If
End If
ObjFactura.CveAlmacen = -1
Else
Alert("Ocurrió un error al generar la cancelación", TipoMensaje.MsgError)
End If
UpEstatus.Update()
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)
GvContratoDetalles.HeaderRow.Cells(1).Style.Add("display", "none")
BtnCargarContratoDetalles_Click(Nothing, Nothing)
LbAgregar.Visible = True
UpPS.Update()
'AplicaGastoContrato = If(ObjContratos.DtResultados(0)("CveContratoTipo").ToString.Contiene("9", "10", "13"), True, False) 'Arrendamiento, Servicios De Impresion, Financiamiento
Else
Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError)
huboerror = True
End If
Else
Alert("Ocurrió un error al carga la información del contrato. Por favor vuelva a intentar.", TipoMensaje.MsgError)
huboerror = True
End If
ObjContratos.Dispose()
End Sub
#End Region
#Region "DESCARGAR E IMPRIMIR LISTADO"
Public Sub DescargarFormato()
Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & "Empresas\Grales\Formatos\FormatoVentas.xlsx"
Dim Archivo As New IO.FileInfo(Directorio)
If Archivo.Exists Then
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.AddHeader("Content-Disposition", "attachment; filename=" + Archivo.Name)
Response.AddHeader("Content-Length", Archivo.Length.ToString())
Response.ContentType = "text/plain"
Response.Flush()
Response.TransmitFile(Archivo.FullName)
Response.End()
End If
End Sub
Public Sub LbDescargarExcel_Click(sender As Object, e As EventArgs) Handles LbDescargarExcelVentas.Click
DescargarFormato()
End Sub
Private Sub CargarArchivo(Ruta As String, FileName As String, Tipo As String)
Dim dt As New DataTable
Dim Conexion As Odbc.OdbcConnection = Nothing
Dim ErrorArchivo = False
Dim n As Integer = 0
Try
Select Case Tipo
Case "EXCEL"
Conexion = New Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + Ruta + FileName + ";")
Conexion.Open()
Dim cmd = Conexion.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select * FROM [Hoja1$]"
Dim DataAdapter = New Odbc.OdbcDataAdapter(cmd)
DataAdapter.Fill(dt)
Case Else
Alert("El archivo no tiene el formato correcto", TipoMensaje.MsgError)
Exit Sub
End Select
Catch ex As Exception
ErrorArchivo = True
OnError("Ocurrio un Error al leer el archivo <br/>" & ex.Message, ex)
End Try
Conexion.Close()
If Not ErrorArchivo Then
If Not dt.Columns(0).ColumnName = "Cantidad" Then
Alert("El nombre de la primera columna debe ser 'Cantidad'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(1).ColumnName = "Código" Then
Alert("El nombre de la segunda columna debe ser 'Código'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(2).ColumnName = "Codigo Barras" Then
Alert("El nombre de la tecera columna debe ser 'Codigo Barras'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(3).ColumnName = "Producto/Servicio" Then
Alert("El nombre de la cuarta columna debe ser 'Producto/Servicio'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(4).ColumnName = "UM" Then
Alert("El nombre de la quinta columna debe ser 'U.M'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(5).ColumnName = "Precio Unitario" Then
Alert("El nombre de la sexta columna debe ser 'Precio Unitario'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(6).ColumnName = "Proyecto" Then
Alert("El nombre de la séptima columna debe ser 'Proyecto'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(7).ColumnName = "Observaciones" Then
Alert("El nombre de la octava columna debe ser 'Observaciones'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(8).ColumnName = "Tiempo Entrega" Then
Alert("El nombre de la octava columna debe ser 'Tiempo Entrega'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
dt.TableName = "Datos"
If Not ErrorArchivo Then
NumRow = 1
Dim RowNoEncontrados As String = ""
Dim NumAgregados As Integer = 0
For Each Row As DataRow In dt.Rows
Dim Cantidad As Decimal = Row("Cantidad").ToString.ToDecimal
Dim UM As String = Row("UM").ToString
Dim Codigo As String = Row("Código").ToString.Trim.ToUpper
Dim CodigoBarras As String = Row("Codigo Barras").ToString.Trim.ToUpper
Dim ProductoServicio As String = Row("Producto/Servicio").ToString.Trim.ToUpper
Dim PrecioUnitario As Decimal = Row("Precio Unitario").ToString.ToDecimal
Dim Proyecto As String = Row("Proyecto").ToString.Trim.ToUpper
Dim Observaciones As String = Row("Observaciones").ToString.Trim.ToUpper
Dim TiempoEntrega As String = Row("Tiempo Entrega").ToString
Dim CvePS As Integer = 0
Dim CveUM As Integer = 0
Dim CodigoPS As Integer = 0
Dim DrProyecto As DataRow
Dim SubProyecto As String = ""
Dim CveProyecto As Integer = 0
Dim CveSubProyecto As Integer = 0
NumRow = NumRow + 1
If Proyecto <> "" Then
Dim DtSubProyecto As DataTable = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa)
DtSubProyecto.CaseSensitive = False
DrProyecto = DtSubProyecto.FiltroPrimero($"(SubProyecto) = '{Proyecto}'")
If DrProyecto IsNot Nothing Then
CveSubProyecto = DrProyecto("CveSubProyecto").ToString.ToEntero
CveProyecto = DrProyecto("CveProyecto").ToString.ToEntero
SubProyecto = DrProyecto("SubProyecto").ToString
End If
Else
CveProyecto = -1
CveSubProyecto = -1
End If
If Codigo <> "" Then
Dim StrArray() As String = GetPS("Codigo", Codigo).Split("|"c)
If StrArray.Length > 0 Then
If CBool(StrArray(0)) = True Then
CvePS = StrArray(1).ToEntero
Else
RowNoEncontrados &= StrArray(1) & "<\BR>"
End If
End If
ElseIf CodigoBarras <> "" Then
Dim StrArray() As String = GetPS("CodigoBarras", CodigoBarras).Split("|"c)
If StrArray.Length > 0 Then
If CBool(StrArray(0)) = True Then
CvePS = StrArray(1).ToEntero
Else
RowNoEncontrados &= StrArray(1) & "<\BR>"
End If
End If
ElseIf ProductoServicio <> "" Then
Dim StrArray() As String = GetPS("PS", ProductoServicio).Split("|"c)
If StrArray.Length > 0 Then
If CBool(StrArray(0)) = True Then
CvePS = StrArray(1).ToEntero
Else
RowNoEncontrados &= StrArray(1) & "<\BR>"
End If
End If
Else
RowNoEncontrados &= "<\BR>&nbsp;&nbsp;&nbsp;&nbsp;- En la fila " & NumRow & " no se especificó código, código de barras ó descripción."
End If
If CvePS > 0 Then
CveUM = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveUnidadMedida", $"CvePS = '{CvePS}'").ToString.ToEntero
AgregarProductoServicio(Cantidad, CveUM, UM, -1, "",
CvePS, HdnPS.Value, Observaciones, PrecioUnitario, HdnDescuento.Value.ToDecimal,
CveProyecto, Proyecto, CveSubProyecto, SubProyecto,
TiempoEntrega:=TiempoEntrega)
'If TmpDT IsNot Nothing Then
' Dim dr As DataRow = TmpDT.NewRow
' TxtCantidad.Text = Cantidad.ToString
' DdlPS.SelectedValue = CvePS.ToString
' DdlPS_SelectedIndexChanged(Nothing, Nothing)
' DdlUnidadMedida.SelectedValueExist(CveUM.ToString)
' TxtObsPS.Text = Observaciones
' DdlProyecto.SelectedValue = CveProyecto.ToString
' DdlProyecto_SelectedIndexChanged(Nothing, Nothing)
' DdlSubProyecto.SelectedValue = CveSubProyecto.ToString
' TxtPrecio.Text = PrecioUnitario.ToString
' TxtTiempoEntrega.Text = TiempoEntrega.ToString
' RegistraScript("Recalcula();")
' LbAgregar_Click(Nothing, Nothing)
' NumAgregados = NumAgregados + 1
'End If
End If
Next
CalculaTotalesVenta()
If RowNoEncontrados.Length > 0 Then
Alert("Los siguientes productos o servicios no se encontraron en la Base de Datos.<\BR>" & RowNoEncontrados, TipoMensaje.MsgAdvertencia)
Else
Alert("Se cargaron " & NumAgregados & " productos o servicios correctamente.")
End If
End If
End If
dt.Dispose()
End Sub
Private Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcel.Click
If TxtExcel.getfiles().Archivos.Count > 0 Then
Dim file As Archivo = TxtExcel.getfiles().Archivos(0)
Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & file.patch
Dim Tipo As String = If(file.Extencion.Contiene("xlsx", "xlsx", "xlsm", "xlsb"), "EXCEL", "CSV")
CargarArchivo(Directorio, file.filename, Tipo)
Else
Alert("No existe el archivo. Favor de subir un archivo excel a la plataforma.", TipoMensaje.MsgError)
End If
End Sub
Private Function GetPS(Opt As String, Valor As String) As String
Dim StrReturn As String = String.Empty
Dim CvePS As Integer = 0
CvePS = GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CvePS", Opt & " = '" & Valor & "'").ToString.ToEntero
If CvePS > 0 Then
StrReturn = "True|" & CvePS.ToString
Else
StrReturn = "False|&nbsp;&nbsp;&nbsp;&nbsp;- 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("<html xmlns=""http://www.w3.org/1999/xhtml""> ")
strBody.Append("<head> ")
strBody.Append(" <style type=""text/css""> ")
strBody.Append(" body ")
strBody.Append(" { ")
strBody.Append(" margin:0px; ")
strBody.Append(" padding:0px 0px 0px 0px; ")
strBody.Append(" font-family: Verdana, Arial, Helvetica, sans-serif; ")
strBody.Append(" font-size: 10px; ")
strBody.Append(" background-color:#F0F0F0; ")
strBody.Append(" } ")
strBody.Append(" a.Texto ")
strBody.Append(" { ")
strBody.Append(" font-size:11px; ")
strBody.Append(" background-color:#F7F6F3; ")
strBody.Append(" text-decoration:none; ")
strBody.Append(" font-weight:bold; ")
strBody.Append(" } ")
strBody.Append(" .Texto ")
strBody.Append(" { ")
strBody.Append(" background-color:#F7F6F3; color:Black; font-family:Verdana; font-size:10px; text-align:center; vertical-align:middle; height:20px;")
strBody.Append(" } ")
strBody.Append(" .TextoAlterno ")
strBody.Append(" { ")
strBody.Append(" background-color:White; color:Black; font-family:Verdana; font-size:10px; text-align:center; ")
strBody.Append(" vertical-align:middle; height:20px;")
strBody.Append(" } ")
strBody.Append(" .BarraIdentidad ")
strBody.Append(" { ")
strBody.Append(" color:#FFFFFF; ")
strBody.Append(" background:#F0F0F0; ")
strBody.Append(" font-weight:bold; ")
strBody.Append(" font-size:19px; ")
strBody.Append(" font-style:oblique; ")
strBody.Append(" } ")
strBody.Append(" .Titulos ")
strBody.Append(" { ")
strBody.Append(" background-color: white;")
strBody.Append(" color:#666; ")
strBody.Append(" font-family:Verdana; font-size:18px; text-align:center; ")
strBody.Append(" vertical-align:middle; font-weight:bold; height:30px; ")
strBody.Append(" text-decoration:none; ")
strBody.Append(" } ")
strBody.Append(" .Verde {color: #00CC00;} ")
strBody.Append(" .Negro {color: #000000;} ")
strBody.Append(" .Rojo {color: #FF0000;} ")
strBody.Append(" </style> ")
strBody.Append("</head> ")
strBody.Append("<body> ")
strBody.AppendFormat("<div class='Titulos'>Favor de surtir el siguiente {0}</div><br>", DdlTipoComprobante.SelectedItem.Text)
strBody.AppendFormat(" <div id=""C_divOC"" style=""width: 630px""> <fieldset> <legend><b>Datos de {0}</b></legend> ", DdlTipoComprobante.SelectedItem.Text)
strBody.Append(" <table border=""0"" cellpadding=""0"" cellspacing=""0"" width=""100%""> ")
strBody.Append(" <tr style=""height: 22px""> ")
strBody.AppendFormat(" <td style=""width: 90px""> Serie-Folio:</td><td style=""width: 125px""><b>{0}-{1}</b></td> ", LblSerie.Text, TxtFolio.Text)
strBody.Append(" </tr> ")
strBody.Append(" <tr style=""height: 22px""> ")
strBody.AppendFormat(" <td style=""width: 90px""> Empresa:</td><td colspan=""3""><b>{0}</b></td> ", UsuarioActual.Empresa.Empresa)
strBody.Append(" </tr> ")
strBody.Append(" <tr style=""height: 22px""> ")
strBody.AppendFormat(" <td style=""width: 90px""> Cliente:</td><td colspan=""3""><b>{0}</b></td> ", LblCliente.Text)
strBody.Append(" </tr> ")
strBody.Append(" <tr style=""height: 22px""> ")
strBody.AppendFormat(" <td style=""width: 90px""> Sucursal:</td><td colspan=""3""><b>{0}</b></td> ", DdlSubProyectoDatos.SelectedItem.Text)
strBody.Append(" </tr> ")
strBody.Append(" <tr style=""height: 22px""> ")
strBody.AppendFormat(" <td style=""width: 90px""> Fecha:</td><td colspan=""3""><b>{0}</b></td> ", TxtFecha.Text)
strBody.Append(" </tr> ")
strBody.Append(" </table> ")
strBody.Append(" </fieldset> ")
strBody.Append(" </div> ")
'Cargo el detalle
strBody.Append(" <div style='width: 630px'> ")
strBody.Append(" <fieldset> ")
strBody.Append(" <legend>Productos/Servicios</legend> ")
strBody.Append(" <table width=""610px""> <tr style='background-color:gray;color:White;font-family:Verdana;font-size:10px;text-align:center;vertical-align:middle;font-weight:bold;height:20px;text-decoration:none;'><th scope='col' style='width: 50px'>Cantidad</th><th scope='col' style='width: 50px'>Unidad</th><th scope='col' style='width: 225px'>Producto/Servicio</th><th scope='col' style='width: 225px'>No. Serie</th>")
strBody.Append(" <th scope='col' style='width: 100px'>Proyecto</th><th scope='col' style='width: 85px'>Precio</th></tr>")
For Each dr As DataRow In TmpDT.Rows
strBody.AppendFormat("<tr class='Texto'><td style='width:50px;'>{0}</td><td style='width:50px;'>{1}</td><td align='left' style='width:225px;'>{2}</td><td style='width:100px;'>{3}</td><td style='width:100px;'>{4}</td><td style='width:85px;'>{5}</td></tr>",
dr("Cantidad").ToString().FormatoNumero(), dr("UM").ToString(), dr("PS").ToString(), dr("Obs").ToString(), dr("SubProyecto").ToString(), dr("PU").ToString().FormatoNumero())
Next
strBody.Append(" </table> ")
strBody.Append(" </fieldset> ")
strBody.Append(" </div> ")
strBody.Append("</body></html>")
Return strBody.ToString
End Function
#End Region
#Region " CANCELAR PEDIDO "
Protected Sub LBCancelarPedido_Click(sender As Object, e As EventArgs)
Dim ObjVentas As New ClsVentas
If ObjVentas.CancelarPedido(CveVenta, UsuarioActual.CveEmpresa) Then
Alert("El pedido se canceló correctamente.", TipoMensaje.MsgInformacion)
'DdlEstatus.Items.Clear()
'DdlEstatus.Items.Insert(0, New ListItem(GlobalDTEstatusFactura.FiltroPrimeroValor("EstatusFactura", "CveEstatusFactura = 14"), "14"))
'DdlEstatus.SelectedValue = "14"
'DdlEstatus.DataBind()
'DdlEstatus.Enabled = False
CveEstatus = 14
UpEstatus.Update()
End If
ObjVentas.Dispose()
End Sub
#End Region
#Region "D E V O L U C I O N D E P E D I D O "
Private Sub CargaFacturaDevolucionPedido()
Dim CveVenta As Integer = Me.CveVenta
Dim MovInv As Integer = ViewState("MovInv").ToString.ToEntero
Dim ObjVentas As New ClsVentas()
Dim ObjInventarios As New ClsInventarios
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then
Dim DbRowVenta As DataRow = ObjVentas.DtResultados.Rows(0)
'CargaCliente
Dim CveCliente As Integer = DbRowVenta("CveCliente").ToString.ToEntero
If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then
Exit Sub
ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then
Exit Sub
End If
HdnCveCliente.Value = CveCliente.ToString
ViewState("CveCliente") = CveCliente
CargaCliente(CveCliente, -1) 'Estatus activo, se requiere para cargar una factura en la que el cliente a sido eliminado
TxtFecha.Text = Now.ToShortDateString
'TxtSubTotal.Text = DbRowVenta("SubTotal").ToString.FormatoNumero(2)
'LblDescuentos.Text = DbRowVenta("Descuento").ToString.FormatoNumero(2)
'LblAmortizacion.Text = DbRowVenta("Amortizacion").ToString.FormatoNumero(2)
'TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2)
'TxtIVA.Text = DbRowVenta("IVA").ToString.FormatoNumero(2)
'TxtRetIVA.Text = DbRowVenta("RetIVA").ToString.FormatoNumero(2)
'TxtRetISR.Text = DbRowVenta("RetISR").ToString.FormatoNumero(2)
'TxtIEPS.Text = DbRowVenta("IEPS").ToString.FormatoNumero(2)
CveContrato = DbRowVenta("CveContrato").ToString.ToEntero
TxtMotivoDescuento.Text = DbRowVenta("MotivoDescuento").ToString
TxtObsFact.Text = DbRowVenta("Observaciones").ToString
HdnIVAOriginal.Value = TxtIVA.Text
TxtPedidoContrato.Text = DbRowVenta("PedidoContrato").ToString
TxtPedidoContrato.Enabled = False
TxtOrdenCompra.Text = DbRowVenta("OrdenCompra").ToString
TxtOrdenCompra.Enabled = False
TxtObsAlmacen.Text = DbRowVenta("ObservacionesAlmacen").ToString
TxtFechaEjecucion.Text = DbRowVenta("FechaEjecucion").ToString.ToDateTime.ToString("dd/MM/yyyy")
'DdlSucursalEjecucion.SelectedValueExist(DbRowVenta("CveSucursalEjecucion").ToString)
'DdlSucursalCobranza.SelectedValueExist(DbRowVenta("CveSucursalCobranza").ToString)
DdlSucursalCliente.SelectedValueExist(DbRowVenta("CveClienteSucursal").ToString)
'DdlSucursal.SelectedValueExist(DbRowVenta("CveSucursal").ToString)
DdlSubProyectoDatos.SelectedValueExist(DbRowVenta("CveSubProyecto").ToString)
DdlSubProyectoCobranza.SelectedValueExist(DbRowVenta("CveSubProyectoCobranza").ToString)
DdlSubProyectoEjecucion.SelectedValueExist(DbRowVenta("CveSubProyectoEjecucion").ToString)
CargaClienteSucursal(DbRowVenta("CveClienteSucursal").ToString.ToEntero)
DdlMetodoPago33.SelectedIndex = 1
DdlFormaPago33.SelectedIndex = 1
DdlUsoCFDI.SelectedIndex = 1
RequiereAlmacenDestino = True
DdlAlmacenAsignado.Items.Clear()
DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
DdlAlmacenAsignado.SelectedValue = "-1"
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.Items.Insert(0, New ListItem("Almacen", DbRowVenta("CveAlmacenTraspasoOrigen").ToString))
DdlAlmacenAsignado.SelectedValueExist(DbRowVenta("CveAlmacenTraspasoOrigen").ToString)
RequiereAlmacenOrigen = True
DdlAlmacenOrigen.Items.Clear()
DdlAlmacenOrigen.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
DdlAlmacenOrigen.SelectedValue = "-1"
DdlAlmacenOrigen.DataBind()
DdlAlmacenOrigen.Items.Insert(0, New ListItem("Almacen", DbRowVenta("CveAlmacenTraspasoDestino").ToString))
DdlAlmacenOrigen.SelectedValueExist(DbRowVenta("CveAlmacenTraspasoDestino").ToString)
If ObjInventarios.GetMovimientosDetalle(MovInv, UsuarioActual.CveEmpresa) AndAlso ObjInventarios.DtResultados.Rows.Count > 0 Then
Dim Cons As Integer = 1
TmpDT.Clear()
Dim Cantidad = 0.0D, PU = 0.0D, Descuento = 0.0D
Dim Filtro As String = ""
If ViewState("CveMovimientoDetalle").ToString.ToEntero > 0 Then
Filtro = $"AND CveMovimientoDetalle = {ViewState("CveMovimientoDetalle").ToString.ToEntero}"
End If
For Each dr As DataRow In ObjInventarios.DtResultados.FiltraParametros($"ExistenciaPedido > 0 {Filtro}").Rows
AgregarProductoServicio(dr("Cantidad").ToString.ToDecimal, dr("CveUM").ToString.ToEntero, dr("UnidadMedida").ToString, dr("CveClasificacion").ToString.ToEntero, dr("Clasificacion").ToString,
dr("CvePS").ToString.ToEntero, dr("PS").ToString, dr("SerieLote").ToString, dr("PU").ToString.ToDecimal, 0.0D,
dr("CveProyecto").ToString.ToEntero, dr("Proyecto").ToString, dr("CveSubProyecto").ToString.ToEntero, dr("SubProyecto").ToString,
CveMovimientoDetallePedido:=dr("CveMovimientoDetalle").ToString.ToEntero)
Next
CalculaTotalesVenta()
End If
'Ocultamos los botones Editar, Clonar y Ordenar
GvPS.Columns(17).Visible = False
GvPS.Columns(19).Visible = False
GvPS.Columns(20).Visible = False
DdlVendedor.SelectedValue = DbRowVenta("CveVendedor").ToString
DdlTipoComprobante.Enabled = False
'DdlSucursal.Enabled = False
DdlSubProyectoDatos.Enabled = False
BtnBuscarCliente.Enabled = False
'TxtDocto.Enabled = False
'DESACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto disabled")
TxtCodigo.ReadOnly = True
ChkEnviarFactura.Enabled = False
TxtCantidad.Enabled = False
DdlClasificacion.Enabled = False
DdlPS.Enabled = False
TxtObsPS.Enabled = False
DdlProyecto.Enabled = False
DdlSubProyecto.Enabled = False
TxtPrecio.Enabled = False
ImgDescPU.Attributes.Clear()
ImgDescTotal.Attributes.Clear()
ImgDescConcepto.Attributes.Clear()
LbAgregar.Enabled = False
LnkAgregarPyME.Enabled = False
divcondicionespago.Visible = False
BtnEmitirImprimir.Text = "Guardar"
BtnEmitirImprimir.Visible = True
UpFacturar.Update()
End If
End If
ObjVentas.Dispose()
ObjInventarios.Dispose()
UpFacturar.Update()
UpPS.Update()
UpCliente.Update()
UpEstatus.Update()
End Sub
#End Region
#Region " FLETES "
Private Sub CargaFletes()
If UsuarioActual.CveEmpresa <> 125 Or CveVenta > 0 Then
Exit Sub
End If
HLModalFletes.Visible = True
Dim ObjVentas As New ClsVentas
If ObjVentas.GetFletes(UsuarioActual.CveEmpresa) Then
GVFletes.DataSource = ObjVentas.DtResultados
GVFletes.DataBind()
End If
UpFletes.Update()
ObjVentas.Dispose()
End Sub
#End Region
#Region "A G R E G A R P S M O D A L"
Private Sub CargaMetodosPSModal()
CargaTipoProductos()
CargaClasificacionesPS()
'CargarMetodosInv()
CargaUnidadesMedida()
CargarMarcas()
End Sub
'Private Sub CargarMetodosInv()
' DdlMetodoInv.Items.Clear()
' DdlMetodoInv.DataSource = GlobalDTInvMetodosInventario
' DdlMetodoInv.DataBind()
' DdlMetodoInv.Items.Insert(0, New ListItem("Seleccione", "-1"))
'End Sub
Private Sub CargaClasificacionesDetalles()
DdlTipo.Items.Clear()
DdlTipo.DataSource = GlobalDTClasificacionesDetalle(UsuarioActual.CveEmpresa)
DdlTipo.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlTipo.DataBind()
End Sub
Private Sub CargaClasificacionesPS()
If UsuarioActual.Empresa.UsaAC Then
DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
Else
DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion")
'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion")
End If
'BLOQUEA DDL CLASIFICACION
If UsuarioActual.Empresa.Funcionalidad(121) = "1" Then
If Not UsuarioActual.TienePermisoProceso(147) Then
DdlClasificacionPS.Enabled = False
'DdlTipo.Enabled = False
End If
End If
DdlClasificacionPS.DataBind()
'DdlTipo.DataBind()
End Sub
Private Sub CargaTipoProductos()
'BLOQUEA DDL TIPO PRODUCTO
If UsuarioActual.Empresa.Funcionalidad(122) = "1" Then
If Not UsuarioActual.TienePermisoProceso(149) Then
DdlTipoPS.Enabled = False
DdlTipoPS.SelectedValueExist("2")
End If
End If
End Sub
Private Sub CargaUnidadesMedida()
DdlUnidadMedidaPS.Items.Clear()
DdlUnidadMedidaPS.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
DdlUnidadMedidaPS.DataBind()
DdlUnidadMedidaPS.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub CargarMarcas()
If UsuarioActual.Empresa.Funcionalidad(130) = "1" Then
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then
DivMarcaPSDes.Visible = True
Else
DivMarca.Visible = True
End If
DdlMarca.Items.Clear()
DdlMarcaPSDes.Items.Clear()
Dim ObjMarcas As New ClsProductosServicios
ObjMarcas.GetMarcas(UsuarioActual.CveEmpresa)
DdlMarca.DataSource = ObjMarcas.DtResultados
DdlMarcaPSDes.DataSource = ObjMarcas.DtResultados
ObjMarcas.Dispose()
DdlMarca.DataBind()
DdlMarcaPSDes.DataBind()
End If
DdlMarca.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlMarcaPSDes.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub BtnModalAddPS_Click(sender As Object, e As EventArgs) Handles BtnModalAddPS.Click
TxtCodigoPS.Text = ""
TxtCodigoBarrasPS.Text = ""
TxtPS.Text = ""
TxtModelo.Text = ""
TxtAdicional.Text = ""
DdlTipoPS.SelectedIndex = 0
DdlUnidadMedidaPS.SelectedIndex = 0
DdlClasificacionPS.SelectedIndex = 0
'DdlMetodoInv.SelectedIndex = 0
ChkRequiereSerie.Checked = False
DdlMarca.SelectedIndex = 0
DdlMarcaPSDes.SelectedIndex = 0
CargaClasificacionesDetalles()
UpAddPS.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddPS"))
End Sub
Private Sub LbAddPS_Click(sender As Object, e As EventArgs) Handles LbAddPS.Click
If (TxtCodigoPS.Text = TxtCodigoBarrasPS.Text AndAlso TxtCodigoPS.Text <> "") Then
Alert("Los codigos no pueden ser iguales. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return
End If
If UsuarioActual.Empresa.Funcionalidad(265) = "1" And TxtCodigoPS.Text = "" Then
Alert("El código es requerido.", TipoMensaje.MsgAdvertencia)
Return
End If
If TxtCodigoPS.Text <> "" AndAlso Not TxtCodigoPS.Text.Length >= 3 Then
Alert("El código tiene que que tener una longitud de al menos 3 digitos.", TipoMensaje.MsgAdvertencia)
Return
End If
Dim CveMetodoInventario As Integer = 0
If ChkRequiereSerie.Checked Then CveMetodoInventario = 5 Else CveMetodoInventario = 1
Dim CveMarca As Integer = 0
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then CveMarca = DdlMarcaPSDes.SelectedValue.ToEntero Else CveMarca = DdlMarca.SelectedValue.ToEntero
Dim ObjProductosServicios As New ClsProductosServicios()
If ObjProductosServicios.AddPS(DdlClasificacionPS.SelectedValue.ToEntero, -1, DdlUnidadMedidaPS.SelectedValue.ToEntero, TxtCodigoPS.Text.Trim, "", TxtCodigoBarrasPS.Text.Trim, TxtPS.Text.Trim, 0, -1, 0, False, 0, False, True, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveMetodoInventario, 0, CveTipoPS:=DdlTipoPS.SelectedValue.ToEntero, CveMarca:=CveMarca, CveSATPS:=DdlSATPS.SelectedValue.ToEntero, CveClasificacionDetalle:=DdlTipo.SelectedValue.ToEntero) > 0 Then
DdlClasificacion.SelectedValueExist(DdlClasificacionPS.SelectedValue.ToEntero)
DdlClasificacion_SelectedIndexChanged(DdlClasificacionPS, e)
'SI ES DDLOST
If UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPS.SelectedValue = ObjProductosServicios.CvePS.ToString
DdlPS.SelectedText = TxtPS.Text.Trim
Else
DdlPS.ddl.Items.Insert(2, New ListItem(TxtPS.Text.Trim, ObjProductosServicios.CvePS.ToString))
DdlPS.ddl.SelectedValueExist(ObjProductosServicios.CvePS)
End If
DdlUnidadMedida.Items.Clear()
DdlUnidadMedida.Items.Insert(0, New ListItem(DdlUnidadMedidaPS.SelectedItem.Text, DdlUnidadMedidaPS.SelectedValue))
DdlUnidadMedida.SelectedValueExist(DdlUnidadMedidaPS.SelectedValue)
HdnPS.Value = TxtPS.Text.Trim
HdnCodigoPS.Value = $"{TxtCodigoPS.Text.Trim}-{TxtPS.Text.Trim}"
HdnTipoPS.Value = DdlTipoPS.SelectedValue
HdnTipoInv.Value = CveMetodoInventario.ToString
HdnAplicaIEPS.Value = "False"
HdnPorcentajeIEPS.Value = "-1"
HdnIVAPS.Value = "0.16"
HdnIVARetAPS.Value = "0"
HdnAsientoContable.Value = "1"
HdnCtaContable.Value = "0"
HdnAplicaParaConcepto.Value = "False"
HdnCodigo.Value = TxtCodigoPS.Text.Trim
End If
ObjProductosServicios.Dispose()
UpPS.Update()
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddPS"))
RecargaGlobal()
End Sub
Private Sub RecargaGlobal()
Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDT)
Hilo.Start()
End Sub
Private Sub GeneraGlobalDT()
Dim ObjPS As New ClsProductosServicios
If (ObjPS.GetPSSimplificado(-1)) Then
Application("GlobalDTPSSimplificado") = ObjPS.DtResultados.AsEnumerable 'Cargamos el GlobalDTPSSimplificado
End If
If ObjPS.GetPSEquivalencias(-1, -1) Then
GlobalDTProductosServiciosEquivalencias(-1, -1) = ObjPS.DtResultados
End If
ObjPS.Dispose()
End Sub
#End Region
#Region "P Y M E"
Private Sub LnkAddVenta_Click(sender As Object, e As EventArgs) Handles LnkAddVenta.Click
Modalidad = "A"
LnkAgregarPyME.Text = "Agregar"
TxtCantidadPyME.Text = ""
TxtObsPyME.Text = ""
TxtPrecioPyME.Text = "0.00"
LblTotalPyME.Text = "0.00"
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPSPyME.SelectedValue = "-1"
Else
DdlPSPyME.SelectedValue = ""
DdlPSPyME.SelectedText = ""
End If
DdlClasificacionPyME.SelectedIndex = -1
DdlProyectoPyME.SelectedIndex = -1
DdlSubProyectoPyME.SelectedIndex = -1
DdlUMPyME.Items.Clear()
ChkAgregar.Checked = True
divagregrarotrops.Visible = True
UpVenta.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta"))
End Sub
Public Sub Edit_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Modalidad = "U"
Index = GvRow.DataKey("Consec").ToEntero
LnkAgregarPyME.Text = "Actualizar"
DdlClasificacionPyME.SelectedValueExist(GvRow.DataKey("CveClasificacion"))
CargaPSPyME(DdlClasificacionPyME.SelectedValue.ToEntero, DdlPSPyME)
UpClasificacionPyME.Update()
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPSPyME.SelectedValue = GvRow.DataKey("CvePS")
Else
DdlPSPyME.SelectedValue = GvRow.DataKey("CvePS")
DdlPSPyME.SelectedText = GvRow.DataKey("PS")
End If
DdlPSPyMEIndexChange()
DdlProyectoPyME.SelectedValueExist(GvRow.DataKey("CveProyecto"))
CargaSubProyecto()
DdlSubProyectoPyME.SelectedValueExist(GvRow.DataKey("CveSubProyecto"))
DdlUMPyME.SelectedValueExist(GvRow.DataKey("CveUM"))
TxtCantidadPyME.Text = GvRow.DataKey("Cantidad")
TxtObsPyME.Text = GvRow.DataKey("Obs")
TxtPrecioPyME.Text = GvRow.DataKey("PU")
TotAnt = GvRow.DataKey("Total").ToDecimal
LblTotalPyME.Text = GvRow.DataKey("Total")
ChkAgregar.Checked = False
divagregrarotrops.Visible = False
UpVenta.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta"), "EdicionVenta")
End Sub
Private Sub LnkAgregarPyME_Click(sender As Object, e As EventArgs) Handles LnkAgregarPyME.Click
AgregarPSPYME()
If ChkAgregar.Checked = True And Modalidad = "A" Then
LnkAgregarPyME.Text = "Agregar"
TxtCantidadPyME.Text = ""
TxtObsPyME.Text = ""
TxtPrecioPyME.Text = "0.00"
LblTotalPyME.Text = "0.00"
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPSPyME.SelectedValue = "-1"
Else
DdlPSPyME.SelectedValue = ""
DdlPSPyME.SelectedText = ""
End If
DdlClasificacionPyME.SelectedIndex = -1
DdlProyectoPyME.SelectedIndex = -1
DdlSubProyectoPyME.SelectedIndex = -1
DdlUMPyME.Items.Clear()
UpVenta.Update()
RegistraScript("displayToastr(1);", "display")
Else
If Modalidad = "A" Then RegistraScript("displayToastr(1);", "display1")
If Modalidad = "U" Then RegistraScript("displayToastr(2);", "display2")
RegistraScript("ClosePopup();", "AddUpdatePS")
End If
End Sub
Private Sub DdlPSPyME_selectedindexchange(sender As Object, e As EventArgs) Handles DdlPSPyME.selectedindexchange
DdlPSPyMEIndexChange()
End Sub
Private Sub CargaPSPyME(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost)
DdlPSPyME.setEsWebService(If(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1", True, False))
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
Objeto.ddl.Items.Clear()
'Objeto.ddl.DataSource = GlobalDTProductosServicios(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1)
Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1)
Objeto.ddl.DataBind()
Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2"))
Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1"))
Else
DdlPSPyME.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue)
End If
End Sub
Private Sub DdlPSPyMEIndexChange()
If CveCliente > 0 OrElse DdlPSPyME.SelectedValue = "-2" Then
If DdlPSPyME.SelectedValue IsNot Nothing AndAlso DdlPSPyME.SelectedValue.ToEntero > 0 Then
Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPSPyME.SelectedValue.ToEntero).FiltroPrimero("")
If drPS IsNot Nothing Then
'HdnUnidadMedida.Value = PS.Rows(0)("CveUnidadMedida").ToString
HdnPS.Value = drPS("PS").ToString
HdnCodigoPS.Value = drPS("PSCodigo").ToString
HdnTipoPS.Value = drPS("CveTipoPS").ToString
HdnTipoInv.Value = drPS("Inv_CveMetodoInventario").ToString
HdnAplicaIEPS.Value = drPS("AplicaIEPS").ToString
HdnPorcentajeIEPS.Value = drPS("IEPSPorcentaje").ToString
DdlUMPyME.Items.Clear()
If UsuarioActual.Empresa.UsaInventarios Then
DdlUMPyME.DataSource = GlobalDTProductosServiciosEquivalencias(DdlPSPyME.SelectedValue.ToEntero, -1)
Else
DdlUMPyME.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
End If
DdlUMPyME.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlUMPyME.SelectedValue = "-1"
DdlUMPyME.DataBind()
DdlUMPyME.SelectedValueExist(drPS("CveUnidadMedida").ToString)
'LblUnidadMedida.Text = PS.Rows(0)("UnidadMedida").ToString
TxtPrecioPyME.Text = drPS("Precio").ToString.FormatoNumero(2).Replace(","c, "")
If UsuarioActual.CveEmpresa = 80 Then
'busca el precio de la sucursal
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSSucursales(DdlPSPyME.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero) Then
Dim dtt As DataTable = ObjPS.DtResultados
Dim drPrecio As DataRow = dtt.FiltroPrimero("")
If drPrecio IsNot Nothing Then
TxtPrecioPyME.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4")
End If
dtt.Dispose()
End If
ObjPS.Dispose()
End If
'If IsNumeric(TxtCantidad.Text.Trim) Then
' LblTotalPyME.Text = (TxtCantidad.Text.Trim.ToDouble * TxtPrecio.Text.ToDouble).ToString.FormatoNumero(2)
'End If
HdnIVAPS.Value = If(drPS("IVA").ToString = "-1", ViewState("IVA"), drPS("IVA").ToString).ToString
HdnIVARetAPS.Value = drPS("RetIVA").ToString
HdnAsientoContable.Value = drPS("AsientoContableVentas").ToString
HdnCtaContable.Value = drPS("IdCtaContVentas").ToString
HdnAplicaParaConcepto.Value = drPS("AplicaParaConcepto").ToString
HdnCodigo.Value = drPS("Codigo").ToString
If DdlClasificacionPyME.SelectedIndex = 0 Then
If drPS("CveClasificacion").ToString IsNot Nothing Then
DdlClasificacionPyME.SelectedValueExist(drPS("CveClasificacion").ToString)
Else
Alert("El Productos/Servicio no tiene asignada una Clasificación.")
End If
End If
End If
'RegistraScript("Recalcula();")
'PS.Dispose()
ElseIf DdlPSPyME.SelectedValue = "-2" Then
CargaPSPyME(-1, DdlPSPyME)
End If
Else
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")")
End If
UpVenta.Update()
End Sub
Private Sub DdlClasificacionPyME_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlClasificacionPyME.SelectedIndexChanged
CargaPSPyME(DdlClasificacionPyME.SelectedValue.ToEntero, DdlPSPyME)
UpClasificacionPyME.Update()
End Sub
#End Region
#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, factura As Modelos.Factura) As Boolean
If Not (UsuarioActual.Empresa.UsaInventarios AndAlso CveAlmacenExistenciasContrato > 0) Then
Return True
End If
Dim CveMovimientoSalidaConsignacion = -1
Dim CveMovimientoEntradaGeneral = -1
Dim CveMovimientoSalidaGeneral = -1
'MOVIMIENTO DE SALIDA POR TRASPASO DEL ALMACEN DE CONSIGNACION
CveMovimientoSalidaConsignacion = ObjInventario.AddMovimiento(CveAlmacenExistenciasContrato, 8, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1)
If CveMovimientoSalidaConsignacion > 0 Then
Dim CveProducto As Integer
Dim CveUnidad As Integer
Dim Cantidad As Double
Dim Existencia As Double
For Each Dr As DataRow In TmpDT.Rows
CveProducto = Dr("CvePS").ToString.ToEntero
CveUnidad = Dr("CveUM").ToString.ToEntero
Cantidad = Dr("Cantidad").ToString.ToDouble
If Not CveProducto > 0 Then
Return False
End If
If Dr("CveTipoInvPS").ToString.ToEntero = 5 Then
For Each Dr2 As DataRow In DtContratosSerieDetalle.FiltraParametros($"ConsecId = {Dr("CveContratoDetalle")}").Rows
Existencia = ObjInventario.GetExistenciasPS(CveProducto, CveUnidad, factura.CveEmpresa, CveAlmacenExistenciasContrato, SerieLote:=Dr2("Serie").ToString, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ExcluyeAdelantado:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1)
If Existencia < 1 Then
Return False
End If
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaConsignacion, 1, CveUnidad, CveProducto, 0, -1, SerieLote:=Dr2("Serie").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then
Return False
End If
Next
Else
Existencia = ObjInventario.GetExistenciasPS(CveProducto, CveUnidad, factura.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ExcluyeAdelantado:=1, RestringirAlmacenes:=1, ExcluyeApartados:=1)
If Existencia < Cantidad Then
Return False
End If
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaConsignacion, Cantidad, CveUnidad, CveProducto, 0, -1, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then
Return False
End If
End If
Next
Else
Return False
End If
'ENTRADA POR TRASPASO A GENERAL
CveMovimientoEntradaGeneral = ObjInventario.AddMovimiento(CveAlmacenOrigenContrato, 9, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1, CveMovimientoRelacionado:=CveMovimientoSalidaConsignacion)
If CveMovimientoEntradaGeneral > 0 Then
If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaConsignacion, UsuarioActual.CveEmpresa) Then
For Each Dr As DataRow In ObjInventario.DtResultados.Rows
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaGeneral, Dr("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, Dr("CveSeccionAlmacen").ToString.ToEntero, Dr("SerieLote").ToString, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then
Return False
End If
Next
End If
Else
Return False
End If
'SALIDA GENERAL
CveMovimientoEntradaGeneral = ObjInventario.AddMovimiento(CveAlmacenOrigenContrato, 3, 1, factura.Fecha, -1, factura.CveUsuario, factura.CveEmpresa, -1, factura.CveVenta, -1, -1)
If CveMovimientoEntradaGeneral > 0 Then
If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaConsignacion, UsuarioActual.CveEmpresa) Then
For Each Dr As DataRow In ObjInventario.DtResultados.Rows
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaGeneral, Dr("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, Dr("CveSeccionAlmacen").ToString.ToEntero, Dr("SerieLote").ToString, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then
Return False
End If
Next
End If
Else
Return False
End If
Return True
End Function
#Region " AGREGA POR SERIE/LOTE "
Private Sub CreaConsignacionSerieDetalle()
If DtContratosSerieDetalle Is Nothing Then
DtContratosSerieDetalle = New DataTable
DtContratosSerieDetalle.Columns.Add("Consec", GetType(Integer))
DtContratosSerieDetalle.Columns.Add("ConsecId", GetType(Integer))
DtContratosSerieDetalle.Columns.Add("CvePS", GetType(Integer))
DtContratosSerieDetalle.Columns.Add("CveUM", GetType(Integer))
DtContratosSerieDetalle.Columns.Add("Serie", GetType(String))
Else
DtContratosSerieDetalle.Clear()
End If
End Sub
Protected Sub BtnSerieConsignacion_Click(sender As Object, e As EventArgs)
Dim Argumentos = CType(sender, Button).CommandArgument.Split("°"c)
CveConsecSerieLote = Argumentos(0).ToEntero
CvePSSerieLote = Argumentos(1).ToEntero
CveUMSerieLote = Argumentos(2).ToEntero
LbProducto.Text = Argumentos(3)
LbCantidad.Text = If(Argumentos(4).ToDecimal < 0.0D, 0, Argumentos(4).ToDecimal).FormatoNumero
LimitaCantidadSerieLote = Argumentos(5).ToEntero
CargaSerie()
End Sub
Private Sub CargaSerie(Optional CerrarCompletado As Boolean = False)
RegistraScript("$('#DivSerieConsignacion').modal();", "ModalLote")
GvSerie.DataSource = DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", CveConsecSerieLote), "Consec DESC")
GvSerie.DataBind()
'VALIDA QUE SIGA AGREGANDO
If DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", CveConsecSerieLote)).Rows.Count = LbCantidad.Text.ToEntero And LimitaCantidadSerieLote = 1 Then
BtnAgregarPS.Enabled = False
If CerrarCompletado Then
RegistraScript("$('#DivSerieConsignacion').modal('hide');")
End If
Else
BtnAgregarPS.Enabled = True
End If
UpSerieConsignacion.Update()
TxtSerieLote.Text = ""
TxtSerieLote.Focus()
End Sub
Protected Sub BtnAgregarPS_Click(sender As Object, e As EventArgs)
AgregaSerieLote(TxtSerieLote.Text.Replace(" ", String.Empty))
End Sub
Private Sub AgregaSerieLote(SerieLote As String)
'SerieLote = SerieLote.Trim.Replace(" ", " ")
If SerieLote.Trim = "" Then
Alert("El campo Serie es obligatorio. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim SeriesArreglo = SerieLote.Trim.Split(";"c)
'VALIDACION DE SERIES DUPLICADAS
Dim MensajeAlert As New StringBuilder
Dim DtDuplicado As New DataTable
Dim DtSeriesNuevas As New DataTable
DtSeriesNuevas.Columns.Add("Serie", GetType(String))
'PARA VALIDAR SI LA SERIE ES IGUAL AL CODIGO O CODIGOBARRAS
' Dim dr As DataRow = GlobalDTProductosServicios(UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CvePS = {0}", CvePSSerieLote), "PS")
Dim dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePSSerieLote).FiltroPrimero("", "PS")
For Each SerieRow In SeriesArreglo
SerieRow = SerieRow.ToUpper
DtDuplicado = DtContratosSerieDetalle.FiltraParametros($"ConsecId = {CveConsecSerieLote} AND Serie = '{SerieRow}'")
If DtDuplicado IsNot Nothing AndAlso DtDuplicado.Rows.Count > 0 Then
MensajeAlert.Append($"<br/> El numero de Serie <b>""{SerieRow}""</b> 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($"<br/> El numero de Serie <b>""{SerieRow}""</b> 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($"<br/> El numero de Serie <b>{SerieRow}</b> coincide con el codigo o codigo de barras del producto. Por favor rectifique y vuelva a intentar.")
Continue For
End If
Dim Row = DtSeriesNuevas.NewRow
Row("Serie") = SerieRow
DtSeriesNuevas.Rows.Add(Row)
Next
If MensajeAlert.ToString <> "" Then
Alert(MensajeAlert.ToString, TipoMensaje.MsgAdvertencia)
RegistraScript("playsonidito('142608__autistic-lucario__error.wav')", "Error")
Exit Sub
End If
Dim MensajeSinExistencias As New StringBuilder
Dim ObjInventarios As New ClsInventarios
Dim Index = 0
For Each SerieRow In SeriesArreglo
Dim Row = DtContratosSerieDetalle.NewRow
Index = Index + 1
If Index > LbCantidad.Text.ToEntero And LimitaCantidadSerieLote = 1 Then
MensajeSinExistencias.Append($"Serie: <b>{SerieRow} - En esta serie ocurrió un error por favor de comunicarse con soporte tecnico.</b>. <br/>")
Continue For
End If
'VERIFICA EXISTENCIAS
Dim Existencia = ObjInventarios.GetExistenciasPS(CvePSSerieLote, CveUMSerieLote, UsuarioActual.CveEmpresa, CveAlmacenExistenciasContrato, FechaMovto:=TxtFecha.Text.ToDateTime.ToString("yyyy/MM/dd HH:mm"), SerieLote:=SerieRow)
If Existencia < 1 Then
MensajeSinExistencias.Append($"Serie: <b>{SerieRow}</b>. <br/>")
Continue For
End If
Row("ConsecId") = CveConsecSerieLote
Row("Consec") = DtContratosSerieDetalle.Rows.Count + 1
Row("CvePS") = CvePSSerieLote
Row("CveUM") = CveUMSerieLote
Row("Serie") = SerieRow
DtContratosSerieDetalle.Rows.Add(Row)
Next
ObjInventarios.Dispose()
TxtSerieLote.Text = ""
CargaCantidadSerieGV()
CargaSerie(True)
If MensajeSinExistencias.ToString <> "" Then
Alert($"Las siguientes Series no cuentan con la existencia suficiente por lo cual se omitieron. <br?><br/> {MensajeSinExistencias.ToString}", TipoMensaje.MsgAdvertencia)
RegistraScript("playsonidito('142608__autistic-lucario__error.wav')", "Error")
Else
RegistraScript("playsonidito('beep-07.wav')", "Existo")
End If
End Sub
Protected Sub GvSerie_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvSerie.RowDeleting
Try
Dim keySerieLote As String = e.Keys("Serie").ToString
For Each dr As DataRow In DtContratosSerieDetalle.Rows
If dr("Serie").ToString = keySerieLote Then
dr.Delete()
End If
Next
Catch ex As Exception
Finally
DtContratosSerieDetalle.AcceptChanges()
CargaCantidadSerieGV()
CargaSerie()
End Try
End Sub
Private Sub CargaCantidadSerieGV()
'MODIFICA CANTIDAD DEL GV CONTRATOS
For Each Gvr As GridViewRow In GvContratoDetalles.Rows
If Gvr.DataKey("CvePS").ToEntero = CvePSSerieLote Then
Dim Contador = DtContratosSerieDetalle.FiltraParametros(String.Format("ConsecId = {0}", Gvr.DataKey("CveContratoDetalle"))).Rows.Count
Gvr.FCTextBox("TxtCant").Text = Contador.ToString
UPEstimaciones.Update()
Exit For
End If
Next
End Sub
#End Region
#End Region
#Region " ENVIAR SMS - CONFIRMACION DE TIMBRADO "
Private Function EnviarSMSTimbrado(ByRef ObjEventos As ClsOIEventos) As Integer
'NOTA:
'0 = NO APLICA
'1 = TODO FINO
'2 = ERROR
'3 = SIN CELULAR - PROBLEMA CON EL CELULAR
Dim Mensaje = UsuarioActual.Empresa.Funcionalidad(152)
If Mensaje = "" Then Return 0
Dim Celular = ObjFactura.Cliente.CobranzaTelefono
If Celular.Length <> 10 Then Return 3
'ARMA MENSAJE
'4: VSH Monitoreo aviso de: Factura pendiente {SerieFolio} del {Fecha} por ${Importe} fecha limite de pago {FechaPago} Bancomer 0171426931-{ClienteNombreCorto}
Mensaje = Mensaje.Replace("{SerieFolio}", ObjFactura.SerieFolio)
Mensaje = Mensaje.Replace("{Fecha}", ObjFactura.Fecha.ToString("dd-MMM-yyyy").Replace(".", ""))
Mensaje = Mensaje.Replace("{Importe}", ObjFactura.Total.FormatoNumero)
Mensaje = Mensaje.Replace("{FechaPago}", ObjFactura.FechaPago.ToString("dd-MMM-yyyy").Replace(".", ""))
Mensaje = Mensaje.Replace("{ClienteNombreCorto}", ObjFactura.Cliente.NombreCorto)
If Mensaje = "" Then Return 2
Dim ObjMensaje As New ClsTecnoMovil
If ObjMensaje.EnviarMensajeWS(Celular, Mensaje) Then
If ObjEventos.AddEventoBitacora($"Notificación al cliente via SMS. Mensaje: {Mensaje}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCliente:=ObjFactura.CveCliente, CveVenta:=ObjFactura.CveVenta) Then
End If
Return 1
Else
Return 2
End If
End Function
#End Region
#Region " COMPLEMENTOS PAGO "
Private Sub CargaComplementosPago()
Dim ObjBancos As New ClsBancos
If UsuarioActual.CveRol = 1 Then
GvComplementoPagos.Columns(8).Visible = True
End If
If ObjBancos.GetComplementoPagos(-1, -1, CveVenta, UsuarioActual.CveEmpresa) Then
GvComplementoPagos.DataSource = ObjBancos.DtResultados
End If
ObjBancos.Dispose()
GvComplementoPagos.DataBind()
UpComplementoPagos.Update()
End Sub
Protected Sub GvComplementoPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvComplementoPagos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(2).Text = String.Format("<a class=""texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"" target=""_blank""><i class=""fa fa-ad-excel""></i></a>", 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("<a class=""texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"" target=""_blank""><i class=""fa fa-ad-pdf""></i></a>", 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 <b>Correo de Pago</b> 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 objRH.DocumentacionElectronicaGet(-1, TempCliente, -1, UsuarioActual.CveEmpresa, TipoDocumento, CveVenta) Then
DtDocumentacionCliente = objRH.DtResultados.FiltraParametros("CveDocumentacionElectronica > 0")
DtDocumentacionCliente.Columns.Add("Accion", Type.GetType("System.String"))
DtDocumentacionCliente.Columns.Add("RutaArchivo", Type.GetType("System.String"))
DtDocumentacionCliente.Columns.Add("UpArchivo", Type.GetType("System.String"))
DtDocumentacionCliente.AcceptChanges()
GvDocumentosCliente.DataSource = DtDocumentacionCliente
LiDocumentoCliente.Visible = True
Else
DtDocumentacionCliente = Nothing
GvDocumentosCliente.DataSource = Nothing
End If
objRH.Dispose()
GvDocumentosCliente.DataBind()
UpDocsCliente.Update()
End Sub
Protected Sub LnkUploadDocumentacionCliente_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
IndexDocumentoCliente = GvRow.RowIndex
Dim Documentacion As String = GvRow.DataKey("Documentacion").ToString
AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString
LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion
BtnModalClienteDocumentoCancelar.Visible = True
UpModalTitleUploadDocumentoCliente.Update()
UpModalButtonUploadDocumentoCliente.Update()
RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});")
End Sub
Protected Sub BtnModalClienteDocumentoUpload_Click(sender As Object, e As EventArgs) Handles BtnModalClienteDocumentoUpload.Click
If Not TxtFileCliente.getfiles().Archivos.Count > 0 Then
Alert("Tiene que cargar un archivo", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim FileExtension As String = "-1"
Dim Filesgral As List(Of Archivo) = TxtFileCliente.getfiles().Archivos
Dim Filename As String = ""
For Each fileItem As Archivo In Filesgral
Try
FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
Dim tempArray() As String
tempArray = fileItem.filename.ToString().Split("-".ToCharArray())
If RequiereOC And Not BtnModalClienteDocumentoCancelar.Visible Then
Dim Count = 0
For Each GvRow As GridViewRow In GvDocumentosCliente.Rows
If GvRow.DataKey("Orden").ToEntero = 1 Then
IndexDocumentoCliente = Count
CargaDocumentoOC = True
Exit For
End If
Count = +1
Next
End If
DtDocumentacionCliente(IndexDocumentoCliente)("RutaArchivo") = fileItem.FileUrl
DtDocumentacionCliente(IndexDocumentoCliente)("UpArchivo") = "1"
TxtFileCliente.Text = ""
UpModalUploadClienteDocumento.Update()
Alert("Documento cargado", TipoMensaje.MsgInformacion)
Catch ex As Exception
OnError("Error al cargar archivo", ex)
End Try
Next
GvDocumentosCliente.DataSource = DtDocumentacionCliente
GvDocumentosCliente.DataBind()
DtDocumentacionCliente.AcceptChanges()
UpDocsCliente.Update()
RegistraScript("$('#DivDocsClienteUpload').modal('hide')", "hidemodal3")
End Sub
Private Sub GvDocumentosCliente_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDocumentosCliente.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ArchivoRuta As String = e.Row.DataKey("RutaArchivo")
Dim Adjunto As String = e.Row.DBCampo("Adjunto").ToString
Dim ImgDownLoad As Literal = e.Row.FCLiteral("ImgDownLoad")
Dim Chk As CheckBox = e.Row.FCCheckBox("chkEstatus")
Chk.Checked = If(e.Row.DataKey("Estatus").ToString = "1", True, False)
If ArchivoRuta.Trim.Length > 0 Then
Dim fi As New FileInfo(ArchivoRuta)
Dim linkDescarga As String = ""
If fi.Exists Then
linkDescarga = $"/Temp/{fi.Name}"
ImgDownLoad.Text = String.Format(" <a class='btn btn-circle btn-sm blue' href='{0}' target='_black' ><i class='fa fa-download' title='Descargar documento'></i></a>", 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(" <a class='btn btn-circle btn-sm blue' href='{0}' target='_black' ><i class='fa fa-download' title='Descargar documento'></i></a>", 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(" <a class='btn btn-circle btn-sm blue' href='{0}' target='_black' ><i class='fa fa-download' title='Descargar documento'></i></a>", linkDescarga)
' Else
' ImgDownLoad.Visible = False
' End If
' Else
' ImgDownLoad.Visible = False
' End If
'End If
End If
End Sub
Private Sub GuardaVentaDocumentosCliente(tCveVenta As Integer, ByRef objDocumentacion As ClsEdocumentacion)
If tCveVenta > 0 Then
For Each DRow As DataRow In DtDocumentacionCliente.FiltraParametros("RutaArchivo <> '' ").Rows
Dim CveDocumentacion As Integer = DRow("CveDocumentacion").ToString.ToEntero
Dim Estatus As Integer = DRow("Estatus").ToString.ToEntero
Dim Adjunto As String = DRow("Adjunto").ToString
Dim NombreArchivo As String = ""
Dim ArchivoRuta As String = DRow("RutaArchivo").ToString
If ArchivoRuta.Length > 0 Then Adjunto = ArchivoRuta
Dim Extension As String = Path.GetExtension(Adjunto)
Dim CveDocumentacionElectronica As Integer = objDocumentacion.DocumentacionElectronicaAdd(CveDocumentacion, -1, -1, -1, 1, DRow("Observacion").ToString, Extension, UsuarioActual.CveUsuario, New Date(1900, 1, 1), CveVenta:=tCveVenta)
If CveDocumentacionElectronica <= 0 Then ErrorList.Add("No se pudo registrar el documento ")
NombreArchivo = $"{CveDocumentacionElectronica}{Extension}"
If ArchivoRuta.Length > 0 And NombreArchivo.Length > 0 Then
If Not Directory.Exists($"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\") Then
Directory.CreateDirectory($"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\")
End If
Dim ArchivoExistenteRuta As String = $"{UsuarioActual.Empresa.Ruta}Documentacion\Ventas\{NombreArchivo}"
If File.Exists(ArchivoExistenteRuta) Then File.Delete(ArchivoExistenteRuta)
Try
File.Move(ArchivoRuta, ArchivoExistenteRuta)
Catch ex As Exception
ErrorList.Add("No se pudo guardar el documento de la venta")
Exit For
End Try
End If
Next
End If
End Sub
Protected Sub chkEstatus_CheckedChanged(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, CheckBox).NamingContainer, GridViewRow)
Dim chk As CheckBox = GvRow.FCCheckBox("chkEstatus")
IndexDocumentoCliente = GvRow.RowIndex
If chk.Checked Then
DtDocumentacionCliente(IndexDocumentoCliente)("Estatus") = True
Else
DtDocumentacionCliente(IndexDocumentoCliente)("Estatus") = False
End If
DtDocumentacionCliente.AcceptChanges()
End Sub
Protected Sub CargarArchivosOC(sender As Object, e As EventArgs)
Dim Documentacion As String = ""
RegistraScript("$('#DivDocsCliente').modal({ backdrop: 'static', keyboard: false });", "ModalArchivos")
Dim Count = 0
For Each GvRow As GridViewRow In GvDocumentosCliente.Rows
If GvRow.DataKey("Orden").ToEntero = 1 Then
IndexDocumentoCliente = Count
Documentacion = GvRow.DataKey("Documentacion").ToString
AdjuntoDocumentacion = GvRow.DataKey("Adjunto").ToString
Exit For
End If
Count = +1
Next
LtlModalTitleUploadDocumentoCliente.Text = "Subir " & Documentacion
BtnModalClienteDocumentoCancelar.Visible = False
UpModalTitleUploadDocumentoCliente.Update()
UpModalButtonUploadDocumentoCliente.Update()
RegistraScript("$('#DivDocsClienteUpload').modal({ backdrop: 'static', keyboard: false});", "modalOC")
End Sub
#End Region
#Region " SALDAR VENTA "
Protected Sub BtnSaldarVenta_Click(sender As Object, e As EventArgs)
SaldarVenta()
End Sub
Private Sub SaldarVenta()
'Dim ObjVenta As New ClsVentas
'If ObjVenta.VentasSaldar(CveVenta, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 0, -1, -1, TxtFechaSaldarVenta.Text.ToDate) Then
' Alert("Documento Saldado")
'End If
'ObjVenta.Dispose()
'RegistraScript("$('#ModalSaldarVenta').modal('hide')", "ModalSaldarVentaHidde")
Dim ObjConta As New ClsContabilidad
ObjConta.IniciaTransacSQL()
Dim CvePrePoliza As Integer = 0
Dim MsgError As String = ""
Dim ObjIE As New ClsBancos
Dim FechaUltimaFluctuacion As Date = MinFecha
Dim TipoCambioFluctuacion As Decimal = 1
If ObjIE.GetFluctuacionesBitacora(UsuarioActual.CveEmpresa) Then
If ObjIE.DtResultados.Rows.Count > 0 Then
Dim tFecha As Date = TxtFechaSaldarVenta.Text.ToDate
Dim Fecha As String = String.Format("{0}/{1}/{2}", tFecha.Year, tFecha.Month, tFecha.Day)
Dim drr As DataRow = ObjIE.DtResultados.FiltroPrimero("Fecha < #" & Fecha & "#", "Fecha DESC")
If drr IsNot Nothing Then
FechaUltimaFluctuacion = drr("Fecha").ToString.ToDate
TipoCambioFluctuacion = drr("TipoCambio").ToString.ToDecimal
End If
End If
End If
ObjIE.Dispose()
Dim IdCtaContable As Integer = IdCtaContClientes
Dim CveCuenta As Integer = 0
Dim PorcentajePago As Decimal = SaldoVenta / TxtTotal.Text.ToDecimal
Dim Saldo As Decimal = SaldoVenta
Dim SubTotal As Decimal = PorcentajePago * TxtSubTotal.Text.ToDecimal
Dim IVA As Decimal = PorcentajePago * TxtIVA.Text.ToDecimal
Dim IEPS As Decimal = PorcentajePago * TxtIEPS.Text.ToDecimal
Dim TCVenta As Decimal = TxtTipoCambio.Text.ToDecimal
Dim FechaVenta As Date = TxtFecha.Text.ToDate
Dim FechaPago As Date = TxtFechaSaldarVenta.Text.ToDate
Dim tCveMoneda As Integer = DdlMoneda.SelectedValue.ToEntero
Dim TCPago As Decimal = GlobalTipoCambio(TxtFechaSaldarVenta.Text.ToDate).FormatoNumero(4).ToDecimal
Dim CveConceptoDeduccion As Integer = 211
'si la fecha del documento es anterior a su ultima fluctuación. toma el Tc de la fluctuacion
If tCveMoneda = 2 Then
If FechaVenta < FechaUltimaFluctuacion Then
TCVenta = TipoCambioFluctuacion
End If
End If
'condicionante
Dim ClienteMovto As Boolean = True
Dim SubtotalMovto As Boolean = False
Dim CveConceptoCliente As Integer = 2
Dim ImpuestosMovto As Boolean = False
Dim IdCuentaContableNoDeducible As Integer = 0
Dim SerieFolio As String = LblSerie.Text & "-" & TxtFolio.Text
Dim ConceptoPartida As String = "saldado " & SerieFolio
' Dim CveSubProyecto As Integer = gr.DataKey("CveSubProyecto").ToEntero
If CveConceptoDeduccion = 255 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(266).ToEntero
If CveConceptoDeduccion = 211 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(559).ToEntero
If CveConceptoDeduccion = 263 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.Funcionalidad(537).ToEntero
If CveConceptoDeduccion = 252 Then IdCuentaContableNoDeducible = 0
If CveConceptoDeduccion = 78 Then IdCuentaContableNoDeducible = UsuarioActual.Empresa.IdCuentaOtrosIngresos
If UsuarioActual.CveEmpresa.Contiene(4, 7, 11, 12, 122) Then
ClienteMovto = False : Saldo = Saldo * -1
ImpuestosMovto = True : IVA = IVA * -1
CveConceptoCliente = 1
'falta cuenta incobrable
IdCuentaContableNoDeducible = 3114
End If
Dim UsaComplementaria As Boolean = False
If UsuarioActual.CveEmpresa = 119 Then
UsaComplementaria = True
End If
If MsgError = "" Then
CvePrePoliza = ObjConta.AddPrePolizas("Ventas/Saldarr", 47, SaldoVenta, SaldoVenta, tCveMoneda, TxtFechaSaldarVenta.Text.ToDate, ConceptoPartida, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
If tCveMoneda = 2 Then
IdCtaContable = IdCtaContMonedaExtranjera
Else
IdCtaContable = IdCtaContClientes
End If
If UsaComplementaria AndAlso tCveMoneda = 2 Then
'normal
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, Saldo, SerieFolio, CveConceptoCliente, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContable, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, Saldo), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
'complementaria
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, 0, SerieFolio, 207, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContComplementaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, (Saldo * TCVenta) - Saldo), ImporteME:=Saldo, CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
Else
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ClienteMovto, Saldo, SerieFolio, CveConceptoCliente, ConceptoPartida, FechaPago, IdCtaContable:=IdCtaContable, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, Saldo, Saldo * TCVenta), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
End If
'fluctuación.
If tCveMoneda = 2 Then
Dim ImporteFluctuacion As Decimal = 0
ImporteFluctuacion = Saldo * (TCPago - TCVenta)
If TCPago > TCVenta Then
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, Math.Abs(ImporteFluctuacion), SerieFolio, 64, ConceptoPartida, FechaPago, IdCtaContable:=UsuarioActual.Empresa.IdCuentaGananciaCambiaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=Math.Abs(ImporteFluctuacion), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
Else
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, Math.Abs(ImporteFluctuacion), SerieFolio, 65, ConceptoPartida, FechaPago, IdCtaContable:=UsuarioActual.Empresa.IdCuentaPerdidaCambiaria, CveIE:=-1, IdSegmentoNegocio:=-1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=Math.Abs(ImporteFluctuacion), CveCuenta:=CveCuenta, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
End If
'cuando hay pago en dólares, se ajusta el concepto de subtotal,
SubTotal = (Saldo * TCVenta) + ImporteFluctuacion - (IVA * TCVenta) - (IEPS * TCVenta)
End If
' iva
Dim PorcentajeImpuesto As Decimal = DdlIVA.SelectedValue.ToEntero
Dim IdCtaIVATrasladado As Integer = 0
Dim CveCuentaIVATrasladado As Integer = 0
If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows.Count > 0 Then
IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero
CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=PorcentajeImpuesto).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero
End If
IdCtaContable = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado)
CveCuenta = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado)
If IVA > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ImpuestosMovto, IVA, SerieFolio, 61, ConceptoPartida, FechaPago, IdCtaContable, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, IVA, IVA * TCVenta), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSTrasladado
CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSTrasladado
If IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, ImpuestosMovto, IEPS, SerieFolio, 39, ConceptoPartida, FechaPago, IdCtaContable, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=If(tCveMoneda = 1, IEPS, IEPS * TCVenta), CveCuenta:=CveCuenta, PorcentajeImpuesto:=PorcentajeImpuesto, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
'al gasto,Subtotal
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, SubtotalMovto, SubTotal, SerieFolio, CveConceptoDeduccion, ConceptoPartida, FechaPago, IdCuentaContableNoDeducible, -1, CveCliente:=CveCliente, CveVenta:=CveVenta, ImporteMX:=SubTotal, CveCuenta:=-1, TipoCambio:=TCVenta, TipoCambioPago:=TCPago) Then
MsgError = "Ocurrio un error al saldar el movimiento"
End If
If ObjConta.ValidacionPrePolizaCuadre(CvePrePoliza, 5) Then
If ObjConta.ValorPolizaDescuadre > 0 Then
MsgError = ObjConta.MensajePolizaDescuadre + " " + ObjConta.ValorDiferencia
GuardaLogAD($"Ventas/ClientesAbonar | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas")
End If
End If
End If
If MsgError = "" Then
'ObjConta.RollBack()
ObjConta.Commit()
RegistraScript("$('#ModalSaldarVenta').modal('hide')", "ModalSaldarVentaHidde")
Alert("Documento Saldado")
Else
ObjConta.RollBack()
Alert(MsgError, TipoMensaje.MsgError)
End If
ObjConta.Dispose()
End Sub
#End Region
#Region "PAQUETERIA GUIAS"
Protected Sub LnkAgregarGuia_Click(sender As Object, e As EventArgs)
''DivModalGuias
'DdlPaqueteria.Items.Clear()
'DdlPaqueteria.DataSource = GlobalDTPaqueterias
'DdlPaqueteria.DataBind()
'DdlPaqueteria.Items.Insert(0, New ListItem("Seleccione ", "-1"))
'UpModalGuias.Update()
'CargaGvPaqueteria()
'RegistraScript("$('#DivModalGuias').modal({ backdrop: 'static', keyboard: false });")
'' 21/Marzo/2018 - Se agrego Link a Modulo Paqueterias Guias
RegistraScript(String.Format("AbrirVentana('/General/PopUpPaqueteriasGuias.aspx?CveVenta={0}',800,620);", CveVenta))
End Sub
Protected Sub BtnAgregarGuia_Click(sender As Object, e As EventArgs)
Dim objInventario As New ClsInventarios
Dim CvePaqueteriaGuia As Integer
If objInventario.AddPaqueteriaGuia(DdlPaqueteria.SelectedValue.ToEntero, -1, TxtPaqueteriaGuia.Text.Trim, TxtPaqueteriaNumcajas.Text.ToEntero, TxtPaqueteriaPeso.Text.ToDecimal, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa,
TxtRastreo.Text.Trim, TxtDimensiones.Text.Trim, TxtFechaEst.Text.Trim, CveVenta:=CveVenta) Then
CvePaqueteriaGuia = objInventario.DtResultados.Rows(0)(0).ToString.ToEntero
CargaGvPaqueteria()
LimpiacontrolesPaqueteria()
'Envia notificacion se agrego guia vacia eliminada
If TxtPaqueteriaGuia.Text.Trim.Length = 0 Then
EnviarCorreoNotificacionGuias(2, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CvePaqueteriaGuia:=CvePaqueteriaGuia)
End If
End If
objInventario.Dispose()
End Sub
Protected Sub LnkRemovePaqueteriaGuia_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim CvePaqueteriaGuia As Integer = GvRow.DataKey("CvePaqueteriaGuia").ToString.ToEntero
Dim Guia As String = GvRow.DataKey("Guia").ToString
Dim objInventario As New ClsInventarios
If objInventario.RemovePaqueteriaGuia(CvePaqueteriaGuia, UsuarioActual.CveEmpresa) Then
CargaGvPaqueteria()
If Guia.Trim.Length = 0 Then
'Envia notificacion se elimino guia vacia eliminada
EnviarCorreoNotificacionGuias(3, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CvePaqueteriaGuia:=CvePaqueteriaGuia)
End If
End If
objInventario.Dispose()
End Sub
Private Sub CargaGvPaqueteria()
Dim objInventario As New ClsInventarios
If objInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then
GvPaqueriaGuias.DataSource = objInventario.DtResultados
If objInventario.DtResultados.Rows.Count > 0 Then
BtnAgregarGuia.Attributes.Add("data-toggle", "confirmation")
BtnAgregarGuia.Attributes.Add("data-popout", "true")
BtnAgregarGuia.Attributes.Add("data-original-title", "¿Está seguro de registrar una nueva guia a la factura?")
BtnAgregarGuia.Attributes.Add("data-btn-ok-label", "si")
Else
BtnAgregarGuia.Attributes.Remove("data-toggle")
BtnAgregarGuia.Attributes.Remove("data-popout")
BtnAgregarGuia.Attributes.Remove("data-original-title")
BtnAgregarGuia.Attributes.Remove("data-btn-ok-label")
End If
If objInventario.DtResultados.Rows.Count > 1 Then
EnviarCorreoNotificacionGuias(4, $"{LblSerie.Text}-{TxtFolio.Text}", NombreCliente, "", DdlPaqueteria.SelectedItem.Text, "", TxtRastreo.Text, CveVenta, TmpDT, CountPaqueteria:=objInventario.DtResultados.Rows.Count)
End If
Else
GvPaqueriaGuias.DataSource = Nothing
End If
objInventario.Dispose()
GvPaqueriaGuias.DataBind()
UpModalGuias.Update()
End Sub
Private Sub LimpiacontrolesPaqueteria()
DdlPaqueteria.SelectedIndex = 0
TxtPaqueteriaGuia.Text = ""
TxtPaqueteriaNumcajas.Text = ""
TxtPaqueteriaPeso.Text = ""
TxtRastreo.Text = ""
TxtDimensiones.Text = ""
TxtFechaEst.Text = ""
End Sub
Protected Sub LnkGuiaPaqueteriaGuia_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim CveMovimiento As Integer = -1
Dim CvePaqueteriaGuia As Integer = GvRow.DataKey("CvePaqueteriaGuia").ToString.ToEntero
Dim NumCajas As String = GvRow.DataKey("NumCajas").ToString
Dim Guia As String = GvRow.DataKey("Guia").ToString
Dim Peso As String = GvRow.DataKey("Peso").ToString.ToDecimal.ToString("####.00")
Dim DTDatosClienteGuia As New DataTable
Dim DTMovimientosDetalle As New DataTable
Dim CvePaqueteria As Integer = GvRow.DataKey("CvePaqueteria").ToString.ToEntero
Dim RutaRdlc As String = Server.MapPath("~") & "\Empresas\Grales\Formatos\GuiasFormato" & CvePaqueteria & ".rdlc"
Dim Rastreo As String = GvRow.DataKey("Rastreo")
Dim Dimensiones As String = GvRow.DataKey("Dimensiones")
Dim FechaEstimada As String = GvRow.DataKey("FechaEstimada")
Dim ValorStimado As Double = 0
If Not File.Exists(RutaRdlc) Then
RutaRdlc = Server.MapPath("~") & "\Empresas\Grales\Formatos\GuiasFormato0.rdlc"
End If
RutaRdlc = RutaRdlc.Replace(Server.MapPath("~") & "\", "")
Dim params As New List(Of ReportParameter)
Dim ObjInventario As New ClsInventarios
If ObjInventario.GetPaqueteriaGuiasInfoFormato(CveMovimiento, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then
DTDatosClienteGuia = ObjInventario.DtResultados
Else
ObjInventario.Dispose()
Exit Sub
End If
If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then
DTMovimientosDetalle = ObjInventario.DtResultados
DTMovimientosDetalle.Columns.Add("Peso")
DTMovimientosDetalle.Columns.Add("Dimensiones")
DTMovimientosDetalle.AcceptChanges()
For Each Drow As DataRow In DTMovimientosDetalle.Rows
Drow("Peso") = Peso
Drow("Dimensiones") = Dimensiones
DTMovimientosDetalle.AcceptChanges()
Next
ValorStimado = DTMovimientosDetalle.SUM("PU")
ObjInventario.Dispose()
Else
ObjInventario.Dispose()
Exit Sub
End If
If DTDatosClienteGuia.Rows.Count > 0 Then
params.Add(New ReportParameter("NombreComercial", DTDatosClienteGuia.Rows(0)("NombreComercial").ToString))
params.Add(New ReportParameter("Direccion", DTDatosClienteGuia.Rows(0)("Direccion").ToString))
params.Add(New ReportParameter("Colonia", DTDatosClienteGuia.Rows(0)("Colonia").ToString))
params.Add(New ReportParameter("NoExt", DTDatosClienteGuia.Rows(0)("NoExt").ToString))
params.Add(New ReportParameter("NoInt", DTDatosClienteGuia.Rows(0)("NoInt").ToString))
params.Add(New ReportParameter("Localidad", DTDatosClienteGuia.Rows(0)("Localidad").ToString))
params.Add(New ReportParameter("Telefono", DTDatosClienteGuia.Rows(0)("Telefono").ToString))
params.Add(New ReportParameter("RFCCliente", DTDatosClienteGuia.Rows(0)("RFC").ToString))
params.Add(New ReportParameter("CiudadCliente", DTDatosClienteGuia.Rows(0)("Ciudad").ToString))
Else
Exit Sub
End If
Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta))
Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa)
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
params.Add(New ReportParameter("EmpresaDireccion", UsuarioActual.Empresa.Direccion))
params.Add(New ReportParameter("EmpresaTelefono", UsuarioActual.Empresa.Telefono))
params.Add(New ReportParameter("EmpresaColonia", UsuarioActual.Empresa.Colonia))
params.Add(New ReportParameter("EmpresaLocalidad", UsuarioActual.Empresa.Localidad))
params.Add(New ReportParameter("RFCEmpresa", UsuarioActual.Empresa.RFC))
params.Add(New ReportParameter("CiudadEmpresa", UsuarioActual.Empresa.Ciudad))
params.Add(New ReportParameter("EmpresaTelefono", UsuarioActual.Empresa.Telefono))
params.Add(New ReportParameter("NumCajas", NumCajas))
params.Add(New ReportParameter("Peso", Peso))
params.Add(New ReportParameter("Guia", Guia))
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre))
params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString))
params.Add(New ReportParameter("Anio", Now.Year.ToString))
params.Add(New ReportParameter("Mes", Now.Month.ToString("00")))
params.Add(New ReportParameter("Dia", Now.Day.ToString("00")))
params.Add(New ReportParameter("Rastreo", Rastreo))
params.Add(New ReportParameter("Dimensiones", Dimensiones))
params.Add(New ReportParameter("FechaEstimada", FechaEstimada))
If Imagen.Exists Then
params.Add(New ReportParameter("LogoPath", logouri))
Else
params.Add(New ReportParameter("LogoPath", ""))
End If
ImprimirPDF(RutaRdlc, DTMovimientosDetalle, params, $"ReporteGuia_{Now.ToString("yyyyMMddhhmmss")}")
End Sub
Private Sub GvPaqueriaGuias_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvPaqueriaGuias.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Lnk As LinkButton = e.Row.FCLinkButton("LnkGuiaPaqueteriaGuia")
Dim Destinatario As String = e.Row.DataKey("Mail").ToString
If Destinatario.Length = 0 Then
e.Row.FCLinkButton("LnkGuiaPaqueteriaMail").Visible = False
Else
e.Row.FCLinkButton("LnkGuiaPaqueteriaMail").Attributes.Add("title", "Enviar correo a: " & Destinatario)
End If
ScriptManager.GetCurrent(Me).RegisterPostBackControl(Lnk)
End If
End Sub
Private Sub GvPaqueteriaCreaEnlaces()
For Each GvRow As GridViewRow In GvPaqueriaGuias.Rows
If GvRow.RowType = DataControlRowType.DataRow Then
Dim Lnk As LinkButton = GvRow.FCLinkButton("LnkGuiaPaqueteriaGuia")
ScriptManager.GetCurrent(Me).RegisterPostBackControl(Lnk)
End If
Next
End Sub
Protected Sub LnkGuiaPaqueteriaMail_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
Dim SerieFolio As String = GvRow.DataKey("SerieFolio").ToString
Dim NombreComercial As String = GvRow.DataKey("NombreComercial").ToString
Dim Destinatario As String = GvRow.DataKey("Mail").ToString
Dim Paqueteria As String = GvRow.DataKey("Paqueteria").ToString
Dim Guia As String = GvRow.DataKey("Guia").ToString
Dim Rastreo As String = GvRow.DataKey("Rastreo").ToString
Dim CveVenta As Integer = GvRow.DataKey("CveVenta").ToEntero
EnviarCorreoNotificacionGuias(1, SerieFolio, NombreComercial, Destinatario, Paqueteria, Guia, Rastreo, CveVenta, New DataTable)
End Sub
Private Sub EnviarCorreoNotificacionGuias(Tipo As Integer, SerieFolio As String, NombreComercial As String, Destinatario As String, Paqueteria As String, Guia As String, Rastreo As String, CveVenta As Integer, tDtMovimientos As DataTable, Optional CountPaqueteria As Integer = Nothing, Optional CvePaqueteriaGuia As Integer = -1)
Dim Correo As New ClsSisMail()
Dim Asunto As String = UsuarioActual.Empresa.NombreCorto & " Envio de pedido: " & SerieFolio
Dim Cuerpo As New StringBuilder
Select Case Tipo
Case 1 'Notificacion Normal
' Dim ObjCliente As New ClsClientes()
'Dim FolioOC As String = ""
'Dim FolioPedido As String = ""
'Dim CorreoDestino = ""
'Dim CveVendedor As Integer = DdlVendedor.SelectedValue.ToEntero
'Dim CorreoVendedor As String = ""
'Dim CorreoVendedorUsuarioActual As String = ""
'If CveVendedor > 0 Then
' Dim DtTemp As New DataTable
' DtTemp = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros($"CveVendedor={CveVendedor}")
' If DtTemp.Rows.Count > 0 Then
' CorreoVendedor = DtTemp.Rows(0)("Correo").ToString
' End If
'End If
'Try
' If UsuarioActual.CveVendedor > 0 Then
' Dim DtTemp As New DataTable
' DtTemp = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros($"CveVendedor={ UsuarioActual.CveVendedor}")
' If DtTemp.Rows.Count > 0 Then
' CorreoVendedorUsuarioActual = DtTemp.Rows(0)("Correo").ToString
' End If
' End If
'Catch ex As Exception
'End Try
'If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, -1, TipoCliente:=-1) Then
' If ObjCliente.CobranzaCorreo <> ObjCliente.Mail Then
' CorreoDestino = $"{ObjCliente.CobranzaCorreo};{ObjCliente.Mail }"
' Else
' CorreoDestino = $"{ObjCliente.Mail}"
' End If
'End If
'ObjCliente.Dispose()
'If CorreoVendedor.Trim.Length > 0 Then
' CorreoDestino = $"{CorreoDestino};{CorreoVendedor}"
'End If
'If CorreoVendedorUsuarioActual.Trim.Length > 0 Then
' CorreoDestino = $"{CorreoDestino};{CorreoVendedorUsuarioActual}"
'End If
'If CveOC > 0 Then
' Dim ObjOC As New ClsOC
' If ObjOC.GetOC(CveOC, UsuarioActual.CveEmpresa) Then
' FolioOC = ObjOC.Folio.ToString
' End If
' ObjOC.Dispose()
'End If
'If CvePedido > 0 Then
' Dim ObjVenta As New ClsVentas
' If ObjVenta.GetVenta(CvePedido, UsuarioActual.CveEmpresa) Then
' FolioPedido = ObjVenta.Folio.ToString
' End If
' ObjVenta.Dispose()
'End If
Cuerpo.AppendLine($"Estimado {NombreComercial} le informamos que los productos de la factura {SerieFolio} han sido enviados mediante la paquetería {Paqueteria} con Guia {Guia} , Rastreo {Rastreo} .<br><br>")
If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then
Cuerpo.AppendLine("<table><tr>")
Cuerpo.AppendLine("<th>Cantidad</th><th>Producto</th>")
For Each Drow As DataRow In tDtMovimientos.Rows
Cuerpo.AppendLine($"<tr><td>{Drow("Cantidad").ToString.ToEntero }</td><td>{Drow("PS").ToString}</td></tr>")
Next
Cuerpo.AppendLine("</tr></table>")
End If
Cuerpo.AppendLine("<br><br>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 }.<br><br>")
'If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then
' Cuerpo.AppendLine("<table><tr>")
' Cuerpo.AppendLine("<th>Cantidad</th><th>Producto</th>")
' For Each Drow As DataRow In tDtMovimientos.Rows
' Cuerpo.AppendLine($"<tr><td>{Drow("Cantidad").ToString.ToEntero }</td><td>{Drow("PS").ToString}</td></tr>")
' Next
' Cuerpo.AppendLine("</tr></table>")
'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 }.<br><br>")
'If tDtMovimientos IsNot Nothing AndAlso tDtMovimientos.Rows.Count > 0 Then
' Cuerpo.AppendLine("<table><tr>")
' Cuerpo.AppendLine("<th>Cantidad</th><th>Producto</th>")
' For Each Drow As DataRow In tDtMovimientos.Rows
' Cuerpo.AppendLine($"<tr><td>{Drow("Cantidad").ToString.ToEntero }</td><td>{Drow("PS").ToString}</td></tr>")
' Next
' Cuerpo.AppendLine("</tr></table>")
' 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 }.<br><br>")
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("<table><tr>")
Cuerpo.AppendLine("<th>Cantidad</th><th>Producto</th>")
For Each Drow As DataRow In tDtMovimientos.Rows
Cuerpo.AppendLine($"<tr><td>{Drow("Cantidad").ToString.ToEntero }</td><td>{Drow("PS").ToString}</td></tr>")
Next
Cuerpo.AppendLine("</tr></table>")
End If
Correo.SendMail(UsuarioActual.Empresa, Destinatario, Asunto, Cuerpo.ToString)
Exit Select
End Select
End Sub
Private Sub GuardarBitacora(CveVenta As Integer, RutaAdjunto As String, Obser As String)
Dim ObjEventos As New ClsOIEventos()
Try
If ObjEventos.AddEventoBitacora(Obser, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then
End If
Catch ex As Exception
OnError("Se presento un Error al guardar la Bitacora", ex)
End Try
ObjEventos.Dispose()
End Sub
#End Region
#Region " APLICAR NOTA DE CREDITO "
Private Sub InicializaAplicarNC()
'If Not UsuarioActual.CveUsuario = 100 Then
' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then
' Exit Sub
' End If
'End If
If CveVenta <= 0 Or Not DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Or Not HplSaldoAuxiliar.Text.ToDouble > 0 Then
''If Not HplSaldoAuxiliar.Text.ToDouble > 0 Then LkNotaCredito.Visible = False
Exit Sub
End If
'sino tiene el permiso de peude generar NC
If Not UsuarioActual.TienePermisoProceso(175) Then
Exit Sub
End If
AplicaNCMasiva = False
AplicaNC = False
LBNotaCredito.Visible = True
'LkNotaCredito.Visible = False
TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNC();")
TxtNCImporte.Attributes.Add("onkeyup", "CalculaPorcentajeNC();")
Dim PorcentajeMaximo = 0.0
If TxtTotal.Text.ToDouble > 0 Then
PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.ToDouble
Else
RVNCPorcentaje.MinimumValue = "0"
RVTxtNCImporte.MinimumValue = "0"
End If
TxtNCPorcentaje.Text = PorcentajeMaximo.FormatoNumero(4)
If PorcentajeMaximo < RVNCPorcentaje.MinimumValue.ToDouble Then
RVNCPorcentaje.MinimumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString
End If
RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString
TxtNCImporte.Text = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero
If ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble < RVTxtNCImporte.MinimumValue.ToDouble Then
RVTxtNCImporte.MinimumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString
End If
RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * TxtTotal.Text.ToDouble) / 100).FormatoNumero().ToDouble.ToString
UpAplicarNC.Update()
End Sub
Private Sub InicializaAplicarNCMasiva()
'If Not UsuarioActual.CveUsuario = 100 Then
' If Not UsuarioActual.CveEmpresa.Contiene(1, 72, 80, 119) Then
' Exit Sub
' End If
'End If
'sino tiene el permiso de peude generar NC
If Not UsuarioActual.TienePermisoProceso(175) Then
Exit Sub
End If
AplicaNCMasiva = True
LBNotaCredito.Visible = True
'LkNotaCredito.Visible = False
DivGvCxC.Visible = True
CargaCxC()
TxtNCPorcentaje.Attributes.Add("onkeyup", "CalculaImporteNCMasivo();")
TxtNCImporte.Text = "0.00"
TxtNCImporte.Enabled = False
RVTxtNCImporte.Enabled = False
UpAplicarNC.Update()
End Sub
Private Sub CargaCxC()
Dim ObjMovtos As New ClsMovimientos()
If ObjMovtos.GetCxCClienteDetalle(ViewState("CveCliente").ToString.ToEntero, "-1", "-1", DdlMoneda.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa, DdlSucursalCliente.SelectedValue.ToEntero) Then
Dim DtTemporal As DataTable = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act' AND CveVenta > 0", "Moneda, OrdenVencimiento, FechaVencimiento")
GvCxC.DataSource = DtTemporal
End If
ObjMovtos.Dispose()
GvCxC.DataBind()
End Sub
Protected Sub GvCxC_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCCheckBox("ChkCxC").Attributes.Add("onclick", $"CalculaTotalChk({e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{e.Row.FCTextBox("TxtImporte").ClientID},{e.Row.DBCampo("Saldo").ToDouble},{TxtNCPorcentaje.Text.ToDouble}, this);")
e.Row.FCTextBox("TxtImporte").Attributes.Add("onkeyup", $"LimitaCantidadNCMasivo({TxtNCPorcentaje.Text.ToDouble()},{e.Row.DBCampo("Saldo").ToDouble},{e.Row.DBCampo("Original").ToDouble},{e.Row.DBCampo("SubTotal").ToDouble},{TxtTotalGv.ClientID},{TxtNCImporte.ClientID},{e.Row.FCCheckBox("ChkCxC").ClientID}, this);")
End If
End Sub
Protected Sub DdlNCNivelImporte_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ImporteReferencia As Double = 0, PorcentajeMaximo As Double = 0
If Not AplicaNCMasiva Then
ImporteReferencia = If(DdlNCNivelImporte.SelectedValue.ToEntero = 1, TxtTotal.Text.Trim.ToDouble, TxtSubTotal.Text.Trim.ToDouble)
PorcentajeMaximo = HplSaldoAuxiliar.Text.ToDouble * 100 / TxtTotal.Text.Trim.ToDouble
RVNCPorcentaje.MaximumValue = PorcentajeMaximo.FormatoNumero(4).ToDouble.ToString
RVTxtNCImporte.MaximumValue = ((PorcentajeMaximo * ImporteReferencia) / 100).FormatoNumero().ToDouble.ToString
End If
If AplicaNCMasiva Then RegistraScript($"CalculaImporteNCMasivo()", "CalculaImporteNCMasivo") Else RegistraScript("CalculaImporteNC();", "CalculaImporteNC")
UpAplicarNC.Update()
End Sub
Protected Sub BtnAplicarNC_Click(sender As Object, e As EventArgs)
Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlNCPS.SelectedValue.ToEntero).FiltroPrimero("")
If DrPS Is Nothing Then
Alert("Ocurrió un error al cargar la información del producto. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError)
Exit Sub
Else
'VALIDA CLAVES SAT
If DrPS("SATClavePS").ToString = "" Then
Alert($"El concepto <b>{DrPS("Codigo").ToString}-{DrPS("PS").ToString}</b> 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 <b>{DrPS("Codigo").ToString}-{DrPS("PS").ToString}</b> no cuenta con Unidad Medida SAT. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
If DdlTipoComprobante.SelectedValue = "Ant" Then CveAnticipo = CveVenta
DdlTipoComprobante.SelectedValueExist("Egs")
'CREAMOS DT PARA UTILIZAR AL TIMBRAR
InicializaDTVentasNC()
Dim DtImpuestos As New DataTable
DtImpuestos.Columns.Add("ImportePU", GetType(Double))
DtImpuestos.Columns.Add("ImporteTotal", GetType(Double))
DtImpuestos.Columns.Add("PorcentajeIVA", GetType(Double))
DtImpuestos.Columns.Add("ImporteIVA", GetType(Double))
DtImpuestos.Columns.Add("PorcentajeRetIVA", GetType(Double))
DtImpuestos.Columns.Add("ImporteRetIVA", GetType(Double))
DtImpuestos.Columns.Add("PorcentajeRetISR", GetType(Double))
DtImpuestos.Columns.Add("ImporteRetISR", GetType(Double))
DtImpuestos.Columns.Add("PorcentajeIEPS", GetType(Double))
DtImpuestos.Columns.Add("ImporteIEPS", GetType(Double))
DtImpuestos.Columns.Add("CveSubProyecto", GetType(Integer))
DtImpuestos.AcceptChanges()
If AplicaNCMasiva Then
For Each Gvr As GridViewRow In GvCxC.Rows
If Gvr.FCCheckBox("ChkCxC").Checked Then
DtImpuestos.Merge(CargaDtImpuestosNC(Gvr.DataKey("CveVenta").ToString.ToEntero, Gvr.FCTextBox("TxtImporte").Text.ToString.ToDecimal), True, MissingSchemaAction.Ignore)
'CARGA FACTURA A LA CUAL SE APLICA LA NC
CargaNCDT(Gvr.DataKey("CveVenta").ToString.ToEntero, Gvr.FCTextBox("TxtImporte").Text.ToString.ToDecimal)
End If
Next
Else
DtImpuestos = CargaDtImpuestosNC(CveVenta, TxtNCImporte.Text.Trim.ToDecimal)
End If
Dim query = From dr In DtImpuestos
Group By PorcentajeIVA = dr("PorcentajeIVA").ToString.ToDecimal,
PorcentajeRetIVA = dr("PorcentajeRetIVA").ToString.ToDecimal,
PorcentajeRetISR = dr("PorcentajeRetISR").ToString.ToDecimal,
PorcentajeIEPS = dr("PorcentajeIEPS").ToString.ToDecimal
Into x = Group
Select ImportePU = x.Sum(Function(s) s("ImportePU").ToString.ToDecimal),
ImporteTotal = x.Sum(Function(s) s("ImporteTotal").ToString.ToDecimal),
ImporteIVA = x.Sum(Function(s) s("ImporteIVA").ToString.ToDecimal),
ImporteRetIVA = x.Sum(Function(s) s("ImporteRetIVA").ToString.ToDecimal),
ImporteRetISR = x.Sum(Function(s) s("ImporteRetISR").ToString.ToDecimal),
ImporteIEPS = x.Sum(Function(s) s("ImporteIEPS").ToString.ToDecimal),
PorcentajeIVA = PorcentajeIVA,
PorcentajeRetIVA = PorcentajeRetIVA,
PorcentajeRetISR = PorcentajeRetISR,
PorcentajeIEPS = PorcentajeIEPS
Dim DrSubProyecto = GlobalDTSubProyectos(-1, TmpDT.FiltroPrimeroValor("CveSubProyecto", "", "ImporteTotal DESC").ToEntero, UsuarioActual.CveEmpresa, -1).FiltroPrimero("")
If DrSubProyecto Is Nothing Then
Alert("Ocurrió un error al cargar la información de centro de costos. Por favor comuniquese con asistencia SIG", TipoMensaje.MsgError)
Exit Sub
End If
DtImpuestos = query.QueryToDataTable(False)
LimpiaDocumentoNC()
Dim CveSubProyecto = DrSubProyecto("CveSubProyecto").ToString.ToEntero
Dim SubProyecto = DrSubProyecto("SubProyecto").ToString
Dim CveProyecto = DrSubProyecto("CveProyecto").ToString.ToEntero
Dim Proyecto = DrSubProyecto("Proyecto").ToString
For Each Dr As DataRow In DtImpuestos.Rows
AgregaTempDT(DrPS("CvePS").ToString.ToEntero, DrPS("PS").ToString, DrPS("Codigo").ToString, DrPS("PSCodigo").ToString, DrPS("CveTipoPS").ToString.ToEntero, DrPS("Inv_CveMetodoInventario").ToString.ToEntero,
DrPS("CveUM").ToString.ToEntero, DrPS("UnidadMedida").ToString, DrPS("CveClasificacion").ToString.ToEntero, DrPS("Clasificacion").ToString, CveProyecto, Proyecto, CveSubProyecto, SubProyecto,
TxtNCObservaciones.Text.Trim, 1, Dr("ImportePU").ToString.ToDecimal, Dr("PorcentajeIVA").ToString.ToDecimal, Dr("ImporteIVA").ToString.ToDecimal, Dr("PorcentajeRetIVA").ToString.ToDecimal, Dr("ImporteRetIVA").ToString.ToDecimal,
Dr("PorcentajeRetISR").ToString.ToDecimal, Dr("ImporteRetISR").ToString.ToDecimal, Dr("PorcentajeIEPS").ToString.ToDecimal, Dr("ImporteIEPS").ToString.ToDecimal, -1, 0.0, Dr("ImporteTotal").ToString.ToDecimal, "", "", -1, -1,
DrPS("SATClavePS").ToString, DrPS("SATClaveUnidadMedida").ToString, -1, -1, -1, -1, -1, -1)
Next
TrTipoRelacion.Visible = True
DdlTiposRelacion.SelectedValueExist("1")
GvPS.DataSource = TmpDT
GvPS.DataBind()
CalculaTotalesVenta(True)
'condicióon, en la que se verifica que el importe total de aplicación de la nota de crédito sea igual al del total de la nota de crédito, ej. saldo de la factura 1000.01 y la nota de crédito se generó po 1000.00
If Not AplicaNCMasiva Then
Dim TT As Decimal = TxtNCImporte.Text.ToDecimal
If TT > TxtTotal.Text.ToDecimal Then TT = TxtTotal.Text.ToDecimal
CargaNCDT(CveVenta, TT)
End If
'verifica el tipo de cambio que se actualice
If DdlMoneda.SelectedValue <> "1" Then
TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString
End If
LblTCValuacion.Visible = False
UpPS.Update()
LBNotaCredito.Visible = False
RegistraScript("$('#ModalAplicarNC').modal('hide');", "EscondeModalNC")
AplicaNC = True
CambiaTipoDocto()
End Sub
Private Function CargaDtImpuestosNC(CveVentaNC As Integer, Importe As Decimal) As DataTable
Dim Total As Decimal = 0, SubTotal As Decimal = 0, Saldo As Decimal = 0
Dim ObjVentas As New ClsVentas
If ObjVentas.GetVentaDetalle(CveVentaNC) Then
TmpDT = ObjVentas.DtResultados
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
End If
If AplicaNCMasiva Then
If ObjVentas.GetVenta(CveVentaNC, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
Total = ObjVentas.DtResultados()(0)("Total").ToString.ToDecimal
SubTotal = ObjVentas.DtResultados()(0)("SubTotal").ToString.ToDecimal
End If
End If
Else
Total = TxtTotal.Text.ToDecimal
SubTotal = TxtSubTotal.Text.ToDecimal
End If
ObjVentas.Dispose()
Dim DtImpuestosLocal = TmpDT.FiltraParametros("", "", {"PorcentajeIVA", "PorcentajeRetIVA", "PorcentajeRetISR", "PorcentajeIEPS", "CveSubProyecto"}).Copy
DtImpuestosLocal.Columns.Add("ImportePU", GetType(Double))
DtImpuestosLocal.Columns.Add("ImporteTotal", GetType(Double))
DtImpuestosLocal.Columns.Add("ImporteIVA", GetType(Double))
DtImpuestosLocal.Columns.Add("ImporteRetIVA", GetType(Double))
DtImpuestosLocal.Columns.Add("ImporteRetISR", GetType(Double))
DtImpuestosLocal.Columns.Add("ImporteIEPS", GetType(Double))
Dim ImporteReferencia As Decimal = If(DdlNCNivelImporte.SelectedValue.ToEntero = 1, Total, SubTotal)
Dim Porcentaje As Decimal = ((Importe * 100) / ImporteReferencia) / 100
For Each Dr As DataRow In DtImpuestosLocal.Rows
Dr("ImporteTotal") = Math.Round(Porcentaje * (TmpDT.SUM("TotalImporte", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ") - TmpDT.SUM("Descuento", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ")), 2)
' COMENTANDO POR JESUS MURUA ALIAS EL CHOLO, LO HIZO EL RAUL ARRIBA ALV ! 28/02/2018
'Dr("ImporteTotal") = Porcentaje * TmpDT.SUM("TotalImporte", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' ")
Dr("ImporteIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIVA", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' "), 2)
Dr("ImporteRetIVA") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetIVA", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}' "), 2)
Dr("ImporteRetISR") = Math.Round(Porcentaje * TmpDT.SUM("ImporteRetISR", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}'"), 2)
Dr("ImporteIEPS") = Math.Round(Porcentaje * TmpDT.SUM("ImporteIEPS", $"ISNULL(PorcentajeIVA,0) = {Dr("PorcentajeIVA").ToString.ToDecimal} AND ISNULL(PorcentajeRetIVA,0) = '{Dr("PorcentajeRetIVA").ToString.ToDecimal}' AND ISNULL(PorcentajeRetISR,0) = '{Dr("PorcentajeRetISR").ToString.ToDecimal}' AND ISNULL(PorcentajeIEPS,0) = '{Dr("PorcentajeIEPS").ToString.ToDecimal}' AND ISNULL(CveSubProyecto,0) = '{Dr("CveSubProyecto").ToString.ToEntero}'"), 2)
Dr("ImportePU") = Dr("ImporteTotal").ToString.ToDecimal '(Dr("ImporteTotal").ToString.ToDecimal - Dr("ImporteIVA").ToString.ToDecimal - Dr("ImporteRetIVA").ToString.ToDecimal - Dr("ImporteRetISR").ToString.ToDecimal - Dr("ImporteIEPS").ToString.ToDecimal)
Next
'codigo para ajuste de centavo, si el importe total no cuadra con los totales
Dim difTmp As Decimal = Importe - (DtImpuestosLocal.SUMD("ImporteTotal") + DtImpuestosLocal.SUMD("ImporteIVA") + DtImpuestosLocal.SUMD("ImporteIEPS") - DtImpuestosLocal.SUMD("ImporteRetIVA") - DtImpuestosLocal.SUMD("ImporteRetISR"))
If Math.Abs(difTmp) >= 0.01 Then
'asusto la diferencia en el último concepto
DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal") = DtImpuestosLocal.Rows(DtImpuestosLocal.Rows.Count - 1)("ImporteTotal").ToString.ToDecimal + difTmp
End If
'CARGA FACTURA A LA CUAL SE APLICA LA NC
'CargaNCDT(CveVentaNC, Importe.ToDecimal)
Return DtImpuestosLocal
End Function
Private Sub AgregaTempDT(CvePS As Integer, PS As String, Codigo As String, CodigoPS As String, CveTipoPS As Integer, CveTipoInvPS As Integer, CveUM As Integer, UM As String,
CveClasificacion As Integer, Clasificacion As String, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String,
Obs As String, Cantidad As Double, PU As Double, PorcentajeIVA As Double, ImporteIVA As Double, PorcentajeRetIVA As Double, ImporteRetIVA As Double,
PorcentajeRetISR As Double, ImporteRetISR As Double, PorcentajeIEPS As Double, ImporteIEPS As Double, TipoDescuento As Integer, Descuento As Double,
Total As Double, SerieLote As String, TiempoEntrega As String, CvePresupuestoIngreso As Integer, EntregaDirecta As Integer, SATClaveProdServ As String,
SATClaveUM As String, CveContratoDetalle As Integer, CveVentaDetalle As Integer, CveMovimientoDetallePedido As Integer, CveOrdenCompraDetalle As Integer,
CveVentaDetalleRemision As Integer, CveVentaDetalleCotizacion As Integer)
Dim Row As DataRow = Nothing
Row = TmpDT.NewRow()
Row("Consec") = TmpDT.Rows.Count + 1
Row("Orden") = TmpDT.Rows.Count + 1
Row("CvePS") = CvePS
Row("PS") = PS
Row("Codigo") = Codigo
Row("CodigoPS") = CodigoPS
Row("CveTipoPS") = CveTipoPS
Row("CveTipoInvPS") = CveTipoInvPS
Row("CveUM") = CveUM
Row("UM") = UM
Row("CveClasificacion") = CveClasificacion
Row("Clasificacion") = Clasificacion
Row("CveProyecto") = CveProyecto
Row("Proyecto") = Proyecto
Row("CveSubProyecto") = CveSubProyecto
Row("SubProyecto") = SubProyecto
Row("Obs") = Obs
Row("Cantidad") = Cantidad
Row("PU") = Math.Round(PU, 6)
Row("PorcentajeIVA") = PorcentajeIVA
Row("IVA") = PorcentajeIVA
Row("ImporteIVA") = Math.Round(ImporteIVA, NumeroDecimales)
Row("PorcentajeRetIVA") = PorcentajeRetIVA
Row("ImporteRetIVA") = Math.Round(ImporteRetIVA, NumeroDecimales)
Row("PorcentajeRetISR") = PorcentajeRetISR
Row("ImporteRetISR") = Math.Round(ImporteRetISR, NumeroDecimales)
Row("PorcentajeIEPS") = PorcentajeIEPS
Row("ImporteIEPS") = Math.Round(ImporteIEPS, NumeroDecimales)
Row("IEPS") = Math.Round(ImporteIEPS, NumeroDecimales)
Row("TipoDescuento") = TipoDescuento
Row("Descuento") = Math.Round(Descuento, NumeroDecimales)
Row("Total") = Math.Round(Total, NumeroDecimales)
Row("TotalImporte") = Math.Round(Total, NumeroDecimales)
Row("SerieLote") = SerieLote
Row("TiempoEntrega") = TiempoEntrega
Row("CvePresupuestoIngreso") = CvePresupuestoIngreso
Row("EntregaDirecta") = EntregaDirecta
Row("SATClaveProdServ") = SATClaveProdServ
Row("SATClaveUM") = SATClaveUM
'Contratos
Row("CveContratoDetalle") = CveContratoDetalle
Row("CveVentaDetalle") = CveVentaDetalle
Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
Row("CveVentaDetalleRemision") = CveVentaDetalleRemision
Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion
TmpDT.Rows.Add(Row)
End Sub
Private Sub LimpiaDocumentoNC()
EsCreaApartirDe = True
DivEstatusFac.Visible = False
TabAlmacen.Visible = False
'LIMPIA ACCIONES
HLOrdendeCompra.Visible = False
LkDevolucion.Visible = False
LBAplicaDevolucion.Visible = False
'LkNotaCredito.Visible = False
LkEliminarFactura.Visible = False
ImgDownCancelacion.Visible = False
LkRefacturacion.Visible = False
HLOrdenServicio.Visible = False
LkCotizacionAutorizar.Visible = False
LnkFacturarRemision.Visible = False
LnkRemisiones.Visible = False
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
LnkOCs.Visible = False
LbCancelarDocumento.Visible = False
LBCancelarPedido.Visible = False
LiDevolucionAlmacen.Visible = False
HLPagar.Visible = False
HlAgregarExcel.Visible = False
HplDownXML.Visible = False
HplDownPDF.Visible = False
HLSaldarVenta.Visible = False
LBNotaCredito.Visible = False
LiComplementoPago.Visible = False
HlCuentaTerminal.Visible = False
LiLnkGuias.Visible = False
LiDocumentoCliente.Visible = False
'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION
GvPS.Columns(6).Visible = False
ThCantidadFacturadaRem.Visible = False
ThCantidadFacturadaRem2.Visible = False
GvPS.Columns(7).Visible = False
ThCantidadFacturada.Visible = False
ThCantidadFacturada2.Visible = False
'LIMPIA DETALLES
TmpDT.Clear()
GvPS.DataSource = Nothing
GvPS.DataBind()
LblFolioFiscal.Text = ""
TxtFecha.Text = Now.ToShortDateString
'DESACTIVA/ACTIVA BOTONES
TrVistaPrevia.Visible = True
BtnEmitir.Visible = False
BtnCrearApartirDe.Visible = False
BtnGenerarRemision.Visible = False
BtnPermisoEditarCotizacion.Visible = False
BtnEditarCotizacion.Visible = False
BtnGenerarOS.Visible = False
'ACTIVA CONDICIONES DE PAGO
DdlUsoCFDI.Enabled = True
DdlUsoCFDI.SelectedValueExist("2")
DdlMetodoPago33.Enabled = True
DdlMetodoPago33.SelectedValueExist("1") ' PUE
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
DdlFormaPago33.Enabled = True
DdlFormaPago33.SelectedValueExist("11") ' condonación por default
UpEstatus.Update()
UpnTools.Update()
UpCliente.Update()
UpParametros.Update()
UpPS.Update()
UpFacturar.Update()
UPObservaciones.Update()
UPPDescuento.Update()
UPCondicionesPago.Update()
UpDetalle.Update()
End Sub
Private Sub InicializaDTVentasNC()
DtVentasNC = New DataTable
DtVentasNC.Columns.Add("CveVenta", GetType(Integer))
DtVentasNC.Columns.Add("Importe", GetType(Decimal))
DtVentasNC.Columns.Add("FolioFiscal", GetType(String))
DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TC", .DataType = GetType(Decimal), .DefaultValue = 1})
DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TCCambioValuacion", .DataType = GetType(Decimal), .DefaultValue = 1})
DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "CveEstatusFactura", .DataType = GetType(Integer), .DefaultValue = -1})
End Sub
Private Sub CargaNCDT(pCveVenta As Integer, Importe As Decimal, Optional FolioFiscal As String = "", Optional NuevaFactura As Integer = -1, Optional ByRef ObjVentas As ClsVentas = Nothing, Optional TC As Decimal = 1)
If (pCveVenta > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs")) OrElse (pCveVenta > 0 AndAlso NuevaFactura = 1) Then
Dim CveEstatusFacturaNC As Integer = -1
Dim TCCambioValuacion As Decimal = 1
If FolioFiscal = "" Then
Dim ObjVentasAplicar As ClsVentas
If ObjVentas IsNot Nothing Then
ObjVentasAplicar = ObjVentas
Else
ObjVentasAplicar = New ClsVentas
End If
If ObjVentasAplicar.GetVenta(pCveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentasAplicar.DtResultados.Rows.Count > 0 Then
FolioFiscal = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("FolioFiscal").ToString()
TC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambio").ToString.ToDecimal()
TCCambioValuacion = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("TipoCambioValuacion").ToString.ToDecimal()
CveEstatusFacturaNC = ObjVentasAplicar.DtResultados.FiltroPrimeroValor("CveEstatusFactura").ToString.ToEntero()
End If
If ObjVentas Is Nothing Then
ObjVentasAplicar.Dispose()
End If
End If
Dim Dr = DtVentasNC.NewRow
Dr("CveVenta") = pCveVenta
Dr("Importe") = Importe
Dr("FolioFiscal") = FolioFiscal
Dr("TC") = TC
Dr("TCCambioValuacion") = TCCambioValuacion
Dr("CveEstatusFactura") = CveEstatusFacturaNC
DtVentasNC.Rows.Add(Dr)
End If
End Sub
#End Region
#Region " APLICA DEVOLUCION "
Private Sub InicializaAplicaDevolucion()
If Not UsuarioActual.CveUsuario = 100 Then
If Not UsuarioActual.CveEmpresa.Contiene(72, 80, 119) Then
Exit Sub
End If
End If
'sino tiene el permiso no puede generar Devolucion
If Not UsuarioActual.TienePermisoProceso(264) Then
Exit Sub
End If
LkDevolucion.Visible = False
LBAplicaDevolucion.Visible = True
Dim SeEsconde As Boolean = False
Dim ObjVenta As New ClsVentas
If ObjVenta.GetVentaDetalle(CveVenta) Then
If Not ObjVenta.DtResultados.SUM("CantSur").ToString.ToDecimal > 0 Then SeEsconde = True
GvAplicaDevolucion.DataSource = ObjVenta.DtResultados.FiltraParametros("CantRes > 0")
End If
ObjVenta.Dispose()
'activo el permiso para registrar el importe diferente a la devolución
GvAplicaDevolucion.Columns(9).Visible = UsuarioActual.TienePermisoProceso(253)
'MODALIDAD CENTRO COSTOS
If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then
GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal"
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then
GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto"
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then
GvAplicaDevolucion.Columns(7).HeaderText = "Sucursal/Proyecto"
ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then
GvAplicaDevolucion.Columns(7).HeaderText = "Proyecto/Sucursal"
End If
If SeEsconde Then GvAplicaDevolucion.Columns(1).Visible = False : GvAplicaDevolucion.Columns(2).Visible = False : GvAplicaDevolucion.Columns(3).Visible = False
GvAplicaDevolucion.DataBind()
UpDevolucion.Update()
End Sub
Protected Sub BtnAplicaDevolucion_Click(sender As Object, e As EventArgs)
'VALIDACIONES
Dim Selecciono As Boolean = False
For Each Gv As GridViewRow In GvAplicaDevolucion.Rows
If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDouble > 0 Then
Selecciono = True
Exit For
End If
Next
If Not Selecciono Then
Alert("Tiene que seleccionar al menos un concepto y este dege tener una cantidad mayor a 0. Por favor verifique y vuelva a intentar", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
AplicaDevolucion = True
SaldoVentaDevolucion = HplSaldoAuxiliar.Text.ToDecimal
CveVentaDevolucion = CveVenta
DdlTipoComprobante.Items.Insert(0, New ListItem("Devolucion", "Dev"))
DdlTipoComprobante.SelectedValue = "Dev"
Dim AplicaPUEditado As Boolean = UsuarioActual.TienePermisoProceso(253)
TmpDT.Clear()
For Each Gv As GridViewRow In GvAplicaDevolucion.Rows
If Gv.FCCheckBox("Chk").Checked And Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal > 0 Then
Dim Cantidad As Decimal = Gv.FCTextBox("TxtCantidadAplicaDevolucion").Text.ToDecimal
Dim Descuento As Decimal = Cantidad * Gv.DataKey("Descuento").ToString.ToDecimal / Gv.DataKey("Cantidad").ToString.ToDecimal
Dim PU As Decimal = If(AplicaPUEditado, Gv.FCTextBox("TxtPrecioEditado").Text.ToDecimal, Gv.DataKey("PU").ToDecimal)
Dim Total As Decimal = (Cantidad * PU)
Dim TotalImpuestos As Decimal = (Cantidad * PU) - Descuento
Dim ImporteIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIVA").ToString.ToDecimal
Dim ImporteRetIVA As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetIVA").ToString.ToDecimal
Dim ImporteRetISR As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeRetISR").ToString.ToDecimal
Dim ImporteIEPS As Decimal = TotalImpuestos * Gv.DataKey("PorcentajeIEPS").ToString.ToDecimal
AgregaTempDT(Gv.DataKey("CvePS").ToString.ToEntero, Gv.DataKey("PS").ToString, Gv.DataKey("Codigo").ToString, Gv.DataKey("CodigoPS").ToString,
Gv.DataKey("CveTipoPS").ToString.ToEntero, Gv.DataKey("CveTipoInvPS").ToString.ToEntero,
Gv.DataKey("CveUM").ToString.ToEntero, Gv.DataKey("UM").ToString, Gv.DataKey("CveClasificacion").ToString.ToEntero,
Gv.DataKey("Clasificacion").ToString, Gv.DataKey("CveProyecto").ToString.ToEntero, Gv.DataKey("Proyecto").ToString,
Gv.DataKey("CveSubProyecto").ToString.ToEntero, Gv.DataKey("SubProyecto").ToString,
Gv.DataKey("Obs").ToString, Cantidad, PU, Gv.DataKey("PorcentajeIVA").ToString.ToDecimal, ImporteIVA,
Gv.DataKey("PorcentajeRetIVA").ToString.ToDecimal, ImporteRetIVA,
Gv.DataKey("PorcentajeRetISR").ToString.ToDecimal, ImporteRetISR, Gv.DataKey("PorcentajeIEPS").ToString.ToDecimal,
ImporteIEPS, -1, Descuento, Total, "", "", -1, -1,
Gv.DataKey("SATClaveProdServ").ToString, Gv.DataKey("SATClaveUM").ToString, -1, Gv.DataKey("CveVentaDetalle").ToString.ToEntero, -1, -1, -1, -1)
End If
Next
LimpiaDocumentoDEV()
CambiaTipoDocto()
CargaNC(CveVenta)
CalculaTotalesVenta()
RegistraScript("$('#DivAplicaDevolucion').modal('hide')")
End Sub
Protected Sub GvAplicaDevolucion_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCTextBox("TxtCantidadAplicaDevolucion").Attributes.Add("onkeyup", $"LimitaCantidadAplicaDev({e.Row.DBCampo("CantRes").ToDecimal}, this);")
If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Or UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then
e.Row.FCLabel("LblProyecto").Text = e.Row.FCLabel("LblSubProyecto").Text
e.Row.FCLabel("LblProyecto").Style.Clear()
e.Row.FCLabel("LblSubProyecto").Text = ""
End If
End If
End Sub
Private Sub LimpiaDocumentoDEV()
'REINICIALIZA PORLET CLIENTES
ChkEnviarFactura.Enabled = True
'ACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto")
TxtCodigo.ReadOnly = False
'REINICIALIZA PORLET DATOS DE EMIISION
trNCFactura.Visible = True
DdlSubProyectoDatos.Enabled = True
TrFolioFiscal.Visible = False
TxtFecha.Text = Now.ToShortDateString()
TipoCambioFactura = TxtTipoCambio.Text.ToDecimal
If DdlMoneda.SelectedValue.ToEntero > 1 Then
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
TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString
DivEstatusFac.Visible = False
'REINICIALIZA TABS
TabAlmacen.Enabled = False
TabE.Enabled = False
'REINICIALIZA GENERALES PS
LbAgregar.Visible = False
GvPS.Columns(17).Visible = False
GvPS.Columns(18).Visible = False
GvPS.Columns(19).Visible = False
GvPS.Columns(20).Visible = False
DivRemisionesFacturadas.Visible = False
DivAnticiposVinculados.Visible = False
'REINICIALIZA TOTALES
TrConversionDolares.Visible = False
'ACTIVA CONDICIONES DE PAGO
DdlUsoCFDI.Enabled = True
DdlUsoCFDI.SelectedValueExist("2")
DdlMetodoPago33.Enabled = True
DdlMetodoPago33.SelectedValueExist("1")
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
DdlFormaPago33.Enabled = True
DdlFormaPago33.SelectedValueExist("11")
'REINICIALIZA OBSERVACIONES
TxtObsFact.Enabled = True
TxtOrdenCompra.Enabled = True
TxtPedidoContrato.Enabled = True
TxtObsAlmacen.Enabled = True
'DESACTIVA/ACTIVA BOTONES
BtnCrearApartirDe.Visible = False
BtnEmitirImprimir.Visible = True
BtnVistaPrevia.Visible = True
BtnEmitir.Visible = False
'REINICIALIZA ACCIONES
LkDevolucion.Visible = False
'LkNotaCredito.Visible = False
LkEliminarFactura.Visible = False
ImgDownCancelacion.Visible = False
LkRefacturacion.Visible = False
HLOrdenServicio.Visible = False
LkCotizacionAutorizar.Visible = False
LnkFacturarRemision.Visible = False
LnkRemisiones.Visible = False
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
LnkOCs.Visible = False
LbCancelarDocumento.Visible = False
LBCancelarPedido.Visible = False
LiDevolucionAlmacen.Visible = False
HLPagar.Visible = False
HlAgregarExcel.Visible = False
HplDownXML.Visible = False
HplDownPDF.Visible = False
HLSaldarVenta.Visible = False
LBNotaCredito.Visible = False
LiComplementoPago.Visible = False
HlCuentaTerminal.Visible = False
LiLnkGuias.Visible = False
LiDocumentoCliente.Visible = False
LBAplicaDevolucion.Visible = False
HplFolioFiscalModal.Visible = False
'Limpia Anticipos Seleccionados
For Each row2 As GridViewRow In GVAnticipos.Rows
If row2.RowType = DataControlRowType.DataRow Then
row2.FCCheckBox("Chk" & row2.RowIndex).Checked = False
End If
Next
UpAnticipos.Update()
UpParametros.Update()
UpPS.Update()
UpEstatus.Update()
UpCliente.Update()
UpRemisiones.Update()
Updatetabs.Update()
UpFacturar.Update()
UPCondicionesPago.Update()
UpnTools.Update()
UPObservaciones.Update()
UpAntNC.Update()
End Sub
#End Region
#Region "COMERCIO EXTERIOR"
'Public Sub InicializaComercioExterior()
' 'CargoComercioExterior = True
' '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 = GlobalDTPais()
DdlComExtPais.DataBind()
DdlComExtPais.SelectedValueExist("151")
End Sub
Private Sub CargaEstado()
DdlComExtEstado.Items.Clear()
If DdlComExtPais.SelectedValue.ToEntero > 0 Then
DdlComExtEstado.DataSource = GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString)
End If
DdlComExtEstado.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlComExtEstado.DataBind()
End Sub
Private Sub CargaMunicipio()
DdlComExtMunicipio.Items.Clear()
If DdlComExtEstado.SelectedValue.ToEntero > 0 Then
DdlComExtMunicipio.DataSource = GlobalDTMunicipio(GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString).FiltraParametros($"CveEstado = {DdlComExtEstado.SelectedValue.ToEntero}")(0)("ClaveSATEstado").ToString)
End If
DdlComExtMunicipio.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlComExtMunicipio.DataBind()
DdlComExtMunicipio.Visible = True
End Sub
Private Sub CargaColonia()
DdlComExtColonia.Items.Clear()
If DdlComExtMunicipio.SelectedValue.ToEntero > 0 Then
DdlComExtColonia.DataSource = GlobalDTColonia(GlobalDTMunicipio(GlobalDTEstado(GlobalDTPais.FiltraParametros($"CvePais = {DdlComExtPais.SelectedValue.ToEntero}")(0)("ClaveSATPais").ToString).FiltraParametros($"CveEstado = {DdlComExtEstado.SelectedValue.ToEntero}")(0)("ClaveSATEstado").ToString).FiltraParametros($"CveMunicipio = {DdlComExtMunicipio.SelectedValue.ToEntero}")(0)("ClaveSATMunicipio").ToString)
End If
DdlComExtColonia.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlComExtColonia.DataBind()
DdlComExtColonia.Visible = True
End Sub
Protected Sub DdlPais_SelectedIndexChanged(sender As Object, e As EventArgs)
'si contiene MX, USA o CANADA carga ddls, si no carga txt
If DdlComExtPais.SelectedValue.Contiene("151", "66", "40") Then
DdlComExtEstado.Visible = True
DdlComExtMunicipio.Visible = True
DdlComExtColonia.Visible = True
TxtComExtEstado.Visible = False
TxtComExtMunicipio.Visible = False
TxtComExtColonia.Visible = False
CargaEstado()
CargaMunicipio()
CargaColonia()
Else
DdlComExtEstado.Visible = False
DdlComExtMunicipio.Visible = False
DdlComExtColonia.Visible = False
TxtComExtEstado.Visible = True
TxtComExtMunicipio.Visible = True
TxtComExtColonia.Visible = True
End If
End Sub
Protected Sub DdlEstado_SelectedIndexChanged(sender As Object, e As EventArgs)
'si contiene USA o CANADA carga txt
If DdlComExtPais.SelectedValue.Contiene("151") Then
CargaMunicipio()
CargaColonia()
Else
If DdlComExtPais.SelectedValue.Contiene("66", "40") Then
DdlComExtMunicipio.Visible = False
DdlComExtColonia.Visible = False
TxtComExtMunicipio.Visible = True
TxtComExtColonia.Visible = True
End If
End If
End Sub
Protected Sub DdlMunicipio_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaColonia()
End Sub
Private Sub BtnComExtConvertirUnidad_Click(sender As Object, e As EventArgs) Handles BtnComExtConvertirUnidad.Click
For Each gvr As GridViewRow In GvComercioExterior.Rows
gvr.FCTextBox("TxtCantidad").Text = (gvr.FCTextBox("TxtCantidad").Text.ToDecimal * TxtComExtConvertir.Text.ToDecimal).ToString
gvr.FCTextBox("TxtValorUnitario").Text = (gvr.FCTextBox("TxtValorUnitario").Text.ToDecimal / TxtComExtConvertir.Text.ToDecimal).ToString
Next
End Sub
#End Region
Private Sub BtnFolioFiscalAsignar_Click(sender As Object, e As EventArgs) Handles BtnFolioFiscalAsignar.Click
Dim ObjVentas As New ClsVentas()
If ObjVentas.UpdateVentaFolioFiscal(TxtModalFolioFiscal.Text.Trim, CveVenta, UsuarioActual.CveEmpresa) Then
Alert("Folio asignado", TipoMensaje.MsgInformacion)
RegistraScript("$('#ModalFolioFiscal').modal('hide')")
End If
ObjVentas.Dispose()
End Sub
#Region "FORMATO CICOVISA"
Protected Sub LnkImprimirFormatoCicovisa_Click(sender As Object, e As EventArgs)
Dim ObjVentas As New ClsVentas
Dim ObjInventario As New ClsInventarios
Dim SerieFolio As String = ""
Dim PedidoContrato As String = ""
Dim EnvioContacto As String = ""
Dim EnvioDireccion As String = ""
Dim Guia As String = ""
If ObjInventario.GetPaqueteriaGuia(-1, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then
If ObjInventario.DtResultados.Rows.Count > 0 Then
Guia = ObjInventario.DtResultados.Rows(0)("Guia").ToString
End If
End If
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
SerieFolio = ObjVentas.DtResultados.Rows(0)("SerieFolio").ToString
PedidoContrato = ObjVentas.DtResultados.Rows(0)("PedidoContrato").ToString
EnvioContacto = ObjVentas.DtResultados.Rows(0)("EnvioContacto").ToString
EnvioDireccion = $"{ObjVentas.DtResultados.Rows(0)("EnvioDireccion").ToString}, NO. EXT: {ObjVentas.DtResultados.Rows(0)("EnvioNoExt").ToString}, COLONIA: {ObjVentas.DtResultados.Rows(0)("EnvioColonia").ToString}, CP: {ObjVentas.DtResultados.Rows(0)("EnvioCP").ToString}"
End If
End If
Dim Dt As DataTable = Nothing
If ObjVentas.GetVentaDetalle(CveVenta) Then
Dt = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
ObjInventario.Dispose()
If Dt.Rows.Count > 0 Then
Dim params As New List(Of ReportParameter)
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre))
params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString))
params.Add(New ReportParameter("EnvioContacto", EnvioContacto))
params.Add(New ReportParameter("SerieFolio", SerieFolio))
params.Add(New ReportParameter("PedidoContrato", PedidoContrato))
params.Add(New ReportParameter("EnvioDireccion", EnvioDireccion))
params.Add(New ReportParameter("Guia", Guia))
ImprimirPDF("Empresas/Grales/Formatos/Cicovisa.rdlc", Dt, params, String.Format("Formato Cicovisa -{0}", Now.ToDateTime.ToShortDateString))
End If
End Sub
#End Region
#Region "REQUIERE OC"
Protected Sub btnBuscarOCRegistrada_Click(sender As Object, e As EventArgs)
Dim ObjVentas As New ClsVentas
If CveCliente > 0 AndAlso TxtOrdenCompra.Text.Trim <> "" AndAlso CveVenta <= 0 Then
If ObjVentas.GetOCVentas(CveCliente, TxtOrdenCompra.Text) Then
If ObjVentas.DtResultados.Rows.Count > 0 Then
Alert("Ya existen ventas con el mismo folio de orden de compra registrado", TipoMensaje.MsgAdvertencia)
End If
End If
End If
ObjVentas.Dispose()
End Sub
#End Region
#Region "CLASIFICACIONES DETALLES"
Protected Sub DdlClasificacionPS_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaClasificacionesDetalles()
End Sub
Protected Sub BtnAddClasificacionDetalle_Click(sender As Object, e As EventArgs)
TxtClasificacionDetalle.Text = ""
DdlClasificacionModal.SelectedValueExist(DdlClasificacionPS.SelectedValue)
UpModal.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DModalClasificacion"))
End Sub
Protected Sub BtnAddClasificacionDetalleModal_Click(sender As Object, e As EventArgs)
Dim ObjVentas As New ClsVentas
If ObjVentas.AddClasificacionDetalle(TxtClasificacionDetalle.Text, DdlClasificacionModal.SelectedValue.ToEntero,
UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then
CargaClasificacionesDetalles()
DdlTipo.SelectedValueExist(ObjVentas.CveClasificacionDetalle)
UpAddPS.Update()
RegistraScript(String.Format("$('#{0}').modal('hide');", "DModalClasificacion"), "1")
RegistraScript("CreaDescripcionPS();", "2")
End If
ObjVentas.Dispose()
End Sub
Private Sub GVAnticipos_PageIndexChanged(sender As Object, e As EventArgs) Handles GVAnticipos.PageIndexChanged
End Sub
Private Sub DdlTipoAmortizacionAnticipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoAmortizacionAnticipo.SelectedIndexChanged
divAnticipoMsg.Visible = False
If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("1", "2") Then
'cuando es amortización por descuento, debe tener seleccionado descuentos previamente registrados
If DdlTipoAmortizacionAnticipo.SelectedValue = "1" AndAlso LblDescuentos.Text.ToDecimal <= 0 Then
divAnticipoMsg.Visible = True
End If
If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then DivConceptoNC.Visible = True Else DivConceptoNC.Visible = False
DdlTipoRelacion.SelectedValueExist("7")
Else
DivConceptoNC.Visible = False
DdlTipoRelacion.SelectedValueExist("-1")
End If
End Sub
Private Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMetodoPago33.SelectedIndexChanged
CambiaMetodoPago33()
End Sub
Private Sub CambiaMetodoPago33()
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
End Sub
#End Region
#Region " COTIZACIONES - EDITAR "
Private Sub BtnPermisoEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnPermisoEditarCotizacion.Click
ModalidadEdicion = True
'ACTIVA BOTONES PARA EDITAR
For Each Row As GridViewRow In GvPS.Rows
Row.FCLiteral("LtlConsecutivo").Text = (Row.RowIndex + 1).ToString()
Next
GvPS.Columns(ColumnaEditar).HeaderText = "Editar"
GvPS.Columns(ColumnaEliminar).HeaderText = "Eliminar"
GvPS.DataSource = TmpDT
GvPS.DataBind()
'PORLET CLIENTE
'ACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto")
TxtCodigo.ReadOnly = False
ChkEnviarFactura.Enabled = True
DdlSucursalCliente.Enabled = True
ChkDireccionEnvio.Enabled = True
DdlDireccionEnvio.Enabled = True
TxtAtencionA.Enabled = True
TxtFechaVencimientoCotizacion.Enabled = True
'BOTONERA
BtnGenerarRemision.Visible = False
BtnCrearApartirDe.Visible = False
BtnEmitirImprimir.Visible = False
BtnGenerarOS.Visible = False
TxtCantidad.Enabled = True
DdlClasificacion.Enabled = True
DdlPS.Enabled = True
TxtObsPS.Enabled = True
DdlProyecto.Enabled = True
DdlSubProyecto.Enabled = True
TxtPrecio.Enabled = True
LbAgregar.Enabled = True
LnkAgregarPyME.Enabled = True
ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';")
LblSubTotal1.Text = TxtSubTotal.Text
LblAmort.Text = TxtSubTotal.Text
TxtTiempoEntrega.Enabled = True
DdlVendedor.Enabled = True
TxtObsFact.Enabled = True
TxtMotivoDescuento.Enabled = True
BtnEditarCotizacion.Visible = True
BtnPermisoEditarCotizacion.Visible = False
DdlFormaPago33.Enabled = True
DdlUsoCFDI.Enabled = True
DdlMetodoPago33.Enabled = True
'TxtNumCtaPago.Enabled = True
DdlMoneda.Enabled = True
TxtPedidoContrato.Enabled = True
TxtOrdenCompra.Enabled = True
If DdlMoneda.SelectedValue = "2" Then
TrConversionTipoCambio.Visible = True
End If
ChkConvertirDoctoPesos.Enabled = True
TxtTipoCambio.Enabled = True
TxtTotal.ReadOnly = False
TxtTotal.Attributes("readonly") = "readonly"
RBLPago.Enabled = True
RBLPago.Items(0).Enabled = True
GvImpuestosLocales2.Enabled = True
UpPS.Update()
UPPDescuento.Update()
UPObservaciones.Update()
UPCondicionesPago.Update()
UpCliente.Update()
End Sub
Private Sub BtnEditarCotizacion_Click(sender As Object, e As EventArgs) Handles BtnEditarCotizacion.Click
If Not TmpDT.Rows.Count > 0 Then
Alert("Es necesario agregar al menos un producto o servicio a la factura.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim Moneda As Integer = DdlMoneda.SelectedValue.ToEntero
Dim TipoCambio As Double = TxtTipoCambio.Text.Trim.ToDecimal
If DdlMoneda.SelectedValue.ToEntero <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then
TipoCambio = 1
Moneda = 1
End If
Dim ObjVentas As New ClsVentas
Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL())
Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL())
Dim OcurrioError = False
Dim MensajeError = ""
'ACTUALIZA VENTA
If Not ObjVentas.UpdateVentas(TxtSubTotal.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), LblDescuentos.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtIVA.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtIEPS.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), TxtTotal.Text.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)),
Moneda, TipoCambio, TxtFecha.Text.Trim.ToDate, TxtObsFact.Text.Trim,
UsuarioActual.CveEmpresa, CveVenta, 0, 0,
Vigencia:=TxtFechaVencimientoCotizacion.Text.Trim.ToDate, CondicionesPago:=If(RBLPago.SelectedValue = "2", 0, 1),
PedidoContrato:=TxtPedidoContrato.Text, AtencionA:=TxtAtencionA.Text.Trim, CveMetodoPago33:=DdlMetodoPago33.SelectedValue.ToEntero, CveFormaPago33:=DdlFormaPago33.SelectedValue.ToEntero,
CveCliente:=CveCliente, CveClienteSucursal:=CveClienteSucursal, OrdenCompra:=TxtOrdenCompra.Text, RetIVA:=TxtRetIVA.Text.ToDecimal, RetISR:=TxtRetISR.Text.ToDecimal,
TipoDocto:=DdlTipoComprobante.SelectedValue) Then
MensajeError = "Ocurrió un error al actualizar la información de la cotización"
OcurrioError = True
End If
'ELIMINA DETALLES
If Not ObjVentas.RemoveVentasDetalle(CveVenta) Then
MensajeError = "Ocurrió un error al actualizar las partidas de la cotización"
OcurrioError = True
End If
'RE-INSERTA DETALLES
For Each Row As DataRow In TmpDT.Rows
If Not ObjVentas.AddVentaDetalle(CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero,
Row("PU").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("ImporteIVA").ToString.ToDouble, Math.Round((Row("Total").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)) * (1 + Row("PorcentajeIVA").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)))), 6),
Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero,
PorcentajeIVA:=Row("PorcentajeIVA").ToString.ToDecimal, IEPS:=Row("IEPS").ToString.ToDouble(If(ChkConvertirDoctoPesos.Checked, TxtTipoCambio.Text.ToDecimal, 1)), PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, TiempoEntrega:=Row("TiempoEntrega").ToString) Then
MensajeError = "Ocurrió un error al guardar las partidas de la cotización"
OcurrioError = True
Exit For
End If
Next
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
If Not ObjVentas.UpdateVentaImpuestoLocales(CveVenta, gvr.DataKey("CveImpuestoLocal").ToString.ToEntero, gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDouble) Then
MensajeError = "Ocurrió un error al actualizar los impuestos locales"
OcurrioError = True
End If
End If
Next
'ORDEN PRODUCCION
If UsuarioActual.CveEmpresa.Contiene(126) Then
If CveVenta > 0 And DdlOrdenProduccion.SelectedValue.ToEntero > 0 Then
If Not ObjCGame.UpdateOrdenProduccionVenta(DdlOrdenProduccion.SelectedValue.ToEntero(), CveVenta) Then
MensajeError = "Ocurrió un error al actualizar la orden de producción"
OcurrioError = True
End If
End If
End If
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
If OcurrioError Then
ObjVentas.RollBack()
Alert($"{MensajeError}. Por favor vuelva a intentar.", TipoMensaje.MsgError)
Else
ObjVentas.Commit()
'ELIMINA PDF VIEJO
Dim ArchivoPDF = New System.IO.FileInfo(String.Format("{0}PDF\{1}\{2}-{3}.pdf", UsuarioActual.Empresa.Ruta, DdlTipoComprobante.SelectedValue, Serie, Folio))
If ArchivoPDF.Exists Then
ArchivoPDF.Delete()
End If
'GENERA PDF NUEVO
GeneraPDFCotizacion(ChkEnviarFactura.Checked)
Alert("Los cambios se guardaron correctamente.", TipoMensaje.MsgInformacion, "document.location.href=""/Ventas/Ventas.aspx?CveVenta=" & CveVenta & "&&Tipo=Cot"";")
End If
ObjVentas.Dispose()
ObjConta.Dispose()
ObjCGame.Dispose()
End Sub
#End Region
#Region " COTIZACIONES - SIN FACTURAR "
Private Sub LnkCotizaciones_Click(sender As Object, e As EventArgs) Handles LnkCotizaciones.Click
If ChkCotProductos.Checked Then
CargaCotizacionesxProducto()
Else
CargaCotizaciones()
End If
RegistraScript("$('#DivCotizaciones').modal('show');")
End Sub
Private Sub BtnConsultarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnConsultarCotizaciones.Click
If ChkCotProductos.Checked Then
CargaCotizacionesxProducto()
Else
CargaCotizaciones()
End If
End Sub
Private Sub ChkCotProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkCotProductos.CheckedChanged
If ChkCotProductos.Checked Then
GvCotPS.Visible = True
GvCot.Visible = False
DivFiltroCotPS.Visible = True
DivFiltroCot.Visible = False
GvCot.DataSource = Nothing
GvCot.DataBind()
CargaCotizacionesxProducto()
Else
GvCotPS.Visible = False
GvCot.Visible = True
DivFiltroCotPS.Visible = False
DivFiltroCot.Visible = True
GvCotPS.DataSource = Nothing
GvCotPS.DataBind()
CargaCotizaciones()
End If
End Sub
Private Sub CargaCotizaciones()
Dim ObjVentas As New ClsVentas
If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 1) Then
DtCotizaciones = ObjVentas.DtResultados
If Not DtCotizaciones.Columns.Contains("Aplicado") Then
DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean"))
End If
GvCot.DataSource = DtCotizaciones
End If
ObjVentas.Dispose()
GvCot.DataBind()
UpCotizacionesFacturas.Update()
End Sub
Private Sub CargaCotizacionesxProducto()
Dim ObjVentas As New ClsVentas
If ObjVentas.GetCotizacionesSinFacturar(txtFechaICot.Text, txtFechaFCot.Text, CveCliente, 2) Then
DtCotizaciones = ObjVentas.DtResultados
If Not DtCotizaciones.Columns.Contains("Aplicado") Then
DtCotizaciones.Columns.Add("Aplicado", Type.GetType("System.Boolean"))
End If
GvCotPS.DataSource = DtCotizaciones.FiltraParametros("Cantidad > 0")
End If
ObjVentas.Dispose()
GvCotPS.DataBind()
UpCotizacionesFacturas.Update()
End Sub
Protected Sub BtnGuardarCotizaciones_Click(sender As Object, e As EventArgs) Handles BtnGuardarCotizaciones.Click
If GvCot.Rows.Count = 0 And GvCotPS.Rows.Count = 0 Then
Alert("Debe existir por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'MARCA LAS SELECCIONADAS
VerificaCotizaciones(DtCotizaciones)
Dim DTSeleccionadas = DtCotizaciones.FiltraParametros("Aplicado = True")
If DTSeleccionadas.Rows.Count = 0 Then
Alert("Debe seleccionar por lo menos una cotización a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then
Alert("Solo debe seleccionar cotizaciones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'")
DdlMoneda.Enabled = False
CambiaMoneda()
'LIMPIA LAS PARTIDAS ACTUALES
If GvPS.Rows.Count > 0 Then
TmpDT.Rows.Clear()
TxtSubTotal.Text = "0.00"
TxtSubTotal2.Text = "0.00"
TxtIVA.Text = "0.00"
TxtIEPS.Text = "0.00"
TxtRetISR.Text = "0.00"
TxtRetIVA.Text = "0.00"
TxtTotal.Text = "0.00"
HdnIVAOriginal.Value = "0.00"
End If
Dim Cves As New StringBuilder
Dim CveMetodoPago As Integer = -1
Dim MetodoPagoDif As Boolean = False
If ChkCotProductos.Checked Then
For Each row As DataRow In DTSeleccionadas.Rows
If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then
MetodoPagoDif = True
End If
CveMetodoPago = row("CveMetodoPago33").ToString.ToEntero
Cves.Append($"{row("CveVentaDetalle").ToString},")
Next
For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows
CotizacionesLista.Add(row("CveVenta").ToString.ToEntero)
Next
Else
For Each row As DataRow In DTSeleccionadas.Rows
If CveMetodoPago <> -1 And row("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then
MetodoPagoDif = True
End If
Cves.Append($"{row("CveVenta").ToString},")
CotizacionesLista.Add(row("CveVenta").ToString.ToEntero)
CveMetodoPago = row("CveMetodoPago33").ToString.ToEntero
Next
End If
If MetodoPagoDif Then
Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia)
End If
Cves.Remove(Cves.Length - 1, 1)
Dim ObjClientes As New ClsClientes
If ObjClientes.GetVentasCotizacionesTotales(CveCliente, Cves.ToString, If(ChkCotProductos.Checked, 2, 1)) Then
DtCotizacionesPS = ObjClientes.DtResultados
End If
ObjClientes.Dispose()
If Not AgregaPSCotizacion() Then
Alert("Ocurrió un error validar las partidas de las cotizaciones seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'BtnEmitirImprimir.Text = "Facturar"
Dim CveTipoDocto = DdlTipoComprobante.SelectedValue
DdlTipoComprobante.Items.Clear()
DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing"))
DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant"))
DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem"))
DdlTipoComprobante.SelectedIndex = 0
DdlTipoComprobante.SelectedValueExist(CveTipoDocto)
CambiaTipoComprobante()
'DdlTipoComprobante.Enabled = False
UpRemisionesFacturas.Update()
UpFacturar.Update()
UpPS.Update()
UpParametros.Update()
RegistraScript("$('#DivCotizaciones').modal('hide');")
End Sub
Private Sub VerificaCotizaciones(ByRef dt As DataTable)
If ChkCotProductos.Checked Then
For Each Gvr As GridViewRow In GvCotPS.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero
Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
Next
Else
For Each Gvr As GridViewRow In GvCot.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero
Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
Next
End If
End Sub
Private Function IndiceGVCotDataKey(GridView As GridView, DataKeyValue As String) As Integer
For Each row As GridViewRow In GridView.Rows
If row.DataKey("CveVentaDetalle") = DataKeyValue Then
Return row.RowIndex
End If
Next
Return Nothing
End Function
Private Function AgregaPSCotizacion() As Boolean
If DtCotizacionesPS IsNot Nothing Then
Dim tCantidad As Decimal = 0
For Each Dr As DataRow In DtCotizacionesPS.Select()
tCantidad = If(ChkCotProductos.Checked, GvCotPS.Rows(IndiceGVCotDataKey(GvCotPS, Dr("CveVentaDetalle").ToString)).FCTextBox("TxtCantidadCot").Text.ToDecimal, Dr("Cantidad")).ToString.ToDecimal
AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString,
Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal,
Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString,
CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero, CveVentaDetalleCotizacion:=Dr("CveVentaDetalle").ToString.ToEntero)
Next
CalculaTotalesVenta()
Return True
Else
Return False
End If
End Function
#End Region
#Region " COTIZACIONES - FACTURAR "
Private Function PreparaFacturarCotizacion() As Boolean
'LIMPIAMOS
TmpDT.Rows.Clear()
TxtSubTotal.Text = "0.00"
TxtSubTotal2.Text = "0.00"
TxtIVA.Text = "0.00"
TxtIEPS.Text = "0.00"
TxtRetIVA.Text = "0.00"
TxtRetISR.Text = "0.00"
TxtTotal.Text = "0.00"
HdnIVAOriginal.Value = TxtIVA.Text
CreaDTVentas()
If CveEmpresaCRM > 0 And CveAcercamientoCRM > 0 And Not CveCliente > 0 Then
Alert(String.Format("La Empresa CRM no tiene un Cliente vinculado. Por favor verifique y vuelva a intentar.<br/><br/>
<b><a target='_blank' class='Texto' href=""/Ventas/Clientes.aspx?CveEmpresaCRM={0}"">Crear Cliente</a></b><br/>", CveEmpresaCRM), TipoMensaje.MsgAdvertencia)
Return False
End If
Dim ObjClientes As New ClsClientes
If ObjClientes.GetVentasCotizacionesTotales(CveCliente, CveVenta.ToString, 1) Then
DtCotizacionesPS = ObjClientes.DtResultados
End If
ObjClientes.Dispose()
If Not AgregaPSCotizacion() Then
Alert("Ocurrió un error al agregar los conceptos de la cotización. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return False
End If
If TmpDT.Rows.Count = 0 Then
Alert("No hay conceptos por facturar de esta cotización o ha sido cambiada su información. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return False
End If
Return True
End Function
#End Region
#Region " REMISIONES - SIN FACTURAR "
Protected Sub ChkCanRem_CheckedChanged(sender As Object, e As EventArgs)
If ChkCanRem.Checked Then
DivGvCancelarRemision.Visible = True
Else
DivGvCancelarRemision.Visible = False
End If
UpCancelarDocumento.Update()
End Sub
Private Sub LnkRemisiones_Click(sender As Object, e As EventArgs) Handles LnkRemisiones.Click
Dim ObjContratos As New ClsContratos
If ObjContratos.GetContratos(-1, UsuarioActual.CveEmpresa, CveCliente, -1) Then
DdlFiltroContrato.DataSource = ObjContratos.DtResultados
DdlFiltroContrato.DataBind()
DdlFiltroContrato.Items.Insert(0, New ListItem("Remisiones sin Contrato", "-1"))
End If
DdlFiltroRemMoneda.Items.Clear()
DdlFiltroRemMoneda.DataSource = GlobalDTMonedas
DdlFiltroRemMoneda.DataBind()
DdlFiltroRemMoneda.Items.Insert(0, New ListItem("Todas", "-1"))
GvContratoDetalles.DataSource = Nothing
GvContratoDetalles.DataBind()
UpContratos.Update()
DivEstimaciones.Visible = True
ContratoDetalles.Visible = False
UPEstimaciones.Update()
Tab.ActiveTab = TabGenerales
TabGenerales.Enabled = True
Updatetabs.Update()
If ChkRemProductos.Checked Then
CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
Else
CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
End If
RegistraScript("$('#DivRemisiones').modal('show');")
End Sub
Private Sub BtnConsultarRem_Click(sender As Object, e As EventArgs) Handles BtnConsultarRem.Click
If ChkRemProductos.Checked Then
CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
Else
CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
End If
End Sub
Private Sub ChkRemProductos_CheckedChanged(sender As Object, e As EventArgs) Handles ChkRemProductos.CheckedChanged
If ChkRemProductos.Checked Then
GvRemPS.Visible = True
GvRem.Visible = False
DivFiltroRemPS.Visible = True
DivFiltroRem.Visible = False
GvRem.DataSource = Nothing
GvRem.DataBind()
CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
Else
GvRemPS.Visible = False
GvRem.Visible = True
DivFiltroRemPS.Visible = False
DivFiltroRem.Visible = True
GvRemPS.DataSource = Nothing
GvRemPS.DataBind()
CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
End If
End Sub
Private Sub DdlFiltroContrato_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroContrato.SelectedIndexChanged
If ChkRemProductos.Checked Then
CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
Else
CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
End If
End Sub
Private Sub DdlFiltroRemMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlFiltroRemMoneda.SelectedIndexChanged
If ChkRemProductos.Checked Then
CargaRemisionesxProducto(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
Else
CargaRemisiones(DdlFiltroContrato.SelectedValue.ToEntero, DdlFiltroRemMoneda.SelectedValue.ToEntero)
End If
End Sub
Private Sub CargaRemisiones(CveContrato As Integer, CveMoneda As Integer)
Dim ObjVentas As New ClsVentas
If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 1, CveMoneda) Then
If CveContrato = -1 Then
DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0")
Else
DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}")
End If
If Not DTRemisiones.Columns.Contains("Aplicado") Then
DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean"))
End If
GvRem.DataSource = DTRemisiones
End If
ObjVentas.Dispose()
GvRem.DataBind()
UpRemisionesFacturas.Update()
End Sub
Private Sub CargaRemisionesxProducto(CveContrato As Integer, CveMoneda As Integer)
Dim ObjVentas As New ClsVentas
If ObjVentas.GetRemisionesSinFacturar(TxtFechaIRem.Text, TxtFechaFRem.Text, CveCliente, CveContrato, 2, CveMoneda) Then
If CveContrato = -1 Then
DTRemisiones = ObjVentas.DtResultados.FiltraParametros("CveContrato = 0")
Else
DTRemisiones = ObjVentas.DtResultados.FiltraParametros($"CveContrato = {CveContrato}")
End If
If Not DTRemisiones.Columns.Contains("Aplicado") Then
DTRemisiones.Columns.Add("Aplicado", Type.GetType("System.Boolean"))
End If
GvRemPS.DataSource = DTRemisiones
End If
ObjVentas.Dispose()
GvRemPS.DataBind()
UpRemisionesFacturas.Update()
End Sub
Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblTipo.SelectedIndexChanged
HuboCambioRemi = Not HuboCambioRemi
End Sub
Protected Sub BtnGuardarRemisiones_Click(sender As Object, e As EventArgs) Handles BtnGuardarRemisiones.Click
If GvRem.Rows.Count > 0 Or GvRemPS.Rows.Count > 0 Then
'Checa las facturas selecionadas
VerificaRemisiones(DTRemisiones)
Dim dtSeleccionadas As DataTable = DTRemisiones.FiltraParametros("Aplicado = True")
Dim CveContrato = DTRemisiones.FiltroPrimeroValor("CveContrato", "Aplicado = True").ToEntero
If dtSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then
Alert("Solo debe seleccionar remisiones de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{dtSeleccionadas.FiltroPrimeroValor("Abreviatura")}'")
DdlMoneda.Enabled = False
CambiaMoneda()
DdlUsoCFDI.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveUsoCFDI"))
DdlMetodoPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveMetodoPago"))
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
DdlFormaPago33.SelectedValueExist(dtSeleccionadas.FiltroPrimeroValor("CveFormaPago"))
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()
If dtSeleccionadas.Rows.Count > 0 Then
Select Case RblTipo.SelectedValue
Case "1" 'T O T A L G E N E R A L
For Each row As DataRow In dtSeleccionadas.Rows
RemisionesLista.Add(row("CveVenta").ToString.ToEntero)
Next
IsTotalxConcepto = False
Dim PU As Decimal = dtSeleccionadas.SUM("SubTotal").ToDecimal
Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa)(0)
Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16)
Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa)(0)
AgregarProductoServicio(1, PS("CveUM").ToString.ToEntero, PS("UnidadMedida").ToString, PS("CveClasificacion").ToString.ToEntero,
PS("Clasificacion").ToString, PS("CvePS").ToString.ToEntero, PS("PS").ToString, "", PU, 0,
rowSP("CveProyecto").ToString.ToEntero, rowSP("Proyecto").ToString, rowSP("CveSubProyecto").ToString.ToEntero, rowSP("SubProyecto").ToString, RegeneraIEPS:=True)
Case "2" 'T O T A L X R E M I S I O N
For Each row As DataRow In dtSeleccionadas.Rows
RemisionesLista.Add(row("CveVenta").ToString.ToEntero)
Next
Dim PS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa)(0)
Dim rowSP As DataRow = GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa)(0)
Dim IVA As Double = If(dtSeleccionadas.SUM("Iva") > 0, dtSeleccionadas.SUM("Iva") / dtSeleccionadas.SUM("SubTotal"), 0.16)
For Each gvr As GridViewRow In GvRem.Rows
If gvr.FCCheckBox("Chk").Checked Then
AgregarProductoServicio(1, PS("CveUM").ToString.ToEntero, PS("UnidadMedida").ToString, PS("CveClasificacion").ToString.ToEntero,
PS("Clasificacion").ToString, PS("CvePS").ToString.ToEntero, PS("PS").ToString, "", gvr.DataKey("SubTotal").ToString.ToDecimal, 0,
rowSP("CveProyecto").ToString.ToEntero, rowSP("Proyecto").ToString, rowSP("CveSubProyecto").ToString.ToEntero, rowSP("SubProyecto").ToString, RegeneraIEPS:=True)
End If
Next
Case "3" 'T O T A L X C O N C E P T O
IsTotalxConcepto = True
Dim sb As New StringBuilder
If ChkRemProductos.Checked Then
For Each row As DataRow In dtSeleccionadas.Rows
sb.Append($"{row("CveVentaDetalle").ToString},")
Next
For Each row As DataRow In dtSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows
RemisionesLista.Add(row("CveVenta").ToString.ToEntero)
Next
Else
For Each row As DataRow In dtSeleccionadas.Rows
sb.Append($"{row("CveVenta").ToString},")
RemisionesLista.Add(row("CveVenta").ToString.ToEntero)
Next
End If
sb.Remove(sb.Length - 1, 1)
CargaConceptosRemisionPorFacturar(sb.ToString, If(ChkRemProductos.Checked, 2, 1))
End Select
Dim CveTipoDocto = DdlTipoComprobante.SelectedValue
DdlTipoComprobante.Items.Clear()
DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing"))
DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant"))
DdlTipoComprobante.SelectedIndex = 0
DdlTipoComprobante.SelectedValueExist(CveTipoDocto)
CambiaTipoComprobante()
Dim MensajeRemisiones As New StringBuilder
Dim ObsOC As New StringBuilder
Dim ObsPedido As New StringBuilder
Dim ObsInv As New StringBuilder
MensajeRemisiones.Append("Remisiones: ")
Dim CveMetodoPago As Integer = -1
Dim MetodoPagoDif As Boolean = False
For Each Dr As DataRow In dtSeleccionadas.Rows
MensajeRemisiones.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString.Length > 0, $"({Dr("ObsFact")})", ""))
ObsOC.AppendFormat("{0}, ", Dr("ObsOC"))
ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido"))
ObsInv.AppendFormat("{0}, ", Dr("ObsInv"))
If CveMetodoPago <> -1 And Dr("CveMetodoPago33").ToString.ToEntero <> CveMetodoPago Then
MetodoPagoDif = True
End If
CveMetodoPago = Dr("CveMetodoPago33").ToString.ToEntero
Next
TxtObsFact.Text = If(MensajeRemisiones.ToString.Length > 0, MensajeRemisiones.ToString.Substring(0, MensajeRemisiones.ToString.Length - 2), "")
TxtOrdenCompra.Text = If(ObsOC.ToString.Length > 0, ObsOC.ToString.Substring(0, ObsOC.ToString.Length - 2), "")
TxtPedidoContrato.Text = If(ObsPedido.ToString.Length > 0, ObsPedido.ToString.Substring(0, ObsPedido.ToString.Length - 2), "")
TxtObsAlmacen.Text = If(ObsInv.ToString.Length > 0, ObsInv.ToString.Substring(0, ObsInv.ToString.Length - 2), "")
UPObservaciones.Update()
If MetodoPagoDif Then
Alert("Las Facturas tienen un método de pago diferente", TipoMensaje.MsgAdvertencia)
End If
If CveContrato > 0 Then
DdlContrato.DataSource = DtContratos.FiltraParametros($"CveContrato = {CveContrato}")
DdlContrato.DataBind()
End If
End If
End If
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 Sub VerificaRemisiones(ByRef dt As DataTable)
If ChkRemProductos.Checked Then
For Each Gvr As GridViewRow In GvRemPS.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero
Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
Next
Else
For Each Gvr As GridViewRow In GvRem.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero
Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
Next
End If
End Sub
Private Sub CargaConceptosRemisionPorFacturar(CveRemisiones As String, TipoCargas As Integer)
Dim ObjClientes As New ClsClientes
If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveRemisiones, TipoCargas) Then
DtRemisionesPS = ObjClientes.DtResultados
End If
ObjClientes.Dispose()
If DtRemisionesPS IsNot Nothing Then
Dim tCantidad As Decimal = 0
For Each Dr As DataRow In DtRemisionesPS.Select()
tCantidad = If(ChkRemProductos.Checked, GvRemPS.Rows(IndiceGVDataKey(GvRemPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadRem").Text, Dr("Cantidad")).ToString.ToDecimal
AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString,
Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal,
Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString,
CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Dr("CveContratoDetalle").ToString.ToEntero,
CveVentaDetalleRemision:=Dr("CveVentaDetalle").ToString.ToEntero, RegeneraIEPS:=True)
Next
If DdlFiltroContrato.SelectedValue.ToEntero > 0 Then
CveContrato = DdlFiltroContrato.SelectedValue.ToEntero
End If
End If
CalculaTotalesVenta()
End Sub
Private Function IndiceGVDataKey(GridView As GridView, DataKey As String, DataKeyValue As String) As Integer
For Each row As GridViewRow In GridView.Rows
If row.DataKey(DataKey) = DataKeyValue Then
Return row.RowIndex
End If
Next
Return Nothing
End Function
#End Region
#Region " REMISIONES - FACTURAR "
Private Sub ActivaFacturarRemision()
'If UsuarioActual.CveUsuario <> 100 Then
' Exit Sub
'End If
Dim ObjClientes As New ClsClientes
If ObjClientes.GetVentasRemisionesTotales(CveCliente, CveVenta.ToString, 1) AndAlso ObjClientes.DtResultados.Rows.Count > 0 Then
LnkFacturarRemision.Visible = True
If ThCantidadFacturadaRem.Visible Then
LnkFacturarRemision.ToolTip = "¿Seguro que desea facturar lo pendiente por facturar de la remisión?"
End If
If DdlMoneda.SelectedValue.ToEntero = 1 Then
TrConversionDolares.Visible = True
ChkConvertirDolares.Enabled = True
TxtTipoCambioDlls.Enabled = True
Else
TrConversionTipoCambio.Visible = True
ChkConvertirDoctoPesos.Enabled = True
TxtTipoCambio.Enabled = True
End If
UpPS.Update()
End If
ObjClientes.Dispose()
End Sub
Private Sub LnkFacturarRemision_Click(sender As Object, e As EventArgs) Handles LnkFacturarRemision.Click
'LIMPIAMOS
TmpDT.Rows.Clear()
TxtSubTotal.Text = "0.00"
TxtSubTotal2.Text = "0.00"
TxtIVA.Text = "0.00"
TxtIEPS.Text = "0.00"
TxtRetIVA.Text = "0.00"
TxtRetISR.Text = "0.00"
TxtTotal.Text = "0.00"
HdnIVAOriginal.Value = TxtIVA.Text
CreaDTVentas()
CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero > 0, DdlContrato.SelectedValue.ToEntero, -1), DdlMoneda.SelectedValue.ToEntero)
Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}")
If DrRemision.Count > 0 Then
DrRemision(0)("Aplicado") = "True"
End If
DTRemisiones.AcceptChanges()
RemisionesLista.Add(CveVenta)
CargaConceptosRemisionPorFacturar(CveVenta.ToString, 1)
BtnEmitirImprimir.Text = "Facturar"
DdlTipoComprobante.SelectedValue = "Ing"
TxtFecha.Text = Now.ToShortDateString()
UpPS.Update()
UpFacturar.Update()
If TmpDT.Rows.Count = 0 Then
Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
BtnEmitirImprimir_Click(BtnEmitirImprimir, EventArgs.Empty)
End Sub
Private Function PreparaFacturarRemision() As Boolean
'LIMPIAMOS
TmpDT.Rows.Clear()
TxtSubTotal.Text = "0.00"
TxtSubTotal2.Text = "0.00"
TxtIVA.Text = "0.00"
TxtIEPS.Text = "0.00"
TxtRetIVA.Text = "0.00"
TxtRetISR.Text = "0.00"
TxtTotal.Text = "0.00"
HdnIVAOriginal.Value = TxtIVA.Text
CreaDTVentas()
CargaRemisiones(If(DdlContrato.SelectedValue.ToEntero > 0, DdlContrato.SelectedValue.ToEntero, -1), DdlMoneda.SelectedValue.ToEntero)
Dim DrRemision As DataRow() = DTRemisiones.Select($"CveVenta = {CveVenta}")
If DrRemision.Count > 0 Then
DrRemision(0)("Aplicado") = "True"
End If
DTRemisiones.AcceptChanges()
RemisionesLista.Add(CveVenta)
CargaConceptosRemisionPorFacturar(CveVenta.ToString, 1)
If TmpDT.Rows.Count = 0 Then
Alert("No hay conceptos por facturar de esta remisión. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return False
End If
Return True
End Function
#End Region
#Region " PEDIDOS2 - SIN FACTURAR "
Protected Sub LnkPedido2SinFacturar_Click(sender As Object, e As EventArgs)
DdlMonedaModalPedido2.Items.Clear()
DdlMonedaModalPedido2.DataSource = GlobalDTMonedas
DdlMonedaModalPedido2.DataBind()
DdlMonedaModalPedido2.Items.Insert(0, New ListItem("Todas", "-1"))
Tab.ActiveTab = TabGenerales
TabGenerales.Enabled = True
Updatetabs.Update()
CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1))
RegistraScript("$('#DivPedidos2').modal('show');")
End Sub
Private Sub BtnConsultaPedido_Click(sender As Object, e As EventArgs) Handles BtnConsultaPedido.Click
CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1))
End Sub
Protected Sub ChkMostrarProductosPedido2_CheckedChanged(sender As Object, e As EventArgs)
MostrarProductoPedido2()
CargaPedidos2(DdlMonedaModalPedido2.SelectedValue.ToEntero, If(ChkMostrarProductosPedido2.Checked, 0, 1))
End Sub
Private Sub MostrarProductoPedido2()
If ChkMostrarProductosPedido2.Checked Then
GvPedidos2SinFacturarPS.Visible = True
GvPedidos2SinFacturar.Visible = False
DivBuscadorPedido2PS.Visible = True
DivBuscadorPedido2.Visible = False
GvPedidos2SinFacturar.DataSource = Nothing
GvPedidos2SinFacturar.DataBind()
Else
GvPedidos2SinFacturarPS.Visible = False
GvPedidos2SinFacturar.Visible = True
DivBuscadorPedido2PS.Visible = False
DivBuscadorPedido2.Visible = True
GvPedidos2SinFacturarPS.DataSource = Nothing
GvPedidos2SinFacturarPS.DataBind()
End If
End Sub
Private Sub CargaPedidos2(CveMoneda As Integer, Tipo As Integer)
Dim ObjVentas As New ClsVentas
If ObjVentas.GetVentaDetallePedido2SinFacturar(TxtFechaIPed.Text, TxtFechaFPedido.Text, CveCliente, CveMoneda, Tipo) Then
DtPedidos2 = ObjVentas.DtResultados
If Not DtPedidos2.Columns.Contains("Aplicado") Then
DtPedidos2.Columns.Add("Aplicado", Type.GetType("System.Boolean"))
End If
If Tipo = 1 Then
GvPedidos2SinFacturar.DataSource = DtPedidos2
Else
GvPedidos2SinFacturarPS.DataSource = DtPedidos2
End If
End If
ObjVentas.Dispose()
If Tipo = 1 Then
GvPedidos2SinFacturar.DataBind()
Else
GvPedidos2SinFacturarPS.DataBind()
End If
UpModalPedidos2.Update()
End Sub
Protected Sub BtnGuardarPedido2_Click(sender As Object, e As EventArgs)
If GvPedidos2SinFacturar.Rows.Count = 0 And GvPedidos2SinFacturarPS.Rows.Count = 0 Then
Alert("Debe existir por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'MARCA LAS SELECCIONADAS
VerificaPedidos2(DtPedidos2)
Dim DTSeleccionadas As DataTable = DtPedidos2.FiltraParametros("Aplicado = True")
If DTSeleccionadas.Rows.Count = 0 Then
Alert("Debe seleccionar por lo menos un pedido a facturar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'SOLO PUEDE SELECCIONAR DE LA MISMA MONEDA
If DTSeleccionadas.FiltraParametros("", "", {"Abreviatura"}).Rows.Count > 1 Then
Alert("Solo debe seleccionar pedidos de la misma moneda. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'LIMPIA LAS PARTIDAS ACTUALES
If GvPS.Rows.Count > 0 Then
TmpDT.Rows.Clear()
TxtSubTotal.Text = "0.00"
TxtSubTotal2.Text = "0.00"
TxtIVA.Text = "0.00"
TxtIEPS.Text = "0.00"
TxtRetISR.Text = "0.00"
TxtRetIVA.Text = "0.00"
TxtTotal.Text = "0.00"
HdnIVAOriginal.Value = "0.00"
End If
Pedidos2Lista.Clear()
'CARGAMOS LOS VALORES DEL PEDIDO
DdlMoneda.SelectedValue = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $"Abreviatura = '{DTSeleccionadas.FiltroPrimeroValor("Abreviatura")}'")
DdlMoneda.Enabled = False
CambiaMoneda()
DdlMetodoPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveMetodoPago"))
DdlFormaPago33.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveFormaPago"))
DdlUsoCFDI.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveUsoCFDI"))
If DdlSubProyectoDatos.Enabled Then 'validación, cuando los pedido2 sean de una sucursal y el usuario solo tenga acceso a otra, deberá tener priodidad la sucursal de la que solo se factura
DdlSubProyectoDatos.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveSubProyecto"))
End If
DdlSucursalCliente.SelectedValueExist(If(DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal").ToEntero > 0, DTSeleccionadas.FiltroPrimeroValor("CveClienteSucursal"), "-1"))
DdlVendedor.SelectedValueExist(DTSeleccionadas.FiltroPrimeroValor("CveVendedor"))
CambiaSucursalGeneral()
CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero)
Dim Cves As New StringBuilder
If ChkMostrarProductosPedido2.Checked Then
For Each row As DataRow In DTSeleccionadas.Rows
Cves.Append($"{row("CveVentaDetalle").ToString},")
Next
For Each row As DataRow In DTSeleccionadas.FiltraParametros("", DistinctColumns:={"CveVenta"}).Rows
Pedidos2Lista.Add(row("CveVenta").ToString.ToEntero)
Next
Else
For Each row As DataRow In DTSeleccionadas.Rows
Cves.Append($"{row("CveVenta").ToString},")
Pedidos2Lista.Add(row("CveVenta").ToString.ToEntero)
Next
End If
Cves.Remove(Cves.Length - 1, 1)
Dim ObjVentas As New ClsVentas
If ObjVentas.GetVentasPedidos2Totales(CveCliente, Cves.ToString, If(ChkMostrarProductosPedido2.Checked, 2, 1)) Then
DtPedidos2PS = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
If Not AgregaPSPedido2() Then
Alert("Ocurrió un error validar las partidas de los pedidos seleccionadas. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim CveTipoDocto = DdlTipoComprobante.SelectedValue
DdlTipoComprobante.Items.Clear()
DdlTipoComprobante.Items.Insert(0, New ListItem("Ingresos", "Ing"))
DdlTipoComprobante.Items.Insert(1, New ListItem("Anticipos", "Ant"))
DdlTipoComprobante.Items.Insert(2, New ListItem("Remisión", "Rem"))
DdlTipoComprobante.SelectedIndex = 0
DdlTipoComprobante.SelectedValueExist(CveTipoDocto)
CambiaTipoComprobante()
'CARGA OBSERVACIONES DE LOS PEDIDOS
Dim MensajePedidos2 As New StringBuilder
Dim ObsOC As New StringBuilder
Dim ObsPedido As New StringBuilder
Dim ObsInv As New StringBuilder
MensajePedidos2.Append("Pedidos: ")
For Each Dr As DataRow In DTSeleccionadas.Rows
MensajePedidos2.AppendFormat("{0} {1}, ", Dr("Folio"), If(Dr("ObsFact").ToString.Length > 0, $"({Dr("ObsFact")})", ""))
ObsOC.AppendFormat("{0}, ", Dr("ObsOC"))
ObsPedido.AppendFormat("{0}, ", Dr("ObsPedido"))
ObsInv.AppendFormat("{0}, ", Dr("ObsInv"))
Next
TxtObsFact.Text = If(MensajePedidos2.ToString.Length > 0, MensajePedidos2.ToString.Substring(0, MensajePedidos2.ToString.Length - 2), "")
TxtOrdenCompra.Text = If(ObsOC.ToString.Length > 0, ObsOC.ToString.Substring(0, ObsOC.ToString.Length - 2), "")
TxtPedidoContrato.Text = If(ObsPedido.ToString.Length > 0, ObsPedido.ToString.Substring(0, ObsPedido.ToString.Length - 2), "")
TxtObsAlmacen.Text = If(ObsInv.ToString.Length > 0, ObsInv.ToString.Substring(0, ObsInv.ToString.Length - 2), "")
UpModalPedidos2.Update()
UpFacturar.Update()
UpPS.Update()
UpParametros.Update()
UPEstimaciones.Update()
UPObservaciones.Update()
RegistraScript("$('#DivPedidos2').modal('hide');", "DivPedidos2Hide")
End Sub
Private Sub VerificaPedidos2(ByRef dt As DataTable)
If ChkMostrarProductosPedido2.Checked Then
For Each Gvr As GridViewRow In GvPedidos2SinFacturarPS.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveVentaDetalle As Integer = Gvr.DataKey("CveVentaDetalle").ToEntero
Dim Drs As DataRow() = dt.Select($"CveVentaDetalle = {CveVentaDetalle}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
Next
Else
For Each Gvr As GridViewRow In GvPedidos2SinFacturar.Rows
If Gvr.RowType = DataControlRowType.DataRow Then
Dim ChkAplicar As CheckBox = Gvr.FCCheckBox("Chk")
Dim CveVenta As Integer = Gvr.DataKey("CveVenta").ToEntero
Dim Drs As DataRow() = dt.Select($"CveVenta = {CveVenta}")
If Drs.Count > 0 Then
Drs(0)("Aplicado") = ChkAplicar.Checked
End If
dt.AcceptChanges()
End If
Next
End If
End Sub
Private Function AgregaPSPedido2() As Boolean
If DtPedidos2PS IsNot Nothing Then
Dim tCantidad As Decimal = 0
For Each Dr As DataRow In DtPedidos2PS.Select()
tCantidad = If(ChkMostrarProductosPedido2.Checked, GvPedidos2SinFacturarPS.Rows(IndiceGVDataKey(GvPedidos2SinFacturarPS, "CveVentaDetalle", $"{Dr("CveVentaDetalle")}")).FCTextBox("TxtCantidadPedido2").Text, Dr("Cantidad")).ToString.ToDecimal
AgregarProductoServicio(tCantidad, Dr("CveUM").ToString.ToEntero, Dr("UM").ToString, Dr("CveClasificacion").ToString.ToEntero, Dr("Clasificacion").ToString,
Dr("CvePS").ToString.ToEntero, Dr("PS").ToString, Dr("Obs").ToString, Dr("PU").ToString.ToDecimal, Dr("Descuento").ToString.ToDecimal,
Dr("CveProyecto").ToString.ToEntero, Dr("Proyecto").ToString, Dr("CveSubProyecto").ToString.ToEntero, Dr("SubProyecto").ToString,
CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero,
CveVentaDetallePedido2:=Dr("CveVentaDetalle").ToString.ToEntero, RegeneraIEPS:=True)
Next
CalculaTotalesVenta()
Return True
Else
Return False
End If
End Function
#End Region
#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
BtnCrearApartirDe.Visible = False '[IPP-2Novimebre2018] REEMPLAZA LO COMENTADO ARRIBA
EsCreaApartirDe = True
ModalidadEdicion = True
DivEstatusFac.Visible = False
TabAlmacen.Visible = False
'CUANDO ES CREAR APARTIR DE SE LIMPIAN FUNCIONALIDADES DE DOCUMENTOS YA REGISTRADOS
BtnGenerarRemision.Visible = False
BtnPermisoEditarCotizacion.Visible = False
BtnEditarCotizacion.Visible = False
BtnGenerarOS.Visible = False
BtnsFacturar.Visible = False
HLOrdendeCompra.Visible = False
LkDevolucion.Visible = False
LBAplicaDevolucion.Visible = False
'LkNotaCredito.Visible = False
LkEliminarFactura.Visible = False
ImgDownCancelacion.Visible = False
LkRefacturacion.Visible = False
HLOrdenServicio.Visible = False
LkCotizacionAutorizar.Visible = False
LnkFacturarRemision.Visible = False
LnkRemisiones.Visible = False
LnkPedido2SinFacturar.Visible = False
LnkCotizaciones.Visible = False
LnkOCs.Visible = False
LbCancelarDocumento.Visible = False
LBCancelarPedido.Visible = False
LiDevolucionAlmacen.Visible = False
HLPagar.Visible = False
HlAgregarExcel.Visible = False
'REINICIALIZA VALORES DE CANTIDAD FACTURADA - SOLO DEBEN MOSTRARSE AL CARGAR UNA REMISION/COTIZACIÓN
GvPS.Columns(6).Visible = False
ThCantidadFacturadaRem.Visible = False
ThCantidadFacturadaRem2.Visible = False
GvPS.Columns(7).Visible = False
ThCantidadFacturada.Visible = False
ThCantidadFacturada2.Visible = False
'Cuando es cotización, Genera nueva cotizacion
If DdlTipoComprobante.SelectedValue = "Cot" Then
BtnEmitirImprimir.Text = "Cotizar"
'TdReferencia.Style.Add("display", "none")
End If
HplDownXML.Visible = False
HplDownPDF.Visible = False
LblFolioFiscal.Text = ""
DdlTipoComprobante.Enabled = True
TxtFecha.Text = Now.ToShortDateString()
LblUsuario.Text = UsuarioActual.Usuario
LblFechaRegistro.Text = Now.ToShortDateString()
LblSeTimbro.Text = "No"
LblMail.Text = "No"
'PORLET CLIENTE
'ACTIVA CAMBIO DE CLIENTE
HlCliente.Attributes.Remove("class")
HlCliente.Attributes.Add("class", "Texto")
TxtCodigo.ReadOnly = False
ChkEnviarFactura.Enabled = True
DdlSucursalCliente.Enabled = True
ChkDireccionEnvio.Enabled = True
DdlDireccionEnvio.Enabled = True
LnkOtraDireccion.Visible = True
TxtAtencionA.Enabled = True
TxtFechaVencimientoCotizacion.Enabled = True
TxtCantidad.Enabled = True
DdlClasificacion.Enabled = True
DdlPS.Enabled = True
TxtObsPS.Enabled = True
DdlProyecto.Enabled = True
DdlSubProyecto.Enabled = True
TxtPrecio.Enabled = True
LbAgregar.Enabled = True
LnkAgregarPyME.Enabled = True
ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';")
TxtMotivoDescuento.Enabled = True
LblSubTotal1.Text = TxtSubTotal.Text
TxtObsFact.Enabled = True
TxtMotivoDescuento.Enabled = True
TxtSubTotal.ReadOnly = False
TxtIVA.ReadOnly = False
TxtRetIVA.ReadOnly = False
TxtRetISR.ReadOnly = False
TxtTotal.ReadOnly = False
CalculaTotalesVenta()
BtnEmitirImprimir.Visible = True
GvImpuestosLocales2.Enabled = True
'Sección Detalle
DdlMoneda.Enabled = True
ChkConvertirDoctoPesos.Enabled = True
TxtTipoCambio.Enabled = True
TxtFechaEjecucion.ReadOnly = False
TxtFechaEjecucion.Text = Now.ToShortDateString
ImgCalendarFechaEje.Enabled = True
DdlVendedor.Enabled = True
DdlSubProyectoDatos.Enabled = True
DdlSubProyectoEjecucion.Enabled = True
DdlSubProyectoCobranza.Enabled = True
TxtTiempoEntrega.Enabled = True
TxtAlfa1.ReadOnly = False
TxtAlfa2.ReadOnly = False
TxtAlfa3.ReadOnly = False
TxtNum1.ReadOnly = False
TxtNum2.ReadOnly = False
TxtNum3.ReadOnly = False
TxtFech1.ReadOnly = False : ImgFech1.Enabled = True
TxtFech2.ReadOnly = False : ImgFech2.Enabled = True
TxtFech3.ReadOnly = False : ImgFech3.Enabled = True
'Condiciones de Pago
RBLPago.Enabled = True
RBLPago.Items(0).Enabled = True
DdlFormaPago33.Enabled = True
DdlUsoCFDI.Enabled = True
DdlMetodoPago33.Enabled = True
'TxtNumCtaPago.Enabled = True
TxtFechaPago.ReadOnly = False
imgCalendario.Enabled = True
TxtPedidoContrato.Enabled = True
TxtOrdenCompra.Enabled = True
Dim ObjCliente As New ClsClientes()
If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
PlazoCobranza = ObjCliente.PlazoCobranza
PlazoCobranzaRemision = ObjCliente.PlazoCobranzaRemision
'TxtNumCtaPago.Text = ObjCliente.NumCtaPago
TxtFechaPago.Text = If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza)).ToShortDateString
End If
End If
ObjCliente.Dispose()
TrVistaPrevia.Visible = True
TxtFechaVencimientoCotizacion.Text = Now.ToShortDateString
'HABILITA EDITAR Y ELIMINAR DEL GV
GvPS.Columns(17).Visible = True
GvPS.Columns(18).Visible = True
UpnTools.Update()
UpCliente.Update()
UpParametros.Update()
UpPS.Update()
UpFacturar.Update()
UPObservaciones.Update()
UPPDescuento.Update()
UPCondicionesPago.Update()
UpDetalle.Update()
UpEstatus.Update()
CambiaTipoDocto()
CambiaSucursalGeneral()
CargaAnticipos(CveCliente)
CargaRestriccionesCreditoCliente()
UpParametros.Update()
End Sub
#End Region
#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 Sub EmitirDocumentoNuevo(TipoDoctoNuevo As String)
Dim FolioFijo As Integer = 0
'CARGA LO PENDIENTE POR FACTURAR DE COTIZACION
If EraCotizacion = 1 Then
If Not PreparaFacturarCotizacion() Then
EraCotizacion = 0
DdlTipoComprobante.SelectedValue = "Cot"
Exit Sub
End If
End If
'CARGA LO PENDIENTE POR FACTURAR DE REMISION
If DdlTipoComprobante.SelectedValue = "Rem" Then
If Not PreparaFacturarRemision() Then
DdlTipoComprobante.SelectedValue = "Rem"
Exit Sub
End If
End If
'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO2
If DdlTipoComprobante.SelectedValue = "Pd2" Then
If Not PreparaFacturarPedido() Then
DdlTipoComprobante.SelectedValue = "Pd2"
Exit Sub
End If
End If
'CARGA LO PENDIENTE POR FACTURAR DE PEDIDO AUTORIZACION
If DdlTipoComprobante.SelectedValue = "PA" Then ' que tome el folio fijo de la autorización
FolioFijo = TxtFolio.Text.ToEntero
ViewState("FolioActual") = FolioFijo
ViewState("EstablecioFolio") = True
TxtFolio.Text = FolioFijo.ToString
End If
Dim TipoDoctoViejo As String = DdlTipoComprobante.SelectedValue
DdlTipoComprobante.SelectedValue = TipoDoctoNuevo
TxtFecha.Text = Now.ToString
TxtFechaPago.Text = If(TipoDoctoViejo = "Rem" AndAlso EsDiasCreditoFijo, Now.AddDays(DiasCredito), If(DdlTipoComprobante.SelectedValue = "Rem", Now.AddDays(PlazoCobranzaRemision), Now.AddDays(PlazoCobranza))).ToShortDateString
TxtFechaEjecucion.Text = Now.ToString
If FolioFijo = 0 Then CargaFolios() 'RECARGA FOLIOS CON EL NUEVO TIPO DOCTO
EmitirImprimir() 'MANDA A EMITIR - PROCESO VIEJO
End Sub
#End Region
#End Region
#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()
If ClienteEsDistribuidor Then
Dim DTTamanios As New DataTable
Dim ObjAcum As New ClsAcumuladores
If ObjAcum.TamañoGet(-1, UsuarioActual.CveEmpresa) Then
DTTamanios = ObjAcum.DtResultados
Dim DTCvePSCostos As New DataTable
DTCvePSCostos = ObjAcum.DtResultados.FiltraParametros("", "", {"CvePSCargo"})
If Not TmpDT.Columns.Contains("Eliminar") Then
TmpDT.Columns.Add("Eliminar", GetType(Integer))
End If
For Each drow As DataRow In TmpDT.Rows
For Each drow2 As DataRow In DTCvePSCostos.Rows
If drow("CvePS").ToString.ToEntero = drow2("CvePSCargo").ToString.ToEntero Then
drow("Eliminar") = 1
Exit For
End If
Next
Next
Dim TmpDTView As New DataView(TmpDT)
TmpDTView.RowFilter = "Eliminar = 1"
For Each dRowEliminar As DataRowView In TmpDTView
dRowEliminar.Delete()
Next
TmpDT.AcceptChanges()
Dim ObjProductosServicios As New ClsProductosServicios()
Dim CveUnidadMedidaPSA As Integer = -1
Dim UnidadMedidaPSA As String = "Unidad"
Dim CveClacificacionPSA As Integer = -1
Dim ClacificacionPSA As String = ""
Dim CveSubProyectoPSA As Integer = -1
Dim SubProyectoPSA As String = ""
Dim PSPSA As String = ""
Dim DTPSTemp As New DataTable '= TmpDT.Clone
'AgregarProductoServicio(1, CveUnidadMedidaPSA, UnidadMedidaPSA, CveClacificacionPSA, ClacificacionPSA, CvePSPSA, PSPSA, "", ImporteCargo, 0, -1, "", CveSubProyectoPSA, SubProyectoPSA)
DTPSTemp.Columns.Add("Cantidad", GetType(Integer))
DTPSTemp.Columns.Add("CveUnidadMedida", GetType(Integer))
DTPSTemp.Columns.Add("UnidadMedida", GetType(String))
DTPSTemp.Columns.Add("CveClacificacion", GetType(Integer))
DTPSTemp.Columns.Add("Clacificacion", GetType(String))
DTPSTemp.Columns.Add("CvePS", GetType(Integer))
DTPSTemp.Columns.Add("PS", GetType(String))
DTPSTemp.Columns.Add("PU", GetType(Decimal))
DTPSTemp.Columns.Add("CveSubProyecto", GetType(Integer))
DTPSTemp.Columns.Add("SubProyecto", GetType(String))
For Each DrowPartidas As DataRow In TmpDT.Rows
Dim CveTamanioTemp As Integer = DrowPartidas("CveTamaño").ToString.ToEntero
If CveTamanioTemp > 0 Then
Dim DTTamanioTemp As New DataTable
Dim CvePsTemp As Integer = DTTamanios.FiltraParametros($"CveTamaño = { CveTamanioTemp } ").Rows(0)("CvePSCargo").ToString.ToEntero
CveSubProyectoPSA = DrowPartidas("CveSubProyecto").ToString.ToEntero
SubProyectoPSA = DrowPartidas("SubProyecto").ToString
If ObjProductosServicios.GetPS(CvePsTemp, -1, UsuarioActual.CveEmpresa) Then
CveUnidadMedidaPSA = ObjProductosServicios.CveUnidadMedida
CveClacificacionPSA = ObjProductosServicios.CveClasificacion
UnidadMedidaPSA = ObjProductosServicios.DtResultados.FiltroPrimeroValor("UnidadMedida")
PSPSA = ObjProductosServicios.PS
End If
If UsuarioActual.Empresa.UsaAC Then
ClacificacionPSA = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, CveClacificacionPSA, -1)).FiltroPrimeroValor("Clasificacion", " Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
Else
ClacificacionPSA = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=If(UsuarioActual.Empresa.UsaContabilidad, CveClacificacionPSA, -1)).FiltroPrimeroValor("Clasificacion", Orderby:="Clasificacion")
End If
Dim Cargo As Decimal = DTTamanios.FiltroPrimeroValor("Cargo", $" CveTamaño = { CveTamanioTemp }").ToDecimal
If DTPSTemp.FiltraParametros($"CvePs = { CvePsTemp }").Rows.Count > 0 Then
For Each dRowUpdate As DataRow In DTPSTemp.Rows
If (dRowUpdate("CvePS").ToString.ToEntero = CvePsTemp) Then
dRowUpdate("Cantidad") = dRowUpdate("Cantidad").ToString.ToDecimal + DrowPartidas("Cantidad").ToString.ToDecimal
dRowUpdate("PU") = Cargo ' dRowUpdate("Total").ToString.ToDecimal + ImporteCargo
End If
Next
DTPSTemp.AcceptChanges()
Else
Dim dRowNuevo As DataRow = DTPSTemp.NewRow
dRowNuevo("Cantidad") = DrowPartidas("Cantidad").ToString.ToDecimal
dRowNuevo("PU") = Cargo
dRowNuevo("CveUnidadMedida") = CveUnidadMedidaPSA
dRowNuevo("UnidadMedida") = UnidadMedidaPSA
dRowNuevo("CveClacificacion") = CveClacificacionPSA
dRowNuevo("Clacificacion") = ClacificacionPSA
dRowNuevo("CvePS") = CvePsTemp
dRowNuevo("PS") = PSPSA
dRowNuevo("CveSubProyecto") = DrowPartidas("CveSubProyecto").ToString.ToEntero
dRowNuevo("SubProyecto") = DrowPartidas("SubProyecto").ToString
DTPSTemp.Rows.Add(dRowNuevo)
DTPSTemp.AcceptChanges()
End If
End If
Next
For Each drowPsTamaños As DataRow In DTPSTemp.Rows
Modalidad = "A"
If drowPsTamaños("PU").ToString.ToDecimal > 0 Then
AgregarProductoServicio(drowPsTamaños("Cantidad").ToString.ToEntero, drowPsTamaños("CveUnidadMedida").ToString.ToEntero, drowPsTamaños("UnidadMedida").ToString,
drowPsTamaños("CveClacificacion").ToString.ToEntero, drowPsTamaños("Clacificacion").ToString, drowPsTamaños("CvePS").ToString.ToEntero,
drowPsTamaños("PS").ToString, "", drowPsTamaños("PU").ToString.ToDecimal, 0, -1, "", drowPsTamaños("CveSubProyecto").ToString.ToEntero,
drowPsTamaños("SubProyecto").ToString)
End If
Next
ObjProductosServicios.Dispose()
End If
ObjAcum.Dispose()
End If
End Sub
Private Function GuardarUsados(SqlTransaccion As SqlClient.SqlTransaction, CveVenta As Integer) As Boolean
Dim Resultado As Boolean = True
If ClienteEsDistribuidor Then
'If UsuarioActual.Empresa.Funcionalidad(533).ToEntero > 0 Then
' Dim CvePSPSA As Integer = UsuarioActual.Empresa.Funcionalidad(533).ToEntero
Dim ObjAcum As New ClsAcumuladores(SqlTransaccion)
For Each drow As DataRow In TmpDT.Rows
If drow("CveTamaño").ToString.ToEntero > 0 Then
Dim TempDTAcums = GlobalDTAcumTamaños.FiltraParametros("CvePSCargo = " & drow("CvePS").ToString)
If TempDTAcums IsNot Nothing AndAlso TempDTAcums.Rows.Count > 0 Then
If Not ObjAcum.DistribuidorMovtosAdd(CveCliente, drow("Cantidad").ToString.ToEntero, drow("CveTamaño").ToString.ToEntero, 2, CveVenta, UsuarioActual.CveUsuario,
UsuarioActual.CveEmpresa, 0D, "") Then
Resultado = False
Exit For
End If
Else
Resultado = True
End If
TempDTAcums.Dispose()
End If
Next
Else
Resultado = True
End If
Return Resultado
End Function
#End Region
#Region "PORCENTAJE IVA"
Protected Sub DdlIVA_SelectedIndexChanged(sender As Object, e As EventArgs)
If Not CveVenta > 0 Or EsCreaApartirDe Or CveDevolucion > 0 Then RecalculaIVA()
End Sub
Private Sub RecalculaIVA()
PorcentajeIVA = Math.Round(DdlIVA.SelectedValue.ToDouble - 1, 2).ToDecimal
For Each Row As DataRow In TmpDT.Rows
If PorcentajeIVA > 0 Then
Dim DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=Row("CvePS").ToString.ToEntero).FiltroPrimero("")
If DrPS IsNot Nothing Then
If DrPS("IVA").ToString.Contiene("-1", "") Then
Row("PorcentajeIVA") = PorcentajeIVA
Else
Row("PorcentajeIVA") = DrPS("IVA")
End If
Dim TotalCalculableImpuestos = (Row("Cantidad").ToString.ToDouble * Row("PU").ToString.ToDouble) - Row("Descuento").ToString.ToDouble
Row("IVA") = Row("PorcentajeIVA").ToString.ToDouble
Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDouble * TotalCalculableImpuestos, NumeroDecimales)
End If
Else
Row("IVA") = 0
Row("PorcentajeIVA") = 0
Row("ImporteIVA") = 0
End If
Next
CalculaTotalesVenta()
End Sub
#End Region
End Class