Option Explicit On Option Strict On Imports System.Data Imports Extensiones Imports System.IO Imports DocumentFormat.OpenXml.Spreadsheet Partial Class Bancos_RepCreditos Inherits ClsPaginas #Region "P R O P I E D A D E S" Private Property DtResumen As DataTable Get DtResumen = CType(ViewState("DtResumen"), DataTable) End Get Set(value As DataTable) ViewState("DtResumen") = value End Set End Property Private Property DtVencimiento As DataTable Get DtVencimiento = CType(ViewState("DtVencimiento"), DataTable) End Get Set(value As DataTable) ViewState("DtVencimiento") = value End Set End Property Private Property CveTipoCredito As Integer Get CveTipoCredito = ViewState("CveTipoCredito").ToString.ToEntero End Get Set(value As Integer) ViewState("CveTipoCredito") = value End Set End Property Private Property DTCreditos As DataTable Get DTCreditos = CType(ViewState("DTCreditos"), DataTable) End Get Set(value As DataTable) ViewState("DTCreditos") = value End Set End Property Private Property DTCreditosTemp As DataTable Get DTCreditosTemp = CType(ViewState("DTCreditosTemp"), DataTable) End Get Set(value As DataTable) ViewState("DTCreditosTemp") = value End Set End Property Private Property DTExcel As DataTable Get DTExcel = CType(ViewState("DTExcel"), DataTable) End Get Set(value As DataTable) ViewState("DTExcel") = value End Set End Property Private Property NombreArchivo As String Get NombreArchivo = ViewState("NombreArchivo").ToString End Get Set(value As String) ViewState("NombreArchivo") = value End Set End Property Private Property FechaArchivo As String Get FechaArchivo = ViewState("FechaArchivo").ToString End Get Set(value As String) ViewState("FechaArchivo") = 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") = "" ViewState("OrdenVencimiento") = "" CveTipoCredito = IfNull(Request("CveTipoCredito"), "0").ToString.ToEntero If CveTipoCredito > 0 Then DvFiltros.Visible = True UPFiltros.Update() CargaDatosTipoCredito() LtTitulo.Text = "Reporte Créditos" Else LtTitulo.Text = "Reporte Créditos" TabContainerReportes.Visible = True CargaDatos() End If If CveTipoCredito > 0 Then 'ImgAdd.Attributes.Add("OnClick", String.Format("window.location = '/Bancos/Creditos.aspx?CveTipoCredito={0}'", CveTipoCredito)) End If End If End Sub #Region " INICIALIZA MODALIDAD " Public Sub CargaDatosTipoCredito() Dim FechaInicial As String = "01/01/1900" Dim FechaFinal As String = "01/01/2999" If txtFechaI.Text.Length = 10 Then FechaInicial = txtFechaI.Text End If If txtFechaF.Text.Length = 10 Then FechaFinal = txtFechaF.Text End If Dim ObjCreditos As New ClsBancos If ObjCreditos.GetCreditosRep(CveTipoCredito, 1, UsuarioActual.CveEmpresa, FechaInicial, FechaFinal, DdlFiltroEstatus.SelectedValue.ToEntero) Then DtResumen = ObjCreditos.DtResultados Else Me.GvR.DataSource = Nothing End If 'PARA UPLOAD EXCEL DTExcel = New DataTable If CveTipoCredito = 1 AndAlso ObjCreditos.GetCreditos(-1, -1, -1, -1, 1, UsuarioActual.CveEmpresa) Then DTCreditos = ObjCreditos.DtResultados DTCreditosTemp = DTCreditos RowCrediProveedor.Visible = True GvC.Columns(0).ItemStyle.Width = Unit.Pixel(150) GvC.Columns(1).Visible = True ' muestro el proveedor GvC.Columns(2).Visible = True ' muestro la factura CargaRegistroExcel() ViewState("Orden") = "FechaVencimiento" End If If CveTipoCredito > 1 Then GvC.Columns(6).Visible = False End If ObjCreditos.Dispose() If ViewState("Orden").ToString() <> String.Empty Then CargaGridTipoCredito(ViewState("Orden").ToString()) Else CargaGridTipoCredito("") End If UPDatos.Update() End Sub #End Region #Region "C A R G A - D A T O S" Public Sub CargaDatos() Dim ObjCreditos As New ClsBancos If ObjCreditos.GetCreditosRep(-1, 0, UsuarioActual.CveEmpresa) Then DtResumen = ObjCreditos.DtResultados Else Me.GvR.DataSource = Nothing End If If ObjCreditos.GetCreditosVencimiento(UsuarioActual.CveEmpresa) Then DtVencimiento = ObjCreditos.DtResultados TxtTC.Text = GlobalTipoCambio.ToString LblTotPesos.Text = String.Format("$ {0}", DtVencimiento.SUM("Total", "CveMoneda = 1").ToString.FormatoNumero()) LblTotDolares.Text = String.Format("$ {0}", DtVencimiento.SUM("Total", "CveMoneda = 2").ToString.FormatoNumero()) LblPesosTotal.Text = String.Format("$ {0}", DtVencimiento.SUM("TotalPesos", "").ToString.FormatoNumero()) Else Me.GvR.DataSource = Nothing End If ObjCreditos.Dispose() If ViewState("Orden").ToString() <> String.Empty Then CargaGrid(ViewState("Orden").ToString()) Else CargaGrid("") End If If ViewState("OrdenVencimiento").ToString() <> String.Empty Then CargaGridVencimiento(ViewState("OrdenVencimiento").ToString()) Else CargaGridVencimiento("") End If UPDatos.Update() End Sub Private Sub CargaGrid(Orden As String) If Orden <> String.Empty Then Dim DV As New DataView(DtResumen, "", Orden, DataViewRowState.CurrentRows) GvR.DataSource = DV.ToTable() DV.Dispose() Else GvR.DataSource = DtResumen End If GvR.DataBind() UPDatos.Update() End Sub Private Sub CargaGridVencimiento(Orden As String) If Orden <> String.Empty Then Dim DV As New DataView(DtVencimiento, "", Orden, DataViewRowState.CurrentRows) GvV.DataSource = DV.ToTable() DV.Dispose() Else GvV.DataSource = DtVencimiento End If GvV.DataBind() UPDatos.Update() End Sub Private Sub CargaGridTipoCredito(Orden As String) If Orden <> String.Empty Then Dim DV As New DataView(DtResumen, "", Orden, DataViewRowState.CurrentRows) GvC.DataSource = DV.ToTable() DV.Dispose() Else GvC.DataSource = DtResumen End If GvC.DataBind() UPDatos.Update() End Sub '#Region "GV - Datos" ' Protected Sub GvAmortizacion_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvDatos.RowDataBound ' If e.Row.RowType = DataControlRowType.DataRow Then ' If e.Row.RowIndex = 0 Then ' e.Row.Cells(0).Width = Unit.Pixel(250) ' e.Row.Cells(1).Width = Unit.Pixel(100) ' e.Row.Cells(2).Width = Unit.Pixel(100) ' e.Row.Cells(3).Width = Unit.Pixel(100) ' e.Row.Cells(4).Width = Unit.Pixel(100) ' End If ' End If ' End Sub '#End Region #End Region #Region " GVs ROW DATA BOUND | DELETE" Protected Sub GvR_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvR.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveTipoCredito") = "" Then e.Row.CssClass = "SubTotales2" End If End If End Sub Protected Sub GvC_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvC.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("CveCredito") = "" Then e.Row.CssClass = "SubTotales2" e.Row.FCLinkButton("imgD").Visible = False 'si es la suma de la linea de credito e.Row.Cells(1).Text = e.Row.DBCampo("Contador") End If If e.Row.DBCampo("FechaVencimiento") <> "" AndAlso e.Row.DBCampo("FechaVencimiento").ToDate <= Now Then e.Row.ForeColor = System.Drawing.Color.Red e.Row.ToolTip = "Fecha Vencida" End If End If End Sub Protected Sub GvC_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GvC.RowDeleting Dim DbRow As DataRow = Nothing DbRow = DtResumen.Rows(e.RowIndex) Dim ObjBancos As New ClsBancos If ObjBancos.CancelarCreditos(DbRow("CveCredito").ToString.ToEntero, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Then Alert("El crédito se eliminó correctamente.", TipoMensaje.MsgInformacion) DtResumen.Rows.Remove(DbRow) Else Alert("ocurrió un error al eliminar el crédito. Por favor vuelva a intentar.", TipoMensaje.MsgError) End If ObjBancos.Dispose() If ViewState("Orden").ToString() <> String.Empty Then CargaGridTipoCredito(ViewState("Orden").ToString()) Else CargaGridTipoCredito("") End If End Sub #End Region #Region "E X C E L" ''Exportar Excel 'Protected Sub ImgExcel_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs) Handles ImgExcel.Click ' GvDatos.ExportToExcel("RepClientes_" & Now.ToShortDateString) 'End Sub #Region "A C T U A L I Z A R - E X C E L" Protected Sub BtnActualizar_Click(sender As Object, e As EventArgs) Handles BtnActualizar.Click Dim Ruta = "" If FUExcel.HasFile Then Dim FileName As String = Path.GetFileName(FUExcel.PostedFile.FileName) NombreArchivo = FileName FechaArchivo = NombreArchivo.Substring(NombreArchivo.Length - 12, 8) FechaArchivo = String.Format("{0}/{1}/{2}", FechaArchivo.Substring(6, 2), FechaArchivo.Substring(4, 2), FechaArchivo.Substring(0, 4)) Dim Extension As String = Path.GetExtension(FUExcel.PostedFile.FileName) Dim FolderPath As String = Request.ApplicationPath + "Temp\" FolderPath.DirectoryExistsCreate Dim FilePath As String = Server.MapPath(FolderPath + FileName) FUExcel.SaveAs(FilePath) 'Import_To_Grid(FilePath, Extension) LeerExcel(FilePath) Else Alert("No tiene ningun archivo", TipoMensaje.MsgAdvertencia) End If End Sub Private Sub LeerExcel(rutaExcel As String) Dim conn As Odbc.OdbcConnection = Nothing Dim ErrorExcel = False Try 'If (Path.GetExtension(rutaExcel).ToUpper() = ".XLS") Then ' cb.Provider = "Microsoft.ACE.OLEDB.12.0" ' cb.Add("Extended Properties", "Excel 14.0;HDR=YES;IMEX=0;") 'ElseIf (Path.GetExtension(rutaExcel).ToUpper() = ".XLSX") Then ' cb.Provider = "Microsoft.ACE.OLEDB.12.0" ' cb.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES;IMEX=0;") 'End If conn = New Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & rutaExcel) conn.Open() Dim cmd = conn.CreateCommand() cmd.CommandType = CommandType.Text cmd.CommandText = "SELECT * FROM [Detalle$]" Dim da = New Odbc.OdbcDataAdapter(cmd) da.Fill(DTExcel) Catch ex As Exception ErrorExcel = True Alert("Ocurrio un error al leer el Excel: " + ex.ToString, TipoMensaje.MsgError) End Try conn.Close() If Not ErrorExcel Then DTExcel.Columns(2).ColumnName = "Referencia" DTExcel.Columns(4).ColumnName = "Proveedor" DTExcel.Columns(5).ColumnName = "Compra" DTExcel.Columns(6).ColumnName = "Estatus" DTExcel.Columns(7).ColumnName = "FechaInicio" DTExcel.Columns(8).ColumnName = "FechaVencimiento" DTExcel.Columns(9).ColumnName = "Importe" DTExcel.Columns(10).ColumnName = "Intereses" DTExcel.Columns(11).ColumnName = "Tasa" DTExcel.Columns(12).ColumnName = "SobreTasa" DTExcel.Columns(16).ColumnName = "FechaOperacion" ProcesarExcel() End If End Sub Private Sub ProcesarExcel() Dim DtTemp = DTExcel.Clone Dim ObjCredito As New ClsBancos Dim ObjMov As New ClsContabilidad(ObjCredito.IniciaTransacSQL) Dim ObjEventoBitacora As New ClsOIEventos(ObjCredito.IniciaTransacSQL) Dim ErrorCredito = False Dim Estatus = -1 Dim Compra = "" Dim drC As DataRow = Nothing Dim DividirCompra(2) As String Dim Msg As New StringBuilder Dim MsgPagadas As New StringBuilder Dim fecha = "" For Each drE As DataRow In DTExcel.Rows DtTemp = DTCreditos.FiltraParametros(String.Format("Folio = '{0}' and CreditoValor = {1}", drE("Compra").ToString.Trim, drE("Importe").ToString.ToDouble)) If DtTemp.Rows.Count > 0 Then 'DividirCompra = drE("Compra").ToString.Split("-"c) Compra = drE("Compra").ToString.Trim 'DtTemp = DTExcel.FiltraParametros(String.Format("Folio = '{0}' and CreditoValor = {1}", Compra.Trim, drE("Importe").ToString.ToDouble)) drC = DtTemp.Rows(0) End If 'Actualiza Credito If DtTemp.Rows.Count >= 1 Then If Not ObjCredito.UpdateCreditosReferencia(drC("CveCredito").ToString.ToEntero, drE("Referencia").ToString.Trim, drE("Plazo").ToString.ToEntero, drE("FechaInicio").ToString.ToDate, drE("FechaVencimiento").ToString.ToDate) Then ErrorCredito = True Exit For End If 'Si no cambia de estatus If drE("Estatus").ToString = drC("Estatus").ToString Then If Not ObjCredito.UpdateCreditosDetalle(drC("CveCreditoDetalle").ToString.ToEntero, drE("FechaVencimiento").ToString.ToDate, drC("CreditoValor").ToString.ToDouble, drE("Intereses").ToString.ToDouble, 0.0, drC("IVACapital").ToString.ToDouble, 0.0, 0.0, -1) Then ErrorCredito = True Exit For End If 'Cuando Cambia de estatus Else 'verifico si hubo un pago, If drC("Estatus").ToString = "C" And (drE("Estatus").ToString.Contiene("P", "L")) Then 'Agrega Bitacora fecha = FechaArchivo If Not ObjEventoBitacora.AddEventoBitacora(String.Format("Se ha pagado el documento de crédito con fecha {0}", fecha), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=drC("CveCompra").ToString.ToEntero) Then ErrorCredito = True Exit For End If If ObjCredito.UpdateCreditosDetalle(drC("CveCreditoDetalle").ToString.ToEntero, drE("FechaVencimiento").ToString.ToDate, drC("CreditoValor").ToString.ToDouble, drE("Intereses").ToString.ToDouble, 0.0, drC("IVACapital").ToString.ToDouble, 0.0, 0.0, 103) Then 'se registra el pago, siempre y cuando no se tenga registrado MsgPagadas.AppendFormat(" - {0} # {1}
", drE("Proveedor"), drE("Compra")) Else ErrorCredito = True Exit For End If ElseIf (drC("Estatus").ToString = "E" And drE("Estatus").ToString = "C") Then 'Agrega Bitacora fecha = drE("FechaOperacion").ToString If Not ObjEventoBitacora.AddEventoBitacora(String.Format("Se ha descargado el documento de crédito con fecha {0}", fecha), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=drC("CveCompra").ToString.ToEntero) Then ErrorCredito = True Exit For End If If Not ObjCredito.UpdateCreditosDetalle(drC("CveCreditoDetalle").ToString.ToEntero, drE("FechaVencimiento").ToString.ToDate, drC("CreditoValor").ToString.ToDouble, drE("Intereses").ToString.ToDouble, 0.0, drC("IVACapital").ToString.ToDouble, 0.0, 0.0, 102) Then ErrorCredito = True Exit For End If End If End If 'Agrega Credito Else If drE("Estatus").ToString.Contiene("E", "C") Then 'inserta 'busco la compra, sino existe la ingresa a creditos Dim CveCompra As Integer = -1 Dim CveProveedor As Integer Dim Comp As New ClsCompras If Comp.GetCompras(UsuarioActual.CveEmpresa, "-1", drE("Compra").ToString.Trim, "-1", "-1", drE("Proveedor").ToString.Substring(0, 20), "-1", "-1", "-1", "-1") Then If Comp.DtResultados.Rows.Count > 0 Then CveCompra = Comp.DtResultados.Rows(0)("CveCompra").ToString.ToEntero CveProveedor = Comp.DtResultados.Rows(0)("CveProveedor").ToString.ToEntero ''obtengo la cuenta de pago, de crediproveedores Dim CveCuenta As Integer Dim drBC As DataRow = GlobalDTBancosCuentas(-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("CveTipoCuenta = 7") 'obtiene la primer cuenta de crediproveedores If drBC IsNot Nothing Then CveCuenta = drBC("CveCuenta").ToString.ToEntero Dim CveCredito As Integer = ObjCredito.AddCreditos(1, drE("Referencia").ToString.Trim, "-1", CveCuenta, CveCompra, -1, 1, drE("FechaInicio").ToString.ToDate, drE("FechaVencimiento").ToString.ToDate, drE("Tasa").ToString.ToDouble, drE("SobreTasa").ToString.ToDouble, 0.16, drE("Plazo").ToString.ToEntero, -1, drE("Importe").ToString.ToDouble, 0, 0, 0, CveProveedor, 1, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) If CveCredito > 0 Then Estatus = If(drE("Estatus").ToString = "E", 101, Estatus) Estatus = If(drE("Estatus").ToString = "C", 102, Estatus) Estatus = If(drE("Estatus").ToString = "P", 103, Estatus) Estatus = If(drE("Estatus").ToString = "L", 104, Estatus) If Not ObjCredito.AddCreditosDetalle(CveCredito, drE("FechaOperacion").ToString.ToDate, drE("Importe").ToString.ToDouble, drE("Intereses").ToString.ToDouble, 0.0, 0, 0.0, 0.0, Estatus) Then ErrorCredito = True Exit For End If Else ErrorCredito = True Exit For End If ''------------------------------------ cuando ya es descargado If drE("Estatus").ToString.Contiene("C") Then 'tambien registro la prepoliza de pago al proveedor, es pago descargado Dim Importe As Decimal = drE("Importe").ToString.ToDecimal Dim Intereses As Double = drE("Intereses").ToString.ToDouble Dim FechaMov As Date = drE("FechaOperacion").ToString.ToDate Dim FolioDocto As String = "0" 'debo de obtener si ya esta pagada,sino esta se inserta el pago, sino se omite If Comp.DtResultados.Rows(0)("Saldo").ToString.ToEntero > 0 Then FolioDocto = ObjCredito.GetNextFolio(CveCuenta, 2).ToString Dim CvePrePoliza As Integer = ObjMov.AddPrePolizas("Banc", 5, Importe, Importe, 1, FechaMov, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) Dim CveIE As Integer = ObjCredito.AddBancos_IE(CveCuenta, 2, FechaMov, FolioDocto, drE("Proveedor").ToString, Importe + Intereses, 1, 1, "", "", True, True, 0, CvePrePoliza, "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) 'debe de registrar la prepoliza If CvePrePoliza > 0 Then If ObjMov.AddPrePolizasDetalle(CvePrePoliza, True, Importe, "", 17, "", FechaMov, 0, -1, CveIE, CveCompra:=CveCompra, CveProveedor:=CveProveedor) Then Dim IVA As Double = 0 'TxtImporte.Text.ToDouble * HdnProvPorIVA.Value.ToDouble If Not ObjMov.AddPrePolizasDetalle(CvePrePoliza, False, Importe, "", 50, "", Now, 0, -1, CveIE, CveCompra:=CveCompra, CveProveedor:=CveProveedor) Then ErrorCredito = True Exit For End If Else ErrorCredito = True Exit For End If Else ErrorCredito = True Exit For End If End If End If Else Msg.AppendFormat(" - {0} # {1}
", drE("Proveedor"), drE("Compra")) End If End If Comp.Dispose() End If End If Next Dim MsgNoRegistradas As New StringBuilder For Each dr As DataRow In DTCreditos.FiltraParametros("Estatus <> 'P' ").Rows DtTemp = DTExcel.FiltraParametros(String.Format("Compra = '{0}' AND Importe = {1}", dr("Folio").ToString, dr("CreditoValor").ToString)) If DtTemp.Rows.Count = 0 Then MsgNoRegistradas.AppendFormat(" - {0} # {1}
", dr("Proveedor").ToString, dr("Compra").ToString) End If Next If Not ErrorCredito Then If Not CreaRegistroExcel() Then ObjCredito.RollBack() Alert("Ocurrio un error al generar el archivo de la bitácora", TipoMensaje.MsgError) CargaDatosTipoCredito() Else ObjCredito.Commit() If Msg.Length > 0 OrElse MsgPagadas.Length > 0 OrElse MsgNoRegistradas.Length > 0 Then Dim MM As String = "" If Msg.Length > 0 Then MM = String.Format("Las siguientes Facturas no coindicieron en el sistema:
{0}

", Msg.ToString) End If If MsgPagadas.Length > 0 Then MM = String.Format("{0}

Las siguientes Facturas ya fueron pagadas y no se ha registrado pago en sistema:
{1}

", MM, MsgPagadas.ToString) End If If MsgNoRegistradas.Length > 0 Then MM += String.Format("

Las siguientes Facturas estan registradas en el sistema, pero no se encuentra el documento excel:

{0}", MsgNoRegistradas) End If Alert(MM, TipoMensaje.MsgAdvertencia) Else Alert("Actualización de créditos exitosa.", TipoMensaje.MsgInformacion, String.Format("document.location.href=""/Bancos/RepCreditos.aspx?CveTipoCredito=1"";")) End If End If Else ObjCredito.RollBack() Alert("Ocurrio un error en la actualización de los créditos. Porfavor intente nuevamente.", TipoMensaje.MsgError) End If ObjCredito.Dispose() CargaDatosTipoCredito() End Sub Private Function CreaRegistroExcel() As Boolean If Not System.IO.Directory.Exists(String.Format("{0}CreditosExcel", UsuarioActual.Empresa.Ruta)) Then IO.Directory.CreateDirectory(String.Format("{0}CreditosExcel", UsuarioActual.Empresa.Ruta)) End If Dim fs As FileStream = Nothing Dim path As String = String.Format("{0}CreditosExcel\Creditos.txt", UsuarioActual.Empresa.Ruta) Try If IO.File.Exists(path) Then File.Delete(path) fs = File.Create(path) 'NombreArchivo = "hola.excel" ' Add text to the file. Dim info As Byte() = New UTF8Encoding(True).GetBytes(String.Format("{0}|{1}", NombreArchivo, Date.Now.ToShortDateString)) fs.Write(info, 0, info.Length) fs.Close() Catch ex As Exception Alert($"Error al registrar en la bitacora de carga de archivos [{ex.Message}]", TipoMensaje.MsgError) Finally If fs IsNot Nothing Then fs.Close() End Try Return True End Function Private Sub CargaRegistroExcel() Dim path As String = String.Format("{0}CreditosExcel\Creditos.txt", UsuarioActual.Empresa.Ruta) If File.Exists(path) Then Dim objReader As New StreamReader(path) Dim Texto = objReader.ReadLine() Dim Arreglo() = Texto.Split("|"c) objReader.Close() TableExcel.Visible = True LtNombreArchivo.Text = Arreglo(0) LtFechaArchivo.Text = Arreglo(1) End If End Sub #End Region #End Region Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) CargaDatosTipoCredito() End Sub End Class