Files
SIG/Ventas/PV.aspx.vb
2019-09-20 13:10:46 -07:00

5539 lines
250 KiB
VB.net

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 PV
Inherits ClsPaginas
#Region "PROPIEDADES"
Private Const NumeroDecimales As Integer = 2
Dim ColumnaDescuento As Integer = 6
Dim ColumnaIVA As Integer = 7
Dim ColumnaIEPS As Integer = 8
Dim ColumnaRetIVA As Integer = 9
Dim ColumnaRetISR As Integer = 10
Dim ColumnaEditar As Integer = 12
Dim ColumnaEliminar As Integer = 13
'Factura de ventas
Dim DTConceptos As DataTable
Private Property Version As String
Private Property Fecha As String
Private Property SerieXML As String
Private Property FolioXML As String
Private Property SubTotal As Decimal
Private Property Total As Decimal = 0
Private Property Descuentos As Decimal = 0
Private Property EmisorRFC As String
Private Property ReceptorRFC As String
Private Property TrasladoIVA As Decimal = 0
Private Property RetencionIVA As Decimal = 0
Private Property RetencionISR As Decimal = 0
Private Property TrasladoIEPS As Decimal = 0
Private Property TFDUUID As String = ""
Private Property Moneda As String = ""
Private Property TipoComprobante As String = ""
Private Property OtrosImpuestos As Decimal = 0
Private Property TotalRetenciones As Decimal = 0
Private Property SumaTotalRetenciones As Decimal = 0
Private Property TotalTraslados As Decimal = 0
Private Property SumaTotalTraslados As Decimal = 0
Private Property SubTotalConceptos As Decimal = 0
Private Property Redondeo As Decimal = 0
Private Property EsSupervisor As Boolean = False
Private Property MandarCorreoSupervisor As Boolean = False
Public Property EstablecioFolio As Boolean
Get
Return CBool(ViewState("EstablecioFolio").ToString)
End Get
Set(value As Boolean)
ViewState("EstablecioFolio") = value
End Set
End Property
Private ReadOnly Property ExFolioFactura As Boolean
Get
Return CBool(ViewState("ExFolioFactura"))
End Get
End Property
Private Property CveFactura As Integer
Get
Return ViewState("CveFactura").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveFactura") = value
End Set
End Property
Private Property IdPoliza As Integer
Get
Return ViewState("IdPoliza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("IdPoliza") = value
End Set
End Property
Private Property RemisionesLista As List(Of Integer)
Get
Return If(IsNothing(ViewState("RemisionesLista")), Nothing, CType(ViewState("RemisionesLista"), List(Of Integer)))
End Get
Set(value As List(Of Integer))
ViewState("RemisionesLista") = value
End Set
End Property
Private Property HuboCambioRemi As Boolean
Get
Return If(IsNothing(ViewState("HuboCambioRemi")), False, CType(ViewState("HuboCambioRemi"), Boolean))
End Get
Set(value As Boolean)
ViewState("HuboCambioRemi") = value
End Set
End Property
Private Property EsCreaApartirDe As Boolean
Get
Return If(IsNothing(ViewState("EsCreaApartirDe")), False, CType(ViewState("EsCreaApartirDe"), Boolean))
End Get
Set(value As Boolean)
ViewState("EsCreaApartirDe") = value
End Set
End Property
Private Property RequiereAlmacenDestino As Boolean
Get
Return If(IsNothing(ViewState("RequiereAlmacenDestino")), False, CType(ViewState("RequiereAlmacenDestino"), Boolean))
End Get
Set(value As Boolean)
ViewState("RequiereAlmacenDestino") = value
End Set
End Property
Private Property EmpresaActual As Empresa
Get
Return CType(ViewState("EmpresaActual"), Empresa)
End Get
Set(value As Empresa)
ViewState("EmpresaActual") = value
End Set
End Property
Private ReadOnly Property CveCliente As Integer
Get
Return ViewState("CveCliente").ToString.ToEntero
End Get
End Property
Private Property CveClienteSucursal As Integer
Get
If ViewState("CveClienteSucursal") Is Nothing Then
Return -1
Else
Return ViewState("CveClienteSucursal").ToString.ToEntero
End If
End Get
Set(value As Integer)
ViewState("CveClienteSucursal") = value
End Set
End Property
Private Property CveUsuarioActual As Integer
Get
Return ViewState("CveUsuarioActual").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveUsuarioActual") = value
End Set
End Property
Private ReadOnly Property Mail As String
Get
Return ViewState("Mail").ToString
End Get
End Property
Private ReadOnly Property MailCC As String
Get
Return ViewState("MailCC").ToString
End Get
End Property
Private ReadOnly Property CveVenta As Integer
Get
Return ViewState("CveVenta").ToString.ToEntero
End Get
End Property
Private Property CveVentaPadre As Integer
Get
Return If(IsNothing(ViewState("CveVentaPadre")), -1, ViewState("CveVentaPadre").ToString.ToEntero)
End Get
Set(value As Integer)
ViewState("CveVentaPadre") = value
End Set
End Property
Private ReadOnly Property CveDevolucion As Integer
Get
Return ViewState("CveDevolucion").ToString.ToEntero
End Get
End Property
Private Property IsTotalxConcepto As Boolean
Get
Return If(IsNothing(ViewState("IsTotalxConcepto")), False, CBool(ViewState("IsTotalxConcepto").ToString))
End Get
Set(value As Boolean)
ViewState("IsTotalxConcepto") = value
End Set
End Property
Private ReadOnly Property CveAlmacenTransitorio As Integer
Get
Return ViewState("CveAlmacenTransitorio").ToString.ToEntero
End Get
End Property
Private ReadOnly Property NuevaFactura As Integer
Get
Return ViewState("NuevaFactura").ToString.ToEntero
End Get
End Property
Private ReadOnly Property VentaFolio As String
Get
Return ViewState("VentaFolio").ToString
End Get
End Property
Private ReadOnly Property SelloCancelacion As String
Get
Return ViewState("SelloCancelacion").ToString
End Get
End Property
Private ReadOnly Property FechaCancelacion As DateTime
Get
Return ViewState("FechaCancelacion").ToString.ToDateTime
End Get
End Property
Private ReadOnly Property FolioFiscal As String
Get
Return ViewState("FolioFiscal").ToString
End Get
End Property
Private ReadOnly Property Ruta As String
Get
Return 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 Double
Get
Return ViewState("TipoCambio").ToString.ToDouble
End Get
End Property
Private ReadOnly Property ProcesoCorrecto As Boolean
Get
Return CBool(ViewState("ProcesoCorrecto"))
End Get
End Property
'Folios
Private ReadOnly Property CveFolio As Integer
Get
Return ViewState("CveFolio").ToString.ToEntero
End Get
End Property
Private ReadOnly Property NumAprobacion As Long
Get
Return CLng(ViewState("NumAprobacion").ToString)
End Get
End Property
Private ReadOnly Property FechaAprobacion As Date
Get
Return ViewState("FechaAprobacion").ToString.ToDate
End Get
End Property
Private ReadOnly Property FolioActual As String
Get
Return ViewState("FolioActual").ToString
End Get
End Property
'Sucursal
Private ReadOnly Property Serie As String
Get
Return ViewState("Serie").ToString
End Get
End Property
Private ReadOnly Property Folio As Integer
Get
Return ViewState("Folio").ToString.ToEntero
End Get
End Property
Private ReadOnly Property FormatoFactura As String
Get
Return ViewState("FormatoFactura").ToString
End Get
End Property
Private ReadOnly Property TipoFormato As String
Get
Return ViewState("TipoFormato").ToString
End Get
End Property
Private ReadOnly Property IVA As Double
Get
Return ViewState("IVA").ToString.ToDouble
End Get
End Property
'Cliente
Private ReadOnly Property NombreCliente As String
Get
Return ViewState("NombreCliente").ToString
End Get
End Property
Private ReadOnly Property Vendedor As String
Get
Return ViewState("Vendedor").ToString
End Get
End Property
Private ReadOnly Property CtaContable As String
Get
Return ViewState("CtaContable").ToString
End Get
End Property
Private ReadOnly Property IdCtaContClientes As Integer
Get
Return ViewState("IdCtaContClientes").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContMonedaExtranjera As Integer
Get
Return ViewState("IdCtaContMonedaExtranjera").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContComplementaria As Integer
Get
Return ViewState("IdCtaContComplementaria").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContAnticipos As Integer
Get
Return ViewState("IdCtaContAnticipos").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContRetIVA As Integer
Get
Return ViewState("IdCtaContRetIVA").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContRetISR As Integer
Get
Return ViewState("IdCtaContRetISR").ToString.ToEntero
End Get
End Property
Private ReadOnly Property IdCtaContDSV As Integer
Get
Return ViewState("IdCtaContDSV").ToString.ToEntero
End Get
End Property
Private ReadOnly Property CodCliente As String
Get
Return ViewState("CodCliente").ToString
End Get
End Property
Private ReadOnly Property CliNoExt As String
Get
Return ViewState("CliNoExt").ToString
End Get
End Property
Private ReadOnly Property CliNoInt As String
Get
Return ViewState("CliNoInt").ToString
End Get
End Property
Private ReadOnly Property CliLocalidad As String
Get
Return ViewState("CliLocalidad").ToString
End Get
End Property
Private ReadOnly Property CliPais As String
Get
Return ViewState("CliPais").ToString
End Get
End Property
Private ReadOnly Property SucCalle As String
Get
Return ViewState("SucCalle").ToString
End Get
End Property
Private ReadOnly Property CliCorreoCot As String
Get
If ViewState("CliCorreoCot") Is Nothing Then
Return ""
Else
Return ViewState("CliCorreoCot").ToString
End If
End Get
End Property
Private ReadOnly Property SucNoExt As String
Get
Return ViewState("SucNoExt").ToString
End Get
End Property
Private ReadOnly Property SucNoInt As String
Get
Return ViewState("SucNoInt").ToString
End Get
End Property
Private ReadOnly Property SucColonia As String
Get
Return ViewState("SucColonia").ToString
End Get
End Property
Private ReadOnly Property SucLocalidad As String
Get
Return ViewState("SucLocalidad").ToString
End Get
End Property
Private ReadOnly Property SucMunicipio As String
Get
Return ViewState("SucMunicipio").ToString
End Get
End Property
Private ReadOnly Property SucEstado As String
Get
Return ViewState("SucEstado").ToString
End Get
End Property
Private ReadOnly Property SucPais As String
Get
Return ViewState("SucPais").ToString
End Get
End Property
Private ReadOnly Property SucCP As String
Get
Return ViewState("SucCP").ToString
End Get
End Property
Private ReadOnly Property MatCalle As String
Get
Return ViewState("MatCalle").ToString
End Get
End Property
Private ReadOnly Property MatNoExt As String
Get
Return ViewState("MatNoExt").ToString
End Get
End Property
Private ReadOnly Property MatNoInt As String
Get
Return ViewState("MatNoInt").ToString
End Get
End Property
Private ReadOnly Property MatColonia As String
Get
Return ViewState("MatColonia").ToString
End Get
End Property
Private ReadOnly Property MatLocalidad As String
Get
Return ViewState("MatLocalidad").ToString
End Get
End Property
Private ReadOnly Property MatMunicipio As String
Get
Return ViewState("MatMunicipio").ToString
End Get
End Property
Private ReadOnly Property MatEstado As String
Get
Return ViewState("MatEstado").ToString
End Get
End Property
Private ReadOnly Property MatPais As String
Get
Return ViewState("MatPais").ToString
End Get
End Property
Private ReadOnly Property MatCP As String
Get
Return ViewState("MatCP").ToString
End Get
End Property
Private ReadOnly Property AplicaFEMSA As Boolean
Get
Return CBool(ViewState("AplicaFEMSA"))
End Get
End Property
Private ReadOnly Property AplicaDetallista As Boolean
Get
Return CBool(ViewState("AplicaDetallista"))
End Get
End Property
Private ReadOnly Property AplicaFord As Boolean
Get
Return CBool(ViewState("AplicaFord"))
End Get
End Property
Private ReadOnly Property CveOS As Integer
Get
Return ViewState("CveOS").ToString.ToEntero
End Get
End Property
Private ReadOnly Property SaldoVenta As Decimal
Get
Return If(IsNothing(ViewState("SaldoVenta")), 0, ViewState("SaldoVenta").ToString.ToDecimal)
End Get
End Property
Private Property CvePSAmortizacion As Integer
Get
Return ViewState("CvePSAmortizacion").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePSAmortizacion") = value
End Set
End Property
Private ReadOnly Property ClienteRetIVA As Decimal
Get
Return ViewState("ClienteRetIVA").ToString.ToDecimal
End Get
End Property
Private ReadOnly Property ClienteRetISR As Decimal
Get
Return ViewState("ClienteRetISR").ToString.ToDecimal
End Get
End Property
Private ReadOnly Property ClienteDesglosaIEPS As Boolean
Get
Return CType(ViewState("ClienteDesglosaIEPS").ToString, Boolean)
End Get
End Property
Private Property CvePrePoliza As Integer
Get
Return ViewState("CvePrePoliza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePrePoliza") = value
End Set
End Property
Private ReadOnly Property SeGuardoPrePoliza As Boolean
Get
Return CBool(ViewState("SeGuardoPrePoliza"))
End Get
End Property
Private Property CveVentaFacturada As Integer
Get
Return ViewState("CveVentaFacturada").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveVentaFacturada") = value
End Set
End Property
Private Property Modalidad As String
Get
Return ViewState("Modalidad").ToString
End Get
Set(value As String)
ViewState("Modalidad") = value
End Set
End Property
Private Property Index As Integer
Get
Return ViewState("Index").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("Index") = value
End Set
End Property
Private ReadOnly Property AplicarVentaFacturada As Boolean
Get
Return CBool(ViewState("AplicarVentaFacturada"))
End Get
End Property
'Estimaciones
Private Property CveContrato As Integer
Get
Return ViewState("CveContrato").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveContrato") = value
End Set
End Property
Private Property CvePedido As Integer
Get
Return ViewState("CvePedido").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePedido") = value
End Set
End Property
Private Property TipoContrato As Integer
Get
Return ViewState("TipoContrato").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("TipoContrato") = value
End Set
End Property
Private Property Opcion As String
Get
Return ViewState("Opcion").ToString
End Get
Set(value As String)
ViewState("Opcion") = value
End Set
End Property
'Presupuesto
Private Property CvePresupuesto As Integer
Get
Return ViewState("CvePresupuesto").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CvePresupuesto") = value
End Set
End Property
Private Property TotalOtrosConceptos As Decimal
Get
Return ViewState("TotalOtrosConceptos").ToString.ToDecimal
End Get
Set(value As Decimal)
ViewState("TotalOtrosConceptos") = value
End Set
End Property
Private Property DevolucionAlmacen As Integer
Get
Return ViewState("DevolucionAlmacen").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("DevolucionAlmacen") = value
End Set
End Property
Private Property CveMetodoPagoCliente As Integer
Get
Return ViewState("CveMetodoPagoCliente").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveMetodoPagoCliente") = value
End Set
End Property
Private Property PlazoCobranza As Integer
Get
Return ViewState("PlazoCobranza").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("PlazoCobranza") = value
End Set
End Property
Private ReadOnly Property SubProyectoPorcentajeIVA As Decimal
Get
Return ViewState("SubProyectoPorcentajeIVA").ToString.ToDecimal
End Get
End Property
Private Property EstatusCliente As Boolean
Get
Return CBool(ViewState("EstatusCliente").ToString)
End Get
Set(value As Boolean)
ViewState("EstatusCliente") = value
End Set
End Property
Private Property EnviarCorreoCliente As Boolean
Get
Return CBool(ViewState("EnviarCorreoCliente").ToString)
End Get
Set(value As Boolean)
ViewState("EnviarCorreoCliente") = value
End Set
End Property
#End Region
#Region "PROPIEDADES DE PUNTO DE VENTA"
Private Property CveCorte As Integer
Get
Return ViewState("CveCorte").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveCorte") = value
End Set
End Property
Private Property Entrega As String
Get
Return ViewState("Entrega").ToString
End Get
Set(value As String)
ViewState("Entrega") = value
End Set
End Property
Private Property Vigencia As String
Get
Return ViewState("Vigencia").ToString
End Get
Set(value As String)
ViewState("Vigencia") = value
End Set
End Property
Private Property DineroCaja As Double
Get
Return ViewState("DineroCaja").ToString.ToDouble
End Get
Set(value As Double)
ViewState("DineroCaja") = value
End Set
End Property
Private Property TmpDTMetodosPago As DataTable
Get
Return If(IsNothing(ViewState("TmpDTMetodosPago")), Nothing, CType(ViewState("TmpDTMetodosPago"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTMetodosPago") = value
End Set
End Property
#End Region
#Region "PROPIEDADES CONTRATOS"
Private Property DtContratos As DataTable
Get
Return If(IsNothing(ViewState("DtContratos")), Nothing, CType(ViewState("DtContratos"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtContratos") = value
End Set
End Property
#End Region
#Region " PROPIEDADES NUEVAS | GUARDAR - IMPRESION | IPP "
Private Property ErrorList As List(Of String)
Get
Return CType(ViewState("ErrorList"), List(Of String))
End Get
Set(value As List(Of String))
ViewState("ErrorList") = value
End Set
End Property
Private Property MensajeAlert As StringBuilder
Get
Return CType(ViewState("MensajeAlert"), StringBuilder)
End Get
Set(value As StringBuilder)
ViewState("MensajeAlert") = value
End Set
End Property
Private Property ObjFactura As Modelos.Factura
Get
Return CType(ViewState("ObjFactura"), Modelos.Factura)
End Get
Set(value As Modelos.Factura)
ViewState("ObjFactura") = value
End Set
End Property
#End Region
#Region " PROPIEDADES OC "
Private Property CveOC As Integer
Get
Return ViewState("CveOC").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("CveOC") = value
End Set
End Property
#End Region
#Region "PROPIEDADES DATATABLE"
Private Property DtRemisionesPS As DataTable
Get
Return If(IsNothing(ViewState("DtRemisionesPS")), Nothing, CType(ViewState("DtRemisionesPS"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtRemisionesPS") = value
End Set
End Property
Private Property DtRemisionesTmpDT As DataTable
Get
Return If(IsNothing(ViewState("DtRemisionesTmpDT")), Nothing, CType(ViewState("DtRemisionesTmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtRemisionesTmpDT") = value
End Set
End Property
Private Property DTPresupuestoIngresos As DataTable
Get
Return CType(ViewState("DTPresupuestoIngresos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTPresupuestoIngresos") = value
End Set
End Property
Private Property DtInv As DataTable
Get
Return CType(ViewState("DtInv"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtInv") = value
End Set
End Property
Private Property DTFacNC As DataTable
Get
Return If(IsNothing(ViewState("DTFacNC")), Nothing, CType(ViewState("DTFacNC"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTFacNC") = value
End Set
End Property
Private Property DtPromociones As DataTable
Get
Return If(IsNothing(ViewState("DtPromociones")), Nothing, CType(ViewState("DtPromociones"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtPromociones") = value
End Set
End Property
Private Property DTSucursal As DataTable
Get
Return If(IsNothing(ViewState("DTSucursal")), Nothing, CType(ViewState("DTSucursal"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTSucursal") = value
End Set
End Property
Private Property TmpDT As DataTable
Get
Return If(IsNothing(ViewState("TmpDT")), Nothing, CType(ViewState("TmpDT"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDT") = value
End Set
End Property
Private Property TmpDTAjustes As DataTable
Get
Return If(IsNothing(ViewState("TmpDTAjustes")), Nothing, CType(ViewState("TmpDTAjustes"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTAjustes") = value
End Set
End Property
Private Property TmpDTRecepcionUsados As DataTable
Get
Return If(IsNothing(ViewState("TmpDTRecepcionUsados")), Nothing, CType(ViewState("TmpDTRecepcionUsados"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTRecepcionUsados") = value
End Set
End Property
Private Property TmpDTImpuestos As DataTable
Get
Return If(IsNothing(ViewState("TmpDTImpuestos")), Nothing, CType(ViewState("TmpDTImpuestos"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTImpuestos") = value
End Set
End Property
Private Property TmpDTEnvioDireccion As DataTable
Get
Return If(IsNothing(ViewState("TmpDTEnvioDireccion")), Nothing, CType(ViewState("TmpDTEnvioDireccion"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTEnvioDireccion") = value
End Set
End Property
Private Property TmpDTDeducciones As DataTable
Get
Return If(IsNothing(ViewState("TmpDTDeducciones")), Nothing, CType(ViewState("TmpDTDeducciones"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTDeducciones") = value
End Set
End Property
Private Property TmpDTComplementos As DataTable
Get
Return If(IsNothing(ViewState("TmpDTComplementos")), Nothing, CType(ViewState("TmpDTComplementos"), DataTable))
End Get
Set(value As DataTable)
ViewState("TmpDTComplementos") = value
End Set
End Property
Private Property DTmpC As DataTable
Get
Return If(IsNothing(ViewState("DTmpC")), Nothing, CType(ViewState("DTmpC"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTmpC") = value
End Set
End Property
Private Property DTmpF As DataTable
Get
Return If(IsNothing(ViewState("DTmpF")), Nothing, CType(ViewState("DTmpF"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTmpF") = value
End Set
End Property
Private Property DTRemisiones As DataTable
Get
Return If(IsNothing(ViewState("DTRemisiones")), Nothing, CType(ViewState("DTRemisiones"), DataTable))
End Get
Set(value As DataTable)
ViewState("DTRemisiones") = value
End Set
End Property
Private Property DtPagos As DataTable
Get
Return CType(ViewState("DtPagos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPagos") = value
End Set
End Property
Private Property DtPUFacturas As DataTable
Get
Return CType(ViewState("DtPUFacturas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPUFacturas") = value
End Set
End Property
#End Region
#Region "PROPIEDADES ACUMULADORES"
Private Property ConsecutivoVenta As Integer
Get
Return ViewState("ConsecutivoVenta").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("ConsecutivoVenta") = value
End Set
End Property
Private Property ModalidadAjuste As String
Get
Return ViewState("ModalidadAjuste").ToString
End Get
Set(value As String)
ViewState("ModalidadAjuste") = value
End Set
End Property
Private Property IndexAjuste As Integer
Get
Return ViewState("IndexAjuste").ToString.ToEntero
End Get
Set(value As Integer)
ViewState("IndexAjuste") = value
End Set
End Property
#End Region
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
DdlBPPS.setEsWebService(True)
DdlBPPS.ddlWS.Attributes.Add("data-clear", "1")
ViewState("ProcesoCorrecto") = True
ViewState("NuevaFactura") = -1
ViewState("CveDevolucion") = -1
ViewState("CvePedido") = -1
ViewState("TipoContrato") = -1
ViewState("CveVenta") = -1
ViewState("CveOS") = -1
ViewState("CveFactura") = -1
ViewState("CveMetodoPagoCliente") = -1
ViewState("Entrega") = ""
ViewState("Vigencia") = ""
ViewState("AplicarVentaFacturada") = False
ViewState("SeGuardoPrePoliza") = False
ViewState("SubProyectoPorcentajeIVA") = 0
ViewState("ClienteDesglosaIEPS") = False
ViewState("ClienteRetIVA") = 0
ViewState("ClienteRetISR") = 0
ViewState("EnviarCorreoCliente") = False
EstablecioFolio = False
EstatusCliente = False
RemisionesLista = New List(Of Integer)
CvePrePoliza = 0
TotalOtrosConceptos = 0
CveUsuarioActual = UsuarioActual.CveUsuario
EmpresaActual = UsuarioActual.Empresa
IdPoliza = 0
CveCorte = -1
CveContrato = -1
DevolucionAlmacen = 0
CvePSAmortizacion = 0
PlazoCobranza = 0
IndexAjuste = 0
ConsecutivoVenta = 0
ModalidadAjuste = ""
EsCreaApartirDe = False
RequiereAlmacenDestino = False
TmpDTComplementos = New DataTable
DtPUFacturas = New DataTable
Modalidad = ""
Index = -1
If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then
ChkAjuste.Visible = True
Else
ChkAjuste.Visible = False
End If
If UsuarioActual.CveEmpresa = 72 Then
TabAlmacen.Visible = False
End If
SetValues()
CvePresupuesto = 0
'MODALIDADES
If Request("Op") IsNot Nothing AndAlso Request("Op").ToString <> "" Then
Opcion = Request("Op").ToString
Else
Opcion = "Ing"
End If
'proceso 163, que activa al edicion de folios.
TxtFecha.Text = Now.ToShortDateString()
LblUsuario.Text = UsuarioActual.Usuario
TxtCantidad.Attributes.Add("onKeyUp ", "Recalcula();")
TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();")
ImgDescPU.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '0'; $get('LblPrecio1').style.display = ''; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';")
'ImgDescConcepto.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '1'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = ''; $get('LblSubTotal1').style.display = 'none'; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = ''; $get('BtnAplicarDescG').style.display = 'none'; $get('TrMotivoDescuento').style.display = '';")
ImgDescTotal.Attributes.Add("onclick", "javascript:$('#ModalDescuento').modal(); $get('LblTitulo1').style.display = ''; $get('LblTitulo2').style.display = 'none'; $get('LblTituloTipo1').style.display = ''; $get('LblTituloTipo2').style.display = 'none'; $get('HdnTipoDescuento').value = '2'; $get('LblPrecio1').style.display = 'none'; $get('LblTotalPS1').style.display = 'none'; $get('LblSubTotal1').style.display = ''; $get('LblAmort').style.display = 'none'; $get('BtnAplicarDescP').style.display = 'none'; $get('BtnAplicarDescG').style.display = ''; $get('TrMotivoDescuento').style.display = '';")
ImgOtrosConceptos.Attributes.Add("onclick", "javascript:$('#ModalOtrosConceptos').modal();")
LkbAgregarComplementos.Attributes.Add("onclick", "javascript:$('#ModalComplementos').modal();")
'ImgCerrar.Attributes.Add("OnClick", "$('#DivAnticipos').hide();")
'LkbEstadodeCaja.Attributes.Add("OnClick", "MuestraEstadoCaja();")
'LkbIngreso.Attributes.Add("OnClick", "MuestraIngresoEgreso(1);")
'LkbRetiro.Attributes.Add("OnClick", "MuestraIngresoEgreso(0);")
TxtImporteEfectivo.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteCredito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteDebito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteCheque.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtImporteTransferencia.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();")
TxtEfectivoEnCaja.Attributes.Add("onKeyUp", "CalculaDiferencia();")
'ImgCerrarTerminoCorte.Attributes.Add("OnClick", "$('#DivTerminarCorte').hide();")
'ImgCerrarIE.Attributes.Add("OnClick", "$('#DivIngresoEgreso').hide();")
'ImgCerrarEstadoCaja.Attributes.Add("OnClick", "$('#DivEstadoCaja').hide();")
TxtPorDescP.Attributes.Add("onKeyUp", "CalculaDescuento();")
TxtDescP.Attributes.Add("onKeyUp", "CalculaDescuento();")
TxtFechaAjuste.Attributes.Add("onchange", "CalculaMesesUso();")
CreaDTmpC()
CreaDTmpF()
CargaDdlSubProyectos()
CargaSucursales()
CargaClasificaciones()
CargaPS(-1, DdlPS)
CargaEmpresa()
CreaDTVentas()
CargaMetodosPago()
CargaUsoCFDI()
CargaMonedas()
CargaVendedores()
CambiaTipoDocto()
CargarAlmacenes()
CargaFormaEntrega()
CargaCuentasTerminal()
If UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then
CargaAjuste()
RVPorDesc.MaximumValue = UsuarioActual.DescuentoAutorizado.ToString
RVPorDesc.ErrorMessage = $"El rango para el % de descuento debe de estar entre <b>0</b> y <b>{UsuarioActual.DescuentoAutorizado.ToString}</b>."
End If
LimpiaEscondeContado()
'Carga cliente
If Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 AndAlso Request("CveFactura") Is Nothing Then
ViewState("CveCliente") = Request("CveCliente")
HdnCveCliente.Value = Request("CveCliente")
CargaCliente(CveCliente)
ElseIf Request("CveFactura") IsNot Nothing AndAlso IsNumeric(Request("CveFactura")) AndAlso Request("CveFactura").ToEntero > 0 AndAlso Request("CveCliente") IsNot Nothing AndAlso IsNumeric(Request("CveCliente")) AndAlso Request("CveCliente").ToEntero > 0 Then
ViewState("CveCliente") = Request("CveCliente")
ViewState("CveFactura") = Request("CveFactura").ToEntero
CargaCliente(CveCliente)
Else
ViewState("CveCliente") = -1
HdnCveCliente.Value = "-1"
End If
'CARGA PARA FACTURAR
ViewState("CveRemision") = IfNull(Request("CveRemision").ToEntero, 0)
ViewState("CveCotizacion") = IfNull(Request("CveCotizacion").ToEntero, 0)
If ViewState("CveCotizacion").ToString.ToEntero > 0 Then
EsCreaApartirDe = True
End If
If UsuarioActual.CveVendedor > 0 Then
If CveVenta = -1 AndAlso Not DdlVendedor.SelectedValue.ToEntero > 0 Then DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString)
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
'multiples vendedores visible
If UsuarioActual.TienePermisoProceso(153) Then
DdlVendedor.Enabled = True
End If
End If
If UsuarioActual.Empresa.Funcionalidad(301).ToEntero > 0 Then
TxtFecha.Enabled = False
ImgFecha.Visible = False
End If
CargarCodigo()
'RegistraScript("FnSuma()")
TxtSubTotal.Attributes.Add("onKeyUp", "FnSuma()")
TxtIVA.Attributes.Add("onKeyUp", "FnSuma()")
TxtIEPS.Attributes.Add("onKeyUp", "FnSuma()")
TxtRetIVA.Attributes.Add("onKeyUp", "FnSuma()")
TxtRetISR.Attributes.Add("onKeyUp", "FnSuma()")
'Permitir Edicion de Iva
If UsuarioActual.Empresa.Funcionalidad(509) = "1" Then
TxtIVA.Enabled = True
End If
'Cortes de Caja
If UsuarioActual.TienePermisoProceso(160) Then
CargaCorteCaja()
End If
'**********************************
'Complementos de Timbrado
Dim ObjVenta As New ClsVentas
If ObjVenta.GetVentaComplementos() Then
RblComplementos.DataSource = ObjVenta.DtResultados
RblComplementos.DataBind()
UpComplementos.Update()
End If
ObjVenta.Dispose()
If Not UsuarioActual.CveEmpresa.Contiene(1, 119) Then 'PAGO CON TERMINAL PARA JAM
RBLPago.Items.RemoveAt(2)
End If
'CARGA VALORES INICIALES PARA AGREGAR PS DESDE MODAL
CargaMetodosPSModal()
If UsuarioActual.CveEmpresa.Contiene(72, 80, 1, 119) Then
BtnEmitirImprimir.Attributes.Add("data-toggle", "confirmation")
BtnEmitirImprimir.Attributes.Add("data-popout", "true")
BtnEmitirImprimir.Attributes.Add("data-original-title", "confirmar")
BtnEmitirImprimir.Attributes.Add("data-btn-ok-label", "Guardar")
BtnEmitirImprimir.Attributes.Add("data-html", "true")
End If
'Le quitamos el tamaño extra
'RegistraScript("window.onload = function AjustarVentana() { $('.page-content').css('min-height','100%'); }")
End If
End Sub
#Region "PUNTO DE VENTA"
Private Sub CargaCorteCaja()
'Checar si hay un Turno Abierto
Dim ObjPVenta As New ClsPuntoVenta
If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
CveCorte = ObjPVenta.CveCorte
LblEstatusCaja.Text = ObjPVenta.FechaInicial.ToShortDateString
TrEstatusCaja.Visible = True
BtnIniciarTurno.Visible = False
LkbEstadodeCaja.Visible = True
LkbIngreso.Visible = True
LkbRetiro.Visible = True
Else
'Ingresar un nuevo Turno
RegistraScript("window.onload = function MuestraCorteCaja() { document.getElementById(""C_btnShow"").click(); }")
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnIniciarTurno_Click(sender As Object, e As EventArgs) Handles BtnIniciarTurno.Click
Dim ObjPVenta As New ClsPuntoVenta
ObjPVenta.AddVtaCortes(Now, TxtDineroCaja.Text.ToDecimal, UsuarioActual.CveUsuario, TxtDescripcionCaja.Text, UsuarioActual.CveEmpresa)
CveCorte = ObjPVenta.CveCorte
LblEstatusCaja.Text = Now.ToShortDateString
TrEstatusCaja.Visible = True
LkbEstadodeCaja.Visible = True
LkbIngreso.Visible = True
LkbRetiro.Visible = True
BtnIniciarTurno.Visible = False
ObjPVenta.Dispose()
RegistraScript("$('#DivCorteDeCaja').hide();")
End Sub
Private Sub LkbEstadodeCaja_Click(sender As Object, e As EventArgs) Handles LkbEstadodeCaja.Click
CargaDatosCorte()
CargaVentasPago()
CargaEntradasSalidas()
RegistraScript("$('#DivEstadoCaja').modal()")
End Sub
Private Sub CargaDatosCorte()
Dim ObjPVenta As New ClsPuntoVenta
Dim Total As Double
If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
Total = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble + ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble + ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble + ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble - ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble
DineroCaja = Total
LblEfectivoEsperado.Text = Total.FormatoNumero(2)
Dim Dt As New DataTable
Dt.Columns.Add("Descripcion", GetType(String))
Dt.Columns.Add("Importe", GetType(Decimal))
Dim Dr1 = Dt.NewRow
Dr1("Descripcion") = "Fondo de Caja"
Dr1("Importe") = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble
Dt.Rows.Add(Dr1)
Dim Dr2 = Dt.NewRow
Dr2("Descripcion") = "Ventas en Efectivo"
Dr2("Importe") = ObjPVenta.DtResultados(0)("VentasEfectivo").ToString.ToDouble
Dt.Rows.Add(Dr2)
Dim Dr3 = Dt.NewRow
Dr3("Descripcion") = "Propinas"
Dr3("Importe") = ObjPVenta.DtResultados(0)("Propina").ToString.ToDouble
Dt.Rows.Add(Dr3)
Dim Dr4 = Dt.NewRow
Dr4("Descripcion") = "Entradas"
Dr4("Importe") = ObjPVenta.DtResultados(0)("Ingresado").ToString.ToDouble
Dt.Rows.Add(Dr4)
Dim Dr5 = Dt.NewRow
Dr5("Descripcion") = "Salidas"
Dr5("Importe") = ObjPVenta.DtResultados(0)("Retirado").ToString.ToDouble
Dt.Rows.Add(Dr5)
Dim Dr6 = Dt.NewRow
Dr6("Descripcion") = "Total"
Dr6("Importe") = Total
Dt.Rows.Add(Dr6)
GvDineroCaja.DataSource = Dt
GvDineroCaja.DataBind()
UpDineroCaja.Update()
UpTerminarCorte.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub CargaVentasPago()
Dim ObjPVenta As New ClsPuntoVenta
If ObjPVenta.GetVta_MetodosPago(CveCorte) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
GvMetodosPago.DataSource = ObjPVenta.DtResultados
GvMetodosPago.DataBind()
UpMetodosPago.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub CargaEntradasSalidas()
Dim ObjPVenta As New ClsPuntoVenta
'Salida
If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 0) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
GvEgresos.DataSource = ObjPVenta.DtResultados
GvEgresos.DataBind()
UpEgresos.Update()
End If
End If
'Entrada
If ObjPVenta.GetVta_MovimientosCajas(CveCorte, 1) Then
If ObjPVenta.DtResultados.Rows.Count > 0 Then
GvIngresos.DataSource = ObjPVenta.DtResultados
GvIngresos.DataBind()
UpIngresos.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnAceptarIE_Click(sender As Object, e As EventArgs) Handles BtnAceptarIE.Click
Dim ObjPVenta As New ClsPuntoVenta
If TxtCantidadIE.Text.ToEntero > 0 Then
If ObjPVenta.AddVta_MovimientosCajas(CveCorte, UsuarioActual.CveUsuario, TxtCantidadIE.Text.ToDouble, TxtDescripcionIE.Text, HdnTipoMovimiento.Value.ToEntero, Now) Then
TxtCantidadIE.Text = ""
TxtDescripcionIE.Text = ""
RegistraScript("$('#DivIngresoEgreso').modal('hide')", "divingresoegreso")
Alert("El movimiento se realizo correctamente")
UpIngresoEgreso.Update()
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnCerrarTurno_Click(sender As Object, e As EventArgs) Handles BtnCerrarTurno.Click
Dim ObjPVenta As New ClsPuntoVenta
If TxtEfectivoEnCaja.Text.Trim <> "" Then
If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoEnCaja.Text.ToDouble, LblDiferenciaCaja.Text.ToDouble, Now, UsuarioActual.CveEmpresa) Then
RegistraScript($"window.location.href = '/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=CORT&CVECORTE={0}&FORMATO={1}", CveCorte, "PDF"))}'", "Imprimir")
Dim Liga = "document.location.href=""/Ventas/PV.aspx"";"
Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga)
End If
End If
ObjPVenta.Dispose()
End Sub
Private Sub BtnCancelar_Click(sender As Object, e As EventArgs) Handles BtnCancelar.Click
Response.Redirect("~/Inicio.aspx")
End Sub
Protected Sub BtnCerrarCaja_Click(sender As Object, e As EventArgs)
RegistraScript("$('#DivEstadoCaja').modal('hide')")
RegistraScript("$('#DivTerminarCorte').modal()", "divterminarcorte")
End Sub
Protected Sub LkbIngreso_Click(sender As Object, e As EventArgs)
CargaIngresoEgreso(1)
End Sub
Public Sub CargaIngresoEgreso(Opcion As Integer)
RegistraScript("$('#DivIngresoEgreso').modal()", "divingresoegreso")
If Opcion = 1 Then
LblTituloIE.Text = "Ingreso de Efectivo: "
HdnTipoMovimiento.Value = "1"
ElseIf Opcion = 0 Then
LblTituloIE.Text = "Retiro de Efectivo: "
HdnTipoMovimiento.Value = "0"
End If
UpIngresoEgreso.Update()
End Sub
Protected Sub LkbRetiro_Click(sender As Object, e As EventArgs)
CargaIngresoEgreso(0)
End Sub
#End Region
#Region "CARGAS"
Private Sub ConfiguraTipoDocto()
'Esconde Todo
TdOrdenPago.Visible = False
Tr33.Visible = False
Tr32.Visible = False
'si tiene la funcionalidad que se active independiente del tipo de documento RMF 15-10-2017
Tr33.Visible = True
Tr32.Visible = False
'' NO CONOCEN EL SWTICH (SELECT EN .NET) ?? O COMO ?? - IPP
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then
BtnEmitirImprimir.Text = "Emitir e Imprimir"
'TdReferencia.Style.Add("display", "none")
End If
UpFacturar.Update()
End Sub
Private Sub CargaMetodosPago()
DdlMetodoPago.DataSource = GlobalDTMetodosPago.FiltraParametros("Estatus = 'Activo'", "ClaveSAT") '.FiltraParametros("CveMetodoPago > 0 ")
DdlMetodoPago.DataBind()
'FACTURACION 3.3
DdlMetodoPago33.DataSource = GlobalDTVtaMetodoPago
DdlMetodoPago33.DataBind()
DdlMetodoPago33.SelectedValue = "3"
If UsuarioActual.CveEmpresa = 119 Then
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
Else
CargaFormaPago(-1)
End If
'End If
End Sub
Private Sub CargaFormaPago(CveMetodoPago As Integer)
'FACTURACION 3.3
Dim dtt As DataTable = Nothing
If CveMetodoPago > 0 Then
dtt = GlobalDTVtaFormaPago.FiltraParametros(If(CveMetodoPago = 1, " CveFormaPago <> 20 ", "CveFormaPago = 20"))
Else
dtt = GlobalDTVtaFormaPago
End If
DdlFormaPago33.Items.Clear()
DdlFormaPago33.ClearSelection()
DdlFormaPago33.DataBind()
DdlFormaPago33.DataSource = dtt
DdlFormaPago33.DataBind()
DdlFormaCliente.DataSource = dtt
DdlFormaCliente.DataBind()
DdlMetodoCliente.DataSource = GlobalDTVtaMetodoPago
DdlMetodoCliente.DataBind()
'End If
End Sub
Private Sub CargaUsoCFDI()
DdlUsoCFDI.DataSource = GlobalDTSATUsosCFDI(UsuarioActual.Empresa.EsPersonaFisica)
DdlUsoCFDI.DataBind()
End Sub
Private Sub CargaNuevaFactura(OVenta As ClsVentas)
Dim ObjVentas As ClsVentas
If OVenta IsNot Nothing Then
ObjVentas = OVenta
Else
ObjVentas = New ClsVentas()
End If
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then
Dim drv As DataRow = ObjVentas.DtResultados.Rows(0)
'CargaCliente
Dim CveCliente As Integer = drv("CveCliente").ToString.ToEntero
If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 77 AndAlso Not CveCliente.Contiene(10450, 10460, 10458) Then
Exit Sub
ElseIf UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario = 21 AndAlso Not CveCliente.Contiene(27448) Then
Exit Sub
End If
HdnCveCliente.Value = CveCliente.ToString
ViewState("CveCliente") = CveCliente
CargaCliente(CveCliente)
'Carga Detalle Sucursal
DdlSucursalCliente.SelectedValueExist(drv("CveClienteSucursal").ToString)
DdlSubProyectoDatos.SelectedValueExist(drv("CveSubProyecto").ToString)
CargaClienteSucursal(drv("CveClienteSucursal").ToString.ToEntero)
'CargaDetalle
If ObjVentas.GetVentaDetalle(CveVenta) Then
TmpDT = ObjVentas.DtResultados
GvPS.DataSource = ObjVentas.DtResultados
GvPS.DataBind()
End If
'Carga Totales
TxtSubTotal.Text = drv("SubTotal").ToString.FormatoNumero(2)
LblDescuentos.Text = drv("Descuento").ToString.FormatoNumero(2)
LblAmortizacion.Text = drv("Amortizacion").ToString.FormatoNumero(2)
TxtSubTotal2.Text = (TxtSubTotal.Text.Replace(",", "").Trim.Trim.ToDouble - LblDescuentos.Text.Replace(",", "").Trim.Trim.ToDouble - LblAmortizacion.Text.Replace(",", "").Trim.Trim.ToDouble).FormatoNumero(2)
TxtIVA.Text = drv("IVA").ToString.FormatoNumero(2)
TxtRetIVA.Text = drv("RetIVA").ToString.FormatoNumero(2)
TxtRetISR.Text = drv("RetISR").ToString.FormatoNumero(2)
TxtTotal.Text = drv("Total").ToString.FormatoNumero(2)
HdnVentaSaldo.Value = drv("Total").ToString
TxtMotivoDescuento.Text = drv("MotivoDescuento").ToString
TxtObsFact.Text = drv("Observaciones").ToString
DdlMoneda.SelectedValue = drv("CveMoneda").ToString
TxtTipoCambio.Text = drv("TipoCambio").ToString
DdlVendedor.SelectedValue = drv("CveVendedor").ToString
DdlMetodoPago.SelectedValueExist(drv("CveMetodoPago").ToString)
HdnIVAOriginal.Value = TxtIVA.Text
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
UpPS.Update()
UpContado.Update()
End If
End If
If OVenta Is Nothing Then
ObjVentas.Dispose()
End If
End Sub
Private Sub CargaSucursales()
If UsuarioActual.TienePermisoProceso(152) Then DdlSubProyectoDatos.Enabled = False
End Sub
Private Sub CargaEmpresa()
If UsuarioActual.Empresa.UsaContabilidad Then
Dim ObjFisConfiguracion As New ClsFISConfiguracion
If ObjFisConfiguracion.GetConfiguracion(UsuarioActual.CveEmpresa) Then
ViewState("IdCtaContDSV") = ObjFisConfiguracion.ERDSV
Else
ViewState("IdCtaContDSV") = 0
End If
ObjFisConfiguracion.Dispose()
Else
ViewState("IdCtaContDSV") = 0
End If
End Sub
Private Sub CargaMonedas()
DdlMoneda.DataSource = GlobalDTMonedas
DdlMoneda.DataBind()
End Sub
Private Sub CargarAlmacenes()
If CveVenta > 0 Then
DivAlmacen.Visible = False
Else
ddlAlmacen.Items.Clear()
ddlAlmacen.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}")
ddlAlmacen.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
ddlAlmacen.DataBind()
If GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").Rows.Count > 0 Then
ddlAlmacen.SelectedValueExist(UsuarioActual.CveAlmacen)
End If
End If
'SI TIENE CONTRATO NO SE MUEVE
If Not CveContrato > 0 Then
DdlAlmacenAsignado.Items.Clear()
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero} AND CveTipoAlmacen IN (4,10)")
DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
DdlAlmacenAsignado.SelectedValue = "-1"
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 10 AND CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}").ToString.ToEntero)
End If
If CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ped", "PeC") Then
DdlAlmacenAsignado.DataSource = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros($"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue.ToEntero}")
DdlAlmacenAsignado.Items.Insert(0, New ListItem(" Seleccione ", "-1"))
DdlAlmacenAsignado.SelectedValue = "-1"
DdlAlmacenAsignado.DataBind()
DdlAlmacenAsignado.SelectedValueExist(GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveSubProyecto = {DdlSubProyectoDatos.SelectedValue}").ToString.ToEntero)
End If
UpINV.Update()
End Sub
Private Sub CargaFormaEntrega()
'TrFormaEntrega.Visible = True
DdlFormaEntrega.DataSource = GlobalDTVtaCondicionesEntrega(UsuarioActual.CveEmpresa)
DdlFormaEntrega.DataBind()
DdlFormaEntrega.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub CargaCliente(CveCliente As Integer, Optional Estatus As Integer = 1)
Dim ObjCliente As New ClsClientes()
If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, Estatus, TipoCliente:=-1) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
TxtCodigo.Text = ObjCliente.Codigo
LblCliente.Text = String.Format("<a Class=""Texto"" href=""/Ventas/Clientes.aspx?CveCliente={0}"">{1}</a>", CveCliente, ObjCliente.Nombre)
ViewState("NombreCliente") = ObjCliente.Nombre
LtlCliente.Text = ObjCliente.Nombre
ChkEnviarFactura.Checked = ObjCliente.EnviarFactura
ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail)
ViewState("MailCC") = ObjCliente.NotificarA
LblDireccion.Text = ObjCliente.Direccion
LblColonia.Text = ObjCliente.Colonia
LblCiudad.Text = ObjCliente.Ciudad
LblEstado.Text = ObjCliente.Estado
LblCP.Text = ObjCliente.CP
LblRFC.Text = ObjCliente.RFC
LblTelefono.Text = ObjCliente.Telefono
LblRetIVA.Text = ObjCliente.RetIVA.ToString.FormatoNumero(5)
LblRetISR.Text = ObjCliente.RetISR.ToString.FormatoNumero(5)
ViewState("ClienteRetIVA") = ObjCliente.RetIVA / 100
ViewState("ClienteRetISR") = ObjCliente.RetISR / 100
ViewState("RetIVAFletes") = ObjCliente.RetieneIVAFletes
If ObjCliente.RetieneIVAFletes Then
TrRetIVA.Style.Add("display", "")
UsuarioActual.Empresa.MostrarRetIVA = True
End If
ViewState("Vendedor") = ObjCliente.Vendedor
ViewState("CtaContable") = ObjCliente.CuentaContable
ViewState("IdCtaContClientes") = ObjCliente.IdCtaContClientes
ViewState("IdCtaContMonedaExtranjera") = ObjCliente.IdCtaContMonedaExtranjera
ViewState("IdCtaContComplementaria") = ObjCliente.IdCtaContComplementaria
ViewState("IdCtaContAnticipos") = ObjCliente.IdCtaContAnticipos
ViewState("IdCtaContRetIVA") = ObjCliente.IdCtaContRetIVA
ViewState("IdCtaContRetISR") = ObjCliente.IdCtaContRetISR
ViewState("CodCliente") = ObjCliente.Codigo
ViewState("ClienteDesglosaIEPS") = ObjCliente.DesglosaIEPS
ViewState("CliNoExt") = ObjCliente.NoExt
ViewState("CliNoInt") = ObjCliente.NoInt
ViewState("CliLocalidad") = If(ObjCliente.Localidad.Trim.Length = 0, ObjCliente.Ciudad.Trim, ObjCliente.Localidad.Trim)
ViewState("CliPais") = ObjCliente.Pais
'ViewState("NumCtaPago") = ObjCliente.NumCtaPago
EnviarCorreoCliente = ObjCliente.EnviarFactura
ChkEnviarFactura.Visible = True
ChkEnviarFactura.Checked = EnviarCorreoCliente
LblEnviarMail.Visible = True
Dim dr As DataRow = Nothing
dr = GlobalDTSubProyectos(-1).FiltroPrimero("Estatus = 'Activo' AND CveEmpresa = " & UsuarioActual.CveEmpresa)
If dr IsNot Nothing Then
ViewState("MatCalle") = dr("Calle")
ViewState("MatNoExt") = dr("NoExt")
ViewState("MatNoInt") = dr("NoInt")
ViewState("MatColonia") = dr("Colonia")
ViewState("MatLocalidad") = dr("Localidad")
ViewState("MatMunicipio") = dr("Municipio")
ViewState("MatEstado") = dr("Estado")
ViewState("MatPais") = dr("Pais")
ViewState("MatCP") = dr("CP")
End If
If CveVenta <= 0 Then
DdlMetodoPago.SelectedValue = ObjCliente.CveMetodoPago.ToString
DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI)
End If
TxtFechaPago.Text = (Now.AddDays(ObjCliente.PlazoCobranza)).ToShortDateString
If ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero > 0 Then
DdlVendedor.SelectedValueExist(ObjCliente.DtResultados(0)("CveVendedor").ToString.ToEntero)
End If
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
EstatusCliente = ObjCliente.Estatus
If Not EstatusCliente Then
BtnEmitirImprimir.Enabled = False
Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia)
Else
BtnEmitirImprimir.Enabled = True
End If
UpFacturar.Update()
If UsuarioActual.Empresa.UsaInventarios Then
RblTipo.Items.Remove(RblTipo.Items.FindByValue("1"))
RblTipo.Items.Remove(RblTipo.Items.FindByValue("2"))
End If
UpnTools.Update()
If Not CveVenta > 0 Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
If UsuarioActual.TienePermisoProceso(152) Then
DdlSubProyectoDatos.SelectedValueExist(UsuarioActual.CveSubProyecto)
DdlSubProyectoDatos.Enabled = False
Else
DdlSubProyectoDatos.SelectedValueExist(ObjCliente.CveSubProyecto)
End If
'RECARGA LOS VALORES DE LA SUCURSAL
CambiaSucursal()
UpParametros.Update()
End If
End If
If ObjCliente.GetSucursales(CveCliente) Then
DdlSucursalCliente.DataSource = ObjCliente.DtResultados
If ObjCliente.DtResultados.Rows.Count > 0 Then
trsucursalciente.Visible = True
Else
trsucursalciente.Visible = False
End If
Else
trsucursalciente.Visible = False
DdlSucursalCliente.DataSource = Nothing
End If
DdlSucursalCliente.DataBind()
LbAgregar.Enabled = True
UpEstatus.Update()
UpPS.Update()
UpParametros.Update()
UPCondicionesPago.Update()
UpComplementos.Update()
CargarAlmacenes()
CargaFacturasAjuste()
Else
Alert("El cliente solicitado no existe, por favor intente de nuevo.", TipoMensaje.MsgError)
End If
End If
ObjCliente.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 CargaFormatoSucursal()
Dim dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)))
If dr IsNot Nothing Then
ViewState("SucCalle") = dr("Calle")
ViewState("SucNoExt") = dr("NoExt")
ViewState("SucNoInt") = dr("NoInt")
ViewState("SucColonia") = dr("Colonia")
ViewState("SucLocalidad") = dr("Localidad")
ViewState("SucMunicipio") = dr("Municipio")
ViewState("SucEstado") = dr("Estado")
ViewState("SucPais") = dr("Pais")
ViewState("SucCP") = dr("CP")
ViewState("FormatoFactura") = dr("FormatoFactura")
ViewState("IVA") = dr("IVA")
ViewState("SubProyectoPorcentajeIVA") = dr("IVA")
ViewState("TipoFormato") = dr("TipoFormato")
ViewState("Serie") = dr("Serie")
LblSerie.Text = dr("Serie").ToString
If SerieXML <> "" Then LblSerie.Text = SerieXML
If dr("TipoVenta").ToString = "1" Then
UpnTools.Update()
'activa el modo de pago efectivo directamente, y es venta nueva
If ViewState("CveVenta").ToString.ToEntero < 0 Then InicializaCondicionesPago()
DdlFormaPago.SelectedValueExist("0")
DdlMetodoPago.SelectedValueExist("1")
RBLPago.SelectedValue = "2"
LimpiaEscondeContado()
If DdlCuentaEfectivo.Items.Count = 2 Then
DdlCuentaEfectivo.SelectedIndex = 0
End If
End If
End If
DdlMetodoPago.SelectedValueExist(CveMetodoPagoCliente.ToString)
UpFacturar.Update()
UpParametros.Update()
End Sub
Private Sub CargaClienteSucursal(CveClienteSuc As Integer, Optional ByRef ObjVentas As ClsVentas = Nothing)
Dim ObjCliente As New ClsClientes
If CveClienteSuc > 0 Then
If ObjCliente.GetSucursales(CveCliente, CveClienteSuc) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
Dim Correo = ObjCliente.DtResultados.Rows(0)("Correo").ToString
If Correo.Trim.Length > 0 Then
ViewState("Mail") = Correo
End If
LblDireccion.Text = ObjCliente.DtResultados.Rows(0)("Direccion").ToString
LblColonia.Text = ObjCliente.DtResultados.Rows(0)("Colonia").ToString
LblCiudad.Text = ObjCliente.DtResultados.Rows(0)("Ciudad").ToString
LblEstado.Text = ObjCliente.DtResultados.Rows(0)("Estado").ToString
'TxtNumCtaPago.Text = ObjCliente.DtResultados.Rows(0)("NumCtaPago").ToString
LblTelefono.Text = ObjCliente.DtResultados.Rows(0)("Telefono").ToString
LblCP.Text = ObjCliente.DtResultados.Rows(0)("CP").ToString
ViewState("CliLocalidad") = ObjCliente.DtResultados.Rows(0)("Localidad").ToString
ViewState("CliPais") = ObjCliente.DtResultados.Rows(0)("Pais").ToString
ViewState("CliNoExt") = ObjCliente.DtResultados.Rows(0)("NoExt").ToString
ViewState("CliNoInt") = ObjCliente.DtResultados.Rows(0)("NoInt").ToString
DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString)
ViewState("CveClienteSucursal") = ObjCliente.DtResultados(0)("CveClienteSucursal").ToString
ViewState("CliCorreoCot") = ObjCliente.DtResultados.Rows(0)("CorreoCotizacion").ToString
If ObjCliente.DtResultados.Rows(0)("Estatus").ToString <> "Activo" Then
RBLPago.Items(0).Enabled = False
Alert("La Sucursal/Departamento del cliente se encuentra inactivo")
End If
If CveVenta <= 0 Then
CveMetodoPagoCliente = ObjCliente.DtResultados.Rows(0)("CveMetodoPago").ToString.ToEntero
DdlMetodoPago.SelectedValueExist(CveMetodoPagoCliente.ToString)
DdlFormaPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveFormaPago33").ToString)
DdlMetodoPago33.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveMetodoPago33").ToString)
DdlUsoCFDI.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveUsoCFDI").ToString)
End If
If CveVenta < 0 Then TxtAtencionA.Text = ObjCliente.DtResultados.Rows(0)("Contacto").ToString
End If
Else
Alert("No se pudieron cargar los datos de la sucursal", TipoMensaje.MsgAdvertencia)
End If
Else
If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, TipoCliente:=-1) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
ViewState("Mail") = If(DdlTipoComprobante.SelectedValue = "Cot", ObjCliente.MailCotizacion, ObjCliente.Mail)
LblDireccion.Text = ObjCliente.Direccion
LblColonia.Text = ObjCliente.Colonia
LblCiudad.Text = ObjCliente.Ciudad
LblEstado.Text = ObjCliente.Estado
LblCP.Text = ObjCliente.CP
LblTelefono.Text = ObjCliente.Telefono
DdlVendedor.SelectedValueExist(ObjCliente.DtResultados.Rows(0)("CveVendedor").ToString)
ViewState("CliNoExt") = ObjCliente.NoExt
ViewState("CliNoInt") = ObjCliente.NoInt
PlazoCobranza = ObjCliente.PlazoCobranza
If CveVenta <= 0 Then
CveMetodoPagoCliente = ObjCliente.CveMetodoPago
DdlMetodoPago.SelectedValueExist(CveMetodoPagoCliente.ToString)
DdlFormaPago33.SelectedValueExist(ObjCliente.CveFormaPago33)
DdlMetodoPago33.SelectedValueExist(ObjCliente.CveMetodoPago33)
DdlUsoCFDI.SelectedValueExist(ObjCliente.CveUsoCFDI)
End If
End If
End If
End If
'SI LA SUCURSAL DEL CLIENTE NO TIENE VENDEDOR SELECCIONAMOS EL DEL USUARIO
If Not DdlVendedor.SelectedValue.ToEntero > 0 Then
DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString)
End If
UPPVentas.Update()
UpEstatus.Update()
UPCondicionesPago.Update()
ObjCliente.Dispose()
End Sub
Private Sub SetValues()
ViewState("TipoCambio") = 1
If UsuarioActual.Empresa.MostrarRetIVA Then TrRetIVA.Style.Add("display", "")
If UsuarioActual.Empresa.MostrarRetISR Then TrRetISR.Style.Add("display", "")
End Sub
Private Sub CargaClasificaciones()
If UsuarioActual.Empresa.UsaAC Then
DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
Else
DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("Estado = 1", Orderby:="Clasificacion")
End If
DdlClasificacion.DataBind()
End Sub
Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost)
Objeto.setEsWebService(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1")
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
Objeto.ddl.Items.Clear()
Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, Estatus:=1, AplicaParaVenta:=1)
Objeto.ddl.DataBind()
Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2"))
Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1"))
Else
Objeto.Attributes.Add("data-cvesubproyecto", DdlSubProyectoDatos.SelectedValue)
Objeto.ddlWS.Attributes.Add("data-cveclasificacion", CveClasificacion.ToString)
Objeto.ddlWS.Attributes.Add("data-pagina", "ventas/ventas")
Objeto.ddlWS.Attributes.Add("data-Estatus", "1")
End If
End Sub
Private Sub CargaFolios()
If ExFolioFactura Then
Exit Sub
End If
If DdlSubProyectoDatos.SelectedValue.ToEntero <= 0 Then
Alert("No se tienen asignadas sucursales", TipoMensaje.MsgError)
Exit Sub
End If
'If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue <> "Cot" AndAlso (CveVenta <= 0 Or (DtVentasNC IsNot Nothing AndAlso DtVentasNC.Rows.Count > 0) Or CveDevolucion > 0) Then
' TxtFolio.Text = ""
'Else
Dim ObjFolios As New ClsGralFolios()
Dim TipoDoctoConsulta As String = If(DdlTipoComprobante.SelectedValue = "Ant", "Ing", If(DdlTipoComprobante.SelectedValue = "PA", "Rem", DdlTipoComprobante.SelectedValue))
If ObjFolios.GetFolios(TipoDoctoConsulta, UsuarioActual.CveEmpresa) Then
Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format(" CveSubProyecto = {0} And Estado = 'Activo'", DdlSubProyectoDatos.SelectedValue))
If DT.Rows.Count > 0 Then
ViewState("CveFolio") = DT.Rows(0)("CveFolio").ToString.ToEntero
'ViewState("NumAprobacion") = CLng(DT.Rows(0)("Aprobacion").ToString)
'ViewState("FechaAprobacion") = DT.Rows(0)("FechaAprobacion").ToString.ToDate
ViewState("FolioActual") = DT.Rows(0)("FActual").ToString
LblSerie.Text = DT.Rows(0)("Serie").ToString
TxtFolio.Text = DT.Rows(0)("FActual").ToString
BtnEmitirImprimir.Visible = True
UpFacturar.Update()
Else
Alert("No tiene registrados Folios para " & DdlTipoComprobante.SelectedItem.Text & " en esta sucursal.", TipoMensaje.MsgAdvertencia)
BtnEmitirImprimir.Visible = False
UpFacturar.Update()
End If
DT.Dispose()
End If
ObjFolios.Dispose()
'End If
End Sub
Private Sub CargaDdlSubProyectos()
DdlSubProyectoDatos.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ")
DdlSubProyectoDatos.DataBind()
End Sub
Private Sub CargaVendedores()
Dim CveVendedorActual = DdlVendedor.SelectedValue
DdlVendedor.Items.Clear()
If UsuarioActual.Empresa.Funcionalidad(302) = "1" AndAlso DdlSubProyectoDatos.SelectedValue.ToEntero > 0 Then
DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue)).FiltraParametros("VendedorTipo = 1")
Else
DdlVendedor.DataSource = GlobalDTVendedores(UsuarioActual.CveEmpresa).FiltraParametros("VendedorTipo = 1")
End If
DdlVendedor.SelectedValue = "0"
DdlVendedor.Items.Insert(0, New ListItem("Sin Asignar", "0"))
DdlVendedor.DataBind()
DdlVendedor.SelectedValueExist(CveVendedorActual)
If Not DdlVendedor.SelectedValue.ToEntero > 0 Then
DdlVendedor.SelectedValueExist(UsuarioActual.CveVendedor.ToString)
End If
End Sub
Private Sub ObtenerFechaVencimientoCER()
Try
Dim CerFile As New FileStream(Ruta & "Certificados\" & UsuarioActual.Empresa.ArchivoCer, FileMode.Open, FileAccess.Read)
Dim Size As Integer = CerFile.Length.ToString.ToEntero()
Dim Data As Byte() = New Byte(Size - 1) {}
Size = CerFile.Read(Data, 0, Size)
CerFile.Close()
CerFile.Dispose()
Dim x509 As New X509Certificate2()
x509.Import(Data)
If x509.NotAfter <= Now() Then
BtnEmitirImprimir.Enabled = False
Alert("La fecha del certificado ha expirado", TipoMensaje.MsgAdvertencia)
End If
Catch ex As Exception
Alert("No se pudo verificar la fecha del certificado", TipoMensaje.MsgError)
End Try
End Sub
#End Region
#Region "GVPS"
Protected Sub GvPS_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvPS.RowDeleting
Dim DbRow As DataRow = Nothing
DbRow = TmpDT.Rows(e.RowIndex)
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
Protected Sub GvPS_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvPS.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("id") = e.Row.RowIndex.ToString
'MODO NORMAL
If UsuarioActual.Empresa.UsaAC Then
e.Row.FCDropDownList("DdlFR").DataSource = DTPresupuestoIngresos
e.Row.FCDropDownList("DdlFR").DataBind()
e.Row.FCDropDownList("DdlFR").SelectedValue = e.Row.DBCampo("CvePresupuestoIngreso")
'e.Row.FCDropDownList("DdlFR").Enabled = False
End If
If e.Row.DataKey("IEPS").ToDouble > 0 Then : TrIEPS.Visible = True : End If
If NuevaFactura = 1 Then
'PUEDE EDTIRAR EL PU DEL PRODUCTO
If UsuarioActual.TienePermisoProceso(222) Then
' e.Row.FCTextBox("TxtPrecio").Enabled = True
e.Row.FCLinkButton("imgD").Visible = True
e.Row.FCLinkButton("imgD").Visible = False
Else
e.Row.FCLinkButton("imgD").Visible = False
e.Row.FCLinkButton("imgE").Visible = False
End If
End If
If UsuarioActual.Empresa.CvePlataforma = 2 Then
e.Row.FCLinkButton("imgE").Visible = False
e.Row.FCLinkButton("imgEPyME").Visible = True
End If
End If
End Sub
Protected Sub OrdenarGvPS(ByVal sender As Object, ByVal e As EventArgs)
For Each row As GridViewRow In GvPS.Rows
TmpDT.Rows(row.RowIndex)("Orden") = row.FCTextBox("TxtOrden").Text.ToEntero
Next
Dim resultados = From OrdenDT In TmpDT
Order By OrdenDT("Orden").ToString.ToEntero
Select OrdenDT
TmpDT = resultados.CopyToDataTable
CalculaTotalesVenta()
GvPS.DataSource = TmpDT
GvPS.DataBind()
UpPS.Update()
End Sub
#End Region
#Region "GVINV"
Private Sub GvInv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvInv.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'SERIE ALMACEN
If e.Row.DBCampo("CveTipoInvPS").ToEntero = 5 Then
If CveVenta > 0 Then
e.Row.FCLiteral("LtlSerie").Visible = True
Else
e.Row.FCTextBox("TxtSerie").Visible = True
e.Row.FCTextBox("TxtSerie").Attributes.Remove("onkeypress")
e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeypress", String.Format("SeriePS(event,{0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID))
e.Row.FCTextBox("TxtSerie").Attributes.Remove("onblur")
e.Row.FCTextBox("TxtSerie").Attributes.Add("onblur", String.Format("SeriePSBlur({0},this,{1});", e.Row.FCButton("BtnSerie").ClientID, e.Row.FCHiddenField("HdnSerie").ClientID))
End If
'e.Row.FCTextBox("TxtSerie").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID))
'e.Row.FCTextBox("LblCodigo").Attributes.Add("onkeyup", String.Format("LimpiaAF(1, '{0}'); EnterAFEdit(event,this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID))
'e.Row.FCTextBox("LblCodigo").Attributes.Add("onblur", String.Format("LimpiaAF(1, '{0}'); AFBlurEdit(this,{1},{2});", e.Row.FCHiddenField("HdnCveConcepto").Value, e.Row.FCHiddenField("HdnCveAF").ClientID, e.Row.FCHiddenField("HdnCodAF").ClientID))
End If
If e.Row.DBCampo("CvePS") = "" Then
e.Row.FCLiteral("LtlPS").Text = String.Format("<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
If UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then
e.Row.FCCheckBox("cbInv").Checked = True
End If
End If
If CveVenta > 0 Then
e.Row.FCCheckBox("cbInv").Visible = False
End If
End If
End Sub
Protected Sub GVINV_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles GvInv.RowEditing
GvInv.EditIndex = e.NewEditIndex
CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2"))
End Sub
Protected Sub GVINV_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles GvInv.RowCancelingEdit
GvInv.EditIndex = -1
CargaGVInv(DtInv.FiltraParametros("CveTipoPS=2"))
End Sub
Protected Sub GVINV_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles GvInv.RowUpdating
Dim Cantidad As Double = DirectCast(GvInv.Rows(e.RowIndex).FindControl("txtECantidad"), TextBox).Text.ToDouble
DtInv.Rows.Item(e.RowIndex)("Cantidad") = Cantidad
GvInv.DataSource = DtInv.FiltraParametros("CveTipoPS=2")
End Sub
#End Region
#Region " INVENTARIO POR ENTREGA"
Private Sub CargaGVInv(DtTemporal As DataTable)
If Not DtTemporal.Columns.Contains("Lote") Then
DtTemporal.Columns.Add("Lote", Type.GetType("System.String"))
End If
If Not DtTemporal.Columns.Contains("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 " EMITIR IMPRIMIR - GUARDAR "
Protected Sub BtnEmitirImprimir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEmitirImprimir.Click
If Not CveCliente > 0 Then
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If TmpDT Is Nothing OrElse TmpDT.Rows.Count = 0 Then
Alert("Es necesario tener al menos un concepto registrado.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'Subproyecto Obligatorio
If UsuarioActual.Empresa.Funcionalidad(120) = "1" AndAlso TmpDT.FiltraParametros("ISNULL(CveSubProyecto,0) <= 0").Rows.Count > 0 Then
Alert("El Subproyecto es obligatorio, favor de seleccionarlo", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'VALIDA PRECIO AL AGREGAR A ALMACEN
If Not UsuarioActual.TienePermisoProceso(169) Then
If Not CveContrato > 0 Then
If DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing") Then
Dim MensajeCosto As New StringBuilder
Dim CostoMenor = 0.0D
Dim CostoMayor = 0.0D
Dim Costo = 0.0D
Dim EsValido = False 'BANDERA
Dim EsValidoMayor = False
'VALIDA PROMOCIONES Y EXISTENCIAS
Dim ObjVentas As New ClsVentas
If ObjVentas.GetPromocionesPS(-1, TxtFecha.Text.ToDateTime, DdlSubProyectoDatos.SelectedValue.ToEntero, CveCliente, DdlVendedor.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
DtPromociones = ObjVentas.DtResultados
End If
ObjVentas.Dispose()
Dim ObjInventarios As New ClsInventarios
Dim PU = 0.0D
For Each dr As DataRow In TmpDT.Rows
'SI ES SERVICIO NO VALIDA
If GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=dr("CvePS").ToString.ToEntero).FiltroPrimeroValor("CveTipoPS").ToString.ToEntero = 1 Then
Continue For
End If
EsValido = False
PU = dr("PU").ToString.ToDecimal * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal)
'COSTO ALMACEN
If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString.ToEntero, dr("Cantidad").ToString.ToDouble, -1, dr("SerieLote").ToString, TxtFecha.Text.ToDate, -1)
CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo)
'SI EL PRECIO ES MAYOR AL COSTO, SI PASA
If PU >= CostoMenor Then
EsValido = True
End If
Else
EsValido = True
End If
If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
Costo = ObjInventarios.GetCostoPS(dr("CvePS").ToString.ToEntero, dr("Cantidad").ToString.ToDouble, -1, dr("SerieLote").ToString, TxtFecha.Text.ToDate)
CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo)
'SI EL PRECIO ES MAYOR AL COSTO, SI PASA
If PU <= CostoMayor Then
EsValidoMayor = True
End If
Else
EsValidoMayor = True
End If
'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR
If Not EsValido Then
If DtPromociones.FiltraParametros($"CvePS = {dr("CvePS").ToString.ToEntero}").Rows.Count > 0 Then
If PU >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {dr("CvePS").ToString.ToEntero}").ToDecimal Then
EsValido = True
End If
End If
End If
'NO DEJA REGISTRAR CON VALIDACION DE COSTO ALMACEN O PROMOCION
If Not EsValido Then
MensajeCosto.AppendFormat("El Producto <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)
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)
End If
Next
ObjInventarios.Dispose()
If MensajeCosto.ToString.Length > 1 Then
Alert(MensajeCosto.ToString, TipoMensaje.MsgAdvertencia)
Exit Sub
End If
End If
End If
End If
If UsuarioActual.Empresa.Funcionalidad(135) = "1" And DdlTipoComprobante.SelectedValue = "Cot" Then
Alert("Se mando autorización al supervisor.")
MandarCorreoSupervisor = True
Dim CorreoSupervisor As String = ""
Dim Objeto As New ClsVtaVendedores
Dim DTSupervisores As New DataTable
If Objeto.GetVendedores(UsuarioActual.CveEmpresa) Then
DTSupervisores = Objeto.DtResultados.FiltraParametros(String.Format("CveVendedor = {0}", DdlVendedor.SelectedValue.ToEntero))
'Verifico si el supervisor tiene correo para proceder
If DTSupervisores.Rows.Count > 0 Then
CorreoSupervisor = DTSupervisores.Rows(0)("CorreoSupervisor").ToString
End If
End If
Objeto.Dispose()
If MandarCorreoSupervisor = True And CorreoSupervisor <> "" Then
ViewState("Mail") = CorreoSupervisor
End If
MandarCorreoSupervisor = False
End If
'If DdlTipoComprobante.SelectedValue = "Cot" Then
' EmitirImprimirNew()
'Else
' LimpiaEscondeContado()
'End If
If TmpDTAjustes IsNot Nothing AndAlso Not TmpDTAjustes.Rows.Count > 0 AndAlso UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then
RegistraScript(String.Format("$('#{0}').modal('show');", "DModalRecepcionUsados"))
Else
EmitirImprimirNew()
End If
End Sub
#End Region
#Region " NNNNEEEEEEEWWWWWW "
Protected Sub EmitirImprimirNew()
If ValidaPagosContado() Then
Exit Sub
End If
CreaObjetosVenta()
If ObjFactura Is Nothing Or ObjFactura.Cliente Is Nothing Then
Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError)
ObjFactura = Nothing
Exit Sub
End If
If ObjFactura.CveCliente > 0 Then
If TmpDT.Rows.Count > 0 Then
Dim Retorno = ObjFactura.EmitirFactura()
For Each Mensaje In Retorno.Mensajes
Alert(Mensaje, If(Retorno.TieneError, TipoMensaje.MsgError, TipoMensaje.MsgInformacion), If(Retorno.TieneError, "", Retorno.LigaPV))
Next
' 'MUESTA ALERT OK
' 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)
End If
End If
End Sub
#End Region
#Region "OBJETO VENTA"
Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False)
ObjFactura = New Modelos.Factura(UsuarioActual)
ObjFactura.CveUsuario = UsuarioActual.CveUsuario
ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa
ObjFactura.TipoCambio = TxtTipoCambio.Text.Trim.ToDecimal
ObjFactura.TipoCambioDolares = TxtTipoCambioDlls.Text.Trim.ToDecimal
ObjFactura.ConvertirPesos = ChkConvertirDoctoPesos.Checked
ObjFactura.ConvertirDolares = ChkConvertirDolares.Checked
ObjFactura.CveMoneda = DdlMoneda.SelectedValue.ToEntero
ObjFactura.Moneda = DdlMoneda.SelectedItem.Text
ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {DdlMoneda.SelectedValue}")
ObjFactura.TipoDocto = If(IfNull(ViewState("CveRemision"), 0).ToString.ToEntero > 0, "Ing", DdlTipoComprobante.SelectedValue)
'ObjFactura.RefDocto = TxtDocto.Text.Trim
ObjFactura.Folio = If(EstablecioFolio Or VistaPrevia Or (CveVenta > 0 And (NuevaFactura.Contiene(0, 2))), TxtFolio.Text.Trim.ToEntero, -1)
'ObjFactura.Folio = If(ExFolioFactura, FolioXML.ToEntero, -1)
ObjFactura.Serie = If(VistaPrevia, "VistaPrevia", LblSerie.Text)
ObjFactura.Fecha = New Date(TxtFecha.Text.Trim.ToDate.Year, TxtFecha.Text.Trim.ToDate.Month, TxtFecha.Text.Trim.ToDate.Day, Now.Hour, Now.Minute, Now.Second)
ObjFactura.CvePrePoliza = -1
ObjFactura.CveMetodoPago = DdlMetodoPago.SelectedValue.ToEntero
ObjFactura.MetodoPago = DdlMetodoPago.SelectedItem.Text
ObjFactura.ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimeroValor("ClaveSAT", $"CveMetodoPago = {DdlMetodoPago.SelectedValue}")
ObjFactura.FechaVencimiento = TxtFechaPago.Text.ToDate
ObjFactura.CveMetodoPago33 = DdlMetodoPago33.SelectedValue.ToEntero
ObjFactura.MetodoPago33 = If(DdlMetodoPago33.SelectedValue.ToEntero > 0, DdlMetodoPago33.SelectedItem.Text, "")
ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {DdlMetodoPago33.SelectedValue}")
ObjFactura.CveFormaPago33 = DdlFormaPago33.SelectedValue.ToEntero
ObjFactura.FormaPago33 = If(DdlFormaPago33.SelectedValue.ToEntero > 0, DdlFormaPago33.SelectedItem.Text, "")
ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {DdlFormaPago33.SelectedValue}")
ObjFactura.CveUsoCFDI = DdlUsoCFDI.SelectedValue.ToEntero
ObjFactura.UsoCFDI = If(DdlUsoCFDI.SelectedValue.ToEntero > 0, DdlUsoCFDI.SelectedItem.Text, "")
ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {DdlUsoCFDI.SelectedValue}")
ObjFactura.UsuarioCreo = LblUsuario.Text.Trim
ObjFactura.CveCondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedValue.ToEntero, -1)
ObjFactura.CondicionEntrega = If(DdlFormaEntrega.SelectedItem IsNot Nothing, DdlFormaEntrega.SelectedItem.Text, "")
ObjFactura.CondicionesPago = If(RBLPago.SelectedValue = "2", 0, If(RBLPago.SelectedValue = "1", 1, 2)) ' 0 - Contado, 1 - Credito, 2 - termianl
ObjFactura.FormaPago = DdlFormaPago.SelectedValue.ToEntero
Select Case ObjFactura.TipoDocto
Case "Ing"
ObjFactura.TipoDocumento = "Factura"
Case "Rem"
ObjFactura.TipoDocumento = "Remision"
Case "Cot"
ObjFactura.TipoDocumento = "Cotizacion"
Case "Egs"
ObjFactura.TipoDocumento = "Nota de Crédito"
Case "Dev"
ObjFactura.TipoDocumento = "Nota de Devolución"
Case Else
ObjFactura.TipoDocumento = ""
End Select
ObjFactura.Fech1 = Now
ObjFactura.Fech2 = Now
ObjFactura.Fech3 = Now
ObjFactura.Alfa1 = ""
ObjFactura.Alfa2 = ""
ObjFactura.Alfa3 = ""
ObjFactura.Num1 = 0
ObjFactura.Num2 = 0
ObjFactura.Num3 = DdlOrdenPago.SelectedValue.ToDouble
ObjFactura.FechaPago = TxtFechaPago.Text.ToDate
ObjFactura.CveCorte = CveCorte
ObjFactura.CveMesa = -1
ObjFactura.NumeroPersonas = 0
ObjFactura.CveContrato = If(CveContrato > 0, CveContrato, CvePresupuesto)
ObjFactura.CveClienteSucursal = DdlSucursalCliente.SelectedValue.ToEntero
ObjFactura.Entrega = Entrega
ObjFactura.Vigencia = Now
ObjFactura.CveVentaPadre = If(CveDevolucion > 0, CveDevolucion, CvePedido)
ObjFactura.CveVendedor = DdlVendedor.SelectedValue.ToEntero
If DdlVendedor.SelectedValue.ToEntero > 0 AndAlso Not UsuarioActual.TienePermisoProceso(161) Then
DdlVendedor.Enabled = False
End If
ObjFactura.FechaEjecucion = Now
ObjFactura.CveSucursalEjecucion = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFactura.CveSucursalCobranza = -1
ObjFactura.CveSubProyecto = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFactura.CveSubProyectoEjecucion = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFactura.CveSubProyectoCobranza = -1
ObjFactura.AtencionA = If(ObjFactura.TipoDocto = "Cot", TxtAtencionA.Text, "-1")
ObjFactura.MotivoDescuento = TxtMotivoDescuento.Text.Trim
ObjFactura.Observaciones = TxtObsFact.Text.Trim
ObjFactura.Det_OrdenCompra = ""
ObjFactura.Det_FechaOrdenCompra = MinFecha.ToShortDateString
ObjFactura.MonedaAbreviatura = ""
'Totales, Y se llena TmpDTImpuestos
ObjFactura.SubTotal = TxtSubTotal.Text.ToDecimal
ObjFactura.Descuento = LblDescuentos.Text.Trim.ToDecimal
ObjFactura.Amortizacion = LblAmortizacion.Text.Trim.ToDecimal
ObjFactura.IVA = TxtIVA.Text.ToDecimal
ObjFactura.RetIVA = TxtRetIVA.Text.ToDecimal
ObjFactura.RetISR = TxtRetISR.Text.ToDecimal
ObjFactura.IEPS = TxtIEPS.Text.ToDecimal
ObjFactura.Total = TxtTotal.Text.ToDecimal
ObjFactura.DtDeduccion = New DataTable
'OTROS
ObjFactura.Det_FechaOrdenCompra = ""
ObjFactura.Det_OrdenCompra = ""
ObjFactura.CveNCaVincular = DdlNCFactura.SelectedValue.ToEntero
If ObjFactura.CveMoneda <> 1 AndAlso ChkConvertirDoctoPesos.Checked Then
ObjFactura.TipoCambio = TxtTipoCambio.Text.Trim.ToDecimal
ObjFactura.CveMoneda = 1
ObjFactura.Moneda = "Pesos"
ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}")
End If
If ObjFactura.CveMoneda <> 2 AndAlso ChkConvertirDolares.Checked Then
ObjFactura.TipoCambio = TxtTipoCambioDlls.Text.Trim.ToDecimal
ObjFactura.CveMoneda = 2
ObjFactura.Moneda = "Dólares"
ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", $"CveMoneda = {ObjFactura.CveMoneda}")
End If
'Se agrega CveVenta -1
For Each Row As DataRow In TmpDT.Rows
Row("CveVenta") = ObjFactura.CveVenta
Next
'DETALLES
ObjFactura.DtDetalle = TmpDT
ObjFactura.DtFirmas = DTmpF
'CLIENTE
ObjFactura.CveCliente = CveCliente
ObjFactura.SetCliente()
'SUCURSAL
ObjFactura.CveSucursal = DdlSubProyectoDatos.SelectedValue.ToEntero
ObjFactura.SetSubProyectoMatriz(Me)
ObjFactura.SetSubProyecto(Me)
ObjFactura.ClienteSucursal = New Modelos.SucursalModel
ObjFactura.ClienteSucursal.NoExt = CliNoExt
ObjFactura.ClienteSucursal.NoInt = CliNoInt
ObjFactura.ClienteSucursal.Localidad = CliLocalidad
ObjFactura.ClienteSucursal.Direccion = LblDireccion.Text
ObjFactura.ClienteSucursal.Colonia = LblColonia.Text
ObjFactura.ClienteSucursal.Municipio = LblCiudad.Text
ObjFactura.ClienteSucursal.Estado = LblEstado.Text
ObjFactura.ClienteSucursal.CP = LblCP.Text
ObjFactura.ClienteSucursal.Pais = CliPais
ObjFactura.ClienteSucursal.CorreoSucursal = CliCorreoCot.ToString
ObjFactura.ClienteSucursal.TelefonoSucursal = LblTelefono.Text
ObjFactura.ClienteSucursal.Sucursal = DdlSucursalCliente.SelectedItem.Text
ObjFactura.DtDetalle = TmpDT
ObjFactura.DtPagos = DtPagos
ObjFactura.DtPromociones = DtPromociones
Dim FM As New Modelos.FemsaFactura
Dim TmpDT7Eleven As New DataTable
Dim TmpDTComplementosTimbrado As New DataTable
PrepararTimbrado(FM, TmpDT7Eleven, TmpDTComplementosTimbrado)
ObjFactura.FemsaFactura = FM
ObjFactura.Timbre = PreParaTimbre(ObjFactura)
ObjFactura.DtAjustes = TmpDTAjustes
ObjFactura.DtRecepcionUsados = TmpDTRecepcionUsados
Dim CveTipoAlmacen As Integer = If(TmpDTAjustes IsNot Nothing AndAlso TmpDTAjustes.Rows.Count > 0, 6, 22)
If GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltraParametros($"CveTipoAlmacen = {CveTipoAlmacen} AND CveSubProyecto= {DdlSubProyectoDatos.SelectedValue}").Rows.Count > 0 Then
ObjFactura.CveAlmacenRecepcionUsados = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltraParametros($"CveTipoAlmacen = {CveTipoAlmacen} AND CveSubProyecto= {DdlSubProyectoDatos.SelectedValue}").Rows(0)("CveAlmacen").ToString.ToEntero
End If
If Not ddlAlmacen.SelectedValue.ToEntero > 0 AndAlso ddlAlmacen.Items.Count > 1 AndAlso UsuarioActual.Empresa.Funcionalidad(531).ToString = "1" Then
ddlAlmacen.SelectedIndex = 1
End If
ObjFactura.CveAlmacen = ddlAlmacen.SelectedValue.ToEntero
DtInv.Columns.Add("Seleccionado", GetType(Integer))
For Each Gvr As GridViewRow In GvInv.Rows
Dim Dr As DataRow = DtInv.Select($"CvePS={Gvr.DataKey("CvePS")}")(0)
If Gvr.FCCheckBox("cbInv").Checked Then
Dr("Seleccionado") = 1
Else
Dr("Seleccionado") = 0
End If
Next
DtInv.AcceptChanges()
ObjFactura.DtInventario = DtInv.FiltraParametros("Seleccionado = 1")
End Sub
#End Region
#Region "TIMBRADO"
Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre
Dim Timbre As New CFDITimbre
Timbre.Comprobante.TipoComprobante = If(Obj.TipoDocto.Contiene("Ing", "Ant"), "I", If(Obj.TipoDocto.Contiene("Egs", "Dev"), "E", ""))
Timbre.Comprobante.Folio = Obj.Folio.ToString
Timbre.Comprobante.Serie = Obj.Serie
Timbre.Comprobante.Fecha = Obj.Fecha
Timbre.Comprobante.FormadePago = Obj.FormaPagoSAT33
Timbre.Comprobante.CondicionesdePago = Obj.FormaPago33
Timbre.Comprobante.MetodoPago = Obj.ClaveMetodoPagoSAT
Timbre.Comprobante.Subtotal = Obj.SubTotal
Timbre.Comprobante.Descuentos = Obj.Descuento
Timbre.Comprobante.Moneda = Obj.MonedaSAT
Timbre.Comprobante.TipoCambio = If(Obj.CveMoneda = 1, "1", Obj.TipoCambio.ToString)
Timbre.Comprobante.Total = Obj.Total
Try
Obj.SetSubProyecto(Me)
Timbre.Comprobante.LugarExpedicion = Obj.SubProyecto.CP
Catch ex As Exception
End Try
Timbre.Comprobante.Confirmacion = ""
Timbre.Receptor.RFC = Obj.Cliente.RFC
Timbre.Receptor.Nombre = Obj.Cliente.Nombre
Timbre.Receptor.ResidenciaFiscal = ""
Timbre.Receptor.NumeroRegistroTributario = ""
Timbre.Receptor.UsoCFDI = Obj.ClaveUsoCFDI
If Obj.CveTipoRelacion > 0 Then
Select Case Obj.CveTipoRelacion
Case 1
Timbre.CFDIRelacionados.TipoRelacion = "01"
Timbre.CFDIRelacionados.TipoRelacionTexto = "01-Nota de Crédito aplicada a Ingreso"
Case 2
Timbre.CFDIRelacionados.TipoRelacion = "02"
Timbre.CFDIRelacionados.TipoRelacionTexto = "02-Nota de débito de los documentos relacionados"
Case 3
Timbre.CFDIRelacionados.TipoRelacion = "03"
Timbre.CFDIRelacionados.TipoRelacionTexto = "03-Devolución aplicada a Ingreso"
Case 4
Timbre.CFDIRelacionados.TipoRelacion = "04"
Timbre.CFDIRelacionados.TipoRelacionTexto = "04-Refacturación de Ingreso"
Case 7
Timbre.CFDIRelacionados.TipoRelacion = "07"
Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo"
Case 8
Timbre.CFDIRelacionados.TipoRelacion = "08"
Timbre.CFDIRelacionados.TipoRelacionTexto = "08-Factura generada por pagos en parcialidades "
Case 9
Timbre.CFDIRelacionados.TipoRelacion = "09"
Timbre.CFDIRelacionados.TipoRelacionTexto = "09-Factura generada por pagos diferidos"
End Select
Timbre.CFDIRelacionados.UUID.Add(HdnFolioFiscalNC.Value)
End If
Dim totSubTotal As Decimal = Obj.SubTotal
Dim totIVA As Decimal = Obj.IVA
Dim totRetIVA As Decimal = Obj.RetIVA
Dim totRetISR As Decimal = Obj.RetISR
Dim TasaRetIVA As Decimal = LblRetIVA.Text.ToDecimal / 100
Dim TasaRetISR As Decimal = LblRetISR.Text.ToDecimal / 100
Dim i As Integer = 1
'detalles
Dim tPS As String = ""
For Each drr As DataRow In Obj.DtDetalle.Rows
If drr("PS").ToString.Length = 1 Then
tPS = drr("Obs").ToString
Else
If drr("PS").ToString.Length = 0 Then
tPS = ""
Else
tPS = String.Format("{0} {1}", drr("PS"), drr("Obs"))
End If
End If
'condicionante, especial
If UsuarioActual.CveEmpresa = 15 Then drr("UM") = "" ' les comentan que no debe de ir la etiqueta de "unidad" en el producto
Dim concepto As New CFDIConceptos With {.Cantidad = drr("Cantidad").ToString.ToDecimal,
.Descripcion = tPS,
.ValorUnitario = drr("PU").ToString.ToDecimal,
.Importe = drr("TotalImporte").ToString.ToDecimal,
.Descuento = drr("Descuento").ToString.ToDecimal,
.Unidad = drr("UM").ToString,
.ClaveUnidad = drr("SATClaveUM").ToString,
.ClaveProdServ = drr("SATClaveProdServ").ToString,
.Noidentificacion = drr("Noidentificacion").ToString,
.CuentaPredial = drr("CuentaPredial").ToString}
'verifica suma subtotales
If i = Obj.DtDetalle.Rows.Count AndAlso totSubTotal <> concepto.Importe Then 'proceso de ajusta de decimales
concepto.Importe = totSubTotal
End If
totSubTotal = totSubTotal - concepto.Importe
'siempre estaremos agregando el iva, auqnue sea en importe cero o tasa cero, para que se emita la factura
' If drr("ImporteIVA").ToString.ToDouble > 0 Then
'si es ingreso amortizado por la totalidad, y arroja el valor total de cero, no debe de impuestos
If Timbre.Comprobante.Total > 0 Then
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteIVA").ToString.ToDecimal})
End If
If drr("ImporteIEPS").ToString.ToDouble > 0 Then
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIEPS").ToString.ToDecimal, .Impuesto = "003", .Importe = drr("ImporteIEPS").ToString.ToDecimal})
End If
If drr("ImporteRetIVA").ToString.ToDouble > 0 Then 'si hay retenciones
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetIVA, .Impuesto = "002", .Importe = drr("ImporteRetIVA").ToString.ToDecimal})
End If
If drr("ImporteRetISR").ToString.ToDouble > 0 Then 'retención de ISR
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = TasaRetISR, .Impuesto = "001", .Importe = drr("ImporteRetISR").ToString.ToDecimal})
End If
Timbre.Conceptos.Add(concepto)
i += 1
Next
Return Timbre
End Function
Private Sub PrepararTimbrado(ByRef FM As Modelos.FemsaFactura, ByRef TmpDT7Eleven As DataTable, ByRef TmpDTComplementosTimbrado As DataTable)
FM.AplicaFEMSA = AplicaFEMSA
FM.FEMSA_NumSociedad = ""
FM.FEMSA_NumProveedor = ""
FM.FEMSA_Mail = ""
FM.FEMSA_Version = "".ToEntero
FM.FEMSA_NumPedido = "".ToEntero
FM.FEMSA_NumEntrada = ""
FM.FEMSA_NumRemision = ""
FM.FEMSA_NumSocio = ""
FM.FEMSA_CentroCosto = ""
FM.FEMSA_IPeriodoLiquidacion = ""
FM.FEMSA_FPeriodoLiquidacion = ""
FM.FEMSA_CodRetencion1 = ""
FM.FEMSA_CodRetencion2 = ""
TmpDT7Eleven.Columns.Add("sevenElevenNumProveedor")
TmpDT7Eleven.Columns.Add("sevenElevenFolio")
TmpDT7Eleven.Columns.Add("sevenElevenTienda")
TmpDT7Eleven.Columns.Add("sevenElevenFecha")
Dim Row As DataRow = TmpDT7Eleven.NewRow
Row("sevenElevenNumProveedor") = ""
Row("sevenElevenFolio") = ""
Row("sevenElevenTienda") = ""
Row("sevenElevenFecha") = ""
TmpDT7Eleven.Rows.Add(Row)
TmpDTComplementosTimbrado.Columns.Add("CveComplemento")
TmpDTComplementosTimbrado.Columns.Add("IdContabilidad")
TmpDTComplementosTimbrado.Columns.Add("TipoProceso")
TmpDTComplementosTimbrado.Columns.Add("TipoAmbito")
TmpDTComplementosTimbrado.Columns.Add("Entidad")
Dim Row2 As DataRow = TmpDTComplementosTimbrado.NewRow
Row2("CveComplemento") = RblComplementos.SelectedValue.ToEntero
Row2("IdContabilidad") = TxtIdConta.Text.ToEntero
Row2("TipoProceso") = DdlTipoCampaña.SelectedValue
Row2("TipoAmbito") = DdlAmbitoComplemento.SelectedValue
Row2("Entidad") = DdlINEEntidad.SelectedValue
TmpDTComplementosTimbrado.Rows.Add(Row2)
End Sub
#End Region
#Region "SELECTED INDEX CHANGE"
Protected Sub DdlFacturas_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaPSAjuste()
End Sub
Private Sub DdlPSIndexChange(CvePSParametro As Integer, Ddl As ADServerControl.Dropdownlost)
If Not CveCliente > 0 Then
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")")
Exit Sub
End If
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)
'SUGIERE PRECIO
Dim PrecioSugerido = 0.0
PrecioSugerido = drPS("Precio").ToString.ToDouble
If UsuarioActual.CveEmpresa.Contiene(80, 119) Then
Dim CvePrecioListaPS = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltroPrimeroValor("CvePrecioLista", $"CveCliente = {CveCliente}").ToEntero
If CvePrecioListaPS > 0 Then
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, CvePrecioListaPS, CvePS:=CvePSParametro) Then
PrecioSugerido = ObjPS.DtResultados.FiltroPrimeroValor("PrecioLista").ToDouble
If PrecioSugerido = 0 Then
Dim ObjInventarios As New ClsInventarios
Dim CostoPS = ObjInventarios.GetCostoPS(CvePSParametro, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero)
ObjInventarios.Dispose()
Dim PorcentajePrecio = ObjPS.DtResultados.FiltroPrimeroValor("Porcentaje").ToDouble
If CostoPS > 0 And PorcentajePrecio > 0 Then
PrecioSugerido = ((PorcentajePrecio / 100) + 1) * CostoPS
End If
End If
ObjPS.Dispose()
End If
End If
End If
If PrecioSugerido > 0 Then
TxtPrecio.Text = PrecioSugerido.FormatoNumero()
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.")
End If
End If
End If
ElseIf CvePSParametro = -2 Then
CargaPS(DdlClasificacion.SelectedValue.ToEntero, Ddl)
Else
DdlUnidadMedida.Items.Clear()
DdlUnidadMedida.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlUnidadMedida.SelectedValue = "-1"
DdlUnidadMedida.DataBind()
End If
UpClasificacion.Update()
UpPS.Update()
UpUnidadMedida.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 DdlSucursalCliente_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSucursalCliente.SelectedIndexChanged
CargaClienteSucursal(DdlSucursalCliente.SelectedValue.ToEntero)
End Sub
Private Sub DdlSubProyectoDatos_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlSubProyectoDatos.SelectedIndexChanged
CambiaSucursalGeneral()
End Sub
Private Sub CambiaSucursalGeneral()
Dim ObjSubProyectos As New ClsSubProyectos
If ObjSubProyectos.GetSubProyectos() Then
DTSucursal = ObjSubProyectos.DtResultados.FiltraParametros(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue.ToEntero))
CambiaSucursal()
End If
ObjSubProyectos.Dispose()
End Sub
Protected Sub DdlTipoComprobante_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlTipoComprobante.SelectedIndexChanged
CambiaTipoComprobante()
End Sub
Private Sub CambiaTipoComprobante()
CambiaTipoDocto()
LimpiaEscondeContado()
End Sub
Private Sub CambiaTipoDocto()
ConfiguraTipoDocto()
CargaFolios()
UpEstatus.Update()
'REINICIALIZA VALORES DE ENTREGA POR ADELANTADO
RequiereAlmacenDestino = False
TrAlmacenAsignado.Visible = False
TrDireccion.Visible = True
TrCiudad.Visible = True
TrRFC.Visible = True
RBLPago.Enabled = True
If DdlTipoComprobante.SelectedValue.Contiene("Ing") Then
ChkEnviarFactura.Checked = EnviarCorreoCliente
ChkEnviarFactura.Visible = True
LblEnviarMail.Visible = True
ObtenerFechaVencimientoCER()
End If
If DdlTipoComprobante.SelectedValue.Contiene("Ing") AndAlso (ReceptorRFC = "XAXX010101000" Or LblRFC.Text = "XAXX010101000") Then
TrDireccion.Visible = False
TrCiudad.Visible = False
TrRFC.Visible = False
tdTelefonoGen.Visible = True
tdTxtTelefonoGen.Visible = True
Else
TxtAtencionA.Text = ""
TxtTelefonoGenerico.Text = ""
End If
TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString
TabAlmacen.Enabled = DdlTipoComprobante.SelectedValue <> "Ant"
'VALIDA ESTATUS CLIENTE - SOLO SE PUEDE USAR EL CLIENTE PARA COTIZAR EN CASO DE ESTAR INACTIVO
If LblCliente.Text <> "Cliente" And Not EstatusCliente Then
Alert("El Cliente seleccionado no esta activo", TipoMensaje.MsgAdvertencia)
End If
BtnEmitirImprimir.Visible = EstatusCliente
If DdlTipoComprobante.SelectedValue = "Cot" Then TrAtencionA.Visible = True
tdVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
tdFechaVigencia.Visible = DdlTipoComprobante.SelectedValue.Contiene("Cot")
Updatetabs.Update()
UPCondicionesPago.Update()
UpCliente.Update()
UpPS.Update()
End Sub
Protected Sub DdlClasificacion_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DdlClasificacion.SelectedIndexChanged
CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS)
UpPS.Update()
End Sub
Private Sub DdlMetodoPago33_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMetodoPago33.SelectedIndexChanged
CambiaMetodoPago33()
End Sub
Private Sub CambiaMetodoPago33()
If UsuarioActual.CveEmpresa = 119 Then
CargaFormaPago(DdlMetodoPago33.SelectedValue.ToEntero)
Else
CargaFormaPago(-1)
End If
End Sub
#End Region
#Region "DATATABLES"
Private Sub CreaDTVentas()
TmpDT = New DataTable
TmpDT.Columns.Add("CveVenta", GetType(Integer))
TmpDT.Columns.Add("Consec", GetType(Integer))
TmpDT.Columns.Add("Cantidad", GetType(Decimal))
TmpDT.Columns.Add("Codigo", GetType(String))
TmpDT.Columns.Add("CveUM", GetType(Integer))
TmpDT.Columns.Add("UM", GetType(String))
TmpDT.Columns.Add("SATClaveUM", GetType(String))
TmpDT.Columns.Add("CveClasificacion", GetType(Integer))
TmpDT.Columns.Add("Clasificacion", GetType(String))
TmpDT.Columns.Add("CvePS", GetType(Integer))
TmpDT.Columns.Add("PS", GetType(String))
TmpDT.Columns.Add("CodigoPS", GetType(String))
TmpDT.Columns.Add("SATClaveProdServ", GetType(String))
TmpDT.Columns.Add("NoIdentificacion", GetType(String))
TmpDT.Columns.Add("CveTipoPS", GetType(Integer))
TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer))
TmpDT.Columns.Add("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))
TmpDT.Columns.Add("EsCargo", GetType(Boolean))
End Sub
Private Sub CreaDTmpC()
DTmpC = New DataTable
DTmpC.Columns.Add("Descripcion", GetType(String))
End Sub
Private Sub CreaDTmpF()
DTmpF = New DataTable
DTmpF.Columns.Add("CveVenta", GetType(Integer))
DTmpF.Columns.Add("Titulo", GetType(String))
DTmpF.Columns.Add("Nombre", GetType(String))
DTmpF.Columns.Add("Puesto", GetType(String))
DTmpF.Columns.Add("Lado", GetType(Integer))
End Sub
#End Region
#Region "ADD PS"
Private Sub AddPS(Cantidad As Double, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String,
PU As Double, IVA As Double, RetIVA As Double, Descuento As Double, AsientoContableVentas As Integer, IdCtaContable As Integer, AplicaParaConcepto As Boolean,
Codigo As String, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, Optional CveTipoPS As Integer = -1, Optional SerieLote As String = "",
Optional CveContratoDetalle As Integer = -1, Optional TiempoEntrega As String = "", Optional CodigoPS As String = "")
If Not CvePS > 0 Then
Alert("Uno de los productos no existe. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgError)
Exit Sub
End If
Dim CveTipoInv = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimeroValor("Inv_CveMetodoInventario").ToEntero
If Cantidad <> 1 And CveTipoInv = 5 AndAlso UsuarioActual.CveEmpresa <> 72 Then
Alert("El producto se tiene que dar salida por serie y producto por producto (Cantidad = 1).", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If TmpDT.FiltraParametros("AsientoContableVentas <> '" & AsientoContableVentas.ToString & "'").Rows.Count = 0 Then
Dim Row As DataRow = Nothing
Row = TmpDT.NewRow()
Row("Codigo") = Codigo
Row("Consec") = TmpDT.Rows.Count + 1
ConsecutivoVenta = TmpDT.Rows.Count + 1
Row("Cantidad") = Cantidad
Row("CveUM") = CveUM
Row("UM") = UM
Row("CveClasificacion") = CveClasificacion
Row("Clasificacion") = Clasificacion
Row("CvePS") = CvePS
Row("PS") = PS
Row("CodigoPS") = CodigoPS
Row("CveTipoPS") = CveTipoPS
Row("CveTipoInvPS") = CveTipoInv
Row("Obs") = Obs
Row("PU") = PU
Row("IVA") = IVA
Row("RetIVA") = RetIVA
Row("IEPS") = If(HdnAplicaIEPS.Value = "True", (Cantidad * PU) * HdnPorcentajeIEPS.Value.ToDecimal, 0)
Row("Descuento") = Descuento
Row("TipoDescuento") = HdnTipoDescuento.Value
Row("Total") = (Cantidad * PU)
Row("AsientoContableVentas") = AsientoContableVentas
Row("IdCtaContVentas") = IdCtaContable
Row("AplicaParaConcepto") = AplicaParaConcepto
Row("CveProyecto") = CveProyecto
Row("Proyecto") = Proyecto
Row("CveSubProyecto") = CveSubProyecto
Row("SubProyecto") = SubProyecto
Row("SerieLote") = SerieLote
Row("TiempoEntrega") = TiempoEntrega
TmpDT.Rows.Add(Row)
GvPS.DataSource = TmpDT
GvPS.DataBind()
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
GvInv.DataSource = TmpDT.FiltraParametros("CveTipoPS=2")
GvInv.DataBind()
UpINV.Update()
TxtSubTotal.Text = (TxtSubTotal.Text.Replace(",", "").ToDouble + (Cantidad * PU)).FormatoNumero(2)
TxtIEPS.Text = (TxtIEPS.Text.Replace(",", "").ToDouble + (Cantidad * PU) * If(HdnPorcentajeIEPS.Value.ToDecimal = -1, 0.0D, HdnPorcentajeIEPS.Value.ToDecimal)).FormatoNumero(2)
If TxtIEPS.Text.ToDouble > 0 Then : TrIEPS.Visible = True : End If
If HdnTipoDescuento.Value = "0" Then
LblDescuentos.Text = (LblDescuentos.Text.Trim.Replace(",", "").ToDouble + (Descuento * Cantidad)).FormatoNumero(2)
TxtIVA.Text = (Math.Round(TxtIVA.Text.Replace(",", "").ToDouble, 2) + Math.Round(((Cantidad * (PU - Descuento)) * IVA), 2)).FormatoNumero(2)
HdnIVAOriginal.Value = TxtIVA.Text
ElseIf HdnTipoDescuento.Value = "1" Then
LblDescuentos.Text = (LblDescuentos.Text.Trim.Replace(",", "").ToDouble + Descuento).FormatoNumero(2)
TxtIVA.Text = (Math.Round(TxtIVA.Text.Replace(",", "").ToDouble, 2) + Math.Round(((Cantidad * PU - Descuento) * IVA), 2)).FormatoNumero(2)
HdnIVAOriginal.Value = TxtIVA.Text
ElseIf HdnTipoDescuento.Value = "-1" Then
LblDescuentos.Text = (LblDescuentos.Text.Trim.Replace(",", "").ToDouble).FormatoNumero(2)
TxtIVA.Text = (Math.Round(TxtIVA.Text.Replace(",", "").ToDouble, 2) + Math.Round(((Cantidad * PU) * IVA), 2)).FormatoNumero(2)
HdnIVAOriginal.Value = TxtIVA.Text
End If
If CBool(ViewState("RetIVAFletes")) AndAlso RetIVA > 0 Then
TxtRetIVA.Text = (TxtRetIVA.Text.Replace(",", "").ToDouble + ((Cantidad * PU)) * RetIVA).FormatoNumero(2)
UpPS.Update()
CalculaTotalesVenta(False)
Else
CalculaTotalesVenta(True)
End If
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
'CVImporteContado.ValueToCompare = TxtTotal.Text.Replace(",", "")
UpContado.Update()
Else
Alert("No se puede hacer una factura que contenga conceptos de Venta y Anticipo. <br />Por favor separa una Factura de Venta de una Factura de Anticipos.", TipoMensaje.MsgAdvertencia)
End If
End Sub
Private Sub LimpiaAgregar()
TxtCantidad.Text = "1"
HdnPS.Value = "-1"
HdnCodigoPS.Value = "-1"
HdnTipoPS.Value = "-1"
HdnTipoInv.Value = "-1"
DdlClasificacion.SelectedIndex = 0
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPS.SelectedValue = "-1"
Else
DdlPS.SelectedValue = "-1"
DdlPS.SelectedText = "Seleccione"
End If
DdlUnidadMedida.Items.Clear()
DdlUnidadMedida.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlUnidadMedida.SelectedValue = "-1"
DdlUnidadMedida.DataBind()
TxtObsPS.Text = ""
TxtPrecio.Text = ""
LblTotalPS.Text = "0.00"
HdnIVAPS.Value = "-1"
HdnIVARetAPS.Value = "-1"
HdnAplicaIEPS.Value = "False"
HdnPorcentajeIEPS.Value = "0"
HdnAsientoContable.Value = "-1"
HdnCtaContable.Value = "-1"
HdnAplicaParaConcepto.Value = "False"
HdnCodigo.Value = "-1"
' codigo comentado RMF. 2016.06.13, esto paa que respete el que tenga selecionado e nla sucursal
'DdlProyecto.SelectedIndex = 0
'DdlSubProyecto.Items.Clear()
'DdlSubProyecto.Items.Insert(0, New ListItem("Sin SubProyecto Asignado", "-1"))
TxtCantidad.Focus()
'Limpia descuentos
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
LblPrecio1.Text = "0.00"
LblTotalPS1.Text = "0.00"
TxtPorDescP.Text = "0"
TxtDescP.Text = "0"
LblDescuento.Text = "0.00"
LblPrecioFinal.Text = "0.00"
'CODIGO BARRAS
'TxtCodigoBarras.Text = ""
'TxtCodigoSerie.Text = ""
'FOCUS DEPENDIENDO MODALIDAD DE CODIGO BARRAS
'If DIVCod.Visible Then
' TxtCodigoBarras.Focus()
'Else
TxtCantidad.Focus()
'End If
ChkAgregar.Checked = True
LimpiaAjuste()
UPPDescuento.Update()
UpINV.Update()
UpClasificacion.Update()
End Sub
Private Function AgregarProductoServicio(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String,
PU As Decimal, Descuento As Decimal,
CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String,
Optional 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 EsCargo 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.MsgAdvertencia)
Return False
End If
If (Obs.Length + PS.Length > 1000) Then
Alert(String.Format("El Nombre y observación del producto tiene longitud de {0} caracteres y excede los 1000 caracteres permitidos.", Obs.Length + PS.Length), TipoMensaje.MsgAdvertencia)
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 rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return False
End If
End If
End If
End If
If Modalidad = "A" Then
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.MsgAdvertencia)
Return False
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")
Row("Consec") = TmpDT.Rows.Count + 1
If Not EsCargo Then
ConsecutivoVenta = 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") = SubProyectoPorcentajeIVA
Else
Row("PorcentajeIVA") = DrPS("IVA")
End If
Row("IVA") = Row("PorcentajeIVA")
Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
Row("PorcentajeRetIVA") = ClienteRetIVA
Row("PorcentajeRetISR") = ClienteRetISR
Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje")
Row("ImporteIEPS") = Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Row("IEPS") = Row("ImporteIEPS")
Row("Descuento") = Math.Round(Descuento, NumeroDecimales)
Row("TipoDescuento") = HdnTipoDescuento.Value
Row("Total") = (Cantidad * PU)
Row("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales)
'Row("AsientoContableVentas") = DrPS("AsientoContableVentas")
' Row("IdCtaContVentas") = IdCtaContable
' Row("AplicaParaConcepto") = AplicaParaConcepto
Row("SATClaveProdServ") = DrPS("SATClavePS")
Row("SATClaveUM") = DrPS("SATClaveUnidadMedida")
Row("EntregaDirecta") = EntregaDirecta
'Contratos
Row("CveContratoDetalle") = CveContratoDetalle
Row("CveVentaDetalle") = CveVentaDetalle
Row("CveMovimientoDetallePedido") = CveVentaDetalle
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
Row("CveVentaDetalleRemision") = CveVentaDetalleRemision
Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion
Row("CveVentaDetallePedido2") = CveVentaDetallePedido2
Row("CuentaPredial") = CuentaPredial
Row("EsCargo") = EsCargo
If 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)
ElseIf Modalidad = "U" Then
Dim TotalCalculableImpuestos As Decimal = 0
PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos
Dim Contador As Integer = 0
For Each Dr As DataRow In TmpDT.Rows
If Dr("Consec").ToString.ToEntero = Index Then
Exit For
End If
Contador = Contador + 1
Next
Dim Row As DataRow = TmpDT.Rows(Contador)
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.MsgAdvertencia)
Return False
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 Not EsCargo Then
ConsecutivoVenta = Row("Consec").ToString.ToEntero
End If
Row("PS") = DrPS("PS")
Row("CodigoPS") = DrPS("PSCodigo").ToString
Row("CveTipoPS") = DrPS("CveTipoPS")
Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario")
Row("CveTamaño") = DrPS("CveTamaño")
If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion")
If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion")
If DrPS("IVA").ToString.Contiene("-1", "") Then
Row("PorcentajeIVA") = SubProyectoPorcentajeIVA
Else
Row("PorcentajeIVA") = DrPS("IVA")
End If
Row("IVA") = Row("PorcentajeIVA")
Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
Row("PorcentajeRetIVA") = ClienteRetIVA
Row("PorcentajeRetISR") = ClienteRetISR
Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje")
Row("ImporteIEPS") = Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Row("IEPS") = Row("ImporteIEPS")
Row("Descuento") = Math.Round(Descuento, NumeroDecimales)
Row("TipoDescuento") = HdnTipoDescuento.Value
Row("Total") = (Cantidad * PU)
Row("TotalImporte") = Math.Round(Cantidad * PU, NumeroDecimales)
'Row("AsientoContableVentas") = DrPS("AsientoContableVentas")
' Row("IdCtaContVentas") = IdCtaContable
' Row("AplicaParaConcepto") = AplicaParaConcepto
Row("SATClaveProdServ") = DrPS("SATClavePS")
Row("SATClaveUM") = DrPS("SATClaveUnidadMedida")
Row("EntregaDirecta") = EntregaDirecta
'Contratos
Row("CveContratoDetalle") = CveContratoDetalle
Row("CveVentaDetalle") = CveVentaDetalle
Row("CveMovimientoDetallePedido") = CveVentaDetalle
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
Row("CveVentaDetalleRemision") = CveVentaDetalleRemision
Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion
Row("CveVentaDetallePedido2") = CveVentaDetallePedido2
Row("CuentaPredial") = CuentaPredial
Row("EsCargo") = EsCargo
If 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
End If
TmpDT.AcceptChanges()
Retorno = True
Return Retorno
End Function
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
If CveCliente <= 0 Then
Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact&TipoCliente=2', 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 Not UsuarioActual.TienePermisoProceso(169) Then ' NO VALIDA EXISTENCIAS NI COSTO - PERMISO PARA NO VALIDAR
'SOLO VALIDA EXISTENCIAS Y COSTO: SI USA INVENTARIOS, SOLO PRODUCTOS TIPO PRODUCTO, SOLO REMISIONES E INGRESOS
If UsuarioActual.Empresa.UsaInventarios AndAlso CveTipoPS = 2 AndAlso (DdlTipoComprobante.SelectedValue.Contiene("Rem", "Ing", "PA") Or (DdlTipoComprobante.SelectedValue.Contiene("Cot") And UsuarioActual.CveEmpresa.Contiene(119, 140))) Then
Dim ObjInventarios As New ClsInventarios
Dim Existencia As Decimal = ObjInventarios.GetExistenciasPS(CvePS, CveUM, UsuarioActual.CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveVendedor:=DdlVendedor.SelectedValue.ToEntero, CveCliente:=If(UsuarioActual.Empresa.Funcionalidad(146) = "1", -1, CveCliente), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1)
Dim Costo As Decimal = ObjInventarios.GetCostoPS(CvePS, TxtCantidad.Text.Trim.ToDouble, -1, "-1", TxtFecha.Text.ToDate, DdlSubProyectoDatos.SelectedValue.ToEntero)
ObjInventarios.Dispose()
Dim PrecioMinimo As Decimal = 0
'RMF. condicion temporal, para reubicación, precio mínimo
If UsuarioActual.CveEmpresa = 119 Then
'Dim CvePrecioLista As Integer = 38
Dim objPS As New ClsProductosServicios
If objPS.GetPSSucursalesALL(CvePS, UsuarioActual.CveEmpresa, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then
PrecioMinimo = objPS.DtResultados.FiltroPrimeroValor("PrecioMinimo", "").ToDecimal
If PrecioMinimo > 0 Then
Costo = PrecioMinimo
End If
End If
objPS.Dispose()
End If
If DdlTipoComprobante.SelectedValue <> "Cot" Then
'VALIDA EXISTENCIA
If UsuarioActual.CveEmpresa.Contiene({1, 72, 80, 119, 140}) Then
If Existencia - TmpDT.SUM("Cantidad", $"CvePS = {CvePS}") < TxtCantidad.Text.ToDouble Then
Alert("No cuenta con la cantidad suficiente en inventario. Cuenta con " + Existencia.FormatoNumero(2) + ".", TipoMensaje.MsgAdvertencia)
Return False
End If
End If
End If
'VALIDA COSTOS
If Not CveContrato > 0 Then
'BANDERAS PARA VALIDACIONES
Dim EsValido = False
Dim EsValidoMayor = False
Dim CostoMenor = 0.0D
Dim CostoMayor = 0.0D
'PRECIO MINIMO
If UsuarioActual.Empresa.Funcionalidad(129).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
CostoMenor = Costo + ((UsuarioActual.Empresa.Funcionalidad(129).ToDecimal / 100) * Costo)
If PrecioMinimo > 0 Then CostoMenor = PrecioMinimo
'SI EL PRECIO ES MAYOR AL COSTO, SI PASA
If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= CostoMenor Then
EsValido = True
End If
Else
EsValido = True
End If
'PRECIO MAXIMO
If UsuarioActual.Empresa.Funcionalidad(133).ToEntero > 0 AndAlso UsuarioActual.CveUsuario <> 1560 Then
CostoMayor = Costo + ((UsuarioActual.Empresa.Funcionalidad(133).ToDecimal / 100) * Costo)
'SI EL PRECIO ES MAYOR AL COSTO MAXIMO, SI PASA
If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) <= CostoMayor Then
EsValidoMayor = True
End If
Else
EsValidoMayor = True
End If
'VALIDA PROMOCION: SI TIENE PROMOCION Y EL PRECIO ES MENOR AL PRECIO DE PROMOCION, NO PASA | SI YA CUMPLE NO VUELVE A VALIDAR
'SIRVE PARA VALIDAR PRECIOS DEBAJO DEL PRECIO MINIMO PERMITIDO
If Not EsValido Then
If DtPromociones.FiltraParametros($"CvePS = {CvePS}").Rows.Count > 0 Then
If PU * If(DdlMoneda.SelectedValue.ToEntero = 1, 1, TxtTipoCambio.Text.ToDecimal) >= DtPromociones.FiltroPrimeroValor("PUPromocion", $"CvePS = {CvePS}").ToDecimal Then
EsValido = True
End If
End If
End If
'NO DEJA REGISTRAR MENOS AL PRECIO MINIMO
Dim MensajeCosto As New StringBuilder
Dim TienePermisoImportes As Boolean = UsuarioActual.TienePermisoProceso(201)
If Not EsValido Then
MensajeCosto.AppendFormat("El Producto <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
If ChkAjuste.Checked Then
If TxtFechaAjuste.Text.ToDate > Now Then
Alert("La fecha de compra no puede ser mayor a la de hoy.", TipoMensaje.MsgAdvertencia)
Return False
End If
End If
Return True
End Function
Protected Sub LbAgregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbAgregar.Click
If Not CveCliente > 0 Then RegistraScript("javascript:AbrirVentana('/Ventas/PopUpBuscarClientes.aspx?Opt=Fact&TipoCliente=2', 800, 547, 'N', 'PopUpBuscar')") : Exit Sub
CargaAgregar()
End Sub
Private Sub CargaAgregar()
Modalidad = "A"
LnkAgregarPS.Text = "Agregar"
LimpiaAgregar()
LimpiaAjuste()
ModalidadAjuste = "A"
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
ConsecutivoVenta = GvRow.DataKey("Consec").ToEntero
LnkAgregarPS.Text = "Actualizar"
DdlClasificacion.SelectedValueExist(GvRow.DataKey("CveClasificacion"))
CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS)
UpClasificacion.Update()
If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPS.SelectedValue = GvRow.DataKey("CvePS")
Else
DdlPS.SelectedValue = GvRow.DataKey("CvePS")
DdlPS.SelectedText = GvRow.DataKey("PS")
End If
DdlPSIndexChange(DdlPS.SelectedValue.ToEntero, DdlPS)
DdlUnidadMedida.SelectedValueExist(GvRow.DataKey("CveUM"))
TxtCantidad.Text = GvRow.DataKey("Cantidad")
TxtObsPS.Text = GvRow.DataKey("Obs")
TxtPrecio.Text = GvRow.DataKey("PU")
LblTotalPS.Text = GvRow.DataKey("Total")
ChkAgregar.Checked = False
divagregrarotrops.Visible = False
Ajuste()
UpVenta.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta"), "EdicionVenta")
End Sub
Protected Sub LnkAgregarPS_Click(sender As Object, e As EventArgs)
If AgregarPS() Then
If ChkAjuste.Checked Then GuardaAjuste()
CalculaTotalesVenta()
If ChkAgregar.Checked = True And Modalidad = "A" Then
LimpiaAgregar()
UpVenta.Update()
Else
RegistraScript("$('#DivAddVenta').modal('hide');")
End If
End If
End Sub
Private Function AgregarPS() As Boolean
'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
Dim CveProyecto As Integer = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0)("CveProyecto").ToString.ToEntero
Dim Proyecto As String = GlobalDTSubProyectos(-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0)("Proyecto").ToString
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,
CveProyecto, Proyecto, DdlSubProyectoDatos.SelectedValue.ToEntero, DdlSubProyectoDatos.SelectedItem.Text,
SerieLote:="", TiempoEntrega:="", CuentaPredial:="", RegeneraIEPS:=ClienteDesglosaIEPS)
CalculaUsados()
Return True
Else
Return False
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 Function
#End Region
#Region " DESCUENTOS "
Private Sub AplicarDescuentos()
If TxtSubTotal.Text.ToDecimal <= 0 Then
Alert("Para aplicar un descuento, el SubTotal debe ser mayor a cero.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim Total = 0.0D
Dim Descuento As Decimal = HdnDescuento.Value.ToDecimal
Dim Porcentaje As Decimal = Descuento / TmpDT.SUMD("Total")
Dim LastDr As DataRow = Nothing
For Each Dr As DataRow In TmpDT.Rows
Descuento = Dr("Total").ToString.ToDecimal * Porcentaje
Dr("Descuento") = Math.Round(Descuento, NumeroDecimales)
Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (Dr("PU").ToString.ToDecimal)) - Dr("Descuento").ToString.ToDecimal
Dr("ImporteIVA") = Math.Round(Dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
Dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
Dr("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Dr("IEPS") = Dr("ImporteIEPS")
LastDr = Dr
Next
If Not IsNothing(LastDr) Then
Dim Fdes As Decimal = Descuento - TmpDT.SUMD("Descuento").ToString.ToDecimal
If Fdes > 0 Then
LastDr("Descuento") = LastDr("Descuento").ToString.ToDecimal + Fdes
End If
End If
TmpDT.AcceptChanges()
End Sub
Protected Sub BtnAplicarDescG_Click(sender As Object, e As System.EventArgs) Handles BtnAplicarDescG.Click
If HdnTipoDescuento.Value = "2" Then
If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then
Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2)
Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble
If IVAPromedio <> IVA Then
Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError)
Else
AplicarDescuentos()
'Dim Descuento As Double = HdnDescuento.Value.Trim.Replace(",", "").ToDouble
CalculaTotalesVenta()
'LblDescuentos.Text = Descuento.FormatoNumero(2)
'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Descuento - LblAmortizacion.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2)
'HdnIVAOriginal.Value = TxtIVA.Text
'CalculaTotales(True)
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
RegistraScript("BorraDescuentos();")
End If
End If
UpPS.Update()
ElseIf HdnTipoDescuento.Value = "3" Then
If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then
Dim IVAPromedio As Double = Math.Round(TmpDT.SUM("IVA") / TmpDT.COUNT("Consec"), 2)
Dim IVA As Double = TmpDT.Rows(0)("IVA").ToString.ToDouble
If IVAPromedio <> IVA Then
Alert("No se puede aplicar descuento general a la factura ya tiene conceptos con diferente tasa de IVA", TipoMensaje.MsgError)
Else
AplicarDescuentos()
'Dim Amortizacion As Decimal = HdnDescuento.Value.Trim.Replace(",", "").ToDecimal
'LblAmortizacion.Text = Amortizacion.FormatoNumero(2)
'TxtIVA.Text = ((TxtSubTotal.Text.Trim.Replace(",", "").ToDouble - Amortizacion - LblDescuentos.Text.Trim.Replace(",", "").ToDouble) * IVAPromedio).FormatoNumero(2)
'HdnIVAOriginal.Value = TxtIVA.Text
'CalculaTotales(True)
CalculaTotalesVenta()
HdnTipoDescuento.Value = "-1"
HdnDescuento.Value = "0"
RegistraScript("BorraDescuentos();")
End If
End If
UpPS.Update()
End If
RegistraScript("$('#ModalDescuento').modal('hide')", "hidemodal")
End Sub
Private Sub BtnAplicarOtrosConceptos_Click(sender As Object, e As EventArgs) Handles BtnAplicarOtrosConceptos.Click
TotalOtrosConceptos = 0
For Each row As GridViewRow In GVOtrosConceptos.Rows
TotalOtrosConceptos += row.FCTextBox("TxtCantidadConcepto").Text.ToDecimal
Next
RegistraScript("$('#ModalOtrosConceptos').modal('hide')", "hidemodal")
End Sub
Private Sub BtnAplicarComplementos_Click(sender As Object, e As EventArgs) Handles AplicarComplementosTimbrado.Click
LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs green"
UpPS.Update()
RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal")
End Sub
Private Sub BtnCancelarComplementos_Click(sender As Object, e As EventArgs) Handles CancelarComplementosTimbrado.Click
trEntidad.Visible = False
trContaComplementos.Visible = False
trAmbito.Visible = False
trTipoCampaña.Visible = False
RblComplementos.SelectedIndex = -1
TxtIdConta.Text = ""
DdlTipoCampaña.SelectedIndex = -1
DdlAmbitoComplemento.SelectedIndex = -1
DdlINEEntidad.SelectedIndex = -1
LkbAgregarComplementos.CssClass = "btn btn-circle btn-xs gray"
UpComplementos.Update()
UpDatosComplementos.Update()
UpPS.Update()
RegistraScript("$('#ModalComplementos').modal('hide')", "hidemodal")
End Sub
#End Region
#Region "CALCULA TOTALES"
Private Sub CalculaTotalesVenta(Optional RecalculaImpuestosLocales As Boolean = True)
Dim TotalSubTotal As Decimal = TmpDT.SUM("TotalImporte").ToDecimal
Dim TotalDescuentos As Decimal = TmpDT.SUM("Descuento").ToDecimal
Dim TotalAmortizacion As Decimal = LblAmortizacion.Text.ToDecimal
Dim TotalIVA As Decimal = TmpDT.SUM("ImporteIVA").ToDecimal
Dim TotalIEPS As Decimal = TmpDT.SUM("ImporteIEPS").ToDecimal
Dim TotalRetIVA As Decimal = TmpDT.SUM("ImporteRetIVA").ToDecimal
Dim TotalRetISR As Decimal = TmpDT.SUM("ImporteRetISR").ToDecimal
Dim Total As Decimal = 0
Dim TotalImpuestosLocales As Decimal = 0
For Each gvr As GridViewRow In GvImpuestosLocales2.Rows
If gvr.RowType = DataControlRowType.DataRow Then
If gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal > 0 Then
If gvr.DataKey("TipoImpuesto") = "5" Then ' traslado de imp local
TotalImpuestosLocales -= gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal
Else
TotalImpuestosLocales += gvr.FCTextBox("TxtImpuestoLocalPS").Text.ToDecimal
End If
End If
End If
Next
'If TotalDescuentos > 0 Then GvPS.Columns(ColumnaDescuento).Visible = True : thEncDesc1.Visible = True : thEncDesc2.Visible = True Else GvPS.Columns(ColumnaDescuento).Visible = False : thEncDesc1.Visible = False : thEncDesc2.Visible = False
If TotalIEPS > 0 Then TrIEPS.Visible = True : GvPS.Columns(ColumnaIEPS).Visible = True : thEncIEPS1.Visible = True Else TrIEPS.Visible = False : GvPS.Columns(ColumnaIEPS).Visible = False : thEncIEPS1.Visible = False
If TotalRetIVA > 0 Then GvPS.Columns(ColumnaRetIVA).Visible = True Else GvPS.Columns(ColumnaRetIVA).Visible = False
If TotalRetISR > 0 Then GvPS.Columns(ColumnaRetISR).Visible = True Else GvPS.Columns(ColumnaRetISR).Visible = False
Total = (TotalSubTotal - TotalDescuentos - TotalAmortizacion + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR - TotalImpuestosLocales)
LblSubTotal1.Text = TotalSubTotal.FormatoNumero(2)
TxtSubTotal.Text = TotalSubTotal.FormatoNumero(2)
LblDescuentos.Text = TotalDescuentos.FormatoNumero
TxtSubTotal2.Text = (TotalSubTotal - TotalDescuentos - TotalAmortizacion).FormatoNumero(2)
TxtRetIVA.Text = TotalRetIVA.FormatoNumero(2)
TxtRetISR.Text = TotalRetISR.FormatoNumero(2)
TxtIVA.Text = TotalIVA.FormatoNumero
TxtIEPS.Text = TotalIEPS.FormatoNumero
TxtTotal.Text = Total.FormatoNumero
LblAmort.Text = TxtSubTotal.Text
If CveVenta <= 0 OrElse (CveDevolucion > 0 And NuevaFactura = 1) Then
HdnVentaSaldo.Value = Total.ToString
Else
HdnVentaSaldo.Value = SaldoVenta.ToString
End If
HdnIVAOriginal.Value = TxtIVA.Text
'JJMQ 20160506: Se agrego para la validacion de pago de contado.
'CVImporteContado.ValueToCompare = Total.ToString
Dim view As DataView = New DataView(TmpDT)
view.Sort = "Consec"
GvPS.DataSource = view
GvPS.DataBind()
'RECARGA GV INVENTARIO
DtInv = TmpDT.Copy.FiltraParametros("CveTipoPS = 2")
CargaGVInv(DtInv)
UpContado.Update()
UpPS.Update()
RegistraScript("BorraDescuentos();", "BorraDescuentos")
End Sub
#End Region
#Region " MANDA CORREO "
Private Sub MandaMails(CveVenta As Integer, EnviarFactura As Boolean, XML As String, PDF As String)
Dim ObjMail As New ClsSisMail()
Dim ObjVentas As New ClsVentas
Try
Dim Asunto As String = String.Empty
Dim Cuerpo As String = String.Empty
Dim ResultadoMail As Integer = 0
Dim TipoComprobante = ""
If DdlTipoComprobante.SelectedValue.ToString = "Ing" Then TipoComprobante = "Factura"
If DdlTipoComprobante.SelectedValue.ToString = "Egs" Then TipoComprobante = "Nota de Crédito"
If DdlTipoComprobante.SelectedValue.ToString = "Dev" Then TipoComprobante = "Nota de Devolución"
If DdlTipoComprobante.SelectedValue.ToString = "Rem" Then TipoComprobante = "Remisión"
If DdlTipoComprobante.SelectedValue.ToString = "Cot" Then TipoComprobante = "Cotización"
If DdlTipoComprobante.SelectedValue.ToString = "Ant" Then TipoComprobante = "Anticipo"
If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then
Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta
Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa)
Cuerpo = Cuerpo.Replace("{""NombreCliente""}", LtlCliente.Text.Trim)
Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante)
Cuerpo = Cuerpo.Replace("{""Fecha""}", TxtFecha.Text)
Cuerpo = Cuerpo.Replace("{""Total""}", TxtTotal.Text)
Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", TxtFechaPago.Text)
Cuerpo = Cuerpo.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}")
End If
If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then
Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta
Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante)
Asunto = Asunto.Replace("{""Sucursal""}", DdlSubProyectoDatos.SelectedItem.Text)
Asunto = Asunto.Replace("{""SerieFolio""}", $"{LblSerie.Text} - {TxtFolio.Text}")
End If
If Not EnviarFactura Then
ObjVentas.UpdateVentaMail(0, CveVenta)
End If
Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
If DdlTipoComprobante.SelectedValue = "Cot" Then
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
Else
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF})
LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML})
End If
Dim DisplayName As String = ""
If UsuarioActual.CveEmpresa = 119 Then DisplayName = "Facturación Agroquímicos JAM"
If ObjMail.SendMail(EmpresaActual, Mail, Asunto, Cuerpo, MailCC, LSRutasMail, Displayname:=DisplayName) Then
ResultadoMail = 1
Else
ResultadoMail = 3
End If
ObjVentas.UpdateVentaMail(ResultadoMail, CveVenta)
'CASO ESPECIAL
If CveUsuarioActual = 1446 Then ' Flora
Dim str As String = "Flora Envio: Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString
str.GuardaLog()
ElseIf CveUsuarioActual = 1513 Then ' Flora
Dim str As String = "Flora Envio (secundario): Correo:" & Mail & " - CorreosCC: " & MailCC & " RM:" & ResultadoMail.ToString
str.GuardaLog()
End If
'Next
Catch ex As Exception
OnError("Ocurrió error al mandar el Mail", ex)
ObjVentas.UpdateVentaMail(3, CveVenta)
Finally
ObjVentas.Dispose()
End Try
End Sub
#End Region
#Region "CODIGO DE BARRAS"
Protected Sub ChkClasificacion_CheckedChanged(sender As Object, e As EventArgs)
If ChkClasificacion.Checked Then
DIVClasificacion.Visible = False
'DIVClasif.Visible = False
DIVCodBarras.Visible = True
'DIVCod.Visible = True
'TxtCodigoBarras.Focus()
Else
DIVClasificacion.Visible = True
'DIVClasif.Visible = True
DIVCodBarras.Visible = False
'DIVCod.Visible = False
End If
End Sub
'Protected Sub CargarCodigo()
' Dim TipoVenta As Integer = 0
' Dim drSucursal As DataRow = GlobalDTSubProyectos(-1).FiltroPrimero(String.Format("CveSubProyecto = {0}", DdlSubProyectoDatos.SelectedValue))
' If drSucursal IsNot Nothing Then TipoVenta = drSucursal("TipoVenta").ToString.ToEntero
' ChkClasificacion.Checked = True
' DIVClasif.Visible = False
' DIVClasificacion.Visible = False
' DIVCodBarras.Visible = True
' DIVCod.Visible = True
' RegistraScript(String.Format("$( document ).ready(function() {{$('#{0}').focus()}});", TxtCodigoBarras.ClientID), "cb")
'End Sub
Protected Sub CargarCodigo()
Dim TipoVenta As Integer = 0
Dim drSucursal As DataRow = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", If(DdlSubProyectoDatos.SelectedValue = "", "-1", DdlSubProyectoDatos.SelectedValue)))
If drSucursal IsNot Nothing Then TipoVenta = drSucursal("TipoVenta").ToString.ToEntero
If TipoVenta = 1 Then
ChkClasificacion.Checked = True
'DIVClasif.Visible = False
DIVClasificacion.Visible = False
DIVCodBarras.Visible = True
'DIVCod.Visible = True
'TxtCodigoBarras.Focus()
'RegistraScript(String.Format("$( document ).ready(function() {{$('#{0}').focus()}});", TxtCodigoBarras.ClientID), "cb")
Else
ChkClasificacion.Visible = False
End If
End Sub
'Protected Sub BtnCodigoBarras_Click(sender As Object, e As EventArgs) Handles BtnCodigoBarrasSerie.Click
' Dim DrProducto As DataRow = Nothing
' If TxtCantidad.Text.Trim.ToDouble <= 0 Then TxtCantidad.Text = "1"
' Dim SerieLote As String = ""
' Dim CodigoBarras As String = ""
' Dim CvePS As Integer
' 'LIMPIA "PROPIEDAD"
' HdnCvePS.Value = ""
' 'BUSCA POR SERIE E IGNORA CODIGO DE BARRAS (LIMPIA)
' If TxtCodigoSerie.Text.Trim <> "" Then
' SerieLote = TxtCodigoSerie.Text.Trim().ToUpper()
' Dim Objinventarios As New ClsInventarios
' Dim Existencia = Objinventarios.GetExistenciasPS(-1, -1, UsuarioActual.CveEmpresa, -1, SerieLote:=SerieLote, ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero)
' Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", SerieLote))
' CvePS = Objinventarios.CvePS
' Objinventarios.Dispose()
' If Existencia - ExistenciaActual > 0 Then
' If CvePS > 0 Then
' DrProducto = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("")
' If DrProducto IsNot Nothing Then
' HdnCvePS.Value = CvePS.ToString
' TxtCantidad.Text = "1"
' Else
' Alert($"No se encontró un producto con la serie: <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("Producto no encontrado ")
' End If
' 'CARGA VALORES DEL PS
' DdlPSIndexChange(CvePS, DdlPS)
' If Not TxtCantidad.Text.ToDouble > 0 Then TxtCantidad.Text = "1"
' TxtPrecio.Focus()
' RegistraScript($"$('#{TxtPrecio.ClientID}').select();")
' 'LO DE ABAJO YA NO SE USA - ES VIEJO
' Exit Sub
' 'PARA AGREGAR PS DIRECTO
' If DrProducto IsNot Nothing Then
' TxtObsPS.Text = ""
' If UsuarioActual.CveEmpresa = 80 Then
' 'BUSCA EL PRECIO DE LA SUCURSAL
' Dim ObjPS As New ClsProductosServicios
' If ObjPS.GetPSSucursales(DrProducto("CvePS").ToString.ToEntero, UsuarioActual.CveEmpresa, DdlSubProyectoDatos.SelectedValue.ToEntero) Then
' Dim dtt As DataTable = ObjPS.DtResultados
' Dim drPrecio As DataRow = dtt.FiltroPrimero("")
' If drPrecio IsNot Nothing And TxtPrecio.Enabled = False Then
' TxtPrecio.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4")
' End If
' dtt.Dispose()
' End If
' ObjPS.Dispose()
' 'SI NO CARGA PRECIO DE LA SUCURSAL TOMA EL DEL PS
' If TxtPrecio.Text.ToDouble <= 0 Then
' TxtPrecio.Text = DrProducto("Precio").ToString.ToDouble.ToString("N4")
' End If
' HdnPS.Value = DrProducto("PS").ToString
' HdnCodigoPS.Value = DrProducto("PSCodigo").ToString
' HdnTipoPS.Value = DrProducto("CveTipoPS").ToString
' HdnTipoInv.Value = DrProducto("Inv_CveMetodoInventario").ToString
' HdnAplicaIEPS.Value = DrProducto("AplicaIEPS").ToString
' HdnPorcentajeIEPS.Value = DrProducto("IEPSPorcentaje").ToString
' HdnIVAPS.Value = If(DrProducto("IVA").ToString = "-1", ViewState("IVA"), DrProducto("IVA").ToString).ToString
' HdnIVARetAPS.Value = DrProducto("RetIVA").ToString
' HdnAsientoContable.Value = DrProducto("AsientoContableVentas").ToString
' HdnCtaContable.Value = DrProducto("IdCtaContVentas").ToString
' HdnAplicaParaConcepto.Value = DrProducto("AplicaParaConcepto").ToString
' HdnCodigo.Value = DrProducto("Codigo").ToString
' If ValidaAgregarPS(DrProducto("CvePS").ToString.ToEntero, DrProducto("CveUM").ToString.ToEntero, TxtPrecio.Text.Trim.ToDouble, DrProducto("CveTipoPS").ToString.ToEntero) Then
' If UsuarioActual.Empresa.Funcionalidad(507) = DdlPS.SelectedValue Then
' CvePSAmortizacion = DdlPS.SelectedValue.ToEntero.ToEntero
' End If
' AgregarProductoServicio(TxtCantidad.Text.Trim.ToDecimal, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString,
' DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDecimal, 0,
' DdlProyecto.SelectedValue.ToEntero, DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text)
' 'AddPS(TxtCantidad.Text.Trim.ToDouble, DrProducto("CveUM").ToString.ToEntero, DrProducto("UnidadMedida").ToString, DrProducto("CveClasificacion").ToString.ToEntero, DrProducto("Clasificacion").ToString,
' ' DrProducto("CvePS").ToString.ToEntero, DrProducto("PS").ToString, TxtObsPS.Text.Trim, TxtPrecio.Text.Trim.ToDouble, HdnIVAPS.Value.ToDouble, 0, 0,
' ' -1, -1, True, DrProducto("Codigo").ToString, DdlProyecto.SelectedValue.ToEntero,
' ' DdlProyecto.SelectedItem.Text, DdlSubProyecto.SelectedValue.ToEntero, DdlSubProyecto.SelectedItem.Text, DrProducto("CveTipoPS").ToString.ToEntero, DrProducto("Inv_CveMetodoInventario").ToString.ToEntero, SerieLote:=SerieLote, CodigoPS:=DrProducto("PSCodigo").ToString)
' LimpiaAgregar()
' End If
' End If
' Else
' Alert("No se encontró el producto.", TipoMensaje.MsgAdvertencia)
' End If
'End Sub
Private Sub btnBuscarPrecio_Click(sender As Object, e As EventArgs) Handles btnBuscarPrecio.Click
Dim Codigo, CodigoBarras As String
Dim CvePS As Integer
CvePS = If(DdlBPPS.SelectedValue.ToEntero > 0, DdlBPPS.SelectedValue.ToEntero, -1)
Codigo = If(TxtBPCodigo.Text.Trim.Length = 0, "", TxtBPCodigo.Text)
CodigoBarras = If(TxtBPCodigoBarras.Text.Trim.Length = 0, "", TxtBPCodigoBarras.Text)
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSSucursalesALL(DdlPS.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, Codigo:=Codigo, CodigoBarras:=CodigoBarras, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero) Then
GVBuscarPrecio.DataSource = ObjPS.DtResultados
Else
GVBuscarPrecio.DataSource = Nothing
End If
ObjPS.Dispose()
GVBuscarPrecio.DataBind()
UpBuscarPrecio.Update()
End Sub
#End Region
#Region "MONEDA"
Private Sub DdlMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlMoneda.SelectedIndexChanged
CambiaMoneda()
End Sub
Private Sub CambiaMoneda()
TrConversionTipoCambio.Visible = False
TrConversionDolares.Visible = False
Select Case DdlMoneda.SelectedValue
Case "1"
TxtTipoCambio.Text = "1"
TxtTipoCambioDlls.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString
TrConversionDolares.Visible = True
Case "2"
TxtTipoCambioDlls.Text = "1"
TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString
TrConversionTipoCambio.Visible = True
Case Else
TxtTipoCambio.Text = GlobalTipoCambio(TxtFecha.Text.ToDate).ToString
TrConversionTipoCambio.Visible = True
End Select
UpPS.Update()
End Sub
#End Region
#Region " CONDICIONES DE PAGO "
Private Sub InicializaCondicionesPago()
DtPagos = New DataTable
DtPagos.Columns.Add("CveTipoMovimiento", GetType(String))
DtPagos.Columns.Add("TipoMovimiento", GetType(String))
DtPagos.Columns.Add("CveCuenta", GetType(String))
DtPagos.Columns.Add("Cuenta", GetType(String))
DtPagos.Columns.Add("Folio", GetType(String))
DtPagos.Columns.Add("Importe", GetType(Decimal))
DtPagos.Columns.Add("Observaciones", GetType(String))
DtPagos.Columns.Add("Tipo", GetType(String))
DtPagos.Columns.Add("CveMetodoPago", GetType(Integer))
CargaCuentas()
End Sub
Private Sub LimpiaContado()
CargaCuentas()
DdlCuentaEfectivo.SelectedValueExist(-1)
TxtImporteEfectivo.Text = "0.00"
TxtImporteCredito.Text = "0.00"
TxtImporteDebito.Text = "0.00"
TxtImporteCheque.Text = "0.00"
TxtImporteTransferencia.Text = "0.00"
TxtImporteContado.Text = "0.00"
TxtCambio.Text = "0.00"
End Sub
Private Sub LimpiaEscondeContado()
'LIMPIA
DivContado.Visible = False
DivTerminal.Visible = False
If DtPagos IsNot Nothing Then DtPagos.Rows.Clear()
CargaGridContado()
Select Case RBLPago.SelectedValue.ToEntero
Case 1 'CREDITO
TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString
Case 2 'CONTADO
If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then
DivContado.Visible = True
TxtImporteContado.Text = TxtTotal.Text
End If
TxtFechaPago.Text = Now.ToShortDateString
Case 3 ' TERMINAL
DivTerminal.Visible = True
TxtFechaPago.Text = Now.AddDays(PlazoCobranza).ToShortDateString
End Select
LimpiaContado()
UpContado.Update()
End Sub
Private Sub CargaCuentas()
DdlCuentaEfectivo.Items.Clear()
DdlCuentaTarjetaCredito.Items.Clear()
DdlCuentaTarjetaDebito.Items.Clear()
DdlCuentaCheque.Items.Clear()
DdlCuentaTransferencia.Items.Clear()
DdlCuentaEfectivo.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).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 - TxtCambio.Text.ToDecimal) > TxtTotal.Text.ToDecimal Then
Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor rectifique.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
'Pago en Efectivo
If TxtImporteEfectivo.Text.ToDecimal > 0 Then
If DdlCuentaEfectivo.Items.Count > 0 Then
Dim DrEfectivo = DtPagos.NewRow
DrEfectivo("CveTipoMovimiento") = 13
DrEfectivo("TipoMovimiento") = "Pago en Efectivo"
DrEfectivo("CveCuenta") = DdlCuentaEfectivo.SelectedValue
DrEfectivo("Cuenta") = DdlCuentaEfectivo.SelectedItem.Text
DrEfectivo("Importe") = TxtImporteEfectivo.Text.ToDecimal - TxtCambio.Text.ToDecimal
DrEfectivo("Folio") = CargaFolioContado(DdlCuentaEfectivo.SelectedValue.ToEntero, 6)
DrEfectivo("Observaciones") = ""
DrEfectivo("Tipo") = "Caja Chica"
DrEfectivo("CveMetodoPago") = 1
DtPagos.Rows.Add(DrEfectivo)
Else
Alert("Debe seleccionar una cuenta válida de Caja", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Tarjeta Credito
If TxtImporteCredito.Text.ToDecimal > 0 Then
If DdlCuentaTarjetaCredito.Items.Count > 0 Then
Dim DrCredito = DtPagos.NewRow
DrCredito("CveTipoMovimiento") = 12
DrCredito("TipoMovimiento") = "Tarjeta de Crédito"
DrCredito("CveCuenta") = DdlCuentaTarjetaCredito.SelectedValue
DrCredito("Cuenta") = DdlCuentaTarjetaCredito.SelectedItem.Text
DrCredito("Importe") = TxtImporteCredito.Text
DrCredito("Folio") = CargaFolioContado(DdlCuentaTarjetaCredito.SelectedValue.ToEntero, 12)
DrCredito("Observaciones") = ""
DrCredito("Tipo") = "Tarjeta de Crédito"
DrCredito("CveMetodoPago") = 4
DtPagos.Rows.Add(DrCredito)
Else
Alert("Debe seleccionar una cuenta válida de Credito", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Tarjeta Debito
If TxtImporteDebito.Text.ToDecimal > 0 Then
If DdlCuentaTarjetaDebito.Items.Count > 0 Then
Dim DrDebito = DtPagos.NewRow
DrDebito("CveTipoMovimiento") = 11
DrDebito("TipoMovimiento") = "Tarjeta de Debito"
DrDebito("CveCuenta") = DdlCuentaTarjetaDebito.SelectedValue
DrDebito("Cuenta") = DdlCuentaTarjetaDebito.SelectedItem.Text
DrDebito("Importe") = TxtImporteDebito.Text
DrDebito("Folio") = CargaFolioContado(DdlCuentaTarjetaDebito.SelectedValue.ToEntero, 11)
DrDebito("Observaciones") = ""
DrDebito("Tipo") = "Tarjeta de Débito"
DrDebito("CveMetodoPago") = 5
DtPagos.Rows.Add(DrDebito)
Else
Alert("Debe seleccionar una cuenta válida de Debito", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Tarjeta Debito
If TxtImporteCheque.Text.ToDecimal > 0 Then
If DdlCuentaCheque.Items.Count > 0 Then
Dim DrCheque = DtPagos.NewRow
DrCheque("CveTipoMovimiento") = 3
DrCheque("TipoMovimiento") = "Cheque"
DrCheque("CveCuenta") = DdlCuentaCheque.SelectedValue
DrCheque("Cuenta") = DdlCuentaCheque.SelectedItem.Text
DrCheque("Importe") = TxtImporteCheque.Text
DrCheque("Folio") = CargaFolioContado(DdlCuentaCheque.SelectedValue.ToEntero, 3)
DrCheque("Observaciones") = ""
DrCheque("Tipo") = "Cheque"
DrCheque("CveMetodoPago") = 2
DtPagos.Rows.Add(DrCheque)
Else
Alert("Debe seleccionar una cuenta de cheque", TipoMensaje.MsgAdvertencia)
End If
End If
'Pago Transferencia
If TxtImporteTransferencia.Text.ToDecimal > 0 Then
If DdlCuentaTransferencia.Items.Count > 0 Then
Dim DrCheque = DtPagos.NewRow
DrCheque("CveTipoMovimiento") = 8
DrCheque("TipoMovimiento") = "Transferencia"
DrCheque("CveCuenta") = DdlCuentaTransferencia.SelectedValue
DrCheque("Cuenta") = DdlCuentaTransferencia.SelectedItem.Text
DrCheque("Importe") = TxtImporteTransferencia.Text
DrCheque("Folio") = CargaFolioContado(DdlCuentaTransferencia.SelectedValue.ToEntero, 8)
DrCheque("Observaciones") = ""
DrCheque("Tipo") = "Transferencia"
DrCheque("CveMetodoPago") = 3
DtPagos.Rows.Add(DrCheque)
Else
Alert("Debe seleccionar una cuenta de transferencia", TipoMensaje.MsgAdvertencia)
End If
End If
'JJMQ 20160506: Validacion para no pagar de mas a peticion de I.P.
abonado = DtPagos.SUM("Importe")
saldo = TxtTotal.Text.Replace(",", "").ToDouble - abonado
'CVImporteContado.ValueToCompare = (saldo.FormatoNumero(2).ToDouble).ToString
CargaGridContado()
UpContado.Update()
End Sub
Private Sub RBLPago_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLPago.SelectedIndexChanged
LimpiaEscondeContado()
End Sub
Private Function ValidaPagosContado() As Boolean
Dim Retorno = False
If DtPagos.SUM("Importe").ToString.ToDecimal > TxtTotal.Text.ToDecimal Then
Alert("El importe de los pagos no puede exceder el importe de la factura. Por favor verifique.", TipoMensaje.MsgAdvertencia)
Retorno = True
End If
Return Retorno
End Function
Private Sub CargaCuentasTerminal()
DdlCuentasTerminal.Items.Clear()
DdlCuentasTerminal.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario).FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTipoCuenta = 1", "", {"CveCuenta", "NumCuentaMoneda"})
DdlCuentasTerminal.DataBind()
DdlCuentasTerminal.Items.Insert(0, New ListItem("Seleccione", "-1"))
UPTarjetaTermminal.Update()
End Sub
#End Region
#Region " SERIE ALMACEN "
Protected Sub BtnSerie_Click(sender As Object, e As EventArgs)
Dim Row = CType(CType(sender, Button).NamingContainer, GridViewRow)
If Row.FCTextBox("TxtSerie").Text.Trim = "" Then Exit Sub
Dim Index = Row.RowIndex
Dim ObjInventarios As New ClsInventarios
Dim Existencia = ObjInventarios.GetExistenciasPSSerie("", ddlAlmacen.SelectedValue.ToEntero, UsuarioActual.CveEmpresa)
Dim ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Row.FCTextBox("TxtSerie").Text.ToString))
'Valida Existencia
If Existencia - ExistenciaActual <= 0 Then
Alert(String.Format("Not hay existencia suficiente del producto con la Serie: <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()
End Sub
Private Function ValidaSerieINV() As Boolean
Dim Retorno = False
Dim Existencia = 0.0
Dim ExistenciaActual = 0.0
Dim ObjInventarios As New ClsInventarios
For Each Gvr As GridViewRow In GvInv.Rows
If Gvr.FCCheckBox("cbInv").Checked Then
'VACIO
If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim = "" Then
Alert("Algun producto con salida de inventario no tiene especificada la SERIE. Por favor rectifique.", TipoMensaje.MsgAdvertencia)
Retorno = True
Exit For
End If
'SIN EXISTENCIA
If Gvr.FCTextBox("TxtSerie").Visible = True And Gvr.FCTextBox("TxtSerie").Text.Trim <> "" Then
Existencia = ObjInventarios.GetExistenciasPSSerie(Gvr.FCTextBox("TxtSerie").Text.ToString, ddlAlmacen.SelectedValue.ToEntero, UsuarioActual.CveEmpresa)
ExistenciaActual = DtInv.SUM("Cantidad", String.Format("SerieLote = '{0}'", Gvr.FCTextBox("TxtSerie").Text.Trim))
'Valida Existencia
If Existencia - ExistenciaActual < 0 Or Existencia = 0 Then
Alert(String.Format("No hay existencia suficiente del producto con la Serie: <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
If ViewState("CveCliente").ToString.ToEntero > 0 Then CargaAgregar()
End Sub
Private Sub LnkAgregarCliente_Click(sender As Object, e As EventArgs) Handles LnkAgregarCliente.Click
DivNombreCliente.Visible = False
DivDireccionCliente.Visible = False
DivNumeroCPCliente.Visible = False
DivColoniaTelefonoCliente.Visible = False
DivCiudadLocalidadCliente.Visible = False
DivEstadoPaisCliente.Visible = False
DivCorreoCuentaCliente.Visible = False
DivBotonesAgregarCliente.Visible = False
DivFormaCliente.Visible = False
UpAgregarCliente.Update()
RegistraScript("showDivEC();")
End Sub
Private Sub BtnValidarRFC_Click(sender As Object, e As EventArgs) Handles BtnValidarRFC.Click
If TxtRFCCliente.Text = "XAXX010101000" Then
DivNombreCliente.Visible = True
DivDireccionCliente.Visible = True
DivNumeroCPCliente.Visible = True
DivColoniaTelefonoCliente.Visible = True
DivCiudadLocalidadCliente.Visible = True
DivEstadoPaisCliente.Visible = True
DivCorreoCuentaCliente.Visible = True
DivBotonesAgregarCliente.Visible = True
DivFormaCliente.Visible = True
RFVDireccionC.Visible = False
RFVNoEC.Visible = False
RFVColoniaC.Visible = False
RFVCiudadC.Visible = False
RFVLocalidadC.Visible = False
RFVEstadoC.Visible = False
RFVPaisC.Visible = False
DdlMetodoCliente.SelectedValueExist(1)
DdlFormaCliente.SelectedValueExist(1)
Else
Dim ObjCliente As New ClsClientes
If ObjCliente.ValidaClienteRFC(TxtRFCCliente.Text, UsuarioActual.CveEmpresa) Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
RegistraScript("hideDivEC();")
ViewState("CveCliente") = ObjCliente.DtResultados(0)("CveCliente").ToString.ToEntero
HdnCveCliente.Value = ObjCliente.DtResultados(0)("CveCliente").ToString
CargaCliente(CveCliente)
UpCliente.Update()
Else
DivNombreCliente.Visible = True
DivDireccionCliente.Visible = True
DivNumeroCPCliente.Visible = True
DivColoniaTelefonoCliente.Visible = True
DivCiudadLocalidadCliente.Visible = True
DivEstadoPaisCliente.Visible = True
DivCorreoCuentaCliente.Visible = True
DivBotonesAgregarCliente.Visible = True
DivFormaCliente.Visible = True
End If
End If
ObjCliente.Dispose()
RFVDireccionC.Visible = True
RFVNoEC.Visible = True
RFVColoniaC.Visible = True
RFVCiudadC.Visible = True
RFVLocalidadC.Visible = True
RFVEstadoC.Visible = True
RFVPaisC.Visible = True
DdlMetodoCliente.SelectedValueExist(-1)
DdlFormaCliente.SelectedValueExist(-1)
End If
End Sub
Private Sub BtnAgregarCliente_Click(sender As Object, e As EventArgs) Handles BtnAgregarCliente.Click
Dim ObjCliente As New ClsClientes
If ObjCliente.AgregarClienteNoFrecuente(TxtNombreCliente.Text.Trim, TxtDireccionCliente.Text.Trim, TxtNumExtCliente.Text.Trim, TxtNumIntCliente.Text.Trim, TxtColoniaCliente.Text.Trim, TxtLocalidadCliente.Text.Trim, TxtCiudadCliente.Text.Trim, TxtEstadoCliente.Text.Trim, TxtPaisCliente.Text.Trim, TxtRFCCliente.Text.Trim, TxtCPCliente.Text.Trim, TxtTelefonoCliente.Text.Trim, TxtCorreoCliente.Text.Trim, DdlSubProyectoDatos.SelectedValue.ToEntero, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "") Then
If ObjCliente.DtResultados.Rows.Count > 0 Then
RegistraScript("hideDivEC();")
ViewState("CveCliente") = ObjCliente.DtResultados(0)("CveCliente").ToString.ToEntero
HdnCveCliente.Value = ObjCliente.DtResultados(0)("CveCliente").ToString
CargaCliente(CveCliente)
UpCliente.Update()
End If
End If
ObjCliente.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)
'If DdlClasificacionPS.SelectedValue.ToEntero > 0 Then
'Dim ObjVenta As New ClsVentas
'If ObjVenta.GetClasificacionDetalle(UsuarioActual.CveEmpresa, CveClasificacion:=DdlClasificacionPS.SelectedValue.ToEntero) Then
' DdlTipo.DataSource = ObjVenta.DtResultados
'End If
'ObjVenta.Dispose()
' End If
DdlTipo.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlTipo.DataBind()
End Sub
Private Sub CargaClasificacionesPS()
If UsuarioActual.Empresa.UsaAC Then
DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion")
Else
DdlClasificacionPS.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion")
'DdlTipo.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("", Orderby:="Clasificacion")
End If
'BLOQUEA DDL CLASIFICACION
If UsuarioActual.Empresa.Funcionalidad(121) = "1" Then
If Not UsuarioActual.TienePermisoProceso(147) Then
DdlClasificacionPS.Enabled = False
'DdlTipo.Enabled = False
End If
End If
DdlClasificacionPS.DataBind()
'DdlTipo.DataBind()
End Sub
Private Sub CargaTipoProductos()
'BLOQUEA DDL TIPO PRODUCTO
If UsuarioActual.Empresa.Funcionalidad(122) = "1" Then
If Not UsuarioActual.TienePermisoProceso(149) Then
DdlTipoPS.Enabled = False
DdlTipoPS.SelectedValueExist("2")
End If
End If
End Sub
Private Sub CargaUnidadesMedida()
DdlUnidadMedidaPS.Items.Clear()
DdlUnidadMedidaPS.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa)
DdlUnidadMedidaPS.DataBind()
DdlUnidadMedidaPS.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub CargarMarcas()
If UsuarioActual.Empresa.Funcionalidad(130) = "1" Then
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then
DivMarcaPSDes.Visible = True
Else
DivMarca.Visible = True
End If
DdlMarca.Items.Clear()
DdlMarcaPSDes.Items.Clear()
Dim ObjMarcas As New ClsProductosServicios
ObjMarcas.GetMarcas(UsuarioActual.CveEmpresa)
DdlMarca.DataSource = ObjMarcas.DtResultados
DdlMarcaPSDes.DataSource = ObjMarcas.DtResultados
ObjMarcas.Dispose()
DdlMarca.DataBind()
DdlMarcaPSDes.DataBind()
End If
DdlMarca.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlMarcaPSDes.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub BtnModalAddPS_Click(sender As Object, e As EventArgs) Handles BtnModalAddPS.Click
TxtCodigoPS.Text = ""
TxtCodigoBarrasPS.Text = ""
TxtPS.Text = ""
TxtModelo.Text = ""
TxtAdicional.Text = ""
DdlTipoPS.SelectedIndex = 0
DdlUnidadMedidaPS.SelectedIndex = 0
DdlClasificacionPS.SelectedIndex = 0
'DdlMetodoInv.SelectedIndex = 0
ChkRequiereSerie.Checked = False
DdlMarca.SelectedIndex = 0
DdlMarcaPSDes.SelectedIndex = 0
CargaClasificacionesDetalles()
UpAddPS.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddPS"))
End Sub
Private Sub LbAddPS_Click(sender As Object, e As EventArgs) Handles LbAddPS.Click
If (TxtCodigoPS.Text = TxtCodigoBarrasPS.Text AndAlso TxtCodigoPS.Text <> "") Then
Alert("Los codigos no pueden ser iguales. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia)
Return
End If
If UsuarioActual.Empresa.Funcionalidad(265) = "1" And TxtCodigoPS.Text = "" Then
Alert("El codigo es requerido.", TipoMensaje.MsgAdvertencia)
Return
End If
If TxtCodigoPS.Text <> "" AndAlso Not TxtCodigoPS.Text.Length >= 3 Then
Alert("El codigo tiene que que tener una longitud de al menos 3 digitos.", TipoMensaje.MsgAdvertencia)
Return
End If
Dim CveMetodoInventario As Integer = 0
If ChkRequiereSerie.Checked Then CveMetodoInventario = 5 Else CveMetodoInventario = 1
Dim CveMarca As Integer = 0
If UsuarioActual.CveEmpresa.Contiene(72, 80) Then CveMarca = DdlMarcaPSDes.SelectedValue.ToEntero Else CveMarca = DdlMarca.SelectedValue.ToEntero
Dim ObjProductosServicios As New ClsProductosServicios()
If ObjProductosServicios.AddPS(DdlClasificacionPS.SelectedValue.ToEntero, -1, DdlUnidadMedidaPS.SelectedValue.ToEntero, TxtCodigoPS.Text.Trim, "", TxtCodigoBarrasPS.Text.Trim, TxtPS.Text.Trim, 0, -1, 0, False, 0, False, True, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveMetodoInventario, 0, CveTipoPS:=DdlTipoPS.SelectedValue.ToEntero, CveMarca:=CveMarca, CveSATPS:=DdlSATPS.SelectedValue.ToEntero, CveClasificacionDetalle:=DdlTipo.SelectedValue.ToEntero) > 0 Then
DdlClasificacion.SelectedValueExist(DdlClasificacionPS.SelectedValue.ToEntero)
DdlClasificacion_SelectedIndexChanged(DdlClasificacionPS, e)
'SI ES DDLOST
If UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then
DdlPS.SelectedValue = ObjProductosServicios.CvePS.ToString
DdlPS.SelectedText = TxtPS.Text.Trim
Else
DdlPS.ddl.Items.Insert(2, New ListItem(TxtPS.Text.Trim, ObjProductosServicios.CvePS.ToString))
DdlPS.ddl.SelectedValueExist(ObjProductosServicios.CvePS)
End If
DdlUnidadMedida.Items.Clear()
DdlUnidadMedida.Items.Insert(0, New ListItem(DdlUnidadMedidaPS.SelectedItem.Text, DdlUnidadMedidaPS.SelectedValue))
DdlUnidadMedida.SelectedValueExist(DdlUnidadMedidaPS.SelectedValue)
HdnPS.Value = TxtPS.Text.Trim
HdnCodigoPS.Value = $"{TxtCodigoPS.Text.Trim}-{TxtPS.Text.Trim}"
HdnTipoPS.Value = DdlTipoPS.SelectedValue
HdnTipoInv.Value = CveMetodoInventario.ToString
HdnAplicaIEPS.Value = "False"
HdnPorcentajeIEPS.Value = "-1"
HdnIVAPS.Value = "0.16"
HdnIVARetAPS.Value = "0"
HdnAsientoContable.Value = "1"
HdnCtaContable.Value = "0"
HdnAplicaParaConcepto.Value = "False"
HdnCodigo.Value = TxtCodigoPS.Text.Trim
End If
ObjProductosServicios.Dispose()
UpPS.Update()
RegistraScript(String.Format("$('#{0}').modal('hide');", "DivAddPS"))
RecargaGlobal()
End Sub
Private Sub RecargaGlobal()
Dim Hilo As New System.Threading.Thread(AddressOf GeneraGlobalDT)
Hilo.Start()
End Sub
Private Sub GeneraGlobalDT()
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 "CLASIFICACIONES DETALLES"
Protected Sub DdlClasificacionPS_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaClasificacionesDetalles()
End Sub
Protected Sub BtnAddClasificacionDetalle_Click(sender As Object, e As EventArgs)
TxtClasificacionDetalle.Text = ""
DdlClasificacionModal.SelectedValueExist(DdlClasificacionPS.SelectedValue)
UpModal.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DModalClasificacion"))
End Sub
Protected Sub BtnAddClasificacionDetalleModal_Click(sender As Object, e As EventArgs)
Dim ObjVentas As New ClsVentas
If ObjVentas.AddClasificacionDetalle(TxtClasificacionDetalle.Text, DdlClasificacionModal.SelectedValue.ToEntero,
UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then
CargaClasificacionesDetalles()
DdlTipo.SelectedValueExist(ObjVentas.CveClasificacionDetalle)
UpAddPS.Update()
RegistraScript(String.Format("$('#{0}').modal('hide');", "DModalClasificacion"), "1")
RegistraScript("CreaDescripcionPS();", "2")
End If
ObjVentas.Dispose()
End Sub
#End Region
#Region "AJUSTE"
Private Sub CreaDTmpDTAjustes()
TmpDTAjustes = New DataTable
TmpDTAjustes.Columns.Add("CveFolioGarantia", GetType(Integer))
TmpDTAjustes.Columns.Add("CveTipoUso", GetType(Integer))
TmpDTAjustes.Columns.Add("CveTipoDefecto", GetType(Integer))
TmpDTAjustes.Columns.Add("CodigoEnsamble", GetType(String))
TmpDTAjustes.Columns.Add("CodigoLinea", GetType(String))
TmpDTAjustes.Columns.Add("CodigoInspeccion", GetType(String))
TmpDTAjustes.Columns.Add("Consecutivo", GetType(String))
TmpDTAjustes.Columns.Add("ConsecutivoVenta", GetType(Integer))
TmpDTAjustes.Columns.Add("FechaAjuste", GetType(Date))
TmpDTAjustes.Columns.Add("Meses", GetType(String))
TmpDTAjustes.Columns.Add("PorcentajeAjuste", GetType(Double))
TmpDTAjustes.Columns.Add("NumPoliza", GetType(String))
TmpDTAjustes.Columns.Add("Importe", GetType(Double))
TmpDTAjustes.Columns.Add("CvePS", GetType(Integer))
TmpDTAjustes.Columns.Add("PS", GetType(String))
TmpDTAjustes.Columns.Add("Cantidad", GetType(Decimal))
TmpDTAjustes.Columns.Add("CveUM", GetType(Integer))
TmpDTAjustes.Columns.Add("CveVentaDetalle", GetType(Integer))
TmpDTAjustes.Columns.Add("CveVenta", GetType(Integer))
TmpDTAjustes.Columns.Add("PUFactura", GetType(Integer))
End Sub
Private Sub CargaFacturasAjuste()
DdlFacturas.Items.Clear()
Dim ObjVenta As New ClsVentas
If ObjVenta.GetVentas(UsuarioActual.CveEmpresa, "Ing", "-1", -1, "-1", CveCliente, -1, -1, -1, "-1", "-1", "-1", CveUsuarioConsulta:=UsuarioActual.CveUsuario) Then
DdlFacturas.DataSource = ObjVenta.DtResultados
DdlFacturas.Items.Insert(0, New ListItem("Sin Factura", "-1"))
End If
ObjVenta.Dispose()
DdlFacturas.DataBind()
UpAjuste.Update()
End Sub
Private Sub CargaAjuste()
Dim ObjAcum As New ClsAcumuladores
If ObjAcum.FoliosGarantiaGet(-1, UsuarioActual.CveEmpresa) Then
DdlFolioGarantia.DataSource = ObjAcum.DtResultados
DdlFolioGarantia.Items.Insert(0, New ListItem("Seleccione", "-1"))
End If
DdlFacturas.Items.Insert(0, New ListItem("Sin Factura", "-1"))
DdlTipoUso.DataSource = GlobalDTAcumTiposUso.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa}")
DdlTipoUso.Items.Insert(0, New ListItem("Seleccione", "-1"))
DdlTipoDefecto.DataSource = GlobalDTAcumTiposDefecto.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa}")
DdlTipoDefecto.Items.Insert(0, New ListItem("Seleccione", "-1"))
GvRecepcionUsados.DataSource = GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CvePSCargo > 0")
ObjAcum.Dispose()
DdlFolioGarantia.DataBind()
DdlTipoUso.DataBind()
DdlTipoDefecto.DataBind()
GvRecepcionUsados.DataBind()
DdlFacturas.DataBind()
CargaPSAjuste()
CreaDTmpDTAjustes()
CreaDTmpDTRecepcionUsados()
DivChkAjuste.Visible = True
End Sub
Private Sub CargaPSAjuste()
DdlPSAjuste.Items.Clear()
DtPUFacturas.Rows.Clear()
If DdlFacturas.SelectedValue.ToEntero > 0 Then
'TxtPUFactura.Enabled = False
Dim ObjVenta As New ClsVentas
If ObjVenta.GetVentaDetalle(DdlFacturas.SelectedValue.ToEntero) Then
DdlPSAjuste.DataSource = ObjVenta.DtResultados
DtPUFacturas = ObjVenta.DtResultados
TxtFechaAjuste.Text = ObjVenta.DtResultados.Rows(0)("Fecha").ToString.ToDate.ToShortDateString
End If
ObjVenta.Dispose()
Else
'TxtPUFactura.Enabled = True
'TxtPUFactura.Text = ""
DdlPSAjuste.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa)
End If
DdlPSAjuste.DataBind()
DdlPSAjuste.Items.Insert(0, New ListItem("Seleccione", "-1"))
DtPUFacturas.AcceptChanges()
UpAjuste.Update()
CalculaPorcentajeAjuste()
End Sub
Private Sub Ajuste()
LimpiaAjuste()
If TmpDTAjustes IsNot Nothing AndAlso TmpDTAjustes.FiltraParametros($"ConsecutivoVenta = {ConsecutivoVenta}").Rows.Count > 0 Then
ModalidadAjuste = "U"
TxtPrecio.Attributes.Add("onKeyUp", $"CambiaAjuste(this,{TxtPUFactura.ClientID});")
ChkAjuste.Checked = True
DivAjuste.Visible = True
CargaAjusteDetalle()
Else
ModalidadAjuste = "A"
TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();")
End If
End Sub
Private Sub LimpiaAjuste()
DdlFolioGarantia.SelectedIndex = -1
TxtConsecutivoAjuste.Text = ""
TxtCodEnsamble.Text = ""
DdlTipoUso.SelectedIndex = -1
TxtCodLinea.Text = ""
TxtPUFactura.Text = ""
TxtFechaAjuste.Text = Now.ToShortDateString
CEEFechaAjuste.EndDate = Now
TxtCodInspeccion.Text = ""
TxtMesesUso.Text = ""
DdlTipoDefecto.SelectedIndex = -1
TxtPorcentajeAjuste.Text = ""
TxtPoliza.Text = ""
TxtImporteAjuste.Text = ""
DdlPSAjuste.SelectedIndex = 0
ChkAjuste.Checked = False
DivAjuste.Visible = False
End Sub
Private Sub CargaAjusteDetalle()
Dim Dr As DataRow = Nothing
IndexAjuste = 0
For Each Dr2 As DataRow In TmpDTAjustes.Rows
If Dr2("ConsecutivoVenta").ToString.ToEntero = ConsecutivoVenta Then
Dr = Dr2
Exit For
End If
IndexAjuste += 1
Next
If Dr IsNot Nothing Then
IndexAjuste = TmpDTAjustes.Rows.IndexOf(Dr)
DdlFolioGarantia.SelectedValueExist(Dr("CveFolioGarantia").ToString)
TxtConsecutivoAjuste.Text = Dr("Consecutivo").ToString
TxtCodEnsamble.Text = Dr("CodigoEnsamble").ToString
DdlTipoUso.SelectedValueExist(Dr("CveTipoUso").ToString)
TxtCodLinea.Text = Dr("CodigoLinea").ToString
TxtCodInspeccion.Text = Dr("CodigoInspeccion").ToString
TxtMesesUso.Text = Dr("Meses").ToString
DdlTipoDefecto.SelectedValueExist(Dr("CveTipoDefecto").ToString)
TxtPorcentajeAjuste.Text = Dr("PorcentajeAjuste").ToString
TxtPoliza.Text = Dr("NumPoliza").ToString
TxtImporteAjuste.Text = Dr("Importe").ToString
DdlFacturas.SelectedValueExist(Dr("CveVenta").ToString)
CargaPSAjuste()
DdlPSAjuste.SelectedValueExist(Dr("CvePS").ToString)
TxtFechaAjuste.Text = Dr("FechaAjuste").ToString.ToDate.ToShortDateString
TxtPUFactura.Text = Dr("PUFactura").ToString.ToDecimal.FormatoNumero(2)
TxtPUFactura.Enabled = Not Dr("CveVenta").ToString.ToEntero > 0
End If
End Sub
Protected Sub BtnCalculaMesesUso_Click(sender As Object, e As EventArgs)
CalculaMesesUso()
End Sub
Private Sub CalculaMesesUso()
TxtMesesUso.Text = DateDiff(DateInterval.Month, TxtFechaAjuste.Text.ToDate, Now).ToEntero.ToString
CalculaPorcentajeAjuste()
End Sub
Protected Sub DdlPSAjuste_selectedindexchange(sender As Object, e As EventArgs)
If DdlPSAjuste.SelectedValue.ToEntero > 0 AndAlso DdlFacturas.SelectedValue.ToEntero > 0 Then
Dim Index As Integer = DdlPSAjuste.SelectedIndex
Dim Contador As Integer = 1
Dim PUFactura As Decimal = 0
For Each Dr As DataRow In DtPUFacturas.Rows
If Index = Contador Then
PUFactura = Dr("PU").ToString.ToDecimal
End If
Contador += 1
Next
'TxtPUFactura.Text = PUFactura.FormatoNumero(2)
End If
If Not DdlPSAjuste.SelectedValue.ToEntero > 0 AndAlso DdlFacturas.SelectedValue.ToEntero > 0 Then
'TxtPUFactura.Text = ""
End If
CalculaPorcentajeAjuste()
End Sub
Protected Sub DdlTipoUso_SelectedIndexChanged(sender As Object, e As EventArgs)
CalculaPorcentajeAjuste()
End Sub
Protected Sub BtnCalcularImporteAjuste_Click(sender As Object, e As EventArgs)
CalculaPorcentajeAjuste()
End Sub
Private Sub CalculaPorcentajeAjuste()
If DdlTipoUso.SelectedValue.ToEntero > 0 AndAlso DdlPSAjuste.SelectedValue.ToEntero > 0 AndAlso TxtMesesUso.Text <> "" AndAlso DdlPS.SelectedValue.ToEntero > 0 Then
Dim CveMarca As Integer = -1
If GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).Rows.Count > 0 Then
CveMarca = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).Rows(0)("CveMarca").ToString.ToEntero
End If
Dim ObjAcum As New ClsAcumuladores
If ObjAcum.GarantiasMesesGet(-1, UsuarioActual.CveEmpresa, CveMarca, DdlTipoUso.SelectedValue.ToEntero, TxtMesesUso.Text.ToEntero) Then
If ObjAcum.DtResultados.Rows.Count > 0 Then
TxtPorcentajeAjuste.Text = (ObjAcum.DtResultados.Rows(0)("Valor").ToString.ToDouble / 100).ToString
TxtImporteAjuste.Text = (TxtPorcentajeAjuste.Text.ToDouble * TxtPUFactura.Text.ToDouble).FormatoNumero
Dim CargoActual As Decimal = 0
Dim CargoAnterior As Decimal = 0
Dim CveTamaño As Integer = 0
If DdlPSAjuste.SelectedValue.ToEntero > 0 Then
Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).Rows(0)
If Dr IsNot Nothing Then
CargoAnterior = Dr("Cargo").ToString.ToDecimal
End If
End If
If DdlPS.SelectedValue.ToEntero > 0 Then
Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPS.SelectedValue.ToEntero).Rows(0)
If Dr IsNot Nothing Then
CveTamaño = Dr("CveTamaño").ToString.ToEntero
End If
End If
If GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {CveTamaño}").Rows(0) IsNot Nothing AndAlso GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {CveTamaño}").Rows.Count > 0 Then
Dim DrCargo As DataRow = GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {CveTamaño}").Rows(0)
If DrCargo IsNot Nothing Then
CargoActual = DrCargo("Cargo").ToString.ToDecimal
End If
End If
TxtDescuentoAjuste.Text = ((TxtPUFactura.Text.ToDouble - TxtImporteAjuste.Text.ToDouble) - (CargoActual - CargoAnterior)).FormatoNumero
TxtDescuentoAjuste.ToolTip = $"La diferencia de ajuste fue: {(TxtPUFactura.Text.ToDouble - TxtImporteAjuste.Text.ToDouble).FormatoNumero()}. La diferencia de tamaños fue: {(CargoActual - CargoAnterior).FormatoNumero}."
End If
End If
ObjAcum.Dispose()
End If
UpAjuste.Update()
End Sub
'Private Function AsignaPUFijo(CvePS As Integer) As Double
' Select Case CvePS
' Case 360449
' Return 500
' Case 360450
' Return 1000
' Case 360451
' Return 2000
' Case 360452
' Return 3000
' Case 360453
' Return 4000
' Case 360455
' Return 5000
' Case 365353
' Return 6000
' Case 360454
' Return 1500 'lth. acumulador
' Case 370810
' Return 2500 'lth. 1872
' Case Else
' Return 5000
' End Select
'End Function
Private Sub GuardaAjuste()
TxtPUFactura.Text = TxtPrecio.Text
UpAjuste.Update()
Dim CargoAnterior As Double = 0
Dim CargoActual As Double = 0
If ModalidadAjuste = "A" Then
Dim Row As DataRow = Nothing
Row = TmpDTAjustes.NewRow
Row("CveFolioGarantia") = DdlFolioGarantia.SelectedValue.ToEntero
Row("CveTipoUso") = DdlTipoUso.SelectedValue.ToEntero
Row("CveTipoDefecto") = DdlTipoDefecto.SelectedValue.ToEntero
Row("CodigoEnsamble") = TxtCodEnsamble.Text
Row("CodigoLinea") = TxtCodLinea.Text
Row("CodigoInspeccion") = TxtCodInspeccion.Text
Row("Consecutivo") = TxtConsecutivoAjuste.Text
Row("FechaAjuste") = TxtFechaAjuste.Text.ToDate
Row("Meses") = TxtMesesUso.Text.ToEntero
Row("PorcentajeAjuste") = TxtPorcentajeAjuste.Text.ToDouble
Row("NumPoliza") = TxtPoliza.Text
Row("Importe") = TxtImporteAjuste.Text.ToDouble
Row("ConsecutivoVenta") = ConsecutivoVenta
Row("CvePS") = DdlPSAjuste.SelectedValue
Row("PS") = DdlPSAjuste.SelectedItem.Text
Row("CveVenta") = DdlFacturas.SelectedValue
Row("PUFactura") = TxtPUFactura.Text.ToDouble
Row("Cantidad") = 1
Dim CveUM As Integer = -1
If DdlPSAjuste.SelectedValue.ToEntero > 0 Then
Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).Rows(0)
If Dr IsNot Nothing Then
CveUM = Dr("CveUnidadMedida").ToString.ToEntero
CargoAnterior = Dr("Cargo").ToString.ToDouble
End If
End If
Row("CveUM") = CveUM
Row("CveVentaDetalle") = -1
TmpDTAjustes.Rows.Add(Row)
ElseIf ModalidadAjuste = "U" Then
TmpDTAjustes.Rows(IndexAjuste)("CveFolioGarantia") = DdlFolioGarantia.SelectedValue.ToEntero
TmpDTAjustes.Rows(IndexAjuste)("CveTipoUso") = DdlTipoUso.SelectedValue.ToEntero
TmpDTAjustes.Rows(IndexAjuste)("CveTipoDefecto") = DdlTipoDefecto.SelectedValue.ToEntero
TmpDTAjustes.Rows(IndexAjuste)("CodigoEnsamble") = TxtCodEnsamble.Text
TmpDTAjustes.Rows(IndexAjuste)("CodigoLinea") = TxtCodLinea.Text
TmpDTAjustes.Rows(IndexAjuste)("CodigoInspeccion") = TxtCodInspeccion.Text
TmpDTAjustes.Rows(IndexAjuste)("Consecutivo") = TxtConsecutivoAjuste.Text
TmpDTAjustes.Rows(IndexAjuste)("FechaAjuste") = TxtFechaAjuste.Text.ToDate
TmpDTAjustes.Rows(IndexAjuste)("Meses") = TxtMesesUso.Text.ToDouble
TmpDTAjustes.Rows(IndexAjuste)("PorcentajeAjuste") = TxtPorcentajeAjuste.Text
TmpDTAjustes.Rows(IndexAjuste)("NumPoliza") = TxtPoliza.Text.ToDouble
TmpDTAjustes.Rows(IndexAjuste)("Importe") = TxtImporteAjuste.Text.ToDouble
TmpDTAjustes.Rows(IndexAjuste)("ConsecutivoVenta") = ConsecutivoVenta
TmpDTAjustes.Rows(IndexAjuste)("CvePS") = DdlPSAjuste.SelectedValue
TmpDTAjustes.Rows(IndexAjuste)("PS") = DdlPSAjuste.SelectedItem.Text
TmpDTAjustes.Rows(IndexAjuste)("CveVenta") = DdlFacturas.SelectedValue
TmpDTAjustes.Rows(IndexAjuste)("PUFactura") = TxtPUFactura.Text.ToDouble
TmpDTAjustes.Rows(IndexAjuste)("Cantidad") = 1
Dim CveUM As Integer = -1
If DdlPSAjuste.SelectedValue.ToEntero > 0 Then
Dim Dr As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, DdlPSAjuste.SelectedValue.ToEntero).Rows(0)
If Dr IsNot Nothing Then
CveUM = Dr("CveUnidadMedida").ToString.ToEntero
CargoAnterior = Dr("Cargo").ToString.ToDouble
End If
End If
TmpDTAjustes.Rows(IndexAjuste)("CveUM") = CveUM
TmpDTAjustes.Rows(IndexAjuste)("CveVentaDetalle") = -1
End If
TmpDTAjustes.AcceptChanges()
If TmpDT IsNot Nothing AndAlso TmpDT.Rows.Count > 0 Then
If TmpDT.Select($"Consec={ConsecutivoVenta}").Length > 0 Then
Dim Dr As DataRow = TmpDT.Select($"Consec={ConsecutivoVenta}")(0)
Dim CvePSCargo As Integer = -1
If GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {Dr("CveTamaño").ToString.ToEntero}").Rows(0) IsNot Nothing AndAlso GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {Dr("CveTamaño").ToString.ToEntero}").Rows.Count > 0 Then
Dim DrCargo As DataRow = GlobalDTAcumTamaños.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveTamaño = {Dr("CveTamaño")}").Rows(0)
If DrCargo IsNot Nothing Then
CvePSCargo = DrCargo("CvePSCargo").ToString.ToEntero
CargoActual = DrCargo("Cargo").ToString.ToDouble
End If
End If
Dr("Descuento") = Math.Round((TxtPUFactura.Text.ToDouble - TxtImporteAjuste.Text.ToDouble) - (CargoActual - CargoAnterior), NumeroDecimales)
Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (Dr("PU").ToString.ToDecimal)) - Dr("Descuento").ToString.ToDecimal
Dr("ImporteIVA") = Math.Round(Dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Dr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
Dr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
Dr("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
Dr("IEPS") = Dr("ImporteIEPS")
If CvePSCargo > 0 AndAlso TmpDT.Select($"CvePS={CvePSCargo}").Length > 0 Then
Dim Dr2 As DataRow = TmpDT.Select($"CvePS={CvePSCargo}")(0)
TmpDT.Rows.Remove(Dr2)
End If
End If
End If
TmpDT.AcceptChanges()
End Sub
Protected Sub ChkAjuste_CheckedChanged(sender As Object, e As EventArgs)
If ChkAjuste.Checked Then
DivAjuste.Visible = True
TxtCantidad.Text = "1"
TxtCantidad.Enabled = False
DivModalVenta.Attributes.Remove("class")
DivModalVenta.Attributes.Add("class", "modal-dialog modal-lg")
DivAjuste.Attributes.Remove("class")
DivAjuste.Attributes.Add("class", "col-md-6")
DivDatosVenta.Attributes.Remove("class")
DivDatosVenta.Attributes.Add("class", "col-md-6")
TxtPrecio.Attributes.Add("onKeyUp", $"CambiaAjuste(this,{TxtPUFactura.ClientID});")
TxtPUFactura.Text = TxtPrecio.Text
Else
DivAjuste.Visible = False
TxtCantidad.Enabled = True
TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();")
DivModalVenta.Attributes.Remove("class")
DivModalVenta.Attributes.Add("class", "modal-dialog")
DivAjuste.Attributes.Remove("class")
DivAjuste.Attributes.Add("class", "col-md-1")
DivDatosVenta.Attributes.Remove("class")
DivDatosVenta.Attributes.Add("class", "col-md-12")
End If
UpModalVenta.Update()
RegistraScript(String.Format("$('#{0}').modal('show');", "DivAddVenta"))
RegistraScript("Recalcula();", "Recalcula")
End Sub
#End Region
#Region "U S A D O S"
Private Sub CreaDTmpDTRecepcionUsados()
TmpDTRecepcionUsados = New DataTable
TmpDTRecepcionUsados.Columns.Add("CvePS", GetType(Integer))
TmpDTRecepcionUsados.Columns.Add("Cantidad", GetType(Decimal))
TmpDTRecepcionUsados.Columns.Add("CveUM", GetType(Integer))
TmpDTRecepcionUsados.Columns.Add("CveVentaDetalle", GetType(Integer))
TmpDTRecepcionUsados.Columns.Add("PU", GetType(Double))
End Sub
Protected Sub BtnRecepcionUsados_Click(sender As Object, e As EventArgs)
TmpDTRecepcionUsados.Clear()
TmpDTRecepcionUsados.AcceptChanges()
Dim TotalCargos As Decimal = 0
Dim TotalCantidad As Decimal = 0
For Each Gvr As GridViewRow In GvRecepcionUsados.Rows
If Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal > 0 Then
TotalCargos += Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal * Gvr.DataKey("Cargo").ToDecimal
TotalCantidad += Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal
Dim Row As DataRow = TmpDTRecepcionUsados.NewRow()
Row("CvePS") = Gvr.DataKey("CvePSCargo").ToEntero
Row("Cantidad") = Gvr.FCTextBox("TxtCantidad").Text.ToString.ToDecimal
Row("CveUM") = Gvr.DataKey("CveUM").ToEntero
Row("CveVentaDetalle") = -1
Row("PU") = Gvr.DataKey("Cargo").ToDouble
TmpDTRecepcionUsados.Rows.Add(Row)
End If
Next
If TotalCantidad > TmpDT.FiltraParametros("EsCargo = True").SUMD("Cantidad") Then
Alert("No puede tener una cantidad mayor a la de los cargos", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
For Each Dr As DataRow In TmpDT.FiltraParametros("EsCargo = True").Rows
Dim TotalAnterior As Decimal = Dr("Cantidad").ToString.ToDecimal * Dr("PU").ToString.ToDecimal
Dim PUActual As Decimal = (TotalAnterior - TotalCargos) / Dr("Cantidad").ToString.ToDecimal
Dim Descuento As Decimal = Dr("Descuento").ToString.ToDecimal
Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (PUActual)) - Descuento
TotalCargos -= TotalAnterior
If PUActual <= 0 Then
Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString)
TmpDT.Rows.Remove(drt(0))
Else
Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString)
Dim drr As DataRow = drt(0)
drr("PU") = PUActual
drr("ImporteIVA") = Math.Round(Dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
drr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
drr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
drr("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
drr("IEPS") = Dr("ImporteIEPS")
drr("Total") = (Dr("Cantidad").ToString.ToDecimal * PUActual)
drr("TotalImporte") = Math.Round(Dr("Cantidad").ToString.ToDecimal * PUActual, NumeroDecimales)
End If
If TotalCargos <= 0 Then
Exit For
End If
Next
TmpDT.AcceptChanges()
If TotalCargos > 0 Then ' cuando se entrega más valor de usados, que los cargos hechos, se descuenta sobre el PU del producto de venta
For Each Dr As DataRow In TmpDT.FiltraParametros("EsCargo = False").Rows
Dim PUAnterior As Decimal = Dr("Cantidad").ToString.ToDecimal * Dr("PU").ToString.ToDecimal
Dim PUActual As Decimal = PUAnterior - (TotalCargos / Dr("Cantidad").ToString.ToDecimal)
Dim Descuento As Decimal = Dr("Descuento").ToString.ToDecimal
Dim TotalCalculableImpuestos As Decimal = (Dr("Cantidad").ToString.ToDecimal * (PUActual)) - Descuento
TotalCargos += -(TotalCargos / Dr("Cantidad").ToString.ToDecimal)
If PUActual <= 0 Then
Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString)
TmpDT.Rows.Remove(drt(0))
Else
Dim drt As DataRow() = TmpDT.Select("Consec = " & Dr("Consec").ToString)
Dim drr As DataRow = drt(0)
drr("PU") = PUActual
drr("ImporteIVA") = Math.Round(Dr("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
drr("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, NumeroDecimales)
drr("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, NumeroDecimales)
drr("ImporteIEPS") = Math.Round(Dr("PorcentajeIEPS").ToString.ToDecimal * TotalCalculableImpuestos, NumeroDecimales)
drr("IEPS") = Dr("ImporteIEPS")
drr("Total") = (Dr("Cantidad").ToString.ToDecimal * PUActual)
drr("TotalImporte") = Math.Round(Dr("Cantidad").ToString.ToDecimal * PUActual, NumeroDecimales)
End If
If TotalCargos <= 0 Then
Exit For
End If
Next
End If
TmpDT.AcceptChanges()
TmpDTRecepcionUsados.AcceptChanges()
CalculaTotalesVenta()
RegistraScript(String.Format("$('#{0}').modal('hide');", "DModalRecepcionUsados"))
EmitirImprimirNew()
End Sub
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, EsCargo:=True)
End If
Next
ObjProductosServicios.Dispose()
End If
ObjAcum.Dispose()
' End If
End Sub
#End Region
End Class