Files
SIG/GPS/RepCombustible.aspx.vb
2023-08-23 20:38:07 -07:00

444 lines
23 KiB
VB.net

Imports Extensiones
Imports System.Data
Imports Microsoft.Reporting.WebForms
Imports System.Net
Imports Newtonsoft.Json.Linq
Imports System.IO
Partial Class GPS_RepCombustible
Inherits ClsPaginas
#Region "P R O P I E D A D E S"
Property DTDatos As DataTable
Get
If ViewState("DTDatos") Is Nothing Then
Return New DataTable
Else
Return DirectCast(ViewState("DTDatos"), DataTable)
End If
End Get
Set(value As DataTable)
ViewState("DTDatos") = value
End Set
End Property
Private Property CveDispositivo As Integer
Get
Return CType(ViewState("CveDispositivo"), Integer)
End Get
Set(value As Integer)
ViewState("CveDispositivo") = value
End Set
End Property
Private Property FechaI As DateTime
Get
Return CType(ViewState("FechaI"), DateTime)
End Get
Set(value As DateTime)
ViewState("FechaI") = value
End Set
End Property
Private Property FechaF As DateTime
Get
Return CType(ViewState("FechaF"), DateTime)
End Get
Set(value As DateTime)
ViewState("FechaF") = value
End Set
End Property
Private Property DTCargas As DataTable
Get
Return CType(ViewState("DTCargas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTCargas") = value
End Set
End Property
Private Property DTDescargas As DataTable
Get
Return CType(ViewState("DTDescargas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DTDescargas") = value
End Set
End Property
#End Region
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CargaDispositivos()
txtFechaI.Text = $"{Now.FirstDayOfMonth.ToString("dd/MM/yyyy")} 00:00"
txtFechaF.Text = $"{Now.LastDayOfMonth.ToString("dd/MM/yyyy")} 00:00"
End If
End Sub
#Region "C O M B O S"
Private Sub CargaDispositivos()
DdlDispositivo.DataSource = GlobalDTDispositivosUsuarios(UsuarioActual.CveCliente, UsuarioActual.CveUsuario).FiltraParametros("TieneCombustible = 1")
'Dim GPS As New ClsGPS
'If GPS.DispositivosGet(-1, 1, UsuarioActual.CveCliente) AndAlso GPS.DtResultados.Rows.Count > 0 Then
' DdlDispositivo.DataSource = GPS.DtResultados.FiltraParametros("TieneCombustible = 1")
'End If
'GPS.Dispose()
DdlDispositivo.DataBind()
DdlDispositivo.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Private Sub CargaDatos()
LtlUnidad.Text = DdlDispositivo.SelectedItem.Text
CveDispositivo = DdlDispositivo.SelectedValue.ToEntero()
FechaI = txtFechaI.Text.ToDateTime
FechaF = txtFechaF.Text.ToDateTime
'UpReportes.Update()
Dim GPS As New ClsGPS
HdfVGrafica.Value = "data=[]"
If GPS.RepCombustibleGet(DdlDispositivo.SelectedValue.ToEntero(), FechaI, FechaF) AndAlso GPS.DtResultados.Rows.Count > 0 Then
Dim Arow As DataRow = GPS.DtResultados.Rows(0)
Dim TotalKilometros As Decimal = (Arow("Distancia").ToString().ToDecimal()) / 1000
Dim CombustibleConsumido As Decimal = $"{(Arow("CombustibleInicial").ToString().ToDecimal() + Arow("SumaCargas").ToString().ToDecimal()) - Arow("CombustibleFinal").ToString().ToDecimal():N2}".ToDecimal
Dim RendBruto As Decimal = If(CombustibleConsumido > 0, TotalKilometros / CombustibleConsumido, 0) '2.8
Dim CostoCombustible As Decimal = GlobalDTDispositivos(-1).FiltroPrimeroValor("CostoCombustible", $"CveDispositivo = {DdlDispositivo.SelectedValue}").ToDecimal
LtlDistancia.Text = TotalKilometros.ToString().FormatoNumero()
lblVelocidad.Text = $"{GPS.DtResultados.Rows(0)("VelocidadMaxima").ToString().FormatoNumero()}"
lblRendBruto.Text = $"{RendBruto.ToString().FormatoNumero()}"
LtlCombustibleConsumido.Text = CombustibleConsumido.ToString().FormatoNumero()
LtlCombustibleInicial.Text = $"{Arow("CombustibleInicial").ToString().ToDecimal():N2}"
LtlCombustibleFinal.Text = GPS.DtResultados.Rows(0)("CombustibleFinal").ToString().FormatoNumero()
LtlNoCargas.Text = $"{Arow("Cargas").ToString().ToDecimal():N2}"
LtlNoDescargas.Text = $"{Arow("Descargas").ToString().ToDecimal():N2}"
SumaCargas.Text = $"{Arow("SumaCargas").ToString().ToDecimal():N2}"
LtlCostoCargas.Text = $"{Arow("SumaCargas").ToString().ToDecimal() * CostoCombustible:N2}"
SumaDescargas.Text = $"{Arow("SumaDescargas").ToString().ToDecimal():N2}"
LtlCostoDescargas.Text = $"{Arow("SumaDescargas").ToString().ToDecimal() * CostoCombustible:N2}"
LtlDistanciaR.Text = TotalKilometros.ToString().FormatoNumero()
lCombustibleConsumido.Text = $"{(CombustibleConsumido - Arow("SumaDescargas").ToString().ToDecimal()):N2}"
LtlCostoConsumo.Text = $"${((CombustibleConsumido - Arow("SumaDescargas").ToString().ToDecimal()) * CostoCombustible).ToString().FormatoNumero()}"
LtlCostoCombustibleF.Text = $"${(GPS.DtResultados.Rows(0)("CombustibleFinal").ToString().ToDecimal * CostoCombustible).ToString().FormatoNumero()}"
LtlCostoInicial.Text = $"${(GPS.DtResultados.Rows(0)("CombustibleInicial").ToString().ToDecimal * CostoCombustible).ToString().FormatoNumero()}"
lblMuerto.Text = $"{((DateDiff(DateInterval.Minute, txtFechaI.Text.ToDateTime, txtFechaF.Text.ToDateTime) - GPS.DtResultados.Rows(0)("Horas").ToString().ToLong) / 60).ToString().FormatoNumero()} Hrs."
lblMovimiento.Text = $"{(GPS.DtResultados.Rows(0)("Horas").ToString().ToDecimal / 60).ToString().FormatoNumero()} Hrs"
LtlRalenti.Text = $"{GPS.DtResultados.Rows(0)("TiempoRalentiHoras").ToString().FormatoNumero()} Hrs. ({GPS.DtResultados.Rows(0)("TiempoRalentiMinutos").ToString()} Minutos)"
CargaHistorico(GPS)
DvReporte.Visible = True
'lblRendEfectivo.Text = $"{(RendBruto + 1).ToString().FormatoNumero()} KM/L"
End If
GPS.Dispose()
UpReporte.Update()
UpDash.Update()
UPTabla.Update()
upDatosComb.Update()
' bodyreportes.Visible = True
' UpReportes.Update()
End Sub
Private Sub CargaHistorico(ByRef GPS As ClsGPS)
If GPS.GetCombustibleHistorico(DdlDispositivo.SelectedValue.ToEntero(), txtFechaI.Text.ToDateTime, txtFechaF.Text.ToDateTime) Then
Dim json As New StringBuilder
json.Append("data=[")
Dim color As String = ""
Dim encencido As Integer = -1
Dim encencidoC As Integer = -1
For Each gvrow As DataRow In GPS.DtResultados.Rows
encencidoC = gvrow("Encendido").ToString().ToEntero()
If encencido <> encencidoC Then
If encencidoC = 1 Then
color = ",lineColor:""#2498d2"""
'color = ",lineColor:""#b7e021"""
Else
color = ",lineColor:""#F3565D"""
'color = ",lineColor:""#2498d2"""
End If
Else
color = ""
End If
encencido = encencidoC
json.Append($",{{date: stringtodate(""{DirectCast(gvrow("FechaTrama"), DateTime).ToString("yyyy-MM-dd HH:mm:ss")}""), value: {gvrow("Valor").ToString().ToDecimal()}")
json.Append($",valuet1: {gvrow("ValorT1").ToString().ToDecimal()}, valuet2: {gvrow("ValorT2").ToString().ToDecimal()} {color}}}")
Next
json.Append(" ]")
json.Remove(6, 1)
HdfVGrafica.Value = json.ToString()
RegistraScript($"CargaHistorico()")
End If
End Sub
Private Sub BtnConsultar_Click(sender As Object, e As EventArgs) Handles BtnConsultar.Click
CargaDatos()
End Sub
Protected Sub lbCargas_Click(sender As Object, e As EventArgs) Handles lbCargas.Click
LtlTituloCD.Text = $"Desglose de cargas de combustible: {LtlUnidad.Text}"
Dim GPS As New ClsGPS
If GPS.GetCargasDescargas(CveDispositivo, FechaI, FechaF, 69) Then
GVHistorico.DataSource = GPS.DtResultados
DTCargas = GPS.DtResultados
Else
GVHistorico.DataSource = Nothing
End If
GPS.Dispose()
GVHistorico.DataBind()
UpdatePanel3.Update()
UpHistorico.Update()
RegistraScript("$('#dvHistorico').modal()")
End Sub
Protected Sub lbDesCargas_Click(sender As Object, e As EventArgs) Handles lbDescargas.Click
LtlTituloCD.Text = $"Desglose de descargas de combustible: {LtlUnidad.Text}"
Dim GPS As New ClsGPS
If GPS.GetCargasDescargas(CveDispositivo, FechaI, FechaF, 74) Then
GVHistorico.DataSource = GPS.DtResultados
DTDescargas = GPS.DtResultados
Else
GVHistorico.DataSource = Nothing
End If
GPS.Dispose()
GVHistorico.DataBind()
UpdatePanel3.Update()
UpHistorico.Update()
RegistraScript("$('#dvHistorico').modal()")
End Sub
Protected Sub GVHistorico_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVHistorico.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim RowID As String = $"row{e.Row.RowIndex}"
e.Row.Attributes("id") = RowID
RegistraScript($"GetDireccionesGV({{ lat: {e.Row.DBCampo("Lat").ToString()}, lng: {e.Row.DBCampo("Lon").ToString() }}}, '#{RowID}', {e.Row.RowIndex});", $"{RowID}")
End If
End Sub
Public Sub EnviarReporteProgramado()
Dim DTHistorico As DataTable = Nothing
Dim GPS As New ClsGPS
If GPS.GetCargasDescargas(CveDispositivo, FechaI, FechaF, -1) Then
DTHistorico = GPS.DtResultados.Copy()
End If
GPS.Dispose()
'DTHistorico.Columns.Add(New DataColumn("Direccion", GetType(String)))
If DTHistorico IsNot Nothing AndAlso DTHistorico.Rows.Count > 0 Then
Dim DireccionJSON As String = ""
Dim request As WebRequest
Dim js As JObject = Nothing
For Each Row As DataRow In DTHistorico.Rows
Try
request = WebRequest.Create(String.Format("{0}nominatim/reverse.php?format=jsonv2&lat={1}&lon={2}", ClsPaginas.UrlDirecciones, Row("Lat"), Row("Lon")))
request.Method = "GET"
Dim response As WebResponse = request.GetResponse()
Dim inputstream1 As Stream = response.GetResponseStream()
Dim reader As New StreamReader(inputstream1)
DireccionJSON = reader.ReadToEnd
inputstream1.Dispose()
reader.Close()
response.Close()
request = Nothing
js = JObject.Parse(DireccionJSON)
If js IsNot Nothing Then
Row("Direccion") = js("display_name").ToString()
End If
Catch ex As Exception
GuardaLog(ex.ToString)
End Try
Next
Dim retorno As Byte()
Dim RutaReporte = "Empresas/Grales/ReportesProgramados/RPCombustible.rdlc"
Try
Dim RptParametro As New List(Of ReportParameter)
RptParametro.Add(New ReportParameter("Equipo", LtlUnidad.Text))
RptParametro.Add(New ReportParameter("FechaInicio", FechaI.ToString("dd/MM/yyyy HH:mm")))
RptParametro.Add(New ReportParameter("FechaFin", FechaF.ToString("dd/MM/yyyy HH:mm")))
RptParametro.Add(New ReportParameter("ChartBase64", HdnChartBase64.Value, True))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("FechaImpresion", Now.ToString("dd/MM/yyyy")))
RptParametro.Add(New ReportParameter("ComInicialLTS", LtlCombustibleInicial.Text))
RptParametro.Add(New ReportParameter("ComInicialTotal", LtlCostoInicial.Text))
RptParametro.Add(New ReportParameter("CargasValor", LtlNoCargas.Text))
RptParametro.Add(New ReportParameter("CargasLTS", SumaCargas.Text))
RptParametro.Add(New ReportParameter("CargasTotal", LtlCostoCargas.Text))
RptParametro.Add(New ReportParameter("DescargasValor", LtlNoCargas.Text))
RptParametro.Add(New ReportParameter("DescargasLTS", SumaDescargas.Text))
RptParametro.Add(New ReportParameter("DescargasTotal", LtlCostoCargas.Text))
RptParametro.Add(New ReportParameter("RecoValor", LtlDistancia.Text))
RptParametro.Add(New ReportParameter("RecoLTS", lCombustibleConsumido.Text))
RptParametro.Add(New ReportParameter("RecoTotal", LtlCostoConsumo.Text))
RptParametro.Add(New ReportParameter("ComFinalLTS", LtlCombustibleFinal.Text))
RptParametro.Add(New ReportParameter("ComFinalTotal", LtlCostoCombustibleF.Text))
RptParametro.Add(New ReportParameter("VMax", lblVelocidad.Text))
RptParametro.Add(New ReportParameter("Rendimiento", lblRendBruto.Text))
RptParametro.Add(New ReportParameter("KMRecorridos", LtlDistanciaR.Text))
RptParametro.Add(New ReportParameter("ComConsumido", LtlCombustibleConsumido.Text))
retorno = StreamPDF(RutaReporte, DTHistorico, RptParametro, "ReporteProgramado", "PDF", MR:=Nothing, RDSName:="DsOC")
ImprimirbytesPDF(retorno, "ReporteCombustible")
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
Else
Alert("No se pudo imprimir el pdf, ya que no se ha hecho una consulta, o ésta no arrojó resultados.", TipoMensaje.MsgInformacion)
End If
End Sub
#End Region
Protected Sub LinkPDF_Click(sender As Object, e As EventArgs)
EnviarReporteProgramado()
End Sub
Protected Sub LnkHistorial_Click(sender As Object, e As EventArgs)
Dim GPS As New ClsGPS
GPS.GetCombustibleResumen(DdlDispositivo.SelectedValue.ToEntero(), txtFechaI.Text.ToDateTime.ToString("yyyy/MM/dd HH:mm"), txtFechaF.Text.ToDateTime.ToString("yyyy/MM/dd HH:mm"))
GVCombustibleResumen.DataSource = GPS.DtResultados
GVCombustibleResumen.DataBind()
GPS.Dispose()
GVCombustibleResumen.ExportToExcel2("Historial")
End Sub
Protected Sub Lnkreportegral_Click(sender As Object, e As EventArgs)
Dim file As String = $"{DirectorioBaseEmpresas}Empresas\Grales\Formatos\CombustibleGeneral.xlsx"
Try
Dim wb As New ClosedXML.Excel.XLWorkbook(file)
Dim libro = wb.Worksheets(0)
Dim NombreCliente As String = ""
Using ObjClientes As New ClsClientes()
If ObjClientes.GetClientes(UsuarioActual.CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, -1, -1) Then
NombreCliente = ObjClientes.DtResultados.Rows(0)("Nombre").ToString()
End If
End Using
libro.Cell(1, 3).Value = NombreCliente
libro.Cell(2, 3).Value = "Reporte de Combustible"
libro.Cell(4, 12).Value = DateTime.Now.ToString("dd/MM/yyyy")
libro.Cell(4, 4).Value = txtFechaI.Text
libro.Cell(5, 4).Value = txtFechaF.Text
Dim cRow As Integer = 9
Dim FechaI As Date = txtFechaI.Text.ToDateTime
Dim FechaF As Date = txtFechaF.Text.ToDateTime
Using GPS As New ClsGPS()
For Each item As ListItem In DdlDispositivo.Items
CveDispositivo = item.Value.ToString().ToEntero()
If CveDispositivo > 0 Then
cRow = cRow + 1
Dim vehiculo As String = item.Text
Dim VelocidadMaxima As String = "VelocidadMaxima"
Dim Rendimiento As String = "Rendimiento"
Dim KMRecorridos As String = "KMRecorridos"
Dim CombustibleConsumido As String = "CombustibleConsumido"
Dim Ralenti As String = "Ralenti"
Dim TiempoMovto As String = "TiempoMovto"
Dim TiempoMuerto As String = "TiempoMuerto"
Dim CILts As String = "CILts"
Dim CITotal As String = "CITotal"
Dim CFLts As String = "CFLts"
Dim CFTotal As String = "CFTotal"
Dim CargaValor As String = "CargaValor"
Dim CargaLts As String = "CargaLts"
Dim CargaTotal As String = "CargaTotal"
Dim DesCargaValor As String = "DesCargaValor"
Dim DesCargaLts As String = "DesCargaLts"
Dim DesCargaTotal As String = "DesCargaTotal"
Dim RecorridoValor As String = "RecorridoValor"
Dim RecorridoLts As String = "RecorridoLts"
Dim RecorridoTotal As String = "RecorridoTotal"
If GPS.RepCombustibleGet(CveDispositivo, FechaI, FechaF) AndAlso GPS.DtResultados.Rows.Count > 0 Then
Dim Arow As DataRow = GPS.DtResultados.Rows(0)
Dim TotalKilometros As Decimal = (Arow("Distancia").ToString().ToDecimal()) / 1000
Dim CostoCombustible As Decimal = GlobalDTDispositivos(-1).FiltroPrimeroValor("CostoCombustible", $"CveDispositivo = {CveDispositivo}").ToDecimal
Dim CombustibleConsumidoCC As Decimal = $"{ (Arow("CombustibleInicial").ToString().ToDecimal() + Arow("SumaCargas").ToString().ToDecimal()) - Arow("CombustibleFinal").ToString().ToDecimal():N2}".ToDecimal
VelocidadMaxima = $"{GPS.DtResultados.Rows(0)("VelocidadMaxima").ToString().FormatoNumero():N2}"
Rendimiento = $"{If(CombustibleConsumidoCC > 0, TotalKilometros / CombustibleConsumidoCC, 0):N2}"
KMRecorridos = $"{TotalKilometros:N2}"
CombustibleConsumido = $"{(Arow("CombustibleInicial").ToString().ToDecimal() + Arow("SumaCargas").ToString().ToDecimal()) - Arow("CombustibleFinal").ToString().ToDecimal():N2}"
Ralenti = $"{GPS.DtResultados.Rows(0)("TiempoRalentiHoras").ToString().FormatoNumero()} Hrs. ({GPS.DtResultados.Rows(0)("TiempoRalentiMinutos").ToString()} Minutos)"
TiempoMovto = $"{(GPS.DtResultados.Rows(0)("Horas").ToString().ToDecimal / 60).ToString().FormatoNumero()} Hrs"
TiempoMuerto = $"{((DateDiff(DateInterval.Minute, txtFechaI.Text.ToDateTime, txtFechaF.Text.ToDateTime).ToString().ToDecimal - GPS.DtResultados.Rows(0)("Horas").ToString().ToLong) / 60).ToString().FormatoNumero()} Hrs."
CILts = $"{Arow("CombustibleInicial").ToString().ToDecimal():N2}"
CITotal = $"{(GPS.DtResultados.Rows(0)("CombustibleInicial").ToString().ToDecimal * CostoCombustible).ToString().FormatoNumero()}"
CFLts = GPS.DtResultados.Rows(0)("CombustibleFinal").ToString().FormatoNumero()
CFTotal = $"{(GPS.DtResultados.Rows(0)("CombustibleFinal").ToString().ToDecimal * CostoCombustible).ToString().FormatoNumero()}"
CargaValor = $"{Arow("Cargas").ToString().ToDecimal():N2}"
CargaLts = $"{Arow("SumaCargas").ToString().ToDecimal():N2}"
CargaTotal = $"{Arow("SumaCargas").ToString().ToDecimal() * CostoCombustible:N2}"
DesCargaValor = $"{Arow("Descargas").ToString().ToDecimal():N2}"
DesCargaLts = $"{Arow("SumaDescargas").ToString().ToDecimal():N2}"
DesCargaTotal = $"{Arow("SumaDescargas").ToString().ToDecimal() * CostoCombustible:N2}"
RecorridoValor = TotalKilometros.ToString().FormatoNumero()
RecorridoLts = $"{(CombustibleConsumido.ToDecimal - Arow("SumaDescargas").ToString().ToDecimal()):N2}"
RecorridoTotal = $"{((CombustibleConsumido.ToDecimal - Arow("SumaDescargas").ToString().ToDecimal()) * CostoCombustible).ToString().FormatoNumero()}"
End If
libro.Cell(cRow, 1).Value = vehiculo
libro.Cell(cRow, 2).Value = VelocidadMaxima
libro.Cell(cRow, 3).Value = Rendimiento
libro.Cell(cRow, 4).Value = KMRecorridos
libro.Cell(cRow, 5).Value = CombustibleConsumido
libro.Cell(cRow, 6).Value = Ralenti
libro.Cell(cRow, 7).Value = TiempoMovto
libro.Cell(cRow, 8).Value = TiempoMuerto
libro.Cell(cRow, 9).Value = CILts
libro.Cell(cRow, 10).Value = CITotal
libro.Cell(cRow, 10).Style.NumberFormat.Format = "$* #,##0.00"
libro.Cell(cRow, 11).Value = CFLts
libro.Cell(cRow, 12).Value = CFTotal
libro.Cell(cRow, 12).Style.NumberFormat.Format = "$* #,##0.00"
libro.Cell(cRow, 13).Value = CargaValor
libro.Cell(cRow, 14).Value = CargaLts
libro.Cell(cRow, 15).Value = CargaTotal
libro.Cell(cRow, 15).Style.NumberFormat.Format = "$* #,##0.00"
libro.Cell(cRow, 16).Value = DesCargaValor
libro.Cell(cRow, 17).Value = DesCargaLts
libro.Cell(cRow, 18).Value = DesCargaTotal
libro.Cell(cRow, 18).Style.NumberFormat.Format = "$* #,##0.00"
libro.Cell(cRow, 19).Value = RecorridoValor
libro.Cell(cRow, 20).Value = RecorridoLts
libro.Cell(cRow, 21).Value = RecorridoTotal
libro.Cell(cRow, 21).Style.NumberFormat.Format = "$* #,##0.00"
End If
Next
End Using
Dim fs As Stream = New MemoryStream()
wb.SaveAs(fs)
fs.Position = 0
Dim memoryStream As New MemoryStream()
Using input As Stream = fs
input.CopyTo(memoryStream)
End Using
memoryStream.Position = 0
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xlsx", "Reporte de Historial de Movimientos"))
Response.BinaryWrite(memoryStream.ToArray())
Response.End()
Catch ex As Exception
Alert("Ocurrio un error al generar el reporte de combustible" & ex.ToString())
End Try
End Sub
End Class