Option Explicit On Option Strict On Imports System.Data Imports System.IO Imports Extensiones Imports Modelos.Factura Partial Class Ventas_PVCobranza Inherits ClsPaginas Private Property CveCliente As Integer Get If ViewState("CveCliente") Is Nothing Then ViewState("CveCliente") = -1 End If Return ViewState("CveCliente").ToString.ToEntero End Get Set(value As Integer) ViewState("CveCliente") = value End Set End Property Private Property TmpDTAnticiposNCIxCCliente As DataTable Get Return If(IsNothing(ViewState("TmpDTAnticiposNCIxCCliente")), Nothing, CType(ViewState("TmpDTAnticiposNCIxCCliente"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDTAnticiposNCIxCCliente") = value End Set End Property Private Property ListaAnticiposAplicados As List(Of Modelos.MAnticipoRelacionado) Get Return If(IsNothing(ViewState("ListaAnticiposAplicados")), Nothing, CType(ViewState("ListaAnticiposAplicados"), List(Of Modelos.MAnticipoRelacionado))) End Get Set(value As List(Of Modelos.MAnticipoRelacionado)) ViewState("ListaAnticiposAplicados") = value End Set End Property Private Property CveCorte As Integer Get Return ViewState("CveCorte").ToString.ToEntero End Get Set(value As Integer) ViewState("CveCorte") = value End Set End Property Private Property DineroCaja As Double Get Return If(IsNothing(ViewState("DineroCaja")), 0, ViewState("DineroCaja").ToString().ToDecimal()) End Get Set(value As Double) ViewState("DineroCaja") = value End Set End Property Private Property CveIE As Integer Get If ViewState("CveIE") Is Nothing Then ViewState("CveIE") = -1 End If Return ViewState("CveIE").ToString.ToEntero End Get Set(value As Integer) ViewState("CveIE") = value End Set End Property Private Property CveTipoTransaccionOriginal As Integer Get If ViewState("CveTipoTransaccionOriginal") Is Nothing Then ViewState("CveTipoTransaccionOriginal") = -1 End If Return ViewState("CveTipoTransaccionOriginal").ToString.ToEntero End Get Set(value As Integer) ViewState("CveTipoTransaccionOriginal") = value End Set End Property Private Property DtCortesVentas As DataTable Get If ViewState("DtCortesVentas") Is Nothing Then ViewState("DtCortesVentas") = New DataTable End If Return CType(ViewState("DtCortesVentas"), DataTable) End Get Set(value As DataTable) ViewState("DtCortesVentas") = value End Set End Property Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then CveCorte = 0 CargaFiltros() CargaDdlPagos() If UsuarioActual.TienePermisoProceso(371) Then CargaCorteCaja() End If If UsuarioActual.CveEmpresa = 189 Then DivDatosCheque.Visible = True End If If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then DivNoTimbradas.Visible = True End If End If End Sub Private Sub CargaFiltros() Dim dtt = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) DdlSubProyecto.DataSource = dtt DdlSubProyecto.DataBind() DdlSucursalCorte.DataSource = dtt.FiltraParametros("EsSucursal = True ") DdlSucursalCorte.DataBind() DdlSucursalCorte.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlSucursalCorte.SelectedValueExist(UsuarioActual.CveSubProyecto) txtFechaI.Text = Now.AddDays(-1).ToShortDateString txtFechaF.Text = Now.ToShortDateString 'DdlCuentaEfectivo.Items.Clear() 'DdlCuentaTarjetaCredito.Items.Clear() 'DdlCuentaTarjetaDebito.Items.Clear() 'DdlCuentaCheque.Items.Clear() 'DdlCuentaTransferencia.Items.Clear() Dim DtCC As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa) Dim CveMon As Integer = 1 'MOSTRAR SOLO CUENTAS DE CONTADO EN BDH 'If UsuarioActual.Empresa.Funcionalidad(531) = "1" Then DdlCuentaEfectivo.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", CveMon)) DdlCuentaCheque.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", CveMon)) 'If UsuarioActual.Empresa.Funcionalidad(558) = "1" OrElse UsuarioActual.Empresa.Funcionalidad(531) = "1" Then DdlCuentaTarjetaCredito.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1 AND TieneTerminal = 1", CveMon)) DdlCuentaTarjetaDebito.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1 AND TieneTerminal = 1", CveMon)) If UsuarioActual.Empresa.Funcionalidad(109) = "1" OrElse UsuarioActual.CveEmpresa.Contiene(195, 197) Then DdlCuentaTransferencia.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(CveMon <= 0, 1, CveMon))) Else DdlCuentaTransferencia.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(CveMon <= 0, 1, CveMon))) End If 'DdlCuentaTransferencia.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", CveMon)) DtCC.Dispose() DdlCuentaEfectivo.DataBind() DdlCuentaTarjetaCredito.DataBind() DdlCuentaTarjetaDebito.DataBind() DdlCuentaCheque.DataBind() DdlCuentaTransferencia.DataBind() DdlCuentaGastoOrigen.DataSource = DtCC.FiltraParametros("CveMoneda = 1 AND CveTipoCuenta = 1") DdlCuentaGastoOrigen.DataBind() DdlCuentaGastoOrigen.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlCuentaGastoDestino.DataSource = DtCC.FiltraParametros("CveMoneda = 1 AND CveTipoCuenta = 1") DdlCuentaGastoDestino.DataBind() DdlCuentaGastoDestino.Items.Insert(0, New ListItem("Seleccione", "-1")) TxtImporteEfectivo.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteCredito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteDebito.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteCheque.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteTransferencia.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtImporteOtrosContado.Attributes.Add("onKeyUp", "CalculaTotalPagoContado();") TxtEfectivoEnCaja.Attributes.Add("onKeyUp", "CalculaDiferencia();") TxtEfectivoCajaBloqueo.Attributes.Add("onKeyUp", "CalculaDiferenciaBloqueo();") End Sub Private Sub CargaCorteCaja() Dim DebeCerrarCorte As Boolean = False 'Checar si hay un Turno Abierto Dim ObjPVenta As New ClsPuntoVenta If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then If ObjPVenta.DtResultados.Rows.Count > 0 Then CveCorte = ObjPVenta.CveCorte Dim FechaICorte As Date = ObjPVenta.FechaInicial.Date '.AddDays(-5) If UsuarioActual.Empresa.Funcionalidad(180) = "1" AndAlso FechaICorte < NowADS().Date Then DebeCerrarCorte = True LblMotivoBloqueo.Text = $"Existe un corte del día {FechaICorte.ToString("dd/MM/yyyy")}. Favor de cerrarlo para iniciar un nuevo corte." Else LblTurno.Text = ObjPVenta.FechaInicial.ToShortDateString BtnIniciarTurno.Visible = False LkbEstadodeCaja.Visible = True LkbIngreso.Visible = True LkbRetiro.Visible = True If UsuarioActual.CveEmpresa = 189 Then LkbRetiro.Visible = False End If UpTurno.Visible = True End If Else UpTurno.Visible = False 'Ingresar un nuevo Turno RegistraScript("window.onload = function MuestraCorteCaja() { document.getElementById(""C_btnShow"").click(); }") End If End If ObjPVenta.Dispose() If DebeCerrarCorte Then CargaDatosCorte() RegistraScript("window.onload = function MuestraPantallaBloqueo() { document.getElementById(""C_btnShowBloqueo"").click(); }") End If End Sub Private Sub CargaDatosCorte() Dim ObjPVenta As New ClsPuntoVenta Dim Total As Double If ObjPVenta.GetVta_Cortes("-1", "-1", UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, 0) Then If ObjPVenta.DtResultados.Rows.Count > 0 Then Total = ObjPVenta.DtResultados(0)("ImporteInicial").ToString.ToDouble + ObjPVenta.DtResultados(0)("VentasEfectivo").ToString().ToDouble + ObjPVenta.DtResultados(0)("Ingresado").ToString().ToDouble - ObjPVenta.DtResultados(0)("Retirado").ToString().ToDouble - ObjPVenta.DtResultados(0)("Devoluciones").ToString().ToDouble DineroCaja = Total LblEfectivoEsperado.Text = Total.FormatoNumero(2) LblEfectivoBloqueo.Text = Total.FormatoNumero(2) Dim Dt As New DataTable Dt.Columns.Add("Descripcion", GetType(String)) Dt.Columns.Add("Importe", GetType(Decimal)) Dim Dr1 As DataRow = Dt.NewRow Dr1("Descripcion") = "Fondo de Caja" Dr1("Importe") = ObjPVenta.DtResultados(0)("ImporteInicial").ToString().ToDouble Dt.Rows.Add(Dr1) Dim Dr2 As DataRow = Dt.NewRow Dr2("Descripcion") = "Ventas en Efectivo" Dr2("Importe") = ObjPVenta.DtResultados(0)("VentasEfectivo").ToString().ToDouble Dt.Rows.Add(Dr2) Dim Dr21 As DataRow = Dt.NewRow Dr21("Descripcion") = "Devoluciones" Dr21("Importe") = ObjPVenta.DtResultados(0)("Devoluciones").ToString().ToDouble Dt.Rows.Add(Dr21) 'Dim Dr3 = Dt.NewRow 'Dr3("Descripcion") = "Propinas" 'Dr3("Importe") = ObjPVenta.DtResultados(0)("Propina").ToString().ToDouble 'Dt.Rows.Add(Dr3) Dim Dr4 As DataRow = Dt.NewRow Dr4("Descripcion") = "Entradas" Dr4("Importe") = ObjPVenta.DtResultados(0)("Ingresado").ToString().ToDouble Dt.Rows.Add(Dr4) Dim Dr5 As DataRow = Dt.NewRow Dr5("Descripcion") = "Salidas" Dr5("Importe") = ObjPVenta.DtResultados(0)("Retirado").ToString().ToDouble Dt.Rows.Add(Dr5) Dim Dr6 As DataRow = 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 CargaDatos() Dim ObjMovtos As New ClsMovimientos() Dim FechaI, FechaF As Date FechaI = If(IsDate(txtFechaI.Text.Trim()), txtFechaI.Text.Trim().ToDate, MinFecha) FechaF = If(IsDate(txtFechaF.Text.Trim()), txtFechaF.Text.Trim().ToDate, MaxFecha).AddDays(1) If ObjMovtos.GetRemisionesCobranza(UsuarioActual.CveEmpresa, DdlSubProyecto.SelectedValue.ToEntero, FechaI, FechaF) Then Dim dtt As DataTable = ObjMovtos.DtResultados.FiltraParametros($"CveVenta > 0 AND (CveUsuarioCobranza IS NULL OR CveUsuarioCobranza = {UsuarioActual.CveUsuario})") 'si hay ya asignado, solo la mostrará Dim Dtta As DataTable = dtt.FiltraParametros($"CveUsuarioCobranza = {UsuarioActual.CveUsuario}") If Dtta IsNot Nothing AndAlso Dtta.Rows.Count > 0 Then dtt = Dtta GvDatos.DataSource = dtt End If ObjMovtos.Dispose() GvDatos.DataBind() UpL.Update() End Sub Private Sub MuestraNoTimbradasCentroCosto() Dim ObjSub As New ClsSubProyectos If ObjSub.GetNoTimbradasCentroCosto(UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then If ObjSub.DtResultados.Rows.Count > 0 Then GvPendientesTimbrar.DataSource = ObjSub.DtResultados.FiltraParametros($"Fecha = '{Now.ToString("dd/MM/yyyy")}'") End If End If ObjSub.Dispose() GvPendientesTimbrar.DataBind() End Sub Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) Handles BtnConsultar.Click LimpiarDatos() If ChkMostrarSoloPagados.Checked Then DVCobraza.Visible = False DVPagado.Visible = True CargaDatosPagos() Else DVCobraza.Visible = True DVPagado.Visible = False CargaDatos() End If MuestraNoTimbradasCentroCosto() End Sub Private Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDatos.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveUsuarioCobranza") <> "" Then e.Row.BackColor = Drawing.ColorTranslator.FromHtml("#3598dc") 'e.Row.CssClass = "blue-madison" End If If e.Row.DBCampo("RemisionEspecial") = "1" Then e.Row.BackColor = Drawing.ColorTranslator.FromHtml("#e9edef") e.Row.ToolTip = "Remisión especial" End If If e.Row.DBCampo("TipoEntrega") = "2" OrElse e.Row.DBCampo("AplicaImpresionPorAnt") = "1" Then e.Row.FCLinkButton("LnkImprimir").Visible = True ScriptManager.GetCurrent(Me).RegisterPostBackControl(e.Row.FCLinkButton("LnkImprimir")) End If If e.Row.DBCampo("AplicaImpresionPorAnt") = "1" Then 'SI TIENE SALDO, QUE APLIQUE EL PAGO If e.Row.DBCampo("Saldo").ToDecimal() > 0 Then e.Row.FCLinkButton("BtnPagar").Visible = True If Not e.Row.DBCampo("TipoEntrega") = "2" Then e.Row.FCLinkButton("LnkImprimir").Visible = False End If Else e.Row.FCLinkButton("BtnPagar").Visible = False End If End If End If End Sub Private Sub GvDatos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvDatos.RowCommand If e.CommandName = "Cobrar" Then LimpiarDatos() Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton) Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow) Dim TieneError As Boolean = False Dim CveVenta As Integer = e.CommandArgument.ToString.ToEntero Dim ObjVentas As New ClsVentas ObjVentas.IniciaTransacSQL() Try If Not ObjVentas.UpdateAsignaVentaCobranza(CveVenta, 1, UsuarioActual.CveUsuario, -1, "", Now) Then TieneError = True End If HdnCveVenta.Value = CveVenta.ToString 'según la forma de pago va a establecer el valor para pago. Select Case GvRow.DataKey("CveFormaPago33") Case "1" TxtImporteEfectivo.Text = GvRow.DataKey("Saldo").FormatoNumero Case "2" TxtImporteCheque.Text = GvRow.DataKey("Saldo").FormatoNumero Case "3" TxtImporteTransferencia.Text = GvRow.DataKey("Saldo").FormatoNumero Case "4" TxtImporteCredito.Text = GvRow.DataKey("Saldo").FormatoNumero Case "18" TxtImporteDebito.Text = GvRow.DataKey("Saldo").FormatoNumero Case Else TxtImporteEfectivo.Text = GvRow.DataKey("Saldo").FormatoNumero End Select TxtImporteContado.Text = GvRow.DataKey("Saldo").FormatoNumero HdnTotal.Value = GvRow.DataKey("Saldo") TxtImporteEfectivo.Focus() LtlNombre.Text = GvRow.DataKey("AtencionA") LtlFolio.Text = GvRow.DataKey("SerieFolio") LtlSaldo.Text = GvRow.DataKey("Saldo").ToDecimal.FormatoNumero If UsuarioActual.CveEmpresa = 189 AndAlso GvRow.DataKey("TipoDocto") = "Rem" Then DivAnticipo.Visible = True ImgAntiPend.Visible = True End If Catch ex As Exception TieneError = True End Try 'carga información para cobranza If Not TieneError Then ObjVentas.Commit() PnlContado.Visible = True Else ObjVentas.RollBack() PnlContado.Visible = False Alert("Hubo un error al asignar datos de cobranza", TipoMensaje.MsgInformacion) End If ObjVentas.Dispose() 'CargaDatos() End If End Sub Private Sub BtnPagar_Click(sender As Object, e As EventArgs) Handles BtnPagar.Click 'registrar pago 'validaciones Dim Pagado As Decimal = TxtImporteEfectivo.Text.ToDecimal + TxtImporteCredito.Text.ToDecimal + TxtImporteDebito.Text.ToDecimal + TxtImporteCheque.Text.ToDecimal + TxtImporteTransferencia.Text.ToDecimal + TxtNCDev.Text.ToDecimal() If Pagado = 0 Then Alert("Favor de especificar importe", TipoMensaje.ToastAdventencia) Exit Sub End If If LtlSaldo.Text.ToDecimal() > Pagado Then Alert("Favor de especificar el saldo total de pagar", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim PagadoSinEfectivo As Decimal = Pagado - TxtImporteEfectivo.Text.ToDecimal Dim tCveCorte As Integer = CveCorte If PagadoSinEfectivo > LtlSaldo.Text.ToDecimal() Then Alert("El pago con los metodos de pago actuales no puede ser mayor al importe de la venta", TipoMensaje.MsgAdvertencia) Exit Sub End If If DivDatosCheque.Visible AndAlso TxtImporteCheque.Text.ToDecimal() > 0 Then If String.IsNullOrEmpty(TxtClaveAutorizacion.Text.Trim()) Then Alert("La clave de autorización es necesaria", TipoMensaje.MsgAdvertencia) Exit Sub End If If String.IsNullOrEmpty(TxtAutorizo.Text.Trim()) Then Alert("El nombre de la persona que autorizó es necesario", TipoMensaje.MsgAdvertencia) Exit Sub End If End If Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero Dim CveVentaRemision As Integer = -1 Dim DbRowVenta As DataRow = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("") End If ObjVentas.Dispose() If DbRowVenta IsNot Nothing Then Dim VentaActual As New Venta(UsuarioActual) VentaActual.CveVenta = CveVenta VentaActual.TipoDocto = DbRowVenta("TipoDocto").ToString VentaActual.Fecha = DbRowVenta("Fecha").ToString.ToDate VentaActual.CveCliente = DbRowVenta("CveCliente").ToString.ToEntero VentaActual.CveMoneda = DbRowVenta("CveMoneda").ToString.ToEntero VentaActual.SerieFolio = DbRowVenta("SerieFolio").ToString VentaActual.ClienteNombre = DbRowVenta("ClienteNombre").ToString VentaActual.TC = DbRowVenta("TipoCambio").ToString.ToDecimal VentaActual.Total = DbRowVenta("Total").ToString.ToDecimal VentaActual.IVA = DbRowVenta("IVA").ToString.ToDecimal VentaActual.IEPS = DbRowVenta("IEPS").ToString.ToDecimal VentaActual.RetIVA = DbRowVenta("RetIVA").ToString.ToDecimal VentaActual.RetISR = DbRowVenta("RetISR").ToString.ToDecimal VentaActual.PorcentajeIVA = DbRowVenta("PorcentajeIVA").ToString.ToDecimal VentaActual.UsuarioActual = UsuarioActual VentaActual.CveSubProyecto = DbRowVenta("CveSubProyecto").ToString.ToEntero If tCveCorte <= 0 AndAlso DbRowVenta("CveCorte").ToString.ToEntero > 0 Then tCveCorte = DbRowVenta("CveCorte").ToString.ToEntero Dim CvePrePoliza As Integer = -1 Dim Fecha As Date = DbRowVenta("Fecha").ToString.ToDate 'NowADS() Dim MsgError As String = "" Dim SaldoPendiente As Decimal = DbRowVenta("Saldo").ToString.ToDecimal Dim SaldoTotalInicial As Decimal = DbRowVenta("Saldo").ToString.ToDecimal Dim PagoAplicado As Decimal = 0 Dim ObjVentas2 As New ClsVentas() Dim ObjIE As New ClsBancos(ObjVentas2.IniciaTransacSQL()) Dim ObjConta As New ClsContabilidad(ObjVentas2.IniciaTransacSQL()) Dim ObjClientes As New ClsClientes(ObjVentas2.IniciaTransacSQL()) Dim respFactura As Modelos.Factura.MMensajeFactura = Nothing Dim respNC As Modelos.Factura.MMensajeFactura = Nothing Dim RegistrarPago As Boolean = True Try 'FACTURAR LA REMISION PARA HACER EL PAGO If UsuarioActual.CveEmpresa.Contiene(189, 197) AndAlso VentaActual.TipoDocto = "Rem" Then CveVentaRemision = HdnCveVenta.Value.ToEntero respFactura = GenerarFactura(VentaActual, ObjVentas2, ObjClientes) If respFactura Is Nothing Then MsgError = "Ocurrió un error al generar la factura" ElseIf (respFactura IsNot Nothing AndAlso respFactura.Mensajes.Count > 0) AndAlso respFactura.TieneError Then MsgError = respFactura.Mensajes(0) End If 'REALIZAR EL PAGO EN LA FACTURA If respFactura IsNot Nothing AndAlso Not respFactura.TieneError Then CveVenta = respFactura.CveVenta If HdnTipoAmortizacion.Value = "4" Then If respFactura.Factura.DtAnticiposAplicados IsNot Nothing Then PagoAplicado += respFactura.Factura.DtAnticiposAplicados.SUM("Importe") SaldoPendiente = SaldoPendiente - PagoAplicado End If End If End If End If 'GENERAR NC PARA AMORTIZACION If MsgError = "" AndAlso UsuarioActual.CveEmpresa.Contiene(189) AndAlso HdnTipoAmortizacion.Value = "2" Then respNC = GenerarNC(VentaActual, ObjVentas2) If respNC IsNot Nothing Then If respNC.TieneError Then CveVenta = -1 If respNC.Mensajes.Count > 0 Then MsgError = respNC.Mensajes(0) Else MsgError = "Ocurrió un error al generar la nota de crédito" End If Else PagoAplicado += respNC.Factura.Total SaldoPendiente = SaldoPendiente - PagoAplicado End If Else MsgError = "Ocurrió un error al generar la nota de crédito" End If End If If MsgError = "" Then If SaldoPendiente > 0 Then If respFactura IsNot Nothing Then CvePrePoliza = respFactura.Factura.CvePrePoliza Else CvePrePoliza = ObjConta.AddPrePolizas("PVCobranza", 11, 0, 0, 1, Fecha, $"Pago {VentaActual.SerieFolio}", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=3) End If If CvePrePoliza > 0 Then If MsgError = "" AndAlso SaldoPendiente > 0 AndAlso TxtImporteCredito.Text.ToDecimal > 0 Then MsgError = RegistraIE(12, DdlCuentaTarjetaCredito.SelectedValue.ToEntero, TxtImporteCredito.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendiente -= TxtImporteCredito.Text.ToDecimal PagoAplicado += TxtImporteCredito.Text.ToDecimal End If If MsgError = "" AndAlso SaldoPendiente > 0 AndAlso TxtImporteDebito.Text.ToDecimal > 0 Then MsgError = RegistraIE(11, DdlCuentaTarjetaDebito.SelectedValue.ToEntero, TxtImporteDebito.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendiente -= TxtImporteDebito.Text.ToDecimal PagoAplicado += TxtImporteDebito.Text.ToDecimal End If If SaldoPendiente > 0 AndAlso TxtImporteCheque.Text.ToDecimal > 0 Then Dim Obs As String = "" If DivDatosCheque.Visible Then Obs = $"{VentaActual.SerieFolio} - Autorizó: {TxtAutorizo.Text}" End If MsgError = RegistraIE(3, DdlCuentaCheque.SelectedValue.ToEntero, TxtImporteCheque.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, Obs:=Obs, CveAutorizacion:=TxtClaveAutorizacion.Text.Trim(), CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendiente -= TxtImporteCheque.Text.ToDecimal PagoAplicado += TxtImporteCheque.Text.ToDecimal End If If MsgError = "" AndAlso SaldoPendiente > 0 AndAlso TxtImporteTransferencia.Text.ToDecimal > 0 Then MsgError = RegistraIE(8, DdlCuentaTransferencia.SelectedValue.ToEntero, TxtImporteTransferencia.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendiente -= TxtImporteTransferencia.Text.ToDecimal PagoAplicado += TxtImporteTransferencia.Text.ToDecimal End If If MsgError = "" AndAlso SaldoPendiente > 0 AndAlso TxtImporteEfectivo.Text.ToDecimal > 0 Then Dim PagoEfectivo As Decimal = TxtImporteEfectivo.Text.ToDecimal PagoAplicado += PagoEfectivo If PagoAplicado >= SaldoTotalInicial Then TxtCambio.Text = (PagoAplicado - SaldoTotalInicial).FormatoNumero PagoEfectivo = SaldoPendiente End If MsgError = RegistraIE(13, DdlCuentaEfectivo.SelectedValue.ToEntero, PagoEfectivo, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendiente -= PagoEfectivo End If If SaldoPendiente > 0 Then MsgError = "Tiene saldo pendiente por aplicar" End If If UsuarioActual.CveRol <> 1 Then If MsgError = "" AndAlso Not ObjVentas2.UpdateVentaCorte(CveVenta, UsuarioActual.CveEmpresa, tCveCorte) Then MsgError = "Error al aplicar el corte" End If End If If MsgError = "" AndAlso Not ObjVentas2.UpdateVentaTicketImpreso(CveVenta, 0) Then MsgError = "No se pudo desmarcar la impresión" End If If CveVentaRemision > 0 Then If MsgError = "" AndAlso Not ObjVentas2.UpdateVentaTicketImpreso(CveVentaRemision, 0) Then MsgError = "No se pudo desmarcar la impresión" End If End If Else MsgError = "Error al registrar prepólizas" End If Else 'SI NO TIENE SALDO PENDIENTE NO GENERAR POLIZA PARA EL PAGO RegistrarPago = False End If End If Catch ex As Exception MsgError = "Error al registrar el pago" GuardaLog(ex.ToString()) End Try If MsgError = "" Then ObjVentas2.Commit() Dim msBuild As New StringBuilder() Dim MsgTimbrado As String = "" 'SI SE GENERO FACTURA DE INGRESO, TIMBRARLA DESPUES DE REALIZAR EL PAGO If respFactura IsNot Nothing Then 'VERIFICA SI SE GENERO NC If respNC IsNot Nothing Then AjustarTimbre(respFactura.Factura, respNC.Factura) MsgTimbrado = TimbrarFactura(respFactura.Factura, respNC.Factura) Else AjustarTimbre(respFactura.Factura, Nothing) MsgTimbrado = TimbrarFactura(respFactura.Factura, Nothing) End If End If If respFactura IsNot Nothing Then If RegistrarPago Then msBuild.Append($"Pago Registrado correctamente.") End If For Each m In respFactura.Mensajes msBuild.AppendFormat("
{0}", m) Next If respNC IsNot Nothing Then For Each m In respNC.Mensajes msBuild.AppendFormat("
{0}", m) Next End If Else msBuild.Append($"Pago Registrado correctamente.

Imprimir ticket") End If If Not String.IsNullOrEmpty(MsgTimbrado) Then msBuild.AppendFormat("
{0}", MsgTimbrado) End If Alert(msBuild.ToString(), TipoMensaje.MsgInformacion) Else ObjVentas2.RollBack() Alert(MsgError, TipoMensaje.MsgError) End If ObjVentas2.Dispose() ObjConta.Dispose() ObjIE.Dispose() ObjClientes.Dispose() If MsgError = "" Then Try If UsuarioActual.Empresa.Funcionalidad(109) = "1" Then ImpresionDirectaPDF(CveVenta) End If LimpiarDatos() CargaDatos() Catch ex As Exception GuardaLog(ex.ToString()) End Try End If Else Alert("Ocurrió un error al cargar la venta", TipoMensaje.MsgError) End If End Sub Private Sub LimpiarDatos() PnlContado.Visible = False TxtImporteEfectivo.Text = "" TxtImporteCredito.Text = "" TxtImporteDebito.Text = "" TxtImporteCheque.Text = "" TxtImporteTransferencia.Text = "" TxtImporteOtrosContado.Text = "" TxtCambio.Text = "" TxtClaveAutorizacion.Text = "" TxtAutorizo.Text = "" TxtNCDev.Text = "" LtlTipoAnticipo.Text = "" HdnTipoAmortizacion.Value = "" CveCliente = -1 If TmpDTAnticiposNCIxCCliente IsNot Nothing Then TmpDTAnticiposNCIxCCliente.Clear() TmpDTAnticiposNCIxCCliente = Nothing End If If ListaAnticiposAplicados IsNot Nothing Then ListaAnticiposAplicados.Clear() ListaAnticiposAplicados = Nothing End If ImgAntiPend.Visible = False DivAnticipo.Visible = False UpL.Update() End Sub Private Function GenerarFactura(ByRef VentaRemision As Venta, ByRef ObjVentas As ClsVentas, ByRef ObjClientes As ClsClientes) As Modelos.Factura.MMensajeFactura Dim Retorno As Modelos.Factura.MMensajeFactura = Nothing Dim DtRemisiones As New DataTable DtRemisiones.Columns.Add(New DataColumn("CveVenta", GetType(Integer))) DtRemisiones.Columns.Add(New DataColumn("SerieFolio", GetType(String))) DtRemisiones.Rows.Add({VentaRemision.CveVenta, VentaRemision.SerieFolio}) Dim RemisionesLista As New List(Of Integer) RemisionesLista.Add(VentaRemision.CveVenta) Dim DtRemisionesPS As New DataTable() Dim DtPagosFacturaGlobal As New DataTable() If ObjClientes.GetVentasRemisionesTotales(VentaRemision.CveCliente, VentaRemision.CveVenta.ToString(), 1, UsuarioActual.CveEmpresa) Then DtRemisionesPS = ObjClientes.DtResultados.Copy() End If Dim ObjFactura = Modelos.Factura.CrearVentaNueva(UsuarioActual, VentaRemision.CveSubProyecto, VentaRemision.CveCliente, VentaRemision.CveMoneda, "Ing") ObjFactura.RemisionesLista = RemisionesLista ObjFactura.DtRemisionesPS = DtRemisionesPS ObjFactura.DtRemisiones = DtRemisiones Dim DtPagos As DataTable = New DataTable("DtPagosFactura") DtPagos.Columns.Add(New DataColumn("CveFormaPago", GetType(Integer))) DtPagos.Columns.Add(New DataColumn("Importe", GetType(Decimal))) If TxtImporteCredito.Text.ToDecimal > 0 Then DtPagos.Rows.Add({4, TxtImporteCredito.Text.ToDecimal}) End If If TxtImporteDebito.Text.ToDecimal > 0 Then DtPagos.Rows.Add({18, TxtImporteDebito.Text.ToDecimal}) End If If TxtImporteCheque.Text.ToDecimal > 0 Then DtPagos.Rows.Add({2, TxtImporteCheque.Text.ToDecimal}) End If If TxtImporteTransferencia.Text.ToDecimal > 0 Then DtPagos.Rows.Add({3, TxtImporteTransferencia.Text.ToDecimal}) End If If TxtImporteEfectivo.Text.ToDecimal > 0 Then DtPagos.Rows.Add({1, TxtImporteEfectivo.Text.ToDecimal}) End If Dim PagoMaximo = DtPagos.MAX("Importe") Dim CveFormaPago As Integer = DtPagos.FiltroPrimeroValor("CveFormaPago", $"Importe = {PagoMaximo}").ToEntero() If CveFormaPago > 0 Then ObjFactura.CveFormaPago33 = CveFormaPago ObjFactura.CveMetodoPago33 = 1 End If For Each Dr As DataRow In ObjFactura.DtRemisionesPS.Rows ObjFactura.AgregarPS(Dr("CvePS").ToString().ToEntero(), Dr("Cantidad").ToString().ToDecimal(), Dr("PU").ToString().ToDecimal(), Dr("Descuento").ToString().ToDecimal, Dr("Obs").ToString(), CveUM:=Dr("CveUM").ToString().ToEntero(), CveProyecto:=Dr("CveProyecto").ToString().ToEntero(), CveSubProyecto:=Dr("CveSubProyecto").ToString().ToEntero(), CveVentaDetallePadre:=Dr("CveVentaDetalle").ToString().ToEntero(), CveVentaDetalleRemision:=Dr("CveVentaDetalle").ToString().ToEntero(), PorcentajeIVA:=Dr("PorcentajeIVA").ToString().ToDecimal()) Next If UsuarioActual.Empresa.Funcionalidad(567) = "1" Then ObjFactura.GenerarSalidaAlmacen = True ObjFactura.DtInventario = ObjFactura.DtDetalle.FiltraParametros("CveTipoPS = 2").Copy() ObjFactura.CveAlmacen = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveAlmacen", $"CveTipoAlmacen = 1 AND CveSubProyecto = {VentaRemision.CveSubProyecto}", "Orden").ToString().ToEntero() End If ObjFactura.CalculaTotales() ObjFactura.PreparaTimbre() If HdnTipoAmortizacion.Value = "4" Then Dim DtAnticipos As New DataTable() DtAnticipos.Columns.Add("CveVenta", GetType(Integer)) DtAnticipos.Columns.Add("Importe", GetType(Decimal)) DtAnticipos.Columns.Add("CveConceptoContable", GetType(Integer)) DtAnticipos.Columns.Add("CveIE", GetType(Integer)) DtAnticipos.Columns.Add("FolioFiscal", GetType(String)) DtAnticipos.Columns.Add("Descuentos", GetType(Decimal)) DtAnticipos.Columns.Add("TotalAnticipo", GetType(Decimal)) DtAnticipos.Columns.Add("SubTotalAnticipo", GetType(Decimal)) DtAnticipos.Columns.Add("CveMoneda", GetType(Decimal)) DtAnticipos.Columns.Add("Fecha", GetType(DateTime)) DtAnticipos.Columns.Add("TipoCambioPago", GetType(Decimal)) DtAnticipos.Columns.Add("Folio", GetType(String)) For Each GvRow As GridViewRow In GVAnticipos.Rows If GvRow.FCCheckBox("Chk" & GvRow.RowIndex) IsNot Nothing AndAlso GvRow.FCCheckBox("Chk" & GvRow.RowIndex).Checked Then Dim CveVenta = GvRow.DataKey("CveVenta").ToEntero() Dim Importe = GvRow.FCTextBox(String.Format("TxtAnticipo{0}", GvRow.RowIndex)).Text.ToDecimal() Dim CveConceptoContable = GvRow.DataKey("CveConceptoContable").ToEntero() Dim CveIE = GvRow.DataKey("CveIE").ToEntero() Dim FolioFiscal = GvRow.DataKey("FolioFiscal") Dim Descuentos As Decimal = GvRow.DataKey("Descuentos").ToDecimal() Dim TotalAnticipo As Decimal = GvRow.DataKey("TotalAnticipo").ToDecimal() Dim SubTotalAnticipo As Decimal = GvRow.DataKey("SubTotalAnticipo").ToDecimal() Dim CveMoneda As Integer = GvRow.DataKey("CveMoneda").ToEntero() Dim Fecha As DateTime = GvRow.DataKey("Fecha").ToDateTime() Dim TipoCambioPago As Decimal = GvRow.DataKey("TipoCambioPago").ToDecimal() Dim Folio = GvRow.DataKey("Folio") DtAnticipos.Rows.Add(CveVenta, Importe, CveConceptoContable, CveIE, FolioFiscal, Descuentos, TotalAnticipo, SubTotalAnticipo, CveMoneda, Fecha, TipoCambioPago, Folio) End If Next ObjFactura.EsNCAmortizacion = True ObjFactura.CveTipoAmortizacionAnticipo = 4 ObjFactura.DtAnticiposAplicados = DtAnticipos End If Dim SbAlert As New StringBuilder() Try Retorno = ObjFactura.EmitirFactura(False, Transac:=ObjVentas.IniciaTransacSQL(), Modulo:="Cobranza/GuardarVenta", MostrarURL:=True) Retorno.Factura = ObjFactura If Retorno IsNot Nothing AndAlso Retorno.CveVenta > 0 Then For Each msg In Retorno.Mensajes SbAlert.AppendFormat("{0}
", msg) Next SbAlert.AppendFormat("
", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", Retorno.CveVenta))) Else SbAlert.Append("Ocurrió un error al generar la factura") End If Catch ex As Exception SbAlert.Append("Ocurrió un error al generar el documento") GuardaLog(ex.ToString()) End Try If Retorno IsNot Nothing AndAlso Retorno.Mensajes IsNot Nothing AndAlso Retorno.Mensajes.Count > 0 Then Retorno.Mensajes.Clear() Retorno.Mensajes.Add(SbAlert.ToString()) If Not Retorno.TieneError Then 'CONVERTIR LA REMISION EN OBJETO DE FACTURA DE INGRESO, PARA HACER EL PAGO EN LA FACTURA VentaRemision = Nothing If ObjVentas.GetVenta(Retorno.CveVenta, UsuarioActual.CveEmpresa) Then Dim DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("") If DbRowVenta IsNot Nothing Then Dim VentaActual As New Venta(UsuarioActual) VentaActual.CveVenta = Retorno.CveVenta VentaActual.TipoDocto = DbRowVenta("TipoDocto").ToString VentaActual.Fecha = DbRowVenta("Fecha").ToString.ToDate VentaActual.CveCliente = DbRowVenta("CveCliente").ToString.ToEntero VentaActual.CveMoneda = DbRowVenta("CveMoneda").ToString.ToEntero VentaActual.SerieFolio = DbRowVenta("SerieFolio").ToString VentaActual.ClienteNombre = DbRowVenta("ClienteNombre").ToString VentaActual.TC = DbRowVenta("TipoCambio").ToString.ToDecimal VentaActual.Total = DbRowVenta("Total").ToString.ToDecimal VentaActual.IVA = DbRowVenta("IVA").ToString.ToDecimal VentaActual.IEPS = DbRowVenta("IEPS").ToString.ToDecimal VentaActual.RetIVA = DbRowVenta("RetIVA").ToString.ToDecimal VentaActual.RetISR = DbRowVenta("RetISR").ToString.ToDecimal VentaActual.PorcentajeIVA = DbRowVenta("PorcentajeIVA").ToString.ToDecimal VentaActual.UsuarioActual = UsuarioActual VentaActual.CveSubProyecto = DbRowVenta("CveSubProyecto").ToString.ToEntero VentaRemision = VentaActual End If End If End If Else Retorno = New Modelos.Factura.MMensajeFactura() Retorno.TieneError = True If SbAlert.Length = 0 Then SbAlert.Append("Ocurrió un error al generar la factura") End If Retorno.Mensajes.Add(SbAlert.ToString()) End If Return Retorno End Function Private Function GenerarNC(ByRef Venta As Venta, ByRef ObjVentas As ClsVentas) As Modelos.Factura.MMensajeFactura Dim Retorno As Modelos.Factura.MMensajeFactura = Nothing Dim ObjNC = Modelos.Factura.CrearVentaNueva(UsuarioActual, Venta.CveSubProyecto, Venta.CveCliente, Venta.CveMoneda, "Egs") Dim Total As Decimal = TxtNCDev.Text.ToDecimal() Dim subTotal As Decimal = (Total / (1D + Venta.PorcentajeIVA)) 'Dim IVA = (subTotal * Factura.PorcentajeIVA).RoundSQL(2) Dim PU As Decimal = subTotal Dim Cantidad As Decimal = 1D Dim Descuento As Decimal = 0 Dim Obs = "" ObjNC.AgregarPS(DdlNCPSAnt.SelectedValue.ToEntero(), Cantidad, PU, Descuento, Obs, CveSubProyecto:=Venta.CveSubProyecto, PorcentajeIVA:=Venta.PorcentajeIVA) ObjNC.CalculaTotales() Dim DtVentasNC = New DataTable DtVentasNC.Columns.Add("CveVenta", GetType(Integer)) DtVentasNC.Columns.Add("Importe", GetType(Decimal)) DtVentasNC.Columns.Add("FolioFiscal", GetType(String)) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TC", .DataType = GetType(Decimal), .DefaultValue = 1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TCCambioValuacion", .DataType = GetType(Decimal), .DefaultValue = 1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "CveEstatusFactura", .DataType = GetType(Integer), .DefaultValue = -1}) DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "Folio", .DataType = GetType(String), .DefaultValue = ""}) DtVentasNC.Rows.Add(Venta.CveVenta, Total, "") ObjNC.DtVentasNC = DtVentasNC Dim DtVentasRelacionadas As New DataTable() DtVentasRelacionadas.Columns.Add("CveVenta", GetType(Integer)) DtVentasRelacionadas.Rows.Add(Venta.CveVenta) ObjNC.DtVentasRelacionadas = DtVentasRelacionadas Dim DtAnticipos As New DataTable() DtAnticipos.Columns.Add("CveVenta", GetType(Integer)) DtAnticipos.Columns.Add("Importe", GetType(Decimal)) DtAnticipos.Columns.Add("CveConceptoContable", GetType(Integer)) DtAnticipos.Columns.Add("CveIE", GetType(Integer)) DtAnticipos.Columns.Add("FolioFiscal", GetType(String)) DtAnticipos.Columns.Add("Descuentos", GetType(Decimal)) DtAnticipos.Columns.Add("TotalAnticipo", GetType(Decimal)) DtAnticipos.Columns.Add("SubTotalAnticipo", GetType(Decimal)) DtAnticipos.Columns.Add("CveMoneda", GetType(Decimal)) DtAnticipos.Columns.Add("Fecha", GetType(DateTime)) DtAnticipos.Columns.Add("TipoCambioPago", GetType(Decimal)) DtAnticipos.Columns.Add("Folio", GetType(String)) For Each GvRow As GridViewRow In GVAnticipos.Rows If GvRow.FCCheckBox("Chk" & GvRow.RowIndex) IsNot Nothing AndAlso GvRow.FCCheckBox("Chk" & GvRow.RowIndex).Checked Then Dim CveVenta = GvRow.DataKey("CveVenta").ToEntero() Dim Importe = GvRow.FCTextBox(String.Format("TxtAnticipo{0}", GvRow.RowIndex)).Text.ToDecimal() Dim CveConceptoContable = GvRow.DataKey("CveConceptoContable").ToEntero() Dim CveIE = GvRow.DataKey("CveIE").ToEntero() Dim FolioFiscal = GvRow.DataKey("FolioFiscal") Dim Descuentos As Decimal = GvRow.DataKey("Descuentos").ToDecimal() Dim TotalAnticipo As Decimal = GvRow.DataKey("TotalAnticipo").ToDecimal() Dim SubTotalAnticipo As Decimal = GvRow.DataKey("SubTotalAnticipo").ToDecimal() Dim CveMoneda As Integer = GvRow.DataKey("CveMoneda").ToEntero() Dim Fecha As DateTime = GvRow.DataKey("Fecha").ToDateTime() Dim TipoCambioPago As Decimal = GvRow.DataKey("TipoCambioPago").ToDecimal() Dim Folio = GvRow.DataKey("Folio") DtAnticipos.Rows.Add(CveVenta, Importe, CveConceptoContable, CveIE, FolioFiscal, Descuentos, TotalAnticipo, SubTotalAnticipo, CveMoneda, Fecha, TipoCambioPago, Folio) End If Next ObjNC.EsNCAmortizacion = True ObjNC.CveTipoAmortizacionAnticipo = 2 ObjNC.DtAnticiposAplicados = DtAnticipos ObjNC.PreparaTimbre() Dim SbAlert As New StringBuilder() Try Retorno = ObjNC.EmitirFactura(False, Transac:=ObjVentas.IniciaTransacSQL(), Modulo:="Cobranza/GuardarVenta", MostrarURL:=True) Retorno.Factura = ObjNC If Retorno IsNot Nothing AndAlso Retorno.CveVenta > 0 Then For Each msg In Retorno.Mensajes SbAlert.AppendFormat("{0}
", msg) Next SbAlert.AppendFormat("
", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", Retorno.CveVenta))) Else SbAlert.Append("Ocurrió un error al generar la nota de crédito") End If Catch ex As Exception SbAlert.Append("Ocurrió un error al generar el documento") GuardaLog(ex.ToString()) End Try Return Retorno End Function Private Sub AjustarTimbre(ByRef ObjFactura As Modelos.Factura, ByRef ObjNC As Modelos.Factura) ObjFactura.Timbre.CFDIRelacionados.UUID.Clear() If HdnTipoAmortizacion.Value = "2" Then Dim Anticipos = ListaAnticiposAplicados.Where(Function(Obj) Obj.Tipo = "Ant") If Anticipos IsNot Nothing AndAlso Anticipos.Count() > 0 Then For Each Ant As Modelos.MAnticipoRelacionado In Anticipos ObjFactura.Timbre.CFDIRelacionados.UUID.Add(Ant.FolioFiscal) Next ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07" ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" 'AJUSTAR NC If ObjNC IsNot Nothing Then ObjNC.Timbre.CFDIRelacionados.UUID.Clear() ObjNC.Timbre.CFDIRelacionados.TipoRelacion = "07" ObjNC.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" End If End If End If 'DEVOLUCIONES DE OTRA VENTA, APLICADAS EN UNA NUEVA If HdnTipoAmortizacion.Value = "4" Then Dim DevolucionesNC = ListaAnticiposAplicados.Where(Function(Obj) Obj.Tipo = "NC") If DevolucionesNC IsNot Nothing AndAlso DevolucionesNC.Count() > 0 Then For Each Ant As Modelos.MAnticipoRelacionado In DevolucionesNC ObjFactura.Timbre.CFDIRelacionados.UUID.Add(Ant.FolioFiscal) Next 'TEMPORAL- DEBE SER TIPO RELACION "01 - Nota de crédito de los documentos relacionados" Dim CveTipoRelacion As Integer = 1 ObjFactura.CveTipoRelacion = CveTipoRelacion Dim RowTipoRelacion As DataRow = GlobalDTVtaTiposRelacion().FiltroPrimero($"CveTipoRelacion = {CveTipoRelacion}") ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = RowTipoRelacion("SATClaveTipoRelacion").ToString() ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = RowTipoRelacion("SATTipoRelacion").ToString() End If End If End Sub Private Function TimbrarFactura(ByRef ObjFactura As Modelos.Factura, ByRef ObjNC As Modelos.Factura) As String Dim MsgErrorTimbrado As String = "" Dim SeTimbro As Boolean = False Dim ObjTimbrado As New Timbrado Try SeTimbro = ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) Dim FolioFiscalFactura As String = ObjTimbrado.UUID MsgErrorTimbrado = ObjTimbrado.MensajeErrorCFDI ObjTimbrado = Nothing If SeTimbro AndAlso ObjNC IsNot Nothing Then If ObjNC.Timbre IsNot Nothing Then ObjNC.Timbre.CFDIRelacionados.UUID.Clear() ObjNC.Timbre.CFDIRelacionados.UUID.Add(FolioFiscalFactura) Dim ObjTimbradoNC As New Timbrado Dim TimbroNC As Boolean = ObjTimbradoNC.TimbrarFactura(UsuarioActual, ObjNC) If Not TimbroNC Then MsgErrorTimbrado = ObjTimbradoNC.MensajeErrorCFDI End If ObjTimbradoNC = Nothing End If End If Catch ex As Exception OnError("Ocurrió un error al generar el timbrado", ex) End Try Return MsgErrorTimbrado End Function Private Function RegistraIE(Metodo As Integer, CveBancoCuenta As Integer, ImportePago As Decimal, Fecha As Date, CvePrePoliza As Integer, VentaActual As Venta, ByRef ObjIE As ClsBancos, ByRef ObjConta As ClsContabilidad, ByRef ObjVentas As ClsVentas, tCveCorte As Integer, Optional Obs As String = "", Optional CveAutorizacion As String = "", Optional CveSubProyecto As Integer = -1) As String Dim Retorno As String = "" Dim CveIEPago As Integer = 0 Dim ErrorConta As Boolean If String.IsNullOrEmpty(Obs) Then Obs = VentaActual.SerieFolio End If CveIEPago = ObjIE.AddBancos_IE(CveBancoCuenta, Metodo, Fecha, "-1", VentaActual.ClienteNombre, ImportePago, 1, 1, Obs, "", False, True, 0, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=tCveCorte, CveAutorizacion:=CveAutorizacion, CveSubProyecto:=CveSubProyecto) If CveIEPago > 0 Then Dim Pago As New VentaPago Pago.ImportePagoVenta = ImportePago Pago.ImportePago = ImportePago Pago.CveIE = CveIEPago Pago.CveMonedaPago = VentaActual.CveMoneda Pago.Fecha = NowADS() Pago.Referencia = VentaActual.SerieFolio ErrorConta = AplicaPrePolizaPagoVenta(VentaActual, Pago, CvePrePoliza, ObjConta) If ErrorConta Then Retorno = "Error en aplicación de pago" End If Dim MetodoPago As Integer = If(Metodo = 13, 1, If(Metodo = 12, 4, If(Metodo = 11, 5, If(Metodo = 3, 2, 3)))) If Not ErrorConta AndAlso Not ObjVentas.AddVta_VentaPago(VentaActual.CveVenta, MetodoPago, ImportePago) Then Retorno = "Error en aplicación de pago.." ErrorConta = True End If Else Retorno = "Pago en Bancos no registrado" ErrorConta = True End If Return Retorno End Function Protected Sub BtnCerrarCaja_Click(sender As Object, e As EventArgs) RegistraScript("$('#DivEstadoCaja').modal('hide')") RegistraScript("$('#DivTerminarCorte').modal()", "divterminarcorte") End Sub Protected Sub LkbIngreso_Click(sender As Object, e As EventArgs) CargaIngresoEgreso(1) End Sub Public Sub CargaIngresoEgreso(Opcion As Integer) RegistraScript("$('#DivIngresoEgreso').modal()") If Opcion = 1 Then LblTituloIE.Text = "Ingreso de Efectivo: " HdnTipoMovimiento.Value = "1" ElseIf Opcion = 0 Then LblTituloIE.Text = "Retiro de Efectivo: " HdnTipoMovimiento.Value = "0" End If UpIngresoEgreso.Update() End Sub Protected Sub LkbRetiro_Click(sender As Object, e As EventArgs) CargaIngresoEgreso(0) End Sub Private Sub LkbEstadodeCaja_Click(sender As Object, e As EventArgs) Handles LkbEstadodeCaja.Click CargaDatosCorte() CargaVentasPago() CargaEntradasSalidas() RegistraScript("$('#DivEstadoCaja').modal()") 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 ClsVentas '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 Function ValidaCobranza() As Boolean Dim Respuesta As Boolean = False If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then Dim ObjMovtos As New ClsMovimientos() Dim FechaI, FechaF As Date FechaI = If(IsDate(txtFechaI.Text.Trim()), txtFechaI.Text.Trim().ToDate, MinFecha) FechaF = If(IsDate(txtFechaF.Text.Trim()), txtFechaF.Text.Trim().ToDate, MaxFecha).AddDays(1) If ObjMovtos.GetRemisionesCobranza(UsuarioActual.CveEmpresa, DdlSubProyecto.SelectedValue.ToEntero(), FechaI, FechaF) Then Dim dtt As DataTable = ObjMovtos.DtResultados.FiltraParametros($"CveVenta > 0 AND (CveUsuarioCobranza IS NULL OR CveUsuarioCobranza = {UsuarioActual.CveUsuario}) AND TipoDocto IN ('Ing','Rem') AND RemisionEspecial = 0") 'Dim Dtta As DataTable = dtt.FiltraParametros($"CveUsuarioCobranza = {UsuarioActual.CveUsuario} ") 'If Dtta IsNot Nothing AndAlso Dtta.Rows.Count > 0 Then dtt = Dtta If dtt.Rows.Count = 0 Then Respuesta = True Else Respuesta = False Alert("No se puede realizar el cerrar el turno, ya que hay cobros pendientes por aplicar.", TipoMensaje.MsgAdvertencia) End If Else Alert("Error al consultarcobros pendientes.", TipoMensaje.MsgAdvertencia) Respuesta = False End If ObjMovtos.Dispose() Else Respuesta = True End If Return Respuesta End Function Private Sub BtnCerrarTurno_Click(sender As Object, e As EventArgs) Handles BtnCerrarTurno.Click 'validar. ' que no existan movimientos pendientes de pago. ' que no halla facturas pendientes de cancelación. ' no facturar remisiones de días anteriores If ValidaCobranza() Then Dim ObjPVenta As New ClsPuntoVenta If TxtEfectivoEnCaja.Text.Trim <> "" Then If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoEnCaja.Text.ToDouble, LblDiferenciaCaja.Text.ToDouble, NowADS(), 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 As String = "document.location.href=""/Ventas/PVCobranza.aspx"";" Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga) End If End If ObjPVenta.Dispose() End If End Sub Private Sub BtnCerrarBloqueo_Click(sender As Object, e As EventArgs) Handles BtnCerrarBloqueo.Click Dim ObjPVenta As New ClsPuntoVenta If TxtEfectivoCajaBloqueo.Text.Trim <> "" Then If ObjPVenta.UpdateFinalizadoVtaCortes(CveCorte, TxtEfectivoCajaBloqueo.Text.ToDouble, LblDiferenciaCajaBloqueo.Text.ToDouble, NowADS(), 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 As String = "document.location.href=""/Ventas/PVCobranza.aspx"";" Alert("Se ha cerrado el turno correctamente.", TipoMensaje.MsgInformacion, Liga) End If Else Alert("Debe especificar el efectivo en caja", TipoMensaje.MsgAdvertencia) RegistraScript("window.onload = function MuestraPantallaBloqueo() { document.getElementById(""C_btnShowBloqueo"").click(); }") End If ObjPVenta.Dispose() End Sub Private Sub BtnIniciarTurno_Click(sender As Object, e As EventArgs) Handles BtnIniciarTurno.Click If DdlSucursalCorte.SelectedValue.ToEntero() <= 0 Then Alert("Debe seleccionar una sucursal.", TipoMensaje.ToastAdventencia) RegistraScript("window.onload = function MuestraCorteCaja() { document.getElementById(""C_btnShow"").click(); }") Exit Sub End If Dim ObjPVenta As New ClsPuntoVenta ObjPVenta.AddVtaCortes(NowADS(), TxtDineroCaja.Text.ToDecimal, UsuarioActual.CveUsuario, "", DdlSucursalCorte.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) CveCorte = ObjPVenta.CveCorte LblTurno.Text = NowADS().ToShortDateString UpTurno.Visible = True LkbEstadodeCaja.Visible = True LkbIngreso.Visible = True LkbRetiro.Visible = True BtnIniciarTurno.Visible = False ObjPVenta.Dispose() If UsuarioActual.CveEmpresa = 189 Then LkbRetiro.Visible = False End If RegistraScript("$('#DivCorteDeCaja').hide();") UpTurno.Update() End Sub Private Sub BtnAceptarIE_Click(sender As Object, e As EventArgs) Handles BtnAceptarIE.Click If TxtCantidadIE.Text.ToEntero() <= 0 Then Alert("La cantidad debe ser mayor a 0", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim TieneError As Boolean = False Dim ObjPVenta As New ClsPuntoVenta Dim ObjIE As New ClsBancos(ObjPVenta.IniciaTransacSQL()) Dim ObjMov As New ClsContabilidad(ObjPVenta.IniciaTransacSQL()) Dim documentos As String = "" Try Dim CveMoneda As Integer = 1 Dim TipoCambio As Decimal = 1D Dim Importe As Decimal = TxtCantidadIE.Text.ToDecimal() If Not ObjPVenta.AddVta_MovimientosCajas(CveCorte, UsuarioActual.CveUsuario, Importe, TxtDescripcionIE.Text, HdnTipoMovimiento.Value.ToEntero(), NowADS()) Then TieneError = True End If If ChkAplicaGasto.Checked Then documentos = "Los Depósitos se realizaron exitosamente

" Dim CvePrePoliza = ObjMov.AddPrePolizas("PVCobranza/Gasto ", 23, Importe, Importe, CveMoneda, Now, "Gasto", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) 'TRANSFERENCIA BANCARIA Dim EsAbonoEnCuenta As Boolean = False Dim AplicaImpuestos As Boolean = False Dim FolioOrigen As Long = ObjIE.GetNextFolio(DdlCuentaGastoOrigen.SelectedValue.ToEntero, 2) Dim FolioDestino As Long = ObjIE.GetNextFolio(DdlCuentaGastoOrigen.SelectedValue.ToEntero, 8) Dim CveIEDestino As Integer = -1 Dim CveIEOrigen = ObjIE.AddBancos_IE(DdlCuentaGastoOrigen.SelectedValue.ToEntero, 2, Now, FolioOrigen.ToString(), "", Importe, CveMoneda, TipoCambio, TxtDescripcionIE.Text.Trim(), "", EsAbonoEnCuenta, AplicaImpuestos, -1, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=Me.CveCorte) If CveIEOrigen > 0 Then documentos += String.Format("IE Salida: {1}    
", CveIEOrigen, FolioOrigen) CveIEDestino = ObjIE.AddBancos_IE(DdlCuentaGastoDestino.SelectedValue.ToEntero, 8, Now, FolioDestino.ToString(), "", Importe, CveMoneda, TipoCambio, TxtDescripcionIE.Text.Trim(), "", EsAbonoEnCuenta, AplicaImpuestos, -1, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=Me.CveCorte) If CveIEDestino > 0 Then documentos += String.Format("IE Entrada: {1}    
", CveIEDestino, FolioDestino) Else TieneError = True End If Else TieneError = True End If If Not TieneError Then Dim TipoMovimiento As Boolean = True If ObjMov.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, Importe, Importe, 30, FolioOrigen.ToString(), FolioOrigen.ToString(), CveIE:=CveIEOrigen) Then If Not ObjMov.AddPrePolizasDetalle(CvePrePoliza, Not TipoMovimiento, Importe, Importe, 30, FolioDestino.ToString(), FolioDestino.ToString(), CveIE:=CveIEDestino) Then TieneError = True End If Else TieneError = True End If End If End If Catch ex As Exception TieneError = True GuardaLog(ex.ToString()) End Try If TieneError Then documentos = "" ObjPVenta.RollBack() Alert("Ocurrió un error al generar el movimiento", TipoMensaje.MsgError) Else ObjPVenta.Commit() End If ObjPVenta.Dispose() ObjIE.Dispose() ObjMov.Dispose() If Not TieneError Then TxtCantidadIE.Text = "" TxtDescripcionIE.Text = "" RegistraScript("$('#DivIngresoEgreso').modal('hide')", "divingresoegreso") If ChkAplicaGasto.Checked Then Alert(documentos) Else Alert("El movimiento se realizó correctamente") End If End If UpIngresoEgreso.Update() End Sub Private Sub ImpresionDirectaPDF(CveVenta As Integer) Dim ObjFactura As New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, CargaDTDetalle:=False, CargaDatosCliente:=False, CargaDatosRelacionados:=False, VerificaAlmacen:=False) Dim ExistePDF As Boolean = False Dim ArchivoPDF As String = "" Dim AplicaTicket As Boolean = ObjFactura.CveEmpresa.Contiene(190, 192) If ObjFactura.TipoDocto = "Ing" Then If AplicaTicket Then ArchivoPDF = String.Format("{0}/PDF/{1}/{2}_Ticket.pdf", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) Else ArchivoPDF = String.Format("{0}/PDF/{1}/{2}.pdf", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) End If Else ArchivoPDF = String.Format("{0}/PDF/{1}/{2}.pdf", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) End If If File.Exists(ArchivoPDF) AndAlso ObjFactura.TipoDocto = "Rem" Then ExistePDF = True Else 'REGENERAR EL PDF Try GenerarPDFVenta(CveVenta, AplicaPagare:="1", GuardarPDF:=True, RegenerarPDF:=True, DescargarArchivo:=False, EsTicket:=AplicaTicket) If File.Exists(ArchivoPDF) Then ExistePDF = True End If Catch ex As Exception OnError("Ocurrió un error al regenerar el PDF", ex) End Try End If If ExistePDF Then Dim pdf64 As String = "" 'DUPLICA EL PDF Using ms As New MemoryStream Using pdfdoc As New iText.Kernel.Pdf.PdfDocument(New iText.Kernel.Pdf.PdfWriter(ms)) pdfdoc.InitializeOutlines() Dim reporteByte As New MemoryStream(System.IO.File.ReadAllBytes(ArchivoPDF)) Dim docPDF As New iText.Kernel.Pdf.PdfDocument(New iText.Kernel.Pdf.PdfReader(reporteByte)) docPDF.CopyPagesTo(1, docPDF.GetNumberOfPages(), pdfdoc) docPDF.CopyPagesTo(1, docPDF.GetNumberOfPages(), pdfdoc) docPDF.Close() pdfdoc.Close() End Using pdf64 = Convert.ToBase64String(ms.ToArray()) End Using If Not String.IsNullOrEmpty(pdf64) Then Using ObjVentas As New ClsVentas If Not ObjVentas.UpdateVentaTicketImpreso(CveVenta, 0) Then pdf64 = "" Alert("No se pudo desmarcar la impresión", TipoMensaje.MsgError) End If End Using End If If Not String.IsNullOrEmpty(pdf64) Then RegistraScript($"impresionBase64('{pdf64}');", "Imprimir") End If Else Alert("No se pudo imprimir el pdf directamente. favor de descargar manualmente el pdf.", TipoMensaje.MsgAdvertencia) End If End Sub Protected Sub LnkLiberar_Click(sender As Object, e As EventArgs) Dim ObjVentas As New ClsVentas If ObjVentas.UpdateAsignaVentaCobranza(HdnCveVenta.Value.ToEntero, -1, -1, -1, "", Now) Then LimpiarDatos() CargaDatos() End If ObjVentas.Dispose() End Sub Protected Sub LnkImprimir_Click(sender As Object, e As EventArgs) Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) Dim CveVenta As Integer = GvRow.DataKey("CveVenta").ToEntero() If CveVenta > 0 Then ImpresionDirectaPDF(CveVenta) CargaDatos() End If End Sub #Region "PAGOS" Public Sub CargaDatosPagos() Dim FechaI As Date = If(txtFechaI.Text <> "", txtFechaI.Text.ToDate, MinFecha) Dim FechaF As Date = If(txtFechaF.Text <> "", txtFechaF.Text.ToDate, MaxFecha) Dim ObjPuntoVenta As New ClsVentas If ObjPuntoVenta.GetCortesDetalleVentas(CveCorte, DdlSubProyecto.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, 2) Then GvD.DataSource = ObjPuntoVenta.DtResultados DtCortesVentas = ObjPuntoVenta.DtResultados End If ObjPuntoVenta.Dispose() GvD.DataBind() UpL.Update() End Sub Protected Sub GvD_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvD.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveVenta").ToString = "" Then e.Row.CssClass = "Totales" End If If e.Row.DBCampo("ImportePagado").ToDecimal() < 0 Then e.Row.FCLabel("LblTotal").CssClass = "badge badge-danger" End If If e.Row.DataKey("CveIE").ToEntero > 0 Then e.Row.FCLinkButton("LnkEditarPago").Visible = True End If End If End Sub Private Sub CargaDdlPagos() DdlTipoTransaccion.DataSource = GlobalDTTipoTransacciones.FiltraParametros("Tipo='Ing' AND Estatus = 1") DdlTipoTransaccion.DataBind() DdlTipoTransaccion.Items.Insert(0, New ListItem("Seleccione Tipo Movimiento", "-1")) DdlCuenta.DataSource = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa) DdlCuenta.DataBind() DdlCuenta.Items.Insert(0, New ListItem("Seleccione", "-1")) End Sub Protected Sub LnkEditarPago_Click(sender As Object, e As EventArgs) Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) CveIE = GvRow.DataKey("CveIE").ToEntero CveTipoTransaccionOriginal = GvRow.DataKey("CveTipoTransaccion").ToEntero Dim CveTipoTransaccion As Integer = GvRow.DataKey("CveTipoTransaccion").ToEntero Dim CveCuenta As Integer = GvRow.DataKey("CveCuenta").ToEntero LblModalPagoTitulo.Text = $"Editar Pago {GvRow.DataKey("SerieFolio")}" DdlTipoTransaccion.SelectedValueExist(CveTipoTransaccion) DdlCuenta.SelectedValueExist(CveCuenta) UpModalPago.Update() RegistraScript("$('#DVModalPagos').modal('show');") End Sub Protected Sub LnkDvModalPagoAceptar_Click(sender As Object, e As EventArgs) Dim TieneError As Boolean = False If CveTipoTransaccionOriginal <> DdlTipoTransaccion.SelectedValue.ToEntero Then Dim Folio As Long Dim objBanco As New ClsBancos Folio = objBanco.GetNextFolio(DdlCuenta.SelectedValue.ToEntero, DdlTipoTransaccion.SelectedValue.ToEntero) If Not objBanco.UpdateBancosIECobranza(CveIE, DdlTipoTransaccion.SelectedValue.ToEntero, Folio.ToString, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then TieneError = True End If objBanco.Dispose() End If If Not TieneError Then CargaDatosPagos() Alert("Movimiento actualizado correctamente") RegistraScript("$('#DVModalPagos').modal('hide');") End If End Sub Protected Sub ChkAplicaGasto_CheckedChanged(sender As Object, e As EventArgs) DivCuentaGasto.Visible = ChkAplicaGasto.Checked UpIngresoEgreso.Update() End Sub #End Region Protected Sub LnkCobrosEnTranscurso_Click(sender As Object, e As EventArgs) Dim ObjMovtos As New ClsMovimientos() Dim FechaI, FechaF As Date FechaI = If(IsDate(txtFechaI.Text.Trim()), txtFechaI.Text.Trim().ToDate, MinFecha) FechaF = If(IsDate(txtFechaF.Text.Trim()), txtFechaF.Text.Trim().ToDate, MaxFecha).AddDays(1) If ObjMovtos.GetRemisionesCobranza(UsuarioActual.CveEmpresa, DdlSubProyecto.SelectedValue.ToEntero, FechaI, FechaF) Then Dim dtt As DataTable = ObjMovtos.DtResultados.FiltraParametros($"CveVenta > 0 AND CveUsuarioCobranza > 0 ") GvModalCobrosEnTranscurso.DataSource = dtt End If ObjMovtos.Dispose() GvModalCobrosEnTranscurso.DataBind() UpDVModalCobrosEnTranscurso.Update() RegistraScript("$('#DVModalCobrosEnTranscurso').modal('show');") End Sub Protected Sub ImgAntiPend_Click(sender As Object, e As EventArgs) Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero() If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then If DdlTipoAmortizacionAnticipo.Items.FindByValue("4") Is Nothing Then DdlTipoAmortizacionAnticipo.Items.Insert(1, New ListItem("Pago con devolución", "4")) End If DdlTipoAmortizacionAnticipo.SelectedValueExist("4") DdlTipoRelacionAnticipo.SelectedValueExist("-1") divAmortizacionTipoRelacion.Visible = False DdlTipoAmortizacionAnticipo_SelectedIndexChanged(DdlTipoAmortizacionAnticipo, EventArgs.Empty) End If If CveCliente <= 0 Then Dim DbRowVenta As DataRow = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("") End If ObjVentas.Dispose() If DbRowVenta IsNot Nothing Then CveCliente = DbRowVenta("CveCliente").ToString().ToEntero() End If End If If CveCliente > 0 Then CargaAnticipos(CveCliente) End If UpAnticipos.Update() RegistraScript("$('#DivAnticipos').modal();", "AE") End Sub Private Sub CargaAnticipos(CveCliente As Integer) If CveCliente > 0 Then 'QUE NO SE PUEDA REALIZAR AMORTIZACIÓN DE ANTICIPO POR DESCUENTO If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then If DdlTipoAmortizacionAnticipo.Items.FindByValue("1") IsNot Nothing Then DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1")) End If End If Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente) Then Me.TmpDTAnticiposNCIxCCliente = ObjMovtos.DtResultados.Copy() End If 'AGREGAR LOS ANTICIPOS, DEV, IxC QUE ESTEN EN PUBLICO GENERAL If Me.TmpDTAnticiposNCIxCCliente IsNot Nothing AndAlso UsuarioActual.CveEmpresa.Contiene(189, 190, 192, 195, 197) Then Dim CveClientePublicoGeneral = UsuarioActual.Empresa.Funcionalidad(714).ToEntero() If CveClientePublicoGeneral > 0 Then If CveCliente <> CveClientePublicoGeneral Then If ObjMovtos.GetAnticiposNCIxCCliente(CveClientePublicoGeneral) Then For Each DrGeneral As DataRow In ObjMovtos.DtResultados.Rows Me.TmpDTAnticiposNCIxCCliente.Rows.Add(DrGeneral.ItemArray) Next End If End If End If End If ObjMovtos.Dispose() If Me.TmpDTAnticiposNCIxCCliente IsNot Nothing Then Dim DtMovtos As DataTable = Me.TmpDTAnticiposNCIxCCliente.FiltraParametros($"Saldo > 0 AND Tipo IN('NC','IxC','Ant') ") If DdlTipoAmortizacionAnticipo.SelectedValue = "4" Then GVAnticipos.DataSource = DtMovtos.FiltraParametros("Tipo IN('NC','IxC')") Else GVAnticipos.DataSource = DtMovtos.FiltraParametros("Tipo IN('Ant')") End If Else GVAnticipos.DataSource = Nothing End If divAmortizacionTipo.Visible = True If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1")) End If GVAnticipos.Columns(4).Visible = False GVAnticipos.Columns(8).Visible = False If UsuarioActual.Empresa.Funcionalidad(109) = "1" Then GVAnticipos.Columns(6).Visible = True End If GVAnticipos.DataBind() End If UpAnticipos.Update() End Sub Protected Sub TxtFechaAnticipoCliente_TextChanged(sender As Object, e As EventArgs) Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero() If CveCliente <= 0 Then Dim DbRowVenta As DataRow = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("") End If ObjVentas.Dispose() If DbRowVenta IsNot Nothing Then CveCliente = DbRowVenta("CveCliente").ToString().ToEntero() End If End If If CveCliente > 0 Then CargaAnticipos(CveCliente) End If End Sub Protected Sub LnkRecargaAnticipos_Click(sender As Object, e As EventArgs) Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero() If CveCliente <= 0 Then Dim DbRowVenta As DataRow = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("") End If ObjVentas.Dispose() If DbRowVenta IsNot Nothing Then CveCliente = DbRowVenta("CveCliente").ToString().ToEntero() End If End If If CveCliente > 0 Then CargaAnticipos(CveCliente) End If End Sub Protected Sub LnkSolicitarActivarAnticipo_Click(sender As Object, e As EventArgs) Dim CveCliente As Integer = -1 'falta sacar a los usuarios a notificar. Dim gvr As GridViewRow = DirectCast(DirectCast(sender, LinkButton).BindingContainer, GridViewRow) Dim Folio As String = gvr.DataKey("Folio") Dim dtt As DataTable = Nothing Dim ObjProceso As New ClsSisProcesos If ObjProceso.GetUsuariosconProceso(379, UsuarioActual.CveEmpresa) Then 'proceso para autorizar dtt = ObjProceso.DtResultados.FiltraParametros("", DistinctColumns:={"CveUsuario", "Celular"}) End If ObjProceso.Dispose() Dim NombreCliente As String = "" If gvr.DataKey("CveCliente").ToEntero() > 0 Then NombreCliente = GlobalDTCliente(UsuarioActual.CveEmpresa, CveCliente:=gvr.DataKey("CveCliente").ToEntero()).FiltroPrimeroValor("NombreComercial") End If Dim EnvioMsg As Boolean = False If dtt IsNot Nothing AndAlso dtt.Rows.Count > 0 Then For Each dr As DataRow In dtt.Rows Dim NumeroTelefono = "526621143532" 'If EsProduccion Then ' NumeroTelefono = String.Format("52{0}", dr("Celular").ToString()) 'End If EnvioMsg = ModExtensiones.EnviarNotificacionWhatsApp2(NumeroTelefono, "", $"Solicitud de activación de anticipo.\\nFolio: {Folio}.\\nCliente: {NombreCliente}.") 'ClsSisNotificaciones.EnviarAlerta("Solicitud de Anticipo", $"Solicitud de activación de anticipo Folio: {Folio}
Ir Activar", dr("CveUsuario").ToString, Tipo:=TipoNotificacion.ToastInformacionB) Next End If If EnvioMsg Then Alert("Se envió una solicitud de autorización") Else Alert("No se envió la solicitud de autorización", TipoMensaje.MsgAdvertencia) End If UpAnticipos.Update() End Sub Protected Sub GVAnticipos_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowCreated If e.Row.RowType = DataControlRowType.Header Then e.Row.ClientIDMode = ClientIDMode.Static e.Row.ID = String.Format("TrH{0}", e.Row.RowIndex) ElseIf e.Row.RowType = DataControlRowType.DataRow Then e.Row.ClientIDMode = ClientIDMode.Static e.Row.ID = String.Format("Tr{0}", e.Row.RowIndex) e.Row.FCCheckBox("Chk").ID = "Chk" & e.Row.RowIndex e.Row.FCTextBox("TxtAnticipo").ID = "TxtAnticipo" & e.Row.RowIndex e.Row.FCTextBox("TxtTC").ID = "TxtTC" & e.Row.RowIndex DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ID = "CVAmortAnti" & e.Row.RowIndex DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).ID = "VCOAmortAnti" & e.Row.RowIndex DirectCast(e.Row.FindControl("CVAmortAnti"), CompareValidator).ControlToValidate = "TxtAnticipo" & e.Row.RowIndex DirectCast(e.Row.FindControl("VCOAmortAnti"), AjaxControlToolkit.ValidatorCalloutExtender).TargetControlID = "CVAmortAnti" & e.Row.RowIndex 'SI NO TIENE PERMISO, NO PERMITIR APLICAR ANTICIPOS PUNTUALES If GVAnticipos.DataSource IsNot Nothing Then If CBool(e.Row.DBCampo("AnticipoPuntual")) AndAlso Not UsuarioActual.TienePermisoProceso(377) Then e.Row.FCCheckBox("Chk").Enabled = False End If End If End If End Sub Protected Sub GVAnticipos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then 'Dim Pagado As Decimal = TxtImporteEfectivo.Text.ToDecimal + TxtImporteCredito.Text.ToDecimal + TxtImporteDebito.Text.ToDecimal + TxtImporteCheque.Text.ToDecimal + TxtImporteTransferencia.Text.ToDecimal If e.Row.RowIndex = 0 Then e.Row.Cells(1).Width = Unit.Pixel(60) e.Row.Cells(2).Width = Unit.Pixel(100) e.Row.Cells(3).Width = Unit.Pixel(80) e.Row.Cells(4).Width = Unit.Pixel(80) End If e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right If e.Row.DataKey("Saldo").ToDouble < 0 Then e.Row.Cells(3).ForeColor = Drawing.Color.Red If e.Row.DataKey("Saldo").ToDouble = 0 Then e.Row.FCLiteral("LtlAnticipos").Text = "" Dim saldo As Decimal = 0 Dim tipoCambio As Decimal = 0 Dim total As Decimal = LtlSaldo.Text.ToDecimal() '- Pagado saldo = e.Row.DataKey("Saldo").ToString().ToDecimal If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("4") Then saldo = e.Row.DataKey("Saldo").ToString().ToDecimal Else saldo = e.Row.DataKey("SaldoConImpuestos").ToString().ToDecimal End If e.Row.FCLiteral("LtlAnticipos").Text = saldo.FormatoNumero saldo = saldo.RoundSQL() Dim maxsaldo As Decimal = 0 If total > saldo Then maxsaldo = saldo Else maxsaldo = total End If Dim AmortizacionSujeridaContrato As Decimal = 0 e.Row.FCLiteral("MonedaVenta").Text = saldo.FormatoNumero(2) e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Attributes.Add("onclick", String.Format("chkAnt(this,{0},{1},{2});", e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, saldo, AmortizacionSujeridaContrato)) e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, saldo)) e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("CambioTipoMoneda({0},{1},{2},{3},{4});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, e.Row.DataKey("Saldo"), e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).ClientID, e.Row.DataKey("CveMoneda"))) If e.Row.DataKey("CveIE").ToString().ToEntero() > 0 Then e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveIE"), e.Row.DataKey("Folio")) Else e.Row.FCLiteral("LtlFactura").Text = String.Format("{1}", e.Row.DataKey("CveVenta"), e.Row.DataKey("Folio")) End If If e.Row.DataKey("ISTotal") = "1" Then e.Row.Cells(0).Visible = False e.Row.Cells(1).ColumnSpan = 3 e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Right e.Row.FCLiteral("LtlFactura").Text = String.Format("Total {0} ", e.Row.DataKey("Tipo")) e.Row.BackColor = Drawing.Color.LightGray e.Row.Cells(2).Visible = False e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Visible = False e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False e.Row.FCLabel("LblTotalAnticipos").Visible = True e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right End If If UsuarioActual.Empresa.Funcionalidad(185) = "1" Then If e.Row.DBCampo("Tipo").ToString().Contiene("NC", "Ant", "IxC") AndAlso Not CBool(e.Row.DBCampo("AnticipoAutorizado")) Then e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Enabled = False e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ToolTip = "Anticipo Bloqueado" e.Row.FCLinkButton("LnkSolicitarActivarAnticipo").Visible = True End If End If If e.Row.DBCampo("CveMoneda").ToString().ToEntero() = 1 Then e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False End If End If End Sub Protected Sub BtnAceptarAnticipos_Click(sender As Object, e As System.EventArgs) Handles BtnAceptarAnticipos.Click If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() <= 0 Then Alert("Debe seleccionar un tipo de amortización", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim Amortizacion As Decimal = 0 If ListaAnticiposAplicados Is Nothing Then ListaAnticiposAplicados = New List(Of Modelos.MAnticipoRelacionado) Else ListaAnticiposAplicados.Clear() End If Dim SbObs As New StringBuilder For Each gvr As GridViewRow In GVAnticipos.Rows If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then If gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal > 0 Then Amortizacion += gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal() If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then ListaAnticiposAplicados.Add(New Modelos.MAnticipoRelacionado() With {.CveVenta = gvr.DataKey("CveVenta").ToEntero(), .FolioFiscal = gvr.DataKey("FolioFiscal"), .Tipo = gvr.DataKey("Tipo")}) End If If DdlTipoAmortizacionAnticipo.SelectedValue = "4" Then ListaAnticiposAplicados.Add(New Modelos.MAnticipoRelacionado() With {.CveVenta = gvr.DataKey("CveVenta").ToEntero(), .FolioFiscal = gvr.DataKey("FolioFiscal"), .Tipo = gvr.DataKey("Tipo")}) End If End If End If Next If Amortizacion > 0 Then TxtNCDev.Text = Amortizacion.ToString() LtlTipoAnticipo.Text = DdlTipoAmortizacionAnticipo.SelectedItem.Text HdnTipoAmortizacion.Value = DdlTipoAmortizacionAnticipo.SelectedValue Else TxtNCDev.Text = "" LtlTipoAnticipo.Text = "" HdnTipoAmortizacion.Value = "" End If RegistraScript("$('#DivAnticipos').modal('hide');CalculaTotalPagoContado()", "AE") UpL.Update() End Sub Protected Sub DdlTipoAmortizacionAnticipo_SelectedIndexChanged(sender As Object, e As EventArgs) divAmortizacionTipoRelacion.Visible = DdlTipoAmortizacionAnticipo.SelectedValue = "2" If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then CargaDdlNCPS() DivConceptoNC.Visible = True Else DivConceptoNC.Visible = False End If If CveCliente <= 0 Then Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero Dim DbRowVenta As DataRow = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("") End If ObjVentas.Dispose() If DbRowVenta IsNot Nothing Then CveCliente = DbRowVenta("CveCliente").ToString().ToEntero() End If End If If CveCliente > 0 Then CargaAnticipos(CveCliente) End If UpAnticipos.Update() End Sub Public Sub CargaDdlNCPS() Dim CveSATNC As String = "84111506" Dim dtt As New DataTable dtt = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CodigoSATPS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC If dtt IsNot Nothing Then DdlNCPSAnt.DataSource = dtt DdlNCPSAnt.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlNCPSAnt.DataBind() dtt.Dispose() End If End Sub End Class