Files
SIG/TareasProgramadas/TareasReporteDiario.ashx
2025-02-21 18:12:06 -07:00

294 lines
10 KiB
Plaintext

<%@ WebHandler Language="C#" Class="TareasReporteDairio" %>
using System;
using System.Web;
using Extensiones;
using System.Net;
using System.IO;
using System.Web.Services;
using System.Web.Services.Protocols;
using GemBox.Spreadsheet;
using System.Data;
using System.Text;
using System.Collections.Generic;
using ClosedXML;
using System.Web.SessionState;
using System.Web.Hosting;
public class TareasReporteDairio : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
bool retorno = false;
string Metodo = context.Request["Metodo"] ==null?"": context.Request["Metodo"];
int CveEmpresa =context.Request["CveEmpresa"] ==null?0: context.Request["CveEmpresa"].ToEntero();
switch (Metodo)
{
case "EjecutaReporteDiario":
retorno = ReporteDiario(CveEmpresa, context);
break;
default:
break;
}
if (retorno)
{
context.Response.Write("True");
}else
{
context.Response.Write("False");
}
context.Response.End();
}
private bool ReporteDiario(int CveEmpresa, HttpContext context)
{
Usuario Usuario = ValidaUsuarioSistema(100, CveEmpresa);
ClsGenerales objGenerales = new ClsGenerales();
bool respuesta = true;
StringBuilder sbTablas = new StringBuilder();
sbTablas.Append($"<b><center>Reporte Diario {DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}</center><b><br><br>");
if (objGenerales.GetReporteDiario(CveEmpresa))
{
int TablaActual = 1;
foreach (DataTable tabla in objGenerales.DSResultados.Tables)
{
sbTablas.AppendLine(ConvertDataTableToHtml(tabla));
TablaActual++;
sbTablas.Append("<br>");
sbTablas.Append("<br>");
}
}
else
{
respuesta = false;
}
objGenerales.Dispose();
MandaCorreo(sbTablas.ToString(), respuesta);
return respuesta;
}
private string ConvertDataTableToHtml(DataTable table)
{
StringBuilder html = new StringBuilder();
string ColumnaTitulo = "Titulo";
html.Append("<table border='1' style='border-collapse:collapse; width:100%;'>");
if(table.Columns[0].ColumnName==ColumnaTitulo && table.Rows.Count > 0) html.AppendFormat(" <caption style='background-color:#333333;'>{0}</caption>", table.Rows[0][ColumnaTitulo]);
html.Append("<thead style='background-color:#DDD; padding: 0px;'><tr>");
foreach (DataColumn column in table.Columns)
{
if (ColumnaTitulo != column.ColumnName) html.Append($"<th style='padding:5px; text-align:left;'>{column.ColumnName}</th>");
}
html.Append("</tr></thead>");
html.Append("<tbody>");
foreach (DataRow row in table.Rows)
{
html.Append("<tr>");
foreach (DataColumn column in table.Columns)
{
if (ColumnaTitulo != column.ColumnName)
{
object value = row[column];
string cellValue;
if (column.DataType == typeof(int) || column.DataType == typeof(decimal) || column.DataType == typeof(double) || column.DataType == typeof(float))
{
if (value != DBNull.Value && decimal.TryParse(value.ToString(), out decimal numericValue))
{
if (numericValue != 0)
{
cellValue = numericValue.ToString("N2");
}
else
{
cellValue = "";//0.00
}
}
else
{
cellValue = "";//0.00
}
html.Append($"<td style='padding:5px; text-align:right;'>{cellValue}</td>");
}
else
{
cellValue = value?.ToString() ?? string.Empty;
html.Append($"<td style='padding:5px; text-align:left;'>{cellValue}</td>");
}
}
}
html.Append("</tr>");
}
html.Append("</tbody>");
// Cerrar la tabla
html.Append("</table>");
return html.ToString();
}
//private string ConvertDataTableToHtml(DataTable table)
//{
// StringBuilder html = new StringBuilder();
// html.Append("<table border='1' style='border-collapse:collapse; width:100%;'>");
// html.Append("<thead><tr>");
// foreach (DataColumn column in table.Columns)
// {
// html.Append($"<th style='padding:5px; text-align:left;'>{column.ColumnName}</th>");
// }
// html.Append("</tr></thead>");
// html.Append("<tbody>");
// foreach (DataRow row in table.Rows)
// {
// html.Append("<tr>");
// foreach (DataColumn column in table.Columns)
// {
// html.Append($"<td style='padding:5px;'>{row[column]}</td>");
// }
// html.Append("</tr>");
// }
// html.Append("</tbody>");
// html.Append("</table>");
// return html.ToString();
//}
private void MandaCorreo(string Cuerpo, bool PrceosoOK)
{
try
{
List<ClsSisMail.ArchivoMail> ListaArchivos = new List<ClsSisMail.ArchivoMail>();
ClsSisMail Correo = new ClsSisMail();
//string Para = "julian@adssistemas.mx;rene.molina@adssistemas.mx;oscar.irigoyen@adssistemas.mx";
//string Para = "rene.molina@adssistemas.mx"; // oscar.irigoyen@adssistemas.mx;
string Para = "hdiaz@grupodiaz.com.mx;libarra@grupodiaz.com.mx;jguerrero@grupodiaz.com.mx;contabilidad@grupodiaz.com.mx;cnazarit@yahoo.com;julian@adsistemas.mx;rene.molina@adssistemas.mx";
string Asunto = PrceosoOK ? $"Reporte Diario":"Reporte Diario Error";
Asunto = $"{Asunto} {DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}";
Correo.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Cuerpo, Archivos:ListaArchivos);
this.GuardaLog($"EjecutaReporteDiario: MandaCorreo() correo enviado. ");
}catch(Exception ex)
{
Extensiones.ModExtensiones.GuardaLog(null,$"Error Tareas Programadas 119 error enviar mail --> {ex.Message} ");
this.GuardaLog($"EjecutaReporteDiario: MandaCorreo() Error {ex.StackTrace.ToString()}. ");
}
}
private Usuario ValidaUsuarioSistema(int CveUsuario, int CveEmpresa)
{
Usuario UsuarioActual = null/* TODO Change to default(_) if this is not a reference type */;
string NombreCadena = ClsPaginas.get_GlobalNombreCadenaConexion(CveEmpresa);
ClsSisUsuarioAutenticacion ObjUsuarios = new ClsSisUsuarioAutenticacion(NombreCadena:NombreCadena);
UsuarioActual = ObjUsuarios.GetUsuarioDetalle(CveUsuario);
if (UsuarioActual != null)
{
if( HttpContext.Current.Session == null)
{
// CrearHttpContextArtificial();
CrearHttpContextConSession();
}
HttpContext.Current.Session["UsuarioSIG"] = UsuarioActual;
}
ObjUsuarios.Dispose();
return UsuarioActual;
}
public static void CrearHttpContextConSession()
{
//CrearHttpContextArtificial();
// Para agregar soporte de sesión, debemos inicializar el manejador de sesión
var sessionContainer = new HttpSessionStateContainer("id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, sessionContainer);
}
private bool VerificarArchivo(FileInfo FInfo, long Tamanio, string FTPServer, string FTPUsr, string FTPPass)
{
bool Respuesta = false;
try
{
this.GuardaLog($"EjecutaThalamus: VerificarArchivo() conectando a FTP .");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"{FTPServer}/{FInfo.Name}");
request.Credentials = new NetworkCredential(FTPUsr, FTPPass);
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.UseBinary = true;
FtpWebResponse loginresponse = (FtpWebResponse)request.GetResponse();
FtpWebResponse respSize = (FtpWebResponse)request.GetResponse();
respSize = (FtpWebResponse)request.GetResponse();
long size = respSize.ContentLength;
respSize.Close();
this.GuardaLog($"EjecutaThalamus: VerificarArchivo() tamaño local {Tamanio} ftp { size}. ");
if (Tamanio == size)
{
Respuesta = true;
this.GuardaLog($"EjecutaThalamus: VerificarArchivo() tamaño ok. ");
}
}catch(Exception ex)
{
Extensiones.ModExtensiones.GuardaLog(null,$"Error Tareas Programadas 119 verificando archivo { FInfo.Name } {ex.Message} ");
this.GuardaLog($"EjecutaThalamus: VerificarArchivo() Error {ex.StackTrace.ToString()}. " );
Respuesta = false;
}
return Respuesta;
}
public bool IsReusable
{
get { return false; }
}
}