diff --git a/App_Code/ClsCompProveedores.vb b/App_Code/ClsCompProveedores.vb index cc81e5ff1..56585d092 100644 --- a/App_Code/ClsCompProveedores.vb +++ b/App_Code/ClsCompProveedores.vb @@ -292,7 +292,7 @@ Public Class ClsCompProveedores Return Retorno End Function - Public Function GetProveedores(TipoConsulta As TipoConsulta, CveProveedor As Integer, Codigo As String, RazonSocial As String, NombreComercial As String, + Public Function GetProveedores(tipoConsulta As TipoConsulta, CveProveedor As Integer, Codigo As String, RazonSocial As String, NombreComercial As String, NombreCorto As String, RFC As String, ContactoNombre As String, Telefono As String, Estatus As Integer, CveEmpresa As Integer, Optional CveTipoProveedor As Integer = -1, Optional CveUsuarioResponsable As Integer = -1, Optional CveMonedaPreferente As Integer = -1, Optional CveProveedorClasificacion As Integer = -1) As Boolean @@ -301,7 +301,7 @@ Public Class ClsCompProveedores DataAdapter("PA_Comp_ProveedoresGet") With SqlAdapter.SelectCommand.Parameters - .Add("@TipoConsulta", SqlDbType.Int).Value = TipoConsulta + .Add("@TipoConsulta", SqlDbType.Int).Value = tipoConsulta .Add("@CveProveedor", SqlDbType.Int).Value = CveProveedor .Add("@Codigo", SqlDbType.VarChar).Value = Codigo .Add("@RazonSocial", SqlDbType.VarChar).Value = RazonSocial @@ -321,7 +321,7 @@ Public Class ClsCompProveedores Try SqlAdapter.Fill(Data) - If Data.Rows.Count = 1 Then + If Data.Rows.Count = 1 And tipoConsulta <> TipoConsulta.ParaGlobalDT Then Me.CveProveedor = Data.Rows(0)("CveProveedor").ToString.ToEntero Me.Codigo = Data.Rows(0)("Codigo").ToString Me.RazonSocial = Data.Rows(0)("RazonSocial").ToString diff --git a/Ashx/SIGWeb.ashx b/Ashx/SIGWeb.ashx index b24cd113d..eb63f151b 100644 --- a/Ashx/SIGWeb.ashx +++ b/Ashx/SIGWeb.ashx @@ -1,72 +1,72 @@ <%@ WebHandler Language="VB" Class="SIGWeb" %> -Imports System -Imports System.Web -Imports System.Data -Imports Newtonsoft.Json -Imports Extensiones -Imports System.IO - -Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState - - Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest - context.Response.ContentType = "text/plain" - Try - Select Case context.Request("metodo") - Case "getps" - GETPS(context) - Case "getps2" - GETPS(context, "PSCodigoClasificacion") - Case "getpsalmacen" - getpsalmacen(context) - Case "Uploadfile" - uploadfile(context) - Case "Downfile" - Downfile(context) - Case "GetImg" - GetImg(context) - Case "getpssat" - GETPSSAT(context) - Case "getpsusados" - GETPSUSADOS(context) - Case "getumsat" - GETUMSAT(context) - Case "getcliente" - GetClientes(context) - Case "getproveedores" - GetProveedores(context) - Case "getfraccionarancelaria" - GetFraccionArancelaria(context) - Case "GetUser" +Imports System +Imports System.Web +Imports System.Data +Imports Newtonsoft.Json +Imports Extensiones +Imports System.IO + +Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState + + Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest + context.Response.ContentType = "text/plain" + Try + Select Case context.Request("metodo") + Case "getps" + GETPS(context) + Case "getps2" + GETPS(context, "PSCodigoClasificacion") + Case "getpsalmacen" + getpsalmacen(context) + Case "Uploadfile" + uploadfile(context) + Case "Downfile" + Downfile(context) + Case "GetImg" + GetImg(context) + Case "getpssat" + GETPSSAT(context) + Case "getpsusados" + GETPSUSADOS(context) + Case "getumsat" + GETUMSAT(context) + Case "getcliente" + GetClientes(context) + Case "getproveedores" + GetProveedores(context) + Case "getfraccionarancelaria" + GetFraccionArancelaria(context) + Case "GetUser" GetUser(context) - Case "ActualizaPreP" - ActualizaPrePoliza(context) - - End Select - Catch ex As Exception - ex.GuardaLog(ex.Message) - End Try - End Sub - - - Private Sub GetUser(ByVal context As HttpContext) - Dim usuario As String = context.Request("usuario").ToString() - Dim CveUsuario As Integer = -1 - Dim objs As New ClsSisUsuarios - objs.GetWSusuarios(usuario) - If objs.DtResultados.Rows.Count > 0 Then - CveUsuario = objs.DtResultados.Rows(0)("CveUsuario").ToString().ToEntero() - End If - objs.Dispose() - If CveUsuario > 0 Then - CveUsuario = 1 - End If - - context.Response.Write(CveUsuario.ToString()) - context.Response.StatusCode = 200 + Case "ActualizaPreP" + ActualizaPrePoliza(context) + + End Select + Catch ex As Exception + ex.GuardaLog(ex.Message) + End Try End Sub - Private Sub ActualizaPrePoliza(ByVal context As HttpContext) + + Private Sub GetUser(ByVal context As HttpContext) + Dim usuario As String = context.Request("usuario").ToString() + Dim CveUsuario As Integer = -1 + Dim objs As New ClsSisUsuarios + objs.GetWSusuarios(usuario) + If objs.DtResultados.Rows.Count > 0 Then + CveUsuario = objs.DtResultados.Rows(0)("CveUsuario").ToString().ToEntero() + End If + objs.Dispose() + If CveUsuario > 0 Then + CveUsuario = 1 + End If + + context.Response.Write(CveUsuario.ToString()) + context.Response.StatusCode = 200 + End Sub + + Private Sub ActualizaPrePoliza(ByVal context As HttpContext) Dim CvePrePoliza As Integer = context.Request("CvePrePoliza").ToString.ToEntero Dim CveEmpresa As Integer = context.Request("CveEmpresa").ToString.ToEntero Dim CveUsuario As Integer = context.Request("CveUsuario").ToString.ToEntero @@ -96,95 +96,95 @@ Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState ObjConta.Dispose() 'context.Response.Write(CveUsuario.ToString()) - context.Response.StatusCode = Retorno - End Sub - - Private Sub GetImg(ByVal context As HttpContext) - Dim Url As String = Decripta(context.Request("r").ToString) - - Dim usuario As Usuario = UsuarioActual(context) - If Not IsNothing(usuario) Then - Url = String.Format("{0}Empresas\{1}\{2}", AppDomain.CurrentDomain.BaseDirectory, usuario.CveEmpresa, Url) - Dim FileInfo As FileInfo = New FileInfo(Url) - If FileInfo.Exists Then - context.Response.ContentType = "image/png" - context.Response.Flush() - context.Response.WriteFile(FileInfo.FullName) - context.Response.End() - End If - - End If + context.Response.StatusCode = Retorno End Sub -#Region "File" + Private Sub GetImg(ByVal context As HttpContext) + Dim Url As String = Decripta(context.Request("r").ToString) - Private Sub Downfile(ByVal context As HttpContext) - Dim savepath As String = "" - Dim tempPath As String = "" - tempPath = String.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings("FolderPath"), "/Temp") - savepath = context.Server.MapPath(tempPath) - Dim nombre As String = String.Format("{0}\{1}", savepath, context.Request("nombre")) - File.Delete(nombre) - context.Response.StatusCode = 200 - End Sub - - Private Sub uploadfile(ByVal context As HttpContext) - Dim postedFile As HttpPostedFile - Dim savepath As String = "" - Dim tempPath As String = "" - tempPath = String.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings("FolderPath"), "/Temp") - savepath = context.Server.MapPath(tempPath) - Dim filename As String - Dim tick As String - tick = (DateTime.Now.Ticks + 1).ToString() - If Not Directory.Exists(savepath) Then - Directory.CreateDirectory(savepath) - End If - If context.Request.Files.Count = 0 Then - Dim copyFile As String = context.Request("File") - Dim Cve As String = context.Request("Cve") - - If copyFile <> "" Then - Dim ext As Integer = copyFile.IndexOf(","c) + 1 - - Dim extncion As String = copyFile.Substring(5, ext - 5) - If extncion.Contains("image/") Then extncion = extncion.Replace("image/", "").Replace(";base64,", "") - 'Dim extncion As String = - filename = String.Format("{0}-{1}.{2}", tick, Cve, extncion) - - Dim msf As New MemoryStream(Convert.FromBase64String(copyFile.Substring(ext))) - Dim stem As Stream = New FileStream(String.Format("{0}\{1}", savepath, filename), FileMode.Create) - msf.WriteTo(stem) - msf.Close() - stem.Close() - - End If - Else - - postedFile = context.Request.Files(0) - filename = String.Format("{0}-{1}", tick, postedFile.FileName) - - postedFile.SaveAs((savepath & "\") + filename) - End If - context.Response.Write(tick) - context.Response.StatusCode = 200 + Dim usuario As Usuario = UsuarioActual(context) + If Not IsNothing(usuario) Then + Url = String.Format("{0}Empresas\{1}\{2}", AppDomain.CurrentDomain.BaseDirectory, usuario.CveEmpresa, Url) + Dim FileInfo As FileInfo = New FileInfo(Url) + If FileInfo.Exists Then + context.Response.ContentType = "image/png" + context.Response.Flush() + context.Response.WriteFile(FileInfo.FullName) + context.Response.End() + End If + + End If End Sub -#End Region -#Region "Get Cliente" - Private Function GetClientes(ByVal context As HttpContext) As String - Dim retorno As String = "" - Dim DtRetorno As DataTable = Nothing - - Dim usuario As Usuario = UsuarioActual(context) - Dim CveEmpresa As String - If IsNothing(usuario) Then - context.Response.Write("") - Else - CveEmpresa = usuario.CveEmpresa +#Region "File" + + Private Sub Downfile(ByVal context As HttpContext) + Dim savepath As String = "" + Dim tempPath As String = "" + tempPath = String.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings("FolderPath"), "/Temp") + savepath = context.Server.MapPath(tempPath) + Dim nombre As String = String.Format("{0}\{1}", savepath, context.Request("nombre")) + File.Delete(nombre) + context.Response.StatusCode = 200 + End Sub + + Private Sub uploadfile(ByVal context As HttpContext) + Dim postedFile As HttpPostedFile + Dim savepath As String = "" + Dim tempPath As String = "" + tempPath = String.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings("FolderPath"), "/Temp") + savepath = context.Server.MapPath(tempPath) + Dim filename As String + Dim tick As String + tick = (DateTime.Now.Ticks + 1).ToString() + If Not Directory.Exists(savepath) Then + Directory.CreateDirectory(savepath) + End If + If context.Request.Files.Count = 0 Then + Dim copyFile As String = context.Request("File") + Dim Cve As String = context.Request("Cve") + + If copyFile <> "" Then + Dim ext As Integer = copyFile.IndexOf(","c) + 1 + + Dim extncion As String = copyFile.Substring(5, ext - 5) + If extncion.Contains("image/") Then extncion = extncion.Replace("image/", "").Replace(";base64,", "") + 'Dim extncion As String = + filename = String.Format("{0}-{1}.{2}", tick, Cve, extncion) + + Dim msf As New MemoryStream(Convert.FromBase64String(copyFile.Substring(ext))) + Dim stem As Stream = New FileStream(String.Format("{0}\{1}", savepath, filename), FileMode.Create) + msf.WriteTo(stem) + msf.Close() + stem.Close() + + End If + Else + + postedFile = context.Request.Files(0) + filename = String.Format("{0}-{1}", tick, postedFile.FileName) + + postedFile.SaveAs((savepath & "\") + filename) + End If + context.Response.Write(tick) + context.Response.StatusCode = 200 + End Sub +#End Region + +#Region "Get Cliente" + Private Function GetClientes(ByVal context As HttpContext) As String + Dim retorno As String = "" + Dim DtRetorno As DataTable = Nothing + + Dim usuario As Usuario = UsuarioActual(context) + Dim CveEmpresa As String + If IsNothing(usuario) Then + context.Response.Write("") + Else + CveEmpresa = usuario.CveEmpresa Dim Name = IfNull(context.Request("Name"), "-1").ToString Dim AppNombre As String = String.Format("GlobalDTCliente{0}", CveEmpresa) - 'sino existe, recarga los datos + 'sino existe, recarga los datos If context.Application(AppNombre) Is Nothing Then Dim ObjClientes As New ClsClientes If ObjClientes.GetClientes(-1, "-1", "-1", "-1", "-1", "-1", "-1", -1, CveEmpresa, Estatus:=-1) Then @@ -214,24 +214,24 @@ Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState context.Response.Write("[]") End If - Return retorno + Return retorno End Function -#End Region +#End Region -#Region "Get Proveedor" - Private Function GetProveedores(ByVal context As HttpContext) As String - Dim retorno As String = "" - Dim DtRetorno As DataTable = Nothing - - Dim usuario As Usuario = UsuarioActual(context) - Dim CveEmpresa As String - If IsNothing(usuario) Then - context.Response.Write("") - Else - CveEmpresa = usuario.CveEmpresa +#Region "Get Proveedor" + Private Function GetProveedores(ByVal context As HttpContext) As String + Dim retorno As String = "" + Dim DtRetorno As DataTable = Nothing + + Dim usuario As Usuario = UsuarioActual(context) + Dim CveEmpresa As String + If IsNothing(usuario) Then + context.Response.Write("") + Else + CveEmpresa = usuario.CveEmpresa Dim Name = IfNull(context.Request("Name"), "-1").ToString Dim AppNombre As String = String.Format("GlobalDTCompProveedores{0}", CveEmpresa) - 'sino existe, recarga los datos + 'sino existe, recarga los datos If context.Application(AppNombre) Is Nothing Then Dim ObjProveedores As New ClsCompProveedores If ObjProveedores.GetProveedores(ClsCompProveedores.TipoConsulta.ParaGlobalDT, -1, "-1", "-1", "-1", "-1", "-1", "-1", "-1", -1, CveEmpresa) Then @@ -260,110 +260,114 @@ Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState context.Response.Write("[]") End If - Return retorno + Return retorno End Function -#End Region +#End Region -#Region " GET PS " - Private Function getpsalmacen(ByVal context As HttpContext) As String - - Dim usuario As Usuario = UsuarioActual(context) - Dim CveEmpresa As String - Dim retorno As String = "" - Dim DtPSRetorno As DataTable = Nothing - - If IsNothing(usuario) Then - context.Response.Write("") - Else - CveEmpresa = usuario.CveEmpresa - - DtPSRetorno = New DataTable - DtPSRetorno.Columns.Add(New DataColumn("id", System.Type.GetType("System.Int32"))) - DtPSRetorno.Columns.Add(New DataColumn("existencia", System.Type.GetType("System.Int32"))) - DtPSRetorno.Columns.Add(New DataColumn("almacen", System.Type.GetType("System.String"))) - - Dim CvePS = IfNull(context.Request("cveps"), "0").ToString.ToEntero - Dim objInv As New ClsInventarios - If objInv.GetExistenciasProducto(CvePS, -1, CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm")) Then - - ' limpio los almacenes donde no tiene ningun producto existencia - For i = objInv.DtResultados.Columns.Count - 1 To 1 Step -1 - - If Not objInv.DtResultados.Columns(i).ColumnName.Contiene("CveAlmacen", "Almacen", "Existencia") Then - objInv.DtResultados.Columns.RemoveAt(i) - End If - Next - - DtPSRetorno = objInv.DtResultados.FiltraParametros("CveAlmacen > 0 and Existencia > 0") - End If - - objInv.Dispose() - - End If - - If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then - DtPSRetorno.Columns("CveAlmacen").ColumnName = "id" - DtPSRetorno.Columns("Almacen").ColumnName = "almacen" - DtPSRetorno.Columns("Existencia").ColumnName = "existencia" - retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString - context.Response.Write(retorno) - Else - context.Response.Write("[]") - End If - - Return retorno - End Function - - Private Function GETPS(ByVal context As HttpContext, Optional PSCodigoDescripcion As String = "PSCodigo") As String - Dim retorno As String = "" - Dim DtPSRetorno As DataTable = Nothing - - 'NOTA: - ' EN EL WHERE DE LINQ NO SE DEBE USAS EL OPERADOR 'AND' SABE PORQUE FUNCIONA DIFERENTE SE DEBE USAR 'ANDALSO', - ' EJEMPLO UNA CONDICION AND DE DOS CAMPOS ARROJA CERO RESULTADOS PERO SI SE PONE ESTAS DOS CONDICIONES POR SEPARADO ARROJA DATOS - Dim usuario As Usuario = UsuarioActual(context) - Dim CveEmpresa As String - If IsNothing(usuario) Then - context.Response.Write("") - Else - CveEmpresa = usuario.CveEmpresa - Dim FuePorXml = IfNull(context.Request("FuePorXml"), "-1").ToString.ToEntero - Dim Name = IfNull(context.Request("Name"), "-1").ToString - Dim CveClasificacion = IfNull(context.Request("CveClasificacion"), "-1").ToString.ToEntero - Dim CveSubFamilia = IfNull(context.Request("CveSubFamilia"), "-1").ToString.ToEntero - Dim CveClasificacionPresupuesto = IfNull(context.Request("CveClasificacionPresupuesto"), "-1").ToString.ToEntero - Dim Pagina = IfNull(context.Request("Pagina"), "-1").ToString - Dim Estatus = IfNull(context.Request("Estatus"), "1").ToString - Dim CveSucursal = IfNull(context.Request("cvesucursal"), "-1").ToString.ToEntero - Dim CveSubProyecto = IfNull(context.Request("cvesubproyecto"), "-1").ToString.ToEntero - Dim UsoClasificacion = IfNull(context.Request("usoclasificacion"), "-1").ToString.ToEntero - Dim AplicaParaVenta = IfNull(context.Request("aplicaparaventa"), "-1").ToString.ToEntero - - Dim UsaGlobal As Boolean = True - - - 'verifica existencias - If Pagina.Contiene("ventas/ventas", "oc/oc", "inv/traspaso") AndAlso CveEmpresa.Contiene(72, 80, 119, 140, 141) Then - UsaGlobal = False - - Dim objInv As New ClsInventarios - If objInv.GetExistenciasProductosLike(Name, CveClasificacion, CveSubProyecto, Estatus.ToEntero, AplicaParaVenta, CveEmpresa) Then - - ' limpio los almacenes donde no tiene ningun producto existencia - For i = objInv.DtResultados.Columns.Count - 1 To 1 Step -1 +#Region " GET PS " + Private Function getpsalmacen(ByVal context As HttpContext) As String - If Not objInv.DtResultados.Columns(i).ColumnName.Contiene("CvePS", "PSCodigo", "PSCodigoClasificacion") AndAlso objInv.DtResultados.SUM(String.Format("[{0}]", objInv.DtResultados.Columns(i).ColumnName)) = 0 Then - objInv.DtResultados.Columns.RemoveAt(i) - End If - Next + Dim usuario As Usuario = UsuarioActual(context) + Dim CveEmpresa As String + Dim retorno As String = "" + Dim DtPSRetorno As DataTable = Nothing + + If IsNothing(usuario) Then + context.Response.Write("") + Else + CveEmpresa = usuario.CveEmpresa + + DtPSRetorno = New DataTable + DtPSRetorno.Columns.Add(New DataColumn("id", System.Type.GetType("System.Int32"))) + DtPSRetorno.Columns.Add(New DataColumn("existencia", System.Type.GetType("System.Int32"))) + DtPSRetorno.Columns.Add(New DataColumn("almacen", System.Type.GetType("System.String"))) + + Dim CvePS = IfNull(context.Request("cveps"), "0").ToString.ToEntero + Dim objInv As New ClsInventarios + If objInv.GetExistenciasProducto(CvePS, -1, CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm")) Then + + ' limpio los almacenes donde no tiene ningun producto existencia + For i = objInv.DtResultados.Columns.Count - 1 To 1 Step -1 + + If Not objInv.DtResultados.Columns(i).ColumnName.Contiene("CveAlmacen", "Almacen", "Existencia") Then + objInv.DtResultados.Columns.RemoveAt(i) + End If + Next + + DtPSRetorno = objInv.DtResultados.FiltraParametros("CveAlmacen > 0 and Existencia > 0") + End If + + objInv.Dispose() + + End If + + If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then + DtPSRetorno.Columns("CveAlmacen").ColumnName = "id" + DtPSRetorno.Columns("Almacen").ColumnName = "almacen" + DtPSRetorno.Columns("Existencia").ColumnName = "existencia" + retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString + context.Response.Write(retorno) + Else + context.Response.Write("[]") + End If + + Return retorno + End Function + + Private Function GETPS(ByVal context As HttpContext, Optional PSCodigoDescripcion As String = "PSCodigo") As String + Dim retorno As String = "" + Dim DtPSRetorno As DataTable = Nothing + + 'NOTA: + ' EN EL WHERE DE LINQ NO SE DEBE USAS EL OPERADOR 'AND' SABE PORQUE FUNCIONA DIFERENTE SE DEBE USAR 'ANDALSO', + ' EJEMPLO UNA CONDICION AND DE DOS CAMPOS ARROJA CERO RESULTADOS PERO SI SE PONE ESTAS DOS CONDICIONES POR SEPARADO ARROJA DATOS + Dim usuario As Usuario = UsuarioActual(context) + Dim CveEmpresa As String + If IsNothing(usuario) Then + context.Response.Write("") + Else + CveEmpresa = usuario.CveEmpresa + Dim FuePorXml = IfNull(context.Request("FuePorXml"), "-1").ToString.ToEntero + Dim Name = IfNull(context.Request("Name"), "-1").ToString + Dim CveClasificacion = IfNull(context.Request("CveClasificacion"), "-1").ToString.ToEntero + Dim CveSubFamilia = IfNull(context.Request("CveSubFamilia"), "-1").ToString.ToEntero + Dim CveClasificacionPresupuesto = IfNull(context.Request("CveClasificacionPresupuesto"), "-1").ToString.ToEntero + Dim Pagina = IfNull(context.Request("Pagina"), "-1").ToString + Dim Estatus = IfNull(context.Request("Estatus"), "1").ToString + Dim CveSucursal = IfNull(context.Request("cvesucursal"), "-1").ToString.ToEntero + Dim CveSubProyecto = IfNull(context.Request("cvesubproyecto"), "-1").ToString.ToEntero + Dim UsoClasificacion = IfNull(context.Request("usoclasificacion"), "-1").ToString.ToEntero + Dim AplicaParaVenta = IfNull(context.Request("aplicaparaventa"), "-1").ToString.ToEntero + + Dim UsaGlobal As Boolean = True + + + 'verifica existencias + If Pagina.Contiene("ventas/ventas", "oc/oc", "inv/traspaso") AndAlso CveEmpresa.Contiene(72, 80, 119, 140, 141) Then + UsaGlobal = False + + Dim objInv As New ClsInventarios + If objInv.GetExistenciasProductosLike(Name, CveClasificacion, CveSubProyecto, Estatus.ToEntero, AplicaParaVenta, CveEmpresa) Then + + ' limpio los almacenes donde no tiene ningun producto existencia + + Dim i As Integer = 0 + While i < objInv.DtResultados.Columns.Count + + If Not objInv.DtResultados.Columns(i).ColumnName.Contiene("CvePS", "PSCodigo", "PSCodigoClasificacion") AndAlso objInv.DtResultados.SUM(String.Format("[{0}]", objInv.DtResultados.Columns(i).ColumnName)) = 0 Then + objInv.DtResultados.Columns.RemoveAt(i) + Else + i = i + 1 + End If + End While DtPSRetorno = objInv.DtResultados - End If - - objInv.Dispose() - + End If + + objInv.Dispose() + End If If usuario.Empresa.Funcionalidad(558) = "1" Then @@ -373,15 +377,15 @@ Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState Catch ex As Exception End Try - End If - + End If + If UsaGlobal Then 'se recarga el global, y el clspaginas, son los unicos 2 lugares Dim AppNombre As String = String.Format("GlobalDTPSSimplificado{0}", CveEmpresa) If context.Application(String.Format("GlobalDTPSSimplificado{0}", CveEmpresa)) Is Nothing Then Dim ObjPS As New ClsProductosServicios If ObjPS.GetPSSimplificado(CveEmpresa) Then context.Application(AppNombre) = ObjPS.DtResultados.AsEnumerable() - ObjPS.Dispose() + ObjPS.Dispose() End If @@ -469,217 +473,217 @@ Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState End If End If - Return retorno + Return retorno End Function -#End Region +#End Region - Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable - Get - Return False - End Get + Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable + Get + Return False + End Get End Property -#Region "Funciones" - Public Function GetJson(ByVal dt As DataTable) As String - - Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer() - Dim rows As New List(Of Dictionary(Of String, Object)) - Dim row As Dictionary(Of String, Object) - - For Each dr As DataRow In dt.Rows - row = New Dictionary(Of String, Object) - For Each col As DataColumn In dt.Columns - row.Add(col.ColumnName, dr(col)) - Next - rows.Add(row) - Next - Return serializer.Serialize(rows) - End Function - ReadOnly Property UsuarioActual(ByVal context As HttpContext) As Usuario - Get - UsuarioActual = DirectCast(context.Session("UsuarioSIG"), Usuario) - End Get +#Region "Funciones" + Public Function GetJson(ByVal dt As DataTable) As String + + Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer() + Dim rows As New List(Of Dictionary(Of String, Object)) + Dim row As Dictionary(Of String, Object) + + For Each dr As DataRow In dt.Rows + row = New Dictionary(Of String, Object) + For Each col As DataColumn In dt.Columns + row.Add(col.ColumnName, dr(col)) + Next + rows.Add(row) + Next + Return serializer.Serialize(rows) + End Function + ReadOnly Property UsuarioActual(ByVal context As HttpContext) As Usuario + Get + UsuarioActual = DirectCast(context.Session("UsuarioSIG"), Usuario) + End Get End Property -#End Region +#End Region -#Region " GET PS SAT " - Private Function GETPSSAT(ByVal context As HttpContext) As String - Dim retorno As String = "" - - Dim DTPS = DirectCast(context.Application("GlobalDTPSATPS"), EnumerableRowCollection(Of DataRow)) - Dim DtPSRetorno As DataTable - - Dim Name = IfNull(context.Request("Name"), "-1").ToString - - If Name <> "-1" Then - DTPS = DTPS.Where((Function(a) a!SATClaveProductoServicio.ToString.ToLower Like ($"*{Name.ToLower}*"))) - End If - - DtPSRetorno = New DataView(DTPS.OrderBy(Function(a) a!SATClavePS).CopyToDataTable).ToTable(True, {"CveSATPS", "SATClaveProductoServicio"}) - - If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then - DtPSRetorno.Columns("CveSATPS").ColumnName = "id" - DtPSRetorno.Columns("SATClaveProductoServicio").ColumnName = "text" - retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString - context.Response.Write(retorno) - Else - context.Response.Write("[]") - End If - DtPSRetorno.Dispose() - Return retorno +#Region " GET PS SAT " + Private Function GETPSSAT(ByVal context As HttpContext) As String + Dim retorno As String = "" + + Dim DTPS = DirectCast(context.Application("GlobalDTPSATPS"), EnumerableRowCollection(Of DataRow)) + Dim DtPSRetorno As DataTable + + Dim Name = IfNull(context.Request("Name"), "-1").ToString + + If Name <> "-1" Then + DTPS = DTPS.Where((Function(a) a!SATClaveProductoServicio.ToString.ToLower Like ($"*{Name.ToLower}*"))) + End If + + DtPSRetorno = New DataView(DTPS.OrderBy(Function(a) a!SATClavePS).CopyToDataTable).ToTable(True, {"CveSATPS", "SATClaveProductoServicio"}) + + If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then + DtPSRetorno.Columns("CveSATPS").ColumnName = "id" + DtPSRetorno.Columns("SATClaveProductoServicio").ColumnName = "text" + retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString + context.Response.Write(retorno) + Else + context.Response.Write("[]") + End If + DtPSRetorno.Dispose() + Return retorno End Function -#End Region +#End Region -#Region " GET UM SAT " - Private Function GETUMSAT(ByVal context As HttpContext) As String - Dim retorno As String = "" - - Dim DTUM = DirectCast(context.Application("GlobalDTPSATUM"), EnumerableRowCollection(Of DataRow)) - Dim DtPSRetorno As DataTable - - Dim Name = IfNull(context.Request("Name"), "-1").ToString - - If Name <> "-1" Then - DTUM = DTUM.Where((Function(a) a!ClaveNombre.ToString.ToLower Like ("*" + Name.ToLower + "*"))) - End If - - DtPSRetorno = New DataView(DTUM.OrderBy(Function(a) a!Nombre).CopyToDataTable).ToTable(True, {"CveSATUnidadMedida", "ClaveNombre"}) - - If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then - DtPSRetorno.Columns("CveSATUnidadMedida").ColumnName = "id" - DtPSRetorno.Columns("ClaveNombre").ColumnName = "text" - retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString - context.Response.Write(retorno) - Else - context.Response.Write("[]") - End If - Return retorno +#Region " GET UM SAT " + Private Function GETUMSAT(ByVal context As HttpContext) As String + Dim retorno As String = "" + + Dim DTUM = DirectCast(context.Application("GlobalDTPSATUM"), EnumerableRowCollection(Of DataRow)) + Dim DtPSRetorno As DataTable + + Dim Name = IfNull(context.Request("Name"), "-1").ToString + + If Name <> "-1" Then + DTUM = DTUM.Where((Function(a) a!ClaveNombre.ToString.ToLower Like ("*" + Name.ToLower + "*"))) + End If + + DtPSRetorno = New DataView(DTUM.OrderBy(Function(a) a!Nombre).CopyToDataTable).ToTable(True, {"CveSATUnidadMedida", "ClaveNombre"}) + + If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then + DtPSRetorno.Columns("CveSATUnidadMedida").ColumnName = "id" + DtPSRetorno.Columns("ClaveNombre").ColumnName = "text" + retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString + context.Response.Write(retorno) + Else + context.Response.Write("[]") + End If + Return retorno End Function -#End Region +#End Region -#Region " GET FRACCION ARANCELARIA " - Private Function GetFraccionArancelaria(ByVal context As HttpContext) As String - Dim retorno As String = "" - - Dim DT = DirectCast(context.Application("GlobalDTFraccionArancelaria"), EnumerableRowCollection(Of DataRow)) - Dim DtRetorno As DataTable - - Dim Name = IfNull(context.Request("Name"), "-1").ToString - - If Name <> "-1" Then - DT = DT.Where((Function(a) a!ClaveSATFraccionArancelariaDescripcion.ToString.ToLower Like ($"*{Name.ToLower}*"))) - End If - - DtRetorno = New DataView(DT.OrderBy(Function(a) a!ClaveSATFraccionArancelaria).CopyToDataTable).ToTable(True, {"CveFraccionArancelaria", "ClaveSATFraccionArancelariaDescripcion"}) - - If DtRetorno IsNot Nothing AndAlso DtRetorno.Rows.Count > 0 Then - DtRetorno.Columns("CveFraccionArancelaria").ColumnName = "id" - DtRetorno.Columns("ClaveSATFraccionArancelariaDescripcion").ColumnName = "text" - retorno = JsonConvert.SerializeObject(DtRetorno).ToString - context.Response.Write(retorno) - Else - context.Response.Write("[]") - End If - DtRetorno.Dispose() - Return retorno +#Region " GET FRACCION ARANCELARIA " + Private Function GetFraccionArancelaria(ByVal context As HttpContext) As String + Dim retorno As String = "" + + Dim DT = DirectCast(context.Application("GlobalDTFraccionArancelaria"), EnumerableRowCollection(Of DataRow)) + Dim DtRetorno As DataTable + + Dim Name = IfNull(context.Request("Name"), "-1").ToString + + If Name <> "-1" Then + DT = DT.Where((Function(a) a!ClaveSATFraccionArancelariaDescripcion.ToString.ToLower Like ($"*{Name.ToLower}*"))) + End If + + DtRetorno = New DataView(DT.OrderBy(Function(a) a!ClaveSATFraccionArancelaria).CopyToDataTable).ToTable(True, {"CveFraccionArancelaria", "ClaveSATFraccionArancelariaDescripcion"}) + + If DtRetorno IsNot Nothing AndAlso DtRetorno.Rows.Count > 0 Then + DtRetorno.Columns("CveFraccionArancelaria").ColumnName = "id" + DtRetorno.Columns("ClaveSATFraccionArancelariaDescripcion").ColumnName = "text" + retorno = JsonConvert.SerializeObject(DtRetorno).ToString + context.Response.Write(retorno) + Else + context.Response.Write("[]") + End If + DtRetorno.Dispose() + Return retorno End Function -#End Region +#End Region -#Region "USADOS" +#Region "USADOS" - Private Function GETPSUSADOS(ByVal context As HttpContext) As String - Dim retorno As String = "" - Dim DtPSRetorno As DataTable = Nothing - - Dim usuario As Usuario = UsuarioActual(context) - Dim CveEmpresa As String - If IsNothing(usuario) Then - context.Response.Write("") - Else - CveEmpresa = usuario.CveEmpresa - Dim FuePorXml = IfNull(context.Request("FuePorXml"), "-1").ToString.ToEntero - Dim Name = IfNull(context.Request("Name"), "-1").ToString - Dim CveClasificacion = IfNull(context.Request("CveClasificacion"), "-1").ToString.ToEntero - Dim CveSubFamilia = IfNull(context.Request("CveSubFamilia"), "-1").ToString.ToEntero - Dim CveClasificacionPresupuesto = IfNull(context.Request("CveClasificacionPresupuesto"), "-1").ToString.ToEntero - Dim Pagina = IfNull(context.Request("Pagina"), "-1").ToString - Dim Estatus = IfNull(context.Request("Estatus"), "1").ToString - Dim CveSucursal = IfNull(context.Request("cvesucursal"), "-1").ToString.ToEntero - Dim CveSubProyecto = IfNull(context.Request("cvesubproyecto"), "-1").ToString.ToEntero - Dim UsoClasificacion = IfNull(context.Request("usoclasificacion"), "-1").ToString.ToEntero + Private Function GETPSUSADOS(ByVal context As HttpContext) As String + Dim retorno As String = "" + Dim DtPSRetorno As DataTable = Nothing + + Dim usuario As Usuario = UsuarioActual(context) + Dim CveEmpresa As String + If IsNothing(usuario) Then + context.Response.Write("") + Else + CveEmpresa = usuario.CveEmpresa + Dim FuePorXml = IfNull(context.Request("FuePorXml"), "-1").ToString.ToEntero + Dim Name = IfNull(context.Request("Name"), "-1").ToString + Dim CveClasificacion = IfNull(context.Request("CveClasificacion"), "-1").ToString.ToEntero + Dim CveSubFamilia = IfNull(context.Request("CveSubFamilia"), "-1").ToString.ToEntero + Dim CveClasificacionPresupuesto = IfNull(context.Request("CveClasificacionPresupuesto"), "-1").ToString.ToEntero + Dim Pagina = IfNull(context.Request("Pagina"), "-1").ToString + Dim Estatus = IfNull(context.Request("Estatus"), "1").ToString + Dim CveSucursal = IfNull(context.Request("cvesucursal"), "-1").ToString.ToEntero + Dim CveSubProyecto = IfNull(context.Request("cvesubproyecto"), "-1").ToString.ToEntero + Dim UsoClasificacion = IfNull(context.Request("usoclasificacion"), "-1").ToString.ToEntero Dim UsaGlobal As Boolean = True - If UsaGlobal Then - + If UsaGlobal Then + Dim DTPS = DirectCast(context.Application(String.Format("GlobalDTPSSimplificado{0}", CveEmpresa)), EnumerableRowCollection(Of DataRow)) - If DTPS IsNot Nothing Then - - 'APLICACION DE FILTROS - DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEmpresa) = CveEmpresa)) - If Estatus = 1 Then - DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEstado) = 1)) - ElseIf Estatus = -1 Then - - End If - - If Name <> "-1" Then - DTPS = DTPS.Where((Function(a) a!PSCodigo.ToString.ToLower Like ("*" + Name.ToLower + "*"))) - End If - - If CveClasificacion > 0 Then - DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) = CveClasificacion)) - ElseIf CveClasificacion = -1 Then - DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) >= 0)) - End If - - If CveClasificacionPresupuesto > 0 Then - DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacionPresupuesto) = CveClasificacionPresupuesto)) - End If - - If UsoClasificacion > 0 Then DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!UsoClasificacion) = UsoClasificacion)) - - If Pagina <> "-1" Then - If Pagina = "Compras" Then - DTPS = DTPS.Where((Function(a) a!CveTipoPS = 1 AndAlso a!CveEstado = 1)) - ElseIf Pagina = "Compras2" Then - DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 1 AndAlso (Convert.ToInt32(a!CveEstado) = 1 OrElse Convert.ToInt32(a!CveEstado) = 2))) - ElseIf Pagina = "Inventarios" Then - DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 2)) - End If - End If - - Try - DtPSRetorno = New DataView(DTPS.OrderBy(Function(a) a!PSCodigo).CopyToDataTable).ToTable(True, {"CvePS", "PSCodigo", "CveTamaño"}) - DtPSRetorno = DtPSRetorno.FiltraParametros("CveTamaño > 0") - Catch ex As Exception - DtPSRetorno = Nothing - End Try - End If - - End If - If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then - DtPSRetorno.Columns("CvePS").ColumnName = "id" - DtPSRetorno.Columns("PSCodigo").ColumnName = "text" - retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString - context.Response.Write(retorno) - Else - context.Response.Write("[]") - End If - End If - - Return retorno + If DTPS IsNot Nothing Then + + 'APLICACION DE FILTROS + DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEmpresa) = CveEmpresa)) + If Estatus = 1 Then + DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEstado) = 1)) + ElseIf Estatus = -1 Then + + End If + + If Name <> "-1" Then + DTPS = DTPS.Where((Function(a) a!PSCodigo.ToString.ToLower Like ("*" + Name.ToLower + "*"))) + End If + + If CveClasificacion > 0 Then + DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) = CveClasificacion)) + ElseIf CveClasificacion = -1 Then + DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) >= 0)) + End If + + If CveClasificacionPresupuesto > 0 Then + DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacionPresupuesto) = CveClasificacionPresupuesto)) + End If + + If UsoClasificacion > 0 Then DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!UsoClasificacion) = UsoClasificacion)) + + If Pagina <> "-1" Then + If Pagina = "Compras" Then + DTPS = DTPS.Where((Function(a) a!CveTipoPS = 1 AndAlso a!CveEstado = 1)) + ElseIf Pagina = "Compras2" Then + DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 1 AndAlso (Convert.ToInt32(a!CveEstado) = 1 OrElse Convert.ToInt32(a!CveEstado) = 2))) + ElseIf Pagina = "Inventarios" Then + DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 2)) + End If + End If + + Try + DtPSRetorno = New DataView(DTPS.OrderBy(Function(a) a!PSCodigo).CopyToDataTable).ToTable(True, {"CvePS", "PSCodigo", "CveTamaño"}) + DtPSRetorno = DtPSRetorno.FiltraParametros("CveTamaño > 0") + Catch ex As Exception + DtPSRetorno = Nothing + End Try + End If + + End If + If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then + DtPSRetorno.Columns("CvePS").ColumnName = "id" + DtPSRetorno.Columns("PSCodigo").ColumnName = "text" + retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString + context.Response.Write(retorno) + Else + context.Response.Write("[]") + End If + End If + + Return retorno End Function -#End Region +#End Region End Class \ No newline at end of file diff --git a/Compras/eFacturas.aspx b/Compras/eFacturas.aspx index 5f537d57a..dea3762d5 100644 --- a/Compras/eFacturas.aspx +++ b/Compras/eFacturas.aspx @@ -274,7 +274,7 @@
- +
diff --git a/Compras/eFacturas.aspx.vb b/Compras/eFacturas.aspx.vb index 6b8ec27dc..bf1189f9b 100644 --- a/Compras/eFacturas.aspx.vb +++ b/Compras/eFacturas.aspx.vb @@ -1,119 +1,119 @@ -Option Strict On -Option Explicit On - -Imports System.Data -Imports Extensiones -Imports System.Diagnostics -Imports System.IO -Imports System.IO.Compression -Imports System.Xml -Imports Microsoft.Reporting.WebForms -Imports System.Globalization -Imports ADSistemaLibrary.SatXml -Imports ADSistemaLibrary.SatXml.XmlSatCFDI - -Partial Class Compras_eFacturas - Inherits ClsPaginas - -#Region "Propiedades" - 'CFDi - Private _Folio As String - Private Property SeriePago As String - Set(value As String) - ViewState("SeriePago") = value - End Set - Get - Return ViewState("SeriePago").ToString - End Get - End Property - Private Property FolioPago As String - Set(value As String) - ViewState("FolioPago") = value - End Set - Get - Return ViewState("FolioPago").ToString - End Get - 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 CveFactura As Integer - Set(value As Integer) - ViewState("CveFactura") = value - End Set - Get - Return CInt(ViewState("CveFactura")) - End Get - End Property - Private Property CveFacturaPago As Integer - Set(value As Integer) - ViewState("CveFacturaPago") = value - End Set - Get - Return CInt(ViewState("CveFacturaPago")) - End Get - End Property - Private Property CveProveedor As Integer - Set(value As Integer) - ViewState("CveProveedor") = value - End Set - Get - Return CInt(ViewState("CveProveedor")) - End Get - End Property - Private Property Folio1 As String - Set(value As String) - ViewState("Folio1") = value - End Set - Get - Return (ViewState("Folio1")).ToString - End Get - End Property - Private Property Proveedor As String - Set(value As String) - ViewState("Proveedor") = value - End Set - Get - Return (ViewState("Proveedor")).ToString - End Get - End Property - - Private Property Ejecutable As String - Set(value As String) - ViewState("Ejecutable") = value - End Set - Get - Return ViewState("Ejecutable").ToString - End Get - End Property - - Private Property ChecandoCorreo As Boolean - Set(value As Boolean) - ViewState("ChecandoCorreo") = value - End Set - Get - Return CType(ViewState("ChecandoCorreo"), Boolean) - End Get - End Property - - Private DTConceptos As DataTable - Private Property Folio() As String - Get - Return _Folio - End Get - Set - _Folio = Value - End Set - End Property - +Option Strict On +Option Explicit On + +Imports System.Data +Imports Extensiones +Imports System.Diagnostics +Imports System.IO +Imports System.IO.Compression +Imports System.Xml +Imports Microsoft.Reporting.WebForms +Imports System.Globalization +Imports ADSistemaLibrary.SatXml +Imports ADSistemaLibrary.SatXml.XmlSatCFDI + +Partial Class Compras_eFacturas + Inherits ClsPaginas + +#Region "Propiedades" + 'CFDi + Private _Folio As String + Private Property SeriePago As String + Set(value As String) + ViewState("SeriePago") = value + End Set + Get + Return ViewState("SeriePago").ToString + End Get + End Property + Private Property FolioPago As String + Set(value As String) + ViewState("FolioPago") = value + End Set + Get + Return ViewState("FolioPago").ToString + End Get + 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 CveFactura As Integer + Set(value As Integer) + ViewState("CveFactura") = value + End Set + Get + Return CInt(ViewState("CveFactura")) + End Get + End Property + Private Property CveFacturaPago As Integer + Set(value As Integer) + ViewState("CveFacturaPago") = value + End Set + Get + Return CInt(ViewState("CveFacturaPago")) + End Get + End Property + Private Property CveProveedor As Integer + Set(value As Integer) + ViewState("CveProveedor") = value + End Set + Get + Return CInt(ViewState("CveProveedor")) + End Get + End Property + Private Property Folio1 As String + Set(value As String) + ViewState("Folio1") = value + End Set + Get + Return (ViewState("Folio1")).ToString + End Get + End Property + Private Property Proveedor As String + Set(value As String) + ViewState("Proveedor") = value + End Set + Get + Return (ViewState("Proveedor")).ToString + End Get + End Property + + Private Property Ejecutable As String + Set(value As String) + ViewState("Ejecutable") = value + End Set + Get + Return ViewState("Ejecutable").ToString + End Get + End Property + + Private Property ChecandoCorreo As Boolean + Set(value As Boolean) + ViewState("ChecandoCorreo") = value + End Set + Get + Return CType(ViewState("ChecandoCorreo"), Boolean) + End Get + End Property + + Private DTConceptos As DataTable + Private Property Folio() As String + Get + Return _Folio + End Get + Set + _Folio = Value + End Set + End Property + Private Property Serie() As String - Get + Get If m_Serie Is Nothing Then Return "" Else @@ -121,2430 +121,2430 @@ Partial Class Compras_eFacturas End If - End Get - Set - m_Serie = Value - End Set - End Property - Private m_Serie As String - - Private _fecha As String - Private Property fecha() As String - Get - Return _fecha - End Get - Set - _fecha = Value - End Set - End Property - - Private _tipoDeComprobante As String - Private Property tipoDeComprobante() As String - Get - Return _tipoDeComprobante - End Get - Set - _tipoDeComprobante = Value - End Set - End Property - - Private _formaDePago As String - Private Property formaDePago() As String - Get - Return _formaDePago - End Get - Set - _formaDePago = Value - End Set - End Property - - Private _subTotal As String - Private Property subTotal() As String - Get - Return _subTotal - End Get - Set - _subTotal = Value - End Set - End Property - - Private _descuento As String - Private Property descuento() As String - Get - Return _descuento - End Get - Set - _descuento = Value - End Set - End Property - Private _total As String - Private Property total() As String - Get - Return _total - End Get - Set - _total = Value - End Set - End Property - - Private _moneda As String - Private Property moneda() As String - Get - Return _moneda - End Get - Set - _moneda = Value - End Set - End Property - - Private _metodoDePago As String - Private Property metodoDePago() As String - Get - Return _metodoDePago - End Get - Set - _metodoDePago = Value - End Set - End Property - - Private _condicionesDePago As String - Private Property condicionesDePago() As String - Get - Return _condicionesDePago - End Get - Set - _condicionesDePago = Value - End Set - End Property - - Private _LugarExpedicion As String - Private Property LugarExpedicion() As String - Get - Return _LugarExpedicion - End Get - Set - _LugarExpedicion = Value - End Set - End Property - - Private _NumCtaPagoNumCtaPago As String - Private Property NumCtaPagoNumCtaPago() As String - Get - Return _NumCtaPagoNumCtaPago - End Get - Set - _NumCtaPagoNumCtaPago = Value - End Set - End Property - - Private _noCertificado As String - Private Property noCertificado() As String - Get - Return _noCertificado - End Get - Set - _noCertificado = Value - End Set - End Property - - ''Emisor - Private _EmiRFC As String - Private Property EmiRFC() As String - Get - Return _EmiRFC - End Get - Set - _EmiRFC = Value - End Set - End Property - - Private _EmiNombre As String - Private Property EmiNombre() As String - Get - Return _EmiNombre - End Get - Set - _EmiNombre = Value - End Set - End Property - - Private _DomFisCalle As String - Private Property DomFisCalle() As String - Get - Return _DomFisCalle - End Get - Set - _DomFisCalle = Value - End Set - End Property - - Private _DomFisNoExt As String - Private Property DomFisNoExt() As String - Get - Return _DomFisNoExt - End Get - Set - _DomFisNoExt = Value - End Set - End Property - 'Dim _DomFisNoInt As String - - Private _DomFisCol As String - Private Property DomFisCol() As String - Get - Return _DomFisCol - End Get - Set - _DomFisCol = Value - End Set - End Property - - Private _DomFisCP As String - Private Property DomFisCP() As String - Get - Return _DomFisCP - End Get - Set - _DomFisCP = Value - End Set - End Property - - Private _DomFisMun As String - Private Property DomFisMun() As String - Get - Return _DomFisMun - End Get - Set - _DomFisMun = Value - End Set - End Property - - Private _DomFisLoc As String - Private Property DomFisLoc() As String - Get - Return _DomFisLoc - End Get - Set - _DomFisLoc = Value - End Set - End Property - - Private _DomFisEst As String - Private Property DomFisEst() As String - Get - Return _DomFisEst - End Get - Set - _DomFisEst = Value - End Set - End Property - - Private _DomFisPais As String - Private Property DomFisPais() As String - Get - Return _DomFisPais - End Get - Set - _DomFisPais = Value - End Set - End Property - - Private _ExpEnCalle As String - Private Property ExpEnCalle() As String - Get - Return _ExpEnCalle - End Get - Set - _ExpEnCalle = Value - End Set - End Property - - Private _ExpEnNoExt As String - Private Property ExpEnNoExt() As String - Get - Return _ExpEnNoExt - End Get - Set - _ExpEnNoExt = Value - End Set - End Property - - - Private ExpEnCol As String - - Private _ExpEnCP As String - Private Property ExpEnCP() As String - Get - Return _ExpEnCP - End Get - Set - _ExpEnCP = Value - End Set - End Property - - Private _ExpEnMun As String - Private Property ExpEnMun() As String - Get - Return _ExpEnMun - End Get - Set - _ExpEnMun = Value - End Set - End Property - - Private _ExpEnLoc As String - Private Property ExpEnLoc() As String - Get - Return _ExpEnLoc - End Get - Set - _ExpEnLoc = Value - End Set - End Property - - Private _ExpEnEst As String - Private Property ExpEnEst() As String - Get - Return _ExpEnEst - End Get - Set - _ExpEnEst = Value - End Set - End Property - Private _ExpEnPais As String - Private Property ExpEnPais() As String - Get - Return _ExpEnPais - End Get - Set - _ExpEnPais = Value - End Set - End Property - - Private _Regimen As String - Private Property Regimen() As String - Get - Return _Regimen - End Get - Set - _Regimen = Value - End Set - End Property - - ''Receptor - Private _RecRfc As String - Private Property RecRfc() As String - Get - Return _RecRfc - End Get - Set - _RecRfc = Value - End Set - End Property - - Private _RecNombre As String - Private Property RecNombre() As String - Get - Return _RecNombre - End Get - Set - _RecNombre = Value - End Set - End Property - - Private _DomRecCalle As String - Private Property DomRecCalle() As String - Get - Return _DomRecCalle - End Get - Set - _DomRecCalle = Value - End Set - End Property - - Private _DomRecFisNoExt As String - Private Property DomRecFisNoExt() As String - Get - Return _DomRecFisNoExt - End Get - Set - _DomRecFisNoExt = Value - End Set - End Property - - Private _DomRecFisNoInt As String - Private Property DomRecFisNoInt() As String - Get - Return _DomRecFisNoInt - End Get - Set - _DomRecFisNoInt = Value - End Set - End Property - - Private _DomRecCol As String - Private Property DomRecCol() As String - Get - Return _DomRecCol - End Get - Set - _DomRecCol = Value - End Set - End Property - - Private _DomRecCP As String - Private Property DomRecCP() As String - Get - Return _DomRecCP - End Get - Set - _DomRecCP = Value - End Set - End Property - - Private _DomRecMun As String - Private Property DomRecMun() As String - Get - Return _DomRecMun - End Get - Set - _DomRecMun = Value - End Set - End Property - - Private _DomRecLoc As String - Private Property DomRecLoc() As String - Get - Return _DomRecLoc - End Get - Set - _DomRecLoc = Value - End Set - End Property - - Private _DomRecEst As String - Private Property DomRecEst() As String - Get - Return _DomRecEst - End Get - Set - _DomRecEst = Value - End Set - End Property - - Private _DomRecPais As String - Private Property DomRecPais() As String - Get - Return _DomRecPais - End Get - Set - _DomRecPais = Value - End Set - End Property - - 'IVA - Private _TrasladoIVA As Double - Private Property TrasladoIVA() As Double - Get - Return _TrasladoIVA - End Get - Set - _TrasladoIVA = Value - End Set - End Property - - 'TFD - Private _TFDUUID As String - Private Property TFDUUID() As String - Get - Return _TFDUUID - End Get - Set - _TFDUUID = Value - End Set - End Property - - Private _TFDFechaTimbrado As String - Private Property TFDFechaTimbrado() As String - Get - Return _TFDFechaTimbrado - End Get - Set - _TFDFechaTimbrado = Value - End Set - End Property - - Private _TFDSelloCFD As String - Private Property TFDSelloCFD() As String - Get - Return _TFDSelloCFD - End Get - Set - _TFDSelloCFD = Value - End Set - End Property - - Private _TFDNoCertSAT As String - Private Property TFDNoCertSAT() As String - Get - Return _TFDNoCertSAT - End Get - Set - _TFDNoCertSAT = Value - End Set - End Property - - Private _TFDSelloSAT As String - Private Property TFDSelloSAT() As String - Get - Return _TFDSelloSAT - End Get - Set - _TFDSelloSAT = Value - End Set - End Property - -#End Region - - Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load - If Not Page.IsPostBack Then - ChecandoCorreo = False - GvD.Columns(GvD.Columns.Count - 1).Visible = (UsuarioActual.CveRol = 1) - 'GvD.Columns(GvD.Columns.Count - 2).Visible = (UsuarioActual.CveRol = 1) - 'GvD.Columns(GvD.Columns.Count - 3).Visible = (UsuarioActual.CveRol = 1) - ViewState("Orden") = String.Empty - - txtFechaI.Text = Now.AddMonths(-1).FirstDayOfMonth().ToShortDateString ' String.Format("01/01/{0}", If(Now.Month > 6, Now.Year, Now.Year - 1)) - - txtFechaF.Text = Now.ToShortDateString 'txtFechaI.Text.ToDate.AddMonths(1).AddDays(-1).ToShortDateString - - Destino = String.Format("{0}Compras\", UsuarioActual.Empresa.Ruta) 'string.format("{0}Empresas\{1}\Compras\", AppDomain.CurrentDomain.BaseDirectory ,UsuarioActual.CveEmpresa & "\Compras\" - Ejecutable = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilerias\ADSUtilerias.exe") - Form.DefaultButton = BtnConsultar.UniqueID - - DdlResponsable.DataSource = GlobalDTUsuarioResponsable.FiltraParametros(String.Format("CveEmpresa = {0}", UsuarioActual.CveEmpresa)) - DdlResponsable.DataBind() - DdlResponsable.Items.Insert(0, New ListItem("Todos", "-1")) - - DdlClasificacionProv.DataSource = GlobalDTProveedorClasificacion(UsuarioActual.CveEmpresa) - DdlClasificacionProv.DataBind() - DdlClasificacionProv.Items.Insert(0, New ListItem("Todos", "-1")) - - TxtFechaBitInicio.Text = Now.ToString("dd/MM/yyyy") - TxtFechaBitFin.Text = Now.ToString("dd/MM/yyyy") - - TxtFolio.Focus() - - If UsuarioActual.Sesion("eFact-Proveedor").ToString <> "" Then TxtProveedor.Text = UsuarioActual.Sesion("eFact-Proveedor").ToString.Trim - If UsuarioActual.Sesion("eFact-FI").ToString <> "" Then txtFechaI.Text = UsuarioActual.Sesion("eFact-FI").ToString.Trim - If UsuarioActual.Sesion("eFact-FF").ToString <> "" Then txtFechaF.Text = UsuarioActual.Sesion("eFact-FF").ToString.Trim - If UsuarioActual.CveUsuario = 100 Then lbDescargar.Visible = True - - If UsuarioActual.TienePermisoProceso(81) Then GvD.Columns(11).Visible = True : GvD.Columns(12).Visible = True - If UsuarioActual.TienePermisoProceso(206) Then GvD.Columns(10).Visible = False - If UsuarioActual.Empresa.Funcionalidad(156) = "1" Then GvD.Columns(5).Visible = True - CargaGvBitacora() - CargaDatos() - End If - removeasincevent() - End Sub - 'Private Sub CompararString() - ' Dim cont As Integer = 10000 - ' Dim Sb As New StringBuilder - ' For i = 0 To cont - ' Sb.AppendFormat("a{0}", i) - ' Next - 'End Sub - - Protected Sub BtnConsultar_Click(sender As Object, e As System.EventArgs) Handles BtnConsultar.Click - CargaDatos() - End Sub - - Private Sub CargaDatos() - Dim Folio, RFC, Proveedor As String - Folio = If(TxtFolio.Text.Trim.Length > 0, String.Format("%{0}%", TxtFolio.Text.Trim.ToUpper), "-1") - RFC = "-1" 'If(TxtRFC.Text.Trim.Length > 0, TxtRFC.Text.Trim, "-1") - Proveedor = If(TxtProveedor.Text.Trim.Length > 0, String.Format("%{0}%", TxtProveedor.Text.Trim.ToUpper.Replace(" ", "%")), "-1") - - UsuarioActual.Sesion("eFact-Proveedor") = TxtProveedor.Text.Trim - If Folio = "" Then UsuarioActual.Sesion("eFact-FI") = txtFechaI.Text - If Folio = "" Then UsuarioActual.Sesion("eFact-FF") = txtFechaF.Text - Dim FechaI, FechaF As Date - FechaI = txtFechaI.Text.ToDate - FechaF = txtFechaF.Text.ToDate - If Folio <> "-1" Then - FechaI = MinFecha - FechaF = MaxFecha - txtFechaI.Text = MinFecha.ToString - txtFechaF.Text = Now.ToShortDateString - End If - Dim DtPagos As DataTable = Nothing - Dim ObjDatos As New ClsCompras - If ObjDatos.GetFacturas(-1, Folio, FechaI, FechaF, RFC, Proveedor, DdlValidado.SelectedValue.ToEntero, DdlResponsable.SelectedValue.ToEntero, DdlClasificacionProv.SelectedValue.ToEntero, DdlCveTipoProveedor.SelectedValue.ToEntero, DdlTipoComprobante.SelectedValue.ToString, UsuarioActual.CveEmpresa) Then - If ObjDatos.DtResultados.Rows.Count > 0 Then - GvD.DataSource = ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P'") '.AsEnumerable().Take(100).CopyToDataTable() - DtPagos = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P'") - Else - GvD.DataSource = Nothing - End If - End If - LblRegistros.Text = String.Format("{0} Registros", ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P'").Rows.Count.ToString("N0")) - LblTotalPagos.Text = String.Format("{0} Pagos", ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P'").Rows.Count.ToString("N0")) - ObjDatos.Dispose() - - If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then - GvPagos.DataSource = DtPagos - End If - GvPagos.DataBind() - UpPagos.Update() - - GvD.DataBind() - - UpDatos.Update() - UPRegistros.Update() - End Sub - - Protected Sub LnkExportar_Click(sender As Object, e As EventArgs) Handles LnkExportar.Click - GenerarPDF("Excel") - End Sub - - Protected Sub ImgRefresh_Click(sender As Object, e As EventArgs) Handles ImgRefresh.Click - - If VerificaCorreo() Then - CargaDatos() - End If - - End Sub - - Private Function VerificaCorreo(Optional ValidaRowCount As Boolean = False) As Boolean - Dim Retorno As Boolean = False - - Dim ObjProcess As Process = Nothing - Dim Mensajes As String = "" - Dim error1 As Boolean = False - Dim CountProcesados As Integer = 0 - - Try - ObjProcess = New Process() - ObjProcess.StartInfo.RedirectStandardOutput = True - ObjProcess.StartInfo.FileName = Ejecutable - ObjProcess.StartInfo.Arguments = $"--mod eFacturas --e {UsuarioActual.CveEmpresa} --c " - ObjProcess.StartInfo.UseShellExecute = False - ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal - ObjProcess.Start() - - - Dim myStreamReader As StreamReader = ObjProcess.StandardOutput - - 'Read the standard output of the spawned process. - Mensajes = myStreamReader.ReadLine() - If Mensajes.Length > 0 Then - - Dim msgs As String() = Mensajes.Split("|"c) - Dim NFacturas As Integer = 0 - - - - - If msgs.Length >= 2 Then - Try - NFacturas = msgs(0).ToEntero - CountProcesados = msgs(0).ToEntero - Mensajes = $"La actualización se realizó correctamente.
Facturas agregadas: { NFacturas }" - Catch ex As Exception - NFacturas = 0 - Mensajes = "La actualización se realizó correctamente" - End Try - Else - Mensajes = "La actualización se realizó correctamente" - End If - - - - LnkNoRecibidas_Click(LnkNoRecibias, EventArgs.Empty, ValidaRowCount:=ValidaRowCount) - - - 'Else - ' Dim Str As New StringBuilder - ' Dim conta As Integer = 1 - ' Str.Append("Se encontraron las siguientes facturas con problema:
") - ' Dim ARR As String() = Mensajes.Split("&"c) - ' Dim ArrDetalle As String() - ' For Each d As String In ARR - ' Str.Append("") - ' ArrDetalle = d.Split("|"c) - ' For Each det As String In ArrDetalle - ' Str.AppendFormat("", If(conta Mod 2 = 0, "TextoAlterno", "Texto"), det) - ' Next - ' Str.Append("") - ' conta += 1 - ' Next - ' Str.Append("
SerieFolioFechaProveedorImporteMotivo
{1}
") - ' Mensajes = Str.ToString - End If - ObjProcess.WaitForExit() - ObjProcess.Close() - Retorno = True - Catch ex As Exception - error1 = True - OnError("Ocurrió un error al ejecutar el actualizador.", ex) - End Try - - - LblFacturasProcesadasCount.Text = "Procesados:" & CountProcesados - RegistraScript("$('#ModalBitacoraEfacturas').modal()") - CargaDatosBitacora() - - 'If Not error1 Then Alert(Mensajes, TipoMensaje.MsgInformacion) - - - Return Retorno - End Function - - Protected Sub BtnBuscarBitacora_Click(sender As Object, e As EventArgs) Handles BtnBuscarBitacora.Click - CargaDatosBitacora() - End Sub - - - Protected Sub LnkBitacotaFacturas_Click(sender As Object, e As EventArgs) - - RegistraScript("$('#ModalBitacoraEfacturas').modal()") - CargaDatosBitacora() - End Sub - - - Private Sub CargaDatosBitacora() - - LblFacturasProcesadasCount.Text = "" - - Dim ObjCompras As New ClsCompras - - If ObjCompras.GetFacturasBitacoraGet(TxtFechaBitInicio.Text.ToDate, TxtFechaBitFin.Text.ToDate, UsuarioActual.CveEmpresa) Then - GvBitacoraEfacturas.DataSource = ObjCompras.DtResultados - Else - GvBitacoraEfacturas.DataSource = Nothing - End If - - ObjCompras.Dispose() - GvBitacoraEfacturas.DataBind() - UpModalBitacoraEfacturas.Update() - - End Sub - -#Region "G V D A T O S" - Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvD.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow Then - e.Row.FindControl("lnkRegenerarPDF").Visible = (UsuarioActual.CveRol = 1) - 'e.Row.FindControl("lnkDownPdf").Visible = (UsuarioActual.CveRol = 1) - 'e.Row.FindControl("lnkXML").Visible = (UsuarioActual.CveRol = 1) - Select Case e.Row.DBCampo("TipoComprobante") - Case "I" - e.Row.FCLabel("LtTipoComprobante").Text = "Ingreso" - e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-success" - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Ingreso") - Case "E" - e.Row.FCLabel("LtTipoComprobante").Text = "Egreso" - e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-warning" - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Egreso") - Case "P" - e.Row.FCLabel("LtTipoComprobante").Text = "Pago" - e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-primary" - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Complemento Pago") - End Select - - e.Row.Cells(2).Attributes.Add("data-order", e.Row.DBCampo("FechaFactura").ToDate.Ticks.ToString) - - If File.Exists(String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))) Then - e.Row.FCLiteral("LtlXML").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("XML"))) - If e.Row.DBCampo("TipoComprobante") = "P" Then - e.Row.FCLinkButton("LnkAgregarPago").Visible = True - End If - Else - e.Row.FCLiteral("LtlXML").Text = "N/D" - If e.Row.DBCampo("TipoComprobante") = "P" Then - e.Row.FCLinkButton("LnkAgregarPago").Visible = False - End If - End If - - If File.Exists(String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))) Then - e.Row.FCLiteral("LtlPDF").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("PDF"))) - Else - e.Row.FCLiteral("LtlPDF").Text = "N/D" - End If - - If e.Row.DBCampo("FueValidado").Contiene("1", "2", "3") Then - e.Row.FCLinkButton("ImgValidarCFDi").Visible = False - e.Row.FCLiteral("LtlValidado").Visible = True - If e.Row.DBCampo("FueValidado") = "2" Then - e.Row.FCLiteral("LtlValidado").Text = "Cancelada" - e.Row.ForeColor = Drawing.Color.Red - e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Red - ElseIf e.Row.DBCampo("FueValidado") = "3" Then - e.Row.FCLiteral("LtlValidado").Text = "Omitida" - e.Row.ForeColor = Drawing.Color.Gray - e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Gray - End If - Else - If e.Row.DBCampo("TipoFactura") = "CFD" Then - e.Row.FCLinkButton("ImgValidarCFDi").CommandName = "ValidarCFD" - e.Row.FCLinkButton("ImgValidarCFDi").OnClientClick = "return confirm('La factura se validó en el sitio del SAT de comprobantes fiscales?');" - End If - e.Row.FCLinkButton("ImgValidarCFDi").Visible = True - e.Row.FCLiteral("LtlValidado").Visible = False - - End If - If e.Row.DBCampo("CveCompra") <> "" Then - e.Row.FCLiteral("LtlFolio").Text = String.Format("{1}", e.Row.DBCampo("CveCompra"), e.Row.DBCampo("SerieFolio")) '1\Compras\GAPC480413QL3\A-69.xml - End If - - If e.Row.DBCampo("CveProveedor") = "" Then - e.Row.FCHyperLink("HplProv").Visible = True - e.Row.FCHyperLink("HplProv").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveFactura={0}", e.Row.DBCampo("CveFactura")) - - Else - - Dim BloquePorComplemento As Integer = e.Row.DataKey("BloquePorComplemento").ToEntero - - e.Row.FCHyperLink("HplProveedor").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", e.Row.DBCampo("CveProveedor")) - - If e.Row.DBCampo("CveCompra") = "" AndAlso (e.Row.DBCampo("FueValidado") = "1") Then ' OrElse UsuarioActual.CveEmpresa = 66 - - If e.Row.DBCampo("TipoComprobante") = "P" Then - e.Row.FCHyperLink("HplAgregar").Visible = False - Else - e.Row.FCHyperLink("HplAgregar").NavigateUrl = String.Format("/Compras/Compras.aspx?CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCDe")) - - If BloquePorComplemento > 0 Then - e.Row.FCHyperLink("HplAgregar").Enabled = False - e.Row.FCHyperLink("HplAgregar").Attributes.Add("title", "Bloqueo por complemento") - End If - - End If - - Else - e.Row.FCHyperLink("HplAgregar").Visible = False - End If - - - - End If - - - If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then - End If - - End If - End Sub - Protected Sub GvDatos_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvD.RowUpdating - Dim ObjDatos As New ClsCompras - Dim FueValidado As Integer = 0 - If GvD.Rows(e.RowIndex).FCCheckBox("ChkFueValidado").Checked Then FueValidado = 1 - If ObjDatos.UpdateEstatus(FueValidado, GvD.DataKeys(e.RowIndex).Value.ToString.ToEntero) Then - GvD.EditIndex = -1 - BtnConsultar_Click(sender, e) - End If - ObjDatos.Dispose() - - - CargaDatos() - End Sub - Protected Sub GvDatos_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvD.RowCancelingEdit - GvD.EditIndex = -1 - CargaDatos() - End Sub - - - Protected Sub imgD_Click(sender As Object, e As EventArgs) - Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) - CveFactura = gvRow.DataKey("CveFactura").ToString.ToEntero - Folio1 = gvRow.DataKey("SerieFolio").ToString - Proveedor = gvRow.DataKey("NombreProveedor").ToString - TxtDescripcion.Text = "" - RegistraScript("$('#divDescripcion').modal()") - UpDescripcion.Update() - End Sub - - Protected Sub GvDatos_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvD.RowEditing - GvD.EditIndex = e.NewEditIndex - CargaDatos() - End Sub - - Protected Sub GvDatos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvD.RowCommand - Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton) - Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow) - Dim ObjDatos As New ClsCompras - Dim Correcto As Boolean = False - - Select Case e.CommandName - Case "ValidarCFDi" - Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), GvRow.DataKey("Total").ToDecimal) - If ObjValidacion.EsValida > 0 Then - If ObjValidacion.EsValida = 2 Then - Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgInformacion) - End If - Correcto = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) - Else - Alert("La Factura no se pudo validar.", TipoMensaje.MsgAdvertencia) - End If - ObjValidacion.Dispose() - Case "ValidarCFD" - Correcto = ObjDatos.UpdateEstatus(1, GvRow.DataKey("CveFactura").ToEntero) - - Case "Omitir" - Correcto = ObjDatos.UpdateEstatus(3, GvRow.DataKey("CveFactura").ToEntero) - End Select - - ObjDatos.Dispose() - If Correcto Then - CargaDatos() - End If - - End Sub -#End Region - -#Region "G V P A G O S" - Protected Sub GvPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvPagos.RowDataBound - If e.Row.RowType = DataControlRowType.DataRow Then - - If e.Row.DBCampo("TipoComprobante") = "P" Then - e.Row.FCLabel("LtTipoComprobante").Text = "Pago" - e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-primary" - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") - e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Complemento Pago") - End If - - e.Row.Cells(2).Attributes.Add("data-order", e.Row.DBCampo("FechaFactura").ToDate.Ticks.ToString) - - If File.Exists(String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))) Then - e.Row.FCLiteral("LtlXML").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("XML"))) - If e.Row.DBCampo("TipoComprobante") = "P" And e.Row.DBCampo("FueValidado") = "1" Then - e.Row.FCLinkButton("LnkAgregarPagoP").Visible = True - End If - Else - e.Row.FCLiteral("LtlXML").Text = "N/D" ' String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML")) ' - If e.Row.DBCampo("TipoComprobante") = "P" Then - e.Row.FCLinkButton("LnkAgregarPagoP").Visible = False - End If - End If - - If File.Exists(String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))) Then - e.Row.FCLiteral("LtlPDF").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("PDF"))) - Else - e.Row.FCLiteral("LtlPDF").Text = "N/D" ' String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF")) - End If - - If e.Row.DBCampo("FueValidado").Contiene("1", "2", "3") Then - e.Row.FCLinkButton("ImgValidarCFDi").Visible = False - e.Row.FCLiteral("LtlValidado").Visible = True - If e.Row.DBCampo("FueValidado") = "2" Then - e.Row.FCLiteral("LtlValidado").Text = "Cancelada" - e.Row.ForeColor = Drawing.Color.Red - e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Red - ElseIf e.Row.DBCampo("FueValidado") = "3" Then - e.Row.FCLiteral("LtlValidado").Text = "Omitida" - e.Row.ForeColor = Drawing.Color.Gray - e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Gray - End If - Else - If e.Row.DBCampo("TipoFactura") = "CFD" Then - e.Row.FCLinkButton("ImgValidarCFDi").CommandName = "ValidarCFD" - e.Row.FCLinkButton("ImgValidarCFDi").OnClientClick = "return confirm('La factura se validó en el sitio del SAT de comprobantes fiscales?');" - End If - e.Row.FCLinkButton("ImgValidarCFDi").Visible = True - e.Row.FCLiteral("LtlValidado").Visible = False - - End If - If e.Row.DBCampo("CveCompra") <> "" Then - e.Row.FCLiteral("LtlFolio").Text = String.Format("{1}", e.Row.DBCampo("CveCompra"), e.Row.DBCampo("SerieFolio")) '1\Compras\GAPC480413QL3\A-69.xml - End If - - If e.Row.DBCampo("CveProveedor") = "" Then - e.Row.FCHyperLink("HplProv").Visible = True - e.Row.FCHyperLink("HplProv").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveFactura={0}", e.Row.DBCampo("CveFactura")) - - Else - e.Row.FCHyperLink("HplProveedor").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", e.Row.DBCampo("CveProveedor")) - - If e.Row.DBCampo("CveCompra") = "" AndAlso (e.Row.DBCampo("FueValidado") = "1") Then ' OrElse UsuarioActual.CveEmpresa = 66 - ' - If e.Row.DBCampo("TipoComprobante") = "P" Then - e.Row.FCHyperLink("HplAgregarP").Visible = False - Else - e.Row.FCHyperLink("HplAgregarP").NavigateUrl = String.Format("/Compras/Compras.aspx?CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCDe")) - End If - - - Else - 'si ya tiene cvecompra es que ya está validada - e.Row.FCHyperLink("HplAgregarP").Visible = False - End If - - End If - - - Dim CveComplementoPagoCompra As Integer = e.Row.DataKey("CveComplementoPagoCompra").ToString.ToEntero - - - If CveComplementoPagoCompra > 0 Then - e.Row.FCLinkButton("LnkAgregarPagoP").CssClass = "btn btn-sm green" - e.Row.FCLinkButton("LnkAgregarPagoP").Text = "" - 'e.Row.FCLinkButton("LnkAgregarPagoP").ToolTip = "Ver vinculación" - e.Row.FCLinkButton("LnkAgregarPagoP").Attributes.Add("Title", "Ver vinculación") - Else - e.Row.FCLinkButton("LnkAgregarPagoP").CssClass = "btn btn-sm blue" - e.Row.FCLinkButton("LnkAgregarPagoP").Text = "" - 'e.Row.FCLinkButton("LnkAgregarPagoP").ToolTip = "Vincular Pago" - e.Row.FCLinkButton("LnkAgregarPagoP").Attributes.Add("Title", "Vincular Pago") - End If - - End If - End Sub - Protected Sub GvPagos_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvPagos.RowUpdating - Dim ObjDatos As New ClsCompras - Dim FueValidado As Integer = 0 - If GvPagos.Rows(e.RowIndex).FCCheckBox("ChkFueValidado").Checked Then FueValidado = 1 - If ObjDatos.UpdateEstatus(FueValidado, GvD.DataKeys(e.RowIndex).Value.ToString.ToEntero) Then - GvPagos.EditIndex = -1 - End If - ObjDatos.Dispose() - CargaDatos() - End Sub - Protected Sub GvPagos_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvPagos.RowCancelingEdit - GvPagos.EditIndex = -1 - CargaDatos() - End Sub - Protected Sub GvPagos_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvPagos.RowEditing - GvPagos.EditIndex = e.NewEditIndex - CargaDatos() - End Sub - Protected Sub imgDP_Click(sender As Object, e As EventArgs) - Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) - CveFactura = gvRow.DataKey("CveFactura").ToString.ToEntero - Folio1 = gvRow.DataKey("SerieFolio").ToString - Proveedor = gvRow.DataKey("NombreProveedor").ToString - TxtDescripcion.Text = "" - RegistraScript("$('#divDescripcionPago').modal()") - UpDescripcionPago.Update() - End Sub - - Protected Sub GvPagos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPagos.RowCommand - Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton) - Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow) - Dim ObjDatos As New ClsCompras - Dim Correcto As Boolean = False - - Select Case e.CommandName - Case "ValidarCFDi" - Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), 0) - If ObjValidacion.EsValida > 0 Then - If ObjValidacion.EsValida = 2 Then - Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgInformacion) - End If - Correcto = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) - Else - Alert("La Factura no se pudo validar.", TipoMensaje.MsgAdvertencia) - End If - ObjValidacion.Dispose() - Case "ValidarCFD" - Correcto = ObjDatos.UpdateEstatus(1, GvRow.DataKey("CveFactura").ToEntero) - - Case "Omitir" - Correcto = ObjDatos.UpdateEstatus(3, GvRow.DataKey("CveFactura").ToEntero) - End Select - - ObjDatos.Dispose() - If Correcto Then - CargaDatos() - End If - End Sub -#End Region - Protected Sub ImgCFDiMasivo_Click(sender As Object, e As EventArgs) Handles LnkCFDiMasivo.Click - Dim ObjDatos As New ClsCompras - ObjDatos.IniciaTransacSQL() - Dim ErrorTrans As Boolean = False - If Tab.ActiveTabIndex = 0 Then - For Each GvRow As GridViewRow In GvD.Rows - If GvRow.DataKey("TipoFactura") = "CFDi" AndAlso GvRow.DataKey("FueValidado").Contiene("0", "1") Then - Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), GvRow.DataKey("Total").ToDecimal) - If ObjValidacion.EsValida > 0 Then - If Not ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) Then - ErrorTrans = True - End If - End If - ObjValidacion.Dispose() - End If - Next - ElseIf Tab.ActiveTabIndex = 1 Then - For Each GvRow As GridViewRow In GvPagos.Rows - If GvRow.DataKey("TipoFactura") = "CFDi" AndAlso GvRow.DataKey("FueValidado").Contiene("0", "1") Then - Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), 0) - If ObjValidacion.EsValida > 0 Then - If Not ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) Then - ErrorTrans = True - End If - End If - ObjValidacion.Dispose() - End If - Next - End If - If Not ErrorTrans Then - ObjDatos.Commit() - Alert("La verificación masiva ha terminado", TipoMensaje.MsgInformacion) - CargaDatos() - Else - ObjDatos.RollBack() - End If - ObjDatos.Dispose() - End Sub - Protected Sub LnkNoRecibidas_Click(sender As Object, e As EventArgs, Optional ValidaRowCount As Boolean = False) Handles LnkNoRecibias.Click - Dim DtNoRecibidas As New DataTable - Dim Ruta As String = String.Format("{0}\Empresas\{1}\Compras\NoRecibidas-{1}.xml", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa) - Dim Str As New StringBuilder - If IO.File.Exists(Ruta) Then - DtNoRecibidas.ReadXml(Ruta) - - Dim conta As Integer = 1 - Str.Append("Se encontraron las siguientes facturas con problema:
") - - For Each dr As DataRow In DtNoRecibidas.FiltraParametros("", "Fecha DESC").Rows - - Str.AppendFormat("", If(conta Mod 2 = 0, "TextoAlterno", "Texto")) - - Str.AppendFormat("", dr("Serie")) - Str.AppendFormat("", dr("Folio")) - Str.AppendFormat("", If(dr("Fecha").ToString <> "", dr("Fecha").ToString.ToDate.ToShortDateString, "")) - Str.AppendFormat("", dr("Proveedor")) - Str.AppendFormat("", dr("Importe").ToString.ToDouble.FormatoNumero) - Str.AppendFormat("", dr("Motivo")) - Str.AppendFormat("", If(dr("Correo").ToString.Length > 20, dr("Correo").ToString.Substring(0, 20), dr("Correo").ToString())) - Str.AppendFormat("", dr("FechaRecepcion").ToString.ToDate.ToShortDateString) - - Str.Append("") - conta += 1 - Next - Str.Append("
SerieFolioFechaProveedorImporteMotivoCorreoF. Recepción
{0}{0}{0}{0}{0}{0}{0}{0}
") - Else - Str.Append("No se encontraron facturas pendientes de recibir.") - End If - - If ValidaRowCount Then 'si las facturas no recividas son matores a cero se muestra el mensaje - If DtNoRecibidas.Rows.Count > 0 Then - Alert(Str.ToString, TipoMensaje.MsgInformacion) - End If - Else - Alert(Str.ToString, TipoMensaje.MsgInformacion) - End If - - DtNoRecibidas.Dispose() - - CargaDatos() - End Sub - -#Region "G E N E R A P D F " - Private Sub GenerarPDF(Optional Tipo As String = "PDF") - Dim ObjDatos As New ClsCompras - Dim FechaI As String = txtFechaI.Text - Dim FechaF As String = txtFechaF.Text - If txtFechaI.Text = "" Then FechaI = "-1" - If txtFechaF.Text = "" Then FechaF = "-1" - Dim Folio = If(TxtFolio.Text.Trim.Length > 0, String.Format("%{0}%", TxtFolio.Text.Trim.ToUpper), "-1") - Dim Proveedor = If(TxtProveedor.Text.Trim.Length > 0, String.Format("%{0}%", TxtProveedor.Text.Trim.ToUpper.Replace(" ", "%")), "-1") - - If ObjDatos.GetFacturas(-1, Folio, txtFechaI.Text.Trim.ToDate, txtFechaF.Text.Trim.ToDate, "-1", Proveedor, DdlValidado.SelectedValue.ToEntero, DdlResponsable.SelectedValue.ToEntero, DdlClasificacionProv.SelectedValue.ToEntero, DdlCveTipoProveedor.SelectedValue.ToEntero, DdlTipoComprobante.SelectedValue.ToString, UsuarioActual.CveEmpresa) Then - - 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 dt As DataTable - - - - If Tab.ActiveTabIndex = 0 Then - dt = ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P'") - Else - dt = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P' ") - End If - - - - Dim params As New List(Of ReportParameter) - params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) - params.Add(New ReportParameter("FechaInicio", FechaI)) - params.Add(New ReportParameter("FechaFin", FechaF)) - params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) - params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) - If Imagen.Exists Then - params.Add(New ReportParameter("LogoPath", logouri)) - Else - params.Add(New ReportParameter("LogoPath", "")) - End If - - ImprimirPDF("Empresas/Grales/Formatos/RepFacturas.rdlc", dt, params, $"FacturasBuzon_{Now.ToString("yyyyMMyyddmmss")}", Tipo) - Else - Alert("No hay datos consultados", TipoMensaje.MsgAdvertencia) - End If - - End Sub - Protected Sub LnkPdf_Click(sender As Object, e As EventArgs) Handles LnkPdf.Click - GenerarPDF() - End Sub -#End Region - -#Region "S U B I R - F A C T U R A S - M A S I V A M E N T E" - Private Sub LnkSubirFacturas_Click(sender As Object, e As EventArgs) Handles LnkSubirFacturas.Click - RegistraScript(String.Format("$('#{0}').modal();", "ModalFacturas")) - End Sub - Private Sub BtnGuardarFaturas_Click(sender As Object, e As EventArgs) Handles BtnGuardarFaturas.Click - - If UsuarioActual.Empresa.SendMail.Trim.Length = 0 Then - Alert("La Empresa no tiene configurado el envió de correo.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - - - Dim sw As New Diagnostics.Stopwatch - Dim swmili As Long = 0 - Dim swTiempo As New StringBuilder - sw.Start() - - - Dim FileExtension As String = "-1" - Dim filesgral As List(Of Archivo) = Anexo.getfiles().Archivos - Dim filemove As String = "" - - Dim ListXML As New List(Of String) - Dim ListPDF As New List(Of String) - Dim ListDirectorios As New List(Of String) - - - - For Each fileItem As Archivo In filesgral - FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "") - filemove = fileItem.filename - - If filemove <> "" Then - filemove.FilesMove("", String.Format("Empresas\{0}\Temp\Facturas", UsuarioActual.CveEmpresa)) - 'AGREGA XML A LA LISTA - If FileExtension.ToUpper = "XML" Then - ListXML.Add(String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, filemove)) - End If - - End If - Next - - - Dim fileEntries As String() = Directory.GetFiles(String.Format("{0}Empresas\{1}\Temp\Facturas", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa)) - - Dim ListaDirectoriosTemporales As New List(Of String) - Dim ListaComprimidos As New List(Of String) - - 'Dim fileName As String - Dim ArchivoExtension As String - Dim sOnlyFilename As String - - For Each filePath In fileEntries - ArchivoExtension = IO.Path.GetExtension(String.Format("{0}", filePath)).Replace(".", "") - sOnlyFilename = System.IO.Path.GetFileName(filePath) - If ArchivoExtension.ToUpper = "RAR" Or ArchivoExtension.ToUpper = "ZIP" Then - ListaComprimidos.Add(filePath) - 'CREO DIRECTORIO ALEATORIO - Dim Aleatorio As New Random - Dim TempDirectorio As String = String.Format("{0}Empresas\{1}\{2}\{3}{4}", Request.PhysicalApplicationPath, UsuarioActual.CveEmpresa, "Temp\Facturas", Date.Now.Ticks, Aleatorio.Next(100, 999)) - Directory.CreateDirectory(TempDirectorio) - ListaDirectoriosTemporales.Add(TempDirectorio) - 'AGREGA DIRECTORIO A LA LISTA - ListDirectorios.Add(TempDirectorio) - 'DESCOMPRIME RAR - DescomprimeFacturas(filePath, TempDirectorio) - 'AGREGA XML A LA LISTA - ListXML.AddRange(Directory.GetFiles(TempDirectorio)) - End If - - - Next - - Dim Arreglo As New ArrayList() - ' Dim Archivos As String() = Directory.GetFiles(String.Format("{0}Empresas\{1}\Temp", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa)) - 'Dim NombreArchivo As String - Dim Bandera = True - Dim Retorno = "" - Dim ListaArchivosMail As New List(Of ClsSisMail.ArchivoMail) - - - sw.Stop() - swTiempo.AppendFormat("ReadFiles: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) - swmili = sw.ElapsedMilliseconds - sw.Start() - - Anexo.Text = "" - UPAddFacturas.Update() - - For Each filePath In ListXML - - If File.Exists(filePath) Then - Dim ArchivoAdjunto As New ClsSisMail.ArchivoMail - ArchivoAdjunto.ArchivoBinario = File.ReadAllBytes(filePath) - ArchivoAdjunto.Ruta = filePath - ArchivoAdjunto.NombreArchivo = New FileInfo(filePath).Name - - ListaArchivosMail.Add(ArchivoAdjunto) - - End If - - Next - - sw.Stop() - swTiempo.AppendFormat("Fill ClsSisMail.ArchivoMail: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) - swmili = sw.ElapsedMilliseconds - sw.Start() - If ListaArchivosMail.Count > 0 Then - - Dim Correo As New ClsSisMail - - 'If Correo.SendMail(UsuarioActual.Empresa, "sig.buzon@gmail.com", "Facturas Efacturas " & Now.ToString("yyyyMMddhhmmss"), "Facturas", Archivos:=ListaArchivosMail) Then - - - - - If Correo.SendMail(UsuarioActual.Empresa, UsuarioActual.Empresa.Buzon_Mail, "Facturas Efacturas " & Now.ToString("yyyyMMddhhmmss"), "Facturas", Archivos:=ListaArchivosMail) Then - - sw.Stop() - swTiempo.AppendFormat("EnvioCorreo: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) - swmili = sw.ElapsedMilliseconds - sw.Start() - System.Threading.Thread.Sleep(3000) - 'ProcesaBuzon() - - sw.Stop() - swTiempo.AppendFormat("espera: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) - swmili = sw.ElapsedMilliseconds - sw.Start() - VerificaCorreo(True) - - sw.Stop() - swTiempo.AppendFormat("Verifica En la app: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) - swmili = sw.ElapsedMilliseconds - sw.Start() - Else - Alert("Se presento un error al procesar las facturas.") - End If - - End If - - - sw.Stop() - swTiempo.AppendFormat("BorrarInicio: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) - swmili = sw.ElapsedMilliseconds - sw.Start() - For Each filePath In ListXML - Try - File.Delete(filePath) - Catch ex As Exception - End Try - Next - - For Each s As String In ListaComprimidos - Try - File.Delete(s) - Catch ex As Exception - End Try - Next - - For Each d As String In ListaDirectoriosTemporales - Try - Directory.Delete(d, True) - Catch ex As Exception - End Try - Next - - - sw.Stop() - swTiempo.AppendFormat("BorrarEnd: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) - swmili = sw.ElapsedMilliseconds - - GuardaLogefacturas(swTiempo.ToString()) - - - 'ArchivoExtension = IO.Path.GetExtension(String.Format("{0}", filePath)).Replace(".", "") - 'NombreArchivo = System.IO.Path.GetFileName(filePath) - 'If ArchivoExtension.ToUpper = "XML" Then - ' Dim ArchivoInfo As New FileInfo(filePath) - ' Dim Fact2 As Modelos.eFactura = GuardaArchivoXML(filePath) - - ' If Fact2 IsNot Nothing Then - ' Fact2.DirectorioTemporal = ArchivoInfo.DirectoryName & "\" - ' Arreglo.Add(Fact2) - ' End If - 'End If - - - 'If Arreglo.Count > 0 Then - ' For Each Fact As Modelos.eFactura In Arreglo - ' ' si es exploraciones, no debe de insertar del 2013 - - ' If UsuarioActual.CveEmpresa = 13 And Convert.ToDateTime(Fact.Fecha).Year < 2014 And Fact.TipodeComprobante <> "egreso" Then - ' Bandera = False - ' 'ModExtensiones.GuardaLog("'*******noingreso :" + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year) - ' End If - - ' 'por default, no alimentar facturas menores al 2013 - - ' If Convert.ToDateTime(Fact.Fecha).Year < 2013 Then - ' Bandera = False - ' 'ModExtensiones.GuardaLog("'*******noingreso :" + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year) - ' End If - ' If Bandera Then - ' If Not String.IsNullOrEmpty(Fact.TFDUUID) Then - ' Dim Valida As New ClsValidaCFDi(Fact.TFDUUID, Fact.EmisorRFC, Fact.ReceptorRFC, Fact.Total, Fact.Fecha) - ' If Valida.EsValida = 1 Then - ' Fact.Validada = 1 - ' End If - ' Valida.Dispose() - - ' If Not String.IsNullOrEmpty(Fact.ArchivoPDF) Then - ' Retorno = AgregaFactura(Fact) - ' Else - ' If GeneraPDF(Fact.DirectorioTemporal, Fact) Then - ' ListPDF.Add(Fact.ArchivoPDF) - ' Retorno = AgregaFactura(Fact) - ' ' ModExtensiones.GuardaLog("'*******se genero el pdf :" + String.Format("{0}Empresas\{1}\Temp", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa) + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year + "Retorno:" + Retorno) - ' Else - ' ' ModExtensiones.GuardaLog("'*******no se genero el pdf :" + String.Format("{0}Empresas\{1}\Temp", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa) + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year + "Retorno:" + Retorno) - - ' End If - ' End If - ' End If - ' End If - - ' Bandera = True - ' Try - ' If File.Exists(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoXML)) Then - ' File.Delete(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoXML)) - ' End If - - ' If File.Exists(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF)) Then - ' File.Delete(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF)) - ' End If - ' Catch ex As Exception - - ' End Try - ' Next - 'End If - - - RegistraScript(String.Format("$('#{0}').modal('hide');", "ModalFacturas")) - 'Alert(String.Format("Se cargaron {0} Facturas", Arreglo.Count), TipoMensaje.MsgInformacion) - End Sub - - Public Sub GuardaLogefacturas(Str As String) - Dim ArchivoW As StreamWriter - Dim strLineaTMP As String - - ' strLineaTMP = Chr(13) & Chr(10) & Day(Now) & "/" & Month(Now) & "/" & Year(Now) & " " & Hour(Now) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) - strLineaTMP = String.Format("{0}{1}Log: {2}{3}:{4}", Chr(13), Chr(10), Str, DateTime.Now.ToShortDateString, DateTime.Now.ToShortTimeString) - Try - ArchivoW = New StreamWriter(String.Format("{0}\Logefacturas.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) - Catch ex As UnauthorizedAccessException - 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) - Exit Sub - Catch ex As Exception - Exit Sub - End Try - - Try - ArchivoW.WriteLine(strLineaTMP) - Catch - End Try - - ArchivoW.Close() - ArchivoW.Dispose() - End Sub - Private Function AgregaFactura(Fact As Modelos.eFactura) As String - Dim Retorno As String = "" - Dim Correcto As Boolean = False - - If Fact.Version = "3.2" Then Fact.TipodeComprobante = Fact.TipodeComprobante.Substring(0, 1) - - - Dim ObjDatos As New ClsCompras - ObjDatos.IniciaTransacSQL() - ObjDatos.CveFactura = 0 - Dim Ret As Integer = ObjDatos.AddFactura(Fact.Serie, Fact.Folio, Convert.ToDateTime(Fact.Fecha), Fact.EmisorNombre, Fact.EmisorRFC, Fact.subTotal, - Fact.TrasladoIVA, Fact.Total, Fact.TFDUUID, Fact.ReceptorRFC, Fact.ArchivoXML, Fact.ArchivoPDF, - Fact.Version, Fact.Descuento, Fact.Moneda, Fact.TipodeComprobante, Fact.TipoCambio, Fact.Validada, - Fact.CveEmpresa, Fact.sUPPrefijo) - - If Ret >= 0 Then - If Not Directory.Exists(Destino + Fact.EmisorRFC) Then - Directory.CreateDirectory(Destino + Fact.EmisorRFC) - End If - 'Try - ' If File.Exists(Destino & Retorno.EmisorRFC & "\" & NombreArchivo) Then File.Delete(Destino & Retorno.EmisorRFC & "\" & NombreArchivo) - ' File.Move(Temporal & NombreArchivo, Destino & Retorno.EmisorRFC & "\" & NombreArchivo) - - 'Catch ex As IOException - ' GuardaLog("'ERROR :" & ex.Message) - 'End Try - - Select Case Ret - Case 0 - - Correcto = True - Dim RRutaDestino As String = String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura) - 'ModExtensiones.GuardaLog(String.Format(" '--------{0} Compra ya insertada : {1}{2} - {3}", ContadorGeneral, Fact.Serie, Fact.Folio, RRutaDestino)) - - If Not File.Exists(RRutaDestino) Then - File.Move(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, Fact.ArchivoXML), RRutaDestino) - ObjDatos.UpdateArchivo(ObjDatos.CveFactura, "XML") - ModExtensiones.GuardaLog(" '--------XML Actualizado ") - End If - - Correcto = True - Exit Select - Case 1 - 'muevo el archivo y lo renombro - Dim StrMover As String = "" - Try - File.Move(String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoXML), String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) - File.Move(String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF), String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) - ModExtensiones.GuardaLog(" '++++++++ Archivo :" + String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoXML) + " - " + String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) - ModExtensiones.GuardaLog(" '++++++++ Archivo :" + String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF) + " - " + String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) - 'si se movieron los dos archivos, los marca como correcto - If File.Exists(String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) AndAlso File.Exists(String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) Then - Correcto = True - End If - Catch ex As Exception - StrMover = ex.Message - End Try - - - ModExtensiones.GuardaLog(Convert.ToString(" '++++++++ Compra Insertada :" + Fact.Serie + Fact.Folio + " - Correcto:" + (If(Correcto, "Si", "No" + " Obs: "))) & StrMover) - Exit Select - End Select - End If - If Correcto Then - ObjDatos.Commit() - 'ya se insertó o está insertada - Dim Idioma As New CultureInfo("es-MX") - 'regreso el format 2014-07 Julio - Retorno = Fact.Fecha.ToDate().ToString("yyyy-MM MMMM", Idioma) - Else - ObjDatos.RollBack() - End If - ObjDatos.Dispose() - - Return Retorno - - End Function - Private Sub CargarFacturas(PathArchivo As String, NombreArchivo As String) - Dim RFC As String = CargaEmisordeXML(String.Format("{0}", PathArchivo), "RFC", UsuarioActual.Empresa.RFC) - If RFC IsNot Nothing Then - If NombreArchivo <> "" Then - DirectoryExistsCreate(String.Format("{0}Compras", UsuarioActual.Empresa.Ruta)) - DirectoryExistsCreate(String.Format("{0}Compras\{1}", UsuarioActual.Empresa.Ruta, RFC.ToUpper)) - - Try - File.Move(PathArchivo, String.Format("{0}Empresas\{1}\Compras\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, RFC.ToUpper, NombreArchivo)) - Catch ex As Exception - Alert("Error") - End Try - - 'NombreArchivo.FilesMove(NombreArchivo, String.Format("Empresas\{0}\Compras\{1}", UsuarioActual.CveEmpresa, RFC.ToUpper)) - End If - End If - End Sub - Private Sub DescomprimeFacturas(PathArchivo As String, Directorio As String) - If Not Directory.Exists(Directorio) Then - Directory.CreateDirectory(Directorio) - End If - Using archive As ZipArchive = ZipFile.OpenRead(String.Format("{0}", PathArchivo)) - - For Each entry As ZipArchiveEntry In archive.Entries - If entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) Then - - 'If File.Exists(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Directorio, entry.Name)) Then - ' File.Delete(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Directorio, entry.Name)) - 'End If - - 'entry.ExtractToFile(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Directorio, entry.Name)) - - If File.Exists(String.Format("{0}\{1}", Directorio, entry.Name)) Then - File.Delete(String.Format("{0}\{1}", Directorio, entry.Name)) - End If - - entry.ExtractToFile(String.Format("{0}\{1}", Directorio, entry.Name)) - - End If - Next - - End Using - End Sub - Public Shared Function CargaEmisordeXML(ArchivoXML As String, CampoXML As String, RFCEmpresaActual As String) As String - Dim Valor As [String] = Nothing - - If File.Exists(ArchivoXML) Then - Dim NombreArchivo As String = Path.GetFileName(ArchivoXML) - Dim invalidChars As Char() = Path.GetInvalidFileNameChars() - Dim invalidString As String = Regex.Escape(New String(invalidChars)) - Dim NombreValido As String = Regex.Replace(NombreArchivo, (Convert.ToString("[") & invalidString) + "]", "") - - Try - Dim XmlDoc As New XmlDocument() - XmlDoc.Load(ArchivoXML) - Dim nodo As XmlNode = XmlDoc.DocumentElement.ChildNodes(0) - Dim node As XmlNode - Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" - Dim RfcXML As String = "" - Dim Prefijo As String = If(XmlDoc.DocumentElement.Prefix = "", "cfd", XmlDoc.DocumentElement.Prefix) - Dim namespaces As New XmlNamespaceManager(XmlDoc.NameTable) - - If Not Prefijo.ToLower().Equals("cfdi") Then - cfdVer = "http://www.sat.gob.mx/cfd/2" - End If - namespaces.AddNamespace(Prefijo, cfdVer) - namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") - namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal") - namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal") - - node = XmlDoc.SelectSingleNode([String].Format("//{0}:Receptor", Prefijo), namespaces) - If node IsNot Nothing Then - RfcXML = ValorXML(node, "RFC") - End If - If RfcXML = RFCEmpresaActual Then - Valor = ValorXML(nodo, CampoXML) - - - End If - Catch exx As XmlException - Valor = Nothing - 'Using file__1 As New System.IO.StreamWriter([String].Format("{0}\UtileriasLOG.txt", Path.GetDirectoryName(Application.StartupPath)), True, System.Text.Encoding.UTF8) - ' file__1.WriteLine("{DateTime.Now}: {exx.Message}") - ' file__1.Close() - ' file__1.Dispose() - 'End Using - End Try - End If - Return Valor - End Function - Private Shared Function ValorXML(n As XmlNode, Campo As String, Optional retorno As [String] = "") As String - If n Is Nothing Then - Return retorno - End If - - Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, StringComparison.CurrentCultureIgnoreCase) = 0) - If o Is Nothing Then - Return retorno - Else - Return o.Value - End If - - End Function - Private Function CargaDatosXML(XMLDoc As XmlDocument) As Modelos.eFactura - Dim nodo As XmlNode = XMLDoc.DocumentElement - - If nodo.ChildNodes.Count = 2 Then - nodo = nodo.ChildNodes(1) - End If - - Dim Fact As Modelos.eFactura = Nothing - Dim node As XmlNode = Nothing - Dim RFC As String = "" - - Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix) - Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" - Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) - - If Prefijo.ToLower() <> "cfdi" Then - cfdVer = "http://www.sat.gob.mx/cfd/2" - End If - namespaces.AddNamespace(Prefijo, cfdVer) - namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") - namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal") - namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal") - - node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces) - 'AndAlso node.ChildNodes.Count > 0 - If node IsNot Nothing Then - RFC = ValorXML(node, "RFC") - End If - - 'solo si el rfc receptor es el mismo al de la empresa seleccionada - - If RFC = UsuarioActual.Empresa.RFC AndAlso Convert.ToDateTime(ValorXML(nodo, "fecha")).Year >= 2013 Then - Fact = New Modelos.eFactura() - - 'Fact.CveEmpresa = CveEmpresa - Fact.Serie = ValorXML(nodo, "serie") - If Not String.IsNullOrEmpty(Fact.Serie) Then - Fact.Serie = Fact.Serie - End If - - Fact.Version = ValorXML(nodo, "version").Replace("..", ".") - Fact.Folio = ValorXML(nodo, "folio").TrimStart("0"c) - Fact.Fecha = ValorXML(nodo, "fecha") - Fact.subTotal = Convert.ToDouble(ValorXML(nodo, "subTotal").Replace("..", ".")) - Fact.Total = Convert.ToDouble(ValorXML(nodo, "total")) - Fact.Moneda = ValorXML(nodo, "Moneda") - Fact.TipodeComprobante = ValorXML(nodo, "tipoDeComprobante") - Fact.TipoCambio = Convert.ToDouble(ValorXML(nodo, "TipoCambio", "1.0")) - Fact.Descuento = Convert.ToDouble(ValorXML(nodo, "descuento", "0")) - Fact.CveEmpresa = UsuarioActual.CveEmpresa - - Fact.sUPPrefijo = Prefijo - - node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) - - If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then - Fact.EmisorRFC = ValorXML(node, "RFC") - Fact.EmisorNombre = ValorXML(node, "nombre") - End If - node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces) - ' AndAlso node.ChildNodes.Count > 0 - If node IsNot Nothing Then - Fact.ReceptorRFC = ValorXML(node, "RFC") - End If - - node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces) - - If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then - Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces) - - Fact.TotalRetenciones = Convert.ToDouble(ValorXML(node, "totalImpuestosRetenidos", "0")) - - For Each retencion As XmlNode In nodeRetenciones - If retencion.Attributes.GetNamedItem("impuesto").Value = "IVA" Then - Fact.RetencionIVA += Convert.ToDouble(retencion.Attributes.GetNamedItem("importe").Value) - End If - If retencion.Attributes.GetNamedItem("impuesto").Value = "ISR" Then - Fact.RetencionISR += Convert.ToDouble(retencion.Attributes.GetNamedItem("importe").Value) - ' Do something. - End If - Next - Fact.SumaTotalRetenciones += Fact.RetencionIVA - Fact.SumaTotalRetenciones += Fact.RetencionISR - - Fact.TotalTraslados = Convert.ToDouble(ValorXML(node, "totalImpuestosTrasladados", "0")) - - 'Dim o As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "impuesto", StringComparison.CurrentCultureIgnoreCase) = 0) - Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) - - For Each traslado As XmlNode In nodeTraslados - ' If traslado.Attributes.GetNamedItem("impuesto").Value = "IVA" - Dim impuesto As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "impuesto", StringComparison.CurrentCultureIgnoreCase) = 0) - If impuesto.Value = "IVA" Then - - Dim ImporteTRaslado As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "Importe", StringComparison.CurrentCultureIgnoreCase) = 0) - Fact.TrasladoIVA += Convert.ToDouble(ImporteTRaslado.Value) - 'If traslado.Attributes("impuesto").Value = "ISR" Then - ' TrasladoISR = traslado.Attributes("importe").Value - 'End If - ' Do something. - End If - Next - Fact.SumaTotalTraslados += Fact.TrasladoIVA - End If - - - Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces) - Dim FacturaMisCuentasSAT As Boolean = False - - - If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then - Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces) - - Fact.TFDUUID = ValorXML(nodeTFD, "UUID", "") - - Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces) - If nodeRF IsNot Nothing Then - Fact.Folio = ValorXML(nodeRF, "folio").TrimStart("0"c) - FacturaMisCuentasSAT = True - - End If - Else - Fact.TFDUUID = "" - If String.IsNullOrEmpty(Fact.TFDUUID) AndAlso Fact.sUPPrefijo.ToLower() = "cfdi" Then - 'Mensajes.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}{6}&", ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate().ToShortDateString(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble().FormatoNumero(), - '"Factura no timbrada correctamente.", "") - 'CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble(), "Factura no timbrada correctamente.", - '"", DateTime.Now) - End If - - 'limpio los valores porque realmente no es una factura - - Fact = Nothing - End If - 'verifico si el metodo de pago esta dentro de la opcion valida - - - If Convert.ToDateTime(ValorXML(nodo, "fecha")) >= ("2016/07/15").ToDate() Then - Dim CasoPermitido As Boolean = False - 'If CveEmpresa.Contiene(72, 80) AndAlso ValorXML(nodo, "MetododePago").ToUpper().PadRight(13, " "c).Substring(0, 13) = "TRANSFERENCIA" Then - ' CasoPermitido = True - 'End If - - 'If CveEmpresa = 5 OrElse FacturaMisCuentasSAT Then - ' CasoPermitido = True - 'End If - - If Not CasoPermitido Then - If (Not (ValorXML(nodo, "MetododePago").ToUpper().PadLeft(2, "0"c).Substring(0, 2).Contiene("01", "02", "03", "04", "05", "06", - "07", "08", "09", "10", "11", "12", - "13", "14", "15", "16", "17", "28", - "98", "99", "NA") OrElse ValorXML(nodo, "MetododePago").ToUpper().Contiene("NO APLICA", "N/A", "N.A.", "NO IDENTIFICADO"))) Then - Dim node2 As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) - Dim Nombre As String = "" - - If node2 IsNot Nothing AndAlso node2.ChildNodes.Count > 0 Then - Nombre = ValorXML(node2, "nombre") - End If - - 'CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble(), "Método de Pago Incorrecto:" + ValorXML(nodo, "MetododePago"), - 'CorreoActual, FechaRecepcionCorreo) - - Return Nothing - End If - - - End If - - 'faltan leer los impuestos locales - 'node = XMLDoc.SelectSingleNode(String.Format("//{0}:ImpuestosLocales", "implocal"), namespaces) - 'If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then - ' Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces) - - ' Fact.TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDouble - - ' For Each retencion As XmlNode In nodeRetenciones - ' If retencion.Attributes("impuesto").Value = "IVA" Then - ' Fact.RetencionIVA += retencion.Attributes("importe").Value.ToDouble - ' End If - ' If retencion.Attributes("impuesto").Value = "ISR" Then - ' Fact.RetencionISR += retencion.Attributes("importe").Value.ToDouble - ' End If - ' ' Do something. - ' Next - ' Fact.SumaTotalRetenciones += Fact.RetencionIVA - ' Fact.SumaTotalRetenciones += Fact.RetencionISR - - ' Fact.TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble - - ' Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) - ' For Each traslado As XmlNode In nodeTraslados - ' If traslado.Attributes("impuesto").Value = "IVA" Then - ' Fact.TrasladoIVA += traslado.Attributes("importe").Value.ToDouble - ' End If - ' 'If traslado.Attributes("impuesto").Value = "ISR" Then - ' ' TrasladoISR = traslado.Attributes("importe").Value - ' 'End If - ' ' Do something. - ' Next - ' Fact.SumaTotalTraslados += Fact.TrasladoIVA - 'End If - - - End If - Else - 'ModExtensiones.GuardaLog((Convert.ToString("'*******RFC incorrecto RFC Emp:") & RFC) + " RFC Fact: " + RFCReceptor) - 'obtengo los datos del xml, para - - Dim node2 As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) - - - 'If node2 IsNot Nothing AndAlso node2.ChildNodes.Count > 0 Then - ' Mensajes.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}{6}&", ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate().ToShortDateString(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble().FormatoNumero(), - ' "RFC Incorrecto:", RFC) - ' CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble(), Convert.ToString("RFC Incorrecto:") & RFC, - ' CorreoActual, FechaRecepcionCorreo) - 'Else - ' CargaMensaje("", "", "01/01/2000".ToDate(), "", 0.0, Convert.ToString("RFC Incorrecto:") & RFC, - ' CorreoActual, FechaRecepcionCorreo) - - - 'End If - End If - - Return Fact - End Function - Private Function GuardaArchivoXML(Archivo As String) As Modelos.eFactura - ' , Destino As String, Temporal As String - Dim Retorno As Modelos.eFactura = Nothing - - If File.Exists(Archivo) Then - Dim NombreArchivo As String = Path.GetFileName(Archivo) - Dim invalidChars As Char() = Path.GetInvalidFileNameChars() - Dim invalidString As String = Regex.Escape(New String(invalidChars)) - Dim valid As String = Regex.Replace(NombreArchivo, (Convert.ToString("[") & invalidString) + "]", "") - - NombreArchivo = valid - - Try - Dim XMLDoc As New XmlDocument() - - XMLDoc.Load(Archivo) - Retorno = CargaDatosXML(XMLDoc) - - Catch exx As XmlException - Retorno = Nothing - 'Dim texto As Dynamic = File.ReadAllText(Archivo) - Dim txt_utf8 As New UTF8Encoding() - 'REEMPLAZA CARACTERES ESPECIALES Y VUELVE A LEER EL DOCUMENTO - - 'texto = RemoveIllegalXMLCharacters(texto) - ' SE RENOMBRA EL ARCHIVO, PERO SE QUITO POR SI NO COINCIDE EL PDF CON EL NOMBRE - 'Archivo = Archivo.ToUpper.Replace(".XML", "-2.XML") - 'NombreArchivo = IO.Path.GetFileName(Archivo) - 'File.WriteAllText(Archivo, texto) - - - ' Dim xmltr As New XmlTextReader(New MemoryStream(RemoveIllegalXMLCharacters(texto))) - Dim XMLDoc As New XmlDocument() - - Try - XMLDoc.Load(Archivo) - Retorno = CargaDatosXML(XMLDoc) - Catch ex As Exception - Retorno = Nothing - - - - End Try - Catch ex As Exception - - - Retorno = Nothing - End Try - - 'si se cargaron todos los datos - If Retorno IsNot Nothing AndAlso Not String.IsNullOrEmpty(Retorno.TFDUUID) Then - 'XML - Retorno.ArchivoXML = NombreArchivo - End If - End If - Return Retorno - - End Function - Private Sub CargaImpuestosXML(XMLDoc As XmlDocument) - Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix) - Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" - Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) - - If Prefijo.ToLower() <> "cfdi" Then - cfdVer = "http://www.sat.gob.mx/cfd/2" - End If - namespaces.AddNamespace(Prefijo, cfdVer) - namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") - namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal") - namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal") - - TrasladoIVA = 0 - '_TrasladoIVA = XMLDoc.DocumentElement.ChildNodes(3).Attributes("totalImpuestosTrasladados").Value - - Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) - For Each traslado As XmlNode In nodeTraslados - If traslado.Attributes.GetNamedItem("impuesto").Value = "IVA" Then - TrasladoIVA += traslado.Attributes.GetNamedItem("importe").Value.ToDouble() - - End If - Next - - Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces) - - - If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then - Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces) - - _TFDUUID = ValorXML(nodeTFD, "UUID", "") - _TFDFechaTimbrado = ValorXML(nodeTFD, "FechaTimbrado", "") - _TFDSelloCFD = ValorXML(nodeTFD, "selloCFD", "") - _TFDNoCertSAT = ValorXML(nodeTFD, "noCertificadoSAT", "") - _TFDSelloSAT = ValorXML(nodeTFD, "selloSAT", "") - - Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces) - If nodeRF IsNot Nothing Then - _Folio = ValorXML(nodeRF, "folio").TrimStart("0"c) - - - End If - End If - - End Sub - Private Shared Sub CargaTFD(XMLDoc As XmlDocument) - '_TFDUUID = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText - '_TFDFechaTimbrado = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("FechaTimbrado").InnerText - '_TFDSelloCFD = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("selloCFD").InnerText - '_TFDNoCertSAT = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("noCertificadoSAT").InnerText - '_TFDSelloSAT = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("selloSAT").InnerText - End Sub - Public Function GeneraPDF(Ruta As String, Fact As Modelos.eFactura) As Boolean - Dim RutaXML As String = String.Empty - Dim RutaPDF As String = String.Empty - Dim Retorno As Boolean = False - Try - - Dim XMLDoc As New XmlDocument() - Dim TmpArchivoPDF As String = String.Format("{0}{1}-ttt.pdf", Ruta, Path.GetFileNameWithoutExtension(Fact.ArchivoXML)) - Dim TmpArchivoQR As String = String.Format("{0}{1}-ttt.jpg", Ruta, Path.GetFileNameWithoutExtension(Fact.ArchivoXML)) - Dim ArchivoXML As String = String.Format("{0}{1}", Ruta, Fact.ArchivoXML) - - ' If Not File.Exists(TmpArchivoPDF) Then - XMLDoc.Load(ArchivoXML) - CreaDTConceptos() - CargaComprobanteXML(XMLDoc) - CargaEmisorXML(XMLDoc) - CargaReceptorXML(XMLDoc) - CargaConceptosXML(XMLDoc) - CargaImpuestosXML(XMLDoc) - CargaTFD(XMLDoc) - - Dim QR As New ClbNegBICFDv3_2.ClsNegCBBGenerar() - Dim dtotal As Decimal = (If(total.ToDecimal() <= 0.0D, 0.0001D, total.ToDecimal())) - QR.GenerarCBB(EmiRFC, RecRfc, dtotal, TFDUUID, TmpArchivoQR) - - - If System.IO.File.Exists(TmpArchivoQR) Then - 'Dim ArchivoBaseXLS As String = String.Format("{0}FacturaPDF.xlsm", Ruta.Replace("Temp", "Compras")) - If GeneraPDFNew(TmpArchivoPDF, TFDUUID, subTotal, descuento, total, TrasladoIVA.ToString(), - moneda, formaDePago, TFDNoCertSAT, TFDFechaTimbrado.ToDate(), noCertificado, DTConceptos, - TFDSelloCFD, TFDSelloSAT, TmpArchivoQR, Serie + Folio, tipoDeComprobante, "", - RecRfc, RecNombre, DomRecCalle, DomRecCol, DomRecFisNoExt, DomRecFisNoInt, - DomRecCP, DomRecMun, DomRecEst, Regimen, condicionesDePago, metodoDePago, - NumCtaPagoNumCtaPago, fecha.ToDate()) Then - Fact.ArchivoPDF = Path.GetFileName(TmpArchivoPDF) - - Retorno = True - End If - - File.Delete(TmpArchivoQR) - - RutaPDF = TmpArchivoPDF - Else - Retorno = False - End If - 'Else - 'RutaPDF = TmpArchivoPDF - 'End If - - - - If DTConceptos IsNot Nothing Then - DTConceptos.Dispose() - End If - Catch ex As Exception - ModExtensiones.GuardaLog("11189" + ex.Message) - End Try - - - Return Retorno - End Function - Private Sub CargaComprobanteXML(XMLDoc As XmlDocument) - Dim nodo As XmlNode = XMLDoc.DocumentElement - Serie = ValorXML(nodo, "serie", "") - _Folio = ValorXML(nodo, "folio", "") - _fecha = ValorXML(nodo, "fecha", "") - _tipoDeComprobante = ValorXML(nodo, "tipoDeComprobante", "") - _formaDePago = ValorXML(nodo, "formaDePago", "") - _subTotal = ValorXML(nodo, "subTotal", "0") - _descuento = ValorXML(nodo, "descuento", "0") - _total = ValorXML(nodo, "total", "0") - _moneda = ValorXML(nodo, "Moneda") - _metodoDePago = ValorXML(nodo, "metodoDePago", "") - _condicionesDePago = ValorXML(nodo, "condicionesDePago", "") - _LugarExpedicion = ValorXML(nodo, "LugarExpedicion", "") - _NumCtaPagoNumCtaPago = ValorXML(nodo, "NumCtaPago", "") - - - _noCertificado = XMLDoc.DocumentElement.Attributes.GetNamedItem("noCertificado").Value - End Sub - Private Sub CargaEmisorXML(XMLDoc As XmlDocument) - Dim nodo As XmlNode = XMLDoc.DocumentElement.ChildNodes(0) - _EmiRFC = ValorXML(nodo, "rfc", "") - _EmiNombre = ValorXML(nodo, "nombre", "") - - nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(0) - _DomFisCalle = ValorXML(nodo, "calle", "") - _DomFisNoExt = ValorXML(nodo, "noExterior", "") - 'LblDomFisNoInt.Text = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(0).Attributes("noInterior").Value - _DomFisCol = ValorXML(nodo, "colonia", "") - _DomFisCP = ValorXML(nodo, "codigoPostal", "") - _DomFisMun = ValorXML(nodo, "municipio", "") - _DomFisLoc = ValorXML(nodo, "localidad", "") - _DomFisEst = ValorXML(nodo, "estado", "") - _DomFisPais = ValorXML(nodo, "pais", "") - - nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(1) - _ExpEnCalle = ValorXML(nodo, "calle", "") - _ExpEnNoExt = ValorXML(nodo, "noExterior", "") - 'LblExpEnNoInt.Text = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(1).Attributes("noInterior").Value - ExpEnCol = ValorXML(nodo, "colonia", "") - _ExpEnCP = ValorXML(nodo, "codigoPostal", "") - _ExpEnMun = ValorXML(nodo, "municipio", "") - _ExpEnLoc = ValorXML(nodo, "localidad", "") - _ExpEnEst = ValorXML(nodo, "estado", "") - _ExpEnPais = ValorXML(nodo, "pais", "") - - nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(2) - _Regimen = ValorXML(nodo, "Regimen", "") - End Sub - Private Sub CargaReceptorXML(XMLDoc As XmlDocument) - Dim nodo As XmlNode = XMLDoc.DocumentElement.ChildNodes(1) - _RecRfc = ValorXML(nodo, "rfc", "") - _RecNombre = ValorXML(nodo, "nombre", "") - - nodo = XMLDoc.DocumentElement.ChildNodes(1).ChildNodes(0) - - _DomRecCalle = ValorXML(nodo, "calle", "") - _DomRecFisNoExt = ValorXML(nodo, "noExterior", "") - _DomRecFisNoInt = ValorXML(nodo, "noInterior", "") - _DomRecCol = ValorXML(nodo, "colonia", "") - _DomRecCP = ValorXML(nodo, "codigoPostal", "") - _DomRecMun = ValorXML(nodo, "municipio", "") - _DomRecLoc = ValorXML(nodo, "localidad", "") - _DomRecEst = ValorXML(nodo, "estado", "") - _DomRecPais = ValorXML(nodo, "pais", "") - End Sub - Private Sub CargaConceptosXML(XMLDoc As XmlDocument) - Dim i As Integer = 0 - 'Dim SB As New StringBuilder() - 'SB.Append("") - 'SB.AppendLine("") - Dim nodo As XmlNode = Nothing - For i = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1 - nodo = XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i) - 'SB.Append("") - 'SB.Append("") - 'SB.Append("") - 'SB.Append("") - 'SB.Append("") - 'SB.Append("") - 'SB.Append("") - - AddPS(nodo.Attributes.GetNamedItem("cantidad").Value.ToDouble(), nodo.Attributes.GetNamedItem("unidad").Value, nodo.Attributes.GetNamedItem("descripcion").Value, nodo.Attributes.GetNamedItem("valorUnitario").Value.ToDouble(), 0, nodo.Attributes.GetNamedItem("importe").Value.ToDouble()) - Next - 'SB.Append("
cantidaddescripcionvalorUnitarioimporteunidad
" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("cantidad").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("descripcion").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("valorUnitario").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("importe").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("unidad").Value & "
") - 'If i > 0 Then Response.Write(SB.ToString) - 'SB.Clear() - End Sub - Private Sub AddPS(Cantidad As Double, UM As String, PS As String, PU As Double, IVA As Double, Optional Total As Double = 0) - If PS <> "IVA" Then - Dim Row As DataRow = Nothing - Row = DTConceptos.NewRow() - Row("Consec") = DTConceptos.Rows.Count + 1 - Row("Cantidad") = Cantidad - Row("UM") = UM - Row("PS") = PS - Row("PU") = PU - Row("IVA") = IVA - Row("Total") = If(Total > 0, Total, (Cantidad * PU)) - DTConceptos.Rows.Add(Row) - End If - End Sub - Private Function GeneraPDFNew(TmpArchivoPDF As String, FolioFiscal As String, SubTotal As String, Descuento As String, Total As String, IVA As String, - Moneda As String, FormaDePago As String, NoSerieCertificado As String, FechaCertificacion As DateTime, NoSerieCertificadoContribuyente As String, DTConceptos As DataTable, - SelloCFDi As String, SelloSAT As String, CBB As String, Folio As String, TipodeComprobante As String, CadenaOriginalCFD As String, - RFC As String, Cliente As String, Direccion As String, Colonia As String, NoExt As String, NoInt As String, - CP As String, Ciudad As String, Estado As String, Regimen As String, CondicionPago As String, MetodoPago As String, - NumCtaPago As String, fecha As System.DateTime) As Boolean - Dim Retorno = False - Dim NombreArchivo As String = TmpArchivoPDF - Dim CadenaOriginal As String = (Convert.ToString((Convert.ToString((Convert.ToString("||1.0|") & FolioFiscal) + "|" + FechaCertificacion.ToString("yyyy-MM-dd") + "T" + FechaCertificacion.ToString("HH:mm:ss") + "|") & SelloCFDi) + "|") & NoSerieCertificado) + "||" - Dim RutaFormato As String = String.Format("{0}Empresas\Grales\Formatos\CFDI.rdlc", AppDomain.CurrentDomain.BaseDirectory) - 'Dim ArchivoTempXLS As String = String.Format("{0}\GenSis{1}-{2}", Path.GetDirectoryName(ArchivoBaseXLS), Now.Ticks, Path.GetFileName(ArchivoBaseXLS)) - - Dim Fiscal As String = String.Format("Domicilio Fiscal {0}{1} {2}{0}Col.{3}{0}CP. {4} {5},{6},{7}", vbCr, DomFisCalle, DomFisNoExt, DomFisCol, DomFisCP, - DomFisMun, DomFisEst, DomFisPais) - Try - Dim parametros As New List(Of ReportParameter)() - 'params.Add(New ReportParameter("ArchivoBaseXLS", ArchivoBaseXLS)) - 'params.Add(New ReportParameter("TmpArchivoPDF", TmpArchivoPDF)) - parametros.Add(New ReportParameter("FolioFiscal", FolioFiscal)) - parametros.Add(New ReportParameter("SubTotal", SubTotal.FormatoNumero())) - parametros.Add(New ReportParameter("Descuento", Descuento.FormatoNumero())) - parametros.Add(New ReportParameter("Total", Total.FormatoNumero())) - parametros.Add(New ReportParameter("IVA", IVA.FormatoNumero())) - parametros.Add(New ReportParameter("Moneda", Moneda)) - parametros.Add(New ReportParameter("FormaDePago", FormaDePago)) - parametros.Add(New ReportParameter("NoSerieCertificado", NoSerieCertificado)) - parametros.Add(New ReportParameter("FechaCertificacion", FechaCertificacion.ToString("yyyy-MM-dd") + "T" + FechaCertificacion.ToString("HH:mm:ss"))) - parametros.Add(New ReportParameter("NoSerieCertificadoContribuyente", NoSerieCertificadoContribuyente)) - parametros.Add(New ReportParameter("SelloCFDi", SelloCFDi)) - parametros.Add(New ReportParameter("SelloSAT", SelloSAT)) - parametros.Add(New ReportParameter("CBB", String.Format("file:///{0}", CBB))) - parametros.Add(New ReportParameter("Folio", Folio)) - parametros.Add(New ReportParameter("TipodeComprobante", TipodeComprobante.ToUpper())) - parametros.Add(New ReportParameter("CadenaOriginalCFD", CadenaOriginalCFD)) - parametros.Add(New ReportParameter("RFC", RFC)) - parametros.Add(New ReportParameter("Cliente", Cliente)) - parametros.Add(New ReportParameter("Direccion", Direccion)) - parametros.Add(New ReportParameter("Colonia", Colonia)) - parametros.Add(New ReportParameter("NoExt", NoExt)) - parametros.Add(New ReportParameter("NoInt", NoInt)) - parametros.Add(New ReportParameter("CP", CP)) - parametros.Add(New ReportParameter("Ciudad", Ciudad)) - parametros.Add(New ReportParameter("Estado", Estado)) - parametros.Add(New ReportParameter("Regimen", Regimen)) - parametros.Add(New ReportParameter("CondicionPago", CondicionPago)) - parametros.Add(New ReportParameter("MetodoPago", MetodoPago)) - parametros.Add(New ReportParameter("NumCtaPago", NumCtaPago)) - parametros.Add(New ReportParameter("fecha", fecha.ToString("yyyy-MM-dd") + "T" + fecha.ToString("HH:mm:ss"))) - parametros.Add(New ReportParameter("Fiscal", Fiscal)) - parametros.Add(New ReportParameter("EmiNombre", EmiNombre)) - parametros.Add(New ReportParameter("EmiRFC", EmiRFC)) - parametros.Add(New ReportParameter("NoSerieCertificado", NoSerieCertificado)) - parametros.Add(New ReportParameter("TotalLetra", Total.ToDouble().Texto2Letras(CveMoneda:=If(Moneda = "MXN", 1, If(Moneda = "USD", 2, 3))))) - parametros.Add(New ReportParameter("Empresa", UsuarioActual.Empresa.Empresa)) - - 'params.Add(New ReportParameter("DTConceptos", DTConceptos)) - - Dim rds As New ReportDataSource() - rds.Name = "DsOC" - rds.Value = DTConceptos - Dim Archivo As New System.IO.FileInfo(RutaFormato) - - If Archivo.Exists Then - Dim MR As New ReportViewer() - MR.LocalReport.DataSources.Add(rds) - MR.LocalReport.ReportPath = RutaFormato - MR.ProcessingMode = ProcessingMode.Local - MR.LocalReport.EnableExternalImages = True - MR.LocalReport.SetParameters(parametros) - MR.LocalReport.Refresh() - - - Dim warnings As Warning() = Nothing - Dim streamids As String() = Nothing - Dim mimeType As String = Nothing - Dim encoding As String = Nothing - Dim extension As String = Nothing - Dim bytes As Byte() = Nothing - bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, - warnings) - - Using fs As New FileStream(NombreArchivo, FileMode.Create) - fs.Write(bytes, 0, bytes.Length) - fs.Close() - End Using - Retorno = True - Else - ModExtensiones.GuardaLog(String.Format("No existe formato Base")) - - - End If - Catch ex As Exception - ModExtensiones.GuardaLog(String.Format("Ocurrio un Error al generar el reporte RLDC")) - Retorno = False - End Try - Return Retorno - End Function - Private Sub CreaDTConceptos() - DTConceptos = New DataTable() - DTConceptos.Columns.Add("Consec", GetType(Integer)) - DTConceptos.Columns.Add("Cantidad", GetType(Double)) - DTConceptos.Columns.Add("UM", GetType(String)) - DTConceptos.Columns.Add("PS", GetType(String)) - DTConceptos.Columns.Add("PU", GetType(Double)) - DTConceptos.Columns.Add("IVA", GetType(Double)) - DTConceptos.Columns.Add("Total", GetType(Double)) - End Sub -#End Region - -#Region "D E S C A R G A R - F A C T U R A " - Protected Sub lbDescargar_Click(sender As Object, e As EventArgs) Handles lbDescargar.Click - - Dim Retorno As Boolean = False - - Dim ObjProcess As Process = Nothing - Dim Mensajes As String = "" - Dim error1 As Boolean = False - Dim CountProcesados As Integer = 0 - - - - Try - ObjProcess = New Process() - ObjProcess.StartInfo.RedirectStandardOutput = True - ObjProcess.StartInfo.FileName = Ejecutable - ObjProcess.StartInfo.Arguments = $"--mod dsat2 --cveemp {UsuarioActual.CveEmpresa} --rfc {UsuarioActual.Empresa.RFC} --ciec {UsuarioActual.Empresa.CIEC} --razon {UsuarioActual.Empresa.Empresa} --fi {txtFechaI.Text} --ff {txtFechaF.Text}" - ObjProcess.StartInfo.UseShellExecute = False - ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal - ObjProcess.Start() - - - Dim myStreamReader As StreamReader = ObjProcess.StandardOutput - - 'Read the standard output of the spawned process. - Mensajes = myStreamReader.ReadLine() - If Mensajes.Length > 0 Then - - Dim msgs As String() = Mensajes.Split("|"c) - Dim NFacturas As Integer = 0 - - If msgs.Length >= 2 Then - Try - NFacturas = msgs(0).ToEntero - CountProcesados = msgs(0).ToEntero - Mensajes = $"La actualización se realizó correctamente.
Facturas agregadas: { NFacturas }" - Catch ex As Exception - NFacturas = 0 - Mensajes = "La actualización se realizó correctamente" - End Try - Else - Mensajes = "La descarga se realizó correctamente" - End If - End If - ObjProcess.WaitForExit() - ObjProcess.Close() - Retorno = True - Catch ex As Exception - error1 = True - OnError("Ocurrió un error al ejecutar el actualizador.", ex) - End Try - - If Retorno Then CargaDatos() - - - - - 'Dim Retorno As Boolean = False - ''Codigo anterior no borrar puede hacer el paro - - 'Dim ObjProcess As Process = Nothing - 'Dim Mensajes As String = "" - 'Dim EjecutableUtilerias = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilerias\UtileriasAD.exe") - 'Dim Folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Empresas\") - 'Dim error1 As Boolean = False - 'Dim en As New CultureInfo("en-US") - 'Dim fechai = txtFechaI.Text.Trim.ToDate.ToString("d", en) - 'Dim fechaf = txtFechaF.Text.Trim.ToDate.ToString("d", en) - 'Try - ' ObjProcess = New Process() - ' ObjProcess.StartInfo.RedirectStandardOutput = True - ' ObjProcess.StartInfo.FileName = EjecutableUtilerias - ' ObjProcess.StartInfo.Verb = "runas" - ' ObjProcess.StartInfo.Arguments = $"{UsuarioActual.CveEmpresa} {Folder} 1 {fechai} {fechaf}" - ' ObjProcess.StartInfo.UseShellExecute = False - ' ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal - ' ObjProcess.Start() - ' ObjProcess.WaitForExit() - ' ObjProcess.Close() - 'Catch ex As Exception - ' error1 = True - ' OnError("Ocurrió un error al ejecutar el actualizador.", ex) - 'End Try - - '' ProcesaBuzon() - - End Sub - - - 'Private Sub ProcesaBuzon() - ' Dim ObjProcess As Process = Nothing - ' Dim Mensajes As String = "" - ' Dim EjecutableUtilerias = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilerias\ADSUtilerias.exe") - ' Dim Folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Empresas\") - ' Dim error1 As Boolean = False - ' Dim en As New CultureInfo("en-US") - ' Dim fechai = txtFechaI.Text.Trim.ToDate.ToString("d", en) - ' Dim fechaf = txtFechaF.Text.Trim.ToDate.ToString("d", en) - ' Dim Salida As String = "" - ' Try - ' ObjProcess = New Process() - ' ObjProcess.StartInfo.RedirectStandardOutput = True - ' ObjProcess.StartInfo.FileName = EjecutableUtilerias - ' ObjProcess.StartInfo.Verb = "runas" - ' ObjProcess.StartInfo.Arguments = $"--mod dsat --e {UsuarioActual.CveEmpresa} --op 1 --fd {Folder} --fi {fechai} --ff {fechaf}" - ' ObjProcess.StartInfo.UseShellExecute = False - ' ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal - ' ObjProcess.Start() - ' Salida = ObjProcess.StandardOutput.ReadToEnd() - ' ObjProcess.WaitForExit() - ' ObjProcess.Close() - ' Catch ex As Exception - ' error1 = True - ' OnError("Ocurrió un error al ejecutar el actualizador.", ex) - ' End Try - 'End Sub - -#End Region - -#Region "B I T A C O R A" - Private Sub CargaGvBitacora() - Dim ObjGral As New ClsGenerales - If ObjGral.GetHistorialBitacoraRemoveGet("Compras", UsuarioActual.CveEmpresa) Then - GvBitacora.DataSource = ObjGral.DtResultados - ObjGral.Dispose() - End If - GvBitacora.DataBind() - End Sub - - Private Sub BtnRemove_Click(sender As Object, e As EventArgs) Handles BtnRemove.Click - Dim Borrar As Boolean = False - If Not TxtDescripcion.Text = "" Then - Dim ObjGral As New ClsGenerales - If ObjGral.AddHistorialBitacora(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 1, TxtDescripcion.Text, "Compras", Folio1 + " / " + Proveedor) Then - Borrar = True - End If - ObjGral.Dispose() - If Borrar = True Then - Dim ObjCompras As New ClsCompras - If ObjCompras.DeleteFactura(CveFactura) Then - GvD.EditIndex = -1 - RegistraScript(String.Format("$('#{0}').modal('hide');", "divDescripcion")) - Alert("La factura se eliminó correctamente.", TipoMensaje.MsgInformacion) - CargaDatos() - UpBitacora.Update() - End If - - ObjCompras.Dispose() - - End If - End If - CargaGvBitacora() - UpBitacora.Update() - End Sub - Private Sub BtnEliminarPago_Click(sender As Object, e As EventArgs) Handles BtnEliminarPago.Click - Dim Borrar As Boolean = False - If Not TxtDescripcion.Text = "" Then - Dim ObjGral As New ClsGenerales - If ObjGral.AddHistorialBitacora(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 1, TxtDescripcion.Text, "Compras", Folio1 + " / " + Proveedor) Then - Borrar = True - End If - ObjGral.Dispose() - If Borrar = True Then - Dim ObjCompras As New ClsCompras - If ObjCompras.DeleteFactura(CveFactura) Then - GvPagos.EditIndex = -1 - RegistraScript("$('#divDescripcionPago').modal('hide');") - Alert("La factura se eliminó correctamente.", TipoMensaje.MsgInformacion) - CargaDatos() - UpBitacora.Update() - End If - - ObjCompras.Dispose() - End If - End If - CargaGvBitacora() - UpBitacora.Update() - End Sub - - Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles BtnMostrar.Click - GvBitacora.Visible = True - BtnOcultar.Visible = True - BtnMostrar.Visible = False - UpBitacora.Update() - End Sub - - Private Sub BtnOcultar_Click(sender As Object, e As EventArgs) Handles BtnOcultar.Click - GvBitacora.Visible = False - BtnOcultar.Visible = False - BtnMostrar.Visible = True - UpBitacora.Update() + End Get + Set + m_Serie = Value + End Set + End Property + Private m_Serie As String + + Private _fecha As String + Private Property fecha() As String + Get + Return _fecha + End Get + Set + _fecha = Value + End Set + End Property + + Private _tipoDeComprobante As String + Private Property tipoDeComprobante() As String + Get + Return _tipoDeComprobante + End Get + Set + _tipoDeComprobante = Value + End Set + End Property + + Private _formaDePago As String + Private Property formaDePago() As String + Get + Return _formaDePago + End Get + Set + _formaDePago = Value + End Set + End Property + + Private _subTotal As String + Private Property subTotal() As String + Get + Return _subTotal + End Get + Set + _subTotal = Value + End Set + End Property + + Private _descuento As String + Private Property descuento() As String + Get + Return _descuento + End Get + Set + _descuento = Value + End Set + End Property + Private _total As String + Private Property total() As String + Get + Return _total + End Get + Set + _total = Value + End Set + End Property + + Private _moneda As String + Private Property moneda() As String + Get + Return _moneda + End Get + Set + _moneda = Value + End Set + End Property + + Private _metodoDePago As String + Private Property metodoDePago() As String + Get + Return _metodoDePago + End Get + Set + _metodoDePago = Value + End Set + End Property + + Private _condicionesDePago As String + Private Property condicionesDePago() As String + Get + Return _condicionesDePago + End Get + Set + _condicionesDePago = Value + End Set + End Property + + Private _LugarExpedicion As String + Private Property LugarExpedicion() As String + Get + Return _LugarExpedicion + End Get + Set + _LugarExpedicion = Value + End Set + End Property + + Private _NumCtaPagoNumCtaPago As String + Private Property NumCtaPagoNumCtaPago() As String + Get + Return _NumCtaPagoNumCtaPago + End Get + Set + _NumCtaPagoNumCtaPago = Value + End Set + End Property + + Private _noCertificado As String + Private Property noCertificado() As String + Get + Return _noCertificado + End Get + Set + _noCertificado = Value + End Set + End Property + + ''Emisor + Private _EmiRFC As String + Private Property EmiRFC() As String + Get + Return _EmiRFC + End Get + Set + _EmiRFC = Value + End Set + End Property + + Private _EmiNombre As String + Private Property EmiNombre() As String + Get + Return _EmiNombre + End Get + Set + _EmiNombre = Value + End Set + End Property + + Private _DomFisCalle As String + Private Property DomFisCalle() As String + Get + Return _DomFisCalle + End Get + Set + _DomFisCalle = Value + End Set + End Property + + Private _DomFisNoExt As String + Private Property DomFisNoExt() As String + Get + Return _DomFisNoExt + End Get + Set + _DomFisNoExt = Value + End Set + End Property + 'Dim _DomFisNoInt As String + + Private _DomFisCol As String + Private Property DomFisCol() As String + Get + Return _DomFisCol + End Get + Set + _DomFisCol = Value + End Set + End Property + + Private _DomFisCP As String + Private Property DomFisCP() As String + Get + Return _DomFisCP + End Get + Set + _DomFisCP = Value + End Set + End Property + + Private _DomFisMun As String + Private Property DomFisMun() As String + Get + Return _DomFisMun + End Get + Set + _DomFisMun = Value + End Set + End Property + + Private _DomFisLoc As String + Private Property DomFisLoc() As String + Get + Return _DomFisLoc + End Get + Set + _DomFisLoc = Value + End Set + End Property + + Private _DomFisEst As String + Private Property DomFisEst() As String + Get + Return _DomFisEst + End Get + Set + _DomFisEst = Value + End Set + End Property + + Private _DomFisPais As String + Private Property DomFisPais() As String + Get + Return _DomFisPais + End Get + Set + _DomFisPais = Value + End Set + End Property + + Private _ExpEnCalle As String + Private Property ExpEnCalle() As String + Get + Return _ExpEnCalle + End Get + Set + _ExpEnCalle = Value + End Set + End Property + + Private _ExpEnNoExt As String + Private Property ExpEnNoExt() As String + Get + Return _ExpEnNoExt + End Get + Set + _ExpEnNoExt = Value + End Set + End Property + + + Private ExpEnCol As String + + Private _ExpEnCP As String + Private Property ExpEnCP() As String + Get + Return _ExpEnCP + End Get + Set + _ExpEnCP = Value + End Set + End Property + + Private _ExpEnMun As String + Private Property ExpEnMun() As String + Get + Return _ExpEnMun + End Get + Set + _ExpEnMun = Value + End Set + End Property + + Private _ExpEnLoc As String + Private Property ExpEnLoc() As String + Get + Return _ExpEnLoc + End Get + Set + _ExpEnLoc = Value + End Set + End Property + + Private _ExpEnEst As String + Private Property ExpEnEst() As String + Get + Return _ExpEnEst + End Get + Set + _ExpEnEst = Value + End Set + End Property + Private _ExpEnPais As String + Private Property ExpEnPais() As String + Get + Return _ExpEnPais + End Get + Set + _ExpEnPais = Value + End Set + End Property + + Private _Regimen As String + Private Property Regimen() As String + Get + Return _Regimen + End Get + Set + _Regimen = Value + End Set + End Property + + ''Receptor + Private _RecRfc As String + Private Property RecRfc() As String + Get + Return _RecRfc + End Get + Set + _RecRfc = Value + End Set + End Property + + Private _RecNombre As String + Private Property RecNombre() As String + Get + Return _RecNombre + End Get + Set + _RecNombre = Value + End Set + End Property + + Private _DomRecCalle As String + Private Property DomRecCalle() As String + Get + Return _DomRecCalle + End Get + Set + _DomRecCalle = Value + End Set + End Property + + Private _DomRecFisNoExt As String + Private Property DomRecFisNoExt() As String + Get + Return _DomRecFisNoExt + End Get + Set + _DomRecFisNoExt = Value + End Set + End Property + + Private _DomRecFisNoInt As String + Private Property DomRecFisNoInt() As String + Get + Return _DomRecFisNoInt + End Get + Set + _DomRecFisNoInt = Value + End Set + End Property + + Private _DomRecCol As String + Private Property DomRecCol() As String + Get + Return _DomRecCol + End Get + Set + _DomRecCol = Value + End Set + End Property + + Private _DomRecCP As String + Private Property DomRecCP() As String + Get + Return _DomRecCP + End Get + Set + _DomRecCP = Value + End Set + End Property + + Private _DomRecMun As String + Private Property DomRecMun() As String + Get + Return _DomRecMun + End Get + Set + _DomRecMun = Value + End Set + End Property + + Private _DomRecLoc As String + Private Property DomRecLoc() As String + Get + Return _DomRecLoc + End Get + Set + _DomRecLoc = Value + End Set + End Property + + Private _DomRecEst As String + Private Property DomRecEst() As String + Get + Return _DomRecEst + End Get + Set + _DomRecEst = Value + End Set + End Property + + Private _DomRecPais As String + Private Property DomRecPais() As String + Get + Return _DomRecPais + End Get + Set + _DomRecPais = Value + End Set + End Property + + 'IVA + Private _TrasladoIVA As Double + Private Property TrasladoIVA() As Double + Get + Return _TrasladoIVA + End Get + Set + _TrasladoIVA = Value + End Set + End Property + + 'TFD + Private _TFDUUID As String + Private Property TFDUUID() As String + Get + Return _TFDUUID + End Get + Set + _TFDUUID = Value + End Set + End Property + + Private _TFDFechaTimbrado As String + Private Property TFDFechaTimbrado() As String + Get + Return _TFDFechaTimbrado + End Get + Set + _TFDFechaTimbrado = Value + End Set + End Property + + Private _TFDSelloCFD As String + Private Property TFDSelloCFD() As String + Get + Return _TFDSelloCFD + End Get + Set + _TFDSelloCFD = Value + End Set + End Property + + Private _TFDNoCertSAT As String + Private Property TFDNoCertSAT() As String + Get + Return _TFDNoCertSAT + End Get + Set + _TFDNoCertSAT = Value + End Set + End Property + + Private _TFDSelloSAT As String + Private Property TFDSelloSAT() As String + Get + Return _TFDSelloSAT + End Get + Set + _TFDSelloSAT = Value + End Set + End Property + +#End Region + + Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load + If Not Page.IsPostBack Then + ChecandoCorreo = False + 'GvD.Columns(GvD.Columns.Count - 1).Visible = True '(UsuarioActual.CveRol = 1) + 'GvD.Columns(GvD.Columns.Count - 2).Visible = (UsuarioActual.CveRol = 1) + 'GvD.Columns(GvD.Columns.Count - 3).Visible = (UsuarioActual.CveRol = 1) + ViewState("Orden") = String.Empty + + txtFechaI.Text = Now.AddMonths(-1).FirstDayOfMonth().ToShortDateString ' String.Format("01/01/{0}", If(Now.Month > 6, Now.Year, Now.Year - 1)) + + txtFechaF.Text = Now.ToShortDateString 'txtFechaI.Text.ToDate.AddMonths(1).AddDays(-1).ToShortDateString + + Destino = String.Format("{0}Compras\", UsuarioActual.Empresa.Ruta) 'string.format("{0}Empresas\{1}\Compras\", AppDomain.CurrentDomain.BaseDirectory ,UsuarioActual.CveEmpresa & "\Compras\" + Ejecutable = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilerias\ADSUtilerias.exe") + Form.DefaultButton = BtnConsultar.UniqueID + + DdlResponsable.DataSource = GlobalDTUsuarioResponsable.FiltraParametros(String.Format("CveEmpresa = {0}", UsuarioActual.CveEmpresa)) + DdlResponsable.DataBind() + DdlResponsable.Items.Insert(0, New ListItem("Todos", "-1")) + + DdlClasificacionProv.DataSource = GlobalDTProveedorClasificacion(UsuarioActual.CveEmpresa) + DdlClasificacionProv.DataBind() + DdlClasificacionProv.Items.Insert(0, New ListItem("Todos", "-1")) + + TxtFechaBitInicio.Text = Now.ToString("dd/MM/yyyy") + TxtFechaBitFin.Text = Now.ToString("dd/MM/yyyy") + + TxtFolio.Focus() + + If UsuarioActual.Sesion("eFact-Proveedor").ToString <> "" Then TxtProveedor.Text = UsuarioActual.Sesion("eFact-Proveedor").ToString.Trim + If UsuarioActual.Sesion("eFact-FI").ToString <> "" Then txtFechaI.Text = UsuarioActual.Sesion("eFact-FI").ToString.Trim + If UsuarioActual.Sesion("eFact-FF").ToString <> "" Then txtFechaF.Text = UsuarioActual.Sesion("eFact-FF").ToString.Trim + If UsuarioActual.CveUsuario = 100 Then lbDescargar.Visible = True + + If UsuarioActual.TienePermisoProceso(81) Then GvD.Columns(11).Visible = True : GvD.Columns(12).Visible = True + If UsuarioActual.TienePermisoProceso(206) Then GvD.Columns(10).Visible = False + If UsuarioActual.Empresa.Funcionalidad(156) = "1" Then GvD.Columns(5).Visible = True + CargaGvBitacora() + CargaDatos() + End If + removeasincevent() + End Sub + 'Private Sub CompararString() + ' Dim cont As Integer = 10000 + ' Dim Sb As New StringBuilder + ' For i = 0 To cont + ' Sb.AppendFormat("a{0}", i) + ' Next + 'End Sub + + Protected Sub BtnConsultar_Click(sender As Object, e As System.EventArgs) Handles BtnConsultar.Click + CargaDatos() End Sub -#End Region + Private Sub CargaDatos() + Dim Folio, RFC, Proveedor As String + Folio = If(TxtFolio.Text.Trim.Length > 0, String.Format("%{0}%", TxtFolio.Text.Trim.ToUpper), "-1") + RFC = "-1" 'If(TxtRFC.Text.Trim.Length > 0, TxtRFC.Text.Trim, "-1") + Proveedor = If(TxtProveedor.Text.Trim.Length > 0, String.Format("%{0}%", TxtProveedor.Text.Trim.ToUpper.Replace(" ", "%")), "-1") + + UsuarioActual.Sesion("eFact-Proveedor") = TxtProveedor.Text.Trim + If Folio = "" Then UsuarioActual.Sesion("eFact-FI") = txtFechaI.Text + If Folio = "" Then UsuarioActual.Sesion("eFact-FF") = txtFechaF.Text + Dim FechaI, FechaF As Date + FechaI = txtFechaI.Text.ToDate + FechaF = txtFechaF.Text.ToDate + If Folio <> "-1" Then + FechaI = MinFecha + FechaF = MaxFecha + txtFechaI.Text = MinFecha.ToString + txtFechaF.Text = Now.ToShortDateString + End If + Dim DtPagos As DataTable = Nothing + Dim ObjDatos As New ClsCompras + If ObjDatos.GetFacturas(-1, Folio, FechaI, FechaF, RFC, Proveedor, DdlValidado.SelectedValue.ToEntero, DdlResponsable.SelectedValue.ToEntero, DdlClasificacionProv.SelectedValue.ToEntero, DdlCveTipoProveedor.SelectedValue.ToEntero, DdlTipoComprobante.SelectedValue.ToString, UsuarioActual.CveEmpresa) Then + If ObjDatos.DtResultados.Rows.Count > 0 Then + GvD.DataSource = ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P'") '.AsEnumerable().Take(100).CopyToDataTable() + DtPagos = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P'") + Else + GvD.DataSource = Nothing + End If + End If + LblRegistros.Text = String.Format("{0} Registros", ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P'").Rows.Count.ToString("N0")) + LblTotalPagos.Text = String.Format("{0} Pagos", ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P'").Rows.Count.ToString("N0")) + ObjDatos.Dispose() + + If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then + GvPagos.DataSource = DtPagos + End If + GvPagos.DataBind() + UpPagos.Update() + + GvD.DataBind() + + UpDatos.Update() + UPRegistros.Update() + End Sub + + Protected Sub LnkExportar_Click(sender As Object, e As EventArgs) Handles LnkExportar.Click + GenerarPDF("Excel") + End Sub + + Protected Sub ImgRefresh_Click(sender As Object, e As EventArgs) Handles ImgRefresh.Click + + If VerificaCorreo() Then + CargaDatos() + End If + + End Sub + + Private Function VerificaCorreo(Optional ValidaRowCount As Boolean = False) As Boolean + Dim Retorno As Boolean = False + + Dim ObjProcess As Process = Nothing + Dim Mensajes As String = "" + Dim error1 As Boolean = False + Dim CountProcesados As Integer = 0 + + Try + ObjProcess = New Process() + ObjProcess.StartInfo.RedirectStandardOutput = True + ObjProcess.StartInfo.FileName = Ejecutable + ObjProcess.StartInfo.Arguments = $"--mod eFacturas --e {UsuarioActual.CveEmpresa} --c " + ObjProcess.StartInfo.UseShellExecute = False + ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal + ObjProcess.Start() + + + Dim myStreamReader As StreamReader = ObjProcess.StandardOutput + + 'Read the standard output of the spawned process. + Mensajes = myStreamReader.ReadLine() + If Mensajes.Length > 0 Then + + Dim msgs As String() = Mensajes.Split("|"c) + Dim NFacturas As Integer = 0 + + + + + If msgs.Length >= 2 Then + Try + NFacturas = msgs(0).ToEntero + CountProcesados = msgs(0).ToEntero + Mensajes = $"La actualización se realizó correctamente.
Facturas agregadas: { NFacturas }" + Catch ex As Exception + NFacturas = 0 + Mensajes = "La actualización se realizó correctamente" + End Try + Else + Mensajes = "La actualización se realizó correctamente" + End If + + + + LnkNoRecibidas_Click(LnkNoRecibias, EventArgs.Empty, ValidaRowCount:=ValidaRowCount) + + + 'Else + ' Dim Str As New StringBuilder + ' Dim conta As Integer = 1 + ' Str.Append("Se encontraron las siguientes facturas con problema:
") + ' Dim ARR As String() = Mensajes.Split("&"c) + ' Dim ArrDetalle As String() + ' For Each d As String In ARR + ' Str.Append("") + ' ArrDetalle = d.Split("|"c) + ' For Each det As String In ArrDetalle + ' Str.AppendFormat("", If(conta Mod 2 = 0, "TextoAlterno", "Texto"), det) + ' Next + ' Str.Append("") + ' conta += 1 + ' Next + ' Str.Append("
SerieFolioFechaProveedorImporteMotivo
{1}
") + ' Mensajes = Str.ToString + End If + ObjProcess.WaitForExit() + ObjProcess.Close() + Retorno = True + Catch ex As Exception + error1 = True + OnError("Ocurrió un error al ejecutar el actualizador.", ex) + End Try + + + LblFacturasProcesadasCount.Text = "Procesados:" & CountProcesados + RegistraScript("$('#ModalBitacoraEfacturas').modal()") + CargaDatosBitacora() + + 'If Not error1 Then Alert(Mensajes, TipoMensaje.MsgInformacion) + + + Return Retorno + End Function + + Protected Sub BtnBuscarBitacora_Click(sender As Object, e As EventArgs) Handles BtnBuscarBitacora.Click + CargaDatosBitacora() + End Sub + + + Protected Sub LnkBitacotaFacturas_Click(sender As Object, e As EventArgs) + + RegistraScript("$('#ModalBitacoraEfacturas').modal()") + CargaDatosBitacora() + End Sub + + + Private Sub CargaDatosBitacora() + + LblFacturasProcesadasCount.Text = "" + + Dim ObjCompras As New ClsCompras + + If ObjCompras.GetFacturasBitacoraGet(TxtFechaBitInicio.Text.ToDate, TxtFechaBitFin.Text.ToDate, UsuarioActual.CveEmpresa) Then + GvBitacoraEfacturas.DataSource = ObjCompras.DtResultados + Else + GvBitacoraEfacturas.DataSource = Nothing + End If + + ObjCompras.Dispose() + GvBitacoraEfacturas.DataBind() + UpModalBitacoraEfacturas.Update() + + End Sub + +#Region "G V D A T O S" + Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvD.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + e.Row.FindControl("lnkRegenerarPDF").Visible = True ' (UsuarioActual.CveRol = 1) + 'e.Row.FindControl("lnkDownPdf").Visible = (UsuarioActual.CveRol = 1) + 'e.Row.FindControl("lnkXML").Visible = (UsuarioActual.CveRol = 1) + Select Case e.Row.DBCampo("TipoComprobante") + Case "I" + e.Row.FCLabel("LtTipoComprobante").Text = "Ingreso" + e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-success" + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Ingreso") + Case "E" + e.Row.FCLabel("LtTipoComprobante").Text = "Egreso" + e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-warning" + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Egreso") + Case "P" + e.Row.FCLabel("LtTipoComprobante").Text = "Pago" + e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-primary" + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Complemento Pago") + End Select + + e.Row.Cells(2).Attributes.Add("data-order", e.Row.DBCampo("FechaFactura").ToDate.Ticks.ToString) + + If File.Exists(String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))) Then + e.Row.FCLiteral("LtlXML").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("XML"))) + If e.Row.DBCampo("TipoComprobante") = "P" Then + e.Row.FCLinkButton("LnkAgregarPago").Visible = True + End If + Else + e.Row.FCLiteral("LtlXML").Text = "N/D" + If e.Row.DBCampo("TipoComprobante") = "P" Then + e.Row.FCLinkButton("LnkAgregarPago").Visible = False + End If + End If + + If File.Exists(String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))) Then + e.Row.FCLiteral("LtlPDF").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("PDF"))) + Else + e.Row.FCLiteral("LtlPDF").Text = "N/D" + End If + + If e.Row.DBCampo("FueValidado").Contiene("1", "2", "3") Then + e.Row.FCLinkButton("ImgValidarCFDi").Visible = False + e.Row.FCLiteral("LtlValidado").Visible = True + If e.Row.DBCampo("FueValidado") = "2" Then + e.Row.FCLiteral("LtlValidado").Text = "Cancelada" + e.Row.ForeColor = Drawing.Color.Red + e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Red + ElseIf e.Row.DBCampo("FueValidado") = "3" Then + e.Row.FCLiteral("LtlValidado").Text = "Omitida" + e.Row.ForeColor = Drawing.Color.Gray + e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Gray + End If + Else + If e.Row.DBCampo("TipoFactura") = "CFD" Then + e.Row.FCLinkButton("ImgValidarCFDi").CommandName = "ValidarCFD" + e.Row.FCLinkButton("ImgValidarCFDi").OnClientClick = "return confirm('La factura se validó en el sitio del SAT de comprobantes fiscales?');" + End If + e.Row.FCLinkButton("ImgValidarCFDi").Visible = True + e.Row.FCLiteral("LtlValidado").Visible = False + + End If + If e.Row.DBCampo("CveCompra") <> "" Then + e.Row.FCLiteral("LtlFolio").Text = String.Format("{1}", e.Row.DBCampo("CveCompra"), e.Row.DBCampo("SerieFolio")) '1\Compras\GAPC480413QL3\A-69.xml + End If + + If e.Row.DBCampo("CveProveedor") = "" Then + e.Row.FCHyperLink("HplProv").Visible = True + e.Row.FCHyperLink("HplProv").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveFactura={0}", e.Row.DBCampo("CveFactura")) + + Else + + Dim BloquePorComplemento As Integer = e.Row.DataKey("BloquePorComplemento").ToEntero + + e.Row.FCHyperLink("HplProveedor").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", e.Row.DBCampo("CveProveedor")) + + If e.Row.DBCampo("CveCompra") = "" AndAlso (e.Row.DBCampo("FueValidado") = "1") Then ' OrElse UsuarioActual.CveEmpresa = 66 + + If e.Row.DBCampo("TipoComprobante") = "P" Then + e.Row.FCHyperLink("HplAgregar").Visible = False + Else + e.Row.FCHyperLink("HplAgregar").NavigateUrl = String.Format("/Compras/Compras.aspx?CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCDe")) + + If BloquePorComplemento > 0 Then + e.Row.FCHyperLink("HplAgregar").Enabled = False + e.Row.FCHyperLink("HplAgregar").Attributes.Add("title", "Bloqueo por complemento") + End If + + End If + + Else + e.Row.FCHyperLink("HplAgregar").Visible = False + End If + + + + End If + + + If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then + End If + + End If + End Sub + Protected Sub GvDatos_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvD.RowUpdating + Dim ObjDatos As New ClsCompras + Dim FueValidado As Integer = 0 + If GvD.Rows(e.RowIndex).FCCheckBox("ChkFueValidado").Checked Then FueValidado = 1 + If ObjDatos.UpdateEstatus(FueValidado, GvD.DataKeys(e.RowIndex).Value.ToString.ToEntero) Then + GvD.EditIndex = -1 + BtnConsultar_Click(sender, e) + End If + ObjDatos.Dispose() + + + CargaDatos() + End Sub + Protected Sub GvDatos_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvD.RowCancelingEdit + GvD.EditIndex = -1 + CargaDatos() + End Sub + + + Protected Sub imgD_Click(sender As Object, e As EventArgs) + Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) + CveFactura = gvRow.DataKey("CveFactura").ToString.ToEntero + Folio1 = gvRow.DataKey("SerieFolio").ToString + Proveedor = gvRow.DataKey("NombreProveedor").ToString + TxtDescripcion.Text = "" + RegistraScript("$('#divDescripcion').modal()") + UpDescripcion.Update() + End Sub + + Protected Sub GvDatos_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvD.RowEditing + GvD.EditIndex = e.NewEditIndex + CargaDatos() + End Sub + + Protected Sub GvDatos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvD.RowCommand + Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton) + Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow) + Dim ObjDatos As New ClsCompras + Dim Correcto As Boolean = False + + Select Case e.CommandName + Case "ValidarCFDi" + Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), GvRow.DataKey("Total").ToDecimal) + If ObjValidacion.EsValida > 0 Then + If ObjValidacion.EsValida = 2 Then + Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgInformacion) + End If + Correcto = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) + Else + Alert("La Factura no se pudo validar.", TipoMensaje.MsgAdvertencia) + End If + ObjValidacion.Dispose() + Case "ValidarCFD" + Correcto = ObjDatos.UpdateEstatus(1, GvRow.DataKey("CveFactura").ToEntero) + + Case "Omitir" + Correcto = ObjDatos.UpdateEstatus(3, GvRow.DataKey("CveFactura").ToEntero) + End Select + + ObjDatos.Dispose() + If Correcto Then + CargaDatos() + End If + + End Sub +#End Region + +#Region "G V P A G O S" + Protected Sub GvPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvPagos.RowDataBound + If e.Row.RowType = DataControlRowType.DataRow Then + + If e.Row.DBCampo("TipoComprobante") = "P" Then + e.Row.FCLabel("LtTipoComprobante").Text = "Pago" + e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-primary" + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") + e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Complemento Pago") + End If + + e.Row.Cells(2).Attributes.Add("data-order", e.Row.DBCampo("FechaFactura").ToDate.Ticks.ToString) + + If File.Exists(String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))) Then + e.Row.FCLiteral("LtlXML").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("XML"))) + If e.Row.DBCampo("TipoComprobante") = "P" And e.Row.DBCampo("FueValidado") = "1" Then + e.Row.FCLinkButton("LnkAgregarPagoP").Visible = True + End If + Else + e.Row.FCLiteral("LtlXML").Text = "N/D" ' String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML")) ' + If e.Row.DBCampo("TipoComprobante") = "P" Then + e.Row.FCLinkButton("LnkAgregarPagoP").Visible = False + End If + End If + + If File.Exists(String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))) Then + e.Row.FCLiteral("LtlPDF").Text = String.Format("Ver", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("PDF"))) + Else + e.Row.FCLiteral("LtlPDF").Text = "N/D" ' String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF")) + End If + + If e.Row.DBCampo("FueValidado").Contiene("1", "2", "3") Then + e.Row.FCLinkButton("ImgValidarCFDi").Visible = False + e.Row.FCLiteral("LtlValidado").Visible = True + If e.Row.DBCampo("FueValidado") = "2" Then + e.Row.FCLiteral("LtlValidado").Text = "Cancelada" + e.Row.ForeColor = Drawing.Color.Red + e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Red + ElseIf e.Row.DBCampo("FueValidado") = "3" Then + e.Row.FCLiteral("LtlValidado").Text = "Omitida" + e.Row.ForeColor = Drawing.Color.Gray + e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Gray + End If + Else + If e.Row.DBCampo("TipoFactura") = "CFD" Then + e.Row.FCLinkButton("ImgValidarCFDi").CommandName = "ValidarCFD" + e.Row.FCLinkButton("ImgValidarCFDi").OnClientClick = "return confirm('La factura se validó en el sitio del SAT de comprobantes fiscales?');" + End If + e.Row.FCLinkButton("ImgValidarCFDi").Visible = True + e.Row.FCLiteral("LtlValidado").Visible = False + + End If + If e.Row.DBCampo("CveCompra") <> "" Then + e.Row.FCLiteral("LtlFolio").Text = String.Format("{1}", e.Row.DBCampo("CveCompra"), e.Row.DBCampo("SerieFolio")) '1\Compras\GAPC480413QL3\A-69.xml + End If + + If e.Row.DBCampo("CveProveedor") = "" Then + e.Row.FCHyperLink("HplProv").Visible = True + e.Row.FCHyperLink("HplProv").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveFactura={0}", e.Row.DBCampo("CveFactura")) + + Else + e.Row.FCHyperLink("HplProveedor").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", e.Row.DBCampo("CveProveedor")) + + If e.Row.DBCampo("CveCompra") = "" AndAlso (e.Row.DBCampo("FueValidado") = "1") Then ' OrElse UsuarioActual.CveEmpresa = 66 + ' + If e.Row.DBCampo("TipoComprobante") = "P" Then + e.Row.FCHyperLink("HplAgregarP").Visible = False + Else + e.Row.FCHyperLink("HplAgregarP").NavigateUrl = String.Format("/Compras/Compras.aspx?CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCDe")) + End If + + + Else + 'si ya tiene cvecompra es que ya está validada + e.Row.FCHyperLink("HplAgregarP").Visible = False + End If + + End If + + + Dim CveComplementoPagoCompra As Integer = e.Row.DataKey("CveComplementoPagoCompra").ToString.ToEntero + + + If CveComplementoPagoCompra > 0 Then + e.Row.FCLinkButton("LnkAgregarPagoP").CssClass = "btn btn-sm green" + e.Row.FCLinkButton("LnkAgregarPagoP").Text = "" + 'e.Row.FCLinkButton("LnkAgregarPagoP").ToolTip = "Ver vinculación" + e.Row.FCLinkButton("LnkAgregarPagoP").Attributes.Add("Title", "Ver vinculación") + Else + e.Row.FCLinkButton("LnkAgregarPagoP").CssClass = "btn btn-sm blue" + e.Row.FCLinkButton("LnkAgregarPagoP").Text = "" + 'e.Row.FCLinkButton("LnkAgregarPagoP").ToolTip = "Vincular Pago" + e.Row.FCLinkButton("LnkAgregarPagoP").Attributes.Add("Title", "Vincular Pago") + End If + + End If + End Sub + Protected Sub GvPagos_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvPagos.RowUpdating + Dim ObjDatos As New ClsCompras + Dim FueValidado As Integer = 0 + If GvPagos.Rows(e.RowIndex).FCCheckBox("ChkFueValidado").Checked Then FueValidado = 1 + If ObjDatos.UpdateEstatus(FueValidado, GvD.DataKeys(e.RowIndex).Value.ToString.ToEntero) Then + GvPagos.EditIndex = -1 + End If + ObjDatos.Dispose() + CargaDatos() + End Sub + Protected Sub GvPagos_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvPagos.RowCancelingEdit + GvPagos.EditIndex = -1 + CargaDatos() + End Sub + Protected Sub GvPagos_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvPagos.RowEditing + GvPagos.EditIndex = e.NewEditIndex + CargaDatos() + End Sub + Protected Sub imgDP_Click(sender As Object, e As EventArgs) + Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) + CveFactura = gvRow.DataKey("CveFactura").ToString.ToEntero + Folio1 = gvRow.DataKey("SerieFolio").ToString + Proveedor = gvRow.DataKey("NombreProveedor").ToString + TxtDescripcion.Text = "" + RegistraScript("$('#divDescripcionPago').modal()") + UpDescripcionPago.Update() + End Sub + + Protected Sub GvPagos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPagos.RowCommand + Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton) + Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow) + Dim ObjDatos As New ClsCompras + Dim Correcto As Boolean = False + + Select Case e.CommandName + Case "ValidarCFDi" + Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), 0) + If ObjValidacion.EsValida > 0 Then + If ObjValidacion.EsValida = 2 Then + Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgInformacion) + End If + Correcto = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) + Else + Alert("La Factura no se pudo validar.", TipoMensaje.MsgAdvertencia) + End If + ObjValidacion.Dispose() + Case "ValidarCFD" + Correcto = ObjDatos.UpdateEstatus(1, GvRow.DataKey("CveFactura").ToEntero) + + Case "Omitir" + Correcto = ObjDatos.UpdateEstatus(3, GvRow.DataKey("CveFactura").ToEntero) + End Select + + ObjDatos.Dispose() + If Correcto Then + CargaDatos() + End If + End Sub +#End Region + Protected Sub ImgCFDiMasivo_Click(sender As Object, e As EventArgs) Handles LnkCFDiMasivo.Click + Dim ObjDatos As New ClsCompras + ObjDatos.IniciaTransacSQL() + Dim ErrorTrans As Boolean = False + If Tab.ActiveTabIndex = 0 Then + For Each GvRow As GridViewRow In GvD.Rows + If GvRow.DataKey("TipoFactura") = "CFDi" AndAlso GvRow.DataKey("FueValidado").Contiene("0", "1") Then + Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), GvRow.DataKey("Total").ToDecimal) + If ObjValidacion.EsValida > 0 Then + If Not ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) Then + ErrorTrans = True + End If + End If + ObjValidacion.Dispose() + End If + Next + ElseIf Tab.ActiveTabIndex = 1 Then + For Each GvRow As GridViewRow In GvPagos.Rows + If GvRow.DataKey("TipoFactura") = "CFDi" AndAlso GvRow.DataKey("FueValidado").Contiene("0", "1") Then + Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), 0) + If ObjValidacion.EsValida > 0 Then + If Not ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero) Then + ErrorTrans = True + End If + End If + ObjValidacion.Dispose() + End If + Next + End If + If Not ErrorTrans Then + ObjDatos.Commit() + Alert("La verificación masiva ha terminado", TipoMensaje.MsgInformacion) + CargaDatos() + Else + ObjDatos.RollBack() + End If + ObjDatos.Dispose() + End Sub + Protected Sub LnkNoRecibidas_Click(sender As Object, e As EventArgs, Optional ValidaRowCount As Boolean = False) Handles LnkNoRecibias.Click + Dim DtNoRecibidas As New DataTable + Dim Ruta As String = String.Format("{0}\Empresas\{1}\Compras\NoRecibidas-{1}.xml", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa) + Dim Str As New StringBuilder + If IO.File.Exists(Ruta) Then + DtNoRecibidas.ReadXml(Ruta) + + Dim conta As Integer = 1 + Str.Append("Se encontraron las siguientes facturas con problema:
") + + For Each dr As DataRow In DtNoRecibidas.FiltraParametros("", "Fecha DESC").Rows + + Str.AppendFormat("", If(conta Mod 2 = 0, "TextoAlterno", "Texto")) + + Str.AppendFormat("", dr("Serie")) + Str.AppendFormat("", dr("Folio")) + Str.AppendFormat("", If(dr("Fecha").ToString <> "", dr("Fecha").ToString.ToDate.ToShortDateString, "")) + Str.AppendFormat("", dr("Proveedor")) + Str.AppendFormat("", dr("Importe").ToString.ToDouble.FormatoNumero) + Str.AppendFormat("", dr("Motivo")) + Str.AppendFormat("", If(dr("Correo").ToString.Length > 20, dr("Correo").ToString.Substring(0, 20), dr("Correo").ToString())) + Str.AppendFormat("", dr("FechaRecepcion").ToString.ToDate.ToShortDateString) + + Str.Append("") + conta += 1 + Next + Str.Append("
SerieFolioFechaProveedorImporteMotivoCorreoF. Recepción
{0}{0}{0}{0}{0}{0}{0}{0}
") + Else + Str.Append("No se encontraron facturas pendientes de recibir.") + End If + + If ValidaRowCount Then 'si las facturas no recividas son matores a cero se muestra el mensaje + If DtNoRecibidas.Rows.Count > 0 Then + Alert(Str.ToString, TipoMensaje.MsgInformacion) + End If + Else + Alert(Str.ToString, TipoMensaje.MsgInformacion) + End If + + DtNoRecibidas.Dispose() + + CargaDatos() + End Sub + +#Region "G E N E R A P D F " + Private Sub GenerarPDF(Optional Tipo As String = "PDF") + Dim ObjDatos As New ClsCompras + Dim FechaI As String = txtFechaI.Text + Dim FechaF As String = txtFechaF.Text + If txtFechaI.Text = "" Then FechaI = "-1" + If txtFechaF.Text = "" Then FechaF = "-1" + Dim Folio = If(TxtFolio.Text.Trim.Length > 0, String.Format("%{0}%", TxtFolio.Text.Trim.ToUpper), "-1") + Dim Proveedor = If(TxtProveedor.Text.Trim.Length > 0, String.Format("%{0}%", TxtProveedor.Text.Trim.ToUpper.Replace(" ", "%")), "-1") + + If ObjDatos.GetFacturas(-1, Folio, txtFechaI.Text.Trim.ToDate, txtFechaF.Text.Trim.ToDate, "-1", Proveedor, DdlValidado.SelectedValue.ToEntero, DdlResponsable.SelectedValue.ToEntero, DdlClasificacionProv.SelectedValue.ToEntero, DdlCveTipoProveedor.SelectedValue.ToEntero, DdlTipoComprobante.SelectedValue.ToString, UsuarioActual.CveEmpresa) Then + + 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 dt As DataTable + + + + If Tab.ActiveTabIndex = 0 Then + dt = ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P'") + Else + dt = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P' ") + End If + + + + Dim params As New List(Of ReportParameter) + params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa)) + params.Add(New ReportParameter("FechaInicio", FechaI)) + params.Add(New ReportParameter("FechaFin", FechaF)) + params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) + params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) + If Imagen.Exists Then + params.Add(New ReportParameter("LogoPath", logouri)) + Else + params.Add(New ReportParameter("LogoPath", "")) + End If + + ImprimirPDF("Empresas/Grales/Formatos/RepFacturas.rdlc", dt, params, $"FacturasBuzon_{Now.ToString("yyyyMMyyddmmss")}", Tipo) + Else + Alert("No hay datos consultados", TipoMensaje.MsgAdvertencia) + End If + + End Sub + Protected Sub LnkPdf_Click(sender As Object, e As EventArgs) Handles LnkPdf.Click + GenerarPDF() + End Sub +#End Region + +#Region "S U B I R - F A C T U R A S - M A S I V A M E N T E" + Private Sub LnkSubirFacturas_Click(sender As Object, e As EventArgs) Handles LnkSubirFacturas.Click + RegistraScript(String.Format("$('#{0}').modal();", "ModalFacturas")) + End Sub + Private Sub BtnGuardarFaturas_Click(sender As Object, e As EventArgs) Handles BtnGuardarFaturas.Click + + If UsuarioActual.Empresa.SendMail.Trim.Length = 0 Then + Alert("La Empresa no tiene configurado el envió de correo.", TipoMensaje.MsgAdvertencia) + Exit Sub + End If + + + + Dim sw As New Diagnostics.Stopwatch + Dim swmili As Long = 0 + Dim swTiempo As New StringBuilder + sw.Start() + + + Dim FileExtension As String = "-1" + Dim filesgral As List(Of Archivo) = Anexo.getfiles().Archivos + Dim filemove As String = "" + + Dim ListXML As New List(Of String) + Dim ListPDF As New List(Of String) + Dim ListDirectorios As New List(Of String) + + + + For Each fileItem As Archivo In filesgral + FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "") + filemove = fileItem.filename + + If filemove <> "" Then + filemove.FilesMove("", String.Format("Empresas\{0}\Temp\Facturas", UsuarioActual.CveEmpresa)) + 'AGREGA XML A LA LISTA + If FileExtension.ToUpper = "XML" Then + ListXML.Add(String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, filemove)) + End If + + End If + Next + + + Dim fileEntries As String() = Directory.GetFiles(String.Format("{0}Empresas\{1}\Temp\Facturas", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa)) + + Dim ListaDirectoriosTemporales As New List(Of String) + Dim ListaComprimidos As New List(Of String) + + 'Dim fileName As String + Dim ArchivoExtension As String + Dim sOnlyFilename As String + + For Each filePath In fileEntries + ArchivoExtension = IO.Path.GetExtension(String.Format("{0}", filePath)).Replace(".", "") + sOnlyFilename = System.IO.Path.GetFileName(filePath) + If ArchivoExtension.ToUpper = "RAR" Or ArchivoExtension.ToUpper = "ZIP" Then + ListaComprimidos.Add(filePath) + 'CREO DIRECTORIO ALEATORIO + Dim Aleatorio As New Random + Dim TempDirectorio As String = String.Format("{0}Empresas\{1}\{2}\{3}{4}", Request.PhysicalApplicationPath, UsuarioActual.CveEmpresa, "Temp\Facturas", Date.Now.Ticks, Aleatorio.Next(100, 999)) + Directory.CreateDirectory(TempDirectorio) + ListaDirectoriosTemporales.Add(TempDirectorio) + 'AGREGA DIRECTORIO A LA LISTA + ListDirectorios.Add(TempDirectorio) + 'DESCOMPRIME RAR + DescomprimeFacturas(filePath, TempDirectorio) + 'AGREGA XML A LA LISTA + ListXML.AddRange(Directory.GetFiles(TempDirectorio)) + End If + + + Next + + Dim Arreglo As New ArrayList() + ' Dim Archivos As String() = Directory.GetFiles(String.Format("{0}Empresas\{1}\Temp", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa)) + 'Dim NombreArchivo As String + Dim Bandera = True + Dim Retorno = "" + Dim ListaArchivosMail As New List(Of ClsSisMail.ArchivoMail) + + + sw.Stop() + swTiempo.AppendFormat("ReadFiles: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + sw.Start() + + Anexo.Text = "" + UPAddFacturas.Update() + + For Each filePath In ListXML + + If File.Exists(filePath) Then + Dim ArchivoAdjunto As New ClsSisMail.ArchivoMail + ArchivoAdjunto.ArchivoBinario = File.ReadAllBytes(filePath) + ArchivoAdjunto.Ruta = filePath + ArchivoAdjunto.NombreArchivo = New FileInfo(filePath).Name + + ListaArchivosMail.Add(ArchivoAdjunto) + + End If + + Next + + sw.Stop() + swTiempo.AppendFormat("Fill ClsSisMail.ArchivoMail: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + sw.Start() + If ListaArchivosMail.Count > 0 Then + + Dim Correo As New ClsSisMail + + 'If Correo.SendMail(UsuarioActual.Empresa, "sig.buzon@gmail.com", "Facturas Efacturas " & Now.ToString("yyyyMMddhhmmss"), "Facturas", Archivos:=ListaArchivosMail) Then + + + + + If Correo.SendMail(UsuarioActual.Empresa, UsuarioActual.Empresa.Buzon_Mail, "Facturas Efacturas " & Now.ToString("yyyyMMddhhmmss"), "Facturas", Archivos:=ListaArchivosMail) Then + + sw.Stop() + swTiempo.AppendFormat("EnvioCorreo: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + sw.Start() + System.Threading.Thread.Sleep(3000) + 'ProcesaBuzon() + + sw.Stop() + swTiempo.AppendFormat("espera: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + sw.Start() + VerificaCorreo(True) + + sw.Stop() + swTiempo.AppendFormat("Verifica En la app: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + sw.Start() + Else + Alert("Se presento un error al procesar las facturas.") + End If + + End If + + + sw.Stop() + swTiempo.AppendFormat("BorrarInicio: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + sw.Start() + For Each filePath In ListXML + Try + File.Delete(filePath) + Catch ex As Exception + End Try + Next + + For Each s As String In ListaComprimidos + Try + File.Delete(s) + Catch ex As Exception + End Try + Next + + For Each d As String In ListaDirectoriosTemporales + Try + Directory.Delete(d, True) + Catch ex As Exception + End Try + Next + + + sw.Stop() + swTiempo.AppendFormat("BorrarEnd: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds) + swmili = sw.ElapsedMilliseconds + + GuardaLogefacturas(swTiempo.ToString()) + + + 'ArchivoExtension = IO.Path.GetExtension(String.Format("{0}", filePath)).Replace(".", "") + 'NombreArchivo = System.IO.Path.GetFileName(filePath) + 'If ArchivoExtension.ToUpper = "XML" Then + ' Dim ArchivoInfo As New FileInfo(filePath) + ' Dim Fact2 As Modelos.eFactura = GuardaArchivoXML(filePath) + + ' If Fact2 IsNot Nothing Then + ' Fact2.DirectorioTemporal = ArchivoInfo.DirectoryName & "\" + ' Arreglo.Add(Fact2) + ' End If + 'End If + + + 'If Arreglo.Count > 0 Then + ' For Each Fact As Modelos.eFactura In Arreglo + ' ' si es exploraciones, no debe de insertar del 2013 + + ' If UsuarioActual.CveEmpresa = 13 And Convert.ToDateTime(Fact.Fecha).Year < 2014 And Fact.TipodeComprobante <> "egreso" Then + ' Bandera = False + ' 'ModExtensiones.GuardaLog("'*******noingreso :" + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year) + ' End If + + ' 'por default, no alimentar facturas menores al 2013 + + ' If Convert.ToDateTime(Fact.Fecha).Year < 2013 Then + ' Bandera = False + ' 'ModExtensiones.GuardaLog("'*******noingreso :" + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year) + ' End If + ' If Bandera Then + ' If Not String.IsNullOrEmpty(Fact.TFDUUID) Then + ' Dim Valida As New ClsValidaCFDi(Fact.TFDUUID, Fact.EmisorRFC, Fact.ReceptorRFC, Fact.Total, Fact.Fecha) + ' If Valida.EsValida = 1 Then + ' Fact.Validada = 1 + ' End If + ' Valida.Dispose() + + ' If Not String.IsNullOrEmpty(Fact.ArchivoPDF) Then + ' Retorno = AgregaFactura(Fact) + ' Else + ' If GeneraPDF(Fact.DirectorioTemporal, Fact) Then + ' ListPDF.Add(Fact.ArchivoPDF) + ' Retorno = AgregaFactura(Fact) + ' ' ModExtensiones.GuardaLog("'*******se genero el pdf :" + String.Format("{0}Empresas\{1}\Temp", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa) + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year + "Retorno:" + Retorno) + ' Else + ' ' ModExtensiones.GuardaLog("'*******no se genero el pdf :" + String.Format("{0}Empresas\{1}\Temp", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa) + Fact.ArchivoXML + " RFC: " + tRF + " Anio" + Convert.ToDateTime(Fact.Fecha).Year + "Retorno:" + Retorno) + + ' End If + ' End If + ' End If + ' End If + + ' Bandera = True + ' Try + ' If File.Exists(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoXML)) Then + ' File.Delete(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoXML)) + ' End If + + ' If File.Exists(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF)) Then + ' File.Delete(String.Format("{0}{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF)) + ' End If + ' Catch ex As Exception + + ' End Try + ' Next + 'End If + + + RegistraScript(String.Format("$('#{0}').modal('hide');", "ModalFacturas")) + 'Alert(String.Format("Se cargaron {0} Facturas", Arreglo.Count), TipoMensaje.MsgInformacion) + End Sub + + Public Sub GuardaLogefacturas(Str As String) + Dim ArchivoW As StreamWriter + Dim strLineaTMP As String + + ' strLineaTMP = Chr(13) & Chr(10) & Day(Now) & "/" & Month(Now) & "/" & Year(Now) & " " & Hour(Now) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10) + strLineaTMP = String.Format("{0}{1}Log: {2}{3}:{4}", Chr(13), Chr(10), Str, DateTime.Now.ToShortDateString, DateTime.Now.ToShortTimeString) + Try + ArchivoW = New StreamWriter(String.Format("{0}\Logefacturas.txt", AppDomain.CurrentDomain.BaseDirectory), True, System.Text.Encoding.UTF8) + Catch ex As UnauthorizedAccessException + 'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError) + Exit Sub + Catch ex As Exception + Exit Sub + End Try + + Try + ArchivoW.WriteLine(strLineaTMP) + Catch + End Try + + ArchivoW.Close() + ArchivoW.Dispose() + End Sub + Private Function AgregaFactura(Fact As Modelos.eFactura) As String + Dim Retorno As String = "" + Dim Correcto As Boolean = False + + If Fact.Version = "3.2" Then Fact.TipodeComprobante = Fact.TipodeComprobante.Substring(0, 1) + + + Dim ObjDatos As New ClsCompras + ObjDatos.IniciaTransacSQL() + ObjDatos.CveFactura = 0 + Dim Ret As Integer = ObjDatos.AddFactura(Fact.Serie, Fact.Folio, Convert.ToDateTime(Fact.Fecha), Fact.EmisorNombre, Fact.EmisorRFC, Fact.subTotal, + Fact.TrasladoIVA, Fact.Total, Fact.TFDUUID, Fact.ReceptorRFC, Fact.ArchivoXML, Fact.ArchivoPDF, + Fact.Version, Fact.Descuento, Fact.Moneda, Fact.TipodeComprobante, Fact.TipoCambio, Fact.Validada, + Fact.CveEmpresa, Fact.sUPPrefijo) + + If Ret >= 0 Then + If Not Directory.Exists(Destino + Fact.EmisorRFC) Then + Directory.CreateDirectory(Destino + Fact.EmisorRFC) + End If + 'Try + ' If File.Exists(Destino & Retorno.EmisorRFC & "\" & NombreArchivo) Then File.Delete(Destino & Retorno.EmisorRFC & "\" & NombreArchivo) + ' File.Move(Temporal & NombreArchivo, Destino & Retorno.EmisorRFC & "\" & NombreArchivo) + + 'Catch ex As IOException + ' GuardaLog("'ERROR :" & ex.Message) + 'End Try + + Select Case Ret + Case 0 + + Correcto = True + Dim RRutaDestino As String = String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura) + 'ModExtensiones.GuardaLog(String.Format(" '--------{0} Compra ya insertada : {1}{2} - {3}", ContadorGeneral, Fact.Serie, Fact.Folio, RRutaDestino)) + + If Not File.Exists(RRutaDestino) Then + File.Move(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, Fact.ArchivoXML), RRutaDestino) + ObjDatos.UpdateArchivo(ObjDatos.CveFactura, "XML") + ModExtensiones.GuardaLog(" '--------XML Actualizado ") + End If + + Correcto = True + Exit Select + Case 1 + 'muevo el archivo y lo renombro + Dim StrMover As String = "" + Try + File.Move(String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoXML), String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) + File.Move(String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF), String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) + ModExtensiones.GuardaLog(" '++++++++ Archivo :" + String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoXML) + " - " + String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) + ModExtensiones.GuardaLog(" '++++++++ Archivo :" + String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF) + " - " + String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) + 'si se movieron los dos archivos, los marca como correcto + If File.Exists(String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) AndAlso File.Exists(String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) Then + Correcto = True + End If + Catch ex As Exception + StrMover = ex.Message + End Try + + + ModExtensiones.GuardaLog(Convert.ToString(" '++++++++ Compra Insertada :" + Fact.Serie + Fact.Folio + " - Correcto:" + (If(Correcto, "Si", "No" + " Obs: "))) & StrMover) + Exit Select + End Select + End If + If Correcto Then + ObjDatos.Commit() + 'ya se insertó o está insertada + Dim Idioma As New CultureInfo("es-MX") + 'regreso el format 2014-07 Julio + Retorno = Fact.Fecha.ToDate().ToString("yyyy-MM MMMM", Idioma) + Else + ObjDatos.RollBack() + End If + ObjDatos.Dispose() + + Return Retorno + + End Function + Private Sub CargarFacturas(PathArchivo As String, NombreArchivo As String) + Dim RFC As String = CargaEmisordeXML(String.Format("{0}", PathArchivo), "RFC", UsuarioActual.Empresa.RFC) + If RFC IsNot Nothing Then + If NombreArchivo <> "" Then + DirectoryExistsCreate(String.Format("{0}Compras", UsuarioActual.Empresa.Ruta)) + DirectoryExistsCreate(String.Format("{0}Compras\{1}", UsuarioActual.Empresa.Ruta, RFC.ToUpper)) + + Try + File.Move(PathArchivo, String.Format("{0}Empresas\{1}\Compras\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, RFC.ToUpper, NombreArchivo)) + Catch ex As Exception + Alert("Error") + End Try + + 'NombreArchivo.FilesMove(NombreArchivo, String.Format("Empresas\{0}\Compras\{1}", UsuarioActual.CveEmpresa, RFC.ToUpper)) + End If + End If + End Sub + Private Sub DescomprimeFacturas(PathArchivo As String, Directorio As String) + If Not Directory.Exists(Directorio) Then + Directory.CreateDirectory(Directorio) + End If + Using archive As ZipArchive = ZipFile.OpenRead(String.Format("{0}", PathArchivo)) + + For Each entry As ZipArchiveEntry In archive.Entries + If entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) Then + + 'If File.Exists(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Directorio, entry.Name)) Then + ' File.Delete(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Directorio, entry.Name)) + 'End If + + 'entry.ExtractToFile(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, Directorio, entry.Name)) + + If File.Exists(String.Format("{0}\{1}", Directorio, entry.Name)) Then + File.Delete(String.Format("{0}\{1}", Directorio, entry.Name)) + End If + + entry.ExtractToFile(String.Format("{0}\{1}", Directorio, entry.Name)) + + End If + Next + + End Using + End Sub + Public Shared Function CargaEmisordeXML(ArchivoXML As String, CampoXML As String, RFCEmpresaActual As String) As String + Dim Valor As [String] = Nothing + + If File.Exists(ArchivoXML) Then + Dim NombreArchivo As String = Path.GetFileName(ArchivoXML) + Dim invalidChars As Char() = Path.GetInvalidFileNameChars() + Dim invalidString As String = Regex.Escape(New String(invalidChars)) + Dim NombreValido As String = Regex.Replace(NombreArchivo, (Convert.ToString("[") & invalidString) + "]", "") + + Try + Dim XmlDoc As New XmlDocument() + XmlDoc.Load(ArchivoXML) + Dim nodo As XmlNode = XmlDoc.DocumentElement.ChildNodes(0) + Dim node As XmlNode + Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" + Dim RfcXML As String = "" + Dim Prefijo As String = If(XmlDoc.DocumentElement.Prefix = "", "cfd", XmlDoc.DocumentElement.Prefix) + Dim namespaces As New XmlNamespaceManager(XmlDoc.NameTable) + + If Not Prefijo.ToLower().Equals("cfdi") Then + cfdVer = "http://www.sat.gob.mx/cfd/2" + End If + namespaces.AddNamespace(Prefijo, cfdVer) + namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") + namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal") + namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal") + + node = XmlDoc.SelectSingleNode([String].Format("//{0}:Receptor", Prefijo), namespaces) + If node IsNot Nothing Then + RfcXML = ValorXML(node, "RFC") + End If + If RfcXML = RFCEmpresaActual Then + Valor = ValorXML(nodo, CampoXML) + + + End If + Catch exx As XmlException + Valor = Nothing + 'Using file__1 As New System.IO.StreamWriter([String].Format("{0}\UtileriasLOG.txt", Path.GetDirectoryName(Application.StartupPath)), True, System.Text.Encoding.UTF8) + ' file__1.WriteLine("{DateTime.Now}: {exx.Message}") + ' file__1.Close() + ' file__1.Dispose() + 'End Using + End Try + End If + Return Valor + End Function + Private Shared Function ValorXML(n As XmlNode, Campo As String, Optional retorno As [String] = "") As String + If n Is Nothing Then + Return retorno + End If + + Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, StringComparison.CurrentCultureIgnoreCase) = 0) + If o Is Nothing Then + Return retorno + Else + Return o.Value + End If + + End Function + Private Function CargaDatosXML(XMLDoc As XmlDocument) As Modelos.eFactura + Dim nodo As XmlNode = XMLDoc.DocumentElement + + If nodo.ChildNodes.Count = 2 Then + nodo = nodo.ChildNodes(1) + End If + + Dim Fact As Modelos.eFactura = Nothing + Dim node As XmlNode = Nothing + Dim RFC As String = "" + + Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix) + Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" + Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) + + If Prefijo.ToLower() <> "cfdi" Then + cfdVer = "http://www.sat.gob.mx/cfd/2" + End If + namespaces.AddNamespace(Prefijo, cfdVer) + namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") + namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal") + namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal") + + node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces) + 'AndAlso node.ChildNodes.Count > 0 + If node IsNot Nothing Then + RFC = ValorXML(node, "RFC") + End If + + 'solo si el rfc receptor es el mismo al de la empresa seleccionada + + If RFC = UsuarioActual.Empresa.RFC AndAlso Convert.ToDateTime(ValorXML(nodo, "fecha")).Year >= 2013 Then + Fact = New Modelos.eFactura() + + 'Fact.CveEmpresa = CveEmpresa + Fact.Serie = ValorXML(nodo, "serie") + If Not String.IsNullOrEmpty(Fact.Serie) Then + Fact.Serie = Fact.Serie + End If + + Fact.Version = ValorXML(nodo, "version").Replace("..", ".") + Fact.Folio = ValorXML(nodo, "folio").TrimStart("0"c) + Fact.Fecha = ValorXML(nodo, "fecha") + Fact.subTotal = Convert.ToDouble(ValorXML(nodo, "subTotal").Replace("..", ".")) + Fact.Total = Convert.ToDouble(ValorXML(nodo, "total")) + Fact.Moneda = ValorXML(nodo, "Moneda") + Fact.TipodeComprobante = ValorXML(nodo, "tipoDeComprobante") + Fact.TipoCambio = Convert.ToDouble(ValorXML(nodo, "TipoCambio", "1.0")) + Fact.Descuento = Convert.ToDouble(ValorXML(nodo, "descuento", "0")) + Fact.CveEmpresa = UsuarioActual.CveEmpresa + + Fact.sUPPrefijo = Prefijo + + node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) + + If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then + Fact.EmisorRFC = ValorXML(node, "RFC") + Fact.EmisorNombre = ValorXML(node, "nombre") + End If + node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces) + ' AndAlso node.ChildNodes.Count > 0 + If node IsNot Nothing Then + Fact.ReceptorRFC = ValorXML(node, "RFC") + End If + + node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces) + + If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then + Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces) + + Fact.TotalRetenciones = Convert.ToDouble(ValorXML(node, "totalImpuestosRetenidos", "0")) + + For Each retencion As XmlNode In nodeRetenciones + If retencion.Attributes.GetNamedItem("impuesto").Value = "IVA" Then + Fact.RetencionIVA += Convert.ToDouble(retencion.Attributes.GetNamedItem("importe").Value) + End If + If retencion.Attributes.GetNamedItem("impuesto").Value = "ISR" Then + Fact.RetencionISR += Convert.ToDouble(retencion.Attributes.GetNamedItem("importe").Value) + ' Do something. + End If + Next + Fact.SumaTotalRetenciones += Fact.RetencionIVA + Fact.SumaTotalRetenciones += Fact.RetencionISR + + Fact.TotalTraslados = Convert.ToDouble(ValorXML(node, "totalImpuestosTrasladados", "0")) + + 'Dim o As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "impuesto", StringComparison.CurrentCultureIgnoreCase) = 0) + Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) + + For Each traslado As XmlNode In nodeTraslados + ' If traslado.Attributes.GetNamedItem("impuesto").Value = "IVA" + Dim impuesto As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "impuesto", StringComparison.CurrentCultureIgnoreCase) = 0) + If impuesto.Value = "IVA" Then + + Dim ImporteTRaslado As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "Importe", StringComparison.CurrentCultureIgnoreCase) = 0) + Fact.TrasladoIVA += Convert.ToDouble(ImporteTRaslado.Value) + 'If traslado.Attributes("impuesto").Value = "ISR" Then + ' TrasladoISR = traslado.Attributes("importe").Value + 'End If + ' Do something. + End If + Next + Fact.SumaTotalTraslados += Fact.TrasladoIVA + End If + + + Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces) + Dim FacturaMisCuentasSAT As Boolean = False + + + If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then + Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces) + + Fact.TFDUUID = ValorXML(nodeTFD, "UUID", "") + + Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces) + If nodeRF IsNot Nothing Then + Fact.Folio = ValorXML(nodeRF, "folio").TrimStart("0"c) + FacturaMisCuentasSAT = True + + End If + Else + Fact.TFDUUID = "" + If String.IsNullOrEmpty(Fact.TFDUUID) AndAlso Fact.sUPPrefijo.ToLower() = "cfdi" Then + 'Mensajes.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}{6}&", ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate().ToShortDateString(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble().FormatoNumero(), + '"Factura no timbrada correctamente.", "") + 'CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble(), "Factura no timbrada correctamente.", + '"", DateTime.Now) + End If + + 'limpio los valores porque realmente no es una factura + + Fact = Nothing + End If + 'verifico si el metodo de pago esta dentro de la opcion valida + + + If Convert.ToDateTime(ValorXML(nodo, "fecha")) >= ("2016/07/15").ToDate() Then + Dim CasoPermitido As Boolean = False + 'If CveEmpresa.Contiene(72, 80) AndAlso ValorXML(nodo, "MetododePago").ToUpper().PadRight(13, " "c).Substring(0, 13) = "TRANSFERENCIA" Then + ' CasoPermitido = True + 'End If + + 'If CveEmpresa = 5 OrElse FacturaMisCuentasSAT Then + ' CasoPermitido = True + 'End If + + If Not CasoPermitido Then + If (Not (ValorXML(nodo, "MetododePago").ToUpper().PadLeft(2, "0"c).Substring(0, 2).Contiene("01", "02", "03", "04", "05", "06", + "07", "08", "09", "10", "11", "12", + "13", "14", "15", "16", "17", "28", + "98", "99", "NA") OrElse ValorXML(nodo, "MetododePago").ToUpper().Contiene("NO APLICA", "N/A", "N.A.", "NO IDENTIFICADO"))) Then + Dim node2 As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) + Dim Nombre As String = "" + + If node2 IsNot Nothing AndAlso node2.ChildNodes.Count > 0 Then + Nombre = ValorXML(node2, "nombre") + End If + + 'CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble(), "Método de Pago Incorrecto:" + ValorXML(nodo, "MetododePago"), + 'CorreoActual, FechaRecepcionCorreo) + + Return Nothing + End If + + + End If + + 'faltan leer los impuestos locales + 'node = XMLDoc.SelectSingleNode(String.Format("//{0}:ImpuestosLocales", "implocal"), namespaces) + 'If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then + ' Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces) + + ' Fact.TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDouble + + ' For Each retencion As XmlNode In nodeRetenciones + ' If retencion.Attributes("impuesto").Value = "IVA" Then + ' Fact.RetencionIVA += retencion.Attributes("importe").Value.ToDouble + ' End If + ' If retencion.Attributes("impuesto").Value = "ISR" Then + ' Fact.RetencionISR += retencion.Attributes("importe").Value.ToDouble + ' End If + ' ' Do something. + ' Next + ' Fact.SumaTotalRetenciones += Fact.RetencionIVA + ' Fact.SumaTotalRetenciones += Fact.RetencionISR + + ' Fact.TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble + + ' Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) + ' For Each traslado As XmlNode In nodeTraslados + ' If traslado.Attributes("impuesto").Value = "IVA" Then + ' Fact.TrasladoIVA += traslado.Attributes("importe").Value.ToDouble + ' End If + ' 'If traslado.Attributes("impuesto").Value = "ISR" Then + ' ' TrasladoISR = traslado.Attributes("importe").Value + ' 'End If + ' ' Do something. + ' Next + ' Fact.SumaTotalTraslados += Fact.TrasladoIVA + 'End If + + + End If + Else + 'ModExtensiones.GuardaLog((Convert.ToString("'*******RFC incorrecto RFC Emp:") & RFC) + " RFC Fact: " + RFCReceptor) + 'obtengo los datos del xml, para + + Dim node2 As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces) + + + 'If node2 IsNot Nothing AndAlso node2.ChildNodes.Count > 0 Then + ' Mensajes.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}{6}&", ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate().ToShortDateString(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble().FormatoNumero(), + ' "RFC Incorrecto:", RFC) + ' CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble(), Convert.ToString("RFC Incorrecto:") & RFC, + ' CorreoActual, FechaRecepcionCorreo) + 'Else + ' CargaMensaje("", "", "01/01/2000".ToDate(), "", 0.0, Convert.ToString("RFC Incorrecto:") & RFC, + ' CorreoActual, FechaRecepcionCorreo) + + + 'End If + End If + + Return Fact + End Function + Private Function GuardaArchivoXML(Archivo As String) As Modelos.eFactura + ' , Destino As String, Temporal As String + Dim Retorno As Modelos.eFactura = Nothing + + If File.Exists(Archivo) Then + Dim NombreArchivo As String = Path.GetFileName(Archivo) + Dim invalidChars As Char() = Path.GetInvalidFileNameChars() + Dim invalidString As String = Regex.Escape(New String(invalidChars)) + Dim valid As String = Regex.Replace(NombreArchivo, (Convert.ToString("[") & invalidString) + "]", "") + + NombreArchivo = valid + + Try + Dim XMLDoc As New XmlDocument() + + XMLDoc.Load(Archivo) + Retorno = CargaDatosXML(XMLDoc) + + Catch exx As XmlException + Retorno = Nothing + 'Dim texto As Dynamic = File.ReadAllText(Archivo) + Dim txt_utf8 As New UTF8Encoding() + 'REEMPLAZA CARACTERES ESPECIALES Y VUELVE A LEER EL DOCUMENTO + + 'texto = RemoveIllegalXMLCharacters(texto) + ' SE RENOMBRA EL ARCHIVO, PERO SE QUITO POR SI NO COINCIDE EL PDF CON EL NOMBRE + 'Archivo = Archivo.ToUpper.Replace(".XML", "-2.XML") + 'NombreArchivo = IO.Path.GetFileName(Archivo) + 'File.WriteAllText(Archivo, texto) + + + ' Dim xmltr As New XmlTextReader(New MemoryStream(RemoveIllegalXMLCharacters(texto))) + Dim XMLDoc As New XmlDocument() + + Try + XMLDoc.Load(Archivo) + Retorno = CargaDatosXML(XMLDoc) + Catch ex As Exception + Retorno = Nothing + + + + End Try + Catch ex As Exception + + + Retorno = Nothing + End Try + + 'si se cargaron todos los datos + If Retorno IsNot Nothing AndAlso Not String.IsNullOrEmpty(Retorno.TFDUUID) Then + 'XML + Retorno.ArchivoXML = NombreArchivo + End If + End If + Return Retorno + + End Function + Private Sub CargaImpuestosXML(XMLDoc As XmlDocument) + Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix) + Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3" + Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) + + If Prefijo.ToLower() <> "cfdi" Then + cfdVer = "http://www.sat.gob.mx/cfd/2" + End If + namespaces.AddNamespace(Prefijo, cfdVer) + namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") + namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal") + namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal") + + TrasladoIVA = 0 + '_TrasladoIVA = XMLDoc.DocumentElement.ChildNodes(3).Attributes("totalImpuestosTrasladados").Value + + Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces) + For Each traslado As XmlNode In nodeTraslados + If traslado.Attributes.GetNamedItem("impuesto").Value = "IVA" Then + TrasladoIVA += traslado.Attributes.GetNamedItem("importe").Value.ToDouble() + + End If + Next + + Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces) + + + If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then + Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces) + + _TFDUUID = ValorXML(nodeTFD, "UUID", "") + _TFDFechaTimbrado = ValorXML(nodeTFD, "FechaTimbrado", "") + _TFDSelloCFD = ValorXML(nodeTFD, "selloCFD", "") + _TFDNoCertSAT = ValorXML(nodeTFD, "noCertificadoSAT", "") + _TFDSelloSAT = ValorXML(nodeTFD, "selloSAT", "") + + Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces) + If nodeRF IsNot Nothing Then + _Folio = ValorXML(nodeRF, "folio").TrimStart("0"c) + + + End If + End If + + End Sub + Private Shared Sub CargaTFD(XMLDoc As XmlDocument) + '_TFDUUID = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText + '_TFDFechaTimbrado = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("FechaTimbrado").InnerText + '_TFDSelloCFD = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("selloCFD").InnerText + '_TFDNoCertSAT = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("noCertificadoSAT").InnerText + '_TFDSelloSAT = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("selloSAT").InnerText + End Sub + Public Function GeneraPDF(Ruta As String, Fact As Modelos.eFactura) As Boolean + Dim RutaXML As String = String.Empty + Dim RutaPDF As String = String.Empty + Dim Retorno As Boolean = False + Try + + Dim XMLDoc As New XmlDocument() + Dim TmpArchivoPDF As String = String.Format("{0}{1}-ttt.pdf", Ruta, Path.GetFileNameWithoutExtension(Fact.ArchivoXML)) + Dim TmpArchivoQR As String = String.Format("{0}{1}-ttt.jpg", Ruta, Path.GetFileNameWithoutExtension(Fact.ArchivoXML)) + Dim ArchivoXML As String = String.Format("{0}{1}", Ruta, Fact.ArchivoXML) + + ' If Not File.Exists(TmpArchivoPDF) Then + XMLDoc.Load(ArchivoXML) + CreaDTConceptos() + CargaComprobanteXML(XMLDoc) + CargaEmisorXML(XMLDoc) + CargaReceptorXML(XMLDoc) + CargaConceptosXML(XMLDoc) + CargaImpuestosXML(XMLDoc) + CargaTFD(XMLDoc) + + Dim QR As New ClbNegBICFDv3_2.ClsNegCBBGenerar() + Dim dtotal As Decimal = (If(total.ToDecimal() <= 0.0D, 0.0001D, total.ToDecimal())) + QR.GenerarCBB(EmiRFC, RecRfc, dtotal, TFDUUID, TmpArchivoQR) + + + If System.IO.File.Exists(TmpArchivoQR) Then + 'Dim ArchivoBaseXLS As String = String.Format("{0}FacturaPDF.xlsm", Ruta.Replace("Temp", "Compras")) + If GeneraPDFNew(TmpArchivoPDF, TFDUUID, subTotal, descuento, total, TrasladoIVA.ToString(), + moneda, formaDePago, TFDNoCertSAT, TFDFechaTimbrado.ToDate(), noCertificado, DTConceptos, + TFDSelloCFD, TFDSelloSAT, TmpArchivoQR, Serie + Folio, tipoDeComprobante, "", + RecRfc, RecNombre, DomRecCalle, DomRecCol, DomRecFisNoExt, DomRecFisNoInt, + DomRecCP, DomRecMun, DomRecEst, Regimen, condicionesDePago, metodoDePago, + NumCtaPagoNumCtaPago, fecha.ToDate()) Then + Fact.ArchivoPDF = Path.GetFileName(TmpArchivoPDF) + + Retorno = True + End If + + File.Delete(TmpArchivoQR) + + RutaPDF = TmpArchivoPDF + Else + Retorno = False + End If + 'Else + 'RutaPDF = TmpArchivoPDF + 'End If + + + + If DTConceptos IsNot Nothing Then + DTConceptos.Dispose() + End If + Catch ex As Exception + ModExtensiones.GuardaLog("11189" + ex.Message) + End Try + + + Return Retorno + End Function + Private Sub CargaComprobanteXML(XMLDoc As XmlDocument) + Dim nodo As XmlNode = XMLDoc.DocumentElement + Serie = ValorXML(nodo, "serie", "") + _Folio = ValorXML(nodo, "folio", "") + _fecha = ValorXML(nodo, "fecha", "") + _tipoDeComprobante = ValorXML(nodo, "tipoDeComprobante", "") + _formaDePago = ValorXML(nodo, "formaDePago", "") + _subTotal = ValorXML(nodo, "subTotal", "0") + _descuento = ValorXML(nodo, "descuento", "0") + _total = ValorXML(nodo, "total", "0") + _moneda = ValorXML(nodo, "Moneda") + _metodoDePago = ValorXML(nodo, "metodoDePago", "") + _condicionesDePago = ValorXML(nodo, "condicionesDePago", "") + _LugarExpedicion = ValorXML(nodo, "LugarExpedicion", "") + _NumCtaPagoNumCtaPago = ValorXML(nodo, "NumCtaPago", "") + + + _noCertificado = XMLDoc.DocumentElement.Attributes.GetNamedItem("noCertificado").Value + End Sub + Private Sub CargaEmisorXML(XMLDoc As XmlDocument) + Dim nodo As XmlNode = XMLDoc.DocumentElement.ChildNodes(0) + _EmiRFC = ValorXML(nodo, "rfc", "") + _EmiNombre = ValorXML(nodo, "nombre", "") + + nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(0) + _DomFisCalle = ValorXML(nodo, "calle", "") + _DomFisNoExt = ValorXML(nodo, "noExterior", "") + 'LblDomFisNoInt.Text = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(0).Attributes("noInterior").Value + _DomFisCol = ValorXML(nodo, "colonia", "") + _DomFisCP = ValorXML(nodo, "codigoPostal", "") + _DomFisMun = ValorXML(nodo, "municipio", "") + _DomFisLoc = ValorXML(nodo, "localidad", "") + _DomFisEst = ValorXML(nodo, "estado", "") + _DomFisPais = ValorXML(nodo, "pais", "") + + nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(1) + _ExpEnCalle = ValorXML(nodo, "calle", "") + _ExpEnNoExt = ValorXML(nodo, "noExterior", "") + 'LblExpEnNoInt.Text = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(1).Attributes("noInterior").Value + ExpEnCol = ValorXML(nodo, "colonia", "") + _ExpEnCP = ValorXML(nodo, "codigoPostal", "") + _ExpEnMun = ValorXML(nodo, "municipio", "") + _ExpEnLoc = ValorXML(nodo, "localidad", "") + _ExpEnEst = ValorXML(nodo, "estado", "") + _ExpEnPais = ValorXML(nodo, "pais", "") + + nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(2) + _Regimen = ValorXML(nodo, "Regimen", "") + End Sub + Private Sub CargaReceptorXML(XMLDoc As XmlDocument) + Dim nodo As XmlNode = XMLDoc.DocumentElement.ChildNodes(1) + _RecRfc = ValorXML(nodo, "rfc", "") + _RecNombre = ValorXML(nodo, "nombre", "") + + nodo = XMLDoc.DocumentElement.ChildNodes(1).ChildNodes(0) + + _DomRecCalle = ValorXML(nodo, "calle", "") + _DomRecFisNoExt = ValorXML(nodo, "noExterior", "") + _DomRecFisNoInt = ValorXML(nodo, "noInterior", "") + _DomRecCol = ValorXML(nodo, "colonia", "") + _DomRecCP = ValorXML(nodo, "codigoPostal", "") + _DomRecMun = ValorXML(nodo, "municipio", "") + _DomRecLoc = ValorXML(nodo, "localidad", "") + _DomRecEst = ValorXML(nodo, "estado", "") + _DomRecPais = ValorXML(nodo, "pais", "") + End Sub + Private Sub CargaConceptosXML(XMLDoc As XmlDocument) + Dim i As Integer = 0 + 'Dim SB As New StringBuilder() + 'SB.Append("") + 'SB.AppendLine("") + Dim nodo As XmlNode = Nothing + For i = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1 + nodo = XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i) + 'SB.Append("") + 'SB.Append("") + 'SB.Append("") + 'SB.Append("") + 'SB.Append("") + 'SB.Append("") + 'SB.Append("") + + AddPS(nodo.Attributes.GetNamedItem("cantidad").Value.ToDouble(), nodo.Attributes.GetNamedItem("unidad").Value, nodo.Attributes.GetNamedItem("descripcion").Value, nodo.Attributes.GetNamedItem("valorUnitario").Value.ToDouble(), 0, nodo.Attributes.GetNamedItem("importe").Value.ToDouble()) + Next + 'SB.Append("
cantidaddescripcionvalorUnitarioimporteunidad
" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("cantidad").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("descripcion").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("valorUnitario").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("importe").Value & "" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("unidad").Value & "
") + 'If i > 0 Then Response.Write(SB.ToString) + 'SB.Clear() + End Sub + Private Sub AddPS(Cantidad As Double, UM As String, PS As String, PU As Double, IVA As Double, Optional Total As Double = 0) + If PS <> "IVA" Then + Dim Row As DataRow = Nothing + Row = DTConceptos.NewRow() + Row("Consec") = DTConceptos.Rows.Count + 1 + Row("Cantidad") = Cantidad + Row("UM") = UM + Row("PS") = PS + Row("PU") = PU + Row("IVA") = IVA + Row("Total") = If(Total > 0, Total, (Cantidad * PU)) + DTConceptos.Rows.Add(Row) + End If + End Sub + Private Function GeneraPDFNew(TmpArchivoPDF As String, FolioFiscal As String, SubTotal As String, Descuento As String, Total As String, IVA As String, + Moneda As String, FormaDePago As String, NoSerieCertificado As String, FechaCertificacion As DateTime, NoSerieCertificadoContribuyente As String, DTConceptos As DataTable, + SelloCFDi As String, SelloSAT As String, CBB As String, Folio As String, TipodeComprobante As String, CadenaOriginalCFD As String, + RFC As String, Cliente As String, Direccion As String, Colonia As String, NoExt As String, NoInt As String, + CP As String, Ciudad As String, Estado As String, Regimen As String, CondicionPago As String, MetodoPago As String, + NumCtaPago As String, fecha As System.DateTime) As Boolean + Dim Retorno = False + Dim NombreArchivo As String = TmpArchivoPDF + Dim CadenaOriginal As String = (Convert.ToString((Convert.ToString((Convert.ToString("||1.0|") & FolioFiscal) + "|" + FechaCertificacion.ToString("yyyy-MM-dd") + "T" + FechaCertificacion.ToString("HH:mm:ss") + "|") & SelloCFDi) + "|") & NoSerieCertificado) + "||" + Dim RutaFormato As String = String.Format("{0}Empresas\Grales\Formatos\CFDI.rdlc", AppDomain.CurrentDomain.BaseDirectory) + 'Dim ArchivoTempXLS As String = String.Format("{0}\GenSis{1}-{2}", Path.GetDirectoryName(ArchivoBaseXLS), Now.Ticks, Path.GetFileName(ArchivoBaseXLS)) + + Dim Fiscal As String = String.Format("Domicilio Fiscal {0}{1} {2}{0}Col.{3}{0}CP. {4} {5},{6},{7}", vbCr, DomFisCalle, DomFisNoExt, DomFisCol, DomFisCP, + DomFisMun, DomFisEst, DomFisPais) + Try + Dim parametros As New List(Of ReportParameter)() + 'params.Add(New ReportParameter("ArchivoBaseXLS", ArchivoBaseXLS)) + 'params.Add(New ReportParameter("TmpArchivoPDF", TmpArchivoPDF)) + parametros.Add(New ReportParameter("FolioFiscal", FolioFiscal)) + parametros.Add(New ReportParameter("SubTotal", SubTotal.FormatoNumero())) + parametros.Add(New ReportParameter("Descuento", Descuento.FormatoNumero())) + parametros.Add(New ReportParameter("Total", Total.FormatoNumero())) + parametros.Add(New ReportParameter("IVA", IVA.FormatoNumero())) + parametros.Add(New ReportParameter("Moneda", Moneda)) + parametros.Add(New ReportParameter("FormaDePago", FormaDePago)) + parametros.Add(New ReportParameter("NoSerieCertificado", NoSerieCertificado)) + parametros.Add(New ReportParameter("FechaCertificacion", FechaCertificacion.ToString("yyyy-MM-dd") + "T" + FechaCertificacion.ToString("HH:mm:ss"))) + parametros.Add(New ReportParameter("NoSerieCertificadoContribuyente", NoSerieCertificadoContribuyente)) + parametros.Add(New ReportParameter("SelloCFDi", SelloCFDi)) + parametros.Add(New ReportParameter("SelloSAT", SelloSAT)) + parametros.Add(New ReportParameter("CBB", String.Format("file:///{0}", CBB))) + parametros.Add(New ReportParameter("Folio", Folio)) + parametros.Add(New ReportParameter("TipodeComprobante", TipodeComprobante.ToUpper())) + parametros.Add(New ReportParameter("CadenaOriginalCFD", CadenaOriginalCFD)) + parametros.Add(New ReportParameter("RFC", RFC)) + parametros.Add(New ReportParameter("Cliente", Cliente)) + parametros.Add(New ReportParameter("Direccion", Direccion)) + parametros.Add(New ReportParameter("Colonia", Colonia)) + parametros.Add(New ReportParameter("NoExt", NoExt)) + parametros.Add(New ReportParameter("NoInt", NoInt)) + parametros.Add(New ReportParameter("CP", CP)) + parametros.Add(New ReportParameter("Ciudad", Ciudad)) + parametros.Add(New ReportParameter("Estado", Estado)) + parametros.Add(New ReportParameter("Regimen", Regimen)) + parametros.Add(New ReportParameter("CondicionPago", CondicionPago)) + parametros.Add(New ReportParameter("MetodoPago", MetodoPago)) + parametros.Add(New ReportParameter("NumCtaPago", NumCtaPago)) + parametros.Add(New ReportParameter("fecha", fecha.ToString("yyyy-MM-dd") + "T" + fecha.ToString("HH:mm:ss"))) + parametros.Add(New ReportParameter("Fiscal", Fiscal)) + parametros.Add(New ReportParameter("EmiNombre", EmiNombre)) + parametros.Add(New ReportParameter("EmiRFC", EmiRFC)) + parametros.Add(New ReportParameter("NoSerieCertificado", NoSerieCertificado)) + parametros.Add(New ReportParameter("TotalLetra", Total.ToDouble().Texto2Letras(CveMoneda:=If(Moneda = "MXN", 1, If(Moneda = "USD", 2, 3))))) + parametros.Add(New ReportParameter("Empresa", UsuarioActual.Empresa.Empresa)) + + 'params.Add(New ReportParameter("DTConceptos", DTConceptos)) + + Dim rds As New ReportDataSource() + rds.Name = "DsOC" + rds.Value = DTConceptos + Dim Archivo As New System.IO.FileInfo(RutaFormato) + + If Archivo.Exists Then + Dim MR As New ReportViewer() + MR.LocalReport.DataSources.Add(rds) + MR.LocalReport.ReportPath = RutaFormato + MR.ProcessingMode = ProcessingMode.Local + MR.LocalReport.EnableExternalImages = True + MR.LocalReport.SetParameters(parametros) + MR.LocalReport.Refresh() + + + Dim warnings As Warning() = Nothing + Dim streamids As String() = Nothing + Dim mimeType As String = Nothing + Dim encoding As String = Nothing + Dim extension As String = Nothing + Dim bytes As Byte() = Nothing + bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, + warnings) + + Using fs As New FileStream(NombreArchivo, FileMode.Create) + fs.Write(bytes, 0, bytes.Length) + fs.Close() + End Using + Retorno = True + Else + ModExtensiones.GuardaLog(String.Format("No existe formato Base")) + + + End If + Catch ex As Exception + ModExtensiones.GuardaLog(String.Format("Ocurrio un Error al generar el reporte RLDC")) + Retorno = False + End Try + Return Retorno + End Function + Private Sub CreaDTConceptos() + DTConceptos = New DataTable() + DTConceptos.Columns.Add("Consec", GetType(Integer)) + DTConceptos.Columns.Add("Cantidad", GetType(Double)) + DTConceptos.Columns.Add("UM", GetType(String)) + DTConceptos.Columns.Add("PS", GetType(String)) + DTConceptos.Columns.Add("PU", GetType(Double)) + DTConceptos.Columns.Add("IVA", GetType(Double)) + DTConceptos.Columns.Add("Total", GetType(Double)) + End Sub +#End Region + +#Region "D E S C A R G A R - F A C T U R A " + Protected Sub lbDescargar_Click(sender As Object, e As EventArgs) Handles lbDescargar.Click + + Dim Retorno As Boolean = False + + Dim ObjProcess As Process = Nothing + Dim Mensajes As String = "" + Dim error1 As Boolean = False + Dim CountProcesados As Integer = 0 + + + + Try + ObjProcess = New Process() + ObjProcess.StartInfo.RedirectStandardOutput = True + ObjProcess.StartInfo.FileName = Ejecutable + ObjProcess.StartInfo.Arguments = $"--mod dsat2 --cveemp {UsuarioActual.CveEmpresa} --rfc {UsuarioActual.Empresa.RFC} --ciec {UsuarioActual.Empresa.CIEC} --razon {UsuarioActual.Empresa.Empresa} --fi {txtFechaI.Text} --ff {txtFechaF.Text}" + ObjProcess.StartInfo.UseShellExecute = False + ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal + ObjProcess.Start() + + + Dim myStreamReader As StreamReader = ObjProcess.StandardOutput + + 'Read the standard output of the spawned process. + Mensajes = myStreamReader.ReadLine() + If Mensajes.Length > 0 Then + + Dim msgs As String() = Mensajes.Split("|"c) + Dim NFacturas As Integer = 0 + + If msgs.Length >= 2 Then + Try + NFacturas = msgs(0).ToEntero + CountProcesados = msgs(0).ToEntero + Mensajes = $"La actualización se realizó correctamente.
Facturas agregadas: { NFacturas }" + Catch ex As Exception + NFacturas = 0 + Mensajes = "La actualización se realizó correctamente" + End Try + Else + Mensajes = "La descarga se realizó correctamente" + End If + End If + ObjProcess.WaitForExit() + ObjProcess.Close() + Retorno = True + Catch ex As Exception + error1 = True + OnError("Ocurrió un error al ejecutar el actualizador.", ex) + End Try + + If Retorno Then CargaDatos() + + + + + 'Dim Retorno As Boolean = False + ''Codigo anterior no borrar puede hacer el paro + + 'Dim ObjProcess As Process = Nothing + 'Dim Mensajes As String = "" + 'Dim EjecutableUtilerias = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilerias\UtileriasAD.exe") + 'Dim Folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Empresas\") + 'Dim error1 As Boolean = False + 'Dim en As New CultureInfo("en-US") + 'Dim fechai = txtFechaI.Text.Trim.ToDate.ToString("d", en) + 'Dim fechaf = txtFechaF.Text.Trim.ToDate.ToString("d", en) + 'Try + ' ObjProcess = New Process() + ' ObjProcess.StartInfo.RedirectStandardOutput = True + ' ObjProcess.StartInfo.FileName = EjecutableUtilerias + ' ObjProcess.StartInfo.Verb = "runas" + ' ObjProcess.StartInfo.Arguments = $"{UsuarioActual.CveEmpresa} {Folder} 1 {fechai} {fechaf}" + ' ObjProcess.StartInfo.UseShellExecute = False + ' ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal + ' ObjProcess.Start() + ' ObjProcess.WaitForExit() + ' ObjProcess.Close() + 'Catch ex As Exception + ' error1 = True + ' OnError("Ocurrió un error al ejecutar el actualizador.", ex) + 'End Try + + '' ProcesaBuzon() + + End Sub + + + 'Private Sub ProcesaBuzon() + ' Dim ObjProcess As Process = Nothing + ' Dim Mensajes As String = "" + ' Dim EjecutableUtilerias = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilerias\ADSUtilerias.exe") + ' Dim Folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Empresas\") + ' Dim error1 As Boolean = False + ' Dim en As New CultureInfo("en-US") + ' Dim fechai = txtFechaI.Text.Trim.ToDate.ToString("d", en) + ' Dim fechaf = txtFechaF.Text.Trim.ToDate.ToString("d", en) + ' Dim Salida As String = "" + ' Try + ' ObjProcess = New Process() + ' ObjProcess.StartInfo.RedirectStandardOutput = True + ' ObjProcess.StartInfo.FileName = EjecutableUtilerias + ' ObjProcess.StartInfo.Verb = "runas" + ' ObjProcess.StartInfo.Arguments = $"--mod dsat --e {UsuarioActual.CveEmpresa} --op 1 --fd {Folder} --fi {fechai} --ff {fechaf}" + ' ObjProcess.StartInfo.UseShellExecute = False + ' ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal + ' ObjProcess.Start() + ' Salida = ObjProcess.StandardOutput.ReadToEnd() + ' ObjProcess.WaitForExit() + ' ObjProcess.Close() + ' Catch ex As Exception + ' error1 = True + ' OnError("Ocurrió un error al ejecutar el actualizador.", ex) + ' End Try + 'End Sub + +#End Region + +#Region "B I T A C O R A" + Private Sub CargaGvBitacora() + Dim ObjGral As New ClsGenerales + If ObjGral.GetHistorialBitacoraRemoveGet("Compras", UsuarioActual.CveEmpresa) Then + GvBitacora.DataSource = ObjGral.DtResultados + ObjGral.Dispose() + End If + GvBitacora.DataBind() + End Sub + + Private Sub BtnRemove_Click(sender As Object, e As EventArgs) Handles BtnRemove.Click + Dim Borrar As Boolean = False + If Not TxtDescripcion.Text = "" Then + Dim ObjGral As New ClsGenerales + If ObjGral.AddHistorialBitacora(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 1, TxtDescripcion.Text, "Compras", Folio1 + " / " + Proveedor) Then + Borrar = True + End If + ObjGral.Dispose() + If Borrar = True Then + Dim ObjCompras As New ClsCompras + If ObjCompras.DeleteFactura(CveFactura) Then + GvD.EditIndex = -1 + RegistraScript(String.Format("$('#{0}').modal('hide');", "divDescripcion")) + Alert("La factura se eliminó correctamente.", TipoMensaje.MsgInformacion) + CargaDatos() + UpBitacora.Update() + End If + + ObjCompras.Dispose() + + End If + End If + CargaGvBitacora() + UpBitacora.Update() + End Sub + Private Sub BtnEliminarPago_Click(sender As Object, e As EventArgs) Handles BtnEliminarPago.Click + Dim Borrar As Boolean = False + If Not TxtDescripcion.Text = "" Then + Dim ObjGral As New ClsGenerales + If ObjGral.AddHistorialBitacora(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 1, TxtDescripcion.Text, "Compras", Folio1 + " / " + Proveedor) Then + Borrar = True + End If + ObjGral.Dispose() + If Borrar = True Then + Dim ObjCompras As New ClsCompras + If ObjCompras.DeleteFactura(CveFactura) Then + GvPagos.EditIndex = -1 + RegistraScript("$('#divDescripcionPago').modal('hide');") + Alert("La factura se eliminó correctamente.", TipoMensaje.MsgInformacion) + CargaDatos() + UpBitacora.Update() + End If + + ObjCompras.Dispose() + End If + End If + CargaGvBitacora() + UpBitacora.Update() + End Sub + + Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles BtnMostrar.Click + GvBitacora.Visible = True + BtnOcultar.Visible = True + BtnMostrar.Visible = False + UpBitacora.Update() + End Sub + + Private Sub BtnOcultar_Click(sender As Object, e As EventArgs) Handles BtnOcultar.Click + GvBitacora.Visible = False + BtnOcultar.Visible = False + BtnMostrar.Visible = True + UpBitacora.Update() + End Sub + +#End Region Property MSGComplemento As String @@ -2602,343 +2602,343 @@ Partial Class Compras_eFacturas End Property -#Region "V I N C U L A R P A G O" +#Region "V I N C U L A R P A G O" + + Protected Sub LnkAgregarPago_Click(sender As Object, e As EventArgs) + - Protected Sub LnkAgregarPago_Click(sender As Object, e As EventArgs) - - MSGComplemento = "" - ViculacionConPUE = False - ListaComprasPUE.Clear() + ViculacionConPUE = False + ListaComprasPUE.Clear() ComplementoConPUE = "" Dim ListaComprasPUEInterna As New List(Of Integer) - Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) - Dim CveComplementoPagoCompra As Integer = gvRow.DataKey("CveComplementoPagoCompra").ToString.ToEntero - - If CveComplementoPagoCompra > 0 Then - DVMensajecomplementoVinculado.Visible = True - Else - DVMensajecomplementoVinculado.Visible = False - End If - - Dim SerieFolioIE As String = "" - Dim UUIDPago As String = "" - 'Dim ImportePago As Decimal = 0 - Dim StrUUID As New StringBuilder - Dim Monto As Decimal = 0 - Dim nodePagos As XmlNode = Nothing - Dim nodePagos2 As XmlNode = Nothing - Dim nodeComp As XmlNode = Nothing - Dim nodeaGral As XmlNode = Nothing - Dim nodeTFD As XmlNode = Nothing - Dim ImporteIES As Double = 0 - Dim DiferenciaImportes As Double = 0 - Dim TextoDiferenciaImporte As String = "" - Dim FechaPago As Date + Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow) + Dim CveComplementoPagoCompra As Integer = gvRow.DataKey("CveComplementoPagoCompra").ToString.ToEntero + + If CveComplementoPagoCompra > 0 Then + DVMensajecomplementoVinculado.Visible = True + Else + DVMensajecomplementoVinculado.Visible = False + End If + + Dim SerieFolioIE As String = "" + Dim UUIDPago As String = "" + 'Dim ImportePago As Decimal = 0 + Dim StrUUID As New StringBuilder + Dim Monto As Decimal = 0 + Dim nodePagos As XmlNode = Nothing + Dim nodePagos2 As XmlNode = Nothing + Dim nodeComp As XmlNode = Nothing + Dim nodeaGral As XmlNode = Nothing + Dim nodeTFD As XmlNode = Nothing + Dim ImporteIES As Double = 0 + Dim DiferenciaImportes As Double = 0 + Dim TextoDiferenciaImporte As String = "" + Dim FechaPago As Date Dim PagosCantidad As Integer = 0 - Dim XMLDoc As New XmlDocument - Dim Archivo As String = String.Format("{0}Empresas\{1}\Compras\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, gvRow.DataKey("RFCDe"), gvRow.DataKey("XML")) - If IO.File.Exists(Archivo) Then - - - Dim SXML As String = File.ReadAllText(Archivo).Replace(vbLf, " ").Replace(vbCrLf, " ") - - SXML = SXML.Trim((Convert.ToChar(0))) - - XMLDoc.LoadXml(SXML) - - Dim Xml As New StringBuilder - Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) - - namespaces.AddNamespace(XMLDoc.DocumentElement.Prefix, "http://www.sat.gob.mx/cfd/3") - namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") - namespaces.AddNamespace("pago10", "http://www.sat.gob.mx/Pagos") - nodeComp = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", XMLDoc.DocumentElement.Prefix), namespaces) - - nodeaGral = XMLDoc.SelectSingleNode(String.Format("//{0}:Comprobante", XMLDoc.DocumentElement.Prefix), namespaces) - - nodeTFD = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces) - nodePagos = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos/{0}:Pago", "pago10"), namespaces) - nodePagos2 = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos", "pago10"), namespaces) - 'Monto = ValorXML(nodePagos, "Monto").ToDecimal - - Dim nodePago As XmlNodeList = nodePagos.SelectNodes(String.Format("//{0}:DoctoRelacionado", "pago10"), namespaces) - - SeriePago = ValorXML(nodeaGral, "Serie") - FolioPago = ValorXML(nodeaGral, "Folio") - - UUIDPago = ValorXML(nodeTFD, "UUID") - LblUUID.Text = UUIDPago - - Dim DTDocumentosRelacionados As New DataTable - DTDocumentosRelacionados.Columns.Add("Serie") - DTDocumentosRelacionados.Columns.Add("SerieFolio") - - DTDocumentosRelacionados.Columns.Add("IdDocumento") - DTDocumentosRelacionados.Columns.Add("Folio", GetType(Integer)) - DTDocumentosRelacionados.Columns.Add("MonedaDR") - DTDocumentosRelacionados.Columns.Add("MetodoDePagoDR") - DTDocumentosRelacionados.Columns.Add("ImpPagado", GetType(Decimal)) - - DTDocumentosRelacionados.Columns.Add("CveFactura", GetType(Integer)) - DTDocumentosRelacionados.Columns.Add("CveCompra", GetType(Integer)) - DTDocumentosRelacionados.Columns.Add("CveIE", GetType(Integer)) - DTDocumentosRelacionados.Columns.Add("Fecha", GetType(Date)) - - DTDocumentosRelacionados.Columns.Add("FolioPago") - DTDocumentosRelacionados.Columns.Add("ImportePago", GetType(Decimal)) - DTDocumentosRelacionados.Columns.Add("FechaPago", GetType(Date)) - DTDocumentosRelacionados.Columns.Add("CveMetodoPago", GetType(Integer)) - DTDocumentosRelacionados.Columns.Add("SerieFolioCompra") - - - - Dim nodePagosN As XmlNodeList - nodePagosN = nodeComp.SelectNodes(String.Format("//{0}:Pagos", "pago10"), namespaces) - - - - For Each NodosPagos As XmlNode In nodePagosN - For Each innernode As XmlNode In NodosPagos - - FechaPago = ValorXML(innernode, "FechaPago").ToDate - PagosCantidad = PagosCantidad + 1 - - For Each node As XmlNode In innernode - - Dim Nrow As DataRow = DTDocumentosRelacionados.NewRow - - Nrow("Serie") = ValorXML(node, "Serie") - Nrow("Folio") = ValorXML(node, "Folio").ToEntero - Nrow("SerieFolio") = ValorXML(node, "Serie") & "-" & ValorXML(node, "Folio").ToEntero - Nrow("IdDocumento") = ValorXML(node, "IdDocumento") - Nrow("MonedaDR") = ValorXML(node, "MonedaDR") - Nrow("MetodoDePagoDR") = ValorXML(node, "MetodoDePagoDR") - - Monto = Monto + ValorXML(node, "ImpPagado").ToDecimal - - Nrow("ImpPagado") = ValorXML(node, "ImpPagado").ToDecimal - Nrow("Fecha") = FechaPago - - DTDocumentosRelacionados.Rows.Add(Nrow) - StrUUID.AppendFormat("'{0}',", ValorXML(node, "IdDocumento").Replace("'", "")) - Next - - Next - Next - - 'ImportePago - 'For Each node As XmlNode In nodePago - - ' Dim Nrow As DataRow = DTDocumentosRelacionados.NewRow - - ' Nrow("Serie") = ValorXML(node, "Serie") - ' Nrow("Folio") = ValorXML(node, "Folio").ToEntero - ' Nrow("SerieFolio") = ValorXML(node, "Serie") & "-" & ValorXML(node, "Folio").ToEntero - ' Nrow("IdDocumento") = ValorXML(node, "IdDocumento") - ' Nrow("MonedaDR") = ValorXML(node, "MonedaDR") - ' Nrow("MetodoDePagoDR") = ValorXML(node, "MetodoDePagoDR") - ' Nrow("ImpPagado") = ValorXML(node, "ImpPagado").ToDecimal - ' Nrow("Fecha") = FechaPago - - ' DTDocumentosRelacionados.Rows.Add(Nrow) - ' StrUUID.AppendFormat("'{0}',", ValorXML(node, "IdDocumento").Replace("'", "")) - 'Next - - Dim ObjCompraFolios As New ClsCompras - If ObjCompraFolios.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa, OP:=2) Then - ' - '.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa) Then - If ObjCompraFolios.DtResultados.Rows.Count > 0 Then - For Each drow As DataRow In ObjCompraFolios.DtResultados.Rows - - For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows - - If dRow2("IdDocumento").ToString.ToUpper = drow("IdDocumento").ToString.ToUpper Then - - dRow2("CveCompra") = drow("CveCompra").ToString.ToEntero - dRow2("CveFactura") = drow("CveFactura").ToString.ToEntero - dRow2("CveMetodoPago") = drow("CveMetodoPago").ToString.ToEntero - dRow2("SerieFolioCompra") = drow("SerieFolioCompra").ToString - - - If drow("CveIE").ToString.ToEntero > 0 Then - - dRow2("CveIE") = drow("CveIE").ToString.ToEntero - dRow2("ImportePago") = drow("Importe").ToString.ToDecimal - - - End If - - dRow2("FolioPago") = drow("FolioIE") - dRow2("FechaPago") = drow("FechaDocumento") - - - - - End If - Next - Next - End If - End If - - ObjCompraFolios.Dispose() - GVPDocumentosRelacionadosPagos.DataSource = DTDocumentosRelacionados - GVPDocumentosRelacionadosPagos.DataBind() - - - For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows - If dRow2("CveMetodoPago").ToString.ToEntero > 0 Then - If dRow2("CveMetodoPago").ToString.ToEntero = 1 Then - MSGComplemento = MSGComplemento & $" Compra {dRow2("SerieFolioCompra").ToString } bloqueado Tipo ""PUE"". " - - ListaComprasPUEInterna.Add(dRow2("CveCompra").ToString.ToEntero) - + Dim XMLDoc As New XmlDocument + Dim Archivo As String = String.Format("{0}Empresas\{1}\Compras\{2}\{3}", AppDomain.CurrentDomain.BaseDirectory, UsuarioActual.CveEmpresa, gvRow.DataKey("RFCDe"), gvRow.DataKey("XML")) + If IO.File.Exists(Archivo) Then + + + Dim SXML As String = File.ReadAllText(Archivo).Replace(vbLf, " ").Replace(vbCrLf, " ") + + SXML = SXML.Trim((Convert.ToChar(0))) + + XMLDoc.LoadXml(SXML) + + Dim Xml As New StringBuilder + Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable) + + namespaces.AddNamespace(XMLDoc.DocumentElement.Prefix, "http://www.sat.gob.mx/cfd/3") + namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital") + namespaces.AddNamespace("pago10", "http://www.sat.gob.mx/Pagos") + nodeComp = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", XMLDoc.DocumentElement.Prefix), namespaces) + + nodeaGral = XMLDoc.SelectSingleNode(String.Format("//{0}:Comprobante", XMLDoc.DocumentElement.Prefix), namespaces) + + nodeTFD = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces) + nodePagos = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos/{0}:Pago", "pago10"), namespaces) + nodePagos2 = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos", "pago10"), namespaces) + 'Monto = ValorXML(nodePagos, "Monto").ToDecimal + + Dim nodePago As XmlNodeList = nodePagos.SelectNodes(String.Format("//{0}:DoctoRelacionado", "pago10"), namespaces) + + SeriePago = ValorXML(nodeaGral, "Serie") + FolioPago = ValorXML(nodeaGral, "Folio") + + UUIDPago = ValorXML(nodeTFD, "UUID") + LblUUID.Text = UUIDPago + + Dim DTDocumentosRelacionados As New DataTable + DTDocumentosRelacionados.Columns.Add("Serie") + DTDocumentosRelacionados.Columns.Add("SerieFolio") + + DTDocumentosRelacionados.Columns.Add("IdDocumento") + DTDocumentosRelacionados.Columns.Add("Folio", GetType(Integer)) + DTDocumentosRelacionados.Columns.Add("MonedaDR") + DTDocumentosRelacionados.Columns.Add("MetodoDePagoDR") + DTDocumentosRelacionados.Columns.Add("ImpPagado", GetType(Decimal)) + + DTDocumentosRelacionados.Columns.Add("CveFactura", GetType(Integer)) + DTDocumentosRelacionados.Columns.Add("CveCompra", GetType(Integer)) + DTDocumentosRelacionados.Columns.Add("CveIE", GetType(Integer)) + DTDocumentosRelacionados.Columns.Add("Fecha", GetType(Date)) + + DTDocumentosRelacionados.Columns.Add("FolioPago") + DTDocumentosRelacionados.Columns.Add("ImportePago", GetType(Decimal)) + DTDocumentosRelacionados.Columns.Add("FechaPago", GetType(Date)) + DTDocumentosRelacionados.Columns.Add("CveMetodoPago", GetType(Integer)) + DTDocumentosRelacionados.Columns.Add("SerieFolioCompra") + + + + Dim nodePagosN As XmlNodeList + nodePagosN = nodeComp.SelectNodes(String.Format("//{0}:Pagos", "pago10"), namespaces) + + + + For Each NodosPagos As XmlNode In nodePagosN + For Each innernode As XmlNode In NodosPagos + + FechaPago = ValorXML(innernode, "FechaPago").ToDate + PagosCantidad = PagosCantidad + 1 + + For Each node As XmlNode In innernode + + Dim Nrow As DataRow = DTDocumentosRelacionados.NewRow + + Nrow("Serie") = ValorXML(node, "Serie") + Nrow("Folio") = ValorXML(node, "Folio").ToEntero + Nrow("SerieFolio") = ValorXML(node, "Serie") & "-" & ValorXML(node, "Folio").ToEntero + Nrow("IdDocumento") = ValorXML(node, "IdDocumento") + Nrow("MonedaDR") = ValorXML(node, "MonedaDR") + Nrow("MetodoDePagoDR") = ValorXML(node, "MetodoDePagoDR") + + Monto = Monto + ValorXML(node, "ImpPagado").ToDecimal + + Nrow("ImpPagado") = ValorXML(node, "ImpPagado").ToDecimal + Nrow("Fecha") = FechaPago + + DTDocumentosRelacionados.Rows.Add(Nrow) + StrUUID.AppendFormat("'{0}',", ValorXML(node, "IdDocumento").Replace("'", "")) + Next + + Next + Next + + 'ImportePago + 'For Each node As XmlNode In nodePago + + ' Dim Nrow As DataRow = DTDocumentosRelacionados.NewRow + + ' Nrow("Serie") = ValorXML(node, "Serie") + ' Nrow("Folio") = ValorXML(node, "Folio").ToEntero + ' Nrow("SerieFolio") = ValorXML(node, "Serie") & "-" & ValorXML(node, "Folio").ToEntero + ' Nrow("IdDocumento") = ValorXML(node, "IdDocumento") + ' Nrow("MonedaDR") = ValorXML(node, "MonedaDR") + ' Nrow("MetodoDePagoDR") = ValorXML(node, "MetodoDePagoDR") + ' Nrow("ImpPagado") = ValorXML(node, "ImpPagado").ToDecimal + ' Nrow("Fecha") = FechaPago + + ' DTDocumentosRelacionados.Rows.Add(Nrow) + ' StrUUID.AppendFormat("'{0}',", ValorXML(node, "IdDocumento").Replace("'", "")) + 'Next + + Dim ObjCompraFolios As New ClsCompras + If ObjCompraFolios.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa, OP:=2) Then + ' + '.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa) Then + If ObjCompraFolios.DtResultados.Rows.Count > 0 Then + For Each drow As DataRow In ObjCompraFolios.DtResultados.Rows + + For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows + + If dRow2("IdDocumento").ToString.ToUpper = drow("IdDocumento").ToString.ToUpper Then + + dRow2("CveCompra") = drow("CveCompra").ToString.ToEntero + dRow2("CveFactura") = drow("CveFactura").ToString.ToEntero + dRow2("CveMetodoPago") = drow("CveMetodoPago").ToString.ToEntero + dRow2("SerieFolioCompra") = drow("SerieFolioCompra").ToString + + + If drow("CveIE").ToString.ToEntero > 0 Then + + dRow2("CveIE") = drow("CveIE").ToString.ToEntero + dRow2("ImportePago") = drow("Importe").ToString.ToDecimal + + + End If + + dRow2("FolioPago") = drow("FolioIE") + dRow2("FechaPago") = drow("FechaDocumento") + + + + + End If + Next + Next + End If + End If + + ObjCompraFolios.Dispose() + GVPDocumentosRelacionadosPagos.DataSource = DTDocumentosRelacionados + GVPDocumentosRelacionadosPagos.DataBind() + + + For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows + If dRow2("CveMetodoPago").ToString.ToEntero > 0 Then + If dRow2("CveMetodoPago").ToString.ToEntero = 1 Then + MSGComplemento = MSGComplemento & $" Compra {dRow2("SerieFolioCompra").ToString } bloqueado Tipo ""PUE"". " + + ListaComprasPUEInterna.Add(dRow2("CveCompra").ToString.ToEntero) + ComplementoConPUE = $"{SeriePago}-{FolioPago}" - End If - End If - Next - - Else - Alert("Ocurrió un error al cargar los archivos de complementos pago", TipoMensaje.MsgError) - End If - - CveFacturaPago = gvRow.DataKey("CveFactura").ToEntero - CveProveedor = gvRow.DataKey("CveProveedor").ToEntero - Dim ObjCompras As New ClsCompras - - If ObjCompras.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa) Then - GvVincularPago.DataSource = ObjCompras.DtResultados - - If ObjCompras.DtResultados.Rows.Count > 0 Then - SerieFolioIE = ObjCompras.DtResultados.Rows(0)("SerieFolio").ToString - DivVincularPagoManualmente.Visible = False - BtnVincularPago.Visible = True - - Else - DivVincularPagoManualmente.Visible = True - BtnVincularPago.Visible = False - End If - 'ImportePago = ObjCompras.DtResultados.SUMD("Monto") - Else - DivVincularPagoManualmente.Visible = False - BtnVincularPago.Visible = False - End If - - - - For Each drow As DataRow In ObjCompras.DtResultados.FiltraParametros("CveIE > 0 AND FechaDocumento IS NOT NULL", "", {"FechaDocumento"}).Rows - - Dim FechaDocumento As Date = drow("FechaDocumento").ToString.ToDate - - Dim FT1 As Date = FechaDocumento.AddDays(-6) - Dim FT2 As Date = FechaDocumento.AddDays(7) - - If Not (FechaPago >= FT1 And FechaPago < FT2) Then - - BtnVincularPago.Visible = False - MSGComplemento = MSGComplemento & " Existen mas de 3 días de diferencia entre la fecha del documento y la fecha de complemento. " - - Exit For - End If - - Next - + End If + End If + Next + + Else + Alert("Ocurrió un error al cargar los archivos de complementos pago", TipoMensaje.MsgError) + End If + + CveFacturaPago = gvRow.DataKey("CveFactura").ToEntero + CveProveedor = gvRow.DataKey("CveProveedor").ToEntero + Dim ObjCompras As New ClsCompras + + If ObjCompras.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa) Then + GvVincularPago.DataSource = ObjCompras.DtResultados + + If ObjCompras.DtResultados.Rows.Count > 0 Then + SerieFolioIE = ObjCompras.DtResultados.Rows(0)("SerieFolio").ToString + DivVincularPagoManualmente.Visible = False + BtnVincularPago.Visible = True + + Else + DivVincularPagoManualmente.Visible = True + BtnVincularPago.Visible = False + End If + 'ImportePago = ObjCompras.DtResultados.SUMD("Monto") + Else + DivVincularPagoManualmente.Visible = False + BtnVincularPago.Visible = False + End If + + + + For Each drow As DataRow In ObjCompras.DtResultados.FiltraParametros("CveIE > 0 AND FechaDocumento IS NOT NULL", "", {"FechaDocumento"}).Rows + + Dim FechaDocumento As Date = drow("FechaDocumento").ToString.ToDate + + Dim FT1 As Date = FechaDocumento.AddDays(-6) + Dim FT2 As Date = FechaDocumento.AddDays(7) + + If Not (FechaPago >= FT1 And FechaPago < FT2) Then + + BtnVincularPago.Visible = False + MSGComplemento = MSGComplemento & " Existen mas de 3 días de diferencia entre la fecha del documento y la fecha de complemento. " + + Exit For + End If + + Next + If MSGComplemento.Trim.Length > 0 Then ' BtnVincularPago.Visible = False ViculacionConPUE = True - End If - - - - 'saco la información de lo vinculado en el ie - - ImporteIES = ObjCompras.DtResultados.FiltraParametros("CveIE > 0").SUM("Importe") - - - DiferenciaImportes = Monto - ImporteIES - ObjCompras.Dispose() - - - If Math.Abs(DiferenciaImportes) > 5 Then - TextoDiferenciaImporte = $"  -   IE ${ImporteIES.FormatoNumero}
Diferencia { DiferenciaImportes.FormatoNumero() }
" - BtnVincularPago.Visible = False - MSGComplemento = MSGComplemento & $" Existe una diferencia mayor a $5.00 ({Math.Abs(DiferenciaImportes)})" - Else - 'BtnVincularPago.Visible = True - 'TextoDiferenciaImporte = "" - End If - - - LblSerieFolioPago.Text = $"{SeriePago}-{FolioPago}" - LblImportePago.Text = Monto.ToString("###,###,###.00") 'ImportePago.FormatoNumero - LblPagosCantidad.Text = PagosCantidad.ToString - LblImporteIE.Text = ImporteIES.FormatoNumero - LblDiferencia.Text = If(DiferenciaImportes <> 0, DiferenciaImportes.FormatoNumero, "") - - - If MSGComplemento.Trim.Length > 0 And CveComplementoPagoCompra <= 0 Then - LblMensajeComlementoError.Text = MSGComplemento - DVMensajecomplementoError.Visible = True - - Else - LblMensajeComlementoError.Text = "" - DVMensajecomplementoError.Visible = False - - End If - - - GvVincularPago.DataBind() + End If + + + + 'saco la información de lo vinculado en el ie + + ImporteIES = ObjCompras.DtResultados.FiltraParametros("CveIE > 0").SUM("Importe") + + + DiferenciaImportes = Monto - ImporteIES + ObjCompras.Dispose() + + + If Math.Abs(DiferenciaImportes) > 5 Then + TextoDiferenciaImporte = $"  -   IE ${ImporteIES.FormatoNumero}
Diferencia { DiferenciaImportes.FormatoNumero() }
" + BtnVincularPago.Visible = False + MSGComplemento = MSGComplemento & $" Existe una diferencia mayor a $5.00 ({Math.Abs(DiferenciaImportes)})" + Else + 'BtnVincularPago.Visible = True + 'TextoDiferenciaImporte = "" + End If + + + LblSerieFolioPago.Text = $"{SeriePago}-{FolioPago}" + LblImportePago.Text = Monto.ToString("###,###,###.00") 'ImportePago.FormatoNumero + LblPagosCantidad.Text = PagosCantidad.ToString + LblImporteIE.Text = ImporteIES.FormatoNumero + LblDiferencia.Text = If(DiferenciaImportes <> 0, DiferenciaImportes.FormatoNumero, "") + + + If MSGComplemento.Trim.Length > 0 And CveComplementoPagoCompra <= 0 Then + LblMensajeComlementoError.Text = MSGComplemento + DVMensajecomplementoError.Visible = True + + Else + LblMensajeComlementoError.Text = "" + DVMensajecomplementoError.Visible = False + + End If + + + GvVincularPago.DataBind() UpVincularPago.Update() ListaComprasPUE = ListaComprasPUEInterna - RegistraScript("$('#ModalVincularPago').modal('show')", "VincularPagoModalShow") - End Sub - - Private Sub BtnVincularPago_Click(sender As Object, e As EventArgs) Handles BtnVincularPago.Click - - 'VERIFICA QUE HALLA UN PAGO - 'Dim Contador = 0 - 'For Each Gv As GridViewRow In GvVincularPago.Rows - ' If Gv.FCCheckBox("ChkVincularPago").Checked Then - ' Contador = 1 - ' Exit For - ' End If - 'Next - 'If Contador = 0 Then - ' Alert("Tiene que seleccionar algun pago. Por favor verifique y vuelta a intentar.", TipoMensaje.MsgAdvertencia) - ' Exit Sub - 'End If - - Dim TieneError = False - Dim ObjCompra As New ClsCompras - ObjCompra.IniciaTransacSQL() - - - For Each Gv As GridViewRow In GvVincularPago.Rows - - If Not ObjCompra.AddComplementoPago(Gv.DataKey("CveIE").ToEntero, Gv.DataKey("CveCompra").ToEntero, Gv.DataKey("Monto").ToDecimal, Gv.DataKey("CvePrePolizaDetalle").ToEntero, CveFacturaPago) > 0 Then - TieneError = True - End If - - - Next - - If Not TieneError AndAlso Not ObjCompra.AddVincularPago(CveFacturaPago) Then - TieneError = True - End If - + RegistraScript("$('#ModalVincularPago').modal('show')", "VincularPagoModalShow") + End Sub + + Private Sub BtnVincularPago_Click(sender As Object, e As EventArgs) Handles BtnVincularPago.Click + + 'VERIFICA QUE HALLA UN PAGO + 'Dim Contador = 0 + 'For Each Gv As GridViewRow In GvVincularPago.Rows + ' If Gv.FCCheckBox("ChkVincularPago").Checked Then + ' Contador = 1 + ' Exit For + ' End If + 'Next + 'If Contador = 0 Then + ' Alert("Tiene que seleccionar algun pago. Por favor verifique y vuelta a intentar.", TipoMensaje.MsgAdvertencia) + ' Exit Sub + 'End If + + Dim TieneError = False + Dim ObjCompra As New ClsCompras + ObjCompra.IniciaTransacSQL() + + + For Each Gv As GridViewRow In GvVincularPago.Rows + + If Not ObjCompra.AddComplementoPago(Gv.DataKey("CveIE").ToEntero, Gv.DataKey("CveCompra").ToEntero, Gv.DataKey("Monto").ToDecimal, Gv.DataKey("CvePrePolizaDetalle").ToEntero, CveFacturaPago) > 0 Then + TieneError = True + End If + + + Next + + If Not TieneError AndAlso Not ObjCompra.AddVincularPago(CveFacturaPago) Then + TieneError = True + End If + If Not TieneError Then Dim objEventos As New ClsOIEventos(ObjCompra.IniciaTransacSQL) @@ -2958,415 +2958,415 @@ Partial Class Compras_eFacturas End If - ObjCompra.Commit() - - Alert("El pago fue vinculado correctamente", TipoMensaje.MsgInformacion) + ObjCompra.Commit() + + Alert("El pago fue vinculado correctamente", TipoMensaje.MsgInformacion) RegistraScript("$('#ModalVincularPago').modal('hide')", "VincularPagoModalHide") - CargaDatos() - Else - ObjCompra.RollBack() - Alert("Ocurrió un error al vincular el pago. Por favor verifique y vuelva a intentar", TipoMensaje.MsgError) - End If - ObjCompra.Dispose() - - - End Sub - - Protected Sub ChkVincularPago_CheckedChanged(sender As Object, e As EventArgs) - - For Each Gvr As GridViewRow In GvVincularPago.Rows - Gvr.FCCheckBox("ChkVincularPago").Checked = False - Next - - CType(sender, CheckBox).Checked = True - End Sub - - Protected Sub BtnVincularManualmente_Click(sender As Object, e As EventArgs) - If HdnCveIE.Value <> "-1" AndAlso IsNumeric(HdnCveIE.Value) AndAlso HdnCveIE.Value.ToEntero > 0 Then - Dim ImportePago As Double = 0 - Dim ImporteIES As Double = 0 - Dim SerieFolioIE As String = "" - Dim ObjCompras As New ClsCompras - If ObjCompras.GetCompararComplementoPago(CveProveedor, -1, "", UsuarioActual.CveEmpresa, HdnCveIE.Value.ToEntero) Then - GvVincularPago.DataSource = ObjCompras.DtResultados - If ObjCompras.DtResultados.Rows.Count > 0 Then - SerieFolioIE = ObjCompras.DtResultados.Rows(0)("SerieFolio").ToString - End If - ImportePago = ObjCompras.DtResultados.SUMD("Monto") - End If - - ImporteIES = ObjCompras.DtResultados.FiltraParametros("CveIE > 0").SUM("Importe") - ObjCompras.Dispose() - - BtnVincularPago.Visible = True - - LblSerieFolioPago.Text = $"{SeriePago}-{FolioPago}" - LblImportePago.Text = ImportePago.FormatoNumero - 'LblSerieFolioIE.Text = SerieFolioIE - LblImporteIE.Text = ImporteIES.FormatoNumero - - GvVincularPago.DataBind() - UpVincularPago.Update() - ObjCompras.Dispose() - End If - End Sub - - Private Sub GVPDocumentosRelacionadosPagos_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GVPDocumentosRelacionadosPagos.RowCreated - - If e.Row.RowType = DataControlRowType.Header Then - Dim HeaderGrid = DirectCast(sender, GridView) - Dim HeaderGridRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert) - Dim HeaderCell = New TableCell - - HeaderCell.Text = "Documentos Relacionados" - HeaderCell.ColumnSpan = 8 - HeaderCell.Attributes.Add("style", "border-top: 1px solid #ddd; vertical-align: top; background-color: #DDD; color: #333333;font-family: 'Open Sans', sans-serif;font-size: 12px; text-align:center!important; font-weight: bold;") - HeaderGridRow.Cells.Add(HeaderCell) - GVPDocumentosRelacionadosPagos.Controls(0).Controls.AddAt(0, HeaderGridRow) - - End If - - End Sub - - Private Sub GVPDocumentosRelacionadosPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVPDocumentosRelacionadosPagos.RowDataBound - - If e.Row.RowType = DataControlRowType.DataRow Then - - If e.Row.DataKey("CveFactura").ToEntero > 0 Then - - If e.Row.DataKey("CveCompra").ToEntero > 0 Then - e.Row.Cells(4).Text = "" - e.Row.ToolTip = "Compra registrada" - e.Row.Cells(4).ForeColor = Drawing.Color.Green - - Else - e.Row.Cells(4).Text = "" - e.Row.ToolTip = "Factura recibida sin registrar" - End If - - - Else - e.Row.Cells(4).Text = "" - e.Row.ToolTip = "No se encontro el Folio Fiscal en el sistema" - e.Row.Cells(4).ForeColor = Drawing.Color.Red - End If - End If - - End Sub - - -#End Region - - - - Public Sub ImprimirPDFXML(NombreArchivo As String, rutaxml As String) - Dim objxml As XmlSatCFDI = XmlSatCFDI.readXML(rutaxml) - - Dim rutaReporte As String = String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\Grales\Formatos\CFDIV3.rdlc") - Dim QR As ClbNegBICFDv3_2.ClsNegCBBGenerar = New ClbNegBICFDv3_2.ClsNegCBBGenerar() - Dim cQr As Byte() = QR.GenerarCBBBytes(objxml.emisor.Rfc, objxml.receptor.Rfc, objxml.comprobante.Total, objxml.complemento.UUID) - Dim parametros As List(Of ReportParameter) = New List(Of ReportParameter)() - parametros.Add(New ReportParameter("comprobante_Certificado", objxml.comprobante.Certificado)) - parametros.Add(New ReportParameter("comprobante_CondicionesDePago", objxml.comprobante.CondicionesDePago)) - parametros.Add(New ReportParameter("comprobante_Confirmacion", objxml.comprobante.Confirmacion)) - parametros.Add(New ReportParameter("comprobante_Fecha", objxml.comprobante.Fecha)) - parametros.Add(New ReportParameter("comprobante_Serie", objxml.comprobante.Serie)) - parametros.Add(New ReportParameter("comprobante_Folio", objxml.comprobante.Folio)) - parametros.Add(New ReportParameter("comprobante_Descuento", objxml.comprobante.Descuento.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_SubTotal", objxml.comprobante.SubTotal.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_Total", objxml.comprobante.Total.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_Version", objxml.comprobante.Version)) - parametros.Add(New ReportParameter("comprobante_TipoDeComprobante", objxml.comprobante.TipoDeComprobanteTexto)) - parametros.Add(New ReportParameter("comprobante_FormaPago", objxml.comprobante.FormaPagoTexto)) - parametros.Add(New ReportParameter("comprobante_LugarExpedicion", objxml.comprobante.LugarExpedicion)) - parametros.Add(New ReportParameter("comprobante_NoCertificado", objxml.comprobante.NoCertificado)) - parametros.Add(New ReportParameter("comprobante_Sello", objxml.comprobante.Sello)) - parametros.Add(New ReportParameter("comprobante_Moneda", objxml.comprobante.Moneda)) - parametros.Add(New ReportParameter("comprobante_TipoCambio", objxml.comprobante.TipoCambio.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_MetodoPago", objxml.comprobante.MetodoPagoTexto)) - parametros.Add(New ReportParameter("emisor_Rfc", objxml.emisor.Rfc)) - parametros.Add(New ReportParameter("emisor_Nombre", objxml.emisor.Nombre)) - parametros.Add(New ReportParameter("emisor_RegimenFiscal", objxml.emisor.RegimenFiscalTexto)) - parametros.Add(New ReportParameter("receptor_Rfc", objxml.receptor.Rfc)) - parametros.Add(New ReportParameter("receptor_Nombre", objxml.receptor.Nombre)) - parametros.Add(New ReportParameter("receptor_NumRegIdTrib", objxml.receptor.NumRegIdTrib)) - parametros.Add(New ReportParameter("receptor_ResidenciaFiscal", objxml.receptor.ResidenciaFiscal)) - parametros.Add(New ReportParameter("receptor_UsoCFDI", objxml.receptor.UsoCFDITexto)) - parametros.Add(New ReportParameter("complemento_FechaTimbrado", objxml.complemento.FechaTimbrado)) - parametros.Add(New ReportParameter("complemento_NoCertificadoSAT", objxml.complemento.NoCertificadoSAT)) - parametros.Add(New ReportParameter("complemento_RfcProvCertif", objxml.complemento.RfcProvCertif)) - parametros.Add(New ReportParameter("complemento_SelloCFD", objxml.complemento.SelloCFD)) - parametros.Add(New ReportParameter("complemento_SelloSAT", objxml.complemento.SelloSAT)) - parametros.Add(New ReportParameter("complemento_UUID", objxml.complemento.UUID)) - parametros.Add(New ReportParameter("complemento_CadenaOriginal", objxml.complemento.CadenaOriginal)) - - Using MR As ReportViewer = New ReportViewer() - Dim rdsTotales As ReportDataSource = New ReportDataSource() - Dim ltotales As List(Of utilValores) = New List(Of utilValores)() - ltotales.Add(New utilValores("Subtotal", objxml.comprobante.SubTotal.ToString("N2"))) - - If objxml.comprobante.Descuento > 0 Then - ltotales.Add(New utilValores("Descuento", objxml.comprobante.Descuento.ToString("N2"))) - End If - - For Each item As CFDIImpuesto In objxml.Impuestos - - If item.Importe > 0 Then - Dim TasaOCuota As Decimal = 0 - Decimal.TryParse(item.TasaOCuota, TasaOCuota) - ltotales.Add(New utilValores($"Impuestos {item.Tipo} {item.ImpuestoTexto} {(If(item.TipoFactor = "Tasa", (TasaOCuota * 100).ToString("N4"), item.TasaOCuota))} {(If(item.TipoFactor = "Tasa", "%", ""))}", item.Importe.ToString("N2"))) - End If - Next - - ltotales.Add(New utilValores("Total", objxml.comprobante.Total.ToString("N2"))) - rdsTotales.Name = "dsTotales" - rdsTotales.Value = ltotales - MR.LocalReport.DataSources.Add(rdsTotales) - Dim rds2 As ReportDataSource = New ReportDataSource() - Dim limagenes As List(Of utilImage) = New List(Of utilImage)() - limagenes.Add(New utilImage(cQr)) - rds2.Name = "dsImagenes" - rds2.Value = limagenes - MR.LocalReport.DataSources.Add(rds2) - Dim rdsrelacionados As ReportDataSource = New ReportDataSource() - rdsrelacionados.Name = "dsRelacionados" - rdsrelacionados.Value = objxml.cFDIRelacionados - MR.LocalReport.DataSources.Add(rdsrelacionados) - Dim rds1 As ReportDataSource = New ReportDataSource() - rds1.Name = "dsConceptos" - rds1.Value = objxml.GetConceptosforpdf() - MR.LocalReport.DataSources.Add(rds1) - MR.LocalReport.ReportPath = rutaReporte - MR.ProcessingMode = ProcessingMode.Local - MR.LocalReport.EnableExternalImages = True - MR.LocalReport.SetParameters(parametros) - MR.LocalReport.Refresh() - Dim warnings As Warning() = Nothing - Dim streamids As String() = Nothing - Dim mimeType As String = Nothing - Dim encoding As String = Nothing - Dim extension As String = Nothing - Dim bytes As Byte() = Nothing - bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings) - - Using fs As FileStream = New FileStream(NombreArchivo, FileMode.Create) - fs.Write(bytes, 0, bytes.Length) - fs.Close() - End Using - End Using - End Sub - Protected Sub lnkRegenerarPDF_Click(sender As Object, e As EventArgs) - Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - Dim strRFCde As String = gvrow.DataKey("RFCde") - Dim strXml As String - Dim strPDF As String - Dim dirbase As String = String.Format("{0}{1}{2}{3}{4}\", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\", UsuarioActual.CveEmpresa, "\Compras\", strRFCde) - If Directory.Exists(dirbase) Then - strXml = String.Format("{0}{1}", dirbase, gvrow.DataKey("XML")) - strPDF = String.Format("{0}{1}", dirbase, gvrow.DataKey("PDF")) - If File.Exists(strXml) Then - ImprimirPDFXML(strPDF, strXml) - Alert("el pdf se regenero satisfactoriamente.") - Else - Alert($"No se encontro el xml favor de contactar a soporte tecnico{strXml.Replace("\", "/")}") - End If - Else - Alert($"No se encontro el xml favor de contactar a soporte tecnico{dirbase.Replace("\", "/")}") - End If - ',PDF - ' - 'ImprimirPDFXML("C:\Generar PFX\405504.pdf", "C:\Generar PFX\405504.xml") - End Sub - Private Sub removeasincevent() - - 'For Each GvRow As GridViewRow In GvD.Rows - ' Dim lnkDownPdf As LinkButton = GvRow.FCLinkButton("lnkDownPdf") - ' Dim lnkXML As LinkButton = GvRow.FCLinkButton("lnkXML") - ' If lnkDownPdf.Visible Then - - ' ScriptManager.GetCurrent(Me).RegisterPostBackControl(lnkDownPdf) - ' End If - ' If lnkXML.Visible Then - ' ScriptManager.GetCurrent(Me).RegisterPostBackControl(lnkXML) - ' End If - 'Next - End Sub - Protected Sub lnkDownPdf_Click(sender As Object, e As EventArgs) - Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - Dim strRFCde As String = gvrow.DataKey("RFCde") - Dim strPDF As String - Dim dirbase As String = String.Format("{0}{1}{2}{3}{4}\", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\", UsuarioActual.CveEmpresa, "\Compras\", strRFCde) - strPDF = String.Format("{0}{1}", dirbase, gvrow.DataKey("PDF")) - If File.Exists(strPDF) Then - Dim file As New System.IO.FileInfo(strPDF) - Dim mimeType As String = "text/plain" - Try - mimeType = MimeMapping.GetMimeMapping(strPDF) - Catch ex As Exception - End Try - Response.Clear() - Response.ClearHeaders() - Response.ClearContent() - Response.AddHeader("Content-Disposition", $"attachment; filename= {Uri.EscapeDataString(file.Name)}") - Response.AddHeader("Content-Length", file.Length.ToString()) - Response.ContentType = mimeType - Response.Flush() - Response.TransmitFile(file.FullName) - Response.End() - End If - End Sub - Protected Sub lnkXML_Click(sender As Object, e As EventArgs) - Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - Dim strRFCde As String = gvrow.DataKey("RFCde") - Dim strXml As String - Dim dirbase As String = String.Format("{0}{1}{2}{3}{4}\", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\", UsuarioActual.CveEmpresa, "\Compras\", strRFCde) - strXml = String.Format("{0}{1}", dirbase, gvrow.DataKey("XML")) - If File.Exists(strXml) Then - Dim file As New System.IO.FileInfo(strXml) - Dim mimeType As String = "text/plain" - Try - mimeType = MimeMapping.GetMimeMapping(strXml) - Catch ex As Exception - End Try - Response.Clear() - Response.ClearHeaders() - Response.ClearContent() - Response.AddHeader("Content-Disposition", $"attachment; filename= {Uri.EscapeDataString(file.Name)}") - Response.AddHeader("Content-Length", file.Length.ToString()) - Response.ContentType = mimeType - Response.Flush() - Response.TransmitFile(file.FullName) - Response.End() - End If - End Sub - Protected Sub LnkRegenerarPdfnew_Click(sender As Object, e As EventArgs) - Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) - Dim objxml As XmlSatCFDI = XmlSatCFDI.readXML(String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("XML"))) - If Not IsNothing(objxml) Then - Dim rutaReporte As String = String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\Grales\Formatos\CFDIV3.rdlc") - If Not IsNothing(objxml.complemento.Pagos) Then - rutaReporte = String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\Grales\Formatos\CFDIV3Pago.rdlc") - End If - Dim NombreArchivo As String = String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("PDF")) - - - Dim QR As ClbNegBICFDv3_2.ClsNegCBBGenerar = New ClbNegBICFDv3_2.ClsNegCBBGenerar() - Dim cQr As Byte() = QR.GenerarCBBBytes(objxml.emisor.Rfc, objxml.receptor.Rfc, If(IsNothing(objxml.complemento.Pagos), objxml.comprobante.Total, objxml.complemento.Pagos.Monto), objxml.complemento.UUID) - Dim parametros As List(Of ReportParameter) = New List(Of ReportParameter)() - parametros.Add(New ReportParameter("comprobante_Certificado", objxml.comprobante.Certificado)) - parametros.Add(New ReportParameter("comprobante_CondicionesDePago", objxml.comprobante.CondicionesDePago)) - parametros.Add(New ReportParameter("comprobante_Confirmacion", objxml.comprobante.Confirmacion)) - parametros.Add(New ReportParameter("comprobante_Fecha", objxml.comprobante.Fecha)) - parametros.Add(New ReportParameter("comprobante_Serie", objxml.comprobante.Serie)) - parametros.Add(New ReportParameter("comprobante_Folio", objxml.comprobante.Folio)) - parametros.Add(New ReportParameter("comprobante_Descuento", objxml.comprobante.Descuento.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_SubTotal", objxml.comprobante.SubTotal.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_Total", objxml.comprobante.Total.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_Version", objxml.comprobante.Version)) - parametros.Add(New ReportParameter("comprobante_TipoDeComprobante", objxml.comprobante.TipoDeComprobanteTexto)) - parametros.Add(New ReportParameter("comprobante_FormaPago", objxml.comprobante.FormaPagoTexto)) - parametros.Add(New ReportParameter("comprobante_LugarExpedicion", objxml.comprobante.LugarExpedicion)) - parametros.Add(New ReportParameter("comprobante_NoCertificado", objxml.comprobante.NoCertificado)) - parametros.Add(New ReportParameter("comprobante_Sello", objxml.comprobante.Sello)) - parametros.Add(New ReportParameter("comprobante_Moneda", objxml.comprobante.Moneda)) - parametros.Add(New ReportParameter("comprobante_TipoCambio", objxml.comprobante.TipoCambio.ToString("N2"))) - parametros.Add(New ReportParameter("comprobante_MetodoPago", objxml.comprobante.MetodoPagoTexto)) - parametros.Add(New ReportParameter("emisor_Rfc", objxml.emisor.Rfc)) - parametros.Add(New ReportParameter("emisor_Nombre", objxml.emisor.Nombre)) - parametros.Add(New ReportParameter("emisor_RegimenFiscal", objxml.emisor.RegimenFiscalTexto)) - parametros.Add(New ReportParameter("receptor_Rfc", objxml.receptor.Rfc)) - parametros.Add(New ReportParameter("receptor_Nombre", objxml.receptor.Nombre)) - parametros.Add(New ReportParameter("receptor_NumRegIdTrib", objxml.receptor.NumRegIdTrib)) - parametros.Add(New ReportParameter("receptor_ResidenciaFiscal", objxml.receptor.ResidenciaFiscal)) - parametros.Add(New ReportParameter("receptor_UsoCFDI", objxml.receptor.UsoCFDITexto)) - parametros.Add(New ReportParameter("complemento_FechaTimbrado", objxml.complemento.FechaTimbrado)) - parametros.Add(New ReportParameter("complemento_NoCertificadoSAT", objxml.complemento.NoCertificadoSAT)) - parametros.Add(New ReportParameter("complemento_RfcProvCertif", objxml.complemento.RfcProvCertif)) - parametros.Add(New ReportParameter("complemento_SelloCFD", objxml.complemento.SelloCFD)) - parametros.Add(New ReportParameter("complemento_SelloSAT", objxml.complemento.SelloSAT)) - parametros.Add(New ReportParameter("complemento_UUID", objxml.complemento.UUID)) - parametros.Add(New ReportParameter("complemento_CadenaOriginal", objxml.complemento.CadenaOriginal)) - If Not IsNothing(objxml.complemento.Pagos) Then - parametros.Add(New ReportParameter("CPFechaPago", objxml.complemento.Pagos.FechaPago)) - parametros.Add(New ReportParameter("CPFormaDePagoP", objxml.complemento.Pagos.FormaDePagoP)) - parametros.Add(New ReportParameter("CPFormaDePagoPText", objxml.complemento.Pagos.FormaDePagoPText)) - parametros.Add(New ReportParameter("CPMonedaP", objxml.complemento.Pagos.MonedaP)) - parametros.Add(New ReportParameter("CPMonto", objxml.complemento.Pagos.Monto.ToString())) - parametros.Add(New ReportParameter("CPTipoCambioP", objxml.complemento.Pagos.TipoCambioP.ToString())) - parametros.Add(New ReportParameter("CPNumOperacion", objxml.complemento.Pagos.NumOperacion)) - parametros.Add(New ReportParameter("CPNomBancoOrdExt", objxml.complemento.Pagos.NomBancoOrdExt)) - parametros.Add(New ReportParameter("CPRfcEmisorCtaOrd", objxml.complemento.Pagos.RfcEmisorCtaOrd)) - parametros.Add(New ReportParameter("CPCtaOrdenante", objxml.complemento.Pagos.CtaOrdenante)) - parametros.Add(New ReportParameter("CPRfcEmisorCtaBen", objxml.complemento.Pagos.RfcEmisorCtaBen)) - parametros.Add(New ReportParameter("CPCtaBeneficiario", objxml.complemento.Pagos.CtaBeneficiario)) - - End If - Using MR As ReportViewer = New ReportViewer() - Dim rdsTotales As ReportDataSource = New ReportDataSource() - Dim ltotales As List(Of utilValores) = New List(Of utilValores)() - ltotales.Add(New utilValores("Subtotal", objxml.comprobante.SubTotal.ToString("N2"))) - - If objxml.comprobante.Descuento > 0 Then - ltotales.Add(New utilValores("Descuento", objxml.comprobante.Descuento.ToString("N2"))) - End If - - For Each item As CFDIImpuesto In objxml.Impuestos - - If item.Importe > 0 Then - Dim TasaOCuota As Decimal = 0 - Decimal.TryParse(item.TasaOCuota, TasaOCuota) - ltotales.Add(New utilValores($"Impuestos {item.Tipo} {item.ImpuestoTexto} {(If(item.TipoFactor = "Tasa", (TasaOCuota * 100).ToString("N4"), item.TasaOCuota))} {(If(item.TipoFactor = "Tasa", "%", ""))}", item.Importe.ToString("N2"))) - End If - Next - - ltotales.Add(New utilValores("Total", objxml.comprobante.Total.ToString("N2"))) - rdsTotales.Name = "dsTotales" - rdsTotales.Value = ltotales - MR.LocalReport.DataSources.Add(rdsTotales) - Dim rds2 As ReportDataSource = New ReportDataSource() - Dim limagenes As List(Of utilImage) = New List(Of utilImage)() - limagenes.Add(New utilImage(cQr)) - rds2.Name = "dsImagenes" - rds2.Value = limagenes - MR.LocalReport.DataSources.Add(rds2) - Dim rdsrelacionados As ReportDataSource = New ReportDataSource() - rdsrelacionados.Name = "dsRelacionados" - rdsrelacionados.Value = objxml.cFDIRelacionados - MR.LocalReport.DataSources.Add(rdsrelacionados) - Dim rds1 As ReportDataSource = New ReportDataSource() - rds1.Name = "dsConceptos" - rds1.Value = objxml.GetConceptosforpdf() - MR.LocalReport.DataSources.Add(rds1) - - If Not IsNothing(objxml.complemento.Pagos) Then - - Dim rdsp As ReportDataSource = New ReportDataSource() - rdsp.Name = "dsPagos" - rdsp.Value = objxml.complemento.Pagos.doctosRelacionados - MR.LocalReport.DataSources.Add(rdsp) - End If - - MR.LocalReport.ReportPath = rutaReporte - MR.ProcessingMode = ProcessingMode.Local - MR.LocalReport.EnableExternalImages = True - MR.LocalReport.SetParameters(parametros) - MR.LocalReport.Refresh() - Dim warnings As Warning() = Nothing - Dim streamids As String() = Nothing - Dim mimeType As String = Nothing - Dim encoding As String = Nothing - Dim extension As String = Nothing - Dim bytes As Byte() = Nothing - bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings) - - Using fs As FileStream = New FileStream(NombreArchivo, FileMode.Create) - fs.Write(bytes, 0, bytes.Length) - fs.Close() - End Using - End Using - Alert("PDF Generado!") - Else - Alert("no se pudo procesar el archivo xml") - End If - End Sub + CargaDatos() + Else + ObjCompra.RollBack() + Alert("Ocurrió un error al vincular el pago. Por favor verifique y vuelva a intentar", TipoMensaje.MsgError) + End If + ObjCompra.Dispose() + + + End Sub + + Protected Sub ChkVincularPago_CheckedChanged(sender As Object, e As EventArgs) + + For Each Gvr As GridViewRow In GvVincularPago.Rows + Gvr.FCCheckBox("ChkVincularPago").Checked = False + Next + + CType(sender, CheckBox).Checked = True + End Sub + + Protected Sub BtnVincularManualmente_Click(sender As Object, e As EventArgs) + If HdnCveIE.Value <> "-1" AndAlso IsNumeric(HdnCveIE.Value) AndAlso HdnCveIE.Value.ToEntero > 0 Then + Dim ImportePago As Double = 0 + Dim ImporteIES As Double = 0 + Dim SerieFolioIE As String = "" + Dim ObjCompras As New ClsCompras + If ObjCompras.GetCompararComplementoPago(CveProveedor, -1, "", UsuarioActual.CveEmpresa, HdnCveIE.Value.ToEntero) Then + GvVincularPago.DataSource = ObjCompras.DtResultados + If ObjCompras.DtResultados.Rows.Count > 0 Then + SerieFolioIE = ObjCompras.DtResultados.Rows(0)("SerieFolio").ToString + End If + ImportePago = ObjCompras.DtResultados.SUMD("Monto") + End If + + ImporteIES = ObjCompras.DtResultados.FiltraParametros("CveIE > 0").SUM("Importe") + ObjCompras.Dispose() + + BtnVincularPago.Visible = True + + LblSerieFolioPago.Text = $"{SeriePago}-{FolioPago}" + LblImportePago.Text = ImportePago.FormatoNumero + 'LblSerieFolioIE.Text = SerieFolioIE + LblImporteIE.Text = ImporteIES.FormatoNumero + + GvVincularPago.DataBind() + UpVincularPago.Update() + ObjCompras.Dispose() + End If + End Sub + + Private Sub GVPDocumentosRelacionadosPagos_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GVPDocumentosRelacionadosPagos.RowCreated + + If e.Row.RowType = DataControlRowType.Header Then + Dim HeaderGrid = DirectCast(sender, GridView) + Dim HeaderGridRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert) + Dim HeaderCell = New TableCell + + HeaderCell.Text = "Documentos Relacionados" + HeaderCell.ColumnSpan = 8 + HeaderCell.Attributes.Add("style", "border-top: 1px solid #ddd; vertical-align: top; background-color: #DDD; color: #333333;font-family: 'Open Sans', sans-serif;font-size: 12px; text-align:center!important; font-weight: bold;") + HeaderGridRow.Cells.Add(HeaderCell) + GVPDocumentosRelacionadosPagos.Controls(0).Controls.AddAt(0, HeaderGridRow) + + End If + + End Sub + + Private Sub GVPDocumentosRelacionadosPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVPDocumentosRelacionadosPagos.RowDataBound + + If e.Row.RowType = DataControlRowType.DataRow Then + + If e.Row.DataKey("CveFactura").ToEntero > 0 Then + + If e.Row.DataKey("CveCompra").ToEntero > 0 Then + e.Row.Cells(4).Text = "" + e.Row.ToolTip = "Compra registrada" + e.Row.Cells(4).ForeColor = Drawing.Color.Green + + Else + e.Row.Cells(4).Text = "" + e.Row.ToolTip = "Factura recibida sin registrar" + End If + + + Else + e.Row.Cells(4).Text = "" + e.Row.ToolTip = "No se encontro el Folio Fiscal en el sistema" + e.Row.Cells(4).ForeColor = Drawing.Color.Red + End If + End If + + End Sub + + +#End Region + + + + Public Sub ImprimirPDFXML(NombreArchivo As String, rutaxml As String) + Dim objxml As XmlSatCFDI = XmlSatCFDI.readXML(rutaxml) + + Dim rutaReporte As String = String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\Grales\Formatos\CFDIV3.rdlc") + Dim QR As ClbNegBICFDv3_2.ClsNegCBBGenerar = New ClbNegBICFDv3_2.ClsNegCBBGenerar() + Dim cQr As Byte() = QR.GenerarCBBBytes(objxml.emisor.Rfc, objxml.receptor.Rfc, objxml.comprobante.Total, objxml.complemento.UUID) + Dim parametros As List(Of ReportParameter) = New List(Of ReportParameter)() + parametros.Add(New ReportParameter("comprobante_Certificado", objxml.comprobante.Certificado)) + parametros.Add(New ReportParameter("comprobante_CondicionesDePago", objxml.comprobante.CondicionesDePago)) + parametros.Add(New ReportParameter("comprobante_Confirmacion", objxml.comprobante.Confirmacion)) + parametros.Add(New ReportParameter("comprobante_Fecha", objxml.comprobante.Fecha)) + parametros.Add(New ReportParameter("comprobante_Serie", objxml.comprobante.Serie)) + parametros.Add(New ReportParameter("comprobante_Folio", objxml.comprobante.Folio)) + parametros.Add(New ReportParameter("comprobante_Descuento", objxml.comprobante.Descuento.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_SubTotal", objxml.comprobante.SubTotal.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_Total", objxml.comprobante.Total.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_Version", objxml.comprobante.Version)) + parametros.Add(New ReportParameter("comprobante_TipoDeComprobante", objxml.comprobante.TipoDeComprobanteTexto)) + parametros.Add(New ReportParameter("comprobante_FormaPago", objxml.comprobante.FormaPagoTexto)) + parametros.Add(New ReportParameter("comprobante_LugarExpedicion", objxml.comprobante.LugarExpedicion)) + parametros.Add(New ReportParameter("comprobante_NoCertificado", objxml.comprobante.NoCertificado)) + parametros.Add(New ReportParameter("comprobante_Sello", objxml.comprobante.Sello)) + parametros.Add(New ReportParameter("comprobante_Moneda", objxml.comprobante.Moneda)) + parametros.Add(New ReportParameter("comprobante_TipoCambio", objxml.comprobante.TipoCambio.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_MetodoPago", objxml.comprobante.MetodoPagoTexto)) + parametros.Add(New ReportParameter("emisor_Rfc", objxml.emisor.Rfc)) + parametros.Add(New ReportParameter("emisor_Nombre", objxml.emisor.Nombre)) + parametros.Add(New ReportParameter("emisor_RegimenFiscal", objxml.emisor.RegimenFiscalTexto)) + parametros.Add(New ReportParameter("receptor_Rfc", objxml.receptor.Rfc)) + parametros.Add(New ReportParameter("receptor_Nombre", objxml.receptor.Nombre)) + parametros.Add(New ReportParameter("receptor_NumRegIdTrib", objxml.receptor.NumRegIdTrib)) + parametros.Add(New ReportParameter("receptor_ResidenciaFiscal", objxml.receptor.ResidenciaFiscal)) + parametros.Add(New ReportParameter("receptor_UsoCFDI", objxml.receptor.UsoCFDITexto)) + parametros.Add(New ReportParameter("complemento_FechaTimbrado", objxml.complemento.FechaTimbrado)) + parametros.Add(New ReportParameter("complemento_NoCertificadoSAT", objxml.complemento.NoCertificadoSAT)) + parametros.Add(New ReportParameter("complemento_RfcProvCertif", objxml.complemento.RfcProvCertif)) + parametros.Add(New ReportParameter("complemento_SelloCFD", objxml.complemento.SelloCFD)) + parametros.Add(New ReportParameter("complemento_SelloSAT", objxml.complemento.SelloSAT)) + parametros.Add(New ReportParameter("complemento_UUID", objxml.complemento.UUID)) + parametros.Add(New ReportParameter("complemento_CadenaOriginal", objxml.complemento.CadenaOriginal)) + + Using MR As ReportViewer = New ReportViewer() + Dim rdsTotales As ReportDataSource = New ReportDataSource() + Dim ltotales As List(Of utilValores) = New List(Of utilValores)() + ltotales.Add(New utilValores("Subtotal", objxml.comprobante.SubTotal.ToString("N2"))) + + If objxml.comprobante.Descuento > 0 Then + ltotales.Add(New utilValores("Descuento", objxml.comprobante.Descuento.ToString("N2"))) + End If + + For Each item As CFDIImpuesto In objxml.Impuestos + + If item.Importe > 0 Then + Dim TasaOCuota As Decimal = 0 + Decimal.TryParse(item.TasaOCuota, TasaOCuota) + ltotales.Add(New utilValores($"Impuestos {item.Tipo} {item.ImpuestoTexto} {(If(item.TipoFactor = "Tasa", (TasaOCuota * 100).ToString("N4"), item.TasaOCuota))} {(If(item.TipoFactor = "Tasa", "%", ""))}", item.Importe.ToString("N2"))) + End If + Next + + ltotales.Add(New utilValores("Total", objxml.comprobante.Total.ToString("N2"))) + rdsTotales.Name = "dsTotales" + rdsTotales.Value = ltotales + MR.LocalReport.DataSources.Add(rdsTotales) + Dim rds2 As ReportDataSource = New ReportDataSource() + Dim limagenes As List(Of utilImage) = New List(Of utilImage)() + limagenes.Add(New utilImage(cQr)) + rds2.Name = "dsImagenes" + rds2.Value = limagenes + MR.LocalReport.DataSources.Add(rds2) + Dim rdsrelacionados As ReportDataSource = New ReportDataSource() + rdsrelacionados.Name = "dsRelacionados" + rdsrelacionados.Value = objxml.cFDIRelacionados + MR.LocalReport.DataSources.Add(rdsrelacionados) + Dim rds1 As ReportDataSource = New ReportDataSource() + rds1.Name = "dsConceptos" + rds1.Value = objxml.GetConceptosforpdf() + MR.LocalReport.DataSources.Add(rds1) + MR.LocalReport.ReportPath = rutaReporte + MR.ProcessingMode = ProcessingMode.Local + MR.LocalReport.EnableExternalImages = True + MR.LocalReport.SetParameters(parametros) + MR.LocalReport.Refresh() + Dim warnings As Warning() = Nothing + Dim streamids As String() = Nothing + Dim mimeType As String = Nothing + Dim encoding As String = Nothing + Dim extension As String = Nothing + Dim bytes As Byte() = Nothing + bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings) + + Using fs As FileStream = New FileStream(NombreArchivo, FileMode.Create) + fs.Write(bytes, 0, bytes.Length) + fs.Close() + End Using + End Using + End Sub + Protected Sub lnkRegenerarPDF_Click(sender As Object, e As EventArgs) + Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + Dim strRFCde As String = gvrow.DataKey("RFCde") + Dim strXml As String + Dim strPDF As String + Dim dirbase As String = String.Format("{0}{1}{2}{3}{4}\", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\", UsuarioActual.CveEmpresa, "\Compras\", strRFCde) + If Directory.Exists(dirbase) Then + strXml = String.Format("{0}{1}", dirbase, gvrow.DataKey("XML")) + strPDF = String.Format("{0}{1}", dirbase, gvrow.DataKey("PDF")) + If File.Exists(strXml) Then + ImprimirPDFXML(strPDF, strXml) + Alert("el pdf se regenero satisfactoriamente.") + Else + Alert($"No se encontro el xml favor de contactar a soporte tecnico{strXml.Replace("\", "/")}") + End If + Else + Alert($"No se encontro el xml favor de contactar a soporte tecnico{dirbase.Replace("\", "/")}") + End If + ',PDF + ' + 'ImprimirPDFXML("C:\Generar PFX\405504.pdf", "C:\Generar PFX\405504.xml") + End Sub + Private Sub removeasincevent() + + 'For Each GvRow As GridViewRow In GvD.Rows + ' Dim lnkDownPdf As LinkButton = GvRow.FCLinkButton("lnkDownPdf") + ' Dim lnkXML As LinkButton = GvRow.FCLinkButton("lnkXML") + ' If lnkDownPdf.Visible Then + + ' ScriptManager.GetCurrent(Me).RegisterPostBackControl(lnkDownPdf) + ' End If + ' If lnkXML.Visible Then + ' ScriptManager.GetCurrent(Me).RegisterPostBackControl(lnkXML) + ' End If + 'Next + End Sub + Protected Sub lnkDownPdf_Click(sender As Object, e As EventArgs) + Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + Dim strRFCde As String = gvrow.DataKey("RFCde") + Dim strPDF As String + Dim dirbase As String = String.Format("{0}{1}{2}{3}{4}\", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\", UsuarioActual.CveEmpresa, "\Compras\", strRFCde) + strPDF = String.Format("{0}{1}", dirbase, gvrow.DataKey("PDF")) + If File.Exists(strPDF) Then + Dim file As New System.IO.FileInfo(strPDF) + Dim mimeType As String = "text/plain" + Try + mimeType = MimeMapping.GetMimeMapping(strPDF) + Catch ex As Exception + End Try + Response.Clear() + Response.ClearHeaders() + Response.ClearContent() + Response.AddHeader("Content-Disposition", $"attachment; filename= {Uri.EscapeDataString(file.Name)}") + Response.AddHeader("Content-Length", file.Length.ToString()) + Response.ContentType = mimeType + Response.Flush() + Response.TransmitFile(file.FullName) + Response.End() + End If + End Sub + Protected Sub lnkXML_Click(sender As Object, e As EventArgs) + Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + Dim strRFCde As String = gvrow.DataKey("RFCde") + Dim strXml As String + Dim dirbase As String = String.Format("{0}{1}{2}{3}{4}\", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\", UsuarioActual.CveEmpresa, "\Compras\", strRFCde) + strXml = String.Format("{0}{1}", dirbase, gvrow.DataKey("XML")) + If File.Exists(strXml) Then + Dim file As New System.IO.FileInfo(strXml) + Dim mimeType As String = "text/plain" + Try + mimeType = MimeMapping.GetMimeMapping(strXml) + Catch ex As Exception + End Try + Response.Clear() + Response.ClearHeaders() + Response.ClearContent() + Response.AddHeader("Content-Disposition", $"attachment; filename= {Uri.EscapeDataString(file.Name)}") + Response.AddHeader("Content-Length", file.Length.ToString()) + Response.ContentType = mimeType + Response.Flush() + Response.TransmitFile(file.FullName) + Response.End() + End If + End Sub + Protected Sub LnkRegenerarPdfnew_Click(sender As Object, e As EventArgs) + Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow) + Dim objxml As XmlSatCFDI = XmlSatCFDI.readXML(String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("XML"))) + If Not IsNothing(objxml) Then + Dim rutaReporte As String = String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\Grales\Formatos\CFDIV3.rdlc") + If Not IsNothing(objxml.complemento.Pagos) Then + rutaReporte = String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "\Empresas\Grales\Formatos\CFDIV3Pago.rdlc") + End If + Dim NombreArchivo As String = String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("PDF")) + + + Dim QR As ClbNegBICFDv3_2.ClsNegCBBGenerar = New ClbNegBICFDv3_2.ClsNegCBBGenerar() + Dim cQr As Byte() = QR.GenerarCBBBytes(objxml.emisor.Rfc, objxml.receptor.Rfc, If(IsNothing(objxml.complemento.Pagos), objxml.comprobante.Total, objxml.complemento.Pagos.Monto), objxml.complemento.UUID) + Dim parametros As List(Of ReportParameter) = New List(Of ReportParameter)() + parametros.Add(New ReportParameter("comprobante_Certificado", objxml.comprobante.Certificado)) + parametros.Add(New ReportParameter("comprobante_CondicionesDePago", objxml.comprobante.CondicionesDePago)) + parametros.Add(New ReportParameter("comprobante_Confirmacion", objxml.comprobante.Confirmacion)) + parametros.Add(New ReportParameter("comprobante_Fecha", objxml.comprobante.Fecha)) + parametros.Add(New ReportParameter("comprobante_Serie", objxml.comprobante.Serie)) + parametros.Add(New ReportParameter("comprobante_Folio", objxml.comprobante.Folio)) + parametros.Add(New ReportParameter("comprobante_Descuento", objxml.comprobante.Descuento.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_SubTotal", objxml.comprobante.SubTotal.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_Total", objxml.comprobante.Total.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_Version", objxml.comprobante.Version)) + parametros.Add(New ReportParameter("comprobante_TipoDeComprobante", objxml.comprobante.TipoDeComprobanteTexto)) + parametros.Add(New ReportParameter("comprobante_FormaPago", objxml.comprobante.FormaPagoTexto)) + parametros.Add(New ReportParameter("comprobante_LugarExpedicion", objxml.comprobante.LugarExpedicion)) + parametros.Add(New ReportParameter("comprobante_NoCertificado", objxml.comprobante.NoCertificado)) + parametros.Add(New ReportParameter("comprobante_Sello", objxml.comprobante.Sello)) + parametros.Add(New ReportParameter("comprobante_Moneda", objxml.comprobante.Moneda)) + parametros.Add(New ReportParameter("comprobante_TipoCambio", objxml.comprobante.TipoCambio.ToString("N2"))) + parametros.Add(New ReportParameter("comprobante_MetodoPago", objxml.comprobante.MetodoPagoTexto)) + parametros.Add(New ReportParameter("emisor_Rfc", objxml.emisor.Rfc)) + parametros.Add(New ReportParameter("emisor_Nombre", objxml.emisor.Nombre)) + parametros.Add(New ReportParameter("emisor_RegimenFiscal", objxml.emisor.RegimenFiscalTexto)) + parametros.Add(New ReportParameter("receptor_Rfc", objxml.receptor.Rfc)) + parametros.Add(New ReportParameter("receptor_Nombre", objxml.receptor.Nombre)) + parametros.Add(New ReportParameter("receptor_NumRegIdTrib", objxml.receptor.NumRegIdTrib)) + parametros.Add(New ReportParameter("receptor_ResidenciaFiscal", objxml.receptor.ResidenciaFiscal)) + parametros.Add(New ReportParameter("receptor_UsoCFDI", objxml.receptor.UsoCFDITexto)) + parametros.Add(New ReportParameter("complemento_FechaTimbrado", objxml.complemento.FechaTimbrado)) + parametros.Add(New ReportParameter("complemento_NoCertificadoSAT", objxml.complemento.NoCertificadoSAT)) + parametros.Add(New ReportParameter("complemento_RfcProvCertif", objxml.complemento.RfcProvCertif)) + parametros.Add(New ReportParameter("complemento_SelloCFD", objxml.complemento.SelloCFD)) + parametros.Add(New ReportParameter("complemento_SelloSAT", objxml.complemento.SelloSAT)) + parametros.Add(New ReportParameter("complemento_UUID", objxml.complemento.UUID)) + parametros.Add(New ReportParameter("complemento_CadenaOriginal", objxml.complemento.CadenaOriginal)) + If Not IsNothing(objxml.complemento.Pagos) Then + parametros.Add(New ReportParameter("CPFechaPago", objxml.complemento.Pagos.FechaPago)) + parametros.Add(New ReportParameter("CPFormaDePagoP", objxml.complemento.Pagos.FormaDePagoP)) + parametros.Add(New ReportParameter("CPFormaDePagoPText", objxml.complemento.Pagos.FormaDePagoPText)) + parametros.Add(New ReportParameter("CPMonedaP", objxml.complemento.Pagos.MonedaP)) + parametros.Add(New ReportParameter("CPMonto", objxml.complemento.Pagos.Monto.ToString())) + parametros.Add(New ReportParameter("CPTipoCambioP", objxml.complemento.Pagos.TipoCambioP.ToString())) + parametros.Add(New ReportParameter("CPNumOperacion", objxml.complemento.Pagos.NumOperacion)) + parametros.Add(New ReportParameter("CPNomBancoOrdExt", objxml.complemento.Pagos.NomBancoOrdExt)) + parametros.Add(New ReportParameter("CPRfcEmisorCtaOrd", objxml.complemento.Pagos.RfcEmisorCtaOrd)) + parametros.Add(New ReportParameter("CPCtaOrdenante", objxml.complemento.Pagos.CtaOrdenante)) + parametros.Add(New ReportParameter("CPRfcEmisorCtaBen", objxml.complemento.Pagos.RfcEmisorCtaBen)) + parametros.Add(New ReportParameter("CPCtaBeneficiario", objxml.complemento.Pagos.CtaBeneficiario)) + + End If + Using MR As ReportViewer = New ReportViewer() + Dim rdsTotales As ReportDataSource = New ReportDataSource() + Dim ltotales As List(Of utilValores) = New List(Of utilValores)() + ltotales.Add(New utilValores("Subtotal", objxml.comprobante.SubTotal.ToString("N2"))) + + If objxml.comprobante.Descuento > 0 Then + ltotales.Add(New utilValores("Descuento", objxml.comprobante.Descuento.ToString("N2"))) + End If + + For Each item As CFDIImpuesto In objxml.Impuestos + + If item.Importe > 0 Then + Dim TasaOCuota As Decimal = 0 + Decimal.TryParse(item.TasaOCuota, TasaOCuota) + ltotales.Add(New utilValores($"Impuestos {item.Tipo} {item.ImpuestoTexto} {(If(item.TipoFactor = "Tasa", (TasaOCuota * 100).ToString("N4"), item.TasaOCuota))} {(If(item.TipoFactor = "Tasa", "%", ""))}", item.Importe.ToString("N2"))) + End If + Next + + ltotales.Add(New utilValores("Total", objxml.comprobante.Total.ToString("N2"))) + rdsTotales.Name = "dsTotales" + rdsTotales.Value = ltotales + MR.LocalReport.DataSources.Add(rdsTotales) + Dim rds2 As ReportDataSource = New ReportDataSource() + Dim limagenes As List(Of utilImage) = New List(Of utilImage)() + limagenes.Add(New utilImage(cQr)) + rds2.Name = "dsImagenes" + rds2.Value = limagenes + MR.LocalReport.DataSources.Add(rds2) + Dim rdsrelacionados As ReportDataSource = New ReportDataSource() + rdsrelacionados.Name = "dsRelacionados" + rdsrelacionados.Value = objxml.cFDIRelacionados + MR.LocalReport.DataSources.Add(rdsrelacionados) + Dim rds1 As ReportDataSource = New ReportDataSource() + rds1.Name = "dsConceptos" + rds1.Value = objxml.GetConceptosforpdf() + MR.LocalReport.DataSources.Add(rds1) + + If Not IsNothing(objxml.complemento.Pagos) Then + + Dim rdsp As ReportDataSource = New ReportDataSource() + rdsp.Name = "dsPagos" + rdsp.Value = objxml.complemento.Pagos.doctosRelacionados + MR.LocalReport.DataSources.Add(rdsp) + End If + + MR.LocalReport.ReportPath = rutaReporte + MR.ProcessingMode = ProcessingMode.Local + MR.LocalReport.EnableExternalImages = True + MR.LocalReport.SetParameters(parametros) + MR.LocalReport.Refresh() + Dim warnings As Warning() = Nothing + Dim streamids As String() = Nothing + Dim mimeType As String = Nothing + Dim encoding As String = Nothing + Dim extension As String = Nothing + Dim bytes As Byte() = Nothing + bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings) + + Using fs As FileStream = New FileStream(NombreArchivo, FileMode.Create) + fs.Write(bytes, 0, bytes.Length) + fs.Close() + End Using + End Using + Alert("PDF Generado!") + Else + Alert("no se pudo procesar el archivo xml") + End If + End Sub End Class \ No newline at end of file diff --git a/Contratos/RepPresupuestos.aspx b/Contratos/RepPresupuestos.aspx index 8353386b1..ba7cfd71f 100644 --- a/Contratos/RepPresupuestos.aspx +++ b/Contratos/RepPresupuestos.aspx @@ -329,9 +329,10 @@ - - - + + + +
AgrupadorAutorizadoEjercidoPor EjercerAutorizadoEjercidoPor EjercerPagado
@@ -340,11 +341,12 @@ <%-- - - + + - + +
@@ -359,85 +361,113 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + +
AgrupadorAutorizadoEneroFebreroMarzoAbrilMayoJunioJulioAgostoSeptiembreOctubreNoviembreDiciembreAutorizadoEneroFebreroMarzoAbrilMayoJunioJulioAgostoSeptiembreOctubreNoviembreDiciembreTotal
- + + + <%-- --%> + + <%-- --%> + + <%-- --%> - + + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + + diff --git a/Contratos/RepPresupuestos.aspx.vb b/Contratos/RepPresupuestos.aspx.vb index 52e95a10b..c49216d9b 100644 --- a/Contratos/RepPresupuestos.aspx.vb +++ b/Contratos/RepPresupuestos.aspx.vb @@ -344,6 +344,9 @@ Partial Class Contratos_RepPresupuestos If e.Row.DBCampo("PorEjercerPorcentaje").ToDecimal = 0 Then e.Row.Cells(5).Text = "-" End If + If e.Row.DBCampo("Pagado").ToDecimal = 0 Then + e.Row.Cells(6).Text = "-" + End If If e.Row.RowIndex > 0 Then Dim CveAgrupador = e.Row.DBCampo("CveAgrupador").ToEntero @@ -387,50 +390,94 @@ Partial Class Contratos_RepPresupuestos End Select If e.Row.DBCampo("EneroEjercido").ToDecimal = 0 Then - e.Row.Cells(2).Text = "-" + e.Row.Cells(3).Text = "-" + End If + If e.Row.DBCampo("EneroPagado").ToDecimal = 0 Then + e.Row.Cells(5).Text = "-" End If If e.Row.DBCampo("FebreroEjercido").ToDecimal = 0 Then - e.Row.Cells(4).Text = "-" + e.Row.Cells(7).Text = "-" + End If + If e.Row.DBCampo("FebreroPagado").ToDecimal = 0 Then + e.Row.Cells(9).Text = "-" End If If e.Row.DBCampo("MarzoEjercido").ToDecimal = 0 Then - e.Row.Cells(6).Text = "-" + e.Row.Cells(11).Text = "-" + End If + If e.Row.DBCampo("MarzoPagado").ToDecimal = 0 Then + e.Row.Cells(13).Text = "-" End If If e.Row.DBCampo("AbrilEjercido").ToDecimal = 0 Then - e.Row.Cells(8).Text = "-" + e.Row.Cells(15).Text = "-" + End If + If e.Row.DBCampo("AbrilPagado").ToDecimal = 0 Then + e.Row.Cells(17).Text = "-" End If If e.Row.DBCampo("MayoEjercido").ToDecimal = 0 Then - e.Row.Cells(10).Text = "-" + e.Row.Cells(19).Text = "-" + End If + If e.Row.DBCampo("MayoPagado").ToDecimal = 0 Then + e.Row.Cells(21).Text = "-" End If If e.Row.DBCampo("JunioEjercido").ToDecimal = 0 Then - e.Row.Cells(12).Text = "-" + e.Row.Cells(23).Text = "-" + End If + If e.Row.DBCampo("JunioPagado").ToDecimal = 0 Then + e.Row.Cells(25).Text = "-" End If If e.Row.DBCampo("JulioEjercido").ToDecimal = 0 Then - e.Row.Cells(14).Text = "-" + e.Row.Cells(27).Text = "-" + End If + If e.Row.DBCampo("JulioPagado").ToDecimal = 0 Then + e.Row.Cells(29).Text = "-" End If If e.Row.DBCampo("AgostoEjercido").ToDecimal = 0 Then - e.Row.Cells(16).Text = "-" + e.Row.Cells(31).Text = "-" + End If + If e.Row.DBCampo("AgostoPagado").ToDecimal = 0 Then + e.Row.Cells(33).Text = "-" End If If e.Row.DBCampo("SeptiembreEjercido").ToDecimal = 0 Then - e.Row.Cells(18).Text = "-" + e.Row.Cells(35).Text = "-" + End If + If e.Row.DBCampo("SeptiembrePagado").ToDecimal = 0 Then + e.Row.Cells(37).Text = "-" End If If e.Row.DBCampo("OctubreEjercido").ToDecimal = 0 Then - e.Row.Cells(20).Text = "-" + e.Row.Cells(39).Text = "-" + End If + If e.Row.DBCampo("OctubrePagado").ToDecimal = 0 Then + e.Row.Cells(41).Text = "-" End If If e.Row.DBCampo("NoviembreEjercido").ToDecimal = 0 Then - e.Row.Cells(22).Text = "-" + e.Row.Cells(43).Text = "-" + End If + If e.Row.DBCampo("NoviembrePagado").ToDecimal = 0 Then + e.Row.Cells(45).Text = "-" End If If e.Row.DBCampo("DiciembreEjercido").ToDecimal = 0 Then - e.Row.Cells(24).Text = "-" + e.Row.Cells(47).Text = "-" + End If + If e.Row.DBCampo("DiciembrePagado").ToDecimal = 0 Then + e.Row.Cells(49).Text = "-" + End If + + If e.Row.DBCampo("TotalEjercido").ToDecimal = 0 Then + e.Row.Cells(50).Text = "-" + End If + + If e.Row.DBCampo("TotalPagado").ToDecimal = 0 Then + e.Row.Cells(52).Text = "-" End If If e.Row.RowIndex > 0 Then diff --git a/Contratos/RepPresupuestosDetalle.aspx b/Contratos/RepPresupuestosDetalle.aspx index 7bf7d886b..05b3668d8 100644 --- a/Contratos/RepPresupuestosDetalle.aspx +++ b/Contratos/RepPresupuestosDetalle.aspx @@ -247,9 +247,10 @@ - - - + + + +
AgrupadorAutorizadoEjercidoPor EjercerAutorizadoEjercidoPor EjercerPagado
@@ -257,12 +258,13 @@ <%-- - - - + + + - + +
@@ -277,85 +279,113 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + +
AgrupadorAutorizadoEneroFebreroMarzoAbrilMayoJunioJulioAgostoSeptiembreOctubreNoviembreDiciembreAutorizadoEneroFebreroMarzoAbrilMayoJunioJulioAgostoSeptiembreOctubreNoviembreDiciembreTotal
- + + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + <%-- --%> + + + diff --git a/Contratos/RepPresupuestosDetalle.aspx.vb b/Contratos/RepPresupuestosDetalle.aspx.vb index 8c69e0060..c68bd35ff 100644 --- a/Contratos/RepPresupuestosDetalle.aspx.vb +++ b/Contratos/RepPresupuestosDetalle.aspx.vb @@ -164,6 +164,9 @@ Partial Class Contratos_RepPresupuestosDetalle If e.Row.DBCampo("PorEjercerPorcentaje").ToDecimal = 0 Then e.Row.Cells(5).Text = "-" End If + If e.Row.DBCampo("Pagado").ToDecimal = 0 Then + e.Row.Cells(6).Text = "-" + End If If e.Row.RowIndex > 0 Then Dim CveAgrupador = e.Row.DBCampo("CveAgrupador").ToEntero Dim EsProyecto = False @@ -195,50 +198,94 @@ Partial Class Contratos_RepPresupuestosDetalle End Select If e.Row.DBCampo("EneroEjercido").ToDecimal = 0 Then - e.Row.Cells(2).Text = "-" + e.Row.Cells(3).Text = "-" + End If + If e.Row.DBCampo("EneroPagado").ToDecimal = 0 Then + e.Row.Cells(5).Text = "-" End If If e.Row.DBCampo("FebreroEjercido").ToDecimal = 0 Then - e.Row.Cells(4).Text = "-" + e.Row.Cells(7).Text = "-" + End If + If e.Row.DBCampo("FebreroPagado").ToDecimal = 0 Then + e.Row.Cells(9).Text = "-" End If If e.Row.DBCampo("MarzoEjercido").ToDecimal = 0 Then - e.Row.Cells(6).Text = "-" + e.Row.Cells(11).Text = "-" + End If + If e.Row.DBCampo("MarzoPagado").ToDecimal = 0 Then + e.Row.Cells(13).Text = "-" End If If e.Row.DBCampo("AbrilEjercido").ToDecimal = 0 Then - e.Row.Cells(8).Text = "-" + e.Row.Cells(15).Text = "-" + End If + If e.Row.DBCampo("AbrilPagado").ToDecimal = 0 Then + e.Row.Cells(17).Text = "-" End If If e.Row.DBCampo("MayoEjercido").ToDecimal = 0 Then - e.Row.Cells(10).Text = "-" + e.Row.Cells(19).Text = "-" + End If + If e.Row.DBCampo("MayoPagado").ToDecimal = 0 Then + e.Row.Cells(21).Text = "-" End If If e.Row.DBCampo("JunioEjercido").ToDecimal = 0 Then - e.Row.Cells(12).Text = "-" + e.Row.Cells(23).Text = "-" + End If + If e.Row.DBCampo("JunioPagado").ToDecimal = 0 Then + e.Row.Cells(25).Text = "-" End If If e.Row.DBCampo("JulioEjercido").ToDecimal = 0 Then - e.Row.Cells(14).Text = "-" + e.Row.Cells(27).Text = "-" + End If + If e.Row.DBCampo("JulioPagado").ToDecimal = 0 Then + e.Row.Cells(29).Text = "-" End If If e.Row.DBCampo("AgostoEjercido").ToDecimal = 0 Then - e.Row.Cells(16).Text = "-" + e.Row.Cells(31).Text = "-" + End If + If e.Row.DBCampo("AgostoPagado").ToDecimal = 0 Then + e.Row.Cells(33).Text = "-" End If If e.Row.DBCampo("SeptiembreEjercido").ToDecimal = 0 Then - e.Row.Cells(18).Text = "-" + e.Row.Cells(35).Text = "-" + End If + If e.Row.DBCampo("SeptiembrePagado").ToDecimal = 0 Then + e.Row.Cells(37).Text = "-" End If If e.Row.DBCampo("OctubreEjercido").ToDecimal = 0 Then - e.Row.Cells(20).Text = "-" + e.Row.Cells(39).Text = "-" + End If + If e.Row.DBCampo("OctubrePagado").ToDecimal = 0 Then + e.Row.Cells(41).Text = "-" End If If e.Row.DBCampo("NoviembreEjercido").ToDecimal = 0 Then - e.Row.Cells(22).Text = "-" + e.Row.Cells(43).Text = "-" + End If + If e.Row.DBCampo("NoviembrePagado").ToDecimal = 0 Then + e.Row.Cells(45).Text = "-" End If If e.Row.DBCampo("DiciembreEjercido").ToDecimal = 0 Then - e.Row.Cells(24).Text = "-" + e.Row.Cells(47).Text = "-" + End If + If e.Row.DBCampo("DiciembrePagado").ToDecimal = 0 Then + e.Row.Cells(49).Text = "-" + End If + + If e.Row.DBCampo("TotalEjercido").ToDecimal = 0 Then + e.Row.Cells(50).Text = "-" + End If + + If e.Row.DBCampo("TotalPagado").ToDecimal = 0 Then + e.Row.Cells(52).Text = "-" End If If e.Row.RowIndex > 0 Then diff --git a/Inventarios/RecepcionUsados.aspx b/Inventarios/RecepcionUsados.aspx index ba194c182..635ed529a 100644 --- a/Inventarios/RecepcionUsados.aspx +++ b/Inventarios/RecepcionUsados.aspx @@ -111,6 +111,12 @@ +
+ + Usados + Ajuste/Garantía + +
@@ -324,8 +330,8 @@ - - + + @@ -337,6 +343,186 @@
+
+
+ + + +
+
+ + Ajuste +
+
+
+
+ +
+
+ + +
+
+
+
+ + + + + +
+
+
+
+
+
+ + + +
+
+
+
+
+
+ + + + + +
+
+
+
+ + <%-- + <%----%> + <%----%> +
+
+
+
+
+
+ + + <%----% + <%----%> + +
+
+
+
+ + + + + +
+
+
+
+
+
+
+ + + <%----%> + <%----%> + +
+
+
+ +
+ + + + + + + + +
+
+
+
+
+
+ + + <%----%> + <%----%> + +
+
+
+
+ + + + + +
+
+
+
+
+
+ + + + + +
+
+
+
+ + + + + +
+
+
+
+ + + + + +
+
+
+
+
+
+ + <%----%> + <%----%> + +
+
+
+
+ + + + + +
+
+
+ + +
+
+
+
+
+
+
<%--INVENTARIO INICIAL--%> @@ -841,6 +1027,7 @@ + @@ -856,6 +1043,10 @@