Imports System.Data Imports System.IO Imports Extensiones Imports iTextSharp.text.pdf Imports Microsoft.Reporting.WebForms Partial Class Contabilidad_FiltraPolizas Inherits ClsPaginas #Region "Propiedades" Private Property DtDatos As DataTable Get Return CType(ViewState("DtDatos"), DataTable) End Get Set(value As DataTable) ViewState("DtDatos") = value End Set End Property Public Property Tick As String Get Return CType(ViewState("Tick"), String) End Get Set(value As String) ViewState("Tick") = 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 ViewState("Orden") = "" DdlPeriodo.SelectedValue = Now.Month.ToString TxtFechaICredito.Text = Now.FirstDayOfMonth.ToShortDateString TxtFechaFCredito.Text = Now.LastDayOfMonth.ToShortDateString If UsuarioActual.Empresa.UsaContabilidad Then CargaSegmentoNeg() CargaEjercicios() CargaDatos() CargaGvBitacora() Else Alert("Este módulo requiere el uso de Contabilidad.", TipoMensaje.MsgAdvertencia) BtnConsultar.Enabled = False LnkImprimir.Visible = False LnkExcel.Visible = False End If 'Dim httpApps As HttpApplication = HttpContext.ApplicationInstance ''Get list of active modules 'Dim httpModuleCollections As HttpModuleCollection = httpApps.Modules '' ViewBag.ModulesCount = httpModuleCollections.Count 'gvv.DataSource = httpModuleCollections 'gvv.DataBind() End If End Sub Public Sub CargaDatos() Dim Ejercicio As Integer = DdlEjercicio.SelectedValue.ToString().ToEntero() Dim Periodo As Integer = DdlPeriodo.SelectedValue.ToString().ToEntero() Dim ObjConta As New ClsContPAQi(UsuarioActual.Empresa) If ObjConta.GetPolizas(Ejercicio, Periodo, DdlTipoPoliza.SelectedValue.ToEntero(), DdlSegmentoNeg.SelectedValue.ToEntero(), UsuarioActual.CveEmpresa) Then DtDatos = ObjConta.DtResultados Gv.DataSource = ObjConta.DtResultados 'If DdlTipoPoliza.SelectedValue.ToEntero > 0 Then ' ViewState("DTPolizas") = ObjConta.DtResultados.FiltraParametros($"TipoPol = '{DdlTipoPoliza.SelectedItem}'") ' DtDatos = ObjConta.DtResultados.FiltraParametros($"TipoPol = '{DdlTipoPoliza.SelectedItem}'") 'Else ' ViewState("DTPolizas") = ObjConta.DtResultados ' DtDatos = ObjConta.DtResultados 'End If End If Gv.DataBind() ObjConta.Dispose() UpDatos.Update() End Sub Private Sub CargaSegmentoNeg() Dim ObjContPAQ As New ClsContPAQi(UsuarioActual.Empresa) If ObjContPAQ.GetSegmentosNegocio(-1, "-1") Then DdlSegmentoNeg.DataSource = ObjContPAQ.DtResultados DdlSegmentoNeg.DataBind() End If ObjContPAQ.Dispose() DdlSegmentoNeg.Items.Insert(0, New ListItem("Todos", "-1")) End Sub Private Sub CargaEjercicios() Dim ClsConta As New ClsContPAQi(UsuarioActual.Empresa) If ClsConta.GetEjercicios() Then DdlEjercicio.DataSource = ClsConta.DtResultados Else DdlEjercicio.DataSource = Nothing End If ClsConta.Dispose() DdlEjercicio.DataBind() DdlEjercicio.SelectedValueExist(UsuarioActual.Empresa.EjercicioActual.ToString) End Sub Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) Handles BtnConsultar.Click CargaDatos() End Sub Private Sub DdlEjercicio_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlEjercicio.SelectedIndexChanged CargaDatos() End Sub Private Sub DdlPeriodo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlPeriodo.SelectedIndexChanged CargaDatos() End Sub 'Private Sub DdlTipoPoliza_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlTipoPoliza.SelectedIndexChanged ' CargaDatos() 'End Sub #Region "O R D E N A M I E N T O" Protected Sub LbOrden_Click(ByVal sender As Object, ByVal e As EventArgs) Dim Orden As String = "" Dim Campo As String = "" Dim Literal As Literal = Nothing Const OrdenInicial As String = "" Dim Arg(2) As String Arg = CType(sender, LinkButton).CommandArgument().ToString.Split(";"c) Campo = Arg(0) Literal = CType(CType(sender, LinkButton).NamingContainer.FindControl("Img" & Campo.Replace(",", "_")), Literal) If ViewState(String.Format("O{0}", Campo)) IsNot Nothing AndAlso ViewState(String.Format("O{0}", Campo)).ToString = String.Format("{0} DESC", Campo) Then ViewState(String.Format("O{0}", Campo)) = String.Format("{0} ASC", Campo) Literal.Text = String.Format("") Else ViewState(String.Format("O{0}", Campo)) = String.Format("{0} DESC", Campo) Literal.Text = String.Format("") End If Orden = OrdenInicial & ViewState(String.Format("O{0}", Campo)).ToString ViewState("Orden") = Orden 'CargaGrid(Orden) End Sub 'Private Sub CargaGrid(Orden As String) ' If Orden <> String.Empty Then ' Dim DV As New DataView(CType(ViewState("DTPolizas"), DataTable), "", Orden, DataViewRowState.CurrentRows) ' Gv.DataSource = DV.ToTable() ' DV.Dispose() ' Else ' Gv.DataSource = CType(ViewState("DTPolizas"), DataTable) ' End If ' Gv.DataBind() 'End Sub #End Region #Region "IMPRIMIR" Private Sub ImprimirPoliza(Optional Formato As String = "PDF") If DtDatos IsNot Nothing Then Dim params As New List(Of ReportParameter) 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 = DtDatos params.Add(New ReportParameter("Empresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("FechaImpresion", Now.ToDateTime.ToShortDateString)) params.Add(New ReportParameter("Ejercicio", DdlEjercicio.SelectedItem.ToString)) params.Add(New ReportParameter("Periodo", DdlPeriodo.SelectedItem.ToString)) If Imagen.Exists Then params.Add(New ReportParameter("LogoPath", logouri)) Else params.Add(New ReportParameter("LogoPath", "")) End If ImprimirPDF("Empresas/Grales/Formatos/PolizasPeriodo.rdlc", dt, params, String.Format("ReporteDePolizas-{0} {1}", DdlEjercicio.SelectedItem, DdlPeriodo.SelectedItem), Formato:=Formato) Else Alert("No hay datos consultados", TipoMensaje.MsgAdvertencia) End If End Sub Private Sub LnkImprimir_Click(sender As Object, e As EventArgs) Handles LnkImprimir.Click ImprimirPoliza("PDF") End Sub Private Sub LnkExcel_Click(sender As Object, e As EventArgs) Handles LnkExcel.Click ImprimirPoliza("EXCEL") End Sub #End Region #Region "HISTORIAL DE ELIMINACION" Private Sub CargaGvBitacora() Dim ObjGral As New ClsGenerales If ObjGral.GetHistorialBitacoraRemoveGet("Polizas", UsuarioActual.CveEmpresa, TxtFechaICredito.Text.ToDate, TxtFechaFCredito.Text.ToDate, DdlTipoPolizaFiltro.SelectedValue.ToEntero) Then GvBitacora.DataSource = ObjGral.DtResultados End If ObjGral.Dispose() GvBitacora.DataBind() End Sub Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles BtnMostrar.Click GvBitacora.Visible = True DivBusquedaBitacora.Visible = True DivFiltrosBitacora.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 DivBusquedaBitacora.Visible = False DivFiltrosBitacora.Visible = False BtnOcultar.Visible = False BtnMostrar.Visible = True UpBitacora.Update() End Sub Protected Sub BtnConsultarBitacora_Click(sender As Object, e As EventArgs) CargaGvBitacora() UpBitacora.Update() End Sub #End Region Protected Sub LnkPaqueteEgre_Click(sender As Object, e As EventArgs) Handles LnkPaqueteEgre.Click Dim filtro() As String = {"CveCompra", "CveIE", "CveConceptoContable"} Dim filtroComplemento() As String = {"CveIE"} Dim Pathpdf As New List(Of String) Dim pdfs = New List(Of Byte()) Dim Path As String Dim ObjCompra As New ClsCompras Dim ObjIE As New ClsBancos() Dim pathPoliza As String = "" Dim TieneComprobante As String = "" Tick = DateTime.Now.Ticks.ToString Dim ObjContabilidad As New ClsContabilidad Dim CvePrePoliza As Integer Dim PolizasSinComprobante As String = "Polizas sin comprobante:
" Dim SinComprobante As Boolean = False Dim contador As Integer = 0 Try If Gv.Rows.Count > 0 Then For Each TempPolizas As GridViewRow In Gv.Rows If TempPolizas.FCCheckBox("ChkPoliza").Checked Then contador += 1 CvePrePoliza = TempPolizas.DataKey("CvePrePoliza").ToString.ToEntero ObjContabilidad.GetContabilizacionDiarioDetalle(CvePrePoliza) TieneComprobante = VerificarComprobante(ObjContabilidad.DtResultados) If TieneComprobante = "" And Not SinComprobante Then Path = ImprimirPolizaPDF(CvePrePoliza) pathPoliza = Path If File.Exists(Path) Then Pathpdf.Add(Path) End If Dim dt As DataTable = ObjContabilidad.DtResultados.FiltraParametros("", "", filtro) For Each Row As DataRow In dt.Rows If Row("CveConceptoContable").ToString.ToEntero = 30 Then If Row("CveIE").ToString.ToEntero > 0 Then If ObjIE.GetBancosIE(Row("CveIE").ToString.ToEntero, UsuarioActual.CveEmpresa) Then If ObjIE.DtResultados.Rows.Count > 0 Then Path = String.Format("{0}IE\{1}", UsuarioActual.Empresa.Ruta, ObjIE.Comprobante.ToString) If File.Exists(Path) Then Dim formato As String = System.IO.Path.GetExtension(Path) If formato.ToLower.Contiene(".jpg", ".png", ".jpeg") Then Dim ComprobantePDF As String = String.Format("{0}\{1}\comprobante.pdf", AppDomain.CurrentDomain.BaseDirectory, Tick) Using crea_archivo = New iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 18, 18, 18, 18) PdfWriter.GetInstance(crea_archivo, New FileStream(ComprobantePDF, FileMode.Create)) crea_archivo.Open() Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Path) If image.Height > image.Width Then Dim percentage As Double = 0.0F percentage = 700 / image.Height image.ScalePercent(percentage * 100) Else Dim percentage As Double = 0.0F percentage = 540 / image.Width image.ScalePercent(percentage * 100) End If crea_archivo.Add(image) End Using Pathpdf.Add(ComprobantePDF) Else Pathpdf.Add(Path) End If End If End If End If End If End If If Row("CveConceptoContable").ToString.ToEntero.Contiene(17, 309, 312, 308) Then If ObjCompra.GetCompras(Row("CveCompra").ToString.ToEntero, "-1", "-1", -1, -1, UsuarioActual.CveEmpresa) Then If ObjCompra.DtResultados IsNot Nothing AndAlso ObjCompra.DtResultados.Rows.Count > 0 Then Dim dr As DataRow = ObjCompra.DtResultados.Rows(0) Dim RFC As String = dr("RFC").ToString Dim CveFactura As String = dr("CveFactura").ToString Path = String.Format("{0}Compras\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, RFC, CveFactura) If File.Exists(Path) Then Pathpdf.Add(Path) End If End If End If End If Next dt = ObjContabilidad.DtResultados.FiltraParametros("", "", filtroComplemento) For Each Row As DataRow In dt.Rows If ObjCompra.GetCompraComplementoPago(-1, UsuarioActual.CveEmpresa, Row("CveIE").ToString.ToEntero) Then If ObjCompra.DtResultados IsNot Nothing AndAlso ObjCompra.DtResultados.Rows.Count > 0 Then Dim dr As DataRow = ObjCompra.DtResultados.Rows(0) Dim RFC As String = dr("RFCde").ToString Dim CveFactura As String = dr("CveFactura").ToString Console.WriteLine(RFC & CveFactura) If CveFactura <> "" Then Path = String.Format("{0}Compras\{1}\{2}.pdf", UsuarioActual.Empresa.Ruta, RFC, CveFactura) Console.WriteLine(Path) If File.Exists(Path) Then Pathpdf.Add(Path) End If End If End If End If Next Else If TieneComprobante <> "" Then PolizasSinComprobante += String.Format("{1} {2}
", TieneComprobante, TempPolizas.DataKey("TipoPol").ToString, TempPolizas.DataKey("Folio").ToString) SinComprobante = True End If End If End If Next If contador > 0 Then If SinComprobante Then Alert(PolizasSinComprobante, TipoMensaje.MsgAdvertencia) Else MergePdfFiles(Pathpdf.ToArray) If File.Exists(pathPoliza) Then Directory.Delete(String.Format("{0}/{1}", AppDomain.CurrentDomain.BaseDirectory, Tick), True) End If End If Else Alert("No hay polizas seleccionadas para imprimir", TipoMensaje.MsgAdvertencia) End If Else Alert("No hay informacion cargada", TipoMensaje.MsgAdvertencia) End If Catch ex As Exception Alert("Error al descargar el paquete", TipoMensaje.MsgError) If File.Exists(pathPoliza) Then Directory.Delete(String.Format("{0}/{1}", AppDomain.CurrentDomain.BaseDirectory, Tick), True) End If End Try ObjCompra.Dispose() ObjIE.Dispose() End Sub Private Function ImprimirPolizaPDF(CvePrePoliza As Integer) As String Dim ObjConta As New ClsContabilidad 'Dim ObjPoliza As New ClsContPAQi(UsuarioActual.Empresa) Dim Archivo As New System.IO.FileInfo(String.Format("{0}Formatos/Polizas.rdlc", UsuarioActual.Empresa.Ruta)) Dim params As New List(Of ReportParameter) Dim Bytes As Byte() = Nothing 'If ObjPoliza.GetPoliza(IdPoliza, -1, -1, -1, -1) AndAlso ObjPoliza.DtResultados.Rows.Count > 0 Then If ObjConta.GetPrePolizasDetalle(CvePrePoliza) AndAlso ObjConta.DtResultados.Rows.Count > 0 Then Dim dtVC As DataTable Dim dr As DataRow dtVC = ObjConta.DtResultados.FiltraParametros("Contabilizable = 1", "Orden") dr = dtVC.Rows(0) Dim ruta As String = "" params.Add(New ReportParameter("Empresa", UsuarioActual.Empresa.Empresa)) params.Add(New ReportParameter("TipoPoliza", dr("TipoPoliza").ToString)) params.Add(New ReportParameter("Finicio", dr("Fecha").ToString.ToDate.ToShortDateString)) params.Add(New ReportParameter("FFin", dr("Fecha").ToString.ToDate.ToShortDateString)) params.Add(New ReportParameter("Fecha", dr("Fecha").ToString.ToDate.ToShortDateString)) 'params.Add(New ReportParameter("Nombre", dr("Cuenta").ToString)) 'params.Add(New ReportParameter("Cuenta", dr("Codigo").ToString)) params.Add(New ReportParameter("Numero", dr("FolioPoliza").ToString)) params.Add(New ReportParameter("Moneda", "")) params.Add(New ReportParameter("CodigoPostal", "")) If UsuarioActual.CveEmpresa = 119 Then params.Add(New ReportParameter("UsuarioRegistro", GlobalDTUsuarios(dr("CveUsuario").ToString.ToEntero).FiltroPrimeroValor("Nombre"))) End If If UsuarioActual.CveEmpresa = 140 Then params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre)) End If If Archivo.Exists Then ruta = UsuarioActual.Empresa.Ruta & "Formatos/Polizas.rdlc" Else ruta = "Empresas/Grales/Formatos/Polizas.rdlc" End If Bytes = StreamPDF(ruta, dtVC, params, "ppoliza") If Not File.Exists(String.Format("{0}{1}\{2}.pdf", AppDomain.CurrentDomain.BaseDirectory, Tick, CvePrePoliza.ToString)) Then DirectoryExistsCreate(String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, Tick)) File.WriteAllBytes(String.Format("{0}\{1}\{2}.pdf", AppDomain.CurrentDomain.BaseDirectory, Tick, CvePrePoliza.ToString), Bytes) End If End If Return String.Format("{0}\{1}\{2}.pdf", AppDomain.CurrentDomain.BaseDirectory, Tick, CvePrePoliza.ToString) ObjConta.Dispose() End Function Private Sub MergePdfFiles(ByVal pdfFiles() As String) Dim result As Boolean = False Dim pdfCount As Integer = 0 Dim f As Integer = 0 Dim fileName As String Dim reader As iTextSharp.text.pdf.PdfReader = Nothing Dim pageCount As Integer = 0 Dim pdfDoc As iTextSharp.text.Document = Nothing Dim writer As PdfWriter = Nothing Dim cb As PdfContentByte = Nothing Dim page As PdfImportedPage = Nothing Dim rotation As Integer = 0 Try pdfCount = pdfFiles.Length If pdfCount > 0 Then fileName = pdfFiles(f) reader = New iTextSharp.text.pdf.PdfReader(fileName) pageCount = reader.NumberOfPages pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18) writer = PdfWriter.GetInstance(pdfDoc, New FileStream(String.Format("{0}\{1}\{2}.pdf", AppDomain.CurrentDomain.BaseDirectory, Tick, "poliza"), FileMode.Create)) With pdfDoc .Open() End With cb = writer.DirectContent While f < pdfCount Dim i As Integer = 0 While i < pageCount i += 1 pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i)) pdfDoc.NewPage() page = writer.GetImportedPage(reader, i) rotation = reader.GetPageRotation(i) If rotation = 90 Then cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height) ElseIf rotation = 270 Then cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30) Else cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0) End If End While f += 1 If f < pdfCount Then fileName = pdfFiles(f) reader = New iTextSharp.text.pdf.PdfReader(fileName) pageCount = reader.NumberOfPages End If End While pdfDoc.Close() Dim Archivo As New System.IO.FileInfo(String.Format("{0}\{1}\{2}.pdf", AppDomain.CurrentDomain.BaseDirectory, Tick, "Poliza")) If Archivo.Exists Then Response.Clear() Response.ContentType = Nothing Response.AppendHeader("Content-disposition", String.Format("attachment; filename={0}", Archivo.Name)) Response.AddHeader("Content-Length", Archivo.Length.ToString()) Response.TransmitFile(String.Format("{0}\{1}\{2}.pdf", AppDomain.CurrentDomain.BaseDirectory, Tick, "Poliza")) Response.Flush() ' send it to the client to download HttpContext.Current.Response.SuppressContent = True HttpContext.Current.ApplicationInstance.CompleteRequest() End If result = True End If Catch ex As Exception End Try End Sub Private Function VerificarComprobante(ByVal PrepolizaDetalle As DataTable) As String Dim filtro() As String = {"CveIE", "CveConceptoContable"} Dim Path As String Dim dt As DataTable = PrepolizaDetalle.FiltraParametros("", "", filtro) Dim ObjIE As New ClsBancos() Dim TieneComprobante As String = "" For Each Row As DataRow In dt.FiltraParametros("CveConceptoContable = 30").Rows If ObjIE.GetBancosIE(Row("CveIE").ToString.ToEntero, UsuarioActual.CveEmpresa) Then If ObjIE.DtResultados.Rows.Count > 0 Then Path = String.Format("{0}IE\{1}", UsuarioActual.Empresa.Ruta, ObjIE.Comprobante.ToString) If File.Exists(Path) Then TieneComprobante = "" Exit For Else TieneComprobante = Row("CveIE").ToString Exit For End If Else TieneComprobante = Row("CveIE").ToString Exit For End If End If Next ObjIE.Dispose() Return TieneComprobante End Function Protected Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Gv.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then 'If e.Row.DataKey("Comprobante").ToString <> "" AndAlso e.Row.DataKey("Comprobante").ToString IsNot Nothing Then ' e.Row.FCCheckBox("ChkPoliza").Enabled = True 'Else ' e.Row.FCCheckBox("ChkPoliza").ToolTip = "No se tiene cargado comprobante de pago" 'End If End If End Sub End Class