Option Explicit On Option Strict On Imports System.Data Imports System.IO Imports System.Net.Http Imports CrystalDecisions.CrystalReports.Engine Imports Extensiones Imports Modelos.Factura Partial Class Ventas_PVCobranza Inherits ClsPaginas #Region "Propiedades" 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 CveVendedor As Integer Get If ViewState("CveVendedor") Is Nothing Then ViewState("CveVendedor") = -1 End If Return ViewState("CveVendedor").ToString.ToEntero End Get Set(value As Integer) ViewState("CveVendedor") = value End Set End Property Private Property CveVentaCancelacion As Integer Get If ViewState("CveVentaCancelacion") Is Nothing Then ViewState("CveVentaCancelacion") = -1 End If Return ViewState("CveVentaCancelacion").ToString.ToEntero End Get Set(value As Integer) ViewState("CveVentaCancelacion") = 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 #End Region Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then 'Dim Arr As New ArrayList 'Arr.Add("autorizada") 'If EnviarNotificacionWhatsApp("526621430964", "solicitud_autorizacion_anticipo_respuesta", Arr) Then ' Alert("bien") 'Else ' Alert("mal", TipoMensaje.MsgAdvertencia) 'End If 'Arr.Add("suc") 'Arr.Add("cliente") 'Arr.Add("10") 'Arr.Add("$ 15.11") 'If EnviarNotificacionWhatsApp("526621430964", "solicitud_autorizacion_anticipo", Arr, "autoriza") Then ' Alert("bien") 'Else ' Alert("mal", TipoMensaje.MsgAdvertencia) 'End If 'Exit Sub CveCorte = 0 CargaFiltros() CargaDdlPagos() If UsuarioActual.CveSubProyecto > 0 Then DdlSubProyecto.SelectedValueExist(UsuarioActual.CveSubProyecto) If UsuarioActual.TienePermisoProceso(371) Then CargaCorteCaja() End If If UsuarioActual.CveEmpresa = 189 Then DivDatosCheque.Visible = True UpContadoOtros.Visible = True UpContadoOtros.Update() End If If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then DivNoTimbradas.Visible = True End If If UsuarioActual.TienePermisoProceso(407) Then LnkEstadosCaja.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 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, UsuarioActual.CveUsuario) 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, DdlSubProyecto.SelectedValue.ToEntero) Then If ObjSub.DtResultados.Rows.Count > 0 Then Dim miFecha As DateTime = Now Dim fechaSiguiente As DateTime = miFecha.AddDays(1) Dim filtro As String = String.Format("Fecha >= #{0}# AND Fecha < #{1}#", miFecha.ToString("MM/dd/yyyy"), fechaSiguiente.ToString("MM/dd/yyyy")) GvPendientesTimbrar.DataSource = ObjSub.DtResultados.FiltraParametros(filtro) 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() If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then CargaCancelaciones() End If End Sub Private Sub CargaCancelaciones() If DdlSubProyecto.SelectedValue.ToEntero() > 0 Then DivCancelacionesPendientes.Visible = True Dim DtVentas As DataTable = Nothing Dim ObjVentas = New ClsVentas() If ObjVentas.GetVentasPendientesCancelacion(UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Then DtVentas = ObjVentas.DtResultados.Copy() End If ObjVentas.Dispose() If DtVentas IsNot Nothing Then GvCancelaciones.DataSource = DtVentas.FiltraParametros($"(CveEstatusFactura IN (20) AND CveEstatusRefacturacion IN (0,4)) AND CveSubProyecto={DdlSubProyecto.SelectedValue.ToEntero()}") GvCancelaciones.DataBind() End If UpL.Update() End If 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("CondicionesPago") = "1" Then ' remis de crédito ' si es de crédito debe de estar autorizado. e.Row.FCLinkButton("BtnPagar").Text = "Crédito" If (e.Row.DBCampo("Bloqueada") = "False") OrElse (e.Row.DBCampo("Bloqueada") = "True" AndAlso e.Row.DBCampo("CveEstatusAutorizacion").Contiene("2")) Then ' si no está bloqueada o si fue bloqueda y autorizada e.Row.FCLinkButton("BtnPagar").CssClass = "btn btn-xs btn-warning" e.Row.FCLinkButton("BtnPagar").Enabled = True Else e.Row.FCLinkButton("BtnPagar").CssClass = "btn btn-xs btn-danger" e.Row.FCLinkButton("BtnPagar").Enabled = False e.Row.FCLinkButton("BtnPagar").OnClientClick = "bootbox.dialog({" & "message: 'La solicitud de crédito esta en proceso de autorización ', " & "className: 'header-red', " & "onEscape: function() {}, " & "title: ' Advertencia', " & "buttons: { " & "success: { label: '', className: 'hide', callback: function() {} }, " & "danger: { label: '', className: 'hide', callback: function() {} }, " & "main: { label: 'Aceptar', className: 'red', callback: function() {} } " & "} " & "});" & "return false;" End If 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 If e.Row.DBCampo("Fecha").ToDate.ToShortDateString <> Now.ToShortDateString Then e.Row.FCLinkButton("BtnPagar").Enabled = False e.Row.FCLinkButton("BtnPagar").Text = "Cobrar" 'e.Row.FCLinkButton("BtnPagar").CssClass = "btn btn-xs default" e.Row.FCLinkButton("BtnPagar").OnClientClick = "bootbox.dialog({" & "message: 'No se puede realizar un cobro a una remisión de días anteriores.
Favor de cancelar la remisión y generarla con fecha actual. ', " & "className: 'header-yellow', " & "onEscape: function() {}, " & "title: ' Advertencia', " & "buttons: { " & "success: { label: '', className: 'hide', callback: function() {} }, " & "danger: { label: '', className: 'hide', callback: function() {} }, " & "main: { label: 'Aceptar', className: 'yellow', callback: function() {} } " & "} " & "});" & "return false;" 'e.Row.BackColor = Drawing.ColorTranslator.FromHtml("#3598dc") 'e.Row.CssClass = "blue-madison" 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 CondicionesPagoContado As Boolean = GvRow.DataKey("CondicionesPago") = "0" 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 HdnCveCliente.Value = GvRow.DataKey("CveCliente") 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 HdnVentaCondicionesPago.Value = GvRow.DataKey("CondicionesPago") HdnPlazoCobranza.Value = GvRow.DataKey("PlazoCobranza") If UsuarioActual.CveEmpresa.Contiene(189, 1) AndAlso GvRow.DataKey("TipoDocto") = "Rem" Then DivAnticipo.Visible = True ImgAntiPend.Visible = True End If If CondicionesPagoContado Then '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 DivContadoBancos.Visible = True BtnPagar.Text = "Pagar" Else DivContadoBancos.Visible = False BtnPagar.Text = "Emitir a crédito" 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 Dim GenerarFac As Boolean = UsuarioActual.CveEmpresa.Contiene(1, 189, 197) 'registrar pago Dim VentaContado As Boolean = HdnVentaCondicionesPago.Value = "0" If VentaContado Then 'validaciones Dim Pagado As Decimal = TxtImporteEfectivo.Text.ToDecimal + TxtImporteCredito.Text.ToDecimal + TxtImporteDebito.Text.ToDecimal + TxtImporteCheque.Text.ToDecimal + TxtImporteTransferencia.Text.ToDecimal + TxtNCDev.Text.ToDecimal() + TxtImporteOtrosContado.Text.ToDecimal() If Pagado = 0 Then Alert("Favor de especificar importe", TipoMensaje.ToastAdventencia) Exit Sub End If If LtlSaldo.Text.ToDecimal + TxtCxCAplicado.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 If PagadoSinEfectivo > (LtlSaldo.Text.ToDecimal() + TxtCxCAplicado.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 If TxtImporteOtrosContado.Text.ToDecimal() > 0 Then If DdlOtroFormaPago.SelectedValue.ToEntero() <= 0 Then Alert("Es necesario especificar la forma de pago adicional", TipoMensaje.MsgAdvertencia) Exit Sub End If If DdlCuentaOtrosContado.SelectedValue.ToEntero() <= 0 Then Alert("Es necesario especificar la cuenta de la forma de pago adicional", TipoMensaje.MsgAdvertencia) Exit Sub End If End If End If Dim tCveCorte As Integer = CveCorte Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero Dim CveVentaRemision As Integer = -1 Dim DbRowVenta As DataRow = Nothing Dim ObjVtaRemision As New ClsVentas If ObjVtaRemision.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then DbRowVenta = ObjVtaRemision.DtResultados.Copy().FiltroPrimero("") End If ObjVtaRemision.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 VentaActual.CveUsoCFDI = DbRowVenta("CveUsoCFDI").ToString.ToEntero Dim CveVendedor As Integer = DbRowVenta("CveVendedor").ToString.ToEntero Dim ObservacionesAlmacen = DbRowVenta("ObservacionesAlmacen").ToString() Dim Observaciones = DbRowVenta("Observaciones").ToString() Dim PedidoContrato = DbRowVenta("PedidoContrato").ToString() Dim OrdenCompra = DbRowVenta("OrdenCompra").ToString() 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 SaldoPendienteVenta As Decimal = DbRowVenta("Saldo").ToString.ToDecimal Dim SaldoTotalInicialVenta As Decimal = DbRowVenta("Saldo").ToString.ToDecimal Dim SaldoPendientePagos As Decimal = TxtImporteContado.Text.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 ObjOIEventos As New ClsOIEventos(ObjVentas2.IniciaTransacSQL()) Dim respFactura As Modelos.Factura.MMensajeFactura = Nothing Dim ListaNC As New List(Of Modelos.Factura.MMensajeFactura) 'Dim respNC As Modelos.Factura.MMensajeFactura = Nothing Dim RegistrarPago As Boolean = True Dim PlazoCobranza As Integer = HdnPlazoCobranza.Value.ToEntero Try 'FACTURAR LA REMISION PARA HACER EL PAGO If GenerarFac AndAlso VentaActual.TipoDocto = "Rem" Then CveVentaRemision = HdnCveVenta.Value.ToEntero respFactura = GenerarFactura(CveVendedor, VentaActual, ObjVentas2, ObjClientes, ObservacionesAlmacen, VentaContado, PlazoCobranza, Observaciones, PedidoContrato, OrdenCompra) 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 respFactura.Factura.DtAnticiposAplicados IsNot Nothing Then PagoAplicado += respFactura.Factura.DtAnticiposAplicados.SUM("Importe") SaldoPendienteVenta = SaldoPendienteVenta - PagoAplicado SaldoPendientePagos = SaldoPendientePagos - PagoAplicado For Each RowAnt As DataRow In respFactura.Factura.DtAnticiposAplicados.Rows If Not ActualizaAnticipos(RowAnt("CveIE").ToString().ToEntero(), RowAnt("CveVenta").ToString().ToEntero(), RowAnt("Tipo").ToString(), RowAnt("Folio").ToString(), ObjVentas2, ObjOIEventos) Then MsgError = "Ocurrió un error al actualizar los anticipos" Exit For End If Next End If End If End If 'GENERAR NC PARA AMORTIZACION If MsgError = "" AndAlso ListaAnticiposAplicados IsNot Nothing AndAlso ListaAnticiposAplicados.Where(Function(x) x.Tipo = "Ant").Any() AndAlso TxtNCDev.Text.ToDecimal() > 0 Then For Each gvr As GridViewRow In GVAnticipos.Rows If gvr.DataKey("Tipo") = "Ant" AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then Dim ImporteAnticipo As Decimal = gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal Dim RespNC = GenerarNC(ImporteAnticipo, CveVendedor, VentaActual, gvr, 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 Exit For Else PagoAplicado += RespNC.Factura.Total SaldoPendienteVenta -= RespNC.Factura.Total SaldoPendientePagos -= RespNC.Factura.Total For Each RowAnt As DataRow In RespNC.Factura.DtAnticiposAplicados.Rows If Not ActualizaAnticipos(RowAnt("CveIE").ToString().ToEntero(), RowAnt("CveVenta").ToString().ToEntero(), RowAnt("Tipo").ToString(), RowAnt("Folio").ToString(), ObjVentas2, ObjOIEventos) Then MsgError = "Ocurrió un error al actualizar los anticipos" Exit For End If Next ListaNC.Add(RespNC) End If Else MsgError = "Ocurrió un error al generar la nota de crédito" End If End If Next End If If MsgError = "" Then If SaldoPendienteVenta > 0 AndAlso VentaContado 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 SaldoPendientePagos > 0 AndAlso TxtImporteCredito.Text.ToDecimal > 0 Then MsgError = RegistraIE(12, DdlCuentaTarjetaCredito.SelectedValue.ToEntero, SaldoPendienteVenta, TxtImporteCredito.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendienteVenta -= TxtImporteCredito.Text.ToDecimal SaldoPendientePagos -= TxtImporteCredito.Text.ToDecimal PagoAplicado += TxtImporteCredito.Text.ToDecimal End If If MsgError = "" AndAlso SaldoPendientePagos > 0 AndAlso TxtImporteDebito.Text.ToDecimal > 0 Then MsgError = RegistraIE(11, DdlCuentaTarjetaDebito.SelectedValue.ToEntero, SaldoPendienteVenta, TxtImporteDebito.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendienteVenta -= TxtImporteDebito.Text.ToDecimal SaldoPendientePagos -= TxtImporteDebito.Text.ToDecimal PagoAplicado += TxtImporteDebito.Text.ToDecimal End If If SaldoPendientePagos > 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, SaldoPendienteVenta, TxtImporteCheque.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, Obs:=Obs, CveAutorizacion:=TxtClaveAutorizacion.Text.Trim(), CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendienteVenta -= TxtImporteCheque.Text.ToDecimal SaldoPendientePagos -= TxtImporteCheque.Text.ToDecimal PagoAplicado += TxtImporteCheque.Text.ToDecimal End If If MsgError = "" AndAlso SaldoPendientePagos > 0 AndAlso TxtImporteTransferencia.Text.ToDecimal > 0 Then MsgError = RegistraIE(8, DdlCuentaTransferencia.SelectedValue.ToEntero, SaldoPendienteVenta, TxtImporteTransferencia.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendienteVenta -= TxtImporteTransferencia.Text.ToDecimal SaldoPendientePagos -= TxtImporteTransferencia.Text.ToDecimal PagoAplicado += TxtImporteTransferencia.Text.ToDecimal End If If MsgError = "" AndAlso SaldoPendientePagos > 0 AndAlso TxtImporteOtrosContado.Text.ToDecimal > 0 Then Dim CveConceptroOtros As Integer = -1 Select Case DdlOtroFormaPago.SelectedValue Case "1" 'Debito CveConceptroOtros = 11 Case "2" 'Crédito CveConceptroOtros = 12 Case "3" 'Transferencia CveConceptroOtros = 8 End Select MsgError = RegistraIE(CveConceptroOtros, DdlCuentaOtrosContado.SelectedValue.ToEntero, SaldoPendienteVenta, TxtImporteOtrosContado.Text.ToDecimal, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendienteVenta -= TxtImporteOtrosContado.Text.ToDecimal SaldoPendientePagos -= TxtImporteOtrosContado.Text.ToDecimal PagoAplicado += TxtImporteOtrosContado.Text.ToDecimal End If If MsgError = "" AndAlso SaldoPendientePagos > 0 AndAlso TxtImporteEfectivo.Text.ToDecimal > 0 Then Dim PagoEfectivo As Decimal = TxtImporteEfectivo.Text.ToDecimal PagoAplicado += PagoEfectivo If PagoAplicado >= SaldoPendientePagos Then TxtCambio.Text = (PagoAplicado - SaldoPendientePagos).FormatoNumero PagoEfectivo = SaldoPendientePagos End If If SaldoPendienteVenta < 0 Then SaldoPendienteVenta = 0 MsgError = RegistraIE(13, DdlCuentaEfectivo.SelectedValue.ToEntero, SaldoPendienteVenta, PagoEfectivo, Fecha, CvePrePoliza, VentaActual, ObjIE, ObjConta, ObjVentas2, tCveCorte, CveSubProyecto:=VentaActual.CveSubProyecto) SaldoPendienteVenta -= PagoEfectivo SaldoPendientePagos -= PagoEfectivo End If If SaldoPendienteVenta > 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 If MsgError = "" Then Dim CveIEPago As Integer = HdnCveIE.Value.ToEntero 'registrar los pagos a cobranza For Each gvr As GridViewRow In GvCxC.Rows If gvr.FCCheckBox("Chk").Checked Then Dim VentaCxC As New Venta(UsuarioActual) VentaCxC.CveVenta = gvr.DataKey("CveVenta").ToEntero VentaCxC.TipoDocto = gvr.DataKey("TipoDocto") VentaCxC.Fecha = gvr.DataKey("Fecha").ToDate VentaCxC.CveCliente = gvr.DataKey("CveCliente").ToEntero VentaCxC.CveMoneda = gvr.DataKey("CveMoneda").ToEntero VentaCxC.SerieFolio = gvr.DataKey("SerieFolio") VentaCxC.ClienteNombre = "sss" 'gvr.DataKey("ClienteNombre") VentaCxC.TC = gvr.DataKey("TipoCambio").ToDecimal VentaCxC.Total = gvr.DataKey("Total").ToDecimal VentaCxC.IVA = gvr.DataKey("IVA").ToDecimal VentaCxC.IEPS = gvr.DataKey("IEPS").ToDecimal VentaCxC.RetIVA = gvr.DataKey("RetIVA").ToDecimal VentaCxC.RetISR = gvr.DataKey("RetISR").ToDecimal VentaCxC.PorcentajeIVA = gvr.DataKey("PorcentajeIVA").ToDecimal VentaCxC.UsuarioActual = UsuarioActual VentaCxC.CveSubProyecto = gvr.DataKey("CveSubProyecto").ToEntero Dim Pago As New VentaPago Pago.ImportePagoVenta = gvr.DataKey("Saldo").ToDecimal Pago.ImportePago = gvr.DataKey("Saldo").ToDecimal Pago.CveIE = CveIEPago Pago.CveMonedaPago = VentaCxC.CveMoneda Pago.Fecha = NowADS() Pago.Referencia = VentaCxC.SerieFolio Pago.TipoPago = "XXX" Dim ErrorConta As Boolean = AplicaPrePolizaPagoVenta(VentaCxC, Pago, CvePrePoliza, ObjConta) If ErrorConta Then MsgError = "Error en aplicación de pago en cobranza" End If End If Next 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 If ObjConta.ValidacionesPrePoliza(CvePrePoliza, UsuarioActual, Opcion:=5, CveVenta:=CveVenta) Then If ObjConta.ValorPolizaDescuadre > 0 Then GuardaLogAD($"Ventas/Ventas-NCGeneradas | Error:{ObjConta.MensajePolizaDescuadre} Diferencia:{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas") End If End If End If If MsgError = "" Then ObjVentas2.Commit() Dim msBuild As New StringBuilder() Try Dim MsgTimbrado As String = "" Dim FolioFiscalFactura = "" Dim DebeTimbrar As Boolean = True Dim SeTimbro As Boolean = False 'SI SE GENERO FACTURA DE INGRESO, TIMBRARLA DESPUES DE REALIZAR EL PAGO If DebeTimbrar AndAlso respFactura IsNot Nothing Then Try AjustarTimbreFactura(respFactura.Factura) Dim ObjTimbre = TimbrarFactura(respFactura.Factura, SeTimbro) MsgTimbrado = ObjTimbre.MensajeErrorCFDI FolioFiscalFactura = ObjTimbre.UUID If Not String.IsNullOrEmpty(MsgTimbrado) Then Dim StrEr As String = $"
Comprobante no emitido :
{MsgTimbrado}
Por favor inténtelo de nuevo a través del botón 'Emitir' en ventas.
" MsgTimbrado = StrEr End If Catch ex As Exception GuardaLogAD(ex.ToString()) End Try End If If respFactura IsNot Nothing Then Try If RegistrarPago Then msBuild.Append("Pago Registrado correctamente.

") End If msBuild.AppendFormat(" La factura {1} se genero correctamente.
", respFactura.CveVenta, respFactura.SerieFolio) If SeTimbro Then Dim xml = String.Format("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", respFactura.CveVenta, "XML", respFactura.SerieFolio, respFactura.Factura.TipoDocto))) msBuild.AppendFormat("{0}", xml) Else If Not String.IsNullOrEmpty(MsgTimbrado) Then msBuild.AppendFormat("
{0}
", MsgTimbrado) End If End If Dim pdf = String.Format("", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", respFactura.CveVenta))) msBuild.AppendFormat("{0}", pdf) If respFactura.Factura.Inv_CveMovimiento > 0 Then msBuild.AppendFormat("Movimiento de Almacén
", respFactura.Factura.Inv_CveMovimiento) End If If respFactura IsNot Nothing AndAlso respFactura.Factura IsNot Nothing AndAlso respFactura.Factura.DtAnticiposAplicados IsNot Nothing Then For Each dr As DataRow In respFactura.Factura.DtAnticiposAplicados.Rows msBuild.AppendLine($"
Imprimir Saldo Aplicado {dr("Folio").ToString}
") Next End If If ListaNC.Count > 0 Then For Each respNC In ListaNC Dim MsgTimbradoNC As String = "" msBuild.AppendFormat(" La nota de crédito {1} se genero correctamente.
", respNC.CveVenta, respNC.SerieFolio) Dim SeTimbroNC As Boolean = False If SeTimbro Then 'PONER LA RELACION CON LA FACTURA CREADA AjustarTimbreNC(respNC.Factura, FolioFiscalFactura) Dim ObjTimbreNC = TimbrarFactura(respNC.Factura, SeTimbroNC) If Not String.IsNullOrEmpty(ObjTimbreNC.MensajeErrorCFDI) Then MsgTimbradoNC = ObjTimbreNC.MensajeErrorCFDI End If Else MsgTimbradoNC = $"No se pudo timbrar la NC porque la factura de ingreso no ha sido timbrada previamente" End If If SeTimbroNC Then Dim xml = String.Format("", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", respNC.CveVenta, "XML", respNC.SerieFolio, respNC.Factura.TipoDocto))) msBuild.AppendFormat("{0}", xml) End If Dim pdfNC = String.Format("", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", respNC.CveVenta))) msBuild.AppendFormat("{0}", pdfNC) If respNC IsNot Nothing AndAlso respNC.Factura IsNot Nothing AndAlso respNC.Factura.DtAnticiposAplicados IsNot Nothing Then For Each dr As DataRow In respNC.Factura.DtAnticiposAplicados.Rows msBuild.AppendLine($"
Imprimir Saldo Aplicado {dr("Folio").ToString}
") Next End If If Not String.IsNullOrEmpty(MsgTimbradoNC) Then Dim StrEr As String = $"
Comprobante no emitido :
{MsgTimbradoNC}
Por favor inténtelo de nuevo a través del botón 'Emitir' en ventas.
" MsgTimbradoNC = StrEr msBuild.AppendFormat("
{0}
", MsgTimbradoNC) End If Next End If Catch ex As Exception GuardaLogAD(ex.ToString()) msBuild.AppendFormat("
{0}
", MsgTimbrado) End Try Else msBuild.Append($"Pago Registrado correctamente.

Imprimir ticket") End If Catch ex As Exception GuardaLogAD(ex.ToString()) msBuild.Append("Ocurrio un error posterior al pago") End Try 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 If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then 'ENVIO DE CORREO Try If respFactura IsNot Nothing AndAlso respFactura.Factura IsNot Nothing Then Dim EnviarMail As Boolean = respFactura.Factura.Cliente.EnviarFactura = "Si" Dim Hilo As New System.Threading.Thread(Sub() EnviarMailFactura(EnviarMail, respFactura.Factura, UsuarioActual)) Hilo.Start() End If Catch ex As Exception GuardaLogAD(ex.ToString()) End Try 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 AjustarTimbreFactura(ByRef ObjFactura As Modelos.Factura) 'TEMPORAL DEBE ESTAR EN EL PREPARA TIMBRE ObjFactura.Timbre.Comprobante.MetodoPago = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {ObjFactura.CveMetodoPago}") ObjFactura.Timbre.Comprobante.FormadePago = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {ObjFactura.CveFormaPago}") ObjFactura.Timbre.Receptor.UsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {ObjFactura.CveUsoCFDI}") ObjFactura.Timbre.Comprobante.CondicionesdePago = GlobalDTVtaFormaPago().FiltroPrimeroValor("FormaPago", $"CveFormaPago = {ObjFactura.CveFormaPago}") ObjFactura.Timbre.CFDIRelacionados.UUID.Clear() If ListaAnticiposAplicados IsNot Nothing Then 'SI TIENE RELACIONADOS ANTICIPOS PONER TIPO RELACION 7 If ListaAnticiposAplicados.Where(Function(x) x.Tipo = "Ant").Any() 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" End If End If 'SI TIENE NC/DEV PONER TIPO RELACION 1 If Not ListaAnticiposAplicados.Where(Function(x) x.Tipo = "Ant").Any() AndAlso ListaAnticiposAplicados.Where(Function(x) x.Tipo = "NC").Any() Then Dim DevolucionesNC = ListaAnticiposAplicados.Where(Function(Obj) Obj.Tipo = "NC") If DevolucionesNC IsNot Nothing AndAlso DevolucionesNC.Count() > 0 Then For Each NC As Modelos.MAnticipoRelacionado In DevolucionesNC ObjFactura.Timbre.CFDIRelacionados.UUID.Add(NC.FolioFiscal) Next Dim RowTipoRelacion As DataRow = GlobalDTVtaTiposRelacion().FiltroPrimero($"CveTipoRelacion = {ObjFactura.CveTipoRelacion}") ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = RowTipoRelacion("SATClaveTipoRelacion").ToString() ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = RowTipoRelacion("SATTipoRelacion").ToString() End If End If End If End Sub Private Sub AjustarTimbreNC(ByRef ObjNC As Modelos.Factura, FolioFiscalFactura As String) ObjNC.Timbre.CFDIRelacionados.UUID.Clear() ObjNC.Timbre.CFDIRelacionados.UUID.Add(FolioFiscalFactura) ObjNC.Timbre.CFDIRelacionados.TipoRelacion = "07" ObjNC.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" 'TEMPORAL DEBE ESTAR EN EL PREPARA TIMBRE ObjNC.Timbre.Comprobante.MetodoPago = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {ObjNC.CveMetodoPago}") ' Obj.ClaveMetodoPagoSAT ObjNC.Timbre.Comprobante.FormadePago = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {ObjNC.CveFormaPago}") 'Obj.ClaveFormaPagoSAT ObjNC.Timbre.Receptor.UsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {ObjNC.CveUsoCFDI}") ObjNC.Timbre.Comprobante.CondicionesdePago = GlobalDTVtaFormaPago().FiltroPrimeroValor("FormaPago", $"CveFormaPago = {ObjNC.CveFormaPago}") End Sub Private Function ActualizaAnticipos(CveIE As Integer, CveVenta As Integer, Tipo As String, Folio As String, ByRef ObjVentas As ClsVentas, ByRef ObjEventoBitacora As ClsOIEventos) As Boolean Dim Retorno As Boolean = True If CveVenta > 0 OrElse CveIE > 0 Then Dim Actualizo As Boolean = False If Tipo.Contiene("NC", "Ant") Then If ObjVentas.UpdateVentaAnticipoAutorizado(CveVenta, False) Then Actualizo = True End If ElseIf Tipo.Contiene("IxC") Then If ObjVentas.UpdateIxCAnticipoAutorizado(CveIE, False) Then Actualizo = True End If End If If Actualizo Then Retorno = ObjEventoBitacora.AddEventoBitacora($"El anticipo se desautorizó correctamente. Folio: {Folio}", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveIE, -1, CveCliente, -1, -1, -1, -1, -1, CveVenta:=CveVenta) End If End If Return Retorno End Function Private Sub LimpiarDatos() PnlContado.Visible = False TxtImporteEfectivo.Text = "" TxtImporteCredito.Text = "" TxtImporteDebito.Text = "" TxtImporteCheque.Text = "" TxtImporteTransferencia.Text = "" TxtImporteOtrosContado.Text = "" TxtCambio.Text = "" TxtCxCAplicado.Text = "" TxtClaveAutorizacion.Text = "" TxtAutorizo.Text = "" TxtNCDev.Text = "" LtlTipoAnticipo.Text = "" 'HdnTipoAmortizacion.Value = "" CveCliente = -1 CveVendedor = -1 If TmpDTAnticiposNCIxCCliente IsNot Nothing Then TmpDTAnticiposNCIxCCliente.Clear() TmpDTAnticiposNCIxCCliente = Nothing End If If ListaAnticiposAplicados IsNot Nothing Then ListaAnticiposAplicados.Clear() ListaAnticiposAplicados = Nothing End If If GVAnticipos IsNot Nothing Then For Each GvRow As GridViewRow In GVAnticipos.Rows If GvRow.FCCheckBox("Chk" & GvRow.RowIndex) IsNot Nothing Then GvRow.FCCheckBox("Chk" & GvRow.RowIndex).Checked = False End If Next End If ImgAntiPend.Visible = False DivAnticipo.Visible = False UpL.Update() End Sub Private Function GenerarFactura(CveVendedor As Integer, ByRef VentaRemision As Venta, ByRef ObjVentas As ClsVentas, ByRef ObjClientes As ClsClientes, ObservacionesAlmacen As String, VentaConta As Boolean, PlazoCobranza As Integer, Observaciones As String, PedidoContrato As String, OrdenCompra As String) As Modelos.Factura.MMensajeFactura Dim Retorno As Modelos.Factura.MMensajeFactura = Nothing Dim SbAlert As New StringBuilder() Dim SBAmortizaciones As New StringBuilder Dim DtAnticipos As New DataTable() Try 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.CveMoneda = VentaRemision.CveMoneda If ObjFactura.CveMoneda = 2 Then ObjFactura.TipoCambio = GlobalTipoCambio(Now).ToString().ToDecimal() Else ObjFactura.TipoCambio = 1 End If ObjFactura.RemisionesLista = RemisionesLista ObjFactura.DtRemisionesPS = DtRemisionesPS ObjFactura.DtRemisiones = DtRemisiones ObjFactura.FechaPago = ObjFactura.Fecha.AddDays(PlazoCobranza) Dim DtPagos As DataTable = New DataTable("DtPagosFactura") DtPagos.Columns.Add(New DataColumn("CveFormaPago", GetType(Integer))) DtPagos.Columns.Add(New DataColumn("Importe", GetType(Decimal))) Dim PagadoSinEfectivo As Decimal = 0 If VentaConta Then If TxtImporteCredito.Text.ToDecimal > 0 Then DtPagos.Rows.Add({4, TxtImporteCredito.Text.ToDecimal}) : PagadoSinEfectivo += TxtImporteCredito.Text.ToDecimal If TxtImporteDebito.Text.ToDecimal > 0 Then DtPagos.Rows.Add({18, TxtImporteDebito.Text.ToDecimal}) : PagadoSinEfectivo += TxtImporteDebito.Text.ToDecimal If TxtImporteCheque.Text.ToDecimal > 0 Then DtPagos.Rows.Add({2, TxtImporteCheque.Text.ToDecimal}) : PagadoSinEfectivo += TxtImporteCheque.Text.ToDecimal If TxtImporteTransferencia.Text.ToDecimal > 0 Then DtPagos.Rows.Add({3, TxtImporteTransferencia.Text.ToDecimal}) : PagadoSinEfectivo += TxtImporteTransferencia.Text.ToDecimal If TxtNCDev.Text.ToDecimal > 0 Then DtPagos.Rows.Add({21, TxtNCDev.Text.ToDecimal}) : PagadoSinEfectivo += TxtNCDev.Text.ToDecimal If TxtImporteOtrosContado.Text.ToDecimal() > 0 Then PagadoSinEfectivo += TxtImporteOtrosContado.Text.ToDecimal Select Case DdlOtroFormaPago.SelectedValue Case "1" 'Debito DtPagos.Rows.Add({18, TxtImporteOtrosContado.Text.ToDecimal}) Case "2" 'Crédito DtPagos.Rows.Add({4, TxtImporteOtrosContado.Text.ToDecimal}) Case "3" 'Transferencia DtPagos.Rows.Add({3, TxtImporteOtrosContado.Text.ToDecimal}) End Select End If If TxtImporteEfectivo.Text.ToDecimal > 0 Then Dim tpag As Decimal = LtlSaldo.Text.ToDecimal - PagadoSinEfectivo If TxtImporteEfectivo.Text.ToDecimal < tpag Then tpag = TxtImporteEfectivo.Text.ToDecimal DtPagos.Rows.Add({1, tpag}) End If Dim PagoMaximo = DtPagos.MAX("Importe") Dim CveFormaPago As Integer = DtPagos.FiltroPrimeroValor("CveFormaPago", $"Importe = {PagoMaximo}").ToEntero() If CveFormaPago > 0 Then ObjFactura.CveFormaPago = CveFormaPago ObjFactura.CveMetodoPago = 1 ObjFactura.ClaveMetodoPagoSAT = "PUE" ObjFactura.ClaveFormaPagoSAT = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {ObjFactura.CveFormaPago}") End If ObjFactura.FechaPago = Now 'venta de cantado el mismo dia Else 'venta a crédito ObjFactura.CveFormaPago = 20 ' por definir ObjFactura.ClaveFormaPagoSAT = "99" ObjFactura.CveMetodoPago = 3 'PPD ObjFactura.ClaveMetodoPagoSAT = "PPD" ObjFactura.CondicionesPago = 1 ' condiciones de pago: crédito End If ObjFactura.CveUsoCFDI = VentaRemision.CveUsoCFDI ObjFactura.ClaveUsoCFDISAT = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {VentaRemision.CveUsoCFDI}") 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(), CvePromocionDetalle:=Dr("CvePromocionDetalle").ToString.ToEntero) Next If Not ValidateString(ObservacionesAlmacen.ToLower(), "parcial") 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() 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)) DtAnticipos.Columns.Add("Tipo", GetType(String)) If TxtNCDev.Text.ToDecimal() > 0 Then For Each GvRow As GridViewRow In GVAnticipos.Rows If GvRow.DataKey("Tipo").Contiene("NC", "IxC") AndAlso 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") Dim Tipo = GvRow.DataKey("Tipo") DtAnticipos.Rows.Add(CveVenta, Importe, CveConceptoContable, CveIE, FolioFiscal, Descuentos, TotalAnticipo, SubTotalAnticipo, CveMoneda, Fecha, TipoCambioPago, Folio, Tipo) End If Next End If If DtAnticipos.Rows.Count > 0 Then ObjFactura.EsNCAmortizacion = True ObjFactura.CveTipoAmortizacionAnticipo = 4 ObjFactura.DtAnticiposAplicados = DtAnticipos End If ObjFactura.CveVendedor = CveVendedor ObjFactura.ObservacionesAlmacen = ObservacionesAlmacen ObjFactura.Observaciones = Observaciones ObjFactura.PedidoContrato = PedidoContrato ObjFactura.OrdenCompra = OrdenCompra If ListaAnticiposAplicados IsNot Nothing Then 'SI TIENE RELACIONADOS ANTICIPOS PONER TIPO RELACION 7 If ListaAnticiposAplicados.Where(Function(x) x.Tipo = "Ant").Any() Then ObjFactura.CveTipoRelacion = 7 End If 'SI TIENE NC/DEV PONER TIPO RELACION 1 If Not ListaAnticiposAplicados.Where(Function(x) x.Tipo = "Ant").Any() AndAlso ListaAnticiposAplicados.Where(Function(x) x.Tipo = "NC").Any() Then ObjFactura.CveTipoRelacion = 1 End If End If 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))) For Each dr As DataRow In DtAnticipos.Rows SBAmortizaciones.AppendLine($"
Imprimir historial {dr("Folio").ToString}
") Next SbAlert.Append(SBAmortizaciones.ToString) 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 VentaActual.CveUsoCFDI = DbRowVenta("CveUsoCFDI").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 ValidateString(texto As String, contenidoValidar As String) As Boolean Dim regex As Text.RegularExpressions.Regex = New Text.RegularExpressions.Regex("\b" + contenidoValidar + "\b") Return (regex.IsMatch(texto)) End Function Private Function GenerarNC(ImporteTotal As Decimal, CveVendedor As Integer, ByRef Venta As Venta, GvRowAnticipo As GridViewRow, ByRef ObjVentas As ClsVentas) As Modelos.Factura.MMensajeFactura Dim Retorno As Modelos.Factura.MMensajeFactura = Nothing Dim SbAlert As New StringBuilder() Try Dim ObjNC = Modelos.Factura.CrearVentaNueva(UsuarioActual, Venta.CveSubProyecto, Venta.CveCliente, Venta.CveMoneda, "Egs") ObjNC.CveMoneda = Venta.CveMoneda If ObjNC.CveMoneda = 2 Then ObjNC.TipoCambio = GlobalTipoCambio(Now).ToString().ToDecimal() Else ObjNC.TipoCambio = 1 End If Dim Total As Decimal = ImporteTotal 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 = "" Dim CvePSAnticipo As Integer = 1 Dim DatarowPS = GlobalDTPS(UsuarioActual.CveEmpresa, SATClavePS:="84111506").FiltroPrimero("CodigoPS LIKE '%ANTICIPO%' OR CodigoPS LIKE '%anticipo%' OR CodigoPS LIKE '%Anticipo%'") If DatarowPS IsNot Nothing Then CvePSAnticipo = DatarowPS("CvePS").ToString().ToEntero() End If ObjNC.AgregarPS(CvePSAnticipo, Cantidad, PU, Descuento, Obs, CveSubProyecto:=Venta.CveSubProyecto, PorcentajeIVA:=Venta.PorcentajeIVA) ObjNC.CalculaTotales() Dim CveIE As Integer = -1 Dim UUIDFactura As String = "" 'VACIO PORQUE AUN NO SE HA GENERADO If GvRowAnticipo IsNot Nothing Then CveIE = GvRowAnticipo.DataKey("CveIE").ToEntero() End If 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("CveIE", GetType(Integer)) 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, UUIDFactura, CveIE) 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)) DtAnticipos.Columns.Add("Tipo", GetType(String)) If GvRowAnticipo IsNot Nothing Then Dim CveVenta = GvRowAnticipo.DataKey("CveVenta").ToEntero() Dim Importe = GvRowAnticipo.FCTextBox(String.Format("TxtAnticipo{0}", GvRowAnticipo.RowIndex)).Text.ToDecimal() Dim CveConceptoContable = GvRowAnticipo.DataKey("CveConceptoContable").ToEntero() Dim FolioFiscal = GvRowAnticipo.DataKey("FolioFiscal") Dim Descuentos As Decimal = GvRowAnticipo.DataKey("Descuentos").ToDecimal() Dim TotalAnticipo As Decimal = GvRowAnticipo.DataKey("TotalAnticipo").ToDecimal() Dim SubTotalAnticipo As Decimal = GvRowAnticipo.DataKey("SubTotalAnticipo").ToDecimal() Dim CveMoneda As Integer = GvRowAnticipo.DataKey("CveMoneda").ToEntero() Dim Fecha As DateTime = GvRowAnticipo.DataKey("Fecha").ToDateTime() Dim TipoCambioPago As Decimal = GvRowAnticipo.DataKey("TipoCambioPago").ToDecimal() Dim Folio = GvRowAnticipo.DataKey("Folio") Dim Tipo = GvRowAnticipo.DataKey("Tipo") DtAnticipos.Rows.Add(CveVenta, Importe, CveConceptoContable, CveIE, FolioFiscal, Descuentos, TotalAnticipo, SubTotalAnticipo, CveMoneda, Fecha, TipoCambioPago, Folio, Tipo) End If ObjNC.EsNCAmortizacion = True ObjNC.CveTipoAmortizacionAnticipo = 2 ObjNC.DtAnticiposAplicados = DtAnticipos ObjNC.CveFormaPago = 21 'Aplicación de anticipos ObjNC.CveMetodoPago = 1 ObjNC.CveUsoCFDI = Venta.CveUsoCFDI ObjNC.CveVendedor = CveVendedor ObjNC.CveTipoRelacion = 7 ObjNC.PreparaTimbre() 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 Function TimbrarFactura(ByRef ObjFactura As Modelos.Factura, ByRef SeTimbro As Boolean) As Timbrado Dim MsgErrorTimbrado As String = "" Dim ObjTimbrado As New Timbrado Try SeTimbro = ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura) Dim FolioFiscalFactura As String = ObjTimbrado.UUID MsgErrorTimbrado = ObjTimbrado.MensajeErrorCFDI Catch ex As Exception OnError("Ocurrió un error al generar el timbrado", ex) End Try If Not String.IsNullOrEmpty(MsgErrorTimbrado) Then GuardaLogAD(MsgErrorTimbrado, Archivo:="LogTimbrado") End If Return ObjTimbrado End Function Private Function RegistraIE(Metodo As Integer, CveBancoCuenta As Integer, ImporteAbonoVenta As Decimal, ImporteBancos 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 = "" If CveBancoCuenta > 0 Then 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, ImporteBancos, 1, 1, Obs, "", False, True, 0, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=tCveCorte, CveAutorizacion:=CveAutorizacion, CveSubProyecto:=CveSubProyecto) If CveIEPago > 0 Then Dim tImportePago As Decimal = If(ImporteBancos > ImporteAbonoVenta, ImporteAbonoVenta, ImporteBancos) 'toma el importe menor para la factura If ImporteBancos > 0 Then Dim Pago As New VentaPago Pago.ImportePagoVenta = tImportePago Pago.ImportePago = ImporteBancos Pago.CveIE = CveIEPago Pago.CveMonedaPago = VentaActual.CveMoneda Pago.Fecha = NowADS() Pago.Referencia = VentaActual.SerieFolio If Pago.CveMonedaPago > 1 Then Pago.TCPago = GlobalTipoCambio(Now).ToDecimal ErrorConta = AplicaPrePolizaPagoVenta(VentaActual, Pago, CvePrePoliza, ObjConta) End If 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, ImporteBancos) Then Retorno = "Error en aplicación de pago.." ErrorConta = True End If HdnCveIE.Value = CveIEPago.ToString Else Retorno = "Pago en Bancos no registrado" ErrorConta = True End If Else Retorno = "No se ha especificado la cuenta" 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.FiltraParametros(" CveTipoTransaccion <> 2") 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, UsuarioActual.CveUsuario) 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, ShowCloseButton:=False) End If Else Alert("Debe especificar el efectivo en caja", TipoMensaje.ToastAdventencia, timeout:=60) 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, timeout:=60) 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, UsuarioActual.CveUsuario) 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 Dim DbRowVenta As DataRow = Nothing Dim ObjVentas As New ClsVentas If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa, VerificaAlmacen:=False) Then DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("") End If ObjVentas.Dispose() If DbRowVenta IsNot Nothing Then CveCliente = DbRowVenta("CveCliente").ToString().ToEntero() CveVendedor = DbRowVenta("CveVendedor").ToString().ToEntero() 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 Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente) Then Me.TmpDTAnticiposNCIxCCliente = ObjMovtos.DtResultados.Copy() End If ObjMovtos.Dispose() If Me.TmpDTAnticiposNCIxCCliente IsNot Nothing Then GVAnticipos.DataSource = Me.TmpDTAnticiposNCIxCCliente.FiltraParametros($"ISTotal = 0 AND Saldo > 0 AND Tipo IN('NC','IxC','Ant') ") Else GVAnticipos.DataSource = Nothing End If GVAnticipos.Columns(5).Visible = False GVAnticipos.Columns(9).Visible = False If UsuarioActual.Empresa.Funcionalidad(109) = "1" Then GVAnticipos.Columns(7).Visible = True End If GVAnticipos.DataBind() If ListaAnticiposAplicados IsNot Nothing Then ListaAnticiposAplicados.Clear() End If TxtNCDev.Text = "0.00" End If UpAnticipos.Update() 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) 'falta sacar a los usuarios a notificar. Dim gvr As GridViewRow = DirectCast(DirectCast(sender, LinkButton).BindingContainer, GridViewRow) Dim CveCliente As Integer = gvr.DataKey("CveCliente").ToEntero() Dim Folio As String = gvr.DataKey("Folio") Dim Importe As Decimal = gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal Dim Saldo As Decimal = gvr.DataKey("Saldo").ToDecimal() Dim dtt As DataTable = Nothing Dim ObjProceso As New ClsSisProcesos If ObjProceso.GetUsuariosconProceso(379, UsuarioActual.CveEmpresa) Then 'proceso para autorizar dtt = ObjProceso.DtResultados.FiltraParametros("Celular <> ''", 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 = "526621430964" If EsProduccion Then NumeroTelefono = String.Format("52{0}", dr("Celular").ToString()) End If Dim Arr As New ArrayList Arr.Add(DdlSucursalCorte.SelectedItem.Text) Arr.Add(NombreCliente) Arr.Add(Folio) Arr.Add($"$ {Importe}") If NumeroTelefono.Length = 12 Then EnvioMsg = EnviarNotificacionWhatsAppPlantilla(NumeroTelefono, "solicitud_autorizacion_anticipo", Arr, $"https://grupodiaz.adssistemas.mx.com/Ventas/CatAutorizacionLimites.aspx?CveCliente={CveCliente}") ClsSisNotificaciones.EnviarAlerta("Solicitud de Anticipo", $"Solicitud de activación de anticipo Folio: {Folio}
Ir Activar", dr("CveUsuario").ToString, Tipo:=TipoNotificacion.ToastInformacionB) End If Next End If Dim CveVenta As Integer = gvr.DataKey("CveVenta").ToEntero() Dim CveIE As Integer = gvr.DataKey("CveIE").ToEntero() Dim ObjVta As New ClsVentas If ObjVta.AddAutorizacionLimite(UsuarioActual.CveEmpresa, CveCliente, CveVendedor, Saldo, 0, UsuarioActual.CveUsuario, 1, TipoDocumento:="Ant", DiasVencidos:=1, CveVenta:=CveVenta, CveIE:=CveIE) Then Dim msgAlert = "La autorización se agregó correctamente." If EnvioMsg Then msgAlert = $"{msgAlert} Se envió una notificación de autorización a los usuarios" End If Alert(msgAlert, TipoMensaje.ToastInformacionB) End If ObjVta.Dispose() 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 PagadoSinEfectivo 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() '- PagadoSinEfectivo If e.Row.DBCampo("Tipo").Contiene("Ant") Then saldo = e.Row.DataKey("SaldoConImpuestos").ToString().ToDecimal Else saldo = e.Row.DataKey("Saldo").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 Dim AnticipoAutorizado = CBool(e.Row.DBCampo("AnticipoAutorizado")) If Not EsProduccion AndAlso UsuarioActual.CveRol = 1 Then AnticipoAutorizado = True End If If UsuarioActual.Empresa.Funcionalidad(185) = "1" Then If e.Row.DBCampo("Tipo").ToString().Contiene("NC", "Ant", "IxC") AndAlso Not 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() ListaAnticiposAplicados.Add(New Modelos.MAnticipoRelacionado() With {.CveVenta = gvr.DataKey("CveVenta").ToEntero(), .FolioFiscal = gvr.DataKey("FolioFiscal"), .Tipo = gvr.DataKey("Tipo")}) 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 DdlOtroFormaPago_SelectedIndexChanged(sender As Object, e As EventArgs) Dim DtCC As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa) Dim CveMon As Integer = 1 If DdlOtroFormaPago.SelectedValue.Contiene("1", "2") Then DdlCuentaOtrosContado.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", CveMon)) ElseIf DdlOtroFormaPago.SelectedValue.Contiene("3") Then If UsuarioActual.Empresa.Funcionalidad(109) = "1" OrElse UsuarioActual.CveEmpresa.Contiene(195, 197) Then DdlCuentaOtrosContado.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta = 1", If(CveMon <= 0, 1, CveMon))) Else DdlCuentaOtrosContado.DataSource = DtCC.FiltraParametros(String.Format("CveMoneda = {0} AND CveTipoCuenta <> 1", If(CveMon <= 0, 1, CveMon))) End If End If DdlCuentaOtrosContado.DataBind() UpContadoOtros.Update() End Sub #Region "C A N C E L A C I O N E S" Protected Sub BtnValidar_Click(ByVal sender As Object, ByVal e As EventArgs) CveVentaCancelacion = -1 Dim GvRow As GridViewRow = CType(((CType(sender, LinkButton)).NamingContainer), GridViewRow) CveVentaCancelacion = GvRow.DataKey("CveVenta").ToEntero() Dim CveCliente As Integer = GvRow.DataKey("CveCliente").ToEntero() Dim Total As String = GvRow.DataKey("Total") Dim SubTotal As String = GvRow.DataKey("SubTotal") Dim Uuid As String = GvRow.DataKey("FolioFiscal") Dim RFCReceptor As String = GvRow.DataKey("RFCReceptor") Dim Folio As String = GvRow.DataKey("Folio") Dim TipoDocto As String = GvRow.DataKey("TipoDocto") Dim Nombre As String = GvRow.DataKey("Nombre") Dim CveEstatusRefact As String = GvRow.DataKey("CveEstatusRefacturacion") Dim Msg As String If CveVentaCancelacion > 0 AndAlso Uuid <> "" Then Dim resp = VerificarVigenciaSAT(CveVentaCancelacion, CveCliente, Folio, TipoDocto, Uuid, UsuarioActual.Empresa.RFC, RFCReceptor, Total) If resp.EnviarAcuse Then Msg = resp.Mensaje If CveEstatusRefact = "4" Then Msg = Msg & "
Refacturar" End If Alert(Msg, TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnEnviarMailCancelacion()", TextoConfirmacion:="Enviar", TextoSegundoBoton:="Cancelar", ShowCloseButton:=False) Else Msg = resp.Mensaje If CveEstatusRefact = "4" Then Msg = Msg & "
Refacturar" End If Alert(Msg) End If End If CargaCancelaciones() End Sub Private Function VerificarVigenciaSAT(ByVal CveVenta As Integer, ByVal CveCliente As Integer, ByVal Folio As String, ByVal TipoDocto As String, ByVal uuid As String, ByVal emisor As String, ByVal receptor As String, ByVal total As String, ByVal Optional EsRefacturacion As Boolean = False, ByVal Optional FolioSustitucion As String = "", ByVal Optional CveEstatusFactura As Integer = -1, ByVal Optional CveMotivoSustitucion As Integer = 0) As MRespuestaSAT Dim retorno = New MRespuestaSAT With { .Mensaje = "", .EnviarAcuse = False, .LigaRefacturacion = "", .IrARefacturar = False } Dim sb = New StringBuilder() Dim CancelacionAcuse As String = "" Dim CancelacionFecha As DateTime = NowADS() Dim CveEstatus As Integer = 4 Try Dim resp = Timbrado.VerificarVigenciaSAT(uuid, UsuarioActual.Empresa.RFC, receptor, total, True) If resp IsNot Nothing Then If resp.Estado Is Nothing Then sb.Append("No se pudo comprobar el estado de la factura. El servicio del sat no esta disponible") retorno.Mensaje = sb.ToString() Return retorno End If sb.AppendFormat("Folio Fiscal: {0}
", uuid) sb.AppendFormat("Código Estado: {0}
", resp.CodigoEstatus) sb.AppendFormat("Estado: {0}
", resp.Estado) sb.AppendFormat("Es Cancelable: {0}
", If(String.IsNullOrEmpty(resp.EsCancelable), "Desconocido", resp.EsCancelable)) sb.AppendFormat("Estatus de Cancelación: {0}

", If(String.IsNullOrEmpty(resp.EsCancelable), "Desconocido", resp.EstatusCancelacion)) If Not UsuarioActual.Empresa.FacturaProduccion AndAlso (String.IsNullOrEmpty(uuid) OrElse uuid.Contains("test")) Then Dim respCancelacion = CancelarDocumento(CveVenta, CveEstatus, CveCliente, Folio, uuid, CancelacionAcuse, CancelacionFecha, TipoDocto, total.ToDouble(), UsuarioActual.Empresa.CvePAC, EsRefacturacion:=EsRefacturacion, FolioSustitucion:=FolioSustitucion, CveMotivoCancelacion:=CveMotivoSustitucion) If Not respCancelacion.HuboError Then CveEstatus = respCancelacion.CveEstatus retorno.EnviarAcuse = True sb.Append("El documento se canceló correctamente.") sb.Append($"
Imprimir Acuse") If Not EsRefacturacion Then sb.Append("

¿Desea enviar el Acuse de Cancelación al Cliente?") End If End If Else If EsRefacturacion AndAlso CveEstatusFactura = 20 AndAlso resp.Estado.ToUpper().Trim() = "VIGENTE" AndAlso String.IsNullOrEmpty(resp.EstatusCancelacion) Then CveEstatus = 23 Dim ObjVentas = New ClsVentas() If ObjVentas.UpdateEstatusVenta(CveVenta, CveEstatus, UsuarioActual.CveEmpresa) Then sb.Append("El estatus de la factura fue cambiado a 'Cancelación Pendiente'.") Else sb.Append("Ocurrió un error al cambiar el estatus de la factura.") End If ObjVentas.Dispose() ElseIf resp.Estado.ToUpper().Trim() = "CANCELADO" OrElse resp.EstatusCancelacion.ToUpper() = "PLAZO VENCIDO" Then CveEstatus = 5 Dim respCancelacion = CancelarDocumento(CveVenta, CveEstatus, CveCliente, Folio, uuid, CancelacionAcuse, CancelacionFecha, TipoDocto, total.ToDouble(), UsuarioActual.Empresa.CvePAC, EsRefacturacion:=EsRefacturacion, FolioSustitucion:=FolioSustitucion, CveMotivoCancelacion:=CveMotivoSustitucion) If Not respCancelacion.HuboError Then If respCancelacion.CveEstatus > 0 Then retorno.EnviarAcuse = True CveEstatus = respCancelacion.CveEstatus Dim ObjVentas = New ClsVentas() If ObjVentas.UpdateEstatusVenta(CveVenta, CveEstatus, UsuarioActual.CveEmpresa) Then If respCancelacion.CveEstatus = 20 Then sb.Append("El estatus de la factura fue cambiado a 'Cancelación en proceso'.") ElseIf respCancelacion.CveEstatus = 23 Then sb.Append("La solicitud de cancelación no la aplicó el SAT, intente cancelar de nuevo.
") sb.AppendFormat("Folio Fiscal: {0}
", uuid) sb.AppendFormat("Código Estado: {0}
", resp.CodigoEstatus) sb.AppendFormat("Estado: {0}
", resp.Estado) sb.AppendFormat("Es Cancelable: {0}
", If(String.IsNullOrEmpty(resp.EsCancelable), "Desconocido", resp.EsCancelable)) sb.AppendFormat("Estatus de Cancelación: {0}

", If(String.IsNullOrEmpty(resp.EsCancelable), "Desconocido", resp.EstatusCancelacion)) Else sb.Append("El estatus de la factura fue cambiado a 'Cancelada'.") End If Else sb.Append("Ocurrió un error al cambiar el estatus de la factura.") End If ObjVentas.Dispose() sb.Append("El documento se canceló correctamente.") sb.Append($"
Imprimir Acuse") If Not EsRefacturacion Then sb.Append("

¿Desea enviar el Acuse de Cancelación al Cliente?") End If Else sb.Append(respCancelacion.Mensaje) End If End If ElseIf resp.EstatusCancelacion.ToUpper() = "SOLICITUD RECHAZADA" Then CveEstatus = 3 Dim Estatus As String = "Emitida" If EsRefacturacion Then CveEstatus = 23 Estatus = "Cancelación pendiente" End If Dim ObjVentas = New ClsVentas() If ObjVentas.UpdateEstatusVenta(CveVenta, CveEstatus, UsuarioActual.CveEmpresa) Then sb.Append($"El estatus de la factura fue cambiado a '{Estatus}'.") Else sb.Append("Ocurrió un error al cambiar el estatus de la factura.") End If ObjVentas.Dispose() ElseIf resp.Estado.ToUpper().Trim() = "VIGENTE" AndAlso String.IsNullOrEmpty(resp.EstatusCancelacion) AndAlso Not EsRefacturacion Then CveEstatus = 3 Dim Estatus As String = "Emitida" If EsRefacturacion Then CveEstatus = 23 Estatus = "Cancelación pendiente" End If Dim ObjVentas = New ClsVentas() If ObjVentas.UpdateEstatusVenta(CveVenta, CveEstatus, UsuarioActual.CveEmpresa) Then sb.Append($"El estatus de la factura fue cambiado a '{Estatus}'.") Else sb.Append("Ocurrió un error al cambiar el estatus de la factura.") End If ObjVentas.Dispose() ElseIf (resp.EsCancelable.ToUpper() = "NO CANCELABLE") Then sb.Append("Esta factura no es cancelable.") retorno.Mensaje = sb.ToString() Return retorno End If End If Else sb.Append("No se pudo comprobar la vigencia de la factura.") retorno.Mensaje = sb.ToString() Return retorno End If Catch ex As Exception sb.Append("Error al consumir el servicio: " & ex.Message) retorno.Mensaje = sb.ToString() Return retorno End Try retorno.CveEstatus = CveEstatus retorno.Mensaje = sb.ToString() Return retorno End Function Private Function CancelarDocumento(ByVal CveVenta As Integer, ByVal CveEstatus As Integer, ByVal CveCliente As Integer, ByVal Folio As String, ByVal FolioFiscal As String, ByVal CancelacionAcuse As String, ByVal CancelacionFecha As DateTime, ByVal TipoComprobante As String, ByVal Total As Double, ByVal CvePACCancelacion As Integer, ByVal Optional EsRefacturacion As Boolean = False, ByVal Optional FolioSustitucion As String = "", ByVal Optional CveEstatusRefacturacion As Integer = 0, ByVal Optional CveMotivoCancelacion As Integer = 0) As Modelos.Factura.MCancelacionVentaMensaje Dim retorno As Modelos.Factura.MCancelacionVentaMensaje = Nothing Dim factura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, EsCancelacion:=True, VerificaAlmacen:=True) If factura.ErrorList.Count > 0 Then retorno.HuboError = True Return retorno End If If EsRefacturacion Then If Not String.IsNullOrEmpty(FolioSustitucion) Then CveEstatusRefacturacion = 2 End If If CveEstatusRefacturacion > 0 Then factura.CveEstatusRefacturacion = CveEstatusRefacturacion End If If CveMotivoCancelacion > 0 Then factura.CveMotivoCancelacion = CveMotivoCancelacion End If Dim CveEstatusFactura As Integer = -1 If CveEstatus = 5 Then CveEstatusFactura = CveEstatus End If If CveEstatus = -2 Then CveEstatusFactura = -1 End If retorno = factura.CancelarPorRefacturacion(factura.CveMotivoCancelacion, factura.MotivoCancelacion, FolioSustitucion:=FolioSustitucion, CveEstadoCancelacion:=CveEstatusFactura) Else If UsuarioActual.Empresa.Funcionalidad(531) = "1" AndAlso factura.TipoDocto = "Dev" AndAlso factura.SaldoAlmacen <> 0 Then factura.RealizarDevolucionAlmacen = 1 End If If UsuarioActual.Empresa.Funcionalidad(567) = "1" AndAlso factura.TipoDocto.Contiene("Ing", "Dev") AndAlso factura.SaldoAlmacen <> 0 Then factura.RealizarDevolucionAlmacen = 1 End If If UsuarioActual.TienePermisoProceso(269) AndAlso factura.TipoDocto.Contiene("Ing", "Dev") AndAlso factura.SaldoAlmacen <> 0 Then factura.RealizarDevolucionAlmacen = 1 End If If factura.TipoDocto = "Ing" Then Using ObjVentas = New ClsVentas() If ObjVentas.GetRemisionesRelacionadas(CveVenta, factura.TipoDocto) Then If ObjVentas.DtResultados.Copy().Rows.Count > 0 Then factura.RealizarDevolucionAlmacen = 1 End If Else retorno = New Modelos.Factura.MCancelacionVentaMensaje() retorno.Mensaje = "No se pudo verificar si tiene remisiones relacionadas" retorno.HuboError = True Return retorno End If End Using End If Dim CancelacionPagos = Modelos.OpcionesCancelacionPagos.SinPagos If UsuarioActual.Empresa.Funcionalidad(109) = "1" OrElse UsuarioActual.Empresa.Funcionalidad(382) = "1" Then CancelacionPagos = Modelos.OpcionesCancelacionPagos.ConPagos_CancelarIE End If retorno = factura.EjecutarCancelacionPendiente(CveEstatus, CancelacionFecha, CancelacionAcuse, CancelacionPagos:=CancelacionPagos) End If Return retorno End Function Protected Sub GvCancelaciones_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then Dim gv As GridView = CType(sender, GridView) If Not (e.Row.DBCampo("PuedeRefacturar").ToEntero() = 0 OrElse Not String.IsNullOrEmpty(e.Row.DBCampo("FolioFiscalSustitucion"))) Then e.Row.FCHyperLink("HplRefact").NavigateUrl = String.Format("/Ventas/Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", e.Row.DBCampo("CveVenta")) e.Row.FCHyperLink("HplRefact").Visible = True End If If e.Row.DBCampo("CveEstatusRefacturacion") = "4" AndAlso gv.ID = "GvDatos" Then e.Row.FCLinkButton("BtnValidar").Text = "02" e.Row.FCLinkButton("BtnValidar").CssClass = "btn btn-circle btn-sm blue" End If If e.Row.DBCampo("PuedeRefacturar") = "0" AndAlso e.Row.DBCampo("CveEstatusFactura") = "23" AndAlso e.Row.DBCampo("CveVentaSustitucion").ToEntero() > 0 Then If e.Row.FCLinkButton("LnkCancelar") IsNot Nothing Then e.Row.FCLinkButton("LnkCancelar").Visible = True End If End If End Sub Public Sub BtnEnviarMailCancelacion_Click(ByVal sender As Object, ByVal e As EventArgs) If CveVentaCancelacion > 0 Then ImprimeCancelacion(CveVentaCancelacion) Else Alert("No se encontro la factura para enviar el acuse", TipoMensaje.MsgAdvertencia) End If End Sub Public Sub ImprimeCancelacion(ByVal CveVenta As Integer) Dim Archivo = New System.IO.FileInfo(ModExtensiones.DirectorioBaseEmpresas & "Empresas\Grales\Formatos\AcuseCancelacion.rdlc") If Archivo.Exists Then Dim ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, CargaDTDetalle:=False, CargaDatosRelacionados:=False) Dim ObjetoPDF As Byte() = DescargarPDF(Encripta(String.Format("OP=CAN&CVEVTA={0}", CveVenta))) Dim LSRutasMail As List(Of ClsSisMail.ArchivoMail) = New List(Of ClsSisMail.ArchivoMail)() Dim Asunto As String = String.Empty Dim Cuerpo As String = String.Empty Dim sb As StringBuilder = New StringBuilder() sb.Append("") sb.Append("") sb.Append("") sb.Append("") sb.Append(" Acuse De Cancelación") sb.Append(vbTab & "") sb.Append("") sb.Append("") sb.Append(" ") sb.Append($" Estimado Cliente {ObjFactura.Cliente.Nombre},

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

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




") sb.Append(" Este correo se generó automaticamente, favor de no responder este mensaje.") sb.Append("
") sb.Append("") sb.Append("") Asunto = $"Acuse de Cancelacion {ObjFactura.SerieFolio}" Cuerpo = sb.ToString() Dim DisplayName As String = "" LSRutasMail.Add(New ClsSisMail.ArchivoMail() With { .ArchivoBinario = ObjetoPDF, .NombreArchivo = $"AcuseCancelacion{ObjFactura.SerieFolio}.pdf" }) Dim ObjMail As ClsSisMail = New ClsSisMail() If ObjMail.SendMail(UsuarioActual.Empresa, ObjFactura.Cliente.Mail, Asunto, Cuerpo, "", LSRutasMail, Displayname:=DisplayName) Then Alert("El acuse de cancelación ha sido envíado correctamente.") Else Alert("El acuse de cancelación no pudo ser enviado.", TipoMensaje.MsgError) End If End If End Sub Private Function DescargarPDF(Parametros As String) As Byte() Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?P={1}", ClsPaginas.UrlSitio, Parametros)) Dim File As Byte() = Nothing Try Using httpClient = New HttpClient() httpClient.Timeout = New TimeSpan(0, 1, 0) Using request = New HttpRequestMessage(HttpMethod.Get, Url) request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CVEUSUARIO={2}", UsuarioActual.CveEmpresa, DateTime.UtcNow.Ticks, UsuarioActual.CveUsuario))) Dim response = httpClient.SendAsync(request).Result If response.StatusCode = Net.HttpStatusCode.OK Then File = response.Content.ReadAsByteArrayAsync().Result End If End Using End Using Catch ex As Exception File = Nothing OnError("Ocurrió un error al descargar la factura", ex) End Try Return File End Function #End Region Private Sub EnviarMailFactura(EnviaCorreo As Boolean, Factura As Modelos.Factura, UsuarioActual As Usuario) 'GUARDA PDF Dim LocalSerieFolio As String = Factura.SerieFolio Dim LocalTipoDocto As String = Factura.TipoDocto Dim ArchivoPDF As String = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) 'TIMBRADO NUEVO Try If Not File.Exists(ArchivoPDF) Then GenerarPDFVenta(Factura.CveVenta, AplicaPagare:="1", GuardarPDF:=True, RegenerarPDF:=True, DescargarArchivo:=False) End If Catch ex As Exception GuardaLogAD(ex.ToString()) End Try Dim ErrorCorreo As Boolean = False If EnviaCorreo Then If Factura IsNot Nothing Then Dim ArchivoXML As String = String.Format("{0}XML\{1}\{2}.xml", UsuarioActual.Empresa.Ruta, LocalTipoDocto, LocalSerieFolio) Try Dim FIXML As New FileInfo(ArchivoXML) Dim FIPDF As New FileInfo(ArchivoPDF) If FIXML.Exists AndAlso FIPDF.Exists Then MandaMails(UsuarioActual, Factura, Factura.TipoDocto, LocalSerieFolio, EnviaCorreo, ArchivoXML, ArchivoPDF) Else ErrorCorreo = True End If Catch ex As Exception ErrorCorreo = True End Try Else ErrorCorreo = True End If If ErrorCorreo Then Dim ObjVentas As New ClsVentas(UsuarioActual:=UsuarioActual) If EnviaCorreo Then ObjVentas.UpdateVentaMail(3, Factura.CveVenta) Else ObjVentas.UpdateVentaMail(0, Factura.CveVenta) End If ObjVentas.Dispose() End If End If End Sub Private Sub MandaMails(UsuarioActual As Usuario, ObjFactura As Modelos.Factura, TipoDocto As String, SerieFolio As String, EnviarFactura As Boolean, XML As String, PDF As String) Dim ObjMail As New ClsSisMail() Dim ResultadoMail As Integer = 0 Dim CorreoDestino As String = ObjFactura.Cliente.Mail Try Dim Asunto As String = String.Empty Dim Cuerpo As String = String.Empty Dim TipoComprobante As String = "" If TipoDocto = "Ing" Then TipoComprobante = "Factura" If TipoDocto = "Egs" Then TipoComprobante = "Nota de Crédito" If UsuarioActual.Empresa.PlantillaMailVenta.Trim.Length > 0 Then Cuerpo = UsuarioActual.Empresa.PlantillaMailVenta Cuerpo = Cuerpo.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa) Cuerpo = Cuerpo.Replace("{""NombreCliente""}", ObjFactura.Cliente.NombreComercial) Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante) Cuerpo = Cuerpo.Replace("{""Fecha""}", ObjFactura.Fecha.ToString("dd/MM/yyyy")) Cuerpo = Cuerpo.Replace("{""Total""}", ObjFactura.Total.ToString("N2")) Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", ObjFactura.FechaVencimiento.ToString("dd/MM/yyyy")) Cuerpo = Cuerpo.Replace("{""SerieFolio""}", SerieFolio) Asunto = Asunto.Replace("{""AtencionA""}", ObjFactura.AtencionA) Asunto = Asunto.Replace("{""Sucursal""}", ObjFactura.SubProyecto.SubProyecto) Asunto = Asunto.Replace("{""DescripcionVenta""}", ObjFactura.DescripcionVenta) Asunto = Asunto.Replace("{""FolioFactura""}", ObjFactura.SerieFolio) End If If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta Asunto = Asunto.Replace("{""NombreEmpresa""}", UsuarioActual.Empresa.Empresa) Asunto = Asunto.Replace("{""NombreCliente""}", ObjFactura.Cliente.NombreComercial) Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante) Cuerpo = Cuerpo.Replace("{""Fecha""}", ObjFactura.Fecha.ToString("dd/MM/yyyy")) Cuerpo = Cuerpo.Replace("{""Total""}", ObjFactura.Total.ToString("N2")) Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", ObjFactura.FechaVencimiento.ToString("dd/MM/yyyy")) Asunto = Asunto.Replace("{""SerieFolio""}", SerieFolio) Asunto = Asunto.Replace("{""AtencionA""}", ObjFactura.AtencionA) Asunto = Asunto.Replace("{""Sucursal""}", ObjFactura.SubProyecto.SubProyecto) Asunto = Asunto.Replace("{""DescripcionVenta""}", ObjFactura.DescripcionVenta) Asunto = Asunto.Replace("{""FolioFactura""}", ObjFactura.SerieFolio) End If If Not EnviarFactura Then ResultadoMail = 0 End If Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML}) Dim DisplayName As String = "" If ObjMail.SendMail(UsuarioActual.Empresa, CorreoDestino, Asunto, Cuerpo, "", LSRutasMail, Displayname:=DisplayName) Then ResultadoMail = 1 Else ResultadoMail = 3 End If Catch ex As Exception OnError("Ocurrió error al mandar el Mail", ex) ResultadoMail = 3 Finally Dim ObjVentas As New ClsVentas(UsuarioActual:=UsuarioActual) ObjVentas.UpdateVentaMail(ResultadoMail, ObjFactura.CveVenta) ObjVentas.Dispose() End Try End Sub Protected Sub LnkCxC_Click(sender As Object, e As EventArgs) CargaCxC(1, HdnCveCliente.Value.ToEntero) 'solo pesos End Sub Private Sub CargaCxC(pCveMoneda As Integer, pCveCliente As Integer) Dim Mov As New ClsMovimientos Dim FechaI As String = IfNull(Request("FechaI"), "-1").ToString Dim FechaF As String = IfNull(Request("FechaF"), "-1").ToString Dim FechaCorte As Date = NowADS().AddYears(1).ToShortDateString.ToString.ToDate If Mov.GetCxCClienteDetalle(pCveCliente, FechaI, FechaF, pCveMoneda, -1, UsuarioActual.CveEmpresa, -1, FechaCorte:=FechaCorte) Then Dim TmpCxCAux As DataTable TmpCxCAux = Mov.DtResultados.FiltraParametros("Saldo > 0 AND TipoDocto = 'Ing'", "Fecha,SerieFolio") GvCxC.DataSource = Mov.DtResultados.FiltraParametros("Saldo > 0 AND TipoDocto = 'Ing'", "Fecha,SerieFolio") End If Mov.Dispose() GvCxC.DataBind() TxtCxCAplicado.Text = "" UPPCxC.Update() RegistraScript("$('#divCxC').modal('show');", "AE2") End Sub Protected Sub BtnAplicarCxC_Click(sender As Object, e As EventArgs) Dim SaldoCxC As Decimal = 0 For Each GvRow As GridViewRow In GvCxC.Rows If GvRow.FCCheckBox("Chk") IsNot Nothing AndAlso GvRow.FCCheckBox("Chk").Checked Then SaldoCxC += GvRow.DataKey("Saldo").ToDecimal End If Next TxtCxCAplicado.Text = (SaldoCxC).FormatoNumero TxtImporteContado.Text = (LtlSaldo.Text.ToDecimal + SaldoCxC).FormatoNumero RegistraScript("$('#divCxC').hide();", "AE21") UPPCobranza.Update() UPPTotalesContado.Update() End Sub Private Property DTEstadosCaja As DataTable Get If ViewState("DTEstadosCaja") Is Nothing Then ViewState("DTEstadosCaja") = New DataTable End If Return DirectCast(ViewState("DTEstadosCaja"), DataTable) End Get Set(value As DataTable) ViewState("DTEstadosCaja") = value End Set End Property Protected Sub LnkEstadosCaja_Click(sender As Object, e As EventArgs) GvEstadoCajas.DataSource = Nothing DTEstadosCaja = New DataTable Dim objPuntoVenta As New ClsPuntoVenta Dim FechaInicio As Date = New Date(txtFechaI.Text.ToDate.Year, 1, 1) Dim FechaFin As Date = New Date(FechaInicio.Year, 12, 31) Dim CveCuenta As Integer = 197107 If objPuntoVenta.GetVta_EstadoCajas(CveCuenta, UsuarioActual.CveEmpresa, FechaInicio, FechaFin) Then GvEstadoCajas.DataSource = objPuntoVenta.DtResultados DTEstadosCaja = objPuntoVenta.DtResultados End If objPuntoVenta.Dispose() GvEstadoCajas.DataBind() UpDVEstadoCaja.Update() RegistraScript("$('#DVEstadoCaja').modal()") End Sub Protected Sub GvEstadoCajas_RowDataBound(sender As Object, e As GridViewRowEventArgs) If DTEstadosCaja.Rows.Count > 0 Then If e.Row.RowType = DataControlRowType.Header Then e.Row.Cells(0).Visible = False e.Row.Cells(1).Width = 300 End If If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Cells(0).Visible = False e.Row.Cells(1).Width = 300 e.Row.Cells(1).Attributes.Add("style", "white-space: nowrap;") Dim IndexRow As Integer = e.Row.RowIndex Dim CveCuenta As Integer = e.Row.DataKey("CveCuenta").ToEntero For x = 2 To DTEstadosCaja.Columns.Count - 1 Dim Fecha As Date = DTEstadosCaja.Columns(x).ColumnName.ToString.ToDate Dim Liga As String = $"../Contabilidad/RepMovimientosAuxiliaresCatalogo.aspx?CveCuenta={CveCuenta}&FI={Fecha.ToString("dd/MM/yyyy")}&FF={Fecha.ToString("dd/MM/yyyy")}&CveProyecto=-1&CveSubProyecto=-1&TP=1" Dim Importe As Decimal = DTEstadosCaja.Rows(IndexRow)(x).ToString.ToDecimal If Importe <> 0 Then e.Row.Cells(x).Text = $"{Importe.ToString("###,###,###.00")}" Else e.Row.Cells(x).Text = "" End If Next End If End If End Sub End Class Public Class MRespuestaSAT Public Property CveEstatus As Integer Public Property EnviarAcuse As Boolean Public Property LigaRefacturacion As String Public Property IrARefacturar As Boolean Public Property Mensaje As String End Class