Ajustes para trasmitir expedientes

This commit is contained in:
2026-03-06 12:56:41 -07:00
parent dcfd606a1c
commit c52344d7f8
13 changed files with 924 additions and 401 deletions

View File

@@ -63,6 +63,7 @@
textBoxPasswordFTP = new TextBox();
button4 = new Button();
button5 = new Button();
lblVersion = new Label();
tabControl1.SuspendLayout();
tabGeneral.SuspendLayout();
groupBox1.SuspendLayout();
@@ -89,6 +90,7 @@
//
// tabGeneral
//
tabGeneral.Controls.Add(lblVersion);
tabGeneral.Controls.Add(groupBox1);
tabGeneral.Controls.Add(groupBoxEspacio);
tabGeneral.Location = new Point(4, 26);
@@ -154,10 +156,10 @@
//
tabPage2.Controls.Add(groupBox4);
tabPage2.Controls.Add(groupBox3);
tabPage2.Location = new Point(4, 26);
tabPage2.Location = new Point(4, 24);
tabPage2.Name = "tabPage2";
tabPage2.Padding = new Padding(3);
tabPage2.Size = new Size(288, 252);
tabPage2.Size = new Size(288, 254);
tabPage2.TabIndex = 1;
tabPage2.Text = "Archivos";
tabPage2.UseVisualStyleBackColor = true;
@@ -247,10 +249,10 @@
tabPage1.Controls.Add(label6);
tabPage1.Controls.Add(txtDiminioEFC);
tabPage1.Controls.Add(groupBox5);
tabPage1.Location = new Point(4, 26);
tabPage1.Location = new Point(4, 24);
tabPage1.Name = "tabPage1";
tabPage1.Padding = new Padding(3);
tabPage1.Size = new Size(288, 252);
tabPage1.Size = new Size(288, 254);
tabPage1.TabIndex = 2;
tabPage1.Text = "Avanzados";
tabPage1.UseVisualStyleBackColor = true;
@@ -416,6 +418,16 @@
button5.UseVisualStyleBackColor = true;
button5.Click += button5_Click;
//
// lblVersion
//
lblVersion.AutoSize = true;
lblVersion.Font = new Font("Century Gothic", 9F, FontStyle.Bold, GraphicsUnit.Point, 0);
lblVersion.Location = new Point(5, 230);
lblVersion.Name = "lblVersion";
lblVersion.Size = new Size(90, 16);
lblVersion.TabIndex = 2;
lblVersion.Text = "Versión 1.0.0.0";
//
// FormConfiguracionExpediente
//
AutoScaleDimensions = new SizeF(7F, 17F);
@@ -437,6 +449,7 @@
Shown += FormConfiguracionExpediente_Shown;
tabControl1.ResumeLayout(false);
tabGeneral.ResumeLayout(false);
tabGeneral.PerformLayout();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBoxEspacio.ResumeLayout(false);
@@ -491,5 +504,6 @@
private TextBox textBoxPasswordFTP;
private Label label6;
private TextBox txtDiminioEFC;
private Label lblVersion;
}
}

View File

@@ -236,6 +236,9 @@ namespace EFCDesk.Forms
private void FormConfiguracionExpediente_Shown(object sender, EventArgs e)
{
lblVersion.Text = "Versión: " + Globales.VersionApp;
var configJson = new ConfiguracionJSON();
configJson = ConfiguracionJSON.LoadFromJson();

View File

@@ -73,6 +73,7 @@
dgwExpedientes.RowHeadersVisible = false;
dgwExpedientes.Size = new Size(559, 258);
dgwExpedientes.TabIndex = 2;
dgwExpedientes.CellClick += dgwExpedientes_CellClick;
//
// BTN_Buscar
//

View File

@@ -1,4 +1,5 @@
using EFCDesk.Classes;
using FontAwesome.Sharp;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
@@ -9,6 +10,7 @@ using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
@@ -22,12 +24,14 @@ namespace EFCDesk.Forms
public long _registros;
public long _pagina;
public long _paginas;
public string? _buscarExpediente;
}
private static SQLiteHelper _sqliteHelper = new SQLiteHelper(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "historico.db"));
private long paginacion = 1000;
private bool _clickPorCodigo = false;
private Paginacion _paginacion = new Paginacion();
private string DominioEFC = Helpers.DominioExpedienteElectronico();
public FormExpedientes()
{
@@ -38,7 +42,7 @@ namespace EFCDesk.Forms
}
private async Task CargarVistaExpedientes(int pagina, string buscarExpediente = "*")
private async Task CargarVistaExpedientes(long pagina, string buscarExpediente = "*")
{
// Limpiar la fuente de datos
dgwExpedientes.DataSource = null;
@@ -54,7 +58,26 @@ namespace EFCDesk.Forms
table.Columns.Add("Expediente", typeof(string));
table.Columns.Add("Ruta", typeof(string));
table.Columns.Add("Estatus", typeof(string));
table.Columns.Add("Fecha Registro", typeof(string));
table.Columns.Add("Fecha Registro", typeof(string)); // TaskId
table.Columns.Add("TaskId", typeof(string)); // TaskId
// Columna de Acciones con botón FontAwesome
var columnaAcciones = new DataGridViewImageColumn
{
Name = "Acciones",
HeaderText = "Acciones",
Width = 50,
ImageLayout = DataGridViewImageCellLayout.Zoom
};
// Columna de acciones
//table.Columns.Add("Acciones", typeof(Image));
// Crear el icono UNA sola vez
Bitmap iconoVer = IconChar.Eye.ToBitmap(
IconFont.Auto,
16,
Color.Black
);
foreach (var exp in listaExpedientes)
{
@@ -63,6 +86,8 @@ namespace EFCDesk.Forms
row["Ruta"] = exp.Ruta;
row["Estatus"] = exp.Estado;
row["Fecha Registro"] = exp.FechaCreacion;
row["TaskId"] = exp.TaskId;
//row["Acciones"] = iconoVer;
table.Rows.Add(row);
}
return table;
@@ -90,6 +115,10 @@ namespace EFCDesk.Forms
dgwExpedientes.Columns["Fecha Registro"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dgwExpedientes.Columns["Fecha Registro"].Width = 180;
//dgwExpedientes.Columns["Acciones"].Width = 40;
//dgwExpedientes.Columns["Acciones"].HeaderText = "";
//((DataGridViewImageColumn)dgwExpedientes.Columns["Acciones"]).ImageLayout = DataGridViewImageCellLayout.Zoom;
_ = Task.Run(() =>
{
long total = dgwExpedientes.RowCount;
@@ -98,6 +127,7 @@ namespace EFCDesk.Forms
_paginacion._registros = total;
_paginacion._pagina = pagina;
_paginacion._paginas = totalPaginas;
_paginacion._buscarExpediente = ((string.IsNullOrEmpty(buscarExpediente) || string.IsNullOrWhiteSpace(buscarExpediente))) ? "*" : buscarExpediente;
ActualizarEtiqueta();
});
@@ -109,6 +139,7 @@ namespace EFCDesk.Forms
_paginacion._registros = 0;
_paginacion._pagina = 0;
_paginacion._paginas = 0;
_paginacion._buscarExpediente = "*";
ActualizarEtiqueta();
}
@@ -116,6 +147,85 @@ namespace EFCDesk.Forms
}
private async Task<string> ConsultarEstadoTareaAsync(string taskId)
{
try
{
var apiClient = Globales.ApiClient;
string url = DominioEFC + $"/api/v1/tasks/status/?task_id={taskId}";
return await apiClient.GetAsync(url);
}
catch (Exception ex)
{
MessageBox.Show($"Error al consultar estado: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return "";
}
}
private async Task ProcesarRespuestaTareaAsync(string responseJson, string rutaExpediente)
{
if (string.IsNullOrEmpty(responseJson)) return;
var apiClient = Globales.ApiClient;
if (!apiClient.IsJson(responseJson)) return;
var data = apiClient.TryParseJson<Dictionary<string, object>>(responseJson);
if (data == null) return;
// Extraer información
string status = data.ContainsKey("status") ? data["status"]?.ToString() ?? "" : "";
bool successful = data.ContainsKey("successful") && Convert.ToBoolean(data["successful"]);
int documentsCreated = 0;
bool tieneError = true;
if (data.ContainsKey("result") && data["result"] is JsonElement resultElement)
{
var result = JsonSerializer.Deserialize<Dictionary<string, object>>(resultElement.GetRawText());
if (result != null)
{
tieneError = result.ContainsKey("tieneError") && Convert.ToBoolean(result["tieneError"]);
documentsCreated = result.ContainsKey("documents_created") ? Convert.ToInt32(result["documents_created"]) : 0;
}
}
// Determinar nuevo estado basado en respuesta
string nuevoEstado = "Error";
string mensaje = "";
if (successful && !tieneError)
{
nuevoEstado = "Procesado";
mensaje = $"Tarea completada. Documentos creados: {documentsCreated}";
}
else if (status == "PENDING" || status == "STARTED")
{
nuevoEstado = "Procesando";
mensaje = "Tarea en proceso...";
}
else
{
mensaje = $"Error en tarea: {status}";
}
// Actualizar en SQLite
_sqliteHelper.MarcarCarpetaProcesada(rutaExpediente, nuevoEstado);
// Mostrar resultado
MessageBox.Show(mensaje, "Estado de Tarea", MessageBoxButtons.OK, MessageBoxIcon.Information);
// Recargar la grilla para ver el cambio
long pagina = _paginacion._pagina; // 'long' no puede ser null, así que no se necesita el operador '??'
string buscarExpediente = _paginacion._buscarExpediente ?? "*"; // Si es null, usar "*"
if (!(pagina > 0))
{
pagina = 1; // Valor predeterminado si 'pagina' no es válido
}
// await Task.Run(() => CargarVistaExpedientes(pagina: pagina, buscarExpediente: buscarExpediente));
await CargarVistaExpedientes(pagina: pagina, buscarExpediente: buscarExpediente);
}
private async void FormExpedientes_Shown(object sender, EventArgs e)
{
edt_Pagina.Text = "1";
@@ -249,12 +359,48 @@ namespace EFCDesk.Forms
private void edt_BuscarExpediente_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
BTN_Buscar.PerformClick();
}
}
private async void dgwExpedientes_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0)
return;
var column = dgwExpedientes.Columns[e.ColumnIndex];
if (column.Name == "Acciones")
{
object? cellValueExp = dgwExpedientes.Rows[e.RowIndex].Cells["Expediente"].Value;
object? cellValueTask = dgwExpedientes.Rows[e.RowIndex].Cells["TaskId"].Value;
string? expediente = cellValueExp?.ToString();
string? taskId = cellValueTask?.ToString();
if (string.IsNullOrEmpty(taskId))
return;
//// Ejecutar trabajo pesado en segundo plano
//var resultado = await Task.Run(() =>
//{
// // Simulación de proceso pesado
// Thread.Sleep(1000);
// return $"Procesado expediente {taskId}";
//});
//MessageBox.Show(resultado);
string responseJson = await ConsultarEstadoTareaAsync(taskId);
await ProcesarRespuestaTareaAsync(responseJson, expediente);
}
}
}
}

View File

@@ -801,96 +801,96 @@ namespace EFCDesk.Forms
sqliteHelper.AgregarRegistroErrorLog(e, sNombreClase, currentMethod);
}
}
private async Task<bool> SubirArchivoApiAsync(string pedimento, string filePath)
{
// private async Task<bool> SubirArchivoApiAsync(string pedimento, string filePath)
// {
try
{
var config = ConfiguracionJSON.LoadFromJson();
string Token = SecureDataHandler.ReadDataAsPlainText() ?? "";
// try
// {
// var config = ConfiguracionJSON.LoadFromJson();
// string Token = SecureDataHandler.ReadDataAsPlainText() ?? "";
if (string.IsNullOrWhiteSpace(DominioEFC))
{
logger.LogError("No se ha configurado el dominio", null);
return false;
}
// if (string.IsNullOrWhiteSpace(DominioEFC))
// {
// logger.LogError("No se ha configurado el dominio", null);
// return false;
// }
if (!string.IsNullOrEmpty(Token))
{
using var apiClient = new ApiClient(timeout: TimeSpan.FromSeconds(10), maxRetries: 3, retryDelay: TimeSpan.FromSeconds(2));
string UrlGetPedimento = DominioEFC + ApiGetPedimento + pedimento;
string jsonResponse = await apiClient.GetAsync(url: UrlGetPedimento);
// if (!string.IsNullOrEmpty(Token))
// {
// var apiClient = Globales.ApiClient;
// string UrlGetPedimento = DominioEFC + ApiGetPedimento + pedimento;
// string jsonResponse = await apiClient.GetAsync(url: UrlGetPedimento);
if (!apiClient.IsJson(jsonResponse))
{
logger.LogError("Error en la respuesta de la peticion de pedimento al intentar subir el archivo al api:" + DominioEFC, new Exception("Error API"));
return false;
}
// if (!apiClient.IsJson(jsonResponse))
// {
// logger.LogError("Error en la respuesta de la peticion de pedimento al intentar subir el archivo al api:" + DominioEFC, new Exception("Error API"));
// return false;
// }
if (!apiClient.HasJsonData(jsonResponse))
{
logger.LogError("No se obtuvo informacion del api:" + DominioEFC, null);
return false;
}
// if (!apiClient.HasJsonData(jsonResponse))
// {
// logger.LogError("No se obtuvo informacion del api:" + DominioEFC, null);
// return false;
// }
var pedimentos = apiClient.TryParseJson<List<Pedimentos>>(jsonResponse);
// var pedimentos = apiClient.TryParseJson<List<Pedimentos>>(jsonResponse);
if (pedimentos != null)
{
// Obtener el primer pedimento de la lista
var primerPedimento = pedimentos.FirstOrDefault();
string guiOrganizacion = primerPedimento.organizacion;
string guiPedimento = primerPedimento.id;
// if (pedimentos != null)
// {
// // Obtener el primer pedimento de la lista
// var primerPedimento = pedimentos.FirstOrDefault();
// string guiOrganizacion = primerPedimento.organizacion;
// string guiPedimento = primerPedimento.id;
string UrlPostArchivo = DominioEFC + ApiPostDocuments;
// string UrlPostArchivo = DominioEFC + ApiPostDocuments;
string respuesta = await apiClient.PostMultipartAsync(
url: UrlPostArchivo,
filePath: filePath,
organizacion: guiOrganizacion,
pedimento: guiPedimento,
documentType: "9",
fuente: "1"
);
//string respuesta = await apiClient.PostMultipartAsync(
// url: UrlPostArchivo,
// filePath: filePath,
// organizacion: guiOrganizacion,
// pedimento: guiPedimento,
// documentType: "9",
// fuente: "1"
// );
if (!apiClient.IsJson(jsonResponse))
{
return false;
}
if (!apiClient.HasJsonData(jsonResponse))
{
return false;
}
// if (!apiClient.IsJson(jsonResponse))
// {
// return false;
// }
// if (!apiClient.HasJsonData(jsonResponse))
// {
// return false;
// }
var documentos = apiClient.TryParseJson<List<Documentos>>(jsonResponse);
if (documentos == null)
{
return false;
}
}
else
{
logger.LogInfo("No se encontro el pedimento");
return false;
}
// var documentos = apiClient.TryParseJson<List<Documentos>>(jsonResponse);
// if (documentos == null)
// {
// return false;
// }
// }
// else
// {
// logger.LogInfo("No se encontro el pedimento");
// return false;
// }
}
else
{
logger.LogError("Error en la configuracion del Id de Usuario:" + DominioEFC, new Exception("Error Id Usuario"));
return false;
}
}
catch (Exception ex)
{
logger.LogError("Error inesperado SubirArchivoApiAsync", ex);
return false;
}
// }
// else
// {
// logger.LogError("Error en la configuracion del Id de Usuario:" + DominioEFC, new Exception("Error Id Usuario"));
// return false;
// }
// }
// catch (Exception ex)
// {
// logger.LogError("Error inesperado SubirArchivoApiAsync", ex);
// return false;
// }
return true;
}
// return true;
// }
private void RegistrarArchivoEnAPI(string file)
{
try