Option Explicit On Option Strict On Imports Extensiones Imports System.Data Imports System.IO Imports System.Xml Imports System.IO.Compression Imports System.Net Imports Microsoft.Reporting.WebForms Imports System.Net.Http Partial Class Ventas_PortalCliente Inherits ClsPaginas Const TopRegistros = 20 #Region " PROPIEDADES " Private Property CveCliente As Integer Get Return ViewState("CveCliente").ToString.ToEntero End Get Set(value As Integer) ViewState("CveCliente") = value End Set End Property Private Property Destino As String Set(value As String) ViewState("Destino") = value End Set Get Return ViewState("Destino").ToString End Get End Property Private Property DTHistorialVentas As DataTable Get Return CType(ViewState("DTHistorialVentas"), DataTable) End Get Set(value As DataTable) ViewState("DTHistorialVentas") = value End Set End Property Private Property DTCxC As DataTable Get Return CType(ViewState("DTCxC"), DataTable) End Get Set(value As DataTable) ViewState("DTCxC") = value End Set End Property Private Property DTCxCHistorial As DataTable Get Return CType(ViewState("DTCxCHistorial"), DataTable) End Get Set(value As DataTable) ViewState("DTCxCHistorial") = value End Set End Property Private Property CveVenta As Integer Get Return ViewState("CveVenta").ToString.ToEntero End Get Set(value As Integer) ViewState("CveVenta") = value End Set End Property Private Property CvePago As Integer Get Return ViewState("CvePago").ToString.ToEntero End Get Set(value As Integer) ViewState("CvePago") = value End Set End Property Private Property DtPagos As DataTable Get Return CType(ViewState("DtPagos"), DataTable) End Get Set(value As DataTable) ViewState("DtPagos") = value End Set End Property Private Property TmpDT As DataTable Get Return If(IsNothing(ViewState("TmpDT")), Nothing, CType(ViewState("TmpDT"), DataTable)) End Get Set(value As DataTable) ViewState("TmpDT") = value End Set End Property Private Property CveSubProyecto As Integer Get Return ViewState("CveSubProyecto").ToString.ToEntero End Get Set(value As Integer) ViewState("CveSubProyecto") = value End Set End Property Private Property Modalidad As String Get Return ViewState("Modalidad").ToString End Get Set(value As String) ViewState("Modalidad") = value End Set End Property Private Property Index As Integer Get Return ViewState("Index").ToString.ToEntero End Get Set(value As Integer) ViewState("Index") = value End Set End Property Private Property SubProyectoPorcentajeIVA As Double Get Return ViewState("SubProyectoPorcentajeIVA").ToString.ToDouble End Get Set(value As Double) ViewState("SubProyectoPorcentajeIVA") = value End Set End Property Private Property Folio As Integer Get Return ViewState("Folio").ToString.ToEntero End Get Set(value As Integer) ViewState("Folio") = value End Set End Property Private Property Serie As String Get Return ViewState("Serie").ToString End Get Set(value As String) ViewState("Serie") = value End Set End Property Private Property SubProyecto As String Get Return ViewState("SubProyecto").ToString End Get Set(value As String) ViewState("SubProyecto") = value End Set End Property Private Property ErrorList As List(Of String) Get Return CType(ViewState("ErrorList"), List(Of String)) End Get Set(value As List(Of String)) ViewState("ErrorList") = value End Set End Property Private Property MensajeAlert As StringBuilder Get Return CType(ViewState("MensajeAlert"), StringBuilder) End Get Set(value As StringBuilder) ViewState("MensajeAlert") = value End Set End Property Private Property ObjFactura As Modelos.Factura Get Return CType(ViewState("ObjFactura"), Modelos.Factura) End Get Set(value As Modelos.Factura) ViewState("ObjFactura") = value End Set End Property #End Region Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not IsPostBack Then Destino = String.Format("{0}\Compras\", UsuarioActual.Empresa.Ruta) Session("FileUpload") = "" ViewState("Orden") = "" RegistraScript("CargaHeader();") CvePago = -1 Modalidad = "" Index = -1 CveSubProyecto = -1 SubProyectoPorcentajeIVA = 0 Folio = -1 Serie = "" SubProyecto = "" CveCliente = UsuarioActual.CveCliente CargaDatosCliente() 'CARGAN PESTANIAS SEGUN PERMISOS If UsuarioActual.TienePermisoProceso(229) Then ' CARGA TAB HISTORIAL DE COMPRAS TabHistorialCompras.Visible = True BtnDescargarPDF.Visible = True BtnDescargarXML.Visible = True CargaHistorial() End If If UsuarioActual.TienePermisoProceso(230) Then ' CARGA TAB CUENTAS X PAGAR TabCxP.Visible = True CargaCxP() End If If UsuarioActual.TienePermisoProceso(231) Then ' CARGA TAB ANTICIPOS TabAnticipos.Visible = True CargaAnticipos() End If If UsuarioActual.TienePermisoProceso(232) Then ' CARGA TAB ORDENES DE SERVICIO TabOS.Visible = True End If If UsuarioActual.TienePermisoProceso(233) Then ' CARGA TAB RH BUZON DE CALIDAD TabBuzonCalidad.Visible = True CargarTipoBuzon() CargarClienteSucursal() End If CargaPedidos() CargaCuentasDepositos() '??ESTE TAB VA DESAPARECER - PARA QUE SOLO LA EMPRESA GESTIONE A LOS USUARIOS POR CLIENTE?? If UsuarioActual.TienePermisoProceso(234) Then ' CARGA TAB SISTEMA TabSistema.Visible = False 'CargaUsuariosPortal() End If 'CARGA TAB CONTRASENIA PARA TODOS LOS USUARIOS If UsuarioActual.CvePlataforma = 6 Then TabContraseña.Visible = True If Request("Opt") IsNot Nothing AndAlso IsNumeric(Request("Opt")) Then Tab.ActiveTabIndex = Request("Opt").ToEntero ChkPermiso4.Enabled = False ChkPermiso5.Enabled = False ChkPermiso6.Enabled = False InicializaProsepago() CargaProsePago() 'TAB PEDIDOS InicializaTabPedido() End If End Sub #Region "DATOS DEL CLIENTE" Private Sub CargaDatosCliente() LtlTitulo.Text = "Portal del Cliente:" Dim ObjClientes As New ClsClientes() If ObjClientes.GetClientes(UsuarioActual.CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa) Then If ObjClientes.DtResultados.Rows.Count > 0 Then 'Campos para Modificación LtlCliente.Text = ObjClientes.Nombre Else Alert("El Cliente Solicitado no existe, por favor revise su búsqueda.", TipoMensaje.MsgAdvertencia) End If End If ObjClientes.Dispose() End Sub #End Region #Region "TAB HISTORIAL DE VENTAS" Private Sub CargaHistorial(Optional SelectTop As Integer = 21, Optional CveClienteSucursal As Integer = -1) Dim ObjClientes As New ClsClientes() If ObjClientes.GetHistorialVentas(CveCliente, SelectTop, CveClienteSucursal:=CveClienteSucursal) Then If ObjClientes.DtResultados.Rows.Count > 0 Then 'Carga Generales LtlCantidad.Text = ObjClientes.DtResultados.Rows(0)("CountTotal").ToString.FormatoNumero(0) LtlTotalVendido.Text = ObjClientes.DtResultados.Rows(0)("Total").ToString.FormatoNumero(2) LtlMinima.Text = ObjClientes.DtResultados.Rows(0)("MIN_Total").ToString.FormatoNumero(2) LtlPromedio.Text = ObjClientes.DtResultados.Rows(0)("AVG_Total").ToString.FormatoNumero(2) LtlMaxima.Text = ObjClientes.DtResultados.Rows(0)("MAX_Total").ToString.FormatoNumero(2) 'Carga Grid DTHistorialVentas = ObjClientes.DtResultados GVHistorial.DataSource = ObjClientes.DtResultados Else GVHistorial.DataSource = Nothing End If Else GVHistorial.DataSource = Nothing End If ObjClientes.Dispose() GVHistorial.DataBind() End Sub Protected Sub GVHistorial_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVHistorial.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCHyperLink("HlPDF").NavigateUrl = $"/Compras/PopUpVerFactura.aspx?P={ Encripta($"OP=VTA&CVEVENTA={e.Row.DataKey("CveVenta")}")}" e.Row.FCHyperLink("HlXML").NavigateUrl = String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", e.Row.DataKey("CveVenta"), "XML", e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("TipoDocto")))) If e.Row.RowIndex = 0 Then e.Row.BackColor = Drawing.Color.LightGray e.Row.FCHyperLink("HlPDF").Visible = False e.Row.FCHyperLink("HlXML").Visible = False End If If Not (e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5) Then If e.Row.DBCampo("EstatusFactura") <> "Emitida" Then e.Row.FCLabel("LtlEstatus").ForeColor = Drawing.Color.Red End If End If e.Row.FCLiteral("LtlFactura").Text = e.Row.DBCampo("Folio") e.Row.Cells(2).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right ' DirectCast(e.Row.FindControl("HLSendMail"), HtmlAnchor).HRef = "javascript:$get('HdnCveVenta').value='" & e.Row.DBCampo("CveVenta") & "';$get('HdnFolioVenta').value='" & e.Row.DBCampo("folio") & "';$('#DivMail').show(1000);PosicionaObjeto('" & DirectCast(e.Row.FindControl("HLSendMail"), HtmlAnchor).ClientID & "', 'DivMail');" End If End Sub Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RblTipo.SelectedIndexChanged If DTHistorialVentas IsNot Nothing AndAlso RblTipo.SelectedValue <> "-1" Then Dim tmp As DataTable = DTHistorialVentas.FiltraParametros($"TipoDocto = '{RblTipo.SelectedValue}'") If tmp.Rows.Count > 0 Then Dim Totales As DataRow = tmp.NewRow Totales("SubTotal") = tmp.SUM("SubTotal") Totales("Total") = tmp.SUM("Total") Totales("Descuento") = tmp.SUM("Descuento") Totales("Amortizacion") = tmp.SUM("Amortizacion") Totales("MAX_Total") = tmp.MAX("MAX_Total") Totales("AVG_Total") = tmp.AVG("AVG_Total") Totales("MIN_Total") = tmp.MIN("MIN_Total") Totales("CountTotal") = tmp.COUNT("CountTotal") tmp.Rows.InsertAt(Totales, 0) End If GVHistorial.DataSource = tmp ElseIf DTHistorialVentas IsNot Nothing AndAlso RblTipo.SelectedValue = "-1" Then GVHistorial.DataSource = DTHistorialVentas End If GVHistorial.DataBind() End Sub Protected Sub BtnVerMasVentas_Click(sender As Object, e As EventArgs) If BtnVerMasVentas.Text = "Ver Más" Then CargaHistorial(-1) BtnVerMasVentas.Text = "Ver Menos" Else CargaHistorial(21) BtnVerMasVentas.Text = "Ver Más" End If End Sub Protected Sub BtnSendMail_Click(sender As Object, e As System.EventArgs) Handles BtnSendMail.Click Try If HdnCveVenta.Value <> "-1" AndAlso HdnFolioVenta.Value <> "-1" Then 'Dim ObjEmprea As New ClsEmpresas() 'If ObjEmprea.GetEmpresas(UsuarioActual.CveEmpresa, "-1", "-1", "-1", "-1") Then Dim ObjMail As New ClsSisMail() Dim Ruta As String = ModExtensiones.DirectorioBaseEmpresas & "Empresas\" & UsuarioActual.CveEmpresa & "\" If File.Exists(Ruta & "PDF\" & HdnFolioVenta.Value & ".pdf") AndAlso File.Exists(Ruta & "XML\" & HdnFolioVenta.Value & ".xml") Then Dim PDF As String = Ruta & "PDF\" & HdnFolioVenta.Value & ".pdf" Dim XML As String = Ruta & "XML\" & HdnFolioVenta.Value & ".xml" Dim ResultadoMail As Integer = 0 Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = PDF}) LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = XML}) 'If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", PDF, XML, ArrayCC, TxtBody.Text.Trim) Then If ObjMail.SendMail(UsuarioActual.Empresa, TxtParaMail.Text.Trim, "Entrega de Factura", TxtBody.Text.Trim, TxtCC.Text.Trim, LSRutasMail) Then ResultadoMail = 1 TxtCC.Text = "" TxtBody.Text = "" Alert("El correo se envió correctamente", TipoMensaje.MsgInformacion) CargaHistorial() UpnHistorial.Update() Else ResultadoMail = 3 End If Dim ObjVentas As New ClsVentas ObjVentas.UpdateVentaMail(ResultadoMail, HdnCveVenta.Value.ToEntero) ObjVentas.Dispose() Else Alert("No se pudo adjuntar el correo electrónico.", TipoMensaje.MsgAdvertencia) End If 'End If 'ObjEmprea.Dispose() Else Alert("No se seleccionó ninguna factura para envíar.", TipoMensaje.MsgAdvertencia) End If Catch ex As Exception OnError("Ocurrió error al mandar MAIL", ex) Dim ObjVentas As New ClsVentas ObjVentas.UpdateVentaMail(3, HdnCveVenta.Value.ToEntero) ObjVentas.Dispose() End Try End Sub #End Region #Region "TAB CUENTAS X PAGAR" Private Sub CargaCxP(Optional VerMas As Integer = -1) If TabCxP.Visible = True Then Dim ObjMovtos As New ClsMovimientos() 'CxC Activas If ObjMovtos.GetCxCClienteDetalle(UsuarioActual.CveCliente, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa, -1) Then GvCxC.DataSource = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act'") DTCxC = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Act'") GvCxCHistorial.DataSource = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Hist'") DTCxCHistorial = ObjMovtos.DtResultados.FiltraParametros("Tipo = 'Hist'") Else GvCxC.DataSource = Nothing GvCxCHistorial.DataSource = Nothing End If ObjMovtos.Dispose() GvCxC.DataBind() GvCxCHistorial.DataBind() End If End Sub Protected Sub GvCxCHistorial_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvCxCHistorial.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex = 0 Then e.Row.Cells(0).ColumnSpan = 4 e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Right e.Row.FCLiteral("LtlFactura").Text = "Total" & " " e.Row.Cells(1).Visible = False e.Row.Cells(2).Visible = False e.Row.Cells(3).Visible = False 'e.Row.Cells(9).ColumnSpan = 2 'e.Row.Cells(10).Visible = False e.Row.BackColor = Drawing.Color.LightGray End If If e.Row.RowIndex = 1 Then e.Row.Cells(0).Width = Unit.Pixel(60) e.Row.Cells(1).Width = Unit.Pixel(70) e.Row.Cells(2).Width = Unit.Pixel(80) e.Row.Cells(3).Width = Unit.Pixel(80) e.Row.Cells(4).Width = Unit.Pixel(90) e.Row.Cells(5).Width = Unit.Pixel(90) e.Row.Cells(6).Width = Unit.Pixel(105) e.Row.Cells(7).Width = Unit.Pixel(90) e.Row.Cells(8).Width = Unit.Pixel(105) End If e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(6).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(7).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(8).HorizontalAlign = HorizontalAlign.Right If e.Row.DBCampo("Saldo").ToDouble < 0 Then e.Row.Cells(5).ForeColor = Drawing.Color.Red If e.Row.DBCampo("DiasVencidos").ToDouble > 0 AndAlso CType(sender, GridView).ID = "GvCxC" Then e.Row.Cells(3).ForeColor = Drawing.Color.Red If e.Row.DBCampo("Original").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldoOriginal"), Literal).Text = "" If e.Row.DBCampo("Abonado").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlAbonado"), Literal).Text = "" If e.Row.DBCampo("PorRecuperado").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlPorRecuperado"), Literal).Text = "" If e.Row.DBCampo("Saldo").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldo"), Literal).Text = "" If e.Row.DBCampo("PorXRecuperar").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlPorXRecuperar"), Literal).Text = "" e.Row.FCLiteral("LtlFactura").Text = e.Row.DBCampo("Folio") If CType(sender, GridView).ID = "GvCxCHistorial" Then DirectCast(e.Row.FindControl("LtlDiasVencido"), Literal).Text = "" Else e.Row.Cells(7).Font.Bold = True e.Row.Cells(8).Font.Bold = True End If End If End Sub Protected Sub GvCxC_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvCxC.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.FCLinkButton("HlVerMas").CommandArgument = e.Row.DataKey("CveVenta") 'e.Row.FCLinkButton("LBPagar").CommandArgument = $"{e.Row.DBCampo("CveVenta")}°{e.Row.DBCampo("Folio")}°{e.Row.DBCampo("Fecha")}°{e.Row.DBCampo("Original")}°{e.Row.DBCampo("Abonado")}°{e.Row.DBCampo("PorRecuperado")}°{e.Row.DBCampo("Saldo")}°{e.Row.DBCampo("PorXRecuperar")}" If e.Row.RowIndex = 0 Then e.Row.Cells(0).ColumnSpan = 4 e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Right e.Row.FCLiteral("LtlFactura").Text = "Total" & " " e.Row.Cells(1).Visible = False e.Row.Cells(2).Visible = False e.Row.Cells(3).Visible = False 'e.Row.Cells(9).ColumnSpan = 2 'e.Row.Cells(10).Visible = False e.Row.BackColor = Drawing.Color.LightGray e.Row.FCCheckBox("ChkPagar").Visible = False End If If e.Row.RowIndex = 1 Then e.Row.Cells(0).Width = Unit.Pixel(60) e.Row.Cells(1).Width = Unit.Pixel(70) e.Row.Cells(2).Width = Unit.Pixel(80) e.Row.Cells(3).Width = Unit.Pixel(80) e.Row.Cells(4).Width = Unit.Pixel(90) e.Row.Cells(5).Width = Unit.Pixel(90) e.Row.Cells(6).Width = Unit.Pixel(105) e.Row.Cells(7).Width = Unit.Pixel(90) e.Row.Cells(8).Width = Unit.Pixel(105) End If e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(6).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(7).HorizontalAlign = HorizontalAlign.Right e.Row.Cells(8).HorizontalAlign = HorizontalAlign.Right If e.Row.DBCampo("Saldo").ToDouble < 0 Then e.Row.Cells(5).ForeColor = Drawing.Color.Red If e.Row.DBCampo("DiasVencidos").ToDouble > 0 AndAlso CType(sender, GridView).ID = "GvCxC" Then e.Row.Cells(4).ForeColor = Drawing.Color.Red If e.Row.DBCampo("Original").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldoOriginal"), Literal).Text = "" If e.Row.DBCampo("Abonado").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlAbonado"), Literal).Text = "" If e.Row.DBCampo("PorRecuperado").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlPorRecuperado"), Literal).Text = "" If e.Row.DBCampo("Saldo").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlSaldo"), Literal).Text = "" If e.Row.DBCampo("PorXRecuperar").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlPorXRecuperar"), Literal).Text = "" e.Row.FCLiteral("LtlFactura").Text = e.Row.DBCampo("Folio") If CType(sender, GridView).ID = "GvCxCHistorial" Then DirectCast(e.Row.FindControl("LtlDiasVencido"), Literal).Text = "" Else e.Row.Cells(7).Font.Bold = True e.Row.Cells(8).Font.Bold = True End If End If End Sub Protected Sub HlVerMas_Click(sender As Object, e As EventArgs) Dim CveVenta = CType(sender, LinkButton).CommandArgument.ToEntero RegistraScript("$('#ModalBitacora').modal()") CargaEventoBitacora(CveVenta) End Sub Private Sub CargaEventoBitacora(CveVenta As Integer) Dim ObjEventoBitacora As New ClsOIEventos() If ObjEventoBitacora.GetAgendaBitacora(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then GvEB.DataSource = ObjEventoBitacora.DtResultados.FiltraParametros("CveTipoEvento = 6 OR CveTipoEvento = 2").ToString Else GvEB.DataSource = Nothing End If ObjEventoBitacora.Dispose() UPAddEventoBitacora.Update() End Sub #Region " PAGO PROSEPAGO " Private Sub InicializaProsepago() If Not UsuarioActual.CveEmpresa.Contiene(1, 4, 7, 11, 12, 145) Then GvCxC.Columns(10).Visible = False LBPagar.Visible = False End If End Sub Protected Sub LBPagar_Click(sender As Object, e As EventArgs) DtPagos = New DataTable DtPagos.TableName = "PagoPortalCliente" DtPagos.Columns.Add("CveCliente", GetType(Integer)) DtPagos.Columns.Add("CveVenta", GetType(Integer)) DtPagos.Columns.Add("Factura", GetType(String)) DtPagos.Columns.Add("CveSubProyecto", GetType(Integer)) DtPagos.Columns.Add("CveMoneda", GetType(Integer)) DtPagos.Columns.Add("TCVenta", GetType(Decimal)) DtPagos.Columns.Add("ImporteVenta", GetType(Decimal)) DtPagos.Columns.Add("IVA", GetType(Decimal)) DtPagos.Columns.Add("PorcentajeIVA", GetType(Decimal)) DtPagos.Columns.Add("RetIVA", GetType(Decimal)) DtPagos.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) DtPagos.Columns.Add("RetISR", GetType(Decimal)) DtPagos.Columns.Add("PorcentajeRetISR", GetType(Decimal)) DtPagos.Columns.Add("IEPS", GetType(Decimal)) DtPagos.Columns.Add("PorcentajeIEPS", GetType(Decimal)) DtPagos.Columns.Add("TCPago", GetType(Decimal)) DtPagos.Columns.Add("ImportePago", GetType(Decimal)) DtPagos.Columns.Add("ImportePagoMX", GetType(Decimal)) Dim Facturas = "" Dim TCPago = GlobalTipoCambio(Now) For Each Gvr As GridViewRow In GvCxC.Rows If Gvr.FCCheckBox("ChkPagar").Checked Then Dim Dr = DtPagos.NewRow Dr("CveCliente") = CveCliente Dr("CveVenta") = Gvr.DataKey("CveVenta").ToEntero Dr("Factura") = Gvr.DataKey("Folio") Dr("CveSubProyecto") = Gvr.DataKey("CveSubProyecto").ToEntero Dr("CveMoneda") = Gvr.DataKey("CveMoneda").ToEntero Dr("TCVenta") = Gvr.DataKey("TipoCambio").ToDecimal Dr("ImporteVenta") = Gvr.DataKey("Original").ToDecimal Dr("IVA") = Gvr.DataKey("IVA").ToDecimal Dr("PorcentajeIVA") = Gvr.DataKey("PorcentajeIVA").ToDecimal Dr("RetIVA") = Gvr.DataKey("RetIVA").ToDecimal Dr("PorcentajeRetIVA") = Gvr.DataKey("PorcentajeRetIVA").ToDecimal Dr("RetISR") = Gvr.DataKey("RetISR").ToDecimal Dr("PorcentajeRetISR") = Gvr.DataKey("PorcentajeRetISR").ToDecimal Dr("IEPS") = Gvr.DataKey("IEPS").ToDecimal Dr("PorcentajeIEPS") = Gvr.DataKey("PorcentajeIEPS").ToDecimal Dr("TCPago") = If(Gvr.DataKey("CveMoneda").ToEntero = 1, 1, TCPago) Dr("ImportePago") = Gvr.DataKey("Saldo").ToDecimal If Gvr.DataKey("CveMoneda").ToEntero > 1 Then Dr("ImportePagoMX") = (Gvr.DataKey("Saldo").ToDecimal * TCPago).RoundAD() Else Dr("ImportePagoMX") = Gvr.DataKey("Saldo").ToDecimal End If DtPagos.Rows.Add(Dr) Facturas += $"{Gvr.DataKey("Folio")}," End If Next 'SIN REGISTROS SELECCIONADOS If Facturas = "" Then Alert("No se seleccionó ningun documento para pagar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If If DtPagos.MAX("CveMoneda").ToEntero > 1 Then DivPagoDolares.Visible = True LtTC.Text = TCPago.FormatoNumero(4) Else DivPagoDolares.Visible = False End If 'LbFactura.Text = Facturas.Substring(0, Facturas.Length - 2) TxtImporte.Text = DtPagos.SUM("ImportePagoMX").FormatoNumero(2) RVTxtImporte.MaximumValue = DtPagos.SUM("ImportePagoMX").FormatoNumero(2) TxtConcepto.Text = "Pago de facturas" TxtReferencia.Text = CveCliente.ToString TxtNombreCompleto.Text = LtlCliente.Text RegistraScript("$('#ModalProsePago').modal()") UpProsePago.Update() End Sub Protected Sub BtnProsePago_Click(sender As Object, e As EventArgs) Dim ClavePago = $"{UsuarioActual.CveUsuario}-{Now.Ticks}" Dim Carpeta = $"{AppDomain.CurrentDomain.BaseDirectory}/PortalCliente/ePagos/{CveCliente}" Carpeta.DirectoryExistsCreate DtPagos.WriteXml($"{Carpeta}/{ClavePago}.xml", XmlWriteMode.WriteSchema) Dim Parametro = Encripta($"Cve={ClavePago}&CveCliente={CveCliente}") Dim uriString = "" Select Case UsuarioActual.CveEmpresa Case 1, 4, 7, 11, 12, 145 uriString = "https://www.prosepago.com/tvirtual/tvds.aspx?ppost=1&t=123" ' VSH SEGURIDAD Case Else Alert("Sin terminal de pago configurada. Por favor comuniquese con su proveedor para verificar.", TipoMensaje.MsgAdvertencia) Exit Sub End Select Dim myNameValueCollection As New NameValueCollection() Dim Nombre = LimpiaTextoSoloLetras(TxtNombreCompleto.Text) myNameValueCollection.Add("nom", Nombre.Substring(0, If(Nombre.Length > 200, 200, Nombre.Length))) myNameValueCollection.Add("con", TxtConcepto.Text) myNameValueCollection.Add("ref", TxtReferencia.Text) myNameValueCollection.Add("imp", TxtImporte.Text) myNameValueCollection.Add("ema", UsuarioActual.Usuario) ' myNameValueCollection.Add("urlOk", $"{Request.Url.GetLeftPart(UriPartial.Authority)}/PortalCliente/PortalCliente.aspx?okpp=1&p={Parametro}") myNameValueCollection.Add("urlKo", $"{Request.Url.GetLeftPart(UriPartial.Authority)}/PortalCliente/PortalCliente.aspx?okpp=0&p={Parametro}") myNameValueCollection.Add("autoBack", "1") myNameValueCollection.Add("datbloq", "1") ''PARA SIMULAR RESPUESTA 'Dim Liga = $"{Request.Url.GetLeftPart(UriPartial.Authority)}/PortalCliente/PortalCliente.aspx?okpp=1&p={Parametro}" 'Alert(Liga, TipoMensaje.MsgInformacion) 'Exit Sub Response.RedirectWithData(uriString, myNameValueCollection) End Sub Private Function LimpiaTextoSoloLetras(Texto As String) As String Dim pattern As String = "[^A-Za-z\s]" Dim replacement As String = "" Return Regex.Replace(Texto, pattern, replacement) End Function Private Function LimpiaTextoSoloLetrasNumeros(Texto As String) As String Dim pattern As String = "[^A-Za-z0-9\s]" Dim replacement As String = "" Return Regex.Replace(Texto, pattern, replacement) End Function Private Sub CargaProsePago() Dim TieneError = False Dim MensajeError As New StringBuilder Dim EstatusPagoProsepago = -1 If Request("okpp") IsNot Nothing AndAlso IsNumeric(Request("okpp")) Then EstatusPagoProsepago = Request("okpp").ToEntero End If If EstatusPagoProsepago < 0 Then Exit Sub End If If EstatusPagoProsepago = 0 Then Alert("Ocurrió un error al procesar el pago, no se a realizadó ningun cargo. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If If EstatusPagoProsepago = 1 Then Dim ParametrosTexto As String = Decripta(Request("p")) If ParametrosTexto <> "" Then CargaParametros(ParametrosTexto) Dim ClavePago = UrlParametros("CVE").ToString Dim CveCliente = UrlParametros("CVECLIENTE").ToString.ToEntero Dim Carpeta = $"{AppDomain.CurrentDomain.BaseDirectory}/PortalCliente/ePagos/{CveCliente}" Dim Archivo = $"{Carpeta}/{ClavePago}.xml" Dim CveProveedorIntermediario = -1 Dim ImporteComision = 0.0D If File.Exists(Archivo) Then DtPagos = New DataTable DtPagos.ReadXml(Archivo) If DtPagos.Rows.Count > 0 Then Dim MensajeAlert As New StringBuilder Dim ObjConta As New ClsContabilidad Dim ObjCliente As New ClsClientes(ObjConta.IniciaTransacSQL) Dim CveCuentacliente = -1 Dim IdCuentaCliente = -1 Dim IdCtaContMonedaExtranjera = -1 Dim CveCuentaComplementaria = -1 Dim CveCuentaMonedaExtranjera = -1 Dim IdCtaContRetIVA = -1 Dim IdCtaContRetISR = -1 Dim CveCuentaRetIVA = -1 Dim CveCuentaRetISR = -1 If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, -1) AndAlso ObjCliente.DtResultados.Rows.Count > 0 Then IdCuentaCliente = ObjCliente.IdCtaContClientes CveCuentacliente = ObjCliente.CveCuentaClientes IdCtaContMonedaExtranjera = ObjCliente.IdCtaContMonedaExtranjera CveCuentaMonedaExtranjera = ObjCliente.CveCuentaMonedaExtranjera CveCuentaComplementaria = ObjCliente.CveCuentaComplementaria IdCtaContRetIVA = ObjCliente.IdCtaContRetIVA IdCtaContRetISR = ObjCliente.IdCtaContRetISR CveCuentaRetIVA = ObjCliente.CveCuentaRetIVA CveCuentaRetISR = ObjCliente.CveCuentaRetISR Else TieneError = True MensajeError.Append("Ocurrió un error al cargar la información contable del cliente. Por favor vuelva a intentar
") End If ' PREPOLIZA Dim CvePlantillaPoliza = 11 Dim FechaMovimiento As Date = Now Dim Concepto = "Prosepago" Dim DtConceptos As New DataTable Dim CveMonedaPago = 1 ' DETALLES Dim ConceptoContable = -1 Dim TipoMovimiento = False Dim ImporteMovimiento = 0.0D Dim importeMX = 0.0D Dim IdCtaContable = 0 Dim CveCuenta = 0 Dim ConceptoMovimiento = "" Dim Referencia = "" Dim CveSubProyecto = -1 Dim CveVenta = -1 Dim CveMonedaVenta = 1 Dim TCVenta = 0.0D Dim IVAVenta = 0.0D Dim PorcentajeIVA = 0.0D Dim RetIVAVenta = 0.0D Dim PorcentajeRetIVA = 0.0D Dim RetISRVenta = 0.0D Dim PorcentajeRetISR = 0.0D Dim IEPSVenta = 0.0D Dim PorcentajeIEPS = 0.0D Dim TCPago = 0.0D Dim PorcentajePago = 0.0D Dim ImportePago = 0.0D Dim ImportePagoMX = 0.0D Dim TCGeneral = 0.0D Dim TCFluctuacion = 0.0D Dim CveProveedorContabilizar = -1 Dim PorcentajeImpuesto As Decimal = 0 Dim CvePrePoliza = ObjConta.AddPrePolizas("PortalCliente/Pago-Prosepago", CvePlantillaPoliza, TxtImporte.Text.Trim.ToDecimal, TxtImporte.Text.Trim.ToDecimal, CveMonedaPago, FechaMovimiento, Concepto, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) If CvePrePoliza > 0 Then If ObjConta.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPoliza) Then DtConceptos = ObjConta.DtResultados End If End If If DtConceptos IsNot Nothing AndAlso DtConceptos.Rows.Count > 0 Then For Each DrPago As DataRow In DtPagos.Rows For Each DrConcepto As DataRow In DtConceptos.Rows 'REINICIALIZA VALORES ConceptoContable = DrConcepto("CveConcepto").ToString.ToEntero TipoMovimiento = If(DrConcepto("TipoMovto").ToString = "True", True, False) ImporteMovimiento = 0 importeMX = 0 IdCtaContable = 0 CveCuenta = 0 PorcentajeImpuesto = 0 ConceptoMovimiento = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, ConceptoContable, LtlCliente.Text, DrPago("Factura").ToString, DrPago("Factura").ToString) 'VALORES DE LA VENTA Referencia = DrPago("Factura").ToString CveSubProyecto = DrPago("CveSubProyecto").ToString.ToEntero CveVenta = DrPago("CveVenta").ToString.ToEntero CveMonedaVenta = DrPago("CveMoneda").ToString.ToEntero TCVenta = DrPago("TCVenta").ToString.ToDecimal IVAVenta = DrPago("IVA").ToString.ToDecimal PorcentajeIVA = DrPago("PorcentajeIVA").ToString.ToDecimal RetIVAVenta = DrPago("RetIVA").ToString.ToDecimal PorcentajeRetIVA = DrPago("PorcentajeRetIVA").ToString.ToDecimal RetISRVenta = DrPago("RetISR").ToString.ToDecimal PorcentajeRetISR = DrPago("PorcentajeRetISR").ToString.ToDecimal IEPSVenta = DrPago("IEPS").ToString.ToDecimal PorcentajeIEPS = DrPago("PorcentajeIEPS").ToString.ToDecimal TCPago = DrPago("TCPago").ToString.ToDecimal ImportePago = DrPago("ImportePago").ToString.ToDecimal ImportePagoMX = DrPago("ImportePagoMX").ToString.ToDecimal PorcentajePago = DrPago("ImportePago").ToString.ToDecimal / DrPago("ImporteVenta").ToString.ToDecimal 'EL IMPORTE PAGO ES EL IMPORTE QUE SE PAGÓ EN LA MONEDA ORIGINAL DE LA VENTA TCFluctuacion = If(UsuarioActual.Empresa.Funcionalidad(159) = "1", TCVenta, TCPago) 'CONFIGURACION POR CONCEPTO DE PREPOLIZA Select Case ConceptoContable Case 2 'PAGO CLIENTE ImporteMovimiento = ImportePago.RoundSQL() importeMX = ImportePagoMX.RoundSQL() TCGeneral = TCVenta If CveMonedaVenta = 1 Then IdCtaContable = IdCuentaCliente CveCuenta = CveCuentacliente Else IdCtaContable = IdCtaContMonedaExtranjera CveCuenta = CveCuentaComplementaria ConceptoMovimiento += $" TC:{TCPago} ${ImporteMovimiento.FormatoNumero(2)}" If ImporteMovimiento <> 0 AndAlso IdCtaContable > 0 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, 0, Referencia, 207, ConceptoMovimiento, FechaMovimiento, IdCtaContable, -1, -1, CveVenta, -1, CveSubProyecto, CveCliente, ImporteMX:=(importeMX - ImporteMovimiento).RoundSQL(), ImporteME:=ImporteMovimiento, CveCuenta:=CveCuenta, TipoCambio:=TCVenta) Then TieneError = True MensajeError.Append("No se pudo insertar el detalle de pago de la póliza
") Exit For End If End If IdCtaContable = IdCtaContMonedaExtranjera CveCuenta = CveCuentaMonedaExtranjera End If Case 134 'PAGO INTERMEDIARIO ImporteMovimiento = ImportePago.RoundSQL() importeMX = ImportePagoMX.RoundSQL() CveProveedorContabilizar = CveProveedorIntermediario If TCVenta > 1 Then ConceptoMovimiento += $" TC:{TCVenta} ${ImporteMovimiento.FormatoNumero(2)}" Case 13 'IVA X TRASLADAR If CveMonedaVenta = 1 Then ImporteMovimiento = IVAVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = IVAVenta * PorcentajePago importeMX = ImporteMovimiento * TCVenta End If PorcentajeImpuesto = PorcentajeIVA ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCVenta IdCtaContable = UsuarioActual.Empresa.IdCuentaIVAxTrasladar CveCuenta = UsuarioActual.Empresa.CveCuentaIVAxTrasladar If TCVenta > 1 Then ConceptoMovimiento += $" TC:{TCVenta} ${ImporteMovimiento.FormatoNumero(2)}" Case 61 'IVA TRASLADADO If CveMonedaVenta = 1 Then ImporteMovimiento = IVAVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = IVAVenta * PorcentajePago importeMX = ImporteMovimiento * TCFluctuacion End If PorcentajeImpuesto = PorcentajeIVA ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCFluctuacion IdCtaContable = UsuarioActual.Empresa.IdCuentaIVATrasladado CveCuenta = UsuarioActual.Empresa.CveCuentaIVATrasladado If TCFluctuacion > 1 Then ConceptoMovimiento += $" TC:{TCFluctuacion} ${ImporteMovimiento.FormatoNumero(2)}" Case 8 'RETIVA X TRASLADAR If CveMonedaVenta = 1 Then ImporteMovimiento = RetIVAVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = RetIVAVenta * PorcentajePago importeMX = ImporteMovimiento * TCVenta End If PorcentajeImpuesto = PorcentajeRetIVA ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCVenta If TCVenta > 1 Then ConceptoMovimiento += $" TC:{TCVenta} ${ImporteMovimiento.FormatoNumero(2)}" 'Conta ContPAQ If IdCtaContRetIVA <> 0 Then IdCtaContable = IdCtaContRetIVA Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetIVACirculacion").ToEntero End If End If 'Conta SIG If CveCuentaRetIVA <> 0 Then CveCuenta = CveCuentaRetIVA Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then CveCuenta = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetIVACirculacionSIG").ToEntero End If End If Case 62 'RETIVA TRASLADADO If CveMonedaVenta = 1 Then ImporteMovimiento = RetIVAVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = RetIVAVenta * PorcentajePago importeMX = ImporteMovimiento * TCFluctuacion End If PorcentajeImpuesto = PorcentajeRetIVA ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCFluctuacion If TCFluctuacion > 1 Then ConceptoMovimiento += $" TC:{TCFluctuacion} ${ImporteMovimiento.FormatoNumero(2)}" 'Conta ContPAQ If IdCtaContRetIVA <> 0 Then IdCtaContable = IdCtaContRetIVA Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetIVACirculacion").ToEntero End If End If 'Conta SIG If CveCuentaRetIVA <> 0 Then CveCuenta = CveCuentaRetIVA Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then CveCuenta = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetIVACirculacionSIG").ToEntero End If End If Case 9 'RETISR X TRASLADAR If CveMonedaVenta = 1 Then ImporteMovimiento = RetISRVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = RetISRVenta * PorcentajePago importeMX = ImporteMovimiento * TCVenta End If PorcentajeImpuesto = PorcentajeRetISR ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCVenta If TCVenta > 1 Then ConceptoMovimiento += $" TC:{TCVenta} ${ImporteMovimiento.FormatoNumero(2)}" 'Conta ContPAQ If IdCtaContRetISR <> 0 Then IdCtaContable = IdCtaContRetISR Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetISRCirculacion").ToEntero End If End If 'Conta SIG If CveCuentaRetISR <> 0 Then CveCuenta = CveCuentaRetISR Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then CveCuenta = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetISRCirculacionSIG").ToEntero End If End If Case 63 'RETISR TRASLADADO If CveMonedaVenta = 1 Then ImporteMovimiento = RetIVAVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = RetIVAVenta * PorcentajePago importeMX = ImporteMovimiento * TCFluctuacion End If PorcentajeImpuesto = PorcentajeRetISR ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCFluctuacion If TCFluctuacion > 1 Then ConceptoMovimiento += $" TC:{TCFluctuacion} ${ImporteMovimiento.FormatoNumero(2)}" 'Conta ContPAQ If IdCtaContRetISR <> 0 Then IdCtaContable = IdCtaContRetISR Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then IdCtaContable = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetISRCirculacion").ToEntero End If End If 'Conta SIG If CveCuentaRetISR <> 0 Then CveCuenta = CveCuentaRetISR Else If ObjConta.GetRetCuenta(ConceptoContable, UsuarioActual.CveEmpresa) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then CveCuenta = ObjConta.DtResultados.FiltroPrimeroValor("IdCuentaRetISRCirculacionSIG").ToEntero End If End If Case 38 'IEPS X TRASLADAR If CveMonedaVenta = 1 Then ImporteMovimiento = IEPSVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = IEPSVenta * PorcentajePago importeMX = ImporteMovimiento * TCVenta End If PorcentajeImpuesto = PorcentajeIEPS ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCVenta IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSxTrasladar CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSxTrasladar If TCVenta > 1 Then ConceptoMovimiento += $" TC:{TCVenta} ${ImporteMovimiento.FormatoNumero(2)}" Case 39 'IEPS TRASLADADO If CveMonedaVenta = 1 Then ImporteMovimiento = IEPSVenta * PorcentajePago importeMX = ImporteMovimiento ElseIf CveMonedaVenta = 2 Then ImporteMovimiento = IEPSVenta * PorcentajePago importeMX = ImporteMovimiento * TCFluctuacion End If PorcentajeImpuesto = PorcentajeIEPS ImporteMovimiento = ImporteMovimiento.RoundSQL() importeMX = importeMX.RoundSQL() TCGeneral = TCFluctuacion IdCtaContable = UsuarioActual.Empresa.IdCuentaIEPSTrasladado CveCuenta = UsuarioActual.Empresa.CveCuentaIEPSTrasladado If TCFluctuacion > 1 Then ConceptoMovimiento += $" TC:{TCFluctuacion} ${ImporteMovimiento.FormatoNumero(2)}" Case 64 'GANANCIA Continue For 'SKIPEA If CveMonedaVenta <> 1 Then IdCtaContable = UsuarioActual.Empresa.IdCuentaGananciaCambiaria CveCuenta = UsuarioActual.Empresa.CveCuentaGananciaCambiaria If TCPago > TCVenta AndAlso CveMonedaVenta = 2 Then ImporteMovimiento = (ImportePago * TCPago) - (ImportePago * TCVenta) ImporteMovimiento -= ((IVAVenta * PorcentajePago) * TCFluctuacion) - ((IVAVenta * PorcentajePago) * TCVenta) ImporteMovimiento += ((RetIVAVenta * PorcentajePago) * TCFluctuacion) - ((RetIVAVenta * PorcentajePago) * TCVenta) ImporteMovimiento += ((RetISRVenta * PorcentajePago) * TCFluctuacion) - ((RetISRVenta * PorcentajePago) * TCVenta) ImporteMovimiento -= ((IEPSVenta * PorcentajePago) * TCFluctuacion) - ((IEPSVenta * PorcentajePago) * TCVenta) ImporteMovimiento = ImporteMovimiento.RoundSQL().Abs() importeMX = ImporteMovimiento End If End If Case 65 'PERDIDA Continue For 'SKIPEA If CveMonedaVenta <> 1 Then IdCtaContable = UsuarioActual.Empresa.IdCuentaPerdidaCambiaria CveCuenta = UsuarioActual.Empresa.CveCuentaPerdidaCambiaria If TCPago < TCVenta AndAlso CveMonedaVenta = 2 Then ImporteMovimiento = (ImportePago * TCPago) - (ImportePago * TCVenta) ImporteMovimiento -= ((IVAVenta * PorcentajePago) * TCFluctuacion) - ((IVAVenta * PorcentajePago) * TCVenta) ImporteMovimiento += ((RetIVAVenta * PorcentajePago) * TCFluctuacion) - ((RetIVAVenta * PorcentajePago) * TCVenta) ImporteMovimiento += ((RetISRVenta * PorcentajePago) * TCFluctuacion) - ((RetISRVenta * PorcentajePago) * TCVenta) ImporteMovimiento -= ((IEPSVenta * PorcentajePago) * TCFluctuacion) - ((IEPSVenta * PorcentajePago) * TCVenta) ImporteMovimiento = ImporteMovimiento.RoundSQL().Abs() importeMX = ImporteMovimiento End If End If End Select 'AGREGA PREPOLIZA DETALLE If ImporteMovimiento <> 0 Then If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, ImporteMovimiento, Referencia, ConceptoContable, ConceptoMovimiento, FechaMovimiento, IdCtaContable, -1, -1, CveVenta, -1, CveSubProyecto, CveCliente, CveProveedorContabilizar, ImporteMX:=importeMX, CveCuenta:=CveCuenta, TipoCambio:=TCGeneral, PorcentajeImpuesto:=PorcentajeImpuesto) Then TieneError = True MensajeError.Append("No se pudo insertar el detalle de la póliza
") Exit For End If End If Next If TieneError Then Exit For MensajeAlert.Append($"- Factura: {DrPago("Factura")} Importe: $ {DrPago("ImportePagoMX").ToString.FormatoNumero(2)}
") Next Else TieneError = True MensajeError.Append("Ocurrió un error al procesar los conceptos de contabilización. Por favor verifique y vuelva a intentar.
") End If If Not TieneError Then ObjConta.Commit() Alert($"Se realizó el pago exitoso de las siguientes facturas:

{MensajeAlert.ToString}", TipoMensaje.MsgInformacion) Else ObjConta.RollBack() Alert(MensajeError.ToString, TipoMensaje.MsgError) End If ObjConta.Dispose() Else TieneError = True MensajeError.Append("Ocurrió un error al obtener la información de los documentos pagados. Por favor comuniquese con su proveedor para verificar.") End If Else TieneError = True MensajeError.Append("Ocurrió un error al obtener la información desde el emisor de pago. Por favor comuniquese con su proveedor para verificar.") End If Else TieneError = True MensajeError.Append("Ocurrió un error al obtener los parametros desde el emisor de pago. Por favor comuniquese con su proveedor para verificar.") End If 'SI EL PAGO SE PROCESO BIEN RECARGA CXP If Not TieneError Then MandaCorreoNotificacionPago() CargaCxP() End If If TieneError Then Alert(MensajeError.ToString, TipoMensaje.MsgError) MandaCorreoERROR(MensajeError.ToString) End If End If End Sub Private Sub MandaCorreoNotificacionPago() 'CABECERA CORREO Dim CorreoDestino = UsuarioActual.Usuario Dim CorreoCC = "rene.molina@adssistemas.mx;israel.pina@adssistemas.mx" Dim Asunto = $"Notificación de pago - {UsuarioActual.Empresa.Empresa}" 'CUERPO CORREO Dim strBody As New StringBuilder strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append("") strBody.Append($"

{UsuarioActual.Empresa.Empresa}

") strBody.Append("

Notificación de pago

") strBody.Append("

") strBody.Append($" Se le informa estimado cliente {LtlCliente.Text} que hemos recibido exitósamente su pago mediante nuestro portal de cliente SIG.") strBody.Append("

") strBody.Append("

Informacion de pago

") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append($" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append($" ") strBody.Append(" ") strBody.Append("
Importe pagado$ {DtPagos.SUM("ImportePagoMX").FormatoNumero()}
Fecha{Now.ToString("dd/MM/yyyy HH:ss")}
") strBody.Append("

Facturas abonadas

") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") strBody.Append(" ") For Each DrPago As DataRow In DtPagos.Rows strBody.Append(" ") strBody.Append($" ") strBody.Append($" ") strBody.Append(" ") Next strBody.Append("
FacturaImporte pagado
{DrPago("Factura")}$ {DrPago("ImportePagoMX").ToString.FormatoNumero()}
") strBody.Append("

Agradecemos su preferencia. Gracias por su pago.

") strBody.Append("") strBody.Append("") 'ENVIO CORREO Dim Mail As New ClsSisMail() Mail.SendMail(ClsPaginas.EmpresaNotificaciones, CorreoDestino, Asunto, strBody.ToString, CorreoCC) End Sub Private Sub MandaCorreoERROR(MensajeError As String) 'CABECERA CORREO Dim CorreoDestino = "rene.molina@adssistemas.mx;israel.pina@adssistemas.mx" Dim Asunto = $"ERROR PROCESO DE PAGO PROSEPAGO - EMPRESA:{UsuarioActual.Empresa.CveEmpresa} CLIENTE:{CveCliente}" Dim Body = $"PARAMETROS LIGA: {Request("p")}
ERROR: {MensajeError}" 'ENVIO CORREO Dim Mail As New ClsSisMail() Mail.SendMail(ClsPaginas.EmpresaNotificaciones, CorreoDestino, Asunto, Body) End Sub #End Region #End Region #Region "TAB ANTICIPOS" Private Sub CargaAnticipos(Optional SelectTop As Integer = 21, Optional CveClienteSucursal As Integer = -1) Dim ObjMovtos As New ClsMovimientos() If ObjMovtos.GetAnticiposNCIxCCliente(CveCliente, CveClienteSucursal:=CveClienteSucursal) Then GVAnticipos.DataSource = ObjMovtos.DtResultados.FiltraParametros("Saldo >0 AND SaldoSubtotal > 0") GVAnticiposHistorial.DataSource = ObjMovtos.DtResultados.FiltraParametros("SaldoSubtotal <=0") Else GVAnticipos.DataSource = Nothing GVAnticiposHistorial.DataSource = Nothing End If ObjMovtos.Dispose() GVAnticipos.DataBind() GVAnticiposHistorial.DataBind() End Sub Protected Sub GVAnticipos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVAnticipos.RowDataBound, GVAnticiposHistorial.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex = 0 Then e.Row.Cells(0).ColumnSpan = 2 e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Right e.Row.FCLiteral("LtlFactura").Text = "Total" & " " e.Row.BackColor = Drawing.Color.LightGray e.Row.Cells(1).Visible = False End If If e.Row.RowIndex = 1 Then e.Row.Cells(0).Width = Unit.Pixel(60) e.Row.Cells(1).Width = Unit.Pixel(100) e.Row.Cells(2).Width = Unit.Pixel(80) End If e.Row.Cells(2).HorizontalAlign = HorizontalAlign.Right 'If e.Row.DBCampo("Saldo").ToDouble < 0 Then e.Row.Cells(2).ForeColor = Drawing.Color.Red 'If e.Row.DBCampo("Saldo").ToDouble = 0 Then DirectCast(e.Row.FindControl("LtlAnticipos"), Literal).Text = "" If e.Row.RowIndex > 0 Then e.Row.FCLiteral("LtlFactura").Text = e.Row.DBCampo("Folio") End If If CType(sender, GridView).ID = "GVAnticipos" Then e.Row.Cells(2).Font.Bold = True End If End If End Sub Protected Sub BtnVerMasAnticipos_Click(sender As Object, e As EventArgs) If BtnVerMasAnticipos.Text = "Ver Más" Then CargaAnticipos(-1) BtnVerMasAnticipos.Text = "Ver Menos" Else CargaAnticipos(21) BtnVerMasAnticipos.Text = "Ver Más" End If End Sub #End Region #Region "TAB BUZON DE CALIDAD" Private Sub CargarTipoBuzon() If TabBuzonCalidad.Visible = True Then DdlTipoBuzon.DataSource = GlobalDTTipoBuzon DdlTipoBuzon.DataBind() End If End Sub Private Sub CargarClienteSucursal() Dim ObjClienteSucursal As New ClsClientes If ObjClienteSucursal.GetSucursales(UsuarioActual.CveCliente) Then DdlClienteSucursal.DataSource = ObjClienteSucursal.DtResultados Else DdlClienteSucursal.DataSource = Nothing End If ObjClienteSucursal.Dispose() DdlClienteSucursal.DataBind() End Sub Private Sub CargaRHPersonal() Dim ObjRHPersonal As New ClsRH If ObjRHPersonal.GetPersonal(-1, "-1", "-1", "-1", "-1", -1, -1, -1, -1, -1, -1, -1, -1, -1, UsuarioActual.CveCliente, TxtHora.PostedTime & ":00", -1, -1, -1, -1, -1, -1, "-1", "-1", "-1", "-1", UsuarioActual.CveEmpresa) Then ViewState("DTRHPersonal") = ObjRHPersonal.DtResultados Else Me.GvRHPersonal.DataSource = Nothing End If ObjRHPersonal.Dispose() CargaGridRHPersonal("") End Sub Protected Sub GvRHPersonal_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvRHPersonal.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.RowIndex >= 0 Then e.Row.Cells(0).Width = Unit.Pixel(100) 'CARGAR IMAGENES DE PERSONAL If File.Exists(ModExtensiones.DirectorioBaseEmpresas & "Empresas\" & UsuarioActual.CveEmpresa & "\RH\Personal\" & e.Row.DBCampo("URL") & ".png") Then e.Row.FCImage("ImgPersonal").ImageUrl = "/Empresas/" & UsuarioActual.CveEmpresa & "/RH/Personal/" & e.Row.DBCampo("URL") & ".png" End If 'If File.Exists(ModExtensiones.DirectorioBaseEmpresas + "Empresas\" & UsuarioActual.CveEmpresa & "\RH\Personal\" & e.Row.DBCampo("URL")) Then 'e.Row.FCLiteral("LtlImgPersonal").Text = "" 'Else 'e.Row.FCLiteral("LtlImgPersonal").Text = "" 'End If 'FIN CARGAR IMAGENES DE PERSONAL e.Row.Cells(1).Width = Unit.Pixel(250) End If e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Center End If End Sub Private Sub CargaGridRHPersonal(Orden As String) If Orden <> String.Empty Then Dim DV As New DataView(CType(ViewState("DTRHPersonal"), DataTable), "", Orden, DataViewRowState.CurrentRows) GvRHPersonal.DataSource = DV.ToTable() DV.Dispose() Else GvRHPersonal.DataSource = CType(ViewState("DTRHPersonal"), DataTable) End If GvRHPersonal.DataBind() End Sub Protected Sub BtnConsultarPersonal_Click(sender As Object, e As System.EventArgs) Handles BtnConsultarPersonal.Click CargaRHPersonal() End Sub Protected Sub BtnEnviar_Click(sender As Object, e As System.EventArgs) Handles BtnEnviar.Click 'GvRHPersonal Dim ObjQueja As New ClsRH For Each Row As GridViewRow In GvRHPersonal.Rows If Row.FCCheckBox("ChbSeleccionado").Checked Then If ObjQueja.AddBuzonCalidad(GvRHPersonal.DataKeys(Row.RowIndex).Value.ToString.ToEntero, UsuarioActual.CveCliente, DdlClienteSucursal.SelectedValue.ToEntero, DdlTipoBuzon.SelectedValue.ToEntero, TxtFechaQueja.Text.ToDate(), TxtDescripcion.Text, TxtNombreReporto.Text, TxtTelefonoReporto.Text, TxtMailReporto.Text, TxtObservaciones.Text, UsuarioActual.CveEmpresa, -1) Then Alert("Se Envió Correctamente", TipoMensaje.MsgInformacion) End If 'Si está seleccionado el check del GridView quiere decir que lo seleccionaron. Hay que hacer el insert 'La clave personal se saca de: '(string)this.grid.DataKeys[rowIndex]["myKey"]; 'GvRHPersonal.DataKeys(Row.RowIndex)("CvePersonal").ToString End If Next ObjQueja.Dispose() End Sub #End Region #Region "TAB SISTEMA" Private Sub CargaUsuariosPortal() Dim ObjUsuario As New ClsSisUsuarios() If ObjUsuario.GetUsuariosPortal(-1, CveCliente, -1) Then Dim dtUsr As DataTable = ObjUsuario.DtResultados 'Dim dr As DataRow = dtUsr.FiltroPrimero("CveUsuario = " & UsuarioActual.CveUsuario) 'If dr IsNot Nothing Then ' If True Then TabHistorialCompras.Visible = True 'Compras 'dr("Permiso1").ToString = "True" ' If True Then TabCxP.Visible = True 'Cuentas por pagar ' If True Then TabAnticipos.Visible = True 'Anticipos ' If True Then TabOS.Visible = True 'Ordenes de Servicio ' If True Then TabBuzonCalidad.Visible = True 'Buzón Calidad ' 'If dr("Permiso6").ToString = "True" Then TabCotizaciones.Visible = True 'Cotizaciones ' If True Then TabSistema.Visible = True 'Sistemas 'End If dtUsr = dtUsr.FiltraParametros("Nombre <> 'Admin' AND CveUsuario <> " & UsuarioActual.CveUsuario) ViewState("OrdenUsuarios") = "" ''busco la clave del admin, si es que existe 'Dim dr As DataRow = dtUsr.FiltroPrimero("Usuario = 'Admin'") 'If dr IsNot Nothing Then ' HdnCveUsuarioPortalAdmin.Value = dr("CveUsuarioPortal").ToString ' If dr("Estatus").ToString = "1" Then ' HdnCveUsuarioPortalActivado.Value = "1" ' End If 'End If 'If HdnCveUsuarioPortalActivado.Value.ToEntero > 0 Then ' trEnviarActivacion.Visible = False ' trRecuperacionContraseña.Visible = True 'End If GvUsuariosPortal.DataSource = dtUsr ViewState("DTUsuariosCliente") = dtUsr Else GvUsuariosPortal.DataSource = Nothing ViewState("DTUsuariosCliente") = Nothing End If ObjUsuario.Dispose() GvUsuariosPortal.DataBind() End Sub #Region "GESTION DE USUARIOS DEL PORTAL" Protected Sub LnkAgregarUsuario_Click(sender As Object, e As EventArgs) Handles LnkAgregarUsuario.Click Dim ObjParametro As SisParametro = GlobalDTParametros(SisParametros.URL) Dim ObjUsuario As New ClsSisUsuarios Dim CveUsuario As Integer = -1 Dim Liga As String = $"{ObjParametro.Cadena1}LogIn.aspx" Dim CvePlataforma As Integer = 6 If UsuarioActual.CveEmpresa = 43 Then Liga = ObjParametro.Cadena1 & "AIMMGM/Portal.aspx" End If ObjUsuario.IniciaTransacSQL() CveUsuario = ObjUsuario.AddUsuarioPortal(TxtCorreoPortal.Text, ContraseñaPredeterminadaEncriptada, TxtNombrePortal.Text, TxtCorreoPortal.Text, CveCliente, -1, CvePlataforma, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) If CveUsuario > 0 Then If ObjUsuario.UpdateUsuariosModulos(CveUsuario, 1101, True, UsuarioActual.CveUsuario) Then ObjUsuario.GetUsuariosPortal(-1, CveCliente, -1) ViewState("DTUsuariosCliente") = ObjUsuario.DtResultados.FiltraParametros("Nombre <> 'Admin' AND CveUsuario <> " & UsuarioActual.CveUsuario) TxtNombrePortal.Text = "" TxtCorreoPortal.Text = "" EnviaCorreo(Liga) Alert("Usuario Creado.
El usuario accesará con la contraseña '" & ContraseñaPredeterminada & "'", TipoMensaje.MsgInformacion) ObjUsuario.Commit() Else ObjUsuario.RollBack() End If Else ObjUsuario.RollBack() End If ObjUsuario.Dispose() If ViewState("OrdenUsuarios").ToString() <> String.Empty Then CargaGridUsuarios(ViewState("OrdenUsuarios").ToString()) Else CargaGridUsuarios("") End If End Sub Protected Sub GvUsuariosPortal_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvUsuariosPortal.RowCommand If e.CommandName = "RestablecerContraseña" Then Dim cveUsuarioPortal As Integer = e.CommandArgument.ToString.ToEntero Dim Usuario As New ClsSisUsuarios If Usuario.GetUsuariosPortal(cveUsuarioPortal, -1, -1) Then Dim dr As DataRow = Usuario.DtResultados.FiltroPrimero("") If Usuario.UpdateUsuarioPortal(dr("Correo").ToString, dr("Nombre").ToString, dr("Correo").ToString, CType(dr("Estatus"), Boolean), ContraseñaPredeterminadaEncriptada, CveCliente, -1, cveUsuarioPortal, UsuarioActual.CveUsuario) Then GvUsuariosPortal.EditIndex = -1 ViewState("DTUsuariosCliente") = Usuario.DtResultados.FiltraParametros("Usuario <> 'Admin' AND CveUsuario <> " & UsuarioActual.CveUsuario) Alert($"Contraseña Restablecida.
La nueva contraseña es: {ContraseñaPredeterminada}", TipoMensaje.MsgInformacion) End If End If Usuario.Dispose() End If End Sub Protected Sub GvUsuariosPortal_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvUsuariosPortal.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Cells(0).Width = Unit.Pixel(80) e.Row.Cells(1).Width = Unit.Pixel(141) e.Row.Cells(2).Width = Unit.Pixel(50) e.Row.Cells(3).Width = Unit.Pixel(50) e.Row.Cells(4).Width = Unit.Pixel(55) e.Row.Cells(5).Width = Unit.Pixel(50) e.Row.Cells(6).Width = Unit.Pixel(50) e.Row.Cells(7).Width = Unit.Pixel(50) e.Row.Cells(8).Width = Unit.Pixel(50) e.Row.Cells(9).Width = Unit.Pixel(50) e.Row.Cells(10).Width = Unit.Pixel(50) e.Row.Cells(11).Width = Unit.Pixel(50) e.Row.Cells(12).Width = Unit.Pixel(45) e.Row.Cells(13).Width = Unit.Pixel(68) e.Row.Cells(14).Width = Unit.Pixel(100) e.Row.Cells(15).Width = Unit.Pixel(140) End If End Sub Protected Sub GvUsuariosPortal_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs) Handles GvUsuariosPortal.RowEditing GvUsuariosPortal.EditIndex = e.NewEditIndex If ViewState("OrdenUsuarios").ToString() <> String.Empty Then CargaGridUsuarios(ViewState("OrdenUsuarios").ToString()) Else CargaGridUsuarios("") End If 'CargaUsuariosPortal() End Sub Protected Sub GvUsuariosPortal_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GvUsuariosPortal.RowUpdating Dim Usuarios As New ClsSisUsuarios Dim Correo, Nombre As String Dim Estatus As Boolean Dim gvr As GridViewRow = GvUsuariosPortal.Rows(e.RowIndex) Correo = gvr.FCLiteral("LtlCorreo").Text.Trim Nombre = gvr.FCTextBox("TxtUsuarioPortalEdit").Text.Trim 'Rol = GvDatos.Rows(e.RowIndex).FCDropDownList("CbxA").SelectedValue.ToEntero Estatus = gvr.FCCheckBox("ChkEstatus").Checked Dim CveUsuarioPortal As Integer = gvr.DataKey("CveUsuario").ToEntero Dim pCveCliente As Integer = gvr.DataKey("CveClientePlataforma").ToEntero ''Correo = GvDatos.Rows(e.RowIndex).FCTextBox("TxtCorreo").Text.Trim ''CveSupervisa = GvDatos.Rows(e.RowIndex).FCDropDownList("CboSupervisa").SelectedValue.ToEntero ''CveAutoriza = GvDatos.Rows(e.RowIndex).FCDropDownList("CboAutoriza").SelectedValue.ToEntero ''CveEmpresa = GvDatos.Rows(e.RowIndex).FCDropDownList("CboEmpresa").SelectedValue.ToEntero If Usuarios.UpdateUsuarioPortal(Correo, Nombre, Correo, Estatus, "-1", pCveCliente, -1, CveUsuarioPortal, UsuarioActual.CveUsuario) Then GvUsuariosPortal.EditIndex = -1 ViewState("DTUsuariosCliente") = Usuarios.DtResultados.FiltraParametros("Nombre <> 'Admin' AND CveUsuario <> " & UsuarioActual.CveUsuario) End If Usuarios.Dispose() If ViewState("OrdenUsuarios").ToString() <> String.Empty Then CargaGridUsuarios(ViewState("OrdenUsuarios").ToString()) Else CargaGridUsuarios("") End If End Sub Protected Sub GvUsuariosPortal_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs) Handles GvUsuariosPortal.RowDeleting Dim Usuario As New ClsSisUsuarios If Usuario.RemoveUsuarioPortal(GvUsuariosPortal.DataKeys(e.RowIndex).Value.ToString().ToEntero()) Then GvUsuariosPortal.EditIndex = -1 ViewState("DTUsuariosCliente") = Usuario.DtResultados End If Usuario.Dispose() If ViewState("OrdenUsuarios").ToString() <> String.Empty Then CargaGridUsuarios(ViewState("OrdenUsuarios").ToString()) Else CargaGridUsuarios("") End If End Sub Protected Sub GvUsuariosPortal_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs) Handles GvUsuariosPortal.RowCancelingEdit GvUsuariosPortal.EditIndex = -1 If ViewState("OrdenUsuarios").ToString() <> String.Empty Then CargaGridUsuarios(ViewState("OrdenUsuarios").ToString()) Else CargaGridUsuarios("") End If End Sub Private Sub CargaGridUsuarios(Orden As String) If CType(ViewState("DTUsuariosCliente"), DataTable).Rows.Count > 0 Then If Orden <> String.Empty Then Dim DV As New DataView(CType(ViewState("DTUsuariosCliente"), DataTable), "", Orden, DataViewRowState.CurrentRows) GvUsuariosPortal.DataSource = DV.ToTable() DV.Dispose() Else GvUsuariosPortal.DataSource = CType(ViewState("DTUsuariosCliente"), DataTable) End If End If GvUsuariosPortal.DataBind() UPPUsuarios.Update() End Sub Private Sub EnviaCorreo(Liga As String) Try Dim Para = TxtCorreoPortal.Text.Trim Dim Asunto = "ACTIVACIÓN DEL PORTAL DE CLIENTE" Dim SBBody As New StringBuilder 'Linia de estilos SBBody.Append("") 'incio Cuerpo del correo SBBody.Append("
") SBBody.Append("
") SBBody.Append("
") SBBody.Append("ALTA DE CUENTA") SBBody.Append("
") SBBody.Append("
") SBBody.AppendFormat(" Estimado {0}:
", TxtNombrePortal.Text.ToUpper) SBBody.AppendFormat("El presente correo es para informarle que se le han asignado los siguientes datos para el acceso al Portal del Cliente de: {0}

", UsuarioActual.Empresa.Empresa) SBBody.Append("
") SBBody.Append("
Datos de usuario
") SBBody.Append("
") SBBody.Append("
") SBBody.Append("
Dirección de Acceso
") SBBody.AppendFormat("", Liga) SBBody.Append("
") SBBody.Append("
") SBBody.Append("
Clave
") SBBody.AppendFormat("
{0}
", CveCliente) SBBody.Append("
") SBBody.Append("
") SBBody.Append("
Usuario
") SBBody.AppendFormat("
{0}
", TxtCorreoPortal.Text) SBBody.Append("
") SBBody.Append("
") SBBody.Append("
Contraseña
") SBBody.AppendFormat("
{0}
", ContraseñaPredeterminada + "oficial") SBBody.Append("
") SBBody.Append("
") SBBody.Append("
") SBBody.Append("
") 'SBBody.Append("Para Activar su cuenta debera cambiar su contraseña.

") SBBody.Append("
") SBBody.Append("Nota Favor de NO responder este correo. ") SBBody.Append("


") SBBody.AppendFormat("", UrlSitio) SBBody.Append("
") SBBody.Append("
") 'Termino Cuerpo del correo Dim Hilo As New System.Threading.Thread(Sub() MandaCorreo(Asunto, Para, SBBody.ToString)) Hilo.Start() Alert("El correo se ha enviado correctamente a: " + TxtCorreoPortal.Text + ".", TipoMensaje.MsgInformacion) Catch ex As Exception OnError("Ocurrió error al mandar MAIL", ex) End Try End Sub Private Sub MandaCorreo(Asunto As String, Para As String, Body As String) Dim a As String = String.Format("{0} -- {1} ---- -->", Asunto, Para) a.GuardaLog() Dim Mail As New ClsSisMail() Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Body) End Sub #End Region #End Region #Region "TAB CONTRASENIA" Protected Sub BtnGuardarContraseña_Click(sender As Object, e As EventArgs) Handles BtnGuardarContraseña.Click If Decripta(UsuarioActual.Contraseña) = TxtContraseniaActual.Text Then Dim ObjUsuario As New ClsSisUsuarios Dim Usuario As Usuario = Nothing If ObjUsuario.GetUsuariosPortal(UsuarioActual.CveUsuario, -1, -1) Then Dim dr As DataRow = ObjUsuario.DtResultados.FiltroPrimero("") If ObjUsuario.UpdateUsuarioPortal(dr("Usuario").ToString, dr("Nombre").ToString, dr("Correo").ToString, True, Encripta(TxtContrasenia1.Text), dr("CveCliente").ToString.ToEntero, dr("CveProveedor").ToString.ToEntero, UsuarioActual.CveUsuario, UsuarioActual.CveUsuario) Then UsuarioActual.Contraseña = Encripta(TxtContrasenia1.Text) Alert("Contraseña Modificada.", TipoMensaje.MsgInformacion) End If End If ObjUsuario.Dispose() Else Alert("La Contraseña Actual es incorrecta.", TipoMensaje.MsgAdvertencia) End If End Sub #End Region #Region "TAB PEDIDOS" Private Sub CargaCuentasDepositos() 'CargaEstatus DdlEstatus.DataSource = GlobalDTEstatusFactura.FiltraParametros(" CveEstatusFactura IN (2, 5, 21) ") DdlEstatus.DataBind() DdlCuenta.Items.Clear() 'Dim ObjGral As New ClsGenerales 'If ObjGral.GetCuentasDepositos(CveProveedor:=-1, CveCliente:=CveCliente, CvePersonal:=-1) Then ' DdlCuentaDeposito.DataSource = ObjGral.DtResultados.FiltraParametros("Estatus ='True'") ' If ObjGral.DtResultados.Rows.Count > 0 Then ' DdlCuentaDeposito.Items.Insert(0, New ListItem("Seleccione una cuenta", "-1")) ' End If 'End If 'ObjGral.Dispose() 'DdlCuentaDeposito.DataBind() Dim dt As DataTable If UsuarioActual.Empresa.Funcionalidad(127) = "1" Then dt = GlobalDTBancosCuentas(-1) Else dt = GlobalDTBancosCuentas(-1).FiltraParametros("CveTipoCuenta <> 1") ' quito las cajas chicas End If DdlCuenta.DataSource = dt DdlCuenta.DataBind() UpIxC.Update() End Sub Private Sub CargaPedidos(Optional TopPedidos As Integer = 21) Dim FechaI = If(IsDate(txtFechaI.Text.Trim()), txtFechaI.Text.Trim.ToDate, MinFecha) Dim FechaF = If(IsDate(txtFechaF.Text.Trim()), txtFechaF.Text.Trim.ToDate, MaxFecha) Dim ObjClientes As New ClsClientes If ObjClientes.GetHistorialVentas(CveCliente, TopPedidos, CveClienteSucursal:=-1, TipoDocto:="Pd2", CveEstatusFactura:=DdlEstatus.SelectedValue.ToEntero(), FechaI:=FechaI, FechaF:=FechaF) Then GvPedidos.DataSource = ObjClientes.DtResultados If ObjClientes.DtResultados.Rows.Count < 21 Then LnkVerMasPedidos.Visible = False End If End If ObjClientes.Dispose() GvPedidos.DataBind() UpTabPedidos.Update() End Sub Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) CargaPedidos() End Sub Protected Sub BtnVerMasPedidos_Click(sender As Object, e As EventArgs) If BtnVerMasVentas.Text = "Ver Más" Then CargaPedidos(-1) BtnVerMasVentas.Text = "Ver Menos" Else CargaPedidos(21) BtnVerMasVentas.Text = "Ver Más" End If End Sub Protected Sub GvPedidos_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveVenta") <> "" Then 'e.Row.FCHyperLink("ImgAbonar").NavigateUrl = String.Format("/Bancos/PopIEVentas.aspx?CveVenta={0}&TB_iframe=true&height=550&width=700", e.Row.DBCampo("CveVenta")) If e.Row.DBCampo("CveEstatusFactura").ToEntero().Contiene(4, 5) Then e.Row.FCLinkButton("ImgAbonar").Visible = False e.Row.FCLinkButton("ImgCancelar").Visible = False End If Else e.Row.FCLinkButton("ImgAbonar").Visible = False e.Row.FCLinkButton("ImgCancelar").Visible = False e.Row.CssClass = "Totales" End If End If End Sub Protected Sub ImgCancelar_Click(sender As Object, e As EventArgs) Dim GvRow As GridViewRow = (DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)) If GvRow.DataKey("CveVenta").ToEntero() > 0 Then Dim ObjFactura As New Modelos.Factura(UsuarioActual, GvRow.DataKey("CveVenta").ToEntero(), UsuarioActual.CveEmpresa) If ObjFactura IsNot Nothing Then Dim Resp = ObjFactura.CancelarFactura(RealizarDevolucionAlmacen:=False, ListaRemisionesCancelar:=New List(Of Integer)) Alert(Resp.Mensaje, If(Resp.HuboError, TipoMensaje.MsgError, TipoMensaje.MsgInformacion)) End If Else Alert("No se encontro pedido para cancelar", TipoMensaje.MsgAdvertencia) End If End Sub Protected Sub ImgAbonar_Click(sender As Object, e As EventArgs) TxtTotalPedido.Text = "" TxtFolio.Text = "" Me.CveVenta = -1 Dim GvRow As GridViewRow = (DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)) If GvRow.DataKey("CveVenta").ToEntero() > 0 Then LblPedido.Text = GvRow.DataKey("SerieFolio") TxtTotalPedido.Text = GvRow.DataKey("Total").ToDecimal().FormatoNumero(2) RVPedido.MaximumValue = GvRow.DataKey("Total").ToDecimal().FormatoNumero(2) Me.CveVenta = GvRow.DataKey("CveVenta").ToEntero() RegistraScript("$('#DivIxC').modal({backdrop: 'static',keyboard: false});") End If UpIxC.Update() End Sub Protected Sub BtnPagarPedido_Click(sender As Object, e As EventArgs) GuargarIxC(CveCliente, TxtTotalPedido.Text.ToDecimal(), New Modelos.Factura(UsuarioActual, Me.CveVenta, UsuarioActual.CveEmpresa)) End Sub Private Sub GuargarIxC(CveCliente As Integer, ImportePagado As Decimal, ObjFactura As Modelos.Factura) Dim MsgError As String = "" Dim CveConceptoContable As Integer = 30 Dim CveConceptoCompra As Integer = 10 Dim CveCreditoDetalle As Integer = -1 Dim CIF As Decimal = 0 Dim CvePlantillaPoliza As Integer = 3 Dim CvePrePoliza As Integer = 0 Dim ComprobanteIE As String = "" Dim CveIE As Integer = -1 Dim CveTipoTransaccion As Integer = 11 Dim FechaDoc As DateTime = Now Dim ConceptoContable As Integer Dim TipoMovimiento As Boolean Dim importeMovimiento As Decimal Dim FechaMovimiento As Date = Now Dim Concepto As String = "" Dim Importe As Decimal = ImportePagado Dim Msg As New StringBuilder Dim ObjIE As New ClsBancos() Dim ObjMov As New ClsContabilidad(ObjIE.IniciaTransacSQL) Dim ObjComp As New ClsCompras(ObjIE.IniciaTransacSQL) Try Dim CveCuentaDeposito As Integer = 0 'If DdlCuentaDeposito.Items.Count > 0 Then ' CveCuentaDeposito = DdlCuentaDeposito.SelectedValue.ToEntero 'End If '*****-_- INICIA: CONFIGURACION REGISTRO -_-***** Dim AgregaPolizaSaldoInicial As Boolean = False 'INGPC CvePlantillaPoliza = 6 If CveCliente > 0 Then CveConceptoCompra = 66 'Anticipo doc por pagar CveConceptoContable = 30 'Bancos End If Dim FolioFijo As Integer = 0 Dim tCveMoneda As Integer = ObjFactura.CveMoneda Dim tImporteMonedaExtranjera As Decimal = 0 If tCveMoneda <> 1 Then tImporteMonedaExtranjera = TxtImporte.Text.ToDecimal * GlobalTipoCambio(Now).ToString.ToDecimal Dim PagueseA = ObjFactura.Cliente.Nombre If MsgError = "" Then CveIE = ObjIE.AddBancos_IE(DdlCuenta.SelectedValue.ToEntero, CveTipoTransaccion, FechaDoc, TxtFolio.Text.Trim, PagueseA, Importe, ObjFactura.CveMoneda, TxtTipoCambio.Text.Trim.ToDouble, TxtObservaciones.Text.Trim, "", False, False, -1, CvePrePoliza, ComprobanteIE, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCuentaDeposito:=CveCuentaDeposito, CveEstatusIE:=1, Referencia:="-1", CveCuentaTarjeta:=-1, ConceptoCIE:="-1") If CveIE > 0 Then If CveTipoTransaccion = 1 AndAlso UsuarioActual.CveEmpresa <> 119 Then FolioFijo = ObjIE.Folio.ToEntero 'cheque CvePrePoliza = ObjMov.AddPrePolizas("PortalCliente/IE " + "INGPC", CvePlantillaPoliza, Importe, Importe, tCveMoneda, FechaDoc, PagueseA, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, FolioFijo:=FolioFijo, ReglaFolioPoliza:=ObjComp.ObtenerReglaFolio(CveTipoTransaccion.ToString(), Nothing, UsuarioActual.CveEmpresa), CveTipoPoliza:=ObjMov.ObtenerTipoPoliza(CveTipoTransaccion.ToString(), "-1", UsuarioActual.CveEmpresa)) 'valida prepoliza If CvePrePoliza > 0 Then If Not ObjIE.UpdateIEPrePoliza(MinFecha, "", -1, CvePrePoliza, CveIE, -1) Then MsgError = "Ocurrio un error al agregar la prepoliza al IE." End If Dim Conc As String = ObjIE.Folio Dim Ref As String = ObjIE.Folio ComprobanteIE = $"{CveIE}" 'GUARDA PREPOLIZAS DETALLE [PRIMERO SON LOS CASOS ESPECIALES, AL FINAL (ELSE) LOS CASOS NORMALES] --REEMPLAZA IFs Dim importeMX As Decimal Dim Multiplicador As Integer If ObjMov.GetPlantillaConceptos(UsuarioActual.CveEmpresa, CvePlantillaPoliza) Then For Each Row As DataRow In ObjMov.DtResultados.Rows ConceptoContable = Row("CveConcepto").ToString.ToEntero TipoMovimiento = If(Row("TipoMovto").ToString = "True", True, False) importeMovimiento = 0 Multiplicador = (Row("Multiplicador").ToString.ToEntero) Concepto = ObjMov.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, ConceptoContable, PagueseA, "", ObjIE.Folio) Select Case ConceptoContable Case 66 importeMovimiento = Importe '- TxtIvaIxC.Text.ToDecimal importeMX = importeMovimiento Case 30 importeMovimiento = Importe importeMX = importeMovimiento End Select If importeMovimiento <> 0 Then If Not ObjMov.AddPrePolizasDetalle(CvePrePoliza, TipoMovimiento, importeMovimiento, Concepto, ConceptoContable, Concepto, FechaMovimiento, If(ConceptoContable = 30, ObjFactura.Cliente.IdCtaContClientes, ObjFactura.Cliente.IdCtaContAnticipos), -1, CveIE:=CveIE, CveCompra:=-1, CveProveedor:=-1, CvePersonal:=-1, CveCreditoDetalle:=CveCreditoDetalle, CveCliente:=CveCliente, ImporteMX:=importeMovimiento, ImporteME:=tImporteMonedaExtranjera, TipoCambio:=TxtTipoCambio.Text.ToDecimal, CveCuenta:=If(ConceptoContable = 30, ObjFactura.Cliente.CveCuentaClientes, ObjFactura.Cliente.CveCuentaAnticipos)) Then MsgError = "Ocurrió un error al registrar el asiento del ingreso." End If End If Next End If If MsgError = "" Then If ObjMov.ValidacionPrePolizaCuadre(CvePrePoliza, -1) Then If ObjMov.ValorPolizaDescuadre > 0 Then GuardaLogAD($"Bancos/IE | Error:{ObjMov.MensajePolizaDescuadre} Diferencia:{ObjMov.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas") End If Else MsgError = "No se pudo validar la prepoliza de cuadre." End If End If 'El movimiento 1 es el de Venta 'Conta ContPAQ 'If UsuarioActual.Empresa.Funcionalidad(200) = "1" AndAlso MsgError = "" Then ' If IDCtaBeneficiario > 0 And IDCtaContable > 0 Then ' If ObjMov.ContabilizarPrePoliza(CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.Empresa) Then ' IDPoliza = ObjMov.ContaIdPoliza ' 'Alert(alertaContabilizacion & ObjMov.AlertaMensaje, ModExtensiones.TipoMensaje.MsgInformacion) ' Else ' Alert("Ocurrio un error al contabilizar, pongase en contacto con Soporte Técnico", TipoMensaje.MsgError) ' End If ' Else ' If IDCtaContable < 1 Then ' Alert("No se puede contabilizar la Prepoliza debido a que la cuenta de Bancos es invalida", TipoMensaje.MsgAdvertencia) ' End If ' If IDCtaBeneficiario < 1 Then ' Alert("No se puede contabilizar la Prepoliza debido a que las cuenta del Beneficiario es invalida", TipoMensaje.MsgAdvertencia) ' End If ' End If 'End If 'If UsuarioActual.Empresa.UsaAC Then ' Dim ConceptoRenglon, Referencia As String ' Dim FolioPoliza As Integer ' Dim Fecha As Date = FechaDoc ' Dim TipoChq As String = "" ' Dim Total As Double = TxtImporte.Text.ToDouble ' Dim Conta As New ClsContPAQi(UsuarioActual.Empresa) ' Conta.IniciaTransacSQL() ' If CveTipoTransaccion = 1 Then TipoChq = "CHQ" ' ConceptoRenglon = String.Format("Anticipo {0}", PagueseA) ' Dim IDPoliza = Conta.AddPoliza(2, ConceptoRenglon, Total, Total, UsuarioActual.CveUsuario, Fecha, ObjIE.Folio, TipoChq) ' If IDPoliza > 0 Then ' FolioPoliza = Conta.Folio ' Referencia = ObjIE.Folio ' ConceptoRenglon = String.Format("Anticipo {0} {1}", PagueseA, TxtObservaciones.Text) ' Total = TxtImporte.Text.ToDouble ' If Not Conta.AddMovimiento(IDPoliza, IDCtaContable, True, Total, Referencia, ConceptoRenglon, 0, Fecha, "") Then MsgError = "No se insertó el movimiento" ' If Not Conta.AddMovimiento(IDPoliza, IDCtaBeneficiario, False, Total, Referencia, ConceptoRenglon, 0, Fecha, "") Then MsgError = "No se insertó el movimiento" ' Else ' MsgError = "No se insertó el encabezado" ' End If ' If MsgError = "" Then ' Conta.Commit() ' Conta.AjustaPoliza(IDPoliza) ' 'actualizar la conta del IE ' ObjIE.UpdateIEPrePoliza(Fecha, FolioPoliza.ToString, IDPoliza, CvePrePoliza, CveIE, 0) ' Else ' Conta.RollBack() ' IDPoliza = 0 ' End If ' Conta.Dispose() 'End If 'Notificación de Pago 'If TxtNotificarA.Text.Trim <> "" And MsgError = "" Then ' 'NotificacionPago(CveIE, TxtNotificarA.Text.Trim) ' EnviarCorreoNotificacion(CveIE, TxtNotificarA.Text.Trim, "", UsuarioActual, False) 'End If Else MsgError = "No se pudo insertar la póliza" End If Else MsgError = "No se insertó el encabezado" End If End If Catch ex As Exception MsgError = ex.ToString() End Try If MsgError = "" Then 'IMPRIME CHEQUE 'GeneraChequePDF(CveIE, UsuarioActual.Empresa, IDPoliza) If Msg.ToString = "" Then ObjIE.Commit() Msg.Append("El Documento se guardo correctamente: Folio:" + ObjIE.Folio) Alert(Msg.ToString(), TipoMensaje.MsgInformacion) End If 'Dim Archivo As System.IO.FileInfo = Nothing ''VERIFICA SI EXISTE EL FORMATO ''If DdlTipoTransaccion.SelectedValue.ToEntero.Contiene(2, 8, 9) Then '' Archivo = New System.IO.FileInfo(String.Format("{0}Formatos/Transferencia.rdlc", UsuarioActual.Empresa.Ruta)) ''ElseIf DdlTipoTransaccion.SelectedValue.ToEntero.Contiene(1) Then '' Archivo = New System.IO.FileInfo(String.Format("{0}Formatos/CHQ-{1}.rdlc", UsuarioActual.Empresa.Ruta, DdlCuenta.SelectedValue.ToEntero)) '' If Not Archivo.Exists Then '' Archivo = New System.IO.FileInfo(String.Format("{0}\Empresas\Grales\Formatos\CHQ.rdlc", ModExtensiones.DirectorioBaseEmpresas)) '' End If ''ElseIf DdlTipoTransaccion.SelectedValue.ToEntero.Contiene(6) And UsuarioActual.CveEmpresa = 72 Then '' Archivo = New System.IO.FileInfo(String.Format("{0}Formatos/ComprobanteEgreso.rdlc", UsuarioActual.Empresa.Ruta, DdlCuenta.SelectedValue.ToEntero)) ''End If 'If Archivo IsNot Nothing Then ' If Archivo.Exists Then ' Msg.AppendFormat("

{1} ", Encripta(String.Format("OP=IECHEQUE&CVEIE={0}", CveIE)), "Imprimir Ingre") ' End If 'End If Else ObjIE.RollBack() Alert(MsgError, TipoMensaje.MsgAdvertencia) End If ObjIE.Dispose() ObjMov.Dispose() ObjComp.Dispose() End Sub Private Function DescargarFactura(CveVenta As Integer, CveEmpresa As Integer) As Byte() Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?P={1}", "http://localhost:85/", Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta)))) Dim File As Byte() = Nothing Try Using httpClient = New HttpClient() httpClient.Timeout = New TimeSpan(0, 15, 0) Using request = New HttpRequestMessage(HttpMethod.Get, Url) request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CVEUSUARIO=100", CveEmpresa, DateTime.UtcNow.Ticks))) 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 Private Sub MandaMails(UsuarioActual As Usuario, CveVenta As Integer, EnviarFactura As Boolean, ObjFactura As Modelos.Factura) Dim ObjMail As New ClsSisMail() Dim ObjVentas As New ClsVentas Dim ArchivoPDF As String = "" Dim ArchivoPDFBytes As Byte() = Nothing Dim ExistePDF As Boolean = False Try Dim Asunto As String = String.Empty Dim Cuerpo As String = String.Empty Dim ResultadoMail As Integer = 0 Dim TipoComprobante = "Pedido" 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.Nombre) Cuerpo = Cuerpo.Replace("{""TipoDocumento""}", TipoComprobante) Cuerpo = Cuerpo.Replace("{""Fecha""}", ObjFactura.Fecha.ToString("dd/MM/yyyy")) Cuerpo = Cuerpo.Replace("{""Total""}", ObjFactura.Total.FormatoNumero(2)) Cuerpo = Cuerpo.Replace("{""FechaVencimiento""}", ObjFactura.FechaVencimiento.ToString("dd/MM/yyyy")) Cuerpo = Cuerpo.Replace("{""SerieFolio""}", ObjFactura.SerieFolio) End If If UsuarioActual.Empresa.AsuntoPlantillaMailVenta.Trim.Length > 0 Then Asunto = UsuarioActual.Empresa.AsuntoPlantillaMailVenta Asunto = Asunto.Replace("{""TipoDocumento""}", TipoComprobante) Asunto = Asunto.Replace("{""Sucursal""}", ObjFactura.SubProyecto.SubProyecto) Asunto = Asunto.Replace("{""SerieFolio""}", ObjFactura.SerieFolio) End If If Not EnviarFactura Then ObjVentas.UpdateVentaMail(0, CveVenta) End If Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail) ArchivoPDF = String.Format("{0}PDF\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, ObjFactura.TipoDocto, ObjFactura.SerieFolio) If Not File.Exists(ArchivoPDF) Then ArchivoPDFBytes = DescargarFactura(ObjFactura.CveVenta, ObjFactura.CveEmpresa) Else ExistePDF = True End If If ExistePDF Then LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = ArchivoPDF}) Else LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.ArchivoBinario = ArchivoPDFBytes, .NombreArchivo = String.Format("{0}.pdf", ObjFactura.SerieFolio)}) End If If ObjMail.SendMail(UsuarioActual.Empresa, ObjFactura.Cliente.Mail, Asunto, Cuerpo, "japmx95@gmail.com", LSRutasMail, Displayname:="") Then ResultadoMail = 1 Else ResultadoMail = 3 End If ObjVentas.UpdateVentaMail(ResultadoMail, CveVenta) Catch ex As Exception OnError("Ocurrió error al mandar el Mail", ex) ObjVentas.UpdateVentaMail(3, CveVenta) Finally ObjVentas.Dispose() End Try End Sub #End Region #Region "O R D E N A M I E N T O" Protected Sub LbOrden_Click(ByVal sender As Object, ByVal e As EventArgs) Dim Orden As String = "" Dim Campo As String = "" Dim gvi As Integer = 0 Dim Literal As Literal = Nothing Const OrdenInicial As String = "" Dim Arg(2) As String Arg = CType(sender, LinkButton).CommandArgument().ToString.Split(";"c) Campo = Arg(0) gvi = Arg(1).ToEntero Literal = CType(CType(sender, LinkButton).NamingContainer.FindControl("Img" & Campo.Replace(",", "_")), Literal) Campo = Campo.Substring(0, Campo.Length - 1) If ViewState(String.Format("O{0}", Campo, gvi)) IsNot Nothing AndAlso ViewState(String.Format("O{0}", Campo, gvi)).ToString = String.Format("{0} DESC", Campo) Then ViewState(String.Format("O{0}", Campo)) = String.Format("{0} ASC", Campo) Literal.Text = String.Format("") Else ViewState(String.Format("O{0}", Campo, gvi)) = String.Format("{0} DESC", Campo) Literal.Text = String.Format("") End If Orden = OrdenInicial & ViewState(String.Format("O{0}", Campo, gvi)).ToString ViewState("Orden") = Orden CargaGrid(Orden, gvi) End Sub Private Sub CargaGrid(Orden As String, gvi As Integer) If gvi = 0 Then CargaRHPersonal() ElseIf gvi = 1 Then CargaGridUsuarios(Orden) End If End Sub #End Region #Region "DESCARGA Todos los Archivos" Private Sub BtnDescargarPDF_Click(sender As Object, e As EventArgs) Handles BtnDescargarPDF.Click If Not Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "Temp") Then Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory & "Temp") If Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\") Then Directory.Delete(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\", True) If Not Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\") Then Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\") Dim RutaArchivo As String = AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario & ".zip" Dim Archivo As String = String.Empty Dim HuboInexistentes As Boolean = False Dim SBInexistentes As New StringBuilder : SBInexistentes.Append("No se pudieron anexar los siguientes archivos:
") Dim RutaDestino As String = AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\" 'Ciclo para notificar si hay archivos que no existen. For Each Row As GridViewRow In GVHistorial.Rows If Row.FCHiddenField("HdnTipo").Value.Trim <> String.Empty Then Archivo = UsuarioActual.Empresa.Ruta & "PDF\" & Row.FCHiddenField("HdnTipo").Value & "\" & Row.FCHiddenField("HdnFolio").Value & ".pdf" If File.Exists(Archivo) Then File.Copy(Archivo, RutaDestino & Row.FCHiddenField("HdnTipo").Value & "_" & Row.FCHiddenField("HdnFolio").Value & ".pdf") Else HuboInexistentes = True SBInexistentes.AppendFormat("Tipo {0}, Folio {1}
", Row.FCHiddenField("HdnTipo").Value, Row.FCHiddenField("HdnFolio").Value) End If End If Next If File.Exists(RutaArchivo) Then File.Delete(RutaArchivo) ZipFile.CreateFromDirectory(RutaDestino, RutaArchivo) If HuboInexistentes Then Alert(SBInexistentes.ToString, TipoMensaje.MsgAdvertencia) End If SBInexistentes.Clear() Dim Script As String = String.Format("window.open(""data:application/zip;base64,"" + encodeURIComponent(""{0}""));", RutaArchivo.SetFileToBase64String()) RegistraScript(Script, "tickdownload") 'Descargar 'Memorystream 'Elimine el .zip que se genero If File.Exists(RutaArchivo) Then File.Delete(RutaArchivo) End Sub Private Sub BtnDescargarXML_Click(sender As Object, e As EventArgs) Handles BtnDescargarXML.Click If Not Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "Temp") Then Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory & "Temp") If Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\") Then Directory.Delete(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\", True) If Not Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\") Then Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\") Dim RutaArchivo As String = AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario & ".zip" Dim Archivo As String = String.Empty Dim HuboInexistentes As Boolean = False Dim SBInexistentes As New StringBuilder : SBInexistentes.Append("No se pudieron anexar los siguientes archivos:
") Dim RutaDestino As String = AppDomain.CurrentDomain.BaseDirectory & "Temp\" & UsuarioActual.CveUsuario.ToString & "\" 'Ciclo para notificar si hay archivos que no existen. For Each Row As GridViewRow In GVHistorial.Rows If Row.FCHiddenField("HdnTipo").Value.Trim <> String.Empty Then Archivo = UsuarioActual.Empresa.Ruta & "XML\" & Row.FCHiddenField("HdnTipo").Value & "\" & Row.FCHiddenField("HdnFolio").Value & ".xml" If File.Exists(Archivo) Then File.Copy(Archivo, RutaDestino & Row.FCHiddenField("HdnTipo").Value & "_" & Row.FCHiddenField("HdnFolio").Value & ".xml") Else HuboInexistentes = True SBInexistentes.AppendFormat("Tipo {0}, Folio {1}
", Row.FCHiddenField("HdnTipo").Value, Row.FCHiddenField("HdnFolio").Value) End If End If Next If File.Exists(RutaArchivo) Then File.Delete(RutaArchivo) ZipFile.CreateFromDirectory(RutaDestino, RutaArchivo) If HuboInexistentes Then Alert(SBInexistentes.ToString, TipoMensaje.MsgAdvertencia) End If SBInexistentes.Clear() Dim Script As String = String.Format("window.open(""data:application/zip;base64,"" + encodeURIComponent(""{0}""));", RutaArchivo.SetFileToBase64String()) RegistraScript(Script, "tickdownload") 'Descargar 'Memorystream 'Elimine el .zip que se genero If File.Exists(RutaArchivo) Then File.Delete(RutaArchivo) End Sub #End Region #Region "IMPRIMIR GVHistorial" Protected Sub BtnExcelHistorial_Click(sender As Object, e As EventArgs) Dim retorno As Byte() = Nothing Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) 'OBTENEMOS LOS DATOS 'Dim DTHistorial As DataTable 'If ObjClientes.GetHistorialVentas(UsuarioActual.CveCliente, TopRegistros) Then ' DTHistorial = ObjClientes.DtResultados 'Else ' DTHistorial = Nothing 'End If If DTHistorialVentas.Rows.Count > 0 Then Dim dr As DataRow = DTHistorialVentas.Rows(0) Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion)) params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If ImprimirPDF("Empresas/Grales/Formatos/ClienteHistorial.rdlc", DTHistorialVentas, params, "Reporte de Historial", "Excel") Else Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia) End If End Sub Protected Sub BtnExcelHistorialPedidos_Click(sender As Object, e As EventArgs) GvPedidos.ExportToExcel("Pedidos") End Sub Protected Sub BtnPDFHistorial_Click(sender As Object, e As EventArgs) Dim retorno As Byte() = ImprimirReporteHistorial() If retorno IsNot Nothing Then ImprimirbytesPDF(retorno, "Reporte de Historial", Descarga:=True) End If End Sub Protected Function ImprimirReporteHistorial() As Byte() Dim retorno As Byte() = Nothing Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) Dim ObjClientes As New ClsClientes() 'OBTENEMOS LOS DATOS 'Dim DTHistorial As DataTable 'If ObjClientes.GetHistorialVentas(UsuarioActual.CveCliente, TopRegistros) Then ' DTHistorial = ObjClientes.DtResultados 'Else ' DTHistorial = Nothing 'End If If DTHistorialVentas.Rows.Count > 0 Then Dim dr As DataRow = DTHistorialVentas.Rows(0) Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion)) params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If retorno = StreamPDF("Empresas/Grales/Formatos/ClienteHistorial.rdlc", DTHistorialVentas, params, "Reporte de Historial") Else Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia) End If ObjClientes.Dispose() Return retorno End Function #End Region #Region "IMPRIMIR CxC Activas" Protected Sub LbExcelCxCActivas_Click(sender As Object, e As EventArgs) Dim retorno As Byte() = Nothing Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) If DTCxC.Rows.Count > 0 Then Dim dr As DataRow = DTCxC.Rows(0) Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion)) params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If ImprimirPDF("Empresas/Grales/Formatos/ClienteCxC.rdlc", DTCxC, params, "Reporte de CxC Activas", "Excel") Else Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia) End If End Sub Protected Sub LbPDFCxCActivas_Click(sender As Object, e As EventArgs) Dim retorno As Byte() = ImprimirReporteCxCActivas() If retorno IsNot Nothing Then ImprimirbytesPDF(retorno, "Reporte de CxC Activas", Descarga:=True) End If End Sub Protected Function ImprimirReporteCxCActivas() As Byte() Dim retorno As Byte() = Nothing Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) Dim ObjMovtos As New ClsMovimientos() If DTCxC.Rows.Count > 0 Then Dim dr As DataRow = DTCxC.Rows(0) Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion)) params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If retorno = StreamPDF("Empresas/Grales/Formatos/ClienteCxC.rdlc", DTCxC, params, "Reporte de CxC Activas") Else Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia) End If ObjMovtos.Dispose() Return retorno End Function #End Region #Region "IMPRIMIR CxCHistorial" Protected Sub LbExcelCxCHistorial_Click(sender As Object, e As EventArgs) Dim retorno As Byte() = Nothing Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) If DTCxCHistorial.Rows.Count > 0 Then Dim dr As DataRow = DTCxCHistorial.Rows(0) Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion)) params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If ImprimirPDF("Empresas/Grales/Formatos/ClienteCxC.rdlc", DTCxCHistorial, params, "Reporte de CxC Historial", "Excel") Else Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia) End If End Sub Protected Sub LbPDFCxCHistorial_Click(sender As Object, e As EventArgs) Dim retorno As Byte() = ImprimirReporteCxCHistorial() If retorno IsNot Nothing Then ImprimirbytesPDF(retorno, "Reporte de CxC Historial", Descarga:=True) End If End Sub Protected Function ImprimirReporteCxCHistorial() As Byte() Dim retorno As Byte() = Nothing Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta)) Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa) Dim ObjMovtos As New ClsMovimientos() If DTCxCHistorial.Rows.Count > 0 Then Dim dr As DataRow = DTCxCHistorial.Rows(0) Dim params As New List(Of ReportParameter) params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("DireccionEmpresa", UsuarioActual.Empresa.Direccion)) params.Add(New ReportParameter("TelefonoEmpresa", UsuarioActual.Empresa.Telefono)) params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If retorno = StreamPDF("Empresas/Grales/Formatos/ClienteCxC.rdlc", DTCxCHistorial, params, "Reporte de CxC Historial") Else Alert("Ocurrió un error.", TipoMensaje.MsgAdvertencia) End If ObjMovtos.Dispose() Return retorno End Function #End Region 'Protected Sub BtnCxPActivas_Click(sender As Object, e As EventArgs) ' If BtnCxPActivas.Text = "Ver Más " Then ' BtnCxPActivas.Text = "Ver Menos " ' CargaCxP() ' Else ' BtnCxPActivas.Text = "Ver Más " ' CargaCxP(1) ' End If 'End Sub 'Protected Sub BtnHistorialCxP_Click(sender As Object, e As EventArgs) ' If BtnHistorialCxP.Text = "Ver Más " Then ' BtnHistorialCxP.Text = "Ver Menos " ' CargaCxP(2) ' Else ' BtnHistorialCxP.Text = "Ver Más " ' CargaCxP(2) ' End If 'End Sub #Region "TAB PEDIDO" #Region "CARGAS" Private Sub CargaFolios() If CveSubProyecto <= 0 Then Alert("No se tienen asignadas sucursales", TipoMensaje.MsgError) Exit Sub End If Dim ObjFolios As New ClsGralFolios() If ObjFolios.GetFolios("Pd2", UsuarioActual.CveEmpresa) Then Dim DT As DataTable = ObjFolios.DtResultados.FiltraParametros(String.Format("CveSubProyecto = {0} And Estado = 'Activo'", CveSubProyecto)) If DT.Rows.Count > 0 Then ViewState("CveFolio") = DT.Rows(0)("CveFolio").ToString.ToEntero ViewState("FolioActual") = DT.Rows(0)("FActual").ToString Serie = DT.Rows(0)("Serie").ToString Folio = DT.Rows(0)("FActual").ToString.ToEntero BtnGuardar.Enabled = True UpOpciones.Update() Else Alert($"No tiene registrados Folios para Pedido2 en esta sucursal: {SubProyecto}.", TipoMensaje.MsgAdvertencia) BtnGuardar.Enabled = False UpOpciones.Update() End If DT.Dispose() End If ObjFolios.Dispose() End Sub Private Sub InicializaTabPedido() 'SE ASIGNA EL SUBPROYECTO MATRIZ, EN CASO DE NO ENCONTRARSE SE LE ASIGNA CUALQUIERA Dim Dr As DataRow = Nothing If GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("TipoSucursal = 1").Rows.Count > 0 Then Dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltraParametros("TipoSucursal = 1").Rows(0) ElseIf GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).Rows.Count > 0 Then Dr = GlobalDTSubProyectos(-1, CveEmpresa:=UsuarioActual.CveEmpresa).Rows(0) End If DdlMoneda.DataSource = GlobalDTMonedas DdlMoneda.DataBind() If Dr IsNot Nothing Then CveSubProyecto = Dr("CveSubProyecto").ToString.ToEntero SubProyectoPorcentajeIVA = Dr("IVA").ToString.ToDouble SubProyecto = Dr("SubProyecto").ToString End If CreaDTVentas() If UsuarioActual.Empresa.UsaAC Then DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby:="Clasificacion") Else DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion:=1).FiltraParametros("Estado = 1", Orderby:="Clasificacion") End If DdlClasificacion.DataBind() CargaPS(-1, DdlPS) TxtPrecio.Attributes.Add("onKeyUp ", "Recalcula();") TxtCantidad.Attributes.Add("onKeyUp ", "Recalcula();") CargaFolios() Dim Dt = New DataSet Dt.Tables.Add("Datos") Dt.Tables("Datos").Columns.Add("") GvPS.DataSource = Dt.Tables("Datos") GvPS.DataBind() End Sub Private Sub CargaPS(CveClasificacion As Integer, Objeto As ADServerControl.Dropdownlost) DdlPS.setEsWebService(If(UsuarioActual.Empresa.Funcionalidad(141).ToString = "1", True, False)) If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then Objeto.ddl.Items.Clear() Objeto.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion, AplicaParaVenta:=1, Estatus:=1) Objeto.ddl.DataBind() Objeto.ddl.Items.Insert(0, New ListItem("*** Actualizar listado de Productos o Servicios ***", "-2")) Objeto.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1")) Else DdlPS.Attributes.Add("data-cvesubproyecto", CveSubProyecto.ToString) End If End Sub 'Private Sub CargaTipoCentroCosto() ' If UsuarioActual.Empresa.Tipo_CentroCosto = 1 Then ' divProyecto.Visible = False ' LblSubProyecto.InnerText = "Sucursal" ' DdlSubProyecto.Items.Clear() ' DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) ' DdlSubProyecto.DataBind() ' DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) ' ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 2 Then ' divProyecto.Visible = False ' LblSubProyecto.InnerText = "Proyecto" ' DdlSubProyecto.Items.Clear() ' DdlSubProyecto.DataSource = GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1) ' DdlSubProyecto.DataBind() ' DdlSubProyecto.Items.Insert(0, New ListItem("Seleccione", "-1")) ' ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 4 Then ' LblProyecto.InnerText = "Sucursal" ' LblSubProyecto.InnerText = "Proyecto" ' ElseIf UsuarioActual.Empresa.Tipo_CentroCosto = 5 Then ' LblProyecto.InnerText = "Proyecto" ' LblSubProyecto.InnerText = "Sucursal" ' End If 'End Sub Private Sub CreaDTVentas() TmpDT = New DataTable TmpDT.Columns.Add("CveVenta", GetType(Integer)) TmpDT.Columns.Add("Consec", GetType(Integer)) TmpDT.Columns.Add("Cantidad", GetType(Decimal)) TmpDT.Columns.Add("Codigo", GetType(String)) TmpDT.Columns.Add("CveUM", GetType(Integer)) TmpDT.Columns.Add("UM", GetType(String)) TmpDT.Columns.Add("SATClaveUM", GetType(String)) TmpDT.Columns.Add("CveClasificacion", GetType(Integer)) TmpDT.Columns.Add("Clasificacion", GetType(String)) TmpDT.Columns.Add("CvePS", GetType(Integer)) TmpDT.Columns.Add("PS", GetType(String)) TmpDT.Columns.Add("CodigoPS", GetType(String)) TmpDT.Columns.Add("SATClaveProdServ", GetType(String)) TmpDT.Columns.Add("NoIdentificacion", GetType(String)) TmpDT.Columns.Add("CveTipoPS", GetType(Integer)) TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer)) TmpDT.Columns.Add("Serie", GetType(String)) TmpDT.Columns.Add("CuentaPredial", GetType(String)) TmpDT.Columns.Add("Obs", GetType(String)) TmpDT.Columns.Add("TiempoEntrega", GetType(String)) TmpDT.Columns.Add("PU", GetType(Decimal)) TmpDT.Columns.Add("IVA", GetType(Decimal)) TmpDT.Columns.Add("ImporteIVA", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeIVA", GetType(Decimal)) TmpDT.Columns.Add("ImporteRetIVA", GetType(Decimal)) TmpDT.Columns.Add("ImporteRetISR", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeRetIVA", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeRetISR", GetType(Decimal)) TmpDT.Columns.Add("ImporteIEPS", GetType(Decimal)) TmpDT.Columns.Add("IEPS", GetType(Decimal)) TmpDT.Columns.Add("PorcentajeIEPS", GetType(Decimal)) TmpDT.Columns.Add("Descuento", GetType(Decimal)) TmpDT.Columns.Add("TipoDescuento", GetType(Integer)) TmpDT.Columns.Add("TotalImporte", GetType(Decimal)) TmpDT.Columns.Add("Total", GetType(Decimal)) 'Para uso del módulo contable TmpDT.Columns.Add("AsientoContableVentas", GetType(Integer)) TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer)) TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean)) TmpDT.Columns.Add("CveProyecto", GetType(Integer)) TmpDT.Columns.Add("Proyecto", GetType(String)) TmpDT.Columns.Add("CveSubProyecto", GetType(Integer)) TmpDT.Columns.Add("SubProyecto", GetType(String)) 'TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto TmpDT.Columns.Add("CvePresupuestoIngreso", GetType(Integer)) TmpDT.Columns.Add("CveFuenteRecaudacion", GetType(Integer)) 'Contratos TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer)) 'Remisiones a Facturas TmpDT.Columns.Add("CveVentaDetalle", GetType(Integer)) TmpDT.Columns.Add("CveVentaDetalleRemision", GetType(Integer)) TmpDT.Columns.Add("CveVentaDetalleCotizacion", GetType(Integer)) 'Pedido2 a Facturas TmpDT.Columns.Add("CveVentaDetallePedido2", GetType(Integer)) TmpDT.Columns.Add("Origen", GetType(Integer)) 'Ordenes Servicio TmpDT.Columns.Add("CveOS", GetType(Integer)) TmpDT.Columns.Add("CveOSDetalle", GetType(Integer)) TmpDT.Columns.Add("SeFacturara", GetType(Integer)) TmpDT.Columns.Add("Folio", GetType(Integer)) TmpDT.Columns.Add("Estatus", GetType(String)) 'Ordenamiento TmpDT.Columns.Add("Orden", GetType(Integer)) TmpDT.Columns.Add("TipoDocto", GetType(String)) 'OC TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer)) TmpDT.Columns.Add("EntregaDirecta", GetType(Integer)) TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer)) TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal)) TmpDT.Columns.Add("CantidadFacturadaCot", GetType(Decimal)) TmpDT.Columns.Add("CantidadInventario", GetType(Decimal)) TmpDT.Columns.Add("ClaveSATFraccionArancelaria", GetType(String)) TmpDT.Columns.Add("ClaveSATUnidadAduana", GetType(String)) TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", GetType(String)) TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", GetType(String)) End Sub #End Region #Region "SELECTED INDEX CHANGE" Protected Sub DdlMoneda_SelectedIndexChanged(sender As Object, e As EventArgs) TrConversionTipoCambio.Visible = False Select Case DdlMoneda.SelectedValue Case "1" TxtTipoCambio.Text = "1" Case "2" TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString TrConversionTipoCambio.Visible = True Case Else TxtTipoCambio.Text = GlobalTipoCambio(Now).ToString TrConversionTipoCambio.Visible = True End Select UpTabPedidos.Update() End Sub Protected Sub DdlPS_selectedindexchange(sender As Object, e As EventArgs) DdlPSIndexChange() End Sub Private Sub DdlPSIndexChange() If CveCliente > 0 OrElse DdlPS.SelectedValue = "-2" Then If DdlPS.SelectedValue IsNot Nothing AndAlso DdlPS.SelectedValue.ToEntero > 0 Then Dim drPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=DdlPS.SelectedValue.ToEntero).FiltroPrimero("") If drPS IsNot Nothing Then DdlUM.Items.Clear() If UsuarioActual.Empresa.UsaInventarios Then DdlUM.DataSource = GlobalDTProductosServiciosEquivalencias(DdlPS.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa) Else DdlUM.DataSource = GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa) End If DdlUM.Items.Insert(0, New ListItem("Seleccione", "-1")) DdlUM.SelectedValue = "-1" DdlUM.DataBind() DdlUM.SelectedValueExist(drPS("CveUnidadMedida").ToString) TxtPrecio.Text = drPS("Precio").ToString.FormatoNumero(2).Replace(","c, "") If UsuarioActual.CveEmpresa = 80 Then 'busca el precio de la sucursal Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSSucursales(DdlPS.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, CveSubProyecto) Then Dim dtt As DataTable = ObjPS.DtResultados Dim drPrecio As DataRow = dtt.FiltroPrimero("") If drPrecio IsNot Nothing Then TxtPrecio.Text = drPrecio("Importe").ToString.ToDouble.ToString("N4") End If dtt.Dispose() End If ObjPS.Dispose() End If If DdlClasificacion.SelectedIndex = 0 Then If drPS("CveClasificacion").ToString IsNot Nothing Then DdlClasificacion.SelectedValueExist(drPS("CveClasificacion").ToString) Else Alert("El Productos/Servicio no tiene asignada una Clasificación.") End If End If End If ElseIf DdlPS.SelectedValue = "-2" Then CargaPS(-1, DdlPS) End If Else Alert("Es necesario seleccionar el cliente al cual se le va a facturar.", TipoMensaje.MsgAdvertencia, "AbrirVentana(""/Ventas/PopUpBuscarClientes.aspx?Opt=Fact"", 800, 547, ""N"", ""PopUpBuscar"")") End If RegistraScript("Recalcula();") UpVenta.Update() End Sub Protected Sub DdlClasificacion_SelectedIndexChanged(sender As Object, e As EventArgs) CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS) UpClasificacion.Update() End Sub #End Region #Region "AGREGAR/EDITAR/ELIMINAR" Protected Sub LnkAddPedido_Click(sender As Object, e As EventArgs) RegistraScript("$('#DivVenta').modal({backdrop: 'static',keyboard: false});") End Sub Protected Sub LnkAddPSVenta_Click(sender As Object, e As EventArgs) Modalidad = "A" LnkAgregar.Text = "Agregar" TxtCantidad.Text = "" TxtObs.Text = "" TxtPrecio.Text = "0.00" LblTotal.Text = "0.00" If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then DdlPS.SelectedValue = "-1" Else DdlPS.SelectedValue = "" DdlPS.SelectedText = "" End If DdlClasificacion.SelectedIndex = -1 DdlUM.Items.Clear() ChkAgregar.Checked = True UpAddPedido.Update() RegistraScript("$('#DivAddVenta').modal({backdrop: 'static',keyboard: false});") End Sub Protected Sub LnkEditar_Click(sender As Object, e As EventArgs) Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) Modalidad = "U" Index = GvRow.DataKey("Consec").ToEntero LnkAgregar.Text = "Actualizar" DdlClasificacion.SelectedValueExist(GvRow.DataKey("CveClasificacion")) CargaPS(DdlClasificacion.SelectedValue.ToEntero, DdlPS) UpClasificacion.Update() If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then DdlPS.SelectedValue = GvRow.DataKey("CvePS") Else DdlPS.SelectedValue = GvRow.DataKey("CvePS") DdlPS.SelectedText = GvRow.DataKey("PS") End If DdlPSIndexChange() DdlUM.SelectedValueExist(GvRow.DataKey("CveUM")) TxtCantidad.Text = GvRow.DataKey("Cantidad") TxtObs.Text = GvRow.DataKey("Obs") TxtPrecio.Text = GvRow.DataKey("PU") LblTotal.Text = GvRow.DataKey("Total") ChkAgregar.Checked = False UpAddPedido.Update() RegistraScript("$('#DivAddVenta').modal('show');", "EdicionVenta") End Sub Protected Sub LnkEliminar_Click(sender As Object, e As EventArgs) Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) Dim DbRow As DataRow = Nothing DbRow = TmpDT.Rows(GvRow.RowIndex) TmpDT.Rows.Remove(DbRow) GvPS.DataSource = TmpDT GvPS.DataBind() CalculaTotalesVenta() Alert("Eliminado Correctamente.", TipoMensaje.MsgInformacion) End Sub Protected Sub LnkAgregar_Click(sender As Object, e As EventArgs) AgregarPS() If ChkAgregar.Checked = True And Modalidad = "A" Then LnkAgregar.Text = "Agregar" TxtCantidad.Text = "" TxtObs.Text = "" TxtPrecio.Text = "0.00" LblTotal.Text = "0.00" If Not UsuarioActual.Empresa.Funcionalidad(141).ToString = "1" Then DdlPS.SelectedValue = "-1" Else DdlPS.SelectedValue = "" DdlPS.SelectedText = "" End If DdlClasificacion.SelectedIndex = -1 DdlUM.Items.Clear() Else RegistraScript("ClosePopup();", "AddUpdatePS") End If UpAddPedido.Update() End Sub Private Sub AgregarPS() If Modalidad = "U" Then Dim ErrorEdit As Boolean = True Dim Contador As Integer = 0 For Each row As DataRow In TmpDT.Rows If row("Consec").ToString.ToEntero = Index Then ErrorEdit = False Exit For End If Contador = Contador + 1 Next If ErrorEdit = True Then Exit Sub Else TmpDT.AcceptChanges() TmpDT.Rows.RemoveAt(Contador) TmpDT.AcceptChanges() End If End If AgregarProductoServicio(TxtCantidad.Text.ToDecimal, DdlUM.SelectedValue.ToEntero, DdlUM.SelectedItem.Text, DdlClasificacion.SelectedValue.ToEntero, DdlClasificacion.SelectedItem.Text, DdlPS.SelectedValue.ToEntero, DdlPS.SelectedText, TxtObs.Text, TxtPrecio.Text.ToDecimal, 0, -1, "", CveSubProyecto, "") CalculaTotalesVenta() End Sub Private Function AgregarProductoServicio(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String, PU As Decimal, Descuento As Decimal, CveProyecto As Integer, Proyecto As String, CveSubProyecto As Integer, SubProyecto As String, Optional Serie As String = "", Optional TiempoEntrega As String = "", Optional EntregaDirecta As Integer = 0, Optional CveContratoDetalle As Integer = 0, Optional CveVentaDetalle As Integer = 0, Optional CveMovimientoDetallePedido As Integer = 0, Optional CveOrdenCompraDetalle As Integer = 0, Optional CveVentaDetalleRemision As Integer = 0, Optional CveVentaDetalleCotizacion As Integer = 0, Optional CuentaPredial As String = "", Optional RegeneraIEPS As Boolean = True, Optional CveVentaDetallePedido2 As Integer = 0) As Boolean Dim Retorno As Boolean = False If Not CvePS > 0 Then Alert("Ocurrió un error al cargar la información del producto a agregar. Por favor verifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If 'VALIDA CONCEPTOS EN CERO - YA SE VALIDA ANTES CON FUNCIONALIDAD - A MIRAS DE ELIMINAR - IPP 28 AGOSTO 2017 If UsuarioActual.CveEmpresa.Contiene(72, 80) AndAlso CveOrdenCompraDetalle = 0 Then ' si viene de una oc, se permiten valores en cero If Cantidad * PU <= 0 Then Alert("El importe del concepto debe ser mayor a cero. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If End If Dim Row As DataRow = Nothing Dim TotalCalculableImpuestos As Decimal = 0 PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos Row = TmpDT.NewRow() Row("CveProyecto") = CveProyecto Row("Proyecto") = Proyecto Row("CveSubProyecto") = CveSubProyecto Row("SubProyecto") = SubProyecto Row("Serie") = Serie Row("TiempoEntrega") = TiempoEntrega Row("Orden") = TmpDT.Rows.Count + 1 Row("Cantidad") = Cantidad Row("CveUM") = CveUM Row("UM") = UM Row("CveClasificacion") = CveClasificacion Row("Clasificacion") = Clasificacion Row("CvePS") = CvePS Row("Obs") = Obs Dim DrPS As DataRow = Nothing DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") ' Estado = -1 If DrPS Is Nothing Then Alert("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.", TipoMensaje.MsgAdvertencia) Return False End If 'verifica si tiene ventaminima If Cantidad > 0 AndAlso DrPS("VentaMinima").ToString.ToDecimal > 0 Then 'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15... If Cantidad Mod DrPS("VentaMinima").ToString.ToDecimal <> 0 Then Alert(String.Format("El producto se vende solo en cantidades de {0}", DrPS("VentaMinima").ToString)) Return False End If End If TotalCalculableImpuestos = (Cantidad * (PU)) - Descuento Row("PU") = PU Row("Codigo") = DrPS("Codigo") Row("NoIdentificacion") = DrPS("Codigo") Row("ClaveSATFraccionArancelaria") = DrPS("ClaveSATFraccionArancelaria") Row("ClaveSATUnidadAduana") = DrPS("ClaveSATUnidadAduana") Row("ClaveSATFraccionArancelariaDescripcion") = DrPS("ClaveSATFraccionArancelariaDescripcion") Row("ClaveSATUnidadAduanaDescripcion") = DrPS("ClaveSATUnidadAduanaDescripcion") If Modalidad = "U" Then Row("Consec") = Index Else Row("Consec") = TmpDT.Rows.Count + 1 End If Row("PS") = DrPS("PS") Row("CodigoPS") = DrPS("PSCodigo").ToString Row("CveTipoPS") = DrPS("CveTipoPS") Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario") If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion") If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion") If DrPS("IVA").ToString.Contiene("-1", "") Then Row("PorcentajeIVA") = SubProyectoPorcentajeIVA Else Row("PorcentajeIVA") = DrPS("IVA") End If Row("IVA") = Row("PorcentajeIVA") Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, 2) Row("Total") = (Cantidad * PU) Row("TotalImporte") = Math.Round(Cantidad * PU, 2) Row("SATClaveProdServ") = DrPS("SATClavePS") Row("SATClaveUM") = DrPS("SATClaveUnidadMedida") Row("EntregaDirecta") = EntregaDirecta 'Contratos Row("CveContratoDetalle") = CveContratoDetalle Row("CveVentaDetalle") = CveVentaDetalle Row("CveMovimientoDetallePedido") = CveVentaDetalle Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle Row("CveVentaDetalleRemision") = CveVentaDetalleRemision Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion Row("CveVentaDetallePedido2") = CveVentaDetallePedido2 Row("CuentaPredial") = CuentaPredial 'RECARGAR GV TmpDT.Rows.Add(Row) Retorno = True Return Retorno End Function Private Sub CalculaTotalesVenta() Dim TotalSubTotal As Decimal = TmpDT.SUM("TotalImporte").ToDecimal Dim TotalDescuentos As Decimal = TmpDT.SUM("Descuento").ToDecimal Dim TotalIVA As Decimal = TmpDT.SUM("ImporteIVA").ToDecimal Dim TotalIEPS As Decimal = TmpDT.SUM("ImporteIEPS").ToDecimal Dim TotalRetIVA As Decimal = TmpDT.SUM("ImporteRetIVA").ToDecimal Dim TotalRetISR As Decimal = TmpDT.SUM("ImporteRetISR").ToDecimal Dim Total As Decimal = 0 Total = (TotalSubTotal - TotalDescuentos + TotalIVA + TotalIEPS - TotalRetIVA - TotalRetISR) TxtSubTotal.Text = TotalSubTotal.FormatoNumero(2) TxtIVA.Text = TotalIVA.FormatoNumero TxtTotal.Text = Total.FormatoNumero Dim view As DataView = New DataView(TmpDT) view.Sort = "Consec" GvPS.DataSource = view GvPS.DataBind() UpAddPedido.Update() End Sub #End Region #Region "GUARDAR VENTA" Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False) ObjFactura = New Modelos.Factura ObjFactura.Version = "3.3" ObjFactura.CveUsuario = UsuarioActual.CveUsuario ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa ObjFactura.TipoCambio = 0 ObjFactura.ConvertirPesos = False ObjFactura.TipoCambio = TxtTipoCambio.Text.Trim.ToDecimal ObjFactura.CveMoneda = DdlMoneda.SelectedValue.ToEntero ObjFactura.Moneda = GlobalDTMonedas.FiltroPrimeroValor("Moneda", $"CveMoneda = {ObjFactura.CveMoneda} ") ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", "CveMoneda = 1") ObjFactura.TipoDocto = "Pd2" ObjFactura.RefDocto = "" ObjFactura.Folio = Folio.ToEntero ObjFactura.Serie = Serie ObjFactura.CveMesa = -1 ObjFactura.Fecha = Now ObjFactura.CvePrePoliza = -1 ObjFactura.FechaPago = Now ObjFactura.MotivoDescuento = "" ObjFactura.Observaciones = "" ObjFactura.FechaEjecucion = Now ObjFactura.UsuarioCreo = UsuarioActual.Usuario ObjFactura.CveCondicionEntrega = -1 ObjFactura.CondicionEntrega = "" ObjFactura.NumeroCuenta = "" ObjFactura.CondicionesPago = 0 ObjFactura.FormaPago = 0 ObjFactura.PedidoContrato = "" ObjFactura.NumeroContrato = "" ObjFactura.DescripcionContrato = "" ObjFactura.CveCorte = -1 ObjFactura.TipoDocumento = "Pedido2" ObjFactura.Alfa1 = "" ObjFactura.Alfa2 = "" ObjFactura.Alfa3 = "" ObjFactura.Descuento = 0 ObjFactura.Amortizacion = 0 ObjFactura.CveContrato = 0 ObjFactura.CveSubProyecto = CveSubProyecto ObjFactura.CveSubProyectoCobranza = CveSubProyecto ObjFactura.CveSubProyectoEjecucion = CveSubProyecto ObjFactura.SubTotal = TxtSubTotal.Text.ToDecimal ObjFactura.Descuento = 0 ObjFactura.Amortizacion = 0 ObjFactura.IVA = TxtIVA.Text.ToDecimal ObjFactura.RetIVA = 0 ObjFactura.RetISR = 0 ObjFactura.IEPS = 0 ObjFactura.Total = TxtTotal.Text.ToDecimal 'DETALLES ObjFactura.DtDetalle = TmpDT 'CLIENTE ObjFactura.CveCliente = CveCliente ObjFactura.SetCliente() Dim ObjCliente As New ClsClientes If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, -1, TipoCliente:=-1) Then If ObjCliente.DtResultados.Rows.Count > 0 Then ObjFactura.CveFormaPago33 = ObjCliente.CveFormaPago33 ObjFactura.FormaPago33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("FormaPago", $"CveFormaPago = {ObjCliente.CveFormaPago33}") ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", $"CveFormaPago = {ObjCliente.CveFormaPago33}") ObjFactura.CveMetodoPago33 = ObjCliente.CveMetodoPago33 ObjFactura.MetodoPago33 = GlobalDTVtaMetodoPago.FiltroPrimeroValor("MetodoPago", $"CveMetodoPago = {ObjCliente.CveMetodoPago33}") ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", $"CveMetodoPago = {ObjCliente.CveMetodoPago33}") ObjFactura.CveUsoCFDI = ObjCliente.CveUsoCFDI ObjFactura.UsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("Descripcion", $"CveUsoCFDI = {ObjCliente.CveUsoCFDI}") ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", $"CveUsoCFDI = {ObjCliente.CveUsoCFDI}") ObjFactura.CveMetodoPago = ObjCliente.CveMetodoPago If GlobalDTMetodosPago.FiltraParametros($"CveMetodoPago = {ObjCliente.CveMetodoPago}").Rows.Count > 0 Then ObjFactura.MetodoPago = GlobalDTMetodosPago.FiltraParametros($"CveMetodoPago = {ObjCliente.CveMetodoPago}").Rows(0)("MetodoPago").ToString Else ObjFactura.CveMetodoPago = 1 ObjFactura.MetodoPago = "Efectivo" End If ViewState("IdCtaContRetIVA") = ObjCliente.IdCtaContRetIVA ViewState("CveCuentaRetIVA") = ObjCliente.CveCuentaRetIVA ViewState("IdCtaContRetISR") = ObjCliente.IdCtaContRetISR ViewState("CveCuentaRetISR") = ObjCliente.CveCuentaRetISR End If End If ObjCliente.Dispose() 'SUBPROYECTO ObjFactura.SetSubProyectoMatriz(Me) ObjFactura.SetSubProyecto(Me) ObjFactura.Timbre = PreParaTimbre(ObjFactura) End Sub Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre Dim Timbre As New CFDITimbre Timbre.Comprobante.TipoComprobante = If(Obj.TipoDocto.Contiene("Ing", "Ant"), "I", If(Obj.TipoDocto.Contiene("Egs", "Dev"), "E", "")) Timbre.Comprobante.Folio = Obj.Folio.ToString Timbre.Comprobante.Serie = Obj.Serie Timbre.Comprobante.Fecha = Obj.Fecha Timbre.Comprobante.FormadePago = Obj.FormaPagoSAT33 Timbre.Comprobante.CondicionesdePago = Obj.FormaPago33 Timbre.Comprobante.MetodoPago = Obj.ClaveMetodoPagoSAT Timbre.Comprobante.Subtotal = Obj.SubTotal Timbre.Comprobante.Descuentos = Obj.Descuento Timbre.Comprobante.Moneda = Obj.MonedaSAT Timbre.Comprobante.TipoCambio = If(Obj.CveMoneda = 1, "1", Obj.TipoCambio.ToString) Timbre.Comprobante.Total = Obj.Total Timbre.Comprobante.LugarExpedicion = Obj.SubProyecto.CP Timbre.Comprobante.Confirmacion = "" Timbre.Receptor.RFC = Obj.Cliente.RFC Timbre.Receptor.Nombre = Obj.Cliente.Nombre Timbre.Receptor.ResidenciaFiscal = "" Timbre.Receptor.NumeroRegistroTributario = "" Timbre.Receptor.UsoCFDI = Obj.ClaveUsoCFDI If Obj.CveTipoRelacion > 0 Then Select Case Obj.CveTipoRelacion Case 1 Timbre.CFDIRelacionados.TipoRelacion = "01" Timbre.CFDIRelacionados.TipoRelacionTexto = "01-Nota de Crédito aplicada a Ingreso" Case 2 Timbre.CFDIRelacionados.TipoRelacion = "02" Timbre.CFDIRelacionados.TipoRelacionTexto = "02-Nota de débito de los documentos relacionados" Case 3 Timbre.CFDIRelacionados.TipoRelacion = "03" Timbre.CFDIRelacionados.TipoRelacionTexto = "03-Devolución aplicada a Ingreso" Case 4 Timbre.CFDIRelacionados.TipoRelacion = "04" Timbre.CFDIRelacionados.TipoRelacionTexto = "04-Refacturación de Ingreso" Case 7 Timbre.CFDIRelacionados.TipoRelacion = "07" Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo" Case 8 Timbre.CFDIRelacionados.TipoRelacion = "08" Timbre.CFDIRelacionados.TipoRelacionTexto = "08-Factura generada por pagos en parcialidades " Case 9 Timbre.CFDIRelacionados.TipoRelacion = "09" Timbre.CFDIRelacionados.TipoRelacionTexto = "09-Factura generada por pagos diferidos" End Select End If Dim totSubTotal As Decimal = Obj.SubTotal Dim totIVA As Decimal = Obj.IVA Dim totRetIVA As Decimal = Obj.RetIVA Dim totRetISR As Decimal = Obj.RetISR Dim i As Integer = 1 'DETALLES Dim tPS As String = "" For Each drr As DataRow In Obj.DtDetalle.Rows If drr("PS").ToString.Length = 1 Then tPS = drr("Obs").ToString Else If drr("PS").ToString.Length = 0 Then tPS = "" Else tPS = String.Format("{0} {1}", drr("PS"), drr("Obs")) End If End If 'CONDICIONANTE, ESPECIAL If UsuarioActual.CveEmpresa = 15 Then drr("UM") = "" 'LES COMENTAN QUE NO DEBE IR LA ETIQUETA DE LA UNIDAD EN EL PRODUCTO Dim concepto As New CFDIConceptos With {.Cantidad = drr("Cantidad").ToString.ToDecimal, .Descripcion = tPS, .ValorUnitario = drr("PU").ToString.ToDecimal, .Importe = drr("TotalImporte").ToString.ToDecimal, .Descuento = drr("Descuento").ToString.ToDecimal, .Unidad = drr("UM").ToString, .ClaveUnidad = drr("SATClaveUM").ToString, .ClaveProdServ = drr("SATClaveProdServ").ToString, .Noidentificacion = drr("Noidentificacion").ToString, .CuentaPredial = drr("CuentaPredial").ToString} 'VERIFICA SUMA SUBTOTALES If i = Obj.DtDetalle.Rows.Count AndAlso totSubTotal <> concepto.Importe Then 'PROCESO DE AJUSTA DE DECIMALES concepto.Importe = totSubTotal End If totSubTotal = totSubTotal - concepto.Importe 'SIEMPRE ESTAMOS AGREGANDO EL IVA concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteIVA").ToString.ToDecimal}) If drr("ImporteIEPS").ToString.ToDouble > 0 Then concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIEPS").ToString.ToDecimal, .Impuesto = "003", .Importe = drr("ImporteIEPS").ToString.ToDecimal}) End If If drr("ImporteRetIVA").ToString.ToDouble > 0 Then 'si hay retenciones concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeRetIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteRetIVA").ToString.ToDecimal}) End If If drr("ImporteRetISR").ToString.ToDouble > 0 Then 'retención de ISR concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeRetISR").ToString.ToDecimal, .Impuesto = "001", .Importe = drr("ImporteRetISR").ToString.ToDecimal}) End If Timbre.Conceptos.Add(concepto) i += 1 Next Return Timbre End Function Protected Sub BtnGuardar_Click(sender As Object, e As EventArgs) If TmpDT Is Nothing OrElse TmpDT.Rows.Count = 0 Then Alert("Es necesario tener al menos un concepto registrado.", TipoMensaje.MsgAdvertencia) Exit Sub End If 'Subproyecto Obligatorio If UsuarioActual.Empresa.Funcionalidad(120) = "1" AndAlso TmpDT.FiltraParametros("ISNULL(CveSubProyecto,0) <= 0").Rows.Count > 0 Then Alert("El Subproyecto de los conceptos es obligatorio, Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If CreaObjetosVenta() If ObjFactura Is Nothing Or ObjFactura.Cliente Is Nothing Then Alert("Ocurrió un error al procesar los datos de la Venta.", TipoMensaje.MsgError) ObjFactura = Nothing Exit Sub End If 'VALIDA CUENTAS CONTABLES DE AC If UsuarioActual.Empresa.UsaAC Then If ObjFactura.Cliente.IdCtaContClientes <= 0 Then Alert("El Cliente no tiene registrado la cuenta contable", TipoMensaje.MsgError) Exit Sub End If If ObjFactura.SubTotal <= 0 Then Alert("Es necesario especificar el importe en los conceptos. Por favor rectifique y vuelva a intentar.", TipoMensaje.MsgAdvertencia) Exit Sub End If End If If ObjFactura.CveCliente > 0 Then If TmpDT.Rows.Count > 0 Then Dim ObjVentas As New ClsVentas() Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) Dim ObjContr As New ClsContratos(ObjVentas.IniciaTransacSQL()) Dim ObjOS As New ClsOS(ObjVentas.IniciaTransacSQL()) Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) Dim ObjClientes As New ClsClientes(ObjVentas.IniciaTransacSQL()) Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) Dim ObjCGame As New ClsCGame(ObjVentas.IniciaTransacSQL()) Dim ObjDocCliente As New ClsEdocumentacion(ObjVentas.IniciaTransacSQL()) Dim ObjContPaq As ClsContPAQi = Nothing ErrorList = New List(Of String) MensajeAlert = New StringBuilder 'CONTABILIDAD AUTOMATICA Y AC If UsuarioActual.Empresa.UsaAC OrElse UsuarioActual.Empresa.Funcionalidad(200) = "1" Then ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) End If GuardarVenta(ObjVentas, ObjConta, ObjInventario, ObjContr, ObjFactura, TmpDT, ObjFactura.CveNCaVincular, ObjContPaq, ObjBancos, ObjOS, ObjEventos, ObjCGame, ObjClientes) If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 Then 'Marcamos las ventas anteriores a febrero como surtidas - Ajuste Compu If ErrorList.Count = 0 Then If Not ObjVentas.MarcarRemisionesSinSurtir(ObjVentas.CveVenta) Then ErrorList.Add("Ocurrió un Error al marcar la factura") End If End If If ObjFactura.CveVenta > 0 AndAlso ErrorList.Count = 0 AndAlso (ObjFactura.TipoDocto.Contiene("Ped", "Cot", "DPe", "PeC", "PA", "Pd2")) Then ObjVentas.Commit() 'ObjVentas.RollBack() If ObjContPaq IsNot Nothing Then ObjContPaq.Commit() 'If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() ViewState("CveVenta") = ObjFactura.CveVenta If ObjFactura.CveVenta > 0 Then EnviarCorreoPedido(ObjFactura) End If 'MENSAJE PRINCIPAL MensajeAlert.AppendFormat(String.Format("
El {0}: {1} se generó correctamente.

", ObjFactura.TipoDocumento, ObjFactura.SerieFolio)) 'MUESTA ALERT OK Alert(MensajeAlert.ToString, TipoMensaje.MsgInformacion) Else ObjVentas.RollBack() If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() For Each ErrorItem In ErrorList Alert(ErrorItem, TipoMensaje.MsgAdvertencia) Next 'MUESTA ALERT ERROR Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) End If ObjVentas.Dispose() ObjConta.Dispose() ObjInventario.Dispose() ObjCGame.Dispose() ObjContr.Dispose() ObjDocCliente.Dispose() ObjClientes.Dispose() 'ObjFolios.Dispose() ErrorList = Nothing MensajeAlert = Nothing If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() LimpiaTabPedido() Else ObjVentas.RollBack() If ObjContPaq IsNot Nothing Then ObjContPaq.RollBack() For Each ErrorItem In ErrorList Alert(ErrorItem, TipoMensaje.MsgAdvertencia) Next 'MUESTA ALERT ERROR Alert("Ocurrió un error al procesar los datos. Por favor rectifique y vuelta a intentar.", TipoMensaje.MsgError) ObjVentas.Dispose() ObjConta.Dispose() ObjInventario.Dispose() ObjCGame.Dispose() ObjContr.Dispose() ObjDocCliente.Dispose() ObjClientes.Dispose() 'ObjFolios.Dispose() ErrorList = Nothing MensajeAlert = Nothing If ObjContPaq IsNot Nothing Then ObjContPaq.Dispose() End If End If End If End Sub Private Sub EnviarCorreoPedido(ObjFactura As Modelos.Factura) Dim Hilo As New System.Threading.Thread(Sub() MandaMails(UsuarioActual, ObjFactura.CveVenta, True, ObjFactura)) Hilo.Start() End Sub Private Sub GuardarVenta(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjInventario As ClsInventarios, ByRef ObjContr As ClsContratos, factura As Modelos.Factura, TmpDTDetalle As DataTable, CveNCaVincular As Integer, ByRef objContPaqi As ClsContPAQi, Optional ByRef ObjBancos As ClsBancos = Nothing, Optional ByRef ObjOS As ClsOS = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, ByRef Optional ObjCGame As ClsCGame = Nothing, ByRef Optional ObjCliente As ClsClientes = Nothing) Dim CveAlmacenTraspasoOrigen As Integer = -1 Dim CveAlmacenTraspasoDestino As Integer = -1 Dim EsDevolucionVenta = -1 Dim TotalImpuestoLocal As Double = 0 factura.CvePrePoliza = ObjConta.AddPrePolizas("PortalC/GuardarVenta", factura.CvePlantillaPoliza, factura.Total, factura.Total, factura.CveMoneda, factura.Fecha, factura.Cliente.Nombre, factura.CveUsuario, factura.CveEmpresa) If Not ObjVentas.AddVenta(factura.TipoDocto, factura.Folio, factura.CveCliente, factura.CveClienteSucursal, factura.SubTotalTC, factura.DescuentoTC, factura.AmortizacionTC, factura.IVATC, factura.RetIVATC, factura.RetISRTC, factura.TotalTC, factura.CveMoneda, factura.TipoCambio, factura.CveMetodoPago, factura.CondicionesPago, factura.FormaPago, factura.FechaPago, factura.Fecha, factura.MotivoDescuento, factura.Observaciones, factura.FechaEjecucion, factura.CveVendedor, factura.Alfa1, factura.Alfa2, factura.Alfa3, factura.Num1, factura.Num2, factura.Num3, factura.Fech1, factura.Fech2, factura.Fech3, factura.CveCorte, factura.CveMesa, factura.NumeroPersonas, factura.CvePrePoliza, factura.CveUsuario, factura.CveEmpresa, AtencionA:=factura.AtencionA, CveContrato:=factura.CveContrato, Det_FechaOrdenCompra:=factura.Det_FechaOrdenCompra, Det_OrdenCompra:=factura.Det_OrdenCompra, otros:=factura.Otros, CveAlmacenTraspasoDestino:=CveAlmacenTraspasoDestino, CveAlmacenTraspasoOrigen:=CveAlmacenTraspasoOrigen, IEPS:=factura.IEPSTC, Serie:=factura.Serie, CveSubProyecto:=factura.CveSubProyecto, CveSubProyectoCobranza:=factura.CveSubProyectoCobranza, CveSubProyectoEjecucion:=factura.CveSubProyectoEjecucion, CveFormaPago33:=factura.CveFormaPago33, CveMetodoPago33:=factura.CveMetodoPago33, CveUsoCFDI:=factura.CveUsoCFDI, CveTipoRelacion:=factura.CveTipoRelacion, ImpuestoLocal:=TotalImpuestoLocal, CveVentaRelacion:=(If(factura.CveVentaRelacion.ToEntero > 0, factura.CveVentaRelacion, -1)), ImporteRelacion:=(If(factura.ImporteRelacion <> Nothing, factura.ImporteRelacion, -1)), CveTipoAmortizacionAnticipo:=factura.CveTipoAmortizacionAnticipo) Then ErrorList.Add("Ocurrió un error al Generar la Venta.
Revise su factura y cualquier detalle comuníquese a Soporte Técnico") End If If ErrorList.Count = 0 AndAlso ObjVentas.CveVenta > 0 Then factura.CveVenta = ObjVentas.CveVenta factura.Serie = ObjVentas.Serie factura.Folio = ObjVentas.Folio ViewState("VentaFolio") = ObjVentas.SerieFolio factura.Timbre.Comprobante.Serie = ObjVentas.Serie factura.Timbre.Comprobante.Folio = ObjVentas.Folio.ToString 'Se agregan los PS For Each Row As DataRow In TmpDTDetalle.Rows If Not ObjVentas.AddVentaDetalle(ObjVentas.CveVenta, Row("CvePS").ToString.ToEntero, Row("Cantidad").ToString.ToDouble, Row("CveUM").ToString.ToEntero, Row("PU").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("IVA").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Math.Round((Row("Total").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)) * (1 + Row("IVA").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)))), 6), Row("Obs").ToString, Row("Descuento").ToString.ToDouble(If(factura.ConvertirPesos, factura.TipoCambio, 1)), Row("TipoDescuento").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, Row("CvePresupuestoIngreso").ToString.ToEntero, TiempoEntrega:=Row("TiempoEntrega").ToString, CveVentaDetallePadre:=Row("CveVentaDetalle").ToString.ToEntero, CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, IEPS:=Row("ImporteIEPS").ToString.ToDouble, CveMovimientoDetallePedido:=Row("CveMovimientoDetallePedido").ToString.ToEntero, ImporteRetIVA:=Row("ImporteRetIVA").ToString.ToDouble, ImporteRetISR:=Row("ImporteRetISR").ToString.ToDouble, PorcentajeIEPS:=Row("PorcentajeIEPS").ToString.ToDouble, PorcentajeRetIVA:=Row("PorcentajeRetIVA").ToString.ToDouble, PorcentajeRetISR:=Row("PorcentajeRetISR").ToString.ToDouble, CuentaPredial:=Row("CuentaPredial").ToString) Then ErrorList.Add("Ocurrió un error al agregar un Producto o Servicio a la Factura.
Revise su factura y cualquier detalle comuníquese a Soporte Técnico") Exit For Else Dim TmpDr As DataRow = TmpDT.Select($"Consec = {Row("Consec").ToString}")(0) TmpDr("CveVentaDetalle") = ObjVentas.CveVentaDetalle End If Next End If 'If ErrorList.Count = 0 Then ' 'prepoliza ' GuardarVentaPrePolizas(ObjConta, factura, TmpDTDetalle, CveNCaVincular, objContPaqi, ObjBancos, ObjVentas, ObjEventos:=ObjEventos) ' If ErrorList.Count = 0 Then ' 'inventarios ' If GuardarVentaInventarios(ObjInventario, ObjConta, factura) Then ' ErrorList.Add("Ocurrio un error al Guardar Inventario") ' End If ' If ErrorList.Count = 0 Then ' 'estimaciones ' GuardarVentaEstimaciones(ObjContr, factura) ' If ErrorList.Count = 0 Then ' 'armonizaccionContable ' GuardarVentaAC(ObjVentas, factura, Msgok, objContPaqi) ' If ErrorList.Count = 0 Then ' 'Impuestos Locales ' If GuardarVentaImpuestosLocales(ObjVentas, ObjConta, factura) Then ' ErrorList.Add("Ocurrio un error al Guardar Impuestos Locales") ' End If ' End If ' End If ' End If ' End If 'End If End Sub Private Sub LimpiaTabPedido() CargaFolios() TmpDT.Rows.Clear() Dim Dt = New DataSet Dt.Tables.Add("Datos") Dt.Tables("Datos").Columns.Add("") GvPS.DataSource = Dt.Tables("Datos") GvPS.DataBind() TxtObs.Text = "" CalculaTotalesVenta() UpTabPedidos.Update() End Sub #End Region #End Region End Class