3024 lines
150 KiB
VB.net
3024 lines
150 KiB
VB.net
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
|
||
|
||
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 <b>{FechaICorte.ToString("dd/MM/yyyy")}</b>. 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: '<i class=""fa fa-warning""></i> 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.<br/> Favor de cancelar la remisión y generarla con fecha actual. ', " &
|
||
"className: 'header-yellow', " &
|
||
"onEscape: function() {}, " &
|
||
"title: '<i class=""fa fa-warning""></i> 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 = 189 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
|
||
'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 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 UsuarioActual.CveEmpresa.Contiene(1, 189, 197) 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 HdnTipoAmortizacion.Value = "4" Then
|
||
If respFactura.Factura.DtAnticiposAplicados IsNot Nothing Then
|
||
PagoAplicado += respFactura.Factura.DtAnticiposAplicados.SUM("Importe")
|
||
SaldoPendienteVenta = SaldoPendienteVenta - 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
|
||
End If
|
||
|
||
'GENERAR NC PARA AMORTIZACION
|
||
If MsgError = "" AndAlso UsuarioActual.CveEmpresa.Contiene(189) AndAlso HdnTipoAmortizacion.Value = "2" Then
|
||
respNC = GenerarNC(CveVendedor, VentaActual, ObjVentas2)
|
||
|
||
If respNC IsNot Nothing Then
|
||
If respNC.TieneError Then
|
||
CveVenta = -1
|
||
|
||
If respNC.Mensajes.Count > 0 Then
|
||
MsgError = respNC.Mensajes(0)
|
||
Else
|
||
MsgError = "Ocurrió un error al generar la nota de crédito"
|
||
End If
|
||
Else
|
||
PagoAplicado += respNC.Factura.Total
|
||
SaldoPendienteVenta = SaldoPendienteVenta - PagoAplicado
|
||
|
||
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
|
||
|
||
End If
|
||
Else
|
||
MsgError = "Ocurrió un error al generar la nota de crédito"
|
||
End If
|
||
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 DebeTimbrar As Boolean = True
|
||
|
||
Dim SeTimbro As Boolean = False
|
||
Dim SeTimbroNC As Boolean = False
|
||
|
||
'SI SE GENERO FACTURA DE INGRESO, TIMBRARLA DESPUES DE REALIZAR EL PAGO
|
||
If DebeTimbrar AndAlso respFactura IsNot Nothing Then
|
||
Try
|
||
'VERIFICA SI SE GENERO NC
|
||
If respNC IsNot Nothing Then
|
||
AjustarTimbre(respFactura.Factura, respNC.Factura)
|
||
MsgTimbrado = TimbrarFactura(respFactura.Factura, respNC.Factura, SeTimbro, SeTimbroNC)
|
||
Else
|
||
AjustarTimbre(respFactura.Factura, Nothing)
|
||
MsgTimbrado = TimbrarFactura(respFactura.Factura, Nothing, SeTimbro, SeTimbroNC)
|
||
End If
|
||
|
||
If Not String.IsNullOrEmpty(MsgTimbrado) Then
|
||
Dim StrEr As String = $"<br/><div id = 'DivTipoCambioAdvertencia' class='alert alert-danger' style='padding: 5px; margin-bottom: 5px; padding-right: 25px;'><strong style = 'font-size: 20px; margin-right: 25px;' > Comprobante no emitido : </strong><br/> {MsgTimbrado}<br/>Por favor inténtelo de nuevo a través del botón 'Emitir' en ventas.</div>"
|
||
MsgTimbrado = StrEr
|
||
End If
|
||
Catch ex As Exception
|
||
GuardaLogAD(ex.ToString())
|
||
msBuild.AppendFormat("<br/>{0}<br/>", MsgTimbrado)
|
||
End Try
|
||
|
||
End If
|
||
|
||
If respFactura IsNot Nothing Then
|
||
If RegistrarPago Then
|
||
msBuild.Append("<span style=""font-size:14px;"">Pago Registrado correctamente. </span> <br/><br/>")
|
||
End If
|
||
|
||
msBuild.AppendFormat("<span style=""font-size:14px;""> La factura <a class=""Texto"" target=""_blank"" style=""font-size:18px;font-weight:bold;"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a> se genero correctamente. </span> <br/>", respFactura.CveVenta, respFactura.SerieFolio)
|
||
|
||
If SeTimbro Then
|
||
Dim xml = String.Format("<ul><li><a class=""Texto"" target=""_blank"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar XML</a></li></ul>", 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)
|
||
End If
|
||
|
||
Dim pdf = String.Format("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar PDF</a></li></ul>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", respFactura.CveVenta)))
|
||
msBuild.AppendFormat("{0}", pdf)
|
||
|
||
If respFactura.Factura.Inv_CveMovimiento > 0 Then
|
||
msBuild.AppendFormat("<b><a target='_blank' class='Texto' href=""/Inventarios/EntradasSalidas.aspx?CveMovimiento={0}"">Movimiento de Almacén</a></b><br/>", respFactura.Factura.Inv_CveMovimiento)
|
||
End If
|
||
|
||
If respNC IsNot Nothing Then
|
||
msBuild.AppendFormat("<span style=""font-size:14px;""> La nota de crédito <a class=""Texto"" target=""_blank"" style=""font-size:18px;font-weight:bold;"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a> se genero correctamente.</span> <br/>", respNC.CveVenta, respNC.SerieFolio)
|
||
If SeTimbroNC Then
|
||
Dim xml = String.Format("<ul><li><a class=""Texto"" target=""_blank"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar XML</a></li></ul>", 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("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar PDF</a></li></ul>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1", respNC.CveVenta)))
|
||
msBuild.AppendFormat("{0}", pdfNC)
|
||
End If
|
||
|
||
|
||
If respNC IsNot Nothing Then
|
||
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($"<br><a class=""Texto"" target='_blank' href=""/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=AMORTIZACIONHIS&CVEIE={0}&CVEVENTA={1}&CVECLIENTE={2}&CVEVENTAAMORTIZADA={3}&MONTO={4}",
|
||
dr("CveIE").ToString,
|
||
dr("CveVenta").ToString,
|
||
respNC.Factura.CveCliente,
|
||
respNC.CveVenta,
|
||
respNC.Factura.Total))}"">Imprimir Saldo Aplicado {dr("Folio").ToString}</a><br/>")
|
||
Next
|
||
End If
|
||
|
||
Else
|
||
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($"<br><a class=""Texto"" target='_blank' href=""/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=AMORTIZACIONHIS&CVEIE={0}&CVEVENTA={1}&CVECLIENTE={2}&CVEVENTAAMORTIZADA={3}&MONTO={4}",
|
||
dr("CveIE").ToString,
|
||
dr("CveVenta").ToString,
|
||
respFactura.Factura.CveCliente,
|
||
respFactura.CveVenta,
|
||
respFactura.Factura.Total))}"">Imprimir Saldo Aplicado {dr("Folio").ToString}</a><br/>")
|
||
Next
|
||
End If
|
||
End If
|
||
|
||
If Not String.IsNullOrEmpty(MsgTimbrado) Then
|
||
msBuild.AppendFormat("<br/>{0}<br/>", MsgTimbrado)
|
||
End If
|
||
|
||
Else
|
||
msBuild.Append($"Pago Registrado correctamente.<br/><br/> <a href=""/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1&TICKET=1®ENERAR=1", CveVenta))}"" class='Texto'>Imprimir ticket</a>")
|
||
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 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: <b>{Folio}</b>", "", 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
|
||
|
||
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()
|
||
|
||
If HdnTipoAmortizacion.Value = "4" Then
|
||
|
||
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))
|
||
|
||
For Each GvRow As GridViewRow In GVAnticipos.Rows
|
||
If GvRow.FCCheckBox("Chk" & GvRow.RowIndex) IsNot Nothing AndAlso GvRow.FCCheckBox("Chk" & GvRow.RowIndex).Checked Then
|
||
|
||
Dim CveVenta = GvRow.DataKey("CveVenta").ToEntero()
|
||
Dim Importe = GvRow.FCTextBox(String.Format("TxtAnticipo{0}", GvRow.RowIndex)).Text.ToDecimal()
|
||
Dim CveConceptoContable = GvRow.DataKey("CveConceptoContable").ToEntero()
|
||
Dim CveIE = GvRow.DataKey("CveIE").ToEntero()
|
||
|
||
Dim FolioFiscal = GvRow.DataKey("FolioFiscal")
|
||
Dim Descuentos As Decimal = GvRow.DataKey("Descuentos").ToDecimal()
|
||
Dim TotalAnticipo As Decimal = GvRow.DataKey("TotalAnticipo").ToDecimal()
|
||
Dim SubTotalAnticipo As Decimal = GvRow.DataKey("SubTotalAnticipo").ToDecimal()
|
||
Dim CveMoneda As Integer = GvRow.DataKey("CveMoneda").ToEntero()
|
||
Dim Fecha As DateTime = GvRow.DataKey("Fecha").ToDateTime()
|
||
Dim TipoCambioPago As Decimal = GvRow.DataKey("TipoCambioPago").ToDecimal()
|
||
Dim Folio = GvRow.DataKey("Folio")
|
||
Dim Tipo = GvRow.DataKey("Tipo")
|
||
|
||
DtAnticipos.Rows.Add(CveVenta, Importe, CveConceptoContable, CveIE, FolioFiscal, Descuentos, TotalAnticipo, SubTotalAnticipo, CveMoneda, Fecha, TipoCambioPago, Folio, Tipo)
|
||
|
||
End If
|
||
Next
|
||
|
||
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
|
||
|
||
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} <br/>", msg)
|
||
Next
|
||
|
||
SbAlert.AppendFormat("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar PDF Factura</a></li></ul><br/>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", Retorno.CveVenta)))
|
||
|
||
For Each dr As DataRow In DtAnticipos.Rows
|
||
SBAmortizaciones.AppendLine($"<br><a class=""Texto"" target='_blank' href=""/Compras/PopUpVerFactura.aspx?P={Encripta(String.Format("OP=AMORTIZACIONHIS&CVEIE={0}&CVEVENTA={1}&CVECLIENTE={2}&CVEVENTAAMORTIZADA={3}&MONTO={4}&SALDO={5}",
|
||
dr("CveIE").ToString,
|
||
dr("CveVenta").ToString,
|
||
Retorno.Factura.CveCliente,
|
||
Retorno.CveVenta,
|
||
Retorno.Factura.Total,
|
||
(Retorno.Factura.Total - Retorno.Factura.DtAnticiposAplicados.SUM("Importe"))))}"">Imprimir historial {dr("Folio").ToString}</a><br/>")
|
||
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
|
||
|
||
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(CveVendedor As Integer, ByRef Venta As Venta, 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 = TxtNCDev.Text.ToDecimal()
|
||
Dim subTotal As Decimal = (Total / (1D + Venta.PorcentajeIVA))
|
||
'Dim IVA = (subTotal * Factura.PorcentajeIVA).RoundSQL(2)
|
||
Dim PU As Decimal = subTotal
|
||
Dim Cantidad As Decimal = 1D
|
||
Dim Descuento As Decimal = 0
|
||
Dim Obs = ""
|
||
|
||
ObjNC.AgregarPS(DdlNCPSAnt.SelectedValue.ToEntero(), Cantidad, PU, Descuento, Obs, CveSubProyecto:=Venta.CveSubProyecto, PorcentajeIVA:=Venta.PorcentajeIVA)
|
||
ObjNC.CalculaTotales()
|
||
|
||
Dim DtVentasNC = New DataTable
|
||
DtVentasNC.Columns.Add("CveVenta", GetType(Integer))
|
||
DtVentasNC.Columns.Add("Importe", GetType(Decimal))
|
||
DtVentasNC.Columns.Add("FolioFiscal", GetType(String))
|
||
DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TC", .DataType = GetType(Decimal), .DefaultValue = 1})
|
||
DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "TCCambioValuacion", .DataType = GetType(Decimal), .DefaultValue = 1})
|
||
DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "CveEstatusFactura", .DataType = GetType(Integer), .DefaultValue = -1})
|
||
DtVentasNC.Columns.Add(New DataColumn With {.ColumnName = "Folio", .DataType = GetType(String), .DefaultValue = ""})
|
||
|
||
DtVentasNC.Rows.Add(Venta.CveVenta, Total, "")
|
||
|
||
ObjNC.DtVentasNC = DtVentasNC
|
||
|
||
Dim DtVentasRelacionadas As New DataTable()
|
||
DtVentasRelacionadas.Columns.Add("CveVenta", GetType(Integer))
|
||
DtVentasRelacionadas.Rows.Add(Venta.CveVenta)
|
||
|
||
ObjNC.DtVentasRelacionadas = DtVentasRelacionadas
|
||
|
||
Dim DtAnticipos As New DataTable()
|
||
DtAnticipos.Columns.Add("CveVenta", GetType(Integer))
|
||
DtAnticipos.Columns.Add("Importe", GetType(Decimal))
|
||
DtAnticipos.Columns.Add("CveConceptoContable", GetType(Integer))
|
||
DtAnticipos.Columns.Add("CveIE", GetType(Integer))
|
||
DtAnticipos.Columns.Add("FolioFiscal", GetType(String))
|
||
DtAnticipos.Columns.Add("Descuentos", GetType(Decimal))
|
||
DtAnticipos.Columns.Add("TotalAnticipo", GetType(Decimal))
|
||
DtAnticipos.Columns.Add("SubTotalAnticipo", GetType(Decimal))
|
||
DtAnticipos.Columns.Add("CveMoneda", GetType(Decimal))
|
||
DtAnticipos.Columns.Add("Fecha", GetType(DateTime))
|
||
DtAnticipos.Columns.Add("TipoCambioPago", GetType(Decimal))
|
||
DtAnticipos.Columns.Add("Folio", GetType(String))
|
||
DtAnticipos.Columns.Add("Tipo", GetType(String))
|
||
|
||
For Each GvRow As GridViewRow In GVAnticipos.Rows
|
||
If GvRow.FCCheckBox("Chk" & GvRow.RowIndex) IsNot Nothing AndAlso GvRow.FCCheckBox("Chk" & GvRow.RowIndex).Checked Then
|
||
Dim CveVenta = GvRow.DataKey("CveVenta").ToEntero()
|
||
Dim Importe = GvRow.FCTextBox(String.Format("TxtAnticipo{0}", GvRow.RowIndex)).Text.ToDecimal()
|
||
Dim CveConceptoContable = GvRow.DataKey("CveConceptoContable").ToEntero()
|
||
Dim CveIE = GvRow.DataKey("CveIE").ToEntero()
|
||
|
||
Dim FolioFiscal = GvRow.DataKey("FolioFiscal")
|
||
Dim Descuentos As Decimal = GvRow.DataKey("Descuentos").ToDecimal()
|
||
Dim TotalAnticipo As Decimal = GvRow.DataKey("TotalAnticipo").ToDecimal()
|
||
Dim SubTotalAnticipo As Decimal = GvRow.DataKey("SubTotalAnticipo").ToDecimal()
|
||
Dim CveMoneda As Integer = GvRow.DataKey("CveMoneda").ToEntero()
|
||
Dim Fecha As DateTime = GvRow.DataKey("Fecha").ToDateTime()
|
||
Dim TipoCambioPago As Decimal = GvRow.DataKey("TipoCambioPago").ToDecimal()
|
||
Dim Folio = GvRow.DataKey("Folio")
|
||
Dim Tipo = GvRow.DataKey("Tipo")
|
||
|
||
|
||
DtAnticipos.Rows.Add(CveVenta, Importe, CveConceptoContable, CveIE, FolioFiscal, Descuentos, TotalAnticipo, SubTotalAnticipo, CveMoneda, Fecha, TipoCambioPago, Folio, Tipo)
|
||
End If
|
||
Next
|
||
|
||
ObjNC.EsNCAmortizacion = True
|
||
ObjNC.CveTipoAmortizacionAnticipo = 2
|
||
ObjNC.DtAnticiposAplicados = DtAnticipos
|
||
|
||
ObjNC.PreparaTimbre()
|
||
|
||
ObjNC.CveFormaPago = 21 'Aplicación de anticipos
|
||
ObjNC.CveMetodoPago = 1
|
||
ObjNC.CveMetodoPago = 1
|
||
|
||
ObjNC.CveVendedor = CveVendedor
|
||
|
||
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} <br/>", msg)
|
||
Next
|
||
|
||
SbAlert.AppendFormat("<ul><li><a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?P={0}"">Descargar PDF Factura</a></li></ul><br/>", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", Retorno.CveVenta)))
|
||
Else
|
||
SbAlert.Append("Ocurrió un error al generar la nota de crédito")
|
||
End If
|
||
Catch ex As Exception
|
||
SbAlert.Append("Ocurrió un error al generar el documento")
|
||
GuardaLog(ex.ToString())
|
||
End Try
|
||
Return Retorno
|
||
End Function
|
||
|
||
Private Sub AjustarTimbre(ByRef ObjFactura As Modelos.Factura, ByRef ObjNC As Modelos.Factura)
|
||
ObjFactura.Timbre.CFDIRelacionados.UUID.Clear()
|
||
If HdnTipoAmortizacion.Value = "2" Then
|
||
Dim Anticipos = ListaAnticiposAplicados.Where(Function(Obj) Obj.Tipo = "Ant")
|
||
If Anticipos IsNot Nothing AndAlso Anticipos.Count() > 0 Then
|
||
For Each Ant As Modelos.MAnticipoRelacionado In Anticipos
|
||
ObjFactura.Timbre.CFDIRelacionados.UUID.Add(Ant.FolioFiscal)
|
||
Next
|
||
|
||
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = "07"
|
||
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo"
|
||
|
||
'AJUSTAR NC
|
||
If ObjNC IsNot Nothing Then
|
||
ObjNC.Timbre.CFDIRelacionados.UUID.Clear()
|
||
|
||
ObjNC.Timbre.CFDIRelacionados.TipoRelacion = "07"
|
||
ObjNC.Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo"
|
||
End If
|
||
End If
|
||
|
||
End If
|
||
|
||
'DEVOLUCIONES DE OTRA VENTA, APLICADAS EN UNA NUEVA
|
||
If HdnTipoAmortizacion.Value = "4" Then
|
||
Dim DevolucionesNC = ListaAnticiposAplicados.Where(Function(Obj) Obj.Tipo = "NC")
|
||
If DevolucionesNC IsNot Nothing AndAlso DevolucionesNC.Count() > 0 Then
|
||
For Each Ant As Modelos.MAnticipoRelacionado In DevolucionesNC
|
||
ObjFactura.Timbre.CFDIRelacionados.UUID.Add(Ant.FolioFiscal)
|
||
Next
|
||
|
||
'TEMPORAL- DEBE SER TIPO RELACION "01 - Nota de crédito de los documentos relacionados"
|
||
Dim CveTipoRelacion As Integer = 1
|
||
|
||
ObjFactura.CveTipoRelacion = CveTipoRelacion
|
||
|
||
Dim RowTipoRelacion As DataRow = GlobalDTVtaTiposRelacion().FiltroPrimero($"CveTipoRelacion = {CveTipoRelacion}")
|
||
|
||
ObjFactura.Timbre.CFDIRelacionados.TipoRelacion = RowTipoRelacion("SATClaveTipoRelacion").ToString()
|
||
ObjFactura.Timbre.CFDIRelacionados.TipoRelacionTexto = RowTipoRelacion("SATTipoRelacion").ToString()
|
||
|
||
End If
|
||
|
||
End If
|
||
|
||
End Sub
|
||
|
||
Private Function TimbrarFactura(ByRef ObjFactura As Modelos.Factura, ByRef ObjNC As Modelos.Factura, ByRef SeTimbro As Boolean, ByRef SeTimbroNC As Boolean) As String
|
||
Dim MsgErrorTimbrado As String = ""
|
||
'Dim SeTimbro As Boolean = False
|
||
'Dim TimbroNC As Boolean = False
|
||
|
||
Dim ObjTimbrado As New Timbrado
|
||
Try
|
||
SeTimbro = ObjTimbrado.TimbrarFactura(UsuarioActual, ObjFactura)
|
||
Dim FolioFiscalFactura As String = ObjTimbrado.UUID
|
||
MsgErrorTimbrado = ObjTimbrado.MensajeErrorCFDI
|
||
ObjTimbrado = Nothing
|
||
|
||
If SeTimbro AndAlso ObjNC IsNot Nothing Then
|
||
If ObjNC.Timbre IsNot Nothing Then
|
||
ObjNC.Timbre.CFDIRelacionados.UUID.Clear()
|
||
ObjNC.Timbre.CFDIRelacionados.UUID.Add(FolioFiscalFactura)
|
||
|
||
Dim ObjTimbradoNC As New Timbrado
|
||
SeTimbroNC = ObjTimbradoNC.TimbrarFactura(UsuarioActual, ObjNC)
|
||
|
||
If Not SeTimbroNC Then
|
||
MsgErrorTimbrado = $"{MsgErrorTimbrado} {ObjTimbradoNC.MensajeErrorCFDI}"
|
||
End If
|
||
ObjTimbradoNC = Nothing
|
||
End If
|
||
End If
|
||
|
||
Catch ex As Exception
|
||
OnError("Ocurrió un error al generar el timbrado", ex)
|
||
End Try
|
||
|
||
If Not String.IsNullOrEmpty(MsgErrorTimbrado) Then
|
||
GuardaLogAD(MsgErrorTimbrado, Archivo:="LogTimbrado")
|
||
End If
|
||
|
||
Return MsgErrorTimbrado
|
||
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
|
||
|
||
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<br/><br/>"
|
||
|
||
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("<a href='/Bancos/IE.aspx?CveIE={0}' target='_blank' class='Texto'>IE Salida: {1}</a>     <br/> ", 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("<a href='/Bancos/IE.aspx?CveIE={0}' target='_blank' class='Texto'>IE Entrada: {1}</a>     <br/> ", 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
|
||
'QUE NO SE PUEDA REALIZAR AMORTIZACIÓN DE ANTICIPO POR DESCUENTO
|
||
If UsuarioActual.Empresa.Funcionalidad(382) = "1" Then
|
||
If DdlTipoAmortizacionAnticipo.Items.FindByValue("1") IsNot Nothing Then
|
||
DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1"))
|
||
End If
|
||
End If
|
||
|
||
Dim ObjMovtos As New ClsMovimientos()
|
||
If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente) Then
|
||
Me.TmpDTAnticiposNCIxCCliente = ObjMovtos.DtResultados.Copy()
|
||
End If
|
||
|
||
''AGREGAR LOS ANTICIPOS, DEV, IxC QUE ESTEN EN PUBLICO GENERAL
|
||
'If Me.TmpDTAnticiposNCIxCCliente IsNot Nothing AndAlso UsuarioActual.CveEmpresa.Contiene(189, 190, 192, 195, 197) Then
|
||
' Dim CveClientePublicoGeneral = UsuarioActual.Empresa.Funcionalidad(714).ToEntero()
|
||
' If CveClientePublicoGeneral > 0 Then
|
||
' If CveCliente <> CveClientePublicoGeneral Then
|
||
' If ObjMovtos.GetAnticiposNCIxCCliente(CveClientePublicoGeneral) Then
|
||
' For Each DrGeneral As DataRow In ObjMovtos.DtResultados.Rows
|
||
' Me.TmpDTAnticiposNCIxCCliente.Rows.Add(DrGeneral.ItemArray)
|
||
' Next
|
||
' End If
|
||
' End If
|
||
' End If
|
||
'End If
|
||
ObjMovtos.Dispose()
|
||
|
||
If Me.TmpDTAnticiposNCIxCCliente IsNot Nothing Then
|
||
Dim DtMovtos As DataTable = Me.TmpDTAnticiposNCIxCCliente.FiltraParametros($"Saldo > 0 AND Tipo IN('NC','IxC','Ant') ")
|
||
|
||
If DdlTipoAmortizacionAnticipo.SelectedValue = "4" Then
|
||
GVAnticipos.DataSource = DtMovtos.FiltraParametros("Tipo IN('NC','IxC')")
|
||
Else
|
||
GVAnticipos.DataSource = DtMovtos.FiltraParametros("Tipo IN('Ant')")
|
||
End If
|
||
Else
|
||
GVAnticipos.DataSource = Nothing
|
||
End If
|
||
|
||
divAmortizacionTipo.Visible = True
|
||
|
||
If UsuarioActual.Empresa.Funcionalidad(343) = "1" Then
|
||
DdlTipoAmortizacionAnticipo.Items.Remove(DdlTipoAmortizacionAnticipo.Items.FindByValue("1"))
|
||
End If
|
||
|
||
GVAnticipos.Columns(4).Visible = False
|
||
GVAnticipos.Columns(8).Visible = False
|
||
|
||
If UsuarioActual.Empresa.Funcionalidad(109) = "1" Then
|
||
GVAnticipos.Columns(6).Visible = True
|
||
End If
|
||
|
||
GVAnticipos.DataBind()
|
||
End If
|
||
UpAnticipos.Update()
|
||
End Sub
|
||
|
||
Protected Sub TxtFechaAnticipoCliente_TextChanged(sender As Object, e As EventArgs)
|
||
Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero()
|
||
|
||
If CveCliente <= 0 Then
|
||
Dim DbRowVenta As DataRow = Nothing
|
||
Dim ObjVentas As New ClsVentas
|
||
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
|
||
DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("")
|
||
End If
|
||
ObjVentas.Dispose()
|
||
|
||
If DbRowVenta IsNot Nothing Then
|
||
CveCliente = DbRowVenta("CveCliente").ToString().ToEntero()
|
||
End If
|
||
End If
|
||
|
||
If CveCliente > 0 Then
|
||
CargaAnticipos(CveCliente)
|
||
End If
|
||
|
||
End Sub
|
||
Protected Sub LnkRecargaAnticipos_Click(sender As Object, e As EventArgs)
|
||
Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero()
|
||
|
||
If CveCliente <= 0 Then
|
||
Dim DbRowVenta As DataRow = Nothing
|
||
Dim ObjVentas As New ClsVentas
|
||
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
|
||
DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("")
|
||
End If
|
||
ObjVentas.Dispose()
|
||
|
||
If DbRowVenta IsNot Nothing Then
|
||
CveCliente = DbRowVenta("CveCliente").ToString().ToEntero()
|
||
End If
|
||
End If
|
||
|
||
If CveCliente > 0 Then
|
||
CargaAnticipos(CveCliente)
|
||
End If
|
||
End Sub
|
||
|
||
Protected Sub LnkSolicitarActivarAnticipo_Click(sender As Object, e As EventArgs)
|
||
|
||
'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} <br/><a href='/Ventas/CatAutorizacionLimites.aspx?CveCliente={CveCliente}&op=ant'>Ir Activar</a>", 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
|
||
|
||
saldo = e.Row.DataKey("Saldo").ToString().ToDecimal
|
||
|
||
If DdlTipoAmortizacionAnticipo.SelectedValue.Contiene("4") Then
|
||
saldo = e.Row.DataKey("Saldo").ToString().ToDecimal
|
||
Else
|
||
saldo = e.Row.DataKey("SaldoConImpuestos").ToString().ToDecimal
|
||
End If
|
||
|
||
e.Row.FCLiteral("LtlAnticipos").Text = saldo.FormatoNumero
|
||
|
||
saldo = saldo.RoundSQL()
|
||
|
||
Dim maxsaldo As Decimal = 0
|
||
If total > saldo Then
|
||
maxsaldo = saldo
|
||
Else
|
||
maxsaldo = total
|
||
End If
|
||
|
||
Dim AmortizacionSujeridaContrato As Decimal = 0
|
||
|
||
e.Row.FCLiteral("MonedaVenta").Text = saldo.FormatoNumero(2)
|
||
e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Attributes.Add("onclick", String.Format("chkAnt(this,{0},{1},{2});", e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, saldo, AmortizacionSujeridaContrato))
|
||
e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("FnCambiaAnt({0},this,{1});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, saldo))
|
||
e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Attributes.Add("onKeyUp", String.Format("CambioTipoMoneda({0},{1},{2},{3},{4});", e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ClientID, e.Row.DataKey("Saldo"), e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).ClientID, e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).ClientID, e.Row.DataKey("CveMoneda")))
|
||
|
||
If e.Row.DataKey("CveIE").ToString().ToEntero() > 0 Then
|
||
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Bancos/IE.aspx?CveIE={0}"">{1}</a>", e.Row.DataKey("CveIE"), e.Row.DataKey("Folio"))
|
||
Else
|
||
e.Row.FCLiteral("LtlFactura").Text = String.Format("<a class=""Texto"" href=""/Ventas/Ventas.aspx?CveVenta={0}"">{1}</a>", e.Row.DataKey("CveVenta"), e.Row.DataKey("Folio"))
|
||
End If
|
||
|
||
If e.Row.DataKey("ISTotal") = "1" Then
|
||
e.Row.Cells(0).Visible = False
|
||
e.Row.Cells(1).ColumnSpan = 3
|
||
e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Right
|
||
e.Row.FCLiteral("LtlFactura").Text = String.Format("Total {0} ", e.Row.DataKey("Tipo"))
|
||
e.Row.BackColor = Drawing.Color.LightGray
|
||
e.Row.Cells(2).Visible = False
|
||
e.Row.FCTextBox("TxtAnticipo" & e.Row.RowIndex).Visible = False
|
||
e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False
|
||
e.Row.FCLabel("LblTotalAnticipos").Visible = True
|
||
e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right
|
||
End If
|
||
|
||
If UsuarioActual.Empresa.Funcionalidad(185) = "1" Then
|
||
If e.Row.DBCampo("Tipo").ToString().Contiene("NC", "Ant", "IxC") AndAlso Not CBool(e.Row.DBCampo("AnticipoAutorizado")) Then
|
||
e.Row.FCCheckBox("Chk" & e.Row.RowIndex).Enabled = False
|
||
e.Row.FCCheckBox("Chk" & e.Row.RowIndex).ToolTip = "Anticipo Bloqueado"
|
||
e.Row.FCLinkButton("LnkSolicitarActivarAnticipo").Visible = True
|
||
End If
|
||
End If
|
||
|
||
If e.Row.DBCampo("CveMoneda").ToString().ToEntero() = 1 Then
|
||
e.Row.FCTextBox("TxtTC" & e.Row.RowIndex).Visible = False
|
||
End If
|
||
|
||
End If
|
||
End Sub
|
||
|
||
Protected Sub BtnAceptarAnticipos_Click(sender As Object, e As System.EventArgs) Handles BtnAceptarAnticipos.Click
|
||
|
||
If DdlTipoAmortizacionAnticipo.SelectedValue.ToEntero() <= 0 Then
|
||
Alert("Debe seleccionar un tipo de amortización", TipoMensaje.MsgAdvertencia)
|
||
Exit Sub
|
||
End If
|
||
|
||
Dim Amortizacion As Decimal = 0
|
||
|
||
If ListaAnticiposAplicados Is Nothing Then
|
||
ListaAnticiposAplicados = New List(Of Modelos.MAnticipoRelacionado)
|
||
Else
|
||
ListaAnticiposAplicados.Clear()
|
||
End If
|
||
|
||
|
||
Dim SbObs As New StringBuilder
|
||
For Each gvr As GridViewRow In GVAnticipos.Rows
|
||
If gvr.FCCheckBox("Chk" & gvr.RowIndex) IsNot Nothing AndAlso gvr.FCCheckBox("Chk" & gvr.RowIndex).Checked Then
|
||
If gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal > 0 Then
|
||
Amortizacion += gvr.FCTextBox(String.Format("TxtAnticipo{0}", gvr.RowIndex)).Text.ToDecimal()
|
||
|
||
If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then
|
||
ListaAnticiposAplicados.Add(New Modelos.MAnticipoRelacionado() With {.CveVenta = gvr.DataKey("CveVenta").ToEntero(), .FolioFiscal = gvr.DataKey("FolioFiscal"), .Tipo = gvr.DataKey("Tipo")})
|
||
End If
|
||
|
||
If DdlTipoAmortizacionAnticipo.SelectedValue = "4" Then
|
||
ListaAnticiposAplicados.Add(New Modelos.MAnticipoRelacionado() With {.CveVenta = gvr.DataKey("CveVenta").ToEntero(), .FolioFiscal = gvr.DataKey("FolioFiscal"), .Tipo = gvr.DataKey("Tipo")})
|
||
End If
|
||
End If
|
||
End If
|
||
Next
|
||
|
||
If Amortizacion > 0 Then
|
||
TxtNCDev.Text = Amortizacion.ToString()
|
||
LtlTipoAnticipo.Text = DdlTipoAmortizacionAnticipo.SelectedItem.Text
|
||
HdnTipoAmortizacion.Value = DdlTipoAmortizacionAnticipo.SelectedValue
|
||
Else
|
||
TxtNCDev.Text = ""
|
||
LtlTipoAnticipo.Text = ""
|
||
HdnTipoAmortizacion.Value = ""
|
||
End If
|
||
|
||
RegistraScript("$('#DivAnticipos').modal('hide');CalculaTotalPagoContado()", "AE")
|
||
UpL.Update()
|
||
End Sub
|
||
|
||
Protected Sub DdlTipoAmortizacionAnticipo_SelectedIndexChanged(sender As Object, e As EventArgs)
|
||
divAmortizacionTipoRelacion.Visible = DdlTipoAmortizacionAnticipo.SelectedValue = "2"
|
||
|
||
If DdlTipoAmortizacionAnticipo.SelectedValue = "2" Then
|
||
CargaDdlNCPS()
|
||
DivConceptoNC.Visible = True
|
||
Else
|
||
DivConceptoNC.Visible = False
|
||
End If
|
||
|
||
Dim CveVenta As Integer = HdnCveVenta.Value.ToEntero
|
||
Dim DbRowVenta As DataRow = Nothing
|
||
Dim ObjVentas As New ClsVentas
|
||
If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then
|
||
DbRowVenta = ObjVentas.DtResultados.Copy().FiltroPrimero("")
|
||
End If
|
||
ObjVentas.Dispose()
|
||
|
||
If DbRowVenta IsNot Nothing Then
|
||
CveCliente = DbRowVenta("CveCliente").ToString().ToEntero()
|
||
CveVendedor = DbRowVenta("CveVendedor").ToString().ToEntero()
|
||
End If
|
||
|
||
|
||
If CveCliente > 0 Then
|
||
CargaAnticipos(CveCliente)
|
||
End If
|
||
|
||
UpAnticipos.Update()
|
||
End Sub
|
||
|
||
Public Sub CargaDdlNCPS()
|
||
Dim CveSATNC As String = "84111506"
|
||
Dim dtt As New DataTable
|
||
dtt = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CodigoSATPS:=CveSATNC, AplicaParaVenta:=1) ', SATClavePS:=CveSATNC
|
||
|
||
If dtt IsNot Nothing Then
|
||
|
||
DdlNCPSAnt.DataSource = dtt
|
||
DdlNCPSAnt.Items.Insert(0, New ListItem("Seleccione", "-1"))
|
||
DdlNCPSAnt.DataBind()
|
||
dtt.Dispose()
|
||
End If
|
||
|
||
End Sub
|
||
|
||
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 & "<br/><a class='Texto' href='/Ventas/Ventas.aspx?CveDevolucion=" & CveVentaCancelacion & "&NuevaFactura=1'> Refacturar</a>"
|
||
End If
|
||
|
||
Alert(Msg, TipoMensaje.MsgConfirmacion, "BtnEnviarMailCancelacion();", TextoConfirmacion:="Enviar", TextoSegundoBoton:="Cancelar")
|
||
Else
|
||
Msg = resp.Mensaje
|
||
|
||
If CveEstatusRefact = "4" Then
|
||
Msg = Msg & "<br/><a class='Texto' href='/Ventas/Ventas.aspx?CveDevolucion=" & CveVentaCancelacion & "&NuevaFactura=1'> Refacturar</a>"
|
||
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} <br/>", uuid)
|
||
sb.AppendFormat("Código Estado: {0} <br/>", resp.CodigoEstatus)
|
||
sb.AppendFormat("Estado: {0} <br/>", resp.Estado)
|
||
sb.AppendFormat("Es Cancelable: {0} <br/>", If(String.IsNullOrEmpty(resp.EsCancelable), "Desconocido", resp.EsCancelable))
|
||
sb.AppendFormat("Estatus de Cancelación: {0} <br/><br/>", 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($"</br> <a href='/Compras/PopUpVerFactura.aspx?P={Encripta($"OP=CAN&CVEVTA={CveVenta}")}' class='Texto' target='_blank'>Imprimir Acuse</a>")
|
||
|
||
If Not EsRefacturacion Then
|
||
sb.Append("</br></br> ¿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.<br/>")
|
||
sb.AppendFormat("Folio Fiscal: {0} <br/>", uuid)
|
||
sb.AppendFormat("Código Estado: {0} <br/>", resp.CodigoEstatus)
|
||
sb.AppendFormat("Estado: {0} <br/>", resp.Estado)
|
||
sb.AppendFormat("Es Cancelable: {0} <br/>", If(String.IsNullOrEmpty(resp.EsCancelable), "Desconocido", resp.EsCancelable))
|
||
sb.AppendFormat("Estatus de Cancelación: {0} <br/><br/>", 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($"</br> <a href='/Compras/PopUpVerFactura.aspx?P={Encripta($"OP=CAN&CVEVTA={CveVenta}")}' class='Texto' target='_blank'>Imprimir Acuse</a>")
|
||
|
||
If Not EsRefacturacion Then
|
||
sb.Append("</br></br> ¿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 = "<i class='fa fa-check'>02</i>"
|
||
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("<!DOCTYPE html>")
|
||
sb.Append("<html>")
|
||
sb.Append("<head>")
|
||
sb.Append("<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8""/>")
|
||
sb.Append(" <title>Acuse De Cancelación</title>")
|
||
sb.Append(vbTab & "<meta charset=""utf-8"" />")
|
||
sb.Append("</head>")
|
||
sb.Append("<body>")
|
||
sb.Append(" <font face=""calibri"">")
|
||
sb.Append($" Estimado Cliente <b>{ObjFactura.Cliente.Nombre}</b>,<br /><br />")
|
||
sb.Append($" A través del presente medio la Empresa <b>{UsuarioActual.Empresa.Empresa} - {UsuarioActual.Empresa.RFC}</b>, canceló el documento tipo <b>{ObjFactura.TipodeComprobante}</b> <br />")
|
||
sb.Append($" con folio <b>{ObjFactura.SerieFolio}</b> y el Importe de <b>${ObjFactura.Total}</b>. <br /><br />")
|
||
sb.Append(" Le hacemos llegar el acuse de cancelación. </font> ")
|
||
sb.Append(" <font face=""calibri"" size=""2"">")
|
||
sb.Append(" <br /><br /><br /><br /><br />")
|
||
sb.Append(" <i>Este correo se generó automaticamente, favor de no responder este mensaje.</i>")
|
||
sb.Append(" </font>")
|
||
sb.Append("</body>")
|
||
sb.Append("</html>")
|
||
|
||
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
|
||
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 |