Files
EFC-DESK-V2/Forms/Login.cs
2026-02-09 10:55:45 -07:00

322 lines
12 KiB
C#

using EFCDesk.Classes;
using EFCDesk.Forms;
using System.Data.SQLite;
using System.Xml;
using System.Xml.Linq;
using static EFCDesk.Program;
namespace EFCDesk
{
public partial class Login : Form
{
private bool ExisteConfiguracionExpediente()
{
using (var connection = sqliteHelper.GetConnection())
{
connection.Open();
// Verificar si hay registros en la tabla ArchivosProcesados
string checkQuery = "SELECT COUNT(1) FROM Configuracion;";
int registrosExistentes;
using (var command = new SQLiteCommand(checkQuery, connection))
{
registrosExistentes = Convert.ToInt32(command.ExecuteScalar());
}
// Si hay registros, no realizar el escaneo inicial
if (registrosExistentes == 0)
{
return false;
}
}
return true;
}
private void VistaConfiguracionExpediente()
{
//FormCargarInformacion info = new FormCargarInformacion();
//info.Show();
MessageBox.Show("Debe capturar la configuración inicial para el envío de los archivos a expediente electrónico", "Configuración", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
FormConfiguracionExpediente configExp = new FormConfiguracionExpediente();
configExp.ShowDialog();
try
{
configExp.Dispose();
this.Visible = true;
}
catch (Exception ex) { }
}
private static SQLiteHelper sqliteHelper = new SQLiteHelper(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "historico.db"));
public Login()
{
InitializeComponent();
}
private void buttonOpciones_Click(object sender, EventArgs e)
{
FormConfiguracionJSON configuracion = new FormConfiguracionJSON();
configuracion.ShowDialog();
}
private async void buttonInicioSesion_Click(object sender, EventArgs e)
{
//var config = ConfiguracionJSON.LoadFromJson();
//Cursor.Current = Cursors.WaitCursor;
//string user = textBoxUsuario.Text.Trim();
//string pass = textBoxContrasenia.Text.Trim();
//if (user == "")
//{
// MessageBox.Show("Debe ingresar el usuario");
// textBoxUsuario.Focus();
// return;
//}
//if (pass == "")
//{
// MessageBox.Show("Debe ingresar la contraseña");
// textBoxContrasenia.Focus();
// return;
//}
//if ((user == "admin") && (pass == "teamweb"))
//{
// //frmAdmin configuracion = new frmAdmin();
// //configuracion.ShowDialog();
//}
//else
//{
// try
// {
// string crypUser = General.CodificarBase64(user);
// string crypPass = General.CodificarBase64(pass);
// string cadena = crypUser + "|" + crypPass;
// string liga = config.DominioExp + "/api/auth/" + cadena;
// dynamic root = config.Consulta(liga);
// if (root is XmlElement)
// {
// string id = "";
// string mensaje = "";
// XmlNodeList nodes = root.SelectNodes("/xml/item");
// foreach (XmlNode node in nodes)
// {
// id = node["login"].InnerText;
// mensaje = node["mensaje"].InnerText;
// }
// if (id != "0")
// {
// //this.Hide();
// /**/
// /*
// SplashScreenEspera Espera = new SplashScreenEspera();
// Espera.ShowDialog();
// */
// /*
// Globales.DirRootExpediente = MyClass.configuracion("folder");
// if (!Directory.Exists(Globales.DirRootExpediente))
// {
// string Folder = "C:" + Path.DirectorySeparatorChar + "EFC";
// MyClass.configuracion("folder", Folder);
// Globales.DirRootExpediente = Folder;
// Directory.CreateDirectory(Globales.DirRootExpediente);
// }
// */
// /*actualizar config*/
// config.UsuarioExp = user;
// config.PasswordExp = pass;
// int.TryParse(id, out int idInt);
// config.idUsuarioExp = idInt;
// config.SaveToJson();
// this.Hide();
// FormCargarInformacion info = new FormCargarInformacion();
// info.Show();
// //Application.Run(new frmMain());
// using (var connection = sqliteHelper.GetConnection())
// {
// connection.Open();
// // Verificar si hay registros en la tabla ArchivosProcesados
// string checkQuery = "SELECT COUNT(1) FROM Configuracion;";
// int registrosExistentes;
// using (var command = new SQLiteCommand(checkQuery, connection))
// {
// registrosExistentes = Convert.ToInt32(command.ExecuteScalar());
// }
// // Si hay registros, no realizar el escaneo inicial
// if (registrosExistentes == 0)
// {
// FormConfiguracionExpediente configExp = new FormConfiguracionExpediente();
// configExp.Show();
// }
// else
// {
// FormMain Main = new FormMain();
// Main.Show();
// }
// }
// }
// else
// {
// MessageBox.Show(mensaje);
// return;
// }
// }
// else if (root is Exception)
// {
// MessageBox.Show(root.ToString());
// return;
// }
// else
// {
// MessageBox.Show("Error: No se hizo el login correctamente. Contacte a su proveedor");
// return;
// }
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.ToString());
// }
//}
//cursor.current = cursors.default;
if (!ExisteConfiguracionExpediente())
{
VistaConfiguracionExpediente();
return;
}
string user = txtUsuario.Text.Trim();
string pass = textBoxContrasenia.Text.Trim();
bool EsvalidoDatos = Utils.Util.StringsValidos(user, pass);
if(!EsvalidoDatos)
{
MessageBox.Show("Debe ingresar el usuario y contraseña", "Información", MessageBoxButtons.OK);
return;
}
var configJson = ConfiguracionJSON.LoadFromJson();
Cursor.Current = Cursors.WaitCursor;
try
{
configJson.UsuarioExp = user;
configJson.PasswordExp = pass;
if (Properties.Settings.Default.urlEFC.ToString() == "")
{
MessageBox.Show("No se ha configurado el dominio de expediente electronico", "Información", MessageBoxButtons.OK);
return;
}
if (configJson.FolderExpediente == null)
{
MessageBox.Show("No se ha configurado la ruta de expediente(s)", "Información", MessageBoxButtons.OK);
return;
}
bool Esvalido = Utils.Util.StringsValidos(configJson.UsuarioExp, configJson.PasswordExp);
if (!Esvalido)
{
MessageBox.Show("No se ha configurado el usuario o contraseña de expediente electronico", "Información", MessageBoxButtons.OK);
return;
}
else
{
textBoxContrasenia.Text = configJson.PasswordExp ?? String.Empty;
}
if (string.IsNullOrWhiteSpace(textBoxContrasenia.Text))
{
MessageBox.Show("Ingresa el Id de usuario", "Información", MessageBoxButtons.OK);
textBoxContrasenia.Focus();
return;
}
configJson.SaveToJson();
bool EsLoginValido = await Utils.Util.Login(txtUsuario.Text, textBoxContrasenia.Text);
if (!EsLoginValido)
{
MessageBox.Show("No se pudo hacer login.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//string token = textBoxContrasenia.Text;
//using var apiClient = new ApiClient(timeout: TimeSpan.FromSeconds(10), maxRetries: 3, retryDelay: TimeSpan.FromSeconds(2));
//string response = await apiClient.GetAsync(url: config.DominioExp+ "/api/v1/customs/pedimentos/", token);
Cursor.Current = Cursors.Default;
//SecureDataHandler.SaveData(textBoxContrasenia.Text);
//textBoxContrasenia.Text = string.Empty;
this.Hide();
FormMain Main = new FormMain(Globales.gMonitor);
Main.Show();
}
catch (ApiException ex)
{
MessageBox.Show($"API respondió con error: {ex.Message} (Código {ex.StatusCode})");
}
catch (Exception ex)
{
MessageBox.Show($"Error en la petición: {ex.Message}");
}
Cursor.Current = Cursors.Default;
}
private void textBoxContrasenia_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//buttonInicioSesion_Click(this, new EventArgs());
buttonInicioSesion.PerformClick();
}
}
private void Login_Shown(object sender, EventArgs e)
{
if (!ExisteConfiguracionExpediente())
{
VistaConfiguracionExpediente();
}
}
private void textBoxContrasenia_TextChanged(object sender, EventArgs e)
{
}
}
}