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