Files
SIG/OI/DocumentoDetalle.aspx.cs
2020-07-22 19:47:27 -07:00

363 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Extensiones;
using System.Data;
using System.IO;
using System.Text;
public partial class OI_DocumentoDetalle : ClsPaginas
{
private int CveDocumento
{
get
{
return ViewState["CveDocumento"].ToString().ToEntero();
}
set
{
ViewState["CveDocumento"] = value;
}
}
private string ErrorMensaje
{
get
{
return ViewState["ErrorMensaje"].ToString();
}
set
{
ViewState["ErrorMensaje"] = value;
}
}
private string ArchivoAdjuntoNombre
{
get
{
return ViewState["ArchivoAdjuntoNombre"].ToString();
}
set
{
ViewState["ArchivoAdjuntoNombre"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Cargar();
}
}
#region "CARGAS"
private void CargarCveDocumento()
{
string CveDocumentoAux = Page.Request["CveDocumento"];
if (CveDocumentoAux != null)
{
this.CveDocumento = CveDocumentoAux.ToEntero();
}
else
{
this.CveDocumento = -1;
}
}
private void CargarUsuarios()
{
GvUsuarios.DataSource = get_GlobalDTUsuarios(CveEmpresa: UsuarioActual.CveEmpresa);
GvUsuarios.DataBind();
}
private void CargarSubCategoria()
{
ClsOIEventos ObjOI = new ClsOIEventos();
if (ObjOI.GetDocumentoSubCategoria())
{
DdlSubCategoria.DataSource = ObjOI.DtResultados;
DdlSubCategoria.DataBind();
}
ObjOI.Dispose();
}
private void CargarResponsable()
{
TxtResponsable.Text = UsuarioActual.Nombre;
}
private void CargarDocumentoYaExistente()
{
ClsOIEventos ObjOI = new ClsOIEventos();
if (ObjOI.GetDocumento(this.CveDocumento, UsuarioActual.CveEmpresa))
{
if (ObjOI.DtResultados.Rows.Count > 0)
{
DataRow Documento = ObjOI.DtResultados.Rows[0];
TxtDescripcion.Text = Documento["Descripcion"].ToString();
DdlSubCategoria.SelectedValue = Documento["CveSubCategoria"].ToString();
DdlEstatus.SelectedValue = Documento["CveEstatus"].ToString();
TxtVersion.Text = Documento["Version"].ToString();
TxtResponsable.Text = Documento["Responsable"].ToString();
TxtObs.InnerText = Documento["Observacion"].ToString();
ArchivoAdjuntoNombre = Documento["ArchivoFisico"].ToString();
string[] ArchivoAux = Documento["ArchivoFisico"].ToString().Split('_');
string ArchivoAdjunto = ArchivoAux[1];
LkbDescargarArchivo.Text = ArchivoAdjunto;
DivDescargarArchivo.Visible = true;
}
}
ObjOI.Dispose();
}
private void CargarUsuariosAutorizo()
{
ClsOIEventos ObjOI = new ClsOIEventos();
if (ObjOI.GetDocumentoAutorizacion(this.CveDocumento))
{
DataTable UsuariosAutorizo = ObjOI.DtResultados;
GridViewRowCollection UsuariosRowCollection = GvUsuarios.Rows;
foreach (GridViewRow UsuarioRow in UsuariosRowCollection)
{
int CveUsuarioRow = UsuarioRow.DataKey("CveUsuario").ToEntero();
UsuarioRow.FCCheckBox("ChkUnir").Checked = UsuariosAutorizo.COUNT("CveUsuario", string.Format("CveUsuario = {0}", CveUsuarioRow)) > 0;
}
}
ObjOI.Dispose();
}
private void ConfiguracionActualizar()
{
LkbGuardar.Text = "Actualizar";
}
private void Cargar()
{
CargarUsuarios();
CargarSubCategoria();
CargarResponsable();
CargarCveDocumento();
if (this.CveDocumento > 0)
{
CargarDocumentoYaExistente();
CargarUsuariosAutorizo();
ConfiguracionActualizar();
}
}
#endregion
#region "GENERAR DOCUMENTO"
protected void LblGuardar_Click(object sender, EventArgs e)
{
ClsOIEventos ObjOI = new ClsOIEventos();
ObjOI.IniciaTransacSQL();
bool TieneError = false;
//Esta variable es requerida más adelante
int CveDocumento = 0;
string RutaArchivo = "-1";
string CorreosNotificacion = "";
byte[] ArchivoNotifiacion = null;
CveDocumento = GuardarDocumento(ref ObjOI, ref TieneError);//Se crea el Documento
if (!TieneError) { RutaArchivo = AsignarArchivoAlDocumento(CveDocumento, ref ObjOI, ref TieneError); }//Se guarda el archivo fisico y se asigna al Documento generado
if (!TieneError) { CorreosNotificacion = GuardarUsuariosQueAutorizan(CveDocumento, RutaArchivo, ref ObjOI, ref TieneError); }//asignamos a los usuarios que participaran en aprovar este documento
if (!TieneError)
{
ArchivoNotifiacion = GenerarArchivoByte(RutaArchivo);
NotificarPorCorreo(CorreosNotificacion, RutaArchivo, ArchivoNotifiacion);
}
//Gestión de errores y resultados
if (!TieneError)
{
ObjOI.Commit();
Alert("Documento guardado correctamente");
Response.Redirect(string.Format("/OI/DocumentoDetalle.aspx?CveDocumento={0}", CveDocumento));
}
else
{
ObjOI.RollBack();
Alert(this.ErrorMensaje, ModExtensiones.TipoMensaje.MsgError);
UpCliente.Update();
}
ObjOI.Dispose();
}
private int GuardarDocumento(ref ClsOIEventos ObjOI, ref bool TieneError)
{
int CveDocumentoPadre = this.CveDocumento > 0 ? this.CveDocumento : -1; //Asociamos el nuevo insert con un CveDocumento ya generado en caso de ser una nueva versión del documento
int CveDocumento = ObjOI.AddDocumento(DdlSubCategoria.SelectedValue.ToEntero(), TxtDescripcion.Text, TxtObs.InnerText, TxtVersion.Text, DdlEstatus.SelectedValue.ToEntero(),
"", TxtResponsable.Text, CveDocumentoPadre, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa);
if (!(CveDocumento > 0))
{
TieneError = true;
this.ErrorMensaje = "Hubo un error al guardar el Documento";
}
return CveDocumento;
}
private string AsignarArchivoAlDocumento(int CveDocumento, ref ClsOIEventos ObjOI, ref bool TieneError)
{
string RutaArchivo = GuardarArchivo(CveDocumento);
if (RutaArchivo != "-1")
{
if (!ObjOI.UpdateDocumento(CveDocumento, -1, "-1", "-1", "-1", -1, RutaArchivo, "-1", ModExtensiones.MinFecha, -1, -1, -1))
{
TieneError = true;
this.ErrorMensaje = "Hubo un error al asignar el archivo";
}
}
else if (RutaArchivo == "Error")
{
TieneError = true;
this.ErrorMensaje = "Hubo un error al guardar el archivo";
}
return RutaArchivo;
}
private string GuardarUsuariosQueAutorizan(int CveDocumento, string RutaArchivo, ref ClsOIEventos ObjOI, ref bool TieneError)
{
StringBuilder CorreosReturn = new StringBuilder("");
GridViewRowCollection GridUsuarios = GvUsuarios.Rows;
foreach (GridViewRow GvRow in GridUsuarios)
{
if (GvRow.FCCheckBox("ChkUnir").Checked && !TieneError)
{
int CveUsuario = GvRow.DataKey("CveUsuario").ToEntero();
if (!ObjOI.AddDocumentoAutorizacion(CveDocumento, CveUsuario, RutaArchivo))
{
TieneError = true;
this.ErrorMensaje = "Hubo un error al asignar los usuarios a este documento";
break;
}
else
{
CorreosReturn.AppendFormat("{0},", GvRow.DataKey("Correo"));
}
}
}
return CorreosReturn.ToString();
}
#endregion
#region "ARCHIVO ADJUNTO"
private string GuardarArchivo(int CveDocumento)
{
string RutaArchivo = "-1";
List<Archivo> Filesgral = TxtDocumentoFile.getfiles().Archivos;
if (TxtDocumentoFile.Text != "[]")
{
foreach (Archivo fileItem in Filesgral)
{
try
{
string Version = TxtVersion.Text;
string NombreArchivo = fileItem.filenameO;
//Preparamos la ruta donde moveremos el archivo cargado
string NombreArchivoGuardado = string.Format("{0}_{1}", CveDocumento, NombreArchivo);
string RutaDestino = UsuarioActual.Empresa.Ruta + @"DocumentosRepo\" + NombreArchivoGuardado;
//Si no existe la carpeta donde se guardan se crea
if (!Directory.Exists(UsuarioActual.Empresa.Ruta + @"\DocumentosRepo"))
{
Directory.CreateDirectory(UsuarioActual.Empresa.Ruta + @"\DocumentosRepo");
}
//Movemos el archivo de la carpeta temporal hacia la carpeta de la empresa
System.IO.File.Move(fileItem.FileUrl, RutaDestino);
RutaArchivo = NombreArchivoGuardado;
}
catch (Exception e)
{
Alert(e.Message);
RutaArchivo = "Error";
}
}
}
return RutaArchivo;
}
protected void LkbDescargarArchivo_Click(object sender, EventArgs e)
{
string Ruta = string.Format("{0}Empresas/{1}/DocumentosRepo/{2}", ModExtensiones.DirectorioBaseEmpresas, UsuarioActual.CveEmpresa, ArchivoAdjuntoNombre);
byte[] archivoBytes = File.ReadAllBytes(Ruta);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", ArchivoAdjuntoNombre));
HttpContext.Current.Response.AddHeader("Content-Length", archivoBytes.Length.ToString());
HttpContext.Current.Response.OutputStream.Write(archivoBytes, 0, archivoBytes.Length);
HttpContext.Current.Response.End();
}
#endregion
#region "NOTIFICACIONES CORREO"
private void NotificarPorCorreo(string Para, string NombreArchivo, byte[] Adjunto)
{
string Descripcion = TxtDescripcion.Text;
string Asunto = "Se le ha agregado como participante en el desarrollo de un Documento";
string a = string.Format("{0} -- {1} --- {2}", Descripcion, Para, "");
a.GuardaLog();
ClsSisMail Mail = new ClsSisMail();
if (Adjunto != null)
{
List<ClsSisMail.ArchivoMail> LSRutasMail = new List<ClsSisMail.ArchivoMail>();
ClsSisMail.ArchivoMail itemMail = new ClsSisMail.ArchivoMail();
{
var withBlock = itemMail;
itemMail.ArchivoBinario = Adjunto;
itemMail.NombreArchivo = NombreArchivo;
}
LSRutasMail.Add(itemMail);
Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Descripcion, "", LSRutasMail);
Mail = null/* TODO Change to default(_) if this is not a reference type */;
}
else
{
Mail.SendMail(ClsPaginas.EmpresaNotificaciones, Para, Asunto, Descripcion, "");
Mail = null/* TODO Change to default(_) if this is not a reference type */;
}
}
private byte[] GenerarArchivoByte(string NombreArchivo)
{
string ArchivoEnviar = string.Format(@"{0}DocumentosRepo\{1}", UsuarioActual.Empresa.Ruta, NombreArchivo);
if (File.Exists(ArchivoEnviar))
{
System.IO.FileStream fs = System.IO.File.Open(ArchivoEnviar, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] buff = new byte[fs.Length + 1];
if (fs.Length > 0)
{
fs.Read(buff, 0, (fs.Length.ToString().ToEntero() - 1));
fs.Close();
}
return buff;
}
return new byte[] { };
}
#endregion
}