Inicio PS por caducar y RSCO Por Vencer, Avance descarga Ingresos

This commit is contained in:
rakcsle
2022-07-20 17:00:22 -07:00
parent dba2eb55e3
commit 679463df72
14 changed files with 1472 additions and 114 deletions

View File

@@ -0,0 +1,534 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Extensiones;
using Newtonsoft.Json.Linq;
public partial class SAT_SolicitudesIngresoSat : ClsPaginas
{
#region Propiedades
public string clasegrid
{
get
{
if (ViewState["clasegrid"] == null) { return ""; }
else { return ViewState["clasegrid"].ToString(); }
}
set { ViewState["clasegrid"] = value; }
}
public string fechaInicio
{
get
{
if (ViewState["fechaInicio"] == null) { return ""; }
else { return ViewState["fechaInicio"].ToString(); }
}
set { ViewState["fechaInicio"] = value; }
}
public string fechaFin
{
get
{
if (ViewState["fechaFin"] == null) { return ""; }
else { return ViewState["fechaFin"].ToString(); }
}
set { ViewState["fechaFin"] = value; }
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TxtRpdFechaInicio.Text = string.Format("01/{0:MM/yyyy}", DateTime.Now.AddMonths(-1));
TxtRpdFechaFin.Text = string.Format("{0:dd/MM/yyyy}", DateTime.Now.AddMonths(-1).LastDayOfMonth());
//LnkConsultar_Click(null, null);
}
}
protected void LnkDownloadExcel_Click(object sender, EventArgs e)
{
using (ClsNominas nom = new ClsNominas())
{
nom.SATSolicitudTimbreNominaGral(DdlReporte.SelectedValue.ToString().ToEntero(), UsuarioActual.CveEmpresa, fechaInicio, fechaFin);
ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook();
var libro = wb.AddWorksheet(nom.DtResultados , "Nomina");
libro.ColumnsUsed().AdjustToContents();
libro.Range(1, 1, 1, nom.DtResultados.Columns.Count).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 153, 153));
switch (DdlReporte.SelectedValue.ToString().ToEntero())
{
case 1:
libro.Range(1, 2, 1, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153,0,0));
libro.Range(1, 3, 1, 5).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
break;
case 2:
libro.Range(1, 2, 1, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 0, 0));
libro.Range(1, 3, 1, 6).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
libro.Range(1, 8, 1, 11).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
break;
case 3:
libro.Range(1, 1, 1, 10).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
libro.Range(1, 11, 1, nom.DtResultados.Columns.Count).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 0, 0));
break;
case 4:
libro.Range(1, 2, 1, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 0, 0));
libro.Range(1, 3, 1, 5).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
break;
case 5:
libro.Range(1, 2, 1, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 0, 0));
libro.Range(1, 3, 1, 3).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
break;
case 6:
libro.Range(1, 4, 1, 6).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 0, 0));
libro.Range(1, 7, 1, 9).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
break;
case 7:
libro.Range(1, 3, 1, 5).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 0, 0));
libro.Range(1, 6, 1, 8).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
break;
case 8:
libro.Range(1, 6, 1, 8).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(153, 0, 0));
libro.Range(1, 9, 1, 12).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(53, 152, 220));
break;
case 9:
break;
default:
break;
}
libro.Row(1).InsertRowsAbove(4);
libro.Range(1, 2, 1, 6).Merge().Value = UsuarioActual.Empresa.Empresa;
libro.Range(2, 2, 2, 6).Merge().Value = $"Reporte de {DdlReporte.SelectedItem.Text }";
libro.Range(3, 2, 3, 6).Merge().Value = $"del {fechaInicio.ToDateTime():dd/MM/yyyy} al {fechaFin.ToDateTime():dd/MM/yyyy}";
libro.Range(2, 7, 2, 9).Merge().Value = $"Fecha:{DateTime.Now:dd/MM/yyyy}";
libro.Range(3, 7, 3, 9).Merge().Value = $"Hora:{DateTime.Now:HH:mm}";
System.IO.Stream fs = new System.IO.MemoryStream();
wb.SaveAs(fs);
fs.Position = 0;
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
using (System.IO.Stream input = fs)
{
input.CopyTo(memoryStream);
}
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", $"Visor nómina ( Reporte :{DdlReporte.SelectedValue}) "));
Response.BinaryWrite(memoryStream.ToArray());
Response.End();
}
}
protected void LnkConsultar_Click(object sender, EventArgs e)
{
using (ClsNominas nom = new ClsNominas())
{
fechaInicio = TxtRpdFechaInicio.Text.ToDateTime().ToString("yyyy/MM/dd");
fechaFin = TxtRpdFechaFin.Text.ToDateTime().ToString("yyyy/MM/dd");
nom.SATSolicitudTimbreNominaGral(0, UsuarioActual.CveEmpresa, fechaInicio, fechaFin);
if (nom.DtResultados.Rows.Count > 0)
{
DataRow drow = nom.DtResultados.Rows[0];
//LtlTimbreFiscalTotal.Text = string.Format("{0:N0}", drow["NOXml"]);
//LtlTimbreFiscalActivos.Text = string.Format("{0:N0}", drow["NOXmlActivos"]);
//LtlTimbreFiscalCancelados.Text = string.Format("{0:N0}", drow["NOXml"].ToString().ToEntero() - drow["NOXmlActivos"].ToString().ToEntero());
//LtlSobrerecibosTotal.Text = string.Format("{0:N0}", drow["NOXmlSig"]);
//LtlSobrerecibosTimbrados.Text = string.Format("{0:N0}", drow["Timbrados"]);
//LtlSobrerecibosSintimbrar.Text = string.Format("{0:N0}", drow["SinTimbrar"]);
}
nom.SATSolicitudTimbreNominaGral(DdlReporte.SelectedValue.ToString().ToEntero(), UsuarioActual.CveEmpresa, fechaInicio, fechaFin);
//GvSolicitudesIngreso.DataSource = nom.DtResultados;
//GvSolicitudesIngreso.DataBind();
clasegrid = string.Format("reporte{0}", DdlReporte.SelectedValue);
}
upDatosChec.Update();
//SATSolicitudTimbreNominaGral
}
private void cargasolicitudes()
{
using (ClsNominas nom = new ClsNominas())
{
if (nom.SolicitudesGet(-1, UsuarioActual.CveEmpresa,CveTipoSolicitud:3))
{
GVSolicitudesPendientes.DataSource = nom.DtResultados.FiltraParametros("Estatus =0");
GVSolicitudesPendientes.DataBind();
GVSolicitudesNominas.DataSource = nom.DtResultados.FiltraParametros("Estatus =1");
GVSolicitudesNominas.DataBind();
}
}
UPModalViewSolicitudes.Update();
}
protected void LnkShowSolicitudes_Click(object sender, EventArgs e)
{
cargasolicitudes();
this.RegistraScript("$('#ModalViewSolicitudes').modal();");
}
protected void LnkSolicitarSat_Click(object sender, EventArgs e)
{
int idSolicitudCFDI = 0;
int idSolicitudMetadata = 0;
int estatus = 0;
string observaciones = "";
DateTime fechaInicio = txtFechaIAdd.Text.ToDateTime();
DateTime fechaFin = txtFechaFAdd.Text.ToDateTime();
int cveUsuarioIng = UsuarioActual.CveUsuario;
int cveEmpresa = UsuarioActual.CveEmpresa;
bool Continuar = false;
using (ClsNominas nom = new ClsNominas())
{
Continuar = nom.SolicitudesAdd(idSolicitudCFDI, idSolicitudMetadata, estatus, observaciones, fechaInicio, fechaFin, cveUsuarioIng, cveEmpresa, CveTipoSolicitud:3);
}
if (Continuar)
{
StringBuilder sbResultado = new StringBuilder();
var api = new GeneralesAPI();
JToken ObjApiSolicitud = (JToken) api.GeneraSolicitud(UsuarioActual.CveEmpresa, 3);
List<string> resultSolicitud = ObjApiSolicitud.Select(token => token.Values().Aggregate((i, j) => $"{i}|{j}").Value<string>()).ToList();
List<string> resultVerificacion = new List<string>();
var ResultadoSolicitudOK = bool.Parse(resultSolicitud[0]);
var ResultadoVerificaionOK = false;
var SeVerifico = false;
if (ResultadoSolicitudOK)
{
JToken ObjApiVerificacion = (JToken) api.VerificaSolicitudesNominas(UsuarioActual.CveEmpresa, 3);
resultVerificacion = ObjApiVerificacion.Select(token => token.Values().Aggregate((i, j) => $"{i}|{j}").Value<string>()).ToList();
ResultadoVerificaionOK = bool.Parse(resultVerificacion[0]);
SeVerifico = true;
}
if (resultSolicitud.Count == 4)
{
if (ResultadoSolicitudOK)
{
sbResultado.Append($"Solicitud Generada Correctamente <br/> {resultSolicitud[2]}");
}
else
{
sbResultado.Append($"Se presento un error al generar la solicitud <br/> {resultSolicitud[2]}");
}
}
else
{
sbResultado.AppendLine("Se presento un error al generar la solicitud (API) <br/>");
}
if (SeVerifico && resultVerificacion.Count == 4)
{
if (ResultadoVerificaionOK)
{
sbResultado.Append($"Verificación ejecutada correctamente <br/> {resultSolicitud[2]}");
}
else
{
sbResultado.Append($"Se presento un error al verificar las solicitudes <br/> {resultSolicitud[2]}");
}
}
else
{
sbResultado.AppendLine("Se presento un error al verificar las solicitudes (API) <br/>");
}
Alert(sbResultado.ToString());
}
if (Continuar)
{
txtFechaIAdd.Text = "";
txtFechaFAdd.Text = "";
this.RegistraScript("$('#DModalSolicitudesNominas').modal('hide');");
cargasolicitudes();
this.Alert("se a envia la solicitud al sat, le enviaremos un correo en cuanto tengamos una respuesta", ModExtensiones.TipoMensaje.ToastInformacion);
}
}
protected void LnkverificarSolicitudes_Click(object sender, EventArgs e)
{
//var api = new GeneralesAPI();
//api.GeneraSolicitud();
//api.VerificaSolicitudesNominas();
StringBuilder sbResultado = new StringBuilder();
var api = new GeneralesAPI();
JToken ObjApiSolicitud = (JToken)api.GeneraSolicitud(UsuarioActual.CveEmpresa, 3);
List<string> resultSolicitud = ObjApiSolicitud.Select(token => token.Values().Aggregate((i, j) => $"{i}|{j}").Value<string>()).ToList();
List<string> resultVerificacion = new List<string>();
var ResultadoSolicitudOK = bool.Parse(resultSolicitud[0]);
var ResultadoVerificaionOK = false;
var SeVerifico = false;
if (ResultadoSolicitudOK)
{
JToken ObjApiVerificacion = (JToken)api.VerificaSolicitudesNominas(UsuarioActual.CveEmpresa, 3);
resultVerificacion = ObjApiVerificacion.Select(token => token.Values().Aggregate((i, j) => $"{i}|{j}").Value<string>()).ToList();
ResultadoVerificaionOK = bool.Parse(resultVerificacion[0]);
SeVerifico = true;
}
if (resultSolicitud.Count == 4)
{
if (ResultadoSolicitudOK)
{
sbResultado.Append($"Solicitud Generada Correctamente <br/> {resultSolicitud[2]}");
}
else
{
sbResultado.Append($"Se presento un error al generar la solicitud <br/> {resultSolicitud[2]}");
}
}
else
{
sbResultado.AppendLine("Se presento un error al generar la solicitud (API) <br/>");
}
if (SeVerifico && resultVerificacion.Count == 4)
{
if (ResultadoVerificaionOK)
{
sbResultado.Append($"Verificación ejecutada correctamente <br/> {resultSolicitud[2]}");
}
else
{
sbResultado.Append($"Se presento un error al verificar las solicitudes <br/> {resultSolicitud[2]}");
}
}
else
{
sbResultado.AppendLine("Se presento un error al verificar las solicitudes (API) <br/>");
}
Alert(sbResultado.ToString());
cargasolicitudes();
}
}
public class GeneralesAPI : ADSNetLibraryzI.HelpersI.ConexionesI.SIGAPII.BaseSIGAPII
{
public GeneralesAPI(string domainApi = "http://localhost:4001/", string token = "") : base(domainApi, token) { }
public object GeneraSolicitud(int CveEmpresa, int CveTipoSolicitud)
{
return getData<object>($"GeneraSolicitud/{CveEmpresa}/{CveTipoSolicitud}", null, ADSNetLibraryzI.HelpersI.ConexionesI.SIGAPII.requestMethod.GET,false);
}
public object VerificaSolicitudesNominas(int CveEmpresa, int CveTipoSolicitud)
{
return getData<object>($"VerificaSolicitudesNominas/{CveEmpresa}/{CveTipoSolicitud}", null, ADSNetLibraryzI.HelpersI.ConexionesI.SIGAPII.requestMethod.GET, false);
}
}
namespace ADSNetLibraryzI.HelpersI.ConexionesI.SIGAPII
{
public enum requestMethod
{
POST = 1,
GET = 2
}
public class BaseSIGAPII
{
private const string tituloLog = "ADSNetLibrary.Helpers.Conexiones.SIGAPI";
public string domainApi;
public string authorization;
protected string RouteController = "";
protected string FullRoute = "";
public string GetRoutbyclass() {
string classname = this.GetType().Name;
return classname.Substring(0, classname.Length - 3);
}
public string GetRoute(string path)
{
if (string.IsNullOrEmpty(FullRoute))
{
return string.Format("api/{0}/{1}", (string.IsNullOrEmpty(RouteController) ? GetRoutbyclass() : RouteController), path);
}
else
{
return string.Format("{0}{1}", FullRoute, path);
}
}
/// <summary>
/// nueva instancia de conexion para una api
/// </summary>
/// <param name="domainApi"> url de la api</param>
/// <param name="authorization"> llenar si se tiene si se desea obtner usuar campos usuario y pasword</param>
public BaseSIGAPII(string domainApi, string authorization = null, string fullRoute = null)
{
if (string.IsNullOrEmpty(domainApi))
{
domainApi = "http://localhost:4001/";//"http://jam.adssistemas.mx:4001/";//Helpers.ModVars.UrlApi;
}
this.authorization = authorization;
this.domainApi = domainApi;
this.FullRoute = fullRoute;
}
/// <summary>
/// Obtiene datos de la api asincrono.
/// </summary>
/// <typeparam name="T">Clase genérica en donde se obtiene la información del SqlDataReader.</typeparam>
/// <param name="path">ruta sin domino ejemplo "/api/usuarios/login".</param>
/// <param name="requestobject">request object.</param>
/// <returns>Lista de objetos.</returns>
public async Task<T> getDataAsync<T>(string path, object requestobject, requestMethod reqmet = requestMethod.POST, bool needauthorization = true, bool isfullpath = false) where T : class, new()
{
T objreturn = null;
using (
HttpClient client = new HttpClient())
{
// Setting Base address.
client.BaseAddress = new Uri(domainApi);
// Setting content type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Setting Authorization.
if (needauthorization) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorization); }
client.Timeout = TimeSpan.FromMinutes(15);
HttpResponseMessage response = new HttpResponseMessage();
var strjsonreq = Newtonsoft.Json.JsonConvert.SerializeObject(requestobject);
StringContent content = new StringContent(strjsonreq, Encoding.UTF8, "application/json");
string route = isfullpath ? path : GetRoute(path);
try
{
switch (reqmet)
{
case requestMethod.POST:
response = await client.PostAsync(route, content);
break;
case requestMethod.GET:
response = await client.GetAsync(route);
break;
}
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
};
objreturn = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsondata, settings);
}
else {
//ModExtensiones.GuardaLog(string.Format("{0}{1}{2}{1}StatusCode:{3}{1}{4}{1}{5}{1}", tituloLog, ModVars.NewLine, route, response.StatusCode, response.RequestMessage, strjsonreq), ModVars.ADSNetLibraryLog);
}
}
catch (Exception e) {
//ModExtensiones.GuardaLog(string.Format("{0}{1}{2}{1}{3}{1}{4}{1}", tituloLog, ModVars.NewLine, route, e, strjsonreq), ModVars.ADSNetLibraryLog);
}
}
return objreturn;
}
/// <summary>
/// Obtiene datos de la api.
/// </summary>
/// <typeparam name="T">Clase genérica en donde se obtiene la información del SqlDataReader.</typeparam>
/// <param name="path">ruta sin domino ejemplo "/api/usuarios/login".</param>
/// <param name="requestobject">request object.</param>
/// <returns>Lista de objetos.</returns>
//public T getData<T> (string path, object requestobject, requestMethod reqmet = requestMethod.POST, bool needauthorization = true, bool isfullpath = false) where T : class, new()
public T getData<T>(string path, object requestobject, requestMethod reqmet = requestMethod.POST, bool needauthorization = true, bool isfullpath = false) where T : class, new()
{
return AsyncHelper.RunSync<T>(() => getDataAsync<T>(path, requestobject, reqmet, needauthorization, isfullpath));
}
}
internal static class AsyncHelper
{
private static readonly TaskFactory _myTaskFactory = new
TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return AsyncHelper._myTaskFactory
.StartNew<Task<TResult>>(func)
.Unwrap<TResult>()
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func<Task> func)
{
AsyncHelper._myTaskFactory
.StartNew<Task>(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
}
}