using Extensiones; using iTextSharp.text.pdf; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; using static Extensiones.ModExtensiones; using Modelos; using System.Text.RegularExpressions; using iTextSharp.text.pdf.parser; using Profact.TimbraCFDI40; using Ionic.Zip; public partial class Nomina_Nomina2 : ClsPaginas { #region Propiedades private int FilaConceptos { get { return 5; } } private DataTable DtNomOrden { get { if (ViewState["DtNomOrden"] == null) { return null; } else { return (DataTable)ViewState["DtNomOrden"]; } } set { ViewState["DtNomOrden"] = value; } } private DataTable DtNomOcultarMostrar { get { if (ViewState["DtNomOcultarMostrar"] == null) { return null; } else { return (DataTable)ViewState["DtNomOcultarMostrar"]; } } set { ViewState["DtNomOcultarMostrar"] = value; } } private DataTable DtNomPersonalizarxls { get { if (ViewState["DtNomPersonalizarxls"] == null) { return null; } else { return (DataTable)ViewState["DtNomPersonalizarxls"]; } } set { ViewState["DtNomPersonalizarxls"] = value; } } private DateTime FechaInicioPeriodo { get { if (ViewState["FechaInicioPeriodo"] == null) { return NowADS(); } else { return (DateTime)ViewState["FechaInicioPeriodo"]; } } set { ViewState["FechaInicioPeriodo"] = value; } } private DateTime FechaFinPeriodo { get { if (ViewState["FechaFinPeriodo"] == null) { return NowADS().AddDays(1); } else { return (DateTime)ViewState["FechaFinPeriodo"]; } } set { ViewState["FechaFinPeriodo"] = value; } } private DataTable dtNomConceptos { get { if (ViewState["dtNomConceptos"] == null) { return null; } else { return (DataTable)ViewState["dtNomConceptos"]; } } set { ViewState["dtNomConceptos"] = value; } } private DataTable dtPeriodos { get { if (ViewState["dtPeriodos"] == null) { return null; } else { return (DataTable)ViewState["dtPeriodos"]; } } set { ViewState["dtPeriodos"] = value; } } private DataTable dtConceptos { get { if (ViewState["dtConceptos"] == null) { return null; } else { return (DataTable)ViewState["dtConceptos"]; } } set { ViewState["dtConceptos"] = value; } } private DataTable dtempleadosConceptos { get { if (ViewState["dtempleadosConceptos"] == null) { return null; } else { return (DataTable)ViewState["dtempleadosConceptos"]; } } set { ViewState["dtempleadosConceptos"] = value; } } private DataTable dtempleados { get { if (ViewState["dtempleados"] == null) { return null; } else { return (DataTable)ViewState["dtempleados"]; } } set { ViewState["dtempleados"] = value; } } #region "Empleados Conceptos" private DataTable dtPerEmpleados { get { if (ViewState["dtPerEmpleados"] == null) { return null; } else { return (DataTable)ViewState["dtPerEmpleados"]; } } set { ViewState["dtPerEmpleados"] = value; } } private DataTable dtPerEmpleadosConceptos { get { if (ViewState["dtPerEmpleadosConceptos"] == null) { return null; } else { return (DataTable)ViewState["dtPerEmpleadosConceptos"]; } } set { ViewState["dtPerEmpleadosConceptos"] = value; } } private DataTable dtPerConceptos { get { if (ViewState["dtPerConceptos"] == null) { return null; } else { return (DataTable)ViewState["dtPerConceptos"]; } } set { ViewState["dtPerConceptos"] = value; } } private DataTable dtPerPeriodo { get { if (ViewState["dtPerPeriodo"] == null) { return null; } else { return (DataTable)ViewState["dtPerPeriodo"]; } } set { ViewState["dtPerPeriodo"] = value; } } #endregion private DataTable DtSuaProcesado { get { if (ViewState["DtSuaProcesado"] == null) { return null; } else { return (DataTable)ViewState["DtSuaProcesado"]; } } set { ViewState["DtSuaProcesado"] = value; } } protected bool enviarCorreoEnTimbrado { get { if (ViewState["enviarCorreoEnTimbrado"] == null) { return false; } else { return (bool)ViewState["enviarCorreoEnTimbrado"]; } } set { ViewState["enviarCorreoEnTimbrado"] = value; } } protected bool PermisoCancelarEmitido { get { if (ViewState["PermisoCancelarEmitido"] == null) { return false; } else { return (bool)ViewState["PermisoCancelarEmitido"]; } } set { ViewState["PermisoCancelarEmitido"] = value; } } protected bool PermisoAutorizar { get { if (ViewState["PermisoAutorizar"] == null) { return false; } else { return (bool)ViewState["PermisoAutorizar"]; } } set { ViewState["PermisoAutorizar"] = value; } } protected bool PermisoEmitir { get { if (ViewState["PermisoEmitir"] == null) { return false; } else { return (bool)ViewState["PermisoEmitir"]; } } set { ViewState["PermisoEmitir"] = value; } } protected int CveTipoTrabajador { get { if (ViewState["CveTipoTrabajador"] == null) { return 0; } else { return ViewState["CveTipoTrabajador"].ToString().ToEntero(); } } set { ViewState["CveTipoTrabajador"] = value; } } protected int CvePeriodoSeleccionado { get { if (ViewState["CvePeriodoSeleccionado"] == null) { return 0; } else { return ViewState["CvePeriodoSeleccionado"].ToString().ToEntero(); } } set { ViewState["CvePeriodoSeleccionado"] = value; } } protected int CcveMovtoPermanente { get { if (ViewState["CcveMovtoPermanente"] == null) { return 0; } else { return ViewState["CcveMovtoPermanente"].ToString().ToEntero(); } } set { ViewState["CcveMovtoPermanente"] = value; } } protected int FiltCveProyecto { get { if (ViewState["FiltCveProyecto"] == null) { return 0; } else { return ViewState["FiltCveProyecto"].ToString().ToEntero(); } } set { ViewState["FiltCveProyecto"] = value; } } protected int FiltCveSubProyecto { get { if (ViewState["FiltCveSubProyecto"] == null) { return 0; } else { return ViewState["FiltCveSubProyecto"].ToString().ToEntero(); } } set { ViewState["FiltCveSubProyecto"] = value; } } protected int FiltCveTurno { get { if (ViewState["FiltCveTurno"] == null) { return 0; } else { return ViewState["FiltCveTurno"].ToString().ToEntero(); } } set { ViewState["FiltCveTurno"] = value; } } protected int FiltCvePeriodo { get { if (ViewState["FiltCvePeriodo"] == null) { return 0; } else { return ViewState["FiltCvePeriodo"].ToString().ToEntero(); } } set { ViewState["FiltCvePeriodo"] = value; } } protected int FiltAgrupador { get { if (ViewState["FiltAgrupador"] == null) { return 0; } else { return ViewState["FiltAgrupador"].ToString().ToEntero(); } } set { ViewState["FiltAgrupador"] = value; } } //private HybridDictionary EmpresasFuncionalidades //{ // get // { // if (ViewState["EmpresasFuncionalidades"] == null) { return null; } // else { return (HybridDictionary)ViewState["EmpresasFuncionalidades"]; } // } // set { ViewState["EmpresasFuncionalidades"] = value; } //} //private HybridDictionary EmpresasFuncionalidadesnoV4 //{ // get // { // if (ViewState["EmpresasFuncionalidadesnoV4"] == null) { return null; } // else { return (HybridDictionary)ViewState["EmpresasFuncionalidadesnoV4"]; } // } // set { ViewState["EmpresasFuncionalidadesnoV4"] = value; } //} #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { cargarutaempresa(); { DtNomOrden = new DataTable(); DtNomOrden.Columns.Add("Columna"); DtNomOrden.Columns.Add("Tipo"); DtNomOrden.Columns.Add("TipoDB"); DtNomOrden.Columns.Add("ColumnaDB"); { DataRow drorden = DtNomOrden.NewRow(); drorden["Columna"] = "Código"; drorden["Tipo"] = "Ascendente"; drorden["ColumnaDB"] = "Codigo"; drorden["TipoDB"] = "ASC"; DtNomOrden.Rows.Add(drorden); } DtNomOcultarMostrar = new DataTable(); DtNomOcultarMostrar.Columns.Add("Columna"); DtNomOcultarMostrar.Columns.Add("Tipo"); DtNomOcultarMostrar.Columns.Add("TipoDB"); DtNomOcultarMostrar.Columns.Add("ColumnaDB"); DtNomPersonalizarxls = new DataTable(); DtNomPersonalizarxls.Columns.Add("Columna"); DtNomPersonalizarxls.Columns.Add("Tipo"); DtNomPersonalizarxls.Columns.Add("TipoDB"); DtNomPersonalizarxls.Columns.Add("ColumnaDB"); } TxtEjercicioFiltroVacaciones.Text = "2023"; TxtejerciciotablasSubsidio.Text = DateTime.Now.Year.ToString(); enviarCorreoEnTimbrado = (UsuarioActual.CveEmpresa == 141 ? true : true); LnkCargaNetos.Visible = (UsuarioActual.Empresa.Funcionalidad(267) == "1") || (UsuarioActual.CveRol == 1); if (UsuarioActual.CveEmpresa == 141) { ddlfiniquito.SelectedValueExist("2"); } using (ClsRH objrh = new ClsRH()) { if (objrh.TiposTrabajadorGet(-1, UsuarioActual.CveEmpresa)) { DataTable dt = objrh.DtResultados; DataRow drow = dt.NewRow(); drow["CveTipoTrabajador"] = "-1"; drow["TipoTrabajadorB"] = "Todos"; dt.Rows.InsertAt(drow, 0); dt.AcceptChanges(); DdlTipoTrabajador.DataSource = dt; DdlTipoTrabajador.DataBind(); DdlTipoTrabajador.SelectedValueExist("-1"); } } DataTable dtperinc = null; using (ClsNominas objnom = new ClsNominas()) { objnom.GetNominasSinTimbrar(-1, UsuarioActual.CveEmpresa); if (objnom.DTSetResultados.Tables.Count > 0) { GVNominaPendiente.DataSource = objnom.DTSetResultados.Tables[0]; GVNominaPendiente.DataBind(); } if (GVNominaPendiente.Rows.Count > 0) { RegistraScript("$('#ModalNominaPendiente').modal();"); } if (objnom.GetConceptos(UsuarioActual.CveEmpresa)) { dtNomConceptos = objnom.DtResultados; } if (objnom.PersonalIncapacidadCatalogos()) { dtperinc = objnom.DtResultados; } } DmodalCancelartimbre.Visible = (UsuarioActual.CveUsuario == 100); //LnkOpenCancelarTimbre.Visible = (UsuarioActual.CveUsuario == 100); LnkVerCalculoISR.Visible = (UsuarioActual.CveUsuario == 100 || UsuarioActual.CveEmpresa == 119); TxtPeriodo.Text = $"{NowADS():yyyyMM}"; CargarCentrosDeCosto(DdlProyecto, DdlSubProyecto, LblProyecto, LblSubProyeccto); CargarCentrosDeCosto(DdlPRProyecto, DdlPRSubProyecto, LblPRProyecto, LblPRSubProyeccto); CargarCentrosDeCosto(DdlAsisProyecto, DdlAsisSubProyecto, LblAsisProyecto, LblAsisSubProyecto); divddlproyeto.Visible = DdlProyecto.Visible; divPRddlproyeto.Visible = DdlPRProyecto.Visible; PnlProyecto.Visible = DdlProyecto.Visible; if (PnlProyecto.Visible) { PnlSubProyecto.CssClass = "col-md-6"; } cargaEjercicios(); CargaTiposPeriodo(); cargaPeriodos(); DdlTurno.DataSource = get_GlobalDTTurno(UsuarioActual.CveEmpresa); DdlTurno.DataBind(); DdlMetodoPago.DataSource = GlobalDTVtaMetodoPago; DdlMetodoPago.DataBind(); DdlBanco.DataSource = GlobalDTNomSatBancos; DdlBanco.DataBind(); //Permisos if (UsuarioActual.TienePermisoProceso(82)) { PermisoAutorizar = true; } else { PermisoAutorizar = false; } if (UsuarioActual.TienePermisoProceso(83)) { PermisoEmitir = true; PermisoCancelarEmitido = true; } else { PermisoEmitir = false; PermisoCancelarEmitido = false; } using (ClsRH onom = new ClsRH()) { if (onom.GetRegistrosPatronales(-1, UsuarioActual.CveEmpresa, 1)) { DdlRegistroPatronal.DataSource = onom.DtResultados; DdlRegistroPatronal.DataBind(); } } if (dtperinc != null) { DdlSRINCcveTipodeIncidencia.DataSource = dtperinc.FiltraParametros("Tipo = -1 OR Tipo =1 "); DdlSRINCcveRamoSeguro.DataSource = dtperinc.FiltraParametros("Tipo = -1 OR Tipo =2 "); DdlSRINCcveTipoRiesgo.DataSource = dtperinc.FiltraParametros("Tipo = -1 OR Tipo =3 "); DdlSRINCcveSecuelaConsecuencia.DataSource = dtperinc.FiltraParametros("Tipo = -1 OR Tipo =4 "); DdlSRINCcveControlIncapacidad.DataSource = dtperinc.FiltraParametros("Tipo = -1 OR Tipo =5 "); DdlSRINCcveTipodeIncidencia.DataBind(); DdlSRINCcveRamoSeguro.DataBind(); DdlSRINCcveTipoRiesgo.DataBind(); DdlSRINCcveSecuelaConsecuencia.DataBind(); DdlSRINCcveControlIncapacidad.DataBind(); } } if (GvVacaciones.Rows.Count > 0) { foreach (GridViewRow item in GvVacaciones.Rows) { LinkButton lnkDescargaFormato = item.FCLinkButton("ImgDescargaFormato"); LinkButton lnkDescargaAutorizacion = item.FCLinkButton("ImgDescargaAutorizacion"); if (lnkDescargaAutorizacion != null && lnkDescargaAutorizacion.Visible) { ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkDescargaAutorizacion); } if (lnkDescargaFormato != null && lnkDescargaFormato.Visible) { ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkDescargaFormato); } } } } private void cargarutaempresa() { string rutaCBBDir = String.Format("{0}CBB\\Nomina\\", UsuarioActual.Empresa.Ruta); if (!Directory.Exists(rutaCBBDir)) { Directory.CreateDirectory(rutaCBBDir); } } #region Filtros private void cargaEjercicios() { int EjercicioActual = UsuarioActual.Empresa.EjercicioActual; if (EjercicioActual == 0) { EjercicioActual = NowADS().Year; } DataTable dtejercicio = null; using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetEjercicios(UsuarioActual.CveEmpresa)) { dtejercicio = objnom.DtResultados; } } DdlEjercicios.DataSource = dtejercicio; DdlEjerciciosCM.DataSource = dtejercicio; DdlEjercicioCM.DataSource = dtejercicio; DdlEjercicios.DataBind(); DdlEjerciciosCM.DataBind(); DdlEjercicioCM.DataBind(); ListItem litem = null; if ((dtejercicio != null) && dtejercicio.Rows.Count > 0) { if (dtejercicio.COUNT("Ejercicio", string.Format("Ejercicio={0}", EjercicioActual)) == 0) { litem = new ListItem(EjercicioActual.ToString(), EjercicioActual.ToString()); DdlEjercicios.Items.Insert(0, litem); DdlEjerciciosCM.Items.Insert(0, litem); } if (dtejercicio.COUNT("Ejercicio", string.Format("Ejercicio={0}", (EjercicioActual - 1))) == 0) { litem = new ListItem((EjercicioActual - 1).ToString(), (EjercicioActual - 1).ToString()); DdlEjercicios.Items.Insert(1, litem); DdlEjerciciosCM.Items.Insert(1, litem); } } else { litem = new ListItem(EjercicioActual.ToString(), EjercicioActual.ToString()); DdlEjercicios.Items.Insert(0, litem); DdlEjerciciosCM.Items.Insert(0, litem); litem = new ListItem((EjercicioActual - 1).ToString(), (EjercicioActual - 1).ToString()); DdlEjercicios.Items.Insert(0, litem); DdlEjerciciosCM.Items.Insert(0, litem); } if (DdlEjercicios.Items.Count > 0) { DdlEjercicios.SelectedIndex = 0; } DdlEjercicios.SelectedValueExist(NowADS().Year.ToString()); } private void CargaTiposPeriodo() { set_GlobalDTTipoPeriodos(UsuarioActual.CveEmpresa, null); DdlTipoPeriodo.DataSource = get_GlobalDTTipoPeriodos(UsuarioActual.CveEmpresa); DdlTipoPeriodoCM.DataSource = DdlTipoPeriodo.DataSource; DdlTipoPeriodoSim.DataSource = DdlTipoPeriodo.DataSource; DdlTipoPeriodoCMB.DataSource = DdlTipoPeriodo.DataSource; DdlTipoPeriodoCMB.DataBind(); DdlTipoPeriodoSim.DataBind(); DdlTipoPeriodoCM.DataBind(); DdlTipoPeriodo.DataBind(); DdlTipoPeriodo.Items.Insert(0, new ListItem("Seleccione", "-1")); if (DdlTipoPeriodo.Items.Count > 0) { DdlTipoPeriodo.SelectedIndex = 0; } } private void cargaPeriodos() { int tipoPeriodo = DdlTipoPeriodo.SelectedValue.ToEntero(); int ejercicio = DdlEjercicios.SelectedValue.ToEntero(); dtPeriodos = null; if (DdlTipoPeriodo.SelectedValue.ToEntero() > 0) { using (ClsNominas objperiodos = new ClsNominas()) { if (objperiodos.GetPeriodos(tipoPeriodo, UsuarioActual.CveEmpresa, ejercicio, -1, -1)) { if (objperiodos.DtResultados.Rows.Count == 0) { Alert("No existen periodos registrados en este año y tipo de periodo,¿desea registrarlos masivamente?", TipoMensaje.MsgConfirmacion, "$(\"#divCargaMasiva\").modal(\"show\");", TextoConfirmacion: "Aceptar", TextoSegundoBoton: "No"); } dtPeriodos = objperiodos.DtResultados.FiltraParametros("Estatus IN (1,2,3,4,5)"); } } } DdlPeriodo.DataSource = dtPeriodos; DdlPeriodo.DataBind(); DdlPeriodo.Items.Insert(0, new ListItem("Seleccione", "-1")); muestraPeriodo(); } protected void DdlEjercicios_SelectedIndexChanged(object sender, EventArgs e) { cargaPeriodos(); } protected void DdlTipoPeriodo_SelectedIndexChanged(object sender, EventArgs e) { cargaPeriodos(); } protected void DdlPeriodo_SelectedIndexChanged(object sender, EventArgs e) { muestraPeriodo(); } private void muestraPeriodo() { int CvePeriodo = DdlPeriodo.SelectedValue.ToEntero(); LnkConsultar.Visible = (CvePeriodo > 0); UPFiltros.Update(); } #endregion #region Datos protected void LnkConsultar_Click(object sender, EventArgs e) { FiltCveProyecto = DdlProyecto.SelectedValue.ToEntero(); FiltCveSubProyecto = DdlSubProyecto.SelectedValue.ToEntero(); FiltCveTurno = DdlTurno.SelectedValue.ToEntero(); FiltCvePeriodo = DdlPeriodo.SelectedValue.ToEntero(); FiltAgrupador = 1; CveTipoTrabajador = DdlTipoTrabajador.SelectedValue.ToEntero(); HypPDFSTimbrados.Attributes.Add("onclick", string.Format("GETPDF({0},{1})", -1, FiltCvePeriodo)); HypXMLSTimbrados.Attributes.Add("onclick", string.Format("GETXML({0},{1})", -1, FiltCvePeriodo)); cargaDatos(); int empleados = 0; if (dtempleados != null && dtempleados.Rows.Count > 0) { empleados = dtempleados.COUNT("CvePersonal", " CvePersonal >0 "); } LtlPeriodoseleccionado.Text = string.Format("{0} ({1} Empleados)", DdlPeriodo.SelectedItem.Text, empleados); LtlPeriodoseleccionadoASis.Text = LtlPeriodoseleccionado.Text; } public void cargaDatos(bool cargaasistencia = true, int CvePersonal = -1) { int Estatus = 0; int CveEmpresa = UsuarioActual.CveEmpresa; bool continuar = false; DataTable dtPeriodo = new DataTable(); if (CvePersonal <= 0) { CvePeriodoSeleccionado = 0; dtempleados = null; dtConceptos = null; } LnkAutorizar.Visible = false; Estatus = 5; if (FiltCvePeriodo > 0) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetPeriodos(-1, UsuarioActual.CveEmpresa, -1, -1, FiltCvePeriodo)) { DataRow drow = objnom.DtResultados.Rows[0]; Estatus = drow["Estatus"].ToString().ToEntero(); int CvePrePolizaProvision = drow["CvePrePolizaProvision"].ToString().ToEntero(); int CvePrePolizaProvisionAsimilados = drow["CvePrePolizaAsimilables"].ToString().ToEntero(); int CvePrePolizaProrrateo = drow["CvePrePolizaProrrateo"].ToString().ToEntero(); FechaInicioPeriodo = drow["FechaInicio"].ToString().ToDateTime(); FechaFinPeriodo = drow["FechaFin"].ToString().ToDateTime(); LnkBitacoraCorreo.Visible = true; //LnkConceptoEmpleado.Visible = (Estatus == 1); LnkRegistrarProvision.Visible = (Estatus >= 2);//&& (CvePrePolizaProvision <= 0 || UsuarioActual.CveUsuario == 100); LnkRegistrarProvision.Text = CvePrePolizaProvision <= 0 ? "Registrar provisión" : "Regenerar provisión"; LnkConceptoEmpleado.Visible = true;//(Estatus < 2); LnkCargaAsistenciaMasiva.Visible = (Estatus < 2); LnkModalPlantillaNomina.Visible = true; LnkTimbrarTodos.Visible = (Estatus > 2); LnkReenviarcorreo.Visible = true; LnkLayoutContable.Visible = (Estatus >= 2); LnkProvisionNomina.Visible = CvePrePolizaProvision > 0; LnkProvisionNomina.NavigateUrl = $"../Contabilidad/RegPrepolizaS.aspx?CvePrePoliza={CvePrePolizaProvision}"; LnkProvisionNominaAsimilados.Visible = CvePrePolizaProvisionAsimilados > 0; LnkProvisionNominaAsimilados.NavigateUrl = $"../Contabilidad/RegPrepolizaS.aspx?CvePrePoliza={CvePrePolizaProvisionAsimilados}"; LnkProvisionProrrateo.NavigateUrl = $"../Contabilidad/RegPrepolizaS.aspx?CvePrePoliza={CvePrePolizaProrrateo}"; LnkProvisionProrrateo.Visible = CvePrePolizaProrrateo > 0; UpAccciones.Update(); } LnkListaRaya.Visible = true; LnkAsistenciaIncidencias.Visible = true; LnkFormatoTabular.Visible = true; LnkPersonalizarNomina.Visible = true; LnkFormatoFiscal.Visible = (UsuarioActual.CveEmpresa == 141 || UsuarioActual.CveRol == 1); HypPDFSTimbrados.Visible = true; HypXMLSTimbrados.Visible = true; if (objnom.GetNominaEmpleado(FiltCveProyecto, FiltCveSubProyecto, FiltCveTurno, FiltCvePeriodo, CveEmpresa, FiltAgrupador, DdlRegimenContratacion.SelectedValue.ToEntero(), CveTipoTrabajador: CveTipoTrabajador, Neto: ddlfiniquito.SelectedValue.ToEntero(), CvePersonal: CvePersonal) && objnom.DTSetResultados.Tables.Count > 4) { if (CvePersonal > 0) { dtPerEmpleados = objnom.DTSetResultados.Tables[3]; dtPerEmpleadosConceptos = objnom.DTSetResultados.Tables[4]; dtPerConceptos = objnom.DTSetResultados.Tables[0]; dtPerPeriodo = objnom.DTSetResultados.Tables[1]; ltlPendienteActualizar.Text = "Hay Cambios pendientes por actualizar, Calcular para mostrar."; } else { dtempleados = objnom.DTSetResultados.Tables[3]; dtempleadosConceptos = objnom.DTSetResultados.Tables[4]; dtConceptos = objnom.DTSetResultados.Tables[0]; dtPeriodo = objnom.DTSetResultados.Tables[1]; ltlPendienteActualizar.Text = ""; } //dtasistencia = objnom.DTSetResultados.Tables[2]; CvePeriodoSeleccionado = FiltCvePeriodo; continuar = true; } if (dtempleados != null) { LnkTimbrarTodos.Visible = (dtempleados.Rows.Count > 0 && dtempleados.COUNT("CvePersonal", "SeTimbro=0 AND CvePersonal >0 AND NomAutorizado =1") > 0); } } } if (CvePersonal > 0) { } else { #region CargaGrid if (continuar) { cargarGrid(); } else { GvNominas.DataSource = null; GvNominas.DataBind(); } #endregion if (cargaasistencia && dtPeriodo != null && dtPeriodo.Rows.Count > 0) { cargarasistencia(); } if (dtempleados != null) { LnkAutorizar.Visible = (dtempleados.COUNT("CvePersonal", "CvePersonal > 0 AND NomAutorizado =0 AND SumaPercepciones > 0 ") > 0) || (Estatus < 2); LnkCancelarNomina.Visible = (dtempleados.COUNT("CvePersonal", "CvePersonal > 0 AND NomAutorizado =1 AND SeTimbro=0") > 0); } UpDatos.Update(); } UpPendienteActualizar.Update(); } public void cargarasistencia() { DateTime FechaInicio = FechaInicioPeriodo; DateTime FechaFin = FechaFinPeriodo; DataTable dtasistencia; using (ClsNominas objnom = new ClsNominas()) { objnom.GetAsistenciabetweendate(UsuarioActual.CveEmpresa, FechaInicio, FechaFin); dtasistencia = objnom.DtResultados; } StringBuilder gvasistencia = new StringBuilder(); gvasistencia.Append("
"); if (true) { DateTime fecha = FechaInicio; gvasistencia.Append(""); gvasistencia.Append(""); while (fecha <= FechaFin) { gvasistencia.AppendFormat("", fecha); fecha = fecha.AddDays(1); } gvasistencia.Append(""); } string tipo = ""; foreach (DataRow rempl in dtempleados.FiltraParametros("CvePersonal>0").Rows) { int CvePersonal = rempl["CvePersonal"].ToString().ToEntero(); string nombre = rempl["Nombre"].ToString(); string Codigo = rempl["Codigo"].ToString(); DateTime fecha = FechaInicio; int HorasDobles, HorasTriples; gvasistencia.Append(""); gvasistencia.AppendFormat("", CvePersonal, nombre, Codigo); while (fecha <= FechaFin) { DataRow drow = dtasistencia.FiltroPrimero(string.Format("Fecha='{0:yyyy/MM/dd}' AND CvePersonal={1}", fecha, CvePersonal)); tipo = "-"; if (drow != null) { tipo = string.Format("{0} ({1}%)", drow["Tipo"], drow["PorcentajePago"]); HorasDobles = drow["HorasDobles"].ToString().ToEntero(); HorasTriples = drow["HorasTriples"].ToString().ToEntero(); if (HorasDobles > 0) { tipo = string.Format("{0}
{1} horas dobles", tipo, HorasDobles); } if (HorasTriples > 0) { tipo = string.Format("{0}
{1} horas triple", tipo, HorasTriples); } drow.Delete(); } gvasistencia.AppendFormat("", tipo, CvePersonal, fecha); fecha = fecha.AddDays(1); } gvasistencia.Append(""); } gvasistencia.Append("
Nombre{0:dd/MM/yyyy}
{2} {1} {0}
"); ltlGvAsistencia.Text = gvasistencia.ToString(); } private void cargarGrid() { int CurrentColumn = 2; BoundField bf; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('P') AND EsPadre = 1 ").Rows) { int CveConcepto = row["CveConcepto"].ToString().ToEntero(); int EsFormula = row["EsFormula"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); GvNominas.Columns[CurrentColumn].ItemStyle.BackColor = System.Drawing.Color.Transparent; GvNominas.Columns[CurrentColumn].ItemStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = " "; if (EsFormula == 1) { GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = "isOnlyVisible "; } GvNominas.Columns[CurrentColumn].Visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) != 0); bf = (BoundField)GvNominas.Columns[CurrentColumn]; bf.DataField = string.Format("V_{0}", CveConcepto); DataRow colrow = DtNomOcultarMostrar.FiltroPrimero(string.Format("ColumnaDB= '{0}'", bf.DataField)); if (colrow != null) { GvNominas.Columns[CurrentColumn].Visible = (colrow["TipoDB"].ToString() == "1"); } bf.HeaderText = Concepto; if (GvNominas.Columns[CurrentColumn].Visible) { CurrentColumn++; } } if (true) { BoundField field = (BoundField)GvNominas.Columns[CurrentColumn]; field.HeaderText = "Percepciones"; field.DataField = "SumaPercepciones"; field.ItemStyle.BackColor = System.Drawing.Color.LightGray; GvNominas.Columns[CurrentColumn].Visible = true; CurrentColumn++; } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('D') AND EsPadre = 1 ").Rows) { int CveConcepto = row["CveConcepto"].ToString().ToEntero(); int CveSistema = row["CveSistema"].ToString().ToEntero(); int EsFormula = row["EsFormula"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); GvNominas.Columns[CurrentColumn].ItemStyle.BackColor = System.Drawing.Color.Transparent; GvNominas.Columns[CurrentColumn].ItemStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = " "; if (EsFormula == 1) { GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = "isOnlyVisible "; } GvNominas.Columns[CurrentColumn].Visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) != 0) && CveSistema != 101; bf = (BoundField)GvNominas.Columns[CurrentColumn]; bf.DataField = string.Format("V_{0}", CveConcepto); DataRow colrow = DtNomOcultarMostrar.FiltroPrimero(string.Format("ColumnaDB= '{0}'", bf.DataField)); if (colrow != null) { GvNominas.Columns[CurrentColumn].Visible = (colrow["TipoDB"].ToString() == "1"); } bf.HeaderText = Concepto; if (GvNominas.Columns[CurrentColumn].Visible) { CurrentColumn++; } } if (true) { BoundField field = (BoundField)GvNominas.Columns[CurrentColumn]; field.HeaderText = "Deducciones"; field.DataField = "SumaDeducciones"; field.ItemStyle.BackColor = System.Drawing.Color.LightGray; GvNominas.Columns[CurrentColumn].ItemStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].Visible = true; CurrentColumn++; field = (BoundField)GvNominas.Columns[CurrentColumn]; field.HeaderText = "Especie"; field.DataField = "SumaEspecie"; field.ItemStyle.BackColor = System.Drawing.Color.LightGray; GvNominas.Columns[CurrentColumn].ItemStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].Visible = (dtempleados.SUM("SumaEspecie") != 0); CurrentColumn++; field = (BoundField)GvNominas.Columns[CurrentColumn]; field.HeaderText = "Total"; field.DataField = "Total"; field.ItemStyle.BackColor = System.Drawing.Color.DarkGray; field.ItemStyle.CssClass = "TotalWhite"; field.HeaderStyle.CssClass = "TotalWhite"; GvNominas.Columns[CurrentColumn].Visible = true; CurrentColumn++; } if (Chkobligaciones.Checked) { foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('O') AND EsPadre = 1 ").Rows) { int CveConcepto = row["CveConcepto"].ToString().ToEntero(); int EsFormula = row["EsFormula"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); GvNominas.Columns[CurrentColumn].ItemStyle.BackColor = System.Drawing.Color.Transparent; GvNominas.Columns[CurrentColumn].ItemStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = " "; if (EsFormula == 1) { GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = "isOnlyVisible "; } GvNominas.Columns[CurrentColumn].Visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) != 0); bf = (BoundField)GvNominas.Columns[CurrentColumn]; bf.DataField = string.Format("V_{0}", CveConcepto); bf.HeaderText = Concepto; DataRow colrow = DtNomOcultarMostrar.FiltroPrimero(string.Format("ColumnaDB= '{0}'", bf.DataField)); if (colrow != null) { GvNominas.Columns[CurrentColumn].Visible = (colrow["TipoDB"].ToString() == "1"); } if (GvNominas.Columns[CurrentColumn].Visible) { CurrentColumn++; } } if (true) { BoundField field = (BoundField)GvNominas.Columns[CurrentColumn]; field.HeaderText = "Obligaciones"; field.DataField = "SumaObligaciones"; field.ItemStyle.BackColor = System.Drawing.Color.LightGray; GvNominas.Columns[CurrentColumn].ItemStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].Visible = true; CurrentColumn++; } } for (int i = CurrentColumn; i < 102; i++) { bf = (BoundField)GvNominas.Columns[i]; bf.DataField = ""; bf.HeaderText = ""; GvNominas.Columns[i].ItemStyle.BackColor = System.Drawing.Color.Transparent; GvNominas.Columns[CurrentColumn].ItemStyle.CssClass = " "; GvNominas.Columns[CurrentColumn].HeaderStyle.CssClass = " "; GvNominas.Columns[i].Visible = false; } setGVNominas(); } private void setGVNominas() { string filtrogrupo = ""; string Orderby = "EsTotal"; string separator = ","; foreach (DataRow item in DtNomOrden.Rows) { Orderby = string.Format("{0} {1} {2} {3}", Orderby, separator, item["ColumnaDB"], item["TipoDB"]); separator = ","; } DataTable dt = dtempleados.Copy().FiltraParametros("", Orderby); if (DdlAgrupadorB.SelectedValue == "1") { foreach (DataRow drow in dtempleados.FiltraParametros("CvePersonal > 0", "", new string[] { "CveSubProyecto", "SubProyecto" }).Rows) { DataRow dr = dt.NewRow(); filtrogrupo = (drow["CveSubProyecto"] == DBNull.Value ? "CveSubProyecto IS NULL AND CvePersonal>0 " : string.Format("CveSubProyecto = {0} AND CvePersonal>0", drow["CveSubProyecto"])); foreach (DataRow row in dtConceptos.FiltraParametros("EsPadre = 1 ").Rows) { int CveConcepto = row["CveConcepto"].ToString().ToEntero(); dr[string.Format("V_{0}", CveConcepto)] = dtempleados.SUM(string.Format("[V_{0}]", CveConcepto), filtrogrupo); } dr["CveSubProyecto"] = drow["CveSubProyecto"]; dr["SubProyecto"] = drow["SubProyecto"]; dr["SumaPercepciones"] = dtempleados.SUM("SumaPercepciones", filtrogrupo); dr["SumaDeducciones"] = dtempleados.SUM("SumaDeducciones", filtrogrupo); dr["SumaEspecie"] = dtempleados.SUM("SumaEspecie", filtrogrupo); dr["Total"] = dtempleados.SUM("Total", filtrogrupo); dr["SumaObligaciones"] = dtempleados.SUM("SumaObligaciones", filtrogrupo); dt.Rows.Add(dr); } dt.AcceptChanges(); dt = dt.FiltraParametros("", "CveSubProyecto,SubProyecto,Codigo,Nombre"); } if (DdlAgrupadorB.SelectedValue == "2") { foreach (DataRow drow in dtempleados.FiltraParametros("CvePersonal > 0", "", new string[] { "CveDepartamento", "Departamento" }).Rows) { DataRow dr = dt.NewRow(); filtrogrupo = (drow["CveDepartamento"] == DBNull.Value ? "CveDepartamento IS NULL AND CvePersonal>0 " : string.Format("CveDepartamento = {0} AND CvePersonal>0", drow["CveDepartamento"])); foreach (DataRow row in dtConceptos.FiltraParametros("EsPadre = 1 ").Rows) { int CveConcepto = row["CveConcepto"].ToString().ToEntero(); dr[string.Format("V_{0}", CveConcepto)] = dtempleados.SUM(string.Format("[V_{0}]", CveConcepto), filtrogrupo); } dr["CveDepartamento"] = drow["CveDepartamento"]; dr["Departamento"] = drow["Departamento"]; dr["SumaPercepciones"] = dtempleados.SUM("SumaPercepciones", filtrogrupo); dr["SumaDeducciones"] = dtempleados.SUM("SumaDeducciones", filtrogrupo); dr["SumaEspecie"] = dtempleados.SUM("SumaEspecie", filtrogrupo); dr["Total"] = dtempleados.SUM("Total", filtrogrupo); dr["SumaObligaciones"] = dtempleados.SUM("SumaObligaciones", filtrogrupo); dt.Rows.Add(dr); } dt.AcceptChanges(); dt = dt.FiltraParametros("", "CveDepartamento,Departamento,Codigo,Nombre"); } if (DdlAgrupadorB.SelectedValue == "3") { foreach (DataRow drow in dtempleados.FiltraParametros("CvePersonal > 0", "", new string[] { "CveTurno", "Turno" }).Rows) { DataRow dr = dt.NewRow(); filtrogrupo = (drow["CveTurno"] == DBNull.Value ? "CveTurno IS NULL AND CvePersonal>0 " : string.Format("CveTurno = {0} AND CvePersonal>0", drow["CveTurno"])); foreach (DataRow row in dtConceptos.FiltraParametros("EsPadre = 1 ").Rows) { int CveConcepto = row["CveConcepto"].ToString().ToEntero(); dr[string.Format("V_{0}", CveConcepto)] = dtempleados.SUM(string.Format("[V_{0}]", CveConcepto), filtrogrupo); } dr["CveTurno"] = drow["CveTurno"]; dr["Turno"] = drow["Turno"]; dr["SumaPercepciones"] = dtempleados.SUM("SumaPercepciones", filtrogrupo); dr["SumaDeducciones"] = dtempleados.SUM("SumaDeducciones", filtrogrupo); dr["SumaEspecie"] = dtempleados.SUM("SumaEspecie", filtrogrupo); dr["Total"] = dtempleados.SUM("Total", filtrogrupo); dr["SumaObligaciones"] = dtempleados.SUM("SumaObligaciones", filtrogrupo); dt.Rows.Add(dr); } dt.AcceptChanges(); dt = dt.FiltraParametros("", "CveDepartamento,Departamento,Codigo,Nombre"); } GvNominas.DataSource = dt; GvNominas.DataBind(); } protected void GvNominas_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Literal LtlNombre = e.Row.FCLiteral("LtlNombre"); LinkButton LnkTimbrar = (LinkButton)e.Row.FindControl("LnkTimbrar"); int cvePersonal = e.Row.DataKey("CvePersonal").ToEntero(); int CvePeriodo = e.Row.DataKey("CvePeriodo").ToEntero(); int CveNomina = e.Row.DataKey("CveNomina").ToEntero(); string SeTimbro = e.Row.DataKey("SeTimbro").ToString(); string SeTimbroFiniquito = SeTimbro;//e.Row.DataKey("SeTimbroFiniquito").ToString(); string EsRenuncia = e.Row.DataKey("EsRenuncia").ToString(); string NomAutorizado = e.Row.DataKey("NomAutorizado").ToString(); string Nombre = e.Row.DataKey("Nombre").ToString(); string Codigo = e.Row.DataKey("Codigo").ToString(); string Turno = e.Row.DataKey("Turno").ToString(); string Departamento = e.Row.DataKey("Departamento").ToString(); string SubProyecto = e.Row.DataKey("SubProyecto").ToString(); e.Row.FCHyperLink("LnkSobreRecibo").Attributes.Add("onclick", string.Format("GETSobreRecibo({0},{1})", cvePersonal, CvePeriodo)); LnkTimbrar.Visible = false; LinkButton ImgDelete = (LinkButton)e.Row.FindControl("ImgDelete"); LinkButton Imgdesautorizar = (LinkButton)e.Row.FindControl("Imgdesautorizar"); LinkButton LnkCancelar = (LinkButton)e.Row.FindControl("LnkCancelar"); LinkButton LnkReenviarCorreo = (LinkButton)e.Row.FindControl("LnkReenviarCorreo"); ImgDelete.Visible = false; Imgdesautorizar.Visible = false; LnkCancelar.Visible = false; LnkReenviarCorreo.Visible = false; if (cvePersonal > 0) { LnkCancelar.Visible = PermisoCancelarEmitido && SeTimbro.ToUpper().Contiene("TRUE", "1"); LnkReenviarCorreo.Visible = SeTimbro.ToUpper().Contiene("TRUE", "1"); LtlNombre.Text = String.Format("{2} {1}", cvePersonal, Nombre, Codigo); if (CveNomina > 0) { Imgdesautorizar.Visible = NomAutorizado.ToUpper().Contiene("TRUE", "1") && !SeTimbro.ToUpper().Contiene("TRUE", "1"); ImgDelete.Visible = !NomAutorizado.ToUpper().Contiene("TRUE", "1") && !SeTimbro.ToUpper().Contiene("TRUE", "1"); if (NomAutorizado == "False") { } else { if (!SeTimbro.ToUpper().Contiene("TRUE", "1")) { LnkTimbrar.Visible = true; e.Row.CssClass = "info"; } else { //onclick() e.Row.FCHyperLink("HypPDF").Attributes.Add("onclick", string.Format("GETPDF({0},{1})", cvePersonal, CvePeriodo)); e.Row.FCHyperLink("HypXml").Attributes.Add("onclick", string.Format("GETXML({0},{1})", cvePersonal, CvePeriodo)); e.Row.FindControl("HypPDF").Visible = true; e.Row.FindControl("HypXml").Visible = true; e.Row.CssClass = "success"; if (EsRenuncia.ToUpper().Contiene("TRUE", "1") && !SeTimbroFiniquito.ToUpper().Contiene("TRUE", "1")) { // cvePersonal bool isfiniquito = false; foreach (DataRow drow in dtConceptos.FiltraParametros("CveSistema IN(10, 11, 32, 47)").Rows) { if (dtempleados.SUM(string.Format("V_{0}", drow["CveConcepto"]), string.Format("CvePersonal ={0}", cvePersonal)) > 0) { isfiniquito = true; } } if (isfiniquito) { LnkTimbrar.Visible = true; e.Row.CssClass = "danger"; e.Row.ToolTip = "sin timbrar conceptos de indemnización"; } } } } } e.Row.FindControl("HypPDF").Visible = e.Row.FindControl("HypPDF").Visible || UsuarioActual.CveRol == 1; e.Row.FindControl("HypXml").Visible = e.Row.FindControl("HypXml").Visible || UsuarioActual.CveRol == 1; } else { LtlNombre.Text = "Total General"; e.Row.FindControl("LnkTimbrar").Visible = false; if (Turno.Length == 0 && SubProyecto.Length > 0) { LtlNombre.Text = String.Format("Centro de costos: {0}", SubProyecto, e.Row.DataKey("CveSubProyecto").ToString()); } else if (Turno.Length > 0) { LtlNombre.Text = String.Format("Turno: {0}", SubProyecto); } else if (Departamento.Length > 0) { LtlNombre.Text = String.Format("Departamento: {0}", Departamento); } else { e.Row.FCHyperLink("HypPDF").Attributes.Add("onclick", string.Format("GETPDF({0},{1})", -1, CvePeriodoSeleccionado)); e.Row.FindControl("HypPDF").Visible = false; e.Row.CssClass = "SubTotales"; } e.Row.FindControl("LnkSobreRecibo").Visible = false; } } } #endregion protected void LnkReenviarcorreo_Click(object sender, EventArgs e) { //string msggral = ""; int CvePeriodo = 0; ClsSisMail Mail = new ClsSisMail(); DataTable dtpersonal = new DataTable(); DataRow drow; using (ClsRH objrh = new ClsRH()) { objrh.GetPersonal(-1, UsuarioActual.CveEmpresa); dtpersonal = objrh.DtResultados.FiltraParametros("", "", new string[] { "CvePersonal", "Correo", "NombreCompleto" }); } using (ClsRH objrh = new ClsRH()) using (ClsNominas ObjNomina = new ClsNominas()) { foreach (GridViewRow gvRow in GvNominas.Rows) { CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); int CveNomina = gvRow.DataKey("CveNomina").ToEntero(); int SeTimbro = (gvRow.DataKey("SeTimbro").ToUpper() == "TRUE" ? 1 : gvRow.DataKey("SeTimbro").ToEntero()); LinkButton LnkTimbrar = gvRow.FCLinkButton("LnkTimbrar"); string Correo = string.Empty; string NombreCompleto = string.Empty; if (dtpersonal.Rows.Count > 0 && (drow = dtpersonal.FiltroPrimero(string.Format("CvePersonal = {0}", CvePersonal))) != null) { Correo = drow["Correo"].ToString(); NombreCompleto = drow["NombreCompleto"].ToString(); } if (CvePersonal > 0 && SeTimbro == 1) { if (Correo.Trim().Length > 0) { byte[] pdf = GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); if (pdf != null) { List objarch = new List(); if (ObjNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodo, -1, UsuarioActual.CveEmpresa)) { string Ruta = ""; string PathXML = ""; string PathXMLF = ""; string Xmlname = ""; string XmlnameF = ""; //string empleado = ""; Ruta = UsuarioActual.Empresa.Ruta; PathXML = $"{Ruta}XML\\Nomina\\{ObjNomina.SerieFolio}.xml"; PathXMLF = $"{Ruta}XML\\Nomina\\{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; Xmlname = $"{ObjNomina.SerieFolio}.xml"; XmlnameF = $"{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; objarch.Add(new ClsSisMail.ArchivoMail() { ArchivoBinario = pdf, NombreArchivo = $"{ObjNomina.SerieFolio}.pdf" }); //this.GuardaLog(PathXML); if (!string.IsNullOrEmpty(PathXML) && System.IO.File.Exists(PathXML)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXML, NombreArchivo = Xmlname }); } if (!string.IsNullOrEmpty(PathXMLF) && System.IO.File.Exists(PathXMLF)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXMLF, NombreArchivo = XmlnameF }); } } Mail.SendMail(UsuarioActual.Empresa, Correo.Trim(), string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy}", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), "", "", objarch); // Mail.SendMail(ClsPaginas.EmpresaNotificaciones, "caudillo.90d@gmail.com", string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy} ", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), Correo.Trim(), "", objarch); objrh.NomBitacoraCorreoAdd(CvePeriodoSeleccionado, CvePersonal, Correo.Trim(), UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario); } } } } } Alert("se reenviaron los recibos timbrados"); } public string msgCorregidoSat(string msg, int CvePersonal, string RFC, string CURP) { string retorno = msg; if (msg.ToUpper().Contains("RFC")) { if (msg.ToUpper().Contains("NOM138")) { retorno = string.Format("Existe un inconveniente con el RFC '{0}' del empleado,favor de validar el RFC en caso que este bien capturado /n el empleado deberá realizar una aclaración directamente ante el SAT.", RFC); } else if (msg.ToUpper().Substring(0, 5).Contains("301")) { retorno = string.Format("RFC '{1}' Invalido favor de actualizarlo en el módulo de personal", CvePersonal, RFC); } } if (msg.ToUpper().Contains("CURP")) { if (msg.ToUpper().Substring(0, 5).Contains("301")) { retorno = string.Format("CURP '{1}' Invalido favor de actualizarlo en el modulo de personal", CvePersonal, CURP); } } if (msg.ToUpper().Contains("CONCEPTO NO REGISTRADO")) { retorno = string.Format("{0} a un concepto del SAT en el catálogo de conceptos.", retorno.Replace("No se pudo generar el pretimbre:", "").Replace("(", ",favor de vincular el concepto SIG '").Replace(")", "'").Trim()); } if (msg.ToUpper().Contains("REGISTROPATRONAL")) { if (msg.ToUpper().Contains("NOM162")) { retorno = string.Format("Es necesario vincular el empleado a un registro patronal en el modulo de personal", CvePersonal); ; } } return retorno; } protected void LnkTimbrarTodos_Click(object sender, EventArgs e) { string msggral = ""; int CvePeriodo = 0; ClsSisMail Mail = new ClsSisMail(); DataTable dtpersonal = new DataTable(); DataRow drow; using (ClsRH objrh = new ClsRH()) { objrh.GetPersonal(-1, UsuarioActual.CveEmpresa); dtpersonal = objrh.DtResultados.FiltraParametros("", "", new string[] { "CvePersonal", "Correo", "NombreCompleto", "RFC", "CURP" }); } using (ClsNominas ObjNomina = new ClsNominas()) { foreach (GridViewRow gvRow in GvNominas.Rows) { CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); int CveNomina = gvRow.DataKey("CveNomina").ToEntero(); LinkButton LnkTimbrar = gvRow.FCLinkButton("LnkTimbrar"); string Correo = string.Empty; string NombreCompleto = string.Empty; string RFC = string.Empty; string CURP = string.Empty; if (dtpersonal.Rows.Count > 0 && (drow = dtpersonal.FiltroPrimero(string.Format("CvePersonal = {0}", CvePersonal))) != null) { Correo = drow["Correo"].ToString(); NombreCompleto = drow["NombreCompleto"].ToString(); RFC = drow["RFC"].ToString(); CURP = drow["CURP"].ToString(); } if (CvePersonal > 0 && LnkTimbrar.Visible) { LogicNominas lognom = new LogicNominas(); string Msg = ""; Msg = lognom.TimbrarNomina(CveNomina, CvePersonal, CvePeriodo, UsuarioActual, CvePAC: 4); if (Msg != null && Msg.Length > 0) { msggral = string.Format("{0}{3}{2}
{4}
{1}", msggral, Msg, gvRow.DataKey("Nombre"), gvRow.DataKey("Codigo"), msgCorregidoSat(Msg, CvePersonal, RFC, CURP)); } else { LnkTimbrar.Visible = false; gvRow.CssClass = "success"; gvRow.FindControl("ImgDelete").Visible = false; gvRow.FindControl("Imgdesautorizar").Visible = false; gvRow.FindControl("LnkCancelar").Visible = true; gvRow.FindControl("HypXml").Visible = true; gvRow.FindControl("HypPDF").Visible = true; gvRow.ForeColor = Color.Green; if (enviarCorreoEnTimbrado && Correo.Trim().Length > 0) { byte[] pdf = GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); if (pdf != null) { List objarch = new List(); if (ObjNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodo, -1, UsuarioActual.CveEmpresa)) { string Ruta = ""; string PathXML = ""; string PathXMLF = ""; string Xmlname = ""; string XmlnameF = ""; //string empleado = ""; Ruta = UsuarioActual.Empresa.Ruta; PathXML = $"{Ruta}XML\\Nomina\\{ObjNomina.SerieFolio}.xml"; PathXMLF = $"{Ruta}XML\\Nomina\\{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; Xmlname = $"{ObjNomina.SerieFolio}.xml"; XmlnameF = $"{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; objarch.Add(new ClsSisMail.ArchivoMail() { ArchivoBinario = pdf, NombreArchivo = $"{ObjNomina.SerieFolio}.pdf" }); if (!string.IsNullOrEmpty(PathXML) && System.IO.File.Exists(PathXML)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXML, NombreArchivo = Xmlname }); } if (!string.IsNullOrEmpty(PathXMLF) && System.IO.File.Exists(PathXMLF)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXMLF, NombreArchivo = XmlnameF }); } } Mail.SendMail(UsuarioActual.Empresa, Correo.Trim(), string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy}", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), "", "", objarch); //Mail.SendMail(ClsPaginas.EmpresaNotificaciones, "caudillo.90d@gmail.com", string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy} ", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), Correo.Trim(), "", objarch); using (ClsRH objrh = new ClsRH()) { objrh.NomBitacoraCorreoAdd(CvePeriodoSeleccionado, CvePersonal, Correo.Trim(), UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario); } } } } } } } if (msggral.Length > 0) { Alert(string.Format("Los siguientes empleados no se timbraron por las siguiente situaciones: {0}
CódigoNombreMensaje SAT
", msggral), TipoMensaje.MsgAdvertencia); } else { using (ClsNominas ObjPeriodo = new ClsNominas()) { ObjPeriodo.CambiaEstatusPeriodo(CvePeriodo, (int)enumNominasEstatus.Timbrada, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa); } } UpDatos.Update(); } //private void CreaObjetoEmpresa(Usuario UsuarioActual) //{ // ClsSisEmpresas ObjEmpresa = new ClsSisEmpresas(); // if (ObjEmpresa.GetEmpresas(UsuarioActual.CveEmpresa, "-1", "-1", "-1", "-1")) // { // if (ObjEmpresa.GetEmpresasFuncionalidades(UsuarioActual.CveEmpresa)) // { // System.Data.DataTable dttmp = ObjEmpresa.DtResultados; // EmpresasFuncionalidades = new HybridDictionary(); // EmpresasFuncionalidadesnoV4 = new HybridDictionary(); // foreach (System.Data.DataRow Row in dttmp.Rows) // { // if (Convert.ToInt32(Row["CveFuncionalidad"]) != 350) // { // EmpresasFuncionalidadesnoV4.Add(Convert.ToInt32(Row["CveFuncionalidad"]), Row["Valor"].ToString()); // EmpresasFuncionalidades.Add(Convert.ToInt32(Row["CveFuncionalidad"]), Row["Valor"].ToString()); // } // else // { // EmpresasFuncionalidades.Add(Convert.ToInt32(Row["CveFuncionalidad"]), Row["Valor"].ToString()); // } // } // ObjEmpresa.Empresa.SetFuncionalidades(EmpresasFuncionalidades); // } // UsuarioActual.Empresa = ObjEmpresa.Empresa; // } // else // { // } // ObjEmpresa.Dispose(); //} protected void LnkReenviarCorreo_Click(object sender, EventArgs e) { LinkButton lnk = (LinkButton)sender; GridViewRow gvRow = (GridViewRow)lnk.NamingContainer; int CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); int CveNomina = gvRow.DataKey("CveNomina").ToEntero(); LogicNominas lognom = new LogicNominas(); ClsSisMail Mail = new ClsSisMail(); DataTable dtpersonal = new DataTable(); DataRow drow; string Correo = string.Empty; string NombreCompleto = string.Empty; using (ClsRH objrh = new ClsRH()) { objrh.GetPersonal(CvePersonal, UsuarioActual.CveEmpresa); dtpersonal = objrh.DtResultados.FiltraParametros("", "", new string[] { "CvePersonal", "Correo", "NombreCompleto" }); } if (dtpersonal.Rows.Count > 0 && (drow = dtpersonal.FiltroPrimero(string.Format("CvePersonal = {0}", CvePersonal))) != null) { Correo = drow["Correo"].ToString(); NombreCompleto = drow["NombreCompleto"].ToString(); } if (Correo.Trim().Length > 0) { byte[] pdf = GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); if (pdf != null) { List objarch = new List(); using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodo, -1, UsuarioActual.CveEmpresa)) { string Ruta = ""; string PathXML = ""; string PathXMLF = ""; string Xmlname = ""; string XmlnameF = ""; //string empleado = ""; Ruta = UsuarioActual.Empresa.Ruta; PathXML = $"{Ruta}XML\\Nomina\\{ObjNomina.SerieFolio}.xml"; PathXMLF = $"{Ruta}XML\\Nomina\\{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; Xmlname = $"{ObjNomina.SerieFolio}.xml"; XmlnameF = $"{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; objarch.Add(new ClsSisMail.ArchivoMail() { ArchivoBinario = pdf, NombreArchivo = $"{ObjNomina.SerieFolio}.pdf" }); if (!string.IsNullOrEmpty(PathXML) && System.IO.File.Exists(PathXML)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXML, NombreArchivo = Xmlname }); } if (!string.IsNullOrEmpty(PathXMLF) && System.IO.File.Exists(PathXMLF)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXMLF, NombreArchivo = XmlnameF }); } } } Mail.SendMail(UsuarioActual.Empresa, Correo.Trim(), string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy}", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), "", "", objarch); using (ClsRH objrh = new ClsRH()) { objrh.NomBitacoraCorreoAdd(CvePeriodoSeleccionado, CvePersonal, Correo.Trim(), UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario); } Alert(string.Format("se envio el correo a '{0}'.", Correo), TipoMensaje.MsgInformacion); } else { Alert("No se pudo generar el PDF para enviar el correo.", TipoMensaje.MsgAdvertencia); } } else { Alert("No se tiene un correo registrado.", TipoMensaje.MsgAdvertencia); } } protected void LnkTimbrar_Click(object sender, EventArgs e) { LinkButton lnk = (LinkButton)sender; GridViewRow gvRow = (GridViewRow)lnk.NamingContainer; int CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); int CveNomina = gvRow.DataKey("CveNomina").ToEntero(); string Msg = ""; Msg = TimprarPersonal(CvePeriodo, CvePersonal, CveNomina); if (Msg != null && Msg.Length > 0) { } else { gvRow.FindControl("ImgDelete").Visible = false; gvRow.FindControl("Imgdesautorizar").Visible = false; gvRow.FindControl("LnkCancelar").Visible = true; gvRow.FindControl("HypXml").Visible = true; gvRow.FindControl("HypPDF").Visible = true; gvRow.FCHyperLink("HypPDF").Attributes.Add("onclick", string.Format("GETPDF({0},{1})", CvePersonal, CvePeriodo)); gvRow.FCHyperLink("HypXml").Attributes.Add("onclick", string.Format("GETXML({0},{1})", CvePersonal, CvePeriodo)); gvRow.ForeColor = Color.Green; lnk.Visible = false; UpDatos.Update(); } } protected void LnkTimbrarB_Click(object sender, EventArgs e) { LinkButton lnk = (LinkButton)sender; GridViewRow gvRow = (GridViewRow)lnk.NamingContainer; int CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); int CveNomina = gvRow.DataKey("CveNomina").ToEntero(); string Msg = ""; Msg = TimprarPersonal(CvePeriodo, CvePersonal, CveNomina); if (Msg != null && Msg.Length > 0) { } else { //GVNominaPendiente.DeleteRow(gvRow.RowIndex); gvRow.FindControl("LnkTimbrarB").Visible = false; } } protected void GVNominaPendiente_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { int cvePersonal = e.Row.DataKey("CvePersonal").ToEntero(); int CvePeriodo = e.Row.DataKey("CvePeriodo").ToEntero(); e.Row.FCHyperLink("HypXml").Attributes.Add("onclick", string.Format("GETXML({0},{1})", cvePersonal, CvePeriodo)); } } public string TimprarPersonal(int CvePeriodo, int CvePersonal, int CveNomina) { LogicNominas lognom = new LogicNominas(); ClsSisMail Mail = new ClsSisMail(); DataTable dtpersonal = new DataTable(); DataRow drow; string Correo = string.Empty; string NombreCompleto = string.Empty; string RFC = string.Empty; string CURP = string.Empty; using (ClsRH objrh = new ClsRH()) { objrh.GetPersonal(CvePersonal, UsuarioActual.CveEmpresa); dtpersonal = objrh.DtResultados.FiltraParametros("", "", new string[] { "CvePersonal", "Correo", "NombreCompleto" }); } if (dtpersonal.Rows.Count > 0 && (drow = dtpersonal.FiltroPrimero(string.Format("CvePersonal = {0}", CvePersonal))) != null) { Correo = drow["Correo"].ToString(); NombreCompleto = drow["NombreCompleto"].ToString(); //RFC = drow["RFC"].ToString(); //CURP = drow["CURP"].ToString(); } string Msg = "";// lognom.TimbrarNomina(CveNomina, CvePersonal, CvePeriodo, UsuarioActual, (UsuarioActual.CveUsuario == 100 ? 4 : 4)); Msg = lognom.TimbrarNomina(CveNomina, CvePersonal, CvePeriodo, UsuarioActual, CvePAC: 4, versionTimbre: VersionTimbradoEnum.Version4_0); if (Msg != null && Msg.Length > 0)//
{4}
{1} { Alert(string.Format("El empleado no se pudo timbrar, el sat nos devolvio el siguiente mensaje:
{1}", Msg, msgCorregidoSat(Msg, CvePersonal, RFC, CURP)), TipoMensaje.MsgAdvertencia); } else { ClsNominas ObjPeriodo = new ClsNominas(); ObjPeriodo.CambiaEstatusPeriodo(CvePeriodo, (int)enumNominasEstatus.Timbrada, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa); ObjPeriodo.Dispose(); if (enviarCorreoEnTimbrado && Correo.Trim().Length > 0) { byte[] pdf = GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); if (pdf != null) { List objarch = new List(); using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodo, -1, UsuarioActual.CveEmpresa)) { string Ruta = ""; string PathXML = ""; string PathXMLF = ""; string Xmlname = ""; string XmlnameF = ""; //string empleado = ""; Ruta = UsuarioActual.Empresa.Ruta; PathXML = $"{Ruta}XML\\Nomina\\{ObjNomina.SerieFolio}.xml"; PathXMLF = $"{Ruta}XML\\Nomina\\{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; Xmlname = $"{ObjNomina.SerieFolio}.xml"; XmlnameF = $"{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; objarch.Add(new ClsSisMail.ArchivoMail() { ArchivoBinario = pdf, NombreArchivo = $"{ObjNomina.SerieFolio}.pdf" }); if (!string.IsNullOrEmpty(PathXML) && System.IO.File.Exists(PathXML)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXML, NombreArchivo = Xmlname }); } if (!string.IsNullOrEmpty(PathXMLF) && System.IO.File.Exists(PathXMLF)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXMLF, NombreArchivo = XmlnameF }); } } } Mail.SendMail(UsuarioActual.Empresa, Correo.Trim(), string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy}", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), "", "", objarch); using (ClsRH objrh = new ClsRH()) { objrh.NomBitacoraCorreoAdd(CvePeriodoSeleccionado, CvePersonal, Correo.Trim(), UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario); } } } Alert("Se ha timbrado correctamente"); } return Msg; } protected void Imgdesautorizar_Click(object sender, EventArgs e) { int Cve = ((LinkButton)sender).CommandArgument.ToEntero(); //LinkButton lnk = (LinkButton)sender; //GridViewRow gvRow = (GridViewRow)lnk.NamingContainer; //int CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); //int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); desAutorizarNomina(Cve); } protected bool desAutorizarNomina(int CveNomina) { bool continuar = true; using (ClsNominas Nom = new ClsNominas()) { Nom.IniciaTransacSQL(); //AutorizaNom_Nominas if (continuar && (continuar = Nom.RemoveNom_Nominas(CveNomina, false, UsuarioActual.CveUsuario))) { Nom.Commit(); } } if (continuar) { Alert("La nomina a sido desautorizada", TipoMensaje.MsgInformacion); cargaDatos(); } return continuar; } protected void ImgDelete_Click(object sender, EventArgs e) { int Cve = ((LinkButton)sender).CommandArgument.ToEntero(); //LinkButton lnk = (LinkButton)sender; //GridViewRow gvRow = (GridViewRow)lnk.NamingContainer; //int CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); //int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); eliminarNomina(Cve); } protected bool eliminarNomina(int CveNomina) { bool continuar = true; using (ClsNominas Nom = new ClsNominas()) { Nom.IniciaTransacSQL(); //AutorizaNom_Nominas if (continuar && (continuar = Nom.RemoveNom_Nominas(CveNomina, true, UsuarioActual.CveUsuario))) { Nom.Commit(); } } if (continuar) { Alert("Los movimientos de la nómina fueron eliminados", TipoMensaje.MsgInformacion); cargaDatos(); } return continuar; } protected int CveNominaCancelar { get { if (ViewState["CveNominaCancelar"] == null) { return 0; } else { return ViewState["CveNominaCancelar"].ToString().ToEntero(); } } set { ViewState["CveNominaCancelar"] = value; } } protected void LnkCancelar_Click(object sender, EventArgs e) { int CveNomina = ((LinkButton)sender).CommandArgument.ToEntero(); CveNominaCancelar = CveNomina; DdlMotivoCancelacion.DataSource = get_GlobalDTMotivosCancelacionEmpresa(UsuarioActual.CveEmpresa).FiltraParametros("CveSATMotivoCancelacion IN (2,3)"); DdlMotivoCancelacion.DataBind(); UpCancelarDocumento.Update(); RegistraScript("$('#ModalCancelarDocumento').modal()"); } protected void BtnCancelarDocumento_Click(object sender, EventArgs e) { int CveNomina = CveNominaCancelar; if (CveNomina > 0) { DdlMotivoCancelacion.Items.Insert(0, new ListItem("Seleccione", "-1")); using (ClsNominas Nom = new ClsNominas()) { if (Nom.GetNom_Nominas(CveNomina, -1, -1, -1, UsuarioActual.CveEmpresa)) { Timbrado ObjTimbrado = new Timbrado(); DataRow nrow = Nom.DtResultados.Rows[0]; bool secancelo11 = false; bool secancelo12 = false; string FolioFiscal = Nom.FolioFiscal; decimal Total = Nom.Total.ToString().ToDecimal(); string RFCReceptor = Nom.RFC; string RFCEmisor = UsuarioActual.Empresa.RFC; string SerieFolio = Nom.SerieFolio; string SerieFolioFiniquito = string.Format("{0}F-{1}", nrow["Serie"], nrow["Folio"]); bool SeTimbroFiniquito = nrow["SeTimbroFiniquito"].ToString().ToUpper().Contiene(new string[] { "1", "TRUE" }); string FolioFiscalFiniquito = nrow["FolioFiscalFiniquito"].ToString(); //SeTimbroFiniquito,N.FolioFiscalFiniquito DataRow rowc = get_GlobalDTMotivosCancelacionEmpresa(UsuarioActual.CveEmpresa).FiltroPrimero(string.Format("CveMotivoCancelacion={0}", DdlMotivoCancelacion.SelectedValue)); int CveMotivoCancelacion = -1; if (rowc != null) { CveMotivoCancelacion = rowc["CveSATMotivoCancelacion"].ToString().ToEntero(); } var reultado = ObjTimbrado.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, Total, RFCReceptor, RFCEmisor, 4, CveSATMotivoCancelacion: CveMotivoCancelacion); string.Format("CveNomina:{0},RFC{3}, FolioFiscal:{1},Resultado :{2}", CveNomina, FolioFiscal, Newtonsoft.Json.JsonConvert.SerializeObject(reultado), RFCReceptor).GuardaLog(); if (reultado.Verificado)//,CveSATMotivoCancelacion:= { try { string ruta = string.Format("{0}XML\\Nomina\\", UsuarioActual.Empresa.Ruta); string archivo = string.Format("{0}{1}.xml", ruta, SerieFolio); int contador = 1; string archivonew = string.Format("{0}{1}_{2}.xml", ruta, SerieFolio, contador++); while (System.IO.File.Exists(archivonew)) { archivonew = string.Format("{0}{1}_{2}.xml", ruta, SerieFolio, contador++); } File.Move(archivo, archivonew); } catch (Exception) { Alert("Ocurrió un error al mover el archivo fiscal cancelado"); } secancelo11 = true; } else { string.Format("Error al cancelar nomina {0}", FolioFiscal).GuardaLog(); //ObjTimbrado.MensajeErrorCFDI.GuardaLog(); } if (!SeTimbroFiniquito) { secancelo12 = true; } else { reultado = ObjTimbrado.CFDICancelar(UsuarioActual.Empresa, FolioFiscalFiniquito, Total, RFCReceptor, RFCEmisor, 4, CveSATMotivoCancelacion: CveMotivoCancelacion); string.Format("CveNomina:{0},RFC{3}, FolioFiscal:{1},Resultado :{2}", CveNomina, FolioFiscal, Newtonsoft.Json.JsonConvert.SerializeObject(reultado), RFCReceptor).GuardaLog(); if (reultado.Verificado)//,CveSATMotivoCancelacion:= { try { string ruta = string.Format("{0}XML\\Nomina\\", UsuarioActual.Empresa.Ruta); string archivo = string.Format("{0}{1}.xml", ruta, SerieFolioFiniquito); int contador = 1; string archivonew = string.Format("{0}{1}_{2}.xml", ruta, SerieFolioFiniquito, contador++); while (System.IO.File.Exists(archivonew)) { archivonew = string.Format("{0}{1}_{2}.xml", ruta, SerieFolioFiniquito, contador++); } File.Move(archivo, archivonew); } catch (Exception) { Alert("Ocurrió un error al mover el archivo fiscal cancelado"); } secancelo12 = true; } else { string.Format("Error al cancelar nomina {0}", FolioFiscalFiniquito).GuardaLog(); //ObjTimbrado.MensajeErrorCFDI.GuardaLog(); } } if (secancelo11 && secancelo12) { Nom.UpdateEstatusNomNominas(2, UsuarioActual.Empresa.CvePAC, "", ("01/01/2000").ToDate(), ("01/01/2000").ToDate(), CveNomina); Alert($"La nómina con folio fiscal '{FolioFiscal}' fue cancelada ante el SAT", TipoMensaje.MsgInformacion); } else { Alert($"no se pudo cancelar el folio fiscal
{ObjTimbrado.MensajeErrorCFDI}", TipoMensaje.MsgAdvertencia); } } } cargaDatos(); } RegistraScript("$('#ModalCancelarDocumento').modal('hide')"); } protected void LnkModalPlantillaNomina_Click(object sender, EventArgs e) { RegistraScript("$('#DModalNominas').modal();"); using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetConceptos(UsuarioActual.CveEmpresa)) { GVConceptosPlantilla.DataSource = ObjNomina.DtResultados.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa}"); GVConceptosPlantilla.DataBind(); } } UpCargarNomina.Update(); } protected void LnkCargaNetos_Click(object sender, EventArgs e) { using (ClsNominas onom = new ClsNominas()) { if (onom.GetConceptos(UsuarioActual.CveEmpresa)) { ddlConceptocomisionNeto.DataSource = onom.DtResultados.FiltraParametros("CveSATConcepto=56"); ddlConceptocomisionNeto.DataBind(); ddlConceptocomisionNeto.SelectedValueExist(onom.DtResultados.FiltroPrimeroValor("CveConcepto", "CveSistema=-2")); } } uppanelnetos.Update(); RegistraScript("$('#DmodalNetos').modal();"); } protected void LnkCargarNominaNetos_Click(object sender, EventArgs e) { LnkCargarNomina_Click(sender, e); } protected void LnkFormatoNetos_Click(object sender, EventArgs e) { try { StringBuilder str = new StringBuilder("0"); bool continuar = false; using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetConceptos(UsuarioActual.CveEmpresa)) { GVConceptosPlantilla.DataSource = ObjNomina.DtResultados.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa}"); GVConceptosPlantilla.DataBind(); foreach (DataRow gvrow in ObjNomina.DtResultados.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa} AND CveSistema =-1").Rows) { if (gvrow["CveConcepto"].ToEntero() > 0) { str.AppendFormat(",{0}", gvrow["CveConcepto"]); continuar = true; } } } } string msgerror = "Debe seleccionar los conceptos a cargar."; if (dtConceptos == null || dtConceptos.Columns.Count <= 2) { msgerror = "Debe cargar el periodo antes de descargar la plantilla"; continuar = false; } if (continuar) { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("Nomina"); int column = 1; libro.Row(1).Hide(); libro.Cell(1, column).Value = "Codigo"; libro.Cell(3, column).Value = "Codigo"; column++; libro.Cell(1, column).Value = "Empleado"; libro.Cell(3, column).Value = "Empleado"; libro.Column(column).Width = 35; DataTable dtcP = dtConceptos.FiltraParametros(string.Format("Tipo = 'P' AND EsPadre = 1 AND CveConcepto in({0})", str)); DataTable dtcD = dtConceptos.FiltraParametros(string.Format("Tipo = 'D' AND EsPadre = 1 AND CveConcepto in({0})", str)); DataTable dtcO = dtConceptos.FiltraParametros(string.Format("Tipo = 'O' AND EsPadre = 1 AND CveConcepto in({0})", str)); int iniciotipe = column; foreach (DataRow row in dtcP.Rows) { column++; libro.Cell(1, column).Value = row["CveConcepto"].ToString(); libro.Cell(FilaConceptos, column).Value = "S"; libro.Cell(3, column).Value = row["Concepto"].ToString(); libro.Cell(4, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; } if (iniciotipe < column) { libro.Range(2, iniciotipe + 1, 2, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(2, iniciotipe + 1, 2, column).Merge().Value = "-"; } iniciotipe = column; foreach (DataRow row in dtcD.Rows) { column++; libro.Cell(1, column).Value = row["CveConcepto"].ToString(); libro.Cell(FilaConceptos, column).Value = "S"; libro.Cell(3, column).Value = row["Concepto"].ToString(); libro.Cell(4, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; } if (iniciotipe < column) { libro.Range(2, iniciotipe + 1, 2, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(2, iniciotipe + 1, 2, column).Merge().Value = "-"; } iniciotipe = column; foreach (DataRow row in dtcO.Rows) { column++; libro.Cell(1, column).Value = row["CveConcepto"].ToString(); libro.Cell(FilaConceptos, column).Value = "S"; libro.Cell(3, column).Value = row["Concepto"].ToString(); libro.Cell(4, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; } if (iniciotipe < column) { libro.Range(2, iniciotipe + 1, 2, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(2, iniciotipe + 1, 2, column).Merge().Value = "-"; } libro.Range(2, 1, 2, 2).Merge().Value = ""; libro.Range(4, 1, 4, 2).Merge().Value = ""; libro.Range(2, 1, 2, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(4, 1, 4, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(1).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(2).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(3).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(4).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(FilaConceptos).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(1).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(2).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(3).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(4).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); //libro.Row(FilaConceptos).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Cell(FilaConceptos, 1).Value = "'-------"; libro.Cell(FilaConceptos, 1).Style.Font.FontColor = ClosedXML.Excel.XLColor.FromArgb(177, 160, 199); libro.Cell(FilaConceptos, 2).Value = "¿Modificar SI(S)/NO(N)?"; libro.Cell(FilaConceptos, 1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(177, 160, 199)); libro.Row(FilaConceptos).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(177, 160, 199)); int Fila = 5; foreach (DataRow erow in dtempleados.FiltraParametros("CvePersonal>0 AND NomAutorizado=0").Rows) { Fila++; column = 1; libro.Cell(Fila, column).Value = string.Format("'{0}", erow["Codigo"]); column++; libro.Cell(Fila, column).Value = erow["Nombre"]; foreach (DataRow row in dtcP.Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; } foreach (DataRow row in dtcD.Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; } foreach (DataRow row in dtcO.Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; } } 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", "Plantilla conceptos nómina ")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } else { Alert(msgerror, TipoMensaje.MsgAdvertencia); } } catch (Exception ex) { Alert("Ocurrio un error al generar el Formato de nominas" + ex.ToString(), TipoMensaje.MsgAdvertencia); } } protected void LnkFormato_Click(object sender, EventArgs e) { try { StringBuilder str = new StringBuilder("0"); bool continuar = false; foreach (GridViewRow gvrow in GVConceptosPlantilla.Rows) { if (gvrow.DataKey("CveConcepto").ToEntero() > 0 && gvrow.FCCheckBox("chkCon").Checked) { str.AppendFormat(",{0}", gvrow.DataKey("CveConcepto")); continuar = true; } } string msgerror = "Debe seleccionar los conceptos a cargar."; if (dtConceptos == null || dtConceptos.Columns.Count <= 2) { msgerror = "Debe cargar el periodo antes de descargar la plantilla"; continuar = false; } if (continuar) { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("Nomina"); int column = 1; libro.Row(1).Hide(); libro.Cell(1, column).Value = "Codigo"; libro.Cell(3, column).Value = "Codigo"; column++; libro.Cell(1, column).Value = "Empleado"; libro.Cell(3, column).Value = "Empleado"; libro.Column(column).Width = 35; DataTable dtcP = dtConceptos.FiltraParametros(string.Format("Tipo = 'P' AND EsPadre = 1 AND CveConcepto in({0})", str)); DataTable dtcD = dtConceptos.FiltraParametros(string.Format("Tipo = 'D' AND EsPadre = 1 AND CveConcepto in({0})", str)); DataTable dtcO = dtConceptos.FiltraParametros(string.Format("Tipo = 'O' AND EsPadre = 1 AND CveConcepto in({0})", str)); int iniciotipe = column; foreach (DataRow row in dtcP.Rows) { column++; libro.Cell(1, column).Value = row["CveConcepto"].ToString(); libro.Cell(FilaConceptos, column).Value = "S"; libro.Cell(3, column).Value = row["Concepto"].ToString(); libro.Cell(4, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; } if (iniciotipe < column) { libro.Range(2, iniciotipe + 1, 2, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(2, iniciotipe + 1, 2, column).Merge().Value = "Percepciones"; } iniciotipe = column; foreach (DataRow row in dtcD.Rows) { column++; libro.Cell(1, column).Value = row["CveConcepto"].ToString(); libro.Cell(FilaConceptos, column).Value = "S"; libro.Cell(3, column).Value = row["Concepto"].ToString(); libro.Cell(4, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; } if (iniciotipe < column) { libro.Range(2, iniciotipe + 1, 2, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(2, iniciotipe + 1, 2, column).Merge().Value = "Deducciones"; } iniciotipe = column; foreach (DataRow row in dtcO.Rows) { column++; libro.Cell(1, column).Value = row["CveConcepto"].ToString(); libro.Cell(FilaConceptos, column).Value = "S"; libro.Cell(3, column).Value = row["Concepto"].ToString(); libro.Cell(4, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; } if (iniciotipe < column) { libro.Range(2, iniciotipe + 1, 2, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(2, iniciotipe + 1, 2, column).Merge().Value = "Obligaciones"; } libro.Range(2, 1, 2, 2).Merge().Value = ""; libro.Range(4, 1, 4, 2).Merge().Value = ""; libro.Range(2, 1, 2, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(4, 1, 4, 2).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(1).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(2).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(3).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(4).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(FilaConceptos).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(1).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(2).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(3).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Row(4).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); //libro.Row(FilaConceptos).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Cell(FilaConceptos, 1).Value = "'-------"; libro.Cell(FilaConceptos, 1).Style.Font.FontColor = ClosedXML.Excel.XLColor.FromArgb(177, 160, 199); libro.Cell(FilaConceptos, 2).Value = "¿Modificar SI(S)/NO(N)?"; libro.Cell(FilaConceptos, 1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(177, 160, 199)); libro.Row(FilaConceptos).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(177, 160, 199)); int Fila = 5; foreach (DataRow erow in dtempleados.FiltraParametros("CvePersonal>0 AND NomAutorizado=0").Rows) { Fila++; column = 1; libro.Cell(Fila, column).Value = string.Format("'{0}", erow["Codigo"]); column++; libro.Cell(Fila, column).Value = erow["Nombre"]; foreach (DataRow row in dtcP.Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; } foreach (DataRow row in dtcD.Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; } foreach (DataRow row in dtcO.Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; } } 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", "Plantilla conceptos nómina ")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } else { Alert(msgerror, TipoMensaje.MsgAdvertencia); } } catch (Exception ex) { Alert("Ocurrio un error al generar el Formato de nominas" + ex.ToString(), TipoMensaje.MsgAdvertencia); } } protected void LnkModalPlantillaNominaUnConc_Click(object sender, EventArgs e) { RegistraScript("$('#DModalNominasUnConcepto').modal();"); using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetConceptos(UsuarioActual.CveEmpresa)) { DdlUnConcepto.DataSource = ObjNomina.DtResultados.FiltraParametros($"CveEmpresa = {UsuarioActual.CveEmpresa}"); DdlUnConcepto.DataBind(); } } UpCargarNominaUnConcepto.Update(); } protected void LnkFormatoUnConcepto_Click(object sender, EventArgs e) { try { StringBuilder str = new StringBuilder("0"); bool continuar = true; str.AppendFormat(",{0}", DdlUnConcepto.SelectedValue.ToEntero()); string msgerror = ""; if (dtConceptos == null || dtConceptos.Columns.Count <= 2) { msgerror = "Debe cargar el periodo antes de descargar la plantilla"; continuar = false; } if (continuar) { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("Nomina"); int column = 1; libro.Cell(1, column).Value = "Codigo"; column++; libro.Cell(1, column).Value = "Empleado"; libro.Column(column).Width = 35; DataTable dtcP = dtConceptos.FiltraParametros(string.Format(" CveConcepto in({0})", str)); foreach (DataRow row in dtcP.Rows) { column++; libro.Cell(1, column).Value = string.Format("{0} - {1} - Valor", row["Codigo"], row["Concepto"]); column++; libro.Cell(1, column).Value = string.Format("{0} - {1} - Importe", row["Codigo"], row["Concepto"]); column++; libro.Cell(1, column).Value = string.Format("{0} - {1} - ImporteGravado", row["Codigo"], row["Concepto"]); } libro.Row(1).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Row(1).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); int Fila = 1; foreach (DataRow erow in dtempleados.FiltraParametros("CvePersonal>0 AND NomAutorizado=0").Rows) { Fila++; column = 1; libro.Cell(Fila, column).Value = string.Format("'{0}", erow["Codigo"]); column++; libro.Cell(Fila, column).Value = erow["Nombre"]; foreach (DataRow row in dtcP.Rows) { column++; string Concepto = string.Format("VAL_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; column++; Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; column++; Concepto = string.Format("VG_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; } } libro.Columns().AdjustToContents(); 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", "Plantilla conceptos nómina ")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } else { Alert(msgerror, TipoMensaje.MsgAdvertencia); } } catch (Exception ex) { Alert("Ocurrio un error al generar el Formato de nominas" + ex.ToString(), TipoMensaje.MsgAdvertencia); } } protected void LnkCargarNomina_Click(object sender, EventArgs e) { int chkImporteValor = 1; int chkImporte = 1; int chkImporteGravado = 0; List Filesgral = TxtArchivoNomina.getfiles().Archivos; if (((LinkButton)sender).ID == LnkCargarNominaNetos.ID) { Filesgral = TxtCargarNetos.getfiles().Archivos; using (ClsNominas objbase = new ClsNominas()) { objbase.ConceptosCveSistemaUp(ddlConceptocomisionNeto.SelectedValue.ToEntero(), -2, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa); } } bool continuar = Filesgral.Count > 0; string stringError = ""; Archivo fileItem = continuar ? Filesgral[0] : null; if (continuar) { string FileExtension = fileItem.Extension.ToUpper(); if (FileExtension == "XLS" | FileExtension == "XLSX" | FileExtension == "CSV") { } else { continuar = false; stringError = "No se inserto un archivo de tipo Excel"; } } else { stringError = "favor de ingresar el archivo y esperar a que cargue"; } if (!(CvePeriodoSeleccionado >= 0)) { continuar = false; stringError = "debe cargar el periodo a actualizar"; } DataTable DTEXcel = new DataTable(); if (continuar) { try { DataTable dtxz = Extensiones.ModExtensiones.ReadExcelFile(fileItem.FileUrl, true); if (dtxz.Rows.Count > 2) { DataRow drowx = dtxz.Rows[2]; for (int i = 2; i < dtxz.Columns.Count; i++) { //para evitar errores agrego una columna al inicio dtxz.Columns[i].ColumnName = string.Format("Z{0}", dtxz.Columns[i].ColumnName.ToUpper()); } for (int i = 2; i < dtxz.Columns.Count; i++) { // string conceptocodigo = drowx[i].ToString(); string CveConcepto; DataRow dconr = dtConceptos.FiltroPrimero(string.Format("codigo='{0}'", conceptocodigo)); if (dconr != null) { CveConcepto = dconr["CveConcepto"].ToString(); if (dtxz.Columns.Contains(CveConcepto)) { stringError = string.Format("Ocurrio un Error al procesar el excel código duplicado '{0}'({1}).", conceptocodigo, i); } else { dtxz.Columns[i].ColumnName = CveConcepto; } } else { continuar = false; stringError = string.Format("Ocurrio un Error al procesar el excel código no valido '{0}'({1}).", conceptocodigo, i); break; } //int CveConcepto = dtxz.Columns[i].ColumnName.ToEntero(); } } DTEXcel = dtxz.FiltraParametros(" LEN(Codigo)>0 AND Codigo <> 'Codigo'"); } catch (Exception ex) { continuar = false; stringError = "Ocurrio un Error al procesar el excel "; string.Format("{0} \r\n{0}", stringError, ex.ToString()).GuardaLog(); } } if (continuar && DTEXcel.Rows.Count == 0) { continuar = false; stringError = "No se encontraron cambios"; } StringBuilder str = new StringBuilder(); bool rollback = false; if (continuar) { int CveMoneda = 1; //List lConceptos = new List(); //foreach (DataColumn item in DTEXcel.Columns) //{ // if (item.ColumnName.ToEntero() > 0) // { // lConceptos.Add(item.ColumnName.ToEntero()); // } //} using (ClsRH objpersonal = new ClsRH()) { using (ClsNominas objNomina = new ClsNominas(objpersonal.IniciaTransacSQL())) { foreach (DataRow row in DTEXcel.FiltraParametros("LEN(Codigo)>0 ").Rows) { if (!rollback) { string Codigo = row["Codigo"].ToString(); int CvePersonal = -1; // row["CvePersonal"].ToString().ToEntero(); int CveNomina = 0; double SubTotal = 0; double Total = 0; int CveMetodoPago = 0; if (Codigo != "-1" && objpersonal.GetPersonal(CvePersonal, Codigo, "-1", "-1", "-1", -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, "-1", -1, -1, -1, -1, -1, -1, "-1", "-1", "-1", "-1", UsuarioActual.CveEmpresa) && objpersonal.DtResultados.Rows.Count == 1) { CvePersonal = objpersonal.CvePersonal; CveMetodoPago = objpersonal.CveMetodoPago; } else { CvePersonal = 0; str.AppendLine(string.Format("No se encontro el codigo {0}
", Codigo)); } if (CvePersonal > 0) { if (objNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodoSeleccionado, -1, UsuarioActual.CveEmpresa)) { if (objNomina.DtResultados.Rows.Count > 0) { CveNomina = objNomina.CveNomina; } else { if (objNomina.AddNom_Nominas(-1, 1, CvePersonal, CvePeriodoSeleccionado, SubTotal, 0, 0, Total, CveMoneda, 1, CveMetodoPago, NowADS(), "Deducciones nómina", "", "", "", "", 0, 0, 0, new DateTime(), new DateTime(), new DateTime(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, false)) { CveNomina = objNomina.CveNomina; } else { rollback = true; } } } else { rollback = true; } } if (CveNomina > 0) { for (int i = 2; i < DTEXcel.Columns.Count; i++) { int CveConcepto = DTEXcel.Columns[i].ColumnName.ToEntero(); decimal Importe = 0; decimal ImporteGravado = 0; decimal ImporteExento = 0; decimal ImporteValor = 0; bool dontsaveconcepto = ((row[i].ToString().ToUpper() == "N") || (DTEXcel.Rows[0][i].ToString().ToUpper() == "N")); Importe = row[i].ToString().ToDecimal(); ImporteGravado = Importe - ImporteExento; ImporteValor = 0; if (CveConcepto > 0) { if (!dontsaveconcepto)//el usuario definira si desea actualizar o no el concepto en el periodo { if (!objNomina.AddUPNom_NominasDetalles(objNomina.CveNomina, CvePeriodoSeleccionado, CvePersonal, CveConcepto, Importe, ImporteGravado, ImporteExento, ImporteValor, UsuarioActual.CveUsuario, true, chkImporte, chkImporteGravado, chkImporteValor, false)) { rollback = true; } } } else { rollback = false; stringError = "ocurrio un error al procesar el archivo favor de intentar de nuevo volviendo a descargar la plantilla.
si el problema Persiste Contacte a soporte."; } } } } } if (rollback) { objpersonal.RollBack(); continuar = false; } else { objpersonal.Commit(); } } } } if (!continuar) { Alert(stringError, ModExtensiones.TipoMensaje.MsgAdvertencia); } else { Alert("La información se a actualizado satisfactoriamente"); if (((LinkButton)sender).ID == LnkCargarNominaNetos.ID || ChkRecalcularNomina.Checked) { cargaDatos(false); } } } protected void LnkFormatoEmpleados_Click(object sender, EventArgs e) { } #region SobreRecibo protected void LnkAutorizarSobreRecibo_Click(object sender, EventArgs e) { cargaDatos(false, -1); autorizarNomina(SRCvePersonal); showhideaccionesSR(true); } protected void LnkTimbrarSobreRecibo_Click(object sender, EventArgs e) { DataRow dr = dtempleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); string Msg = TimprarPersonal(dr["CvePeriodo"].ToString().ToEntero(), SRCvePersonal, dr["CveNomina"].ToString().ToEntero()); if (Msg != null && Msg.Length > 0) { } else { showhideaccionesSR(true); } } protected void LnkdesautorizarSobreRecibo_Click(object sender, EventArgs e) { DataRow dr = dtempleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); if (desAutorizarNomina(dr["CveNomina"].ToString().ToEntero())) { cargaDatos(false, -1); dtPerEmpleados = dtempleados.FiltraParametros(string.Format("CvePersonal = {0}", SRCvePersonal)); dtPerEmpleadosConceptos = dtempleadosConceptos.FiltraParametros(string.Format("CvePersonal = {0}", SRCvePersonal)); dtPerConceptos = dtConceptos; dtPerPeriodo = dtPeriodos; showhideaccionesSR(false); } }//Imgdesautorizar protected void LnkDeleteSobreRecibo_Click(object sender, EventArgs e) { DataRow dr = dtempleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); if (eliminarNomina(dr["CveNomina"].ToString().ToEntero())) { showhideaccionesSR(false); } }//ImgDelete protected void LnkReenviarCorreoSobreRecibo_Click(object sender, EventArgs e) { //string msggral = ""; int CvePeriodo = 0; ClsSisMail Mail = new ClsSisMail(); DataTable dtpersonal = new DataTable(); DataRow drow; using (ClsRH objrh = new ClsRH()) { objrh.GetPersonal(-1, UsuarioActual.CveEmpresa); dtpersonal = objrh.DtResultados.FiltraParametros("", "", new string[] { "CvePersonal", "Correo", "NombreCompleto" }); } using (ClsRH objrh = new ClsRH()) using (ClsNominas ObjNomina = new ClsNominas()) { foreach (GridViewRow gvRow in GvNominas.Rows) { CvePeriodo = gvRow.DataKey("CvePeriodo").ToEntero(); int CvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); int CveNomina = gvRow.DataKey("CveNomina").ToEntero(); int SeTimbro = (gvRow.DataKey("SeTimbro").ToUpper() == "TRUE" ? 1 : gvRow.DataKey("SeTimbro").ToEntero()); LinkButton LnkTimbrar = gvRow.FCLinkButton("LnkTimbrar"); string Correo = string.Empty; string NombreCompleto = string.Empty; if (dtpersonal.Rows.Count > 0 && (drow = dtpersonal.FiltroPrimero(string.Format("CvePersonal = {0}", CvePersonal))) != null) { Correo = drow["Correo"].ToString(); NombreCompleto = drow["NombreCompleto"].ToString(); } if (CvePersonal == SRCvePersonal && SeTimbro == 1) { if (Correo.Trim().Length > 0) { byte[] pdf = GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); if (pdf != null) { List objarch = new List(); if (ObjNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodo, -1, UsuarioActual.CveEmpresa)) { string Ruta = ""; string PathXML = ""; string PathXMLF = ""; string Xmlname = ""; string XmlnameF = ""; //string empleado = ""; Ruta = UsuarioActual.Empresa.Ruta; PathXML = $"{Ruta}XML\\Nomina\\{ObjNomina.SerieFolio}.xml"; PathXMLF = $"{Ruta}XML\\Nomina\\{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; Xmlname = $"{ObjNomina.SerieFolio}.xml"; XmlnameF = $"{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; objarch.Add(new ClsSisMail.ArchivoMail() { ArchivoBinario = pdf, NombreArchivo = $"{ObjNomina.SerieFolio}.pdf" }); //this.GuardaLog(PathXML); if (!string.IsNullOrEmpty(PathXML) && System.IO.File.Exists(PathXML)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXML, NombreArchivo = Xmlname }); } if (!string.IsNullOrEmpty(PathXMLF) && System.IO.File.Exists(PathXMLF)) { objarch.Add(new ClsSisMail.ArchivoMail() { Ruta = PathXMLF, NombreArchivo = XmlnameF }); } } Mail.SendMail(UsuarioActual.Empresa, Correo.Trim(), string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy}", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), "", "", objarch); // Mail.SendMail(ClsPaginas.EmpresaNotificaciones, "caudillo.90d@gmail.com", string.Format("Empleado {0} Nomina del {1:dd/MM/yyyy} al {2:dd/MM/yyyy} ", NombreCompleto, FechaInicioPeriodo, FechaFinPeriodo), Correo.Trim(), "", objarch); objrh.NomBitacoraCorreoAdd(CvePeriodoSeleccionado, CvePersonal, Correo.Trim(), UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario); } } } } } Alert("se reenvió el recibos timbrados"); } protected void LnkCancelarSobreRecibo_Click(object sender, EventArgs e) { DataRow dr = dtempleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); CveNominaCancelar = dr["CveNomina"].ToString().ToEntero(); DdlMotivoCancelacion.DataSource = get_GlobalDTMotivosCancelacionEmpresa(UsuarioActual.CveEmpresa).FiltraParametros("CveSATMotivoCancelacion IN (2,3)"); DdlMotivoCancelacion.DataBind(); UpCancelarDocumento.Update(); RegistraScript("$('#ModalCancelarDocumento').modal()"); //showhideaccionesSR(true); } public void showhideaccionesSR(bool cargadatos = false) { if (cargadatos) { cargaDatos(CvePersonal: SRCvePersonal); dtPerEmpleados = dtempleados.FiltraParametros(string.Format("CvePersonal = {0}", SRCvePersonal)); dtPerEmpleadosConceptos = dtempleadosConceptos.FiltraParametros(string.Format("CvePersonal = {0}", SRCvePersonal)); dtPerConceptos = dtConceptos; dtPerPeriodo = dtPeriodos; } DataRow dr = dtPerEmpleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); NomAutorizado = dr["NomAutorizado"].ToString().ToUpper().Contiene(new string[] { "1", "TRUE" }); LnkCancelarSobreRecibo.Visible = dr["SeTimbro"].ToString().ToUpper().Contiene("TRUE", "1"); LnkDeleteSobreRecibo.Visible = dr["CveNomina"].ToString().ToEntero() > 0 && !LnkCancelarSobreRecibo.Visible; LnkAutorizarSobreRecibo.Visible = !dr["NomAutorizado"].ToString().ToUpper().Contiene("TRUE", "1"); LnkdesautorizarSobreRecibo.Visible = dr["NomAutorizado"].ToString().ToUpper().Contiene("TRUE", "1") && !LnkCancelarSobreRecibo.Visible; LnkReenviarCorreoSobreRecibo.Visible = LnkCancelarSobreRecibo.Visible; HyppdfSobreRecibo.Visible = LnkCancelarSobreRecibo.Visible || UsuarioActual.CveRol == 1; HypXmlSobreRecibo.Visible = LnkCancelarSobreRecibo.Visible || UsuarioActual.CveRol == 1; LnkTimbrarSobreRecibo.Visible = !LnkCancelarSobreRecibo.Visible && dr["NomAutorizado"].ToString().ToUpper().Contiene("TRUE", "1"); } #region SobreRecibo propiedades protected int CveFonacot { get { if (ViewState["CveFonacot"] == null) { return 0; } else { return ViewState["CveFonacot"].ToString().ToEntero(); } } set { ViewState["CveFonacot"] = value; } } protected int SRCvePersonal { get { if (ViewState["SRCvePersonal"] == null) { return 0; } else { return ViewState["SRCvePersonal"].ToString().ToEntero(); } } set { ViewState["SRCvePersonal"] = value; } } protected int SRCvePeriodo { get { if (ViewState["SRCvePeriodo"] == null) { return 0; } else { return ViewState["SRCvePeriodo"].ToString().ToEntero(); } } set { ViewState["SRCvePeriodo"] = value; } } protected int SRCveConcepto { get { if (ViewState["SRCveConcepto"] == null) { return 0; } else { return ViewState["SRCveConcepto"].ToString().ToEntero(); } } set { ViewState["SRCveConcepto"] = value; } } protected string SRTipoConcepto { get { if (ViewState["SRTipoConcepto"] == null) { return ""; } else { return ViewState["SRTipoConcepto"].ToString(); } } set { ViewState["SRTipoConcepto"] = value; } } protected bool NomAutorizado { get { if (ViewState["NomAutorizado"] == null) { return false; } else { return (bool)ViewState["NomAutorizado"]; } } set { ViewState["NomAutorizado"] = value; } } #endregion protected void LnkSobreRecibo_Click(object sender, EventArgs e) { SRCvePersonal = TxtCvePersonal.Text.ToEntero(); //GridViewRow gvrow = (GridViewRow)(((LinkButton)sender).NamingContainer); TxtVacDiasPago.Text = "0"; LnkSRVacacionesADD.Visible = false; dtPerEmpleados = dtempleados.FiltraParametros(string.Format("CvePersonal = {0}", SRCvePersonal)); dtPerEmpleadosConceptos = dtempleadosConceptos.FiltraParametros(string.Format("CvePersonal = {0}", SRCvePersonal)); dtPerConceptos = dtConceptos; dtPerPeriodo = dtPeriodos; if (DdlCtaContable.Items.Count == 0) { if (UsuarioActual.Empresa.TipoContabilidad == 1) { using (ClsContabilidad ObjConta = new ClsContabilidad()) { if (ObjConta.GetCuentas(-1, "-1", 1, UsuarioActual.CveEmpresa)) { DdlCtaContable.DataSource = ObjConta.DtResultados; DdlCtaContable.DataBind(); } } } else { using (ClsContPAQi ObjConta = new ClsContPAQi(UsuarioActual.Empresa)) { if (ObjConta.Conectado && ObjConta.GetCuentas(-1, "-1", 1)) { DdlCtaContable.DataValueField = "Id"; DdlCtaContable.DataSource = ObjConta.DtResultados; DdlCtaContable.DataBind(); } } } DdlCtaContable.Items.Insert(0, new ListItem("Seleccione", "-1")); DdlCtaContable.SelectedValueExist("-1"); } //SRCvePersonal = gvrow.DataKey("CvePersonal").ToEntero(); //string Nombre = gvrow.DataKey("Nombre").ToString(); //SRCvePeriodo = gvrow.DataKey("CvePeriodo").ToEntero(); //int CveNomina = gvrow.DataKey("CveNomina").ToEntero(); //NomAutorizado = gvrow.DataKey("NomAutorizado").ToUpper().Contiene(new string[] { "1", "TRUE" }); showhideaccionesSR(); HypXmlSobreRecibo.Attributes.Add("onclick", string.Format("GETXML({0},{1})", SRCvePersonal, CvePeriodoSeleccionado)); HyppdfSobreRecibo.Attributes.Add("onclick", string.Format("GETPDF({0},{1})", SRCvePersonal, CvePeriodoSeleccionado)); DataRow drow = dtPerEmpleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); string Nombre = ""; SRCvePeriodo = 0; int CveNomina = 0; NomAutorizado = false; if (drow != null) { Nombre = drow["Nombre"].ToString(); SRCvePeriodo = drow["CvePeriodo"].ToString().ToEntero(); CveNomina = drow["CveNomina"].ToString().ToEntero(); NomAutorizado = drow["NomAutorizado"].ToString().ToUpper().Contiene(new string[] { "1", "TRUE" }); } cargaBitacora(); using (ClsNominas nom = new ClsNominas()) { if (nom.GetNom_Nominas(CveNomina, SRCvePersonal, SRCvePeriodo, -1, UsuarioActual.CveEmpresa) && nom.DtResultados.Rows.Count > 0) { DataRow drownom = nom.DtResultados.Rows[0]; ChkMetodoPago.Checked = drownom["MetodoPagoFijo"].ToString().ToUpper().Contiene(new string[] { "1", "TRUE" }); DdlMetodoPago.SelectedValueExist(drownom["CveMetodoPago"].ToString()); DdlBanco.SelectedValueExist(drownom["CveSATBanco"].ToString()); TxtBancoNumCuenta.Text = drownom["BancoNumCuenta"].ToString(); TxtCLABE.Text = drownom["CLABE"].ToString(); } } using (ClsRH objrh = new ClsRH()) { string CodigoEmpleado = ""; string NombreCompleto = ""; string RFC = ""; string CURP = ""; string TipoPeriodo = ""; string NSS = ""; string Departamento = ""; string Puesto = ""; if (objrh.GetPersonal(SRCvePersonal, UsuarioActual.CveEmpresa) && objrh.DtResultados.Rows.Count > 0) { DataRow erow = objrh.DtResultados.Rows[0]; CodigoEmpleado = erow["Codigo"].ToString(); NombreCompleto = erow["NombreCompleto"].ToString(); RFC = erow["RFC"].ToString(); CURP = erow["CURP"].ToString(); TipoPeriodo = erow["TipoPeriodo"].ToString(); NSS = erow["NSS"].ToString(); Puesto = erow["Puesto"].ToString(); Departamento = erow["Departamento"].ToString(); } LblCodigoEmpleado.Text = CodigoEmpleado; LblRFC.Text = RFC; LblCURP.Text = CURP; LblTipoPeriodo.Text = TipoPeriodo; LblNSS.Text = NSS; LblSRDepartamento.Text = Departamento; LblSRPuesto.Text = Puesto; } LblEmpleado.Text = Nombre; LblEmpleado.NavigateUrl = string.Format("/RH/Personal.aspx?CvePersonal={0}", SRCvePersonal); TabPersonal.ActiveTabIndex = 0; DdlTipoAsistenciasB.DataSource = get_GlobalDTAsistenciasInasistencias(UsuarioActual.CveEmpresa); DdlTipoAsistenciasB.DataBind(); cargaasistenciaSR(); mostrarConceptos(); CargaVacaciones(); pnlAddupMovto.Visible = false; CargaMovtoPermanente(); CargaPersonalIncapacidad(); RegistraScript("$('#ModalConceptos').modal();"); } #region Asistencias protected void LnkRecalcular_Click(object sender, EventArgs e) { cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); } protected void cargaasistenciaSR(string orden = "") { using (ClsRH objpersonal = new ClsRH()) { if (objpersonal.GetAsistencias(SRCvePersonal, -1, -1, -1, -1, -1, -1, FechaInicioPeriodo, FechaFinPeriodo, UsuarioActual.CveEmpresa)) { GVAsistencia.DataSource = objpersonal.DtResultados.FiltraParametros("Fecha IS NOT NULL"); } else { GVAsistencia.DataSource = null; } } GVAsistencia.DataBind(); } protected void LbOrden_Click(object sender, EventArgs e) { string Orden = ""; string Campo = ""; int gvi = 0; Literal Literal = null/* TODO Change to default(_) if this is not a reference type */; const string OrdenInicial = ""; string[] Arg = new string[3]; Arg = ((LinkButton)sender).CommandArgument.Split(';'); Campo = Arg[0]; gvi = Arg[1].ToEntero(); Literal = (Literal)((LinkButton)sender).NamingContainer.FindControl("Img" + Campo.Replace(",", "_")); Campo = Campo.Substring(0, Campo.Length - 1); if (ViewState[string.Format("O{0}", Campo, gvi)] != null && ViewState[string.Format("O{0}", Campo, gvi)].ToString() == string.Format("{0} DESC", Campo)) { ViewState[string.Format("O{0}", Campo)] = string.Format("{0} ASC", Campo); Literal.Text = string.Format(""); } else { ViewState[string.Format("O{0}", Campo, gvi)] = string.Format("{0} DESC", Campo); Literal.Text = string.Format(""); } Orden = OrdenInicial + ViewState[string.Format("O{0}", Campo, gvi)].ToString(); ViewState["Orden"] = Orden; cargaasistenciaSR(Orden); } protected void DdlTipoAsistencias_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; GridViewRow gvrow = (GridViewRow)ddl.NamingContainer; if (ddl.SelectedItem.Text == "Retardo") gvrow.FCTextBox("TxtPorPago").Text = "87.5"; } protected void LbGuardarAsistencia_Click(object sender, EventArgs e) { bool continuar = false; using (ClsRH ObjPersonal = new ClsRH()) { if (ObjPersonal.AddAsistencia(SRCvePersonal, -2, -2, TxtFechaAsistencia.Text.Trim().ToDate(), DdlTipoAsistenciasB.SelectedValue.ToEntero(), TxtPorPago.Text.Trim().ToDouble(), TxtHorasDobles.Text.Trim().ToDouble(), TxtHorasTriples.Text.Trim().ToDouble(), DdlMotivoHoraExtra.SelectedValue.ToEntero(), TxtObservaciones.Text.Trim(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "N")) { Alert("La Asistencia se guardó correctamente.", TipoMensaje.MsgInformacion); continuar = true; } } if (continuar) { cargaasistenciaSR(); LnkRecalcular_Click(null, null); } } protected void BtnGuardarAsistenciaCambios_Click(object sender, EventArgs e) { bool continuar = false; using (ClsRH ObjPersonal = new ClsRH()) { ObjPersonal.IniciaTransacSQL(); bool OcurrioError = false; foreach (GridViewRow Row in GVAsistencia.Rows) { if (!ObjPersonal.AddAsistencia(SRCvePersonal, -2, -2, Row.FCLiteral("LtlFecha").Text.Trim().ToDate(), Row.FCDropDownList("DdlTipoAsistencias").SelectedValue.ToEntero(), Row.FCTextBox("TxtPorPago").Text.Trim().ToDouble(), Row.FCTextBox("TxtHorasDobles").Text.Trim().ToDouble(), Row.FCTextBox("TxtHorasTriples").Text.Trim().ToDouble(), Row.FCDropDownList("DdlMotivoHoraExtra").SelectedValue.ToEntero(), Row.FCTextBox("TxtObservaciones").Text.Trim(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "O")) { OcurrioError = true; break; } } if (OcurrioError) { ObjPersonal.RollBack(); Alert("Ocurrió un error al guardar las Asistencias.", TipoMensaje.MsgError); } else { ObjPersonal.Commit(); continuar = true; Alert("Las Asistencias se guardaron correctamente.", TipoMensaje.MsgInformacion); } } if (continuar) { cargaasistenciaSR(); LnkRecalcular_Click(null, null); } } protected void GVAsistencia_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Left; e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left; e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Left; //if ((e.Row.DBCampo("Fecha"))) e.Row.FCLiteral("LtlFecha").Text = e.Row.DBCampo("Fecha").ToDate().ToShortDateString(); if (e.Row.FCLiteral("LtlCliente").Text != "N/A") e.Row.FCLiteral("LtlCliente").Text = "
" + e.Row.DBCampo("Cliente") + ""; e.Row.FCTextBox("TxtPorPago").Text = e.Row.DBCampo("PorcentajePago"); e.Row.FCTextBox("TxtHorasDobles").Text = e.Row.DBCampo("HorasDobles"); e.Row.FCTextBox("TxtHorasTriples").Text = e.Row.DBCampo("HorasTriples"); // Carga Tipos de Asistencia e.Row.FCDropDownList("DdlTipoAsistencias").DataSource = get_GlobalDTAsistenciasInasistencias(UsuarioActual.CveEmpresa); e.Row.FCDropDownList("DdlTipoAsistencias").DataBind(); if (e.Row.DBCampo("CveAsistenciasInasistencias") != "-1") e.Row.FCDropDownList("DdlTipoAsistencias").SelectedValue = e.Row.DBCampo("CveAsistenciasInasistencias"); // Carga Motivos Horas Extras e.Row.FCDropDownList("DdlMotivoHoraExtra").DataSource = get_GlobalDTMotivosHorasExtras(UsuarioActual.CveEmpresa).FiltraParametros("CveEmpresa = " + UsuarioActual.CveEmpresa); e.Row.FCDropDownList("DdlMotivoHoraExtra").DataBind(); if (e.Row.DBCampo("CveMotivoHoraExtra") != "-1") e.Row.FCDropDownList("DdlMotivoHoraExtra").SelectedValue = e.Row.DBCampo("CveMotivoHoraExtra"); e.Row.FCTextBox("TxtObservaciones").Text = e.Row.DBCampo("Observacion"); if (e.Row.DBCampo("SeModifico") == "0") { e.Row.Cells[0].BackColor = System.Drawing.Color.LightBlue; e.Row.Cells[1].BackColor = System.Drawing.Color.LightBlue; e.Row.Cells[2].BackColor = System.Drawing.Color.LightBlue; e.Row.Cells[3].BackColor = System.Drawing.Color.LightBlue; } else if (e.Row.DBCampo("SeModifico") == "1") { e.Row.Cells[0].ForeColor = System.Drawing.Color.Red; e.Row.Cells[1].ForeColor = System.Drawing.Color.Red; e.Row.Cells[2].ForeColor = System.Drawing.Color.Red; e.Row.Cells[3].ForeColor = System.Drawing.Color.Red; } } } #endregion #region "CalculosSistema" private void showModalCalculo() { DataRow drow = dtempleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); TxtCCSysSalarioMinimo.Text = ""; if (drow != null) { decimal UMA = 0M; using (ClsNominas onom = new ClsNominas()) { if (onom.UMAFechaGet(UsuarioActual.CveEmpresa, $"{NowADS():yyyy/MM/dd}") && onom.DtResultados.Rows.Count > 0) { UMA = onom.DtResultados.Rows[0]["UMA"].ToString().ToDecimal(); } } TxtCCSysUMA.Text = $"{UMA:N2}"; TxtCCSysSalarioMinimo.Text = string.Format("${0:N2}", drow["SalarioMinimo"]); } UpModalCalculos.Update(); RegistraScript("$('#ModalCalculosSys').modal();"); } public void showhidepnlscalculo(int concepto) { PnlIMSSV.Visible = false; PnlIMSSF.Visible = false; PnlHorasExtras.Visible = false; PnlHorasExtrasF.Visible = false; LblcalculoTitulos.Text = ""; switch (concepto) { case 1: LblcalculoTitulos.Text = " Calculo conceptos IMSS"; PnlIMSSV.Visible = true; PnlIMSSF.Visible = true; break; case 2: LblcalculoTitulos.Text = " Calculo de importe gravado(horas extras)"; PnlHorasExtras.Visible = true; PnlHorasExtrasF.Visible = true; break; default: break; } } protected void LnkCalculoIMSS_Click(object sender, EventArgs e) { TxtCCSysDiasIMSS.Text = ""; TxtCCSysSalarioBC.Text = ""; DataRow drow = dtempleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); if (drow != null) { int Fechafin = string.Format("{0:yyyyMMdd}", drow["FechaFin"]).ToEntero(); decimal UMA = 0M; using (ClsNominas onom = new ClsNominas()) { if (onom.UMAFechaGet(UsuarioActual.CveEmpresa, $"{NowADS():yyyy/MM/dd}") && onom.DtResultados.Rows.Count > 0) { UMA = onom.DtResultados.Rows[0]["UMA"].ToString().ToDecimal(); } } decimal SalarioDiarioIMSS = drow["SalarioDiarioIMSS"].ToString().ToDecimal(); decimal DiasIMSS = drow["DiasIMSS"].ToString().ToDecimal(); decimal importeparacuota = SalarioDiarioIMSS > (3 * UMA) ? SalarioDiarioIMSS - (3 * UMA) : 0M; decimal CuotaExcedente = (DiasIMSS * 0.004M) * (importeparacuota > (25M * UMA) ? (25M * UMA) : importeparacuota); decimal PrestacionesDinero = (DiasIMSS * 0.0025M) * SalarioDiarioIMSS; decimal GastosMedicos = (DiasIMSS * (Fechafin > 20210831 ? 0.00375M : 0.0038M)) * SalarioDiarioIMSS; decimal retenfermadMaterObrero = CuotaExcedente + PrestacionesDinero + GastosMedicos; decimal RetInvYVida = (DiasIMSS * 0.00625M) * SalarioDiarioIMSS; decimal RetCesentia = (DiasIMSS * 0.01125M) * SalarioDiarioIMSS; decimal IMSS = retenfermadMaterObrero + RetInvYVida + RetCesentia; TxtCCSysDiasIMSS.Text = string.Format("{0:N0}", DiasIMSS); TxtCCSysSalarioBC.Text = string.Format("${0:N4}", drow["SalarioDiarioIMSS"]); LblCCSysImporteCuotaExcedente.Text = string.Format("
 SI( [Salario base cotización] > (3 *[UMA]), [Salario base cotización] - (3 *[UMA]) , 0)\n SI({0}>(3*{1}),             {0}-(3*{1}),               0 ) 
", SalarioDiarioIMSS, UMA); TxtCCSysImporteCuotaExcedente.Text = string.Format("{0:N4}", importeparacuota); LblCCSysCuotaExcedente.Text = string.Format("
(0.004 * [Días IMSS]) * SI( [Importe cuota e.] > (25 *[UMA]), (25 *[UMA]) , [Importe cuota e.] )\n SI( {0} > (25*{1}),  (25*{1}),   {0}) 
", importeparacuota, UMA); TxtCCSysCuotaExcedente.Text = string.Format("{0:N2}", CuotaExcedente); LblCCSysPrestacionesenDinero.Text = string.Format("
 0.0025 * [Días IMSS] * [Salario base cotización] \n 0.0025 * {1:#} * {0:#.0000}", SalarioDiarioIMSS, DiasIMSS);
            TxtCCSysPrestacionesenDinero.Text = string.Format("{0:N2}", PrestacionesDinero);

            LblCCSysGastosMedicos.Text = string.Format("
 0.00375 * [Días IMSS] * [Salario base cotización] \n 0.00375 * {1:#} * {0:#.0000}", SalarioDiarioIMSS, DiasIMSS);
            TxtCCSysGastosMedicos.Text = string.Format("{0:N2}", GastosMedicos);

            LblCCSysRetEnfYMatOb.Text = string.Format("
 [Cuota excedente] + [Prestaciones en dinero] + [Gastos médicos pensionados] \n {0:#.00} + {1:#.00} + {2}:#.00", CuotaExcedente, PrestacionesDinero, GastosMedicos);
            TxtCCSysRetEnfYMatOb.Text = string.Format("{0:N2}", retenfermadMaterObrero);

            LblCCSysRetInvYVida.Text = string.Format("
 0.00625 * [Días IMSS] * [Salario base cotización] \n 0.00625 * {1:#} * {0:#.0000}", SalarioDiarioIMSS, DiasIMSS);
            TxtCCSysRetInvYVida.Text = string.Format("{0:N2}", RetInvYVida);

            LblCCSysRetCesentia.Text = string.Format("
 0.01125 * [Días IMSS] * [Salario base cotización] \n 0.01125 * {1:#} * {0:#.0000}", SalarioDiarioIMSS, DiasIMSS);
            TxtCCSysRetCesentia.Text = string.Format("{0:N2}", RetCesentia);

            LblCCSysImporteIMSS.Text = string.Format("
 [Ret. Enf. y Mat. obrero] + [Ret. Inv. y vida] + [Ret. Cesantia] \n {0:#.00} + {1:#.00} + {2:#.00}", retenfermadMaterObrero, RetInvYVida, RetCesentia);
            TxtCCSysImporteIMSS.Text = string.Format("{0:N2}", IMSS);
        }
        showhidepnlscalculo(1);
        showModalCalculo();
    }

    protected void LnkCalculoHorasExtras_Click(object sender, EventArgs e)
    {

        showhidepnlscalculo(2);
        //AreaGeografica  HorasDobles HorasTriples 
        TxtCCSysHorasDobles.Text = "";
        TxtCCSysHorasTriples.Text = "";
        TxtCCSysDiasLaborados.Text = "";
        DataRow drow = dtempleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal));
        if (drow != null)
        {
            decimal UMA = 0M;
            using (ClsNominas onom = new ClsNominas())
            {
                if (onom.UMAFechaGet(UsuarioActual.CveEmpresa, $"{NowADS():yyyy/MM/dd}") && onom.DtResultados.Rows.Count > 0)
                {
                    UMA = onom.DtResultados.Rows[0]["UMA"].ToString().ToDecimal();
                }
            }
            TxtCCSysUMA.Text = $"{UMA:N2}";
            decimal HorasDobles = drow["HorasDobles"].ToString().ToDecimal();
            decimal HorasTriples = drow["HorasTriples"].ToString().ToDecimal();
            decimal ImporteHora = drow["SalarioDiario"].ToString().ToDecimal() / 8;
            decimal Semanaslaboradas = Decimal.Truncate((drow["DiasPeriodo"].ToString().ToDecimal() / 7M));
            bool seExentandobles = !(drow["SalarioDiario"].ToString().ToDecimal() > drow["SalarioMinimo"].ToString().ToDecimal());
            decimal TopeHorasDobles = Semanaslaboradas * 9M;
            decimal HorasExcentas = HorasDobles > TopeHorasDobles ? TopeHorasDobles : HorasDobles;
            decimal ImporteHorasExtrasAntes = HorasExcentas * ImporteHora * (seExentandobles ? 2 : 1);
            decimal TopeImporte = Semanaslaboradas * 5 * UMA;
            decimal ImporteHorasExtras = ImporteHorasExtrasAntes > TopeImporte ? TopeImporte : ImporteHorasExtrasAntes;
            decimal TotalHorasextras = ImporteHora * ((HorasDobles * 2) + (HorasTriples * 3));

            TxtCCSysHorasDobles.Text = string.Format("{0:N2}", HorasDobles);
            TxtCCSysHorasTriples.Text = string.Format("{0:N2}", HorasTriples);
            TxtCCSysSalarioDiario.Text = string.Format("${0:N2}", drow["SalarioDiario"]);
            TxtCCSysDiasLaborados.Text = string.Format("{0:N0}", drow["DiasLaborados"]);
            TxtCCSysImporteHora.Text = string.Format("${0:N2}", ImporteHora);

            LblCCSysSeExcentanDobles.Text = string.Format("
 SI( [Salario diario({0:N2})] > [Salario mínimo({1:N2})], \"No\", \"Sí\" )  
", drow["SalarioDiario"], drow["SalarioMinimo"]); TxtCCSysSeExcentanDobles.Text = seExentandobles ? "Sí" : "No"; LblCCSysTopeHorasDobles.Text = string.Format("
 [Semanas laboradas({0:N0})] * 9 
", Semanaslaboradas); TxtCCSysTopeHorasDobles.Text = string.Format("{0:N0}", Semanaslaboradas * 9); LblCCSysHorasExcentas.Text = string.Format("
 SI( [Horas dobles({0:N0})] > [Tope horas({1:N0})], [Tope horas({1:N0})] , [Horas dobles({0:N0})]) 
", HorasDobles, TopeHorasDobles); TxtCCSysHorasExcentas.Text = string.Format("{0:N0}", HorasExcentas); LblCCSysImporteExentoAntesTope.Text = string.Format("
 [Horas exentas] * [Importe hora] * Si([se exentan dobles] , 2, 1)  
", Semanaslaboradas, UMA); TxtCCSysImporteExentoAntesTope.Text = string.Format("{0:N2}", ImporteHorasExtrasAntes); LblCCSysTopeImporte.Text = string.Format("
 [Semanas laboradas({0:N0})] * 5 * [UMA({1:N2})]  
", Semanaslaboradas, UMA); TxtCCSysTopeImporte.Text = string.Format("{0:N2}", TopeImporte); LblCCSysImporteExento.Text = string.Format("
SI( [Importe exento(antes del tope)({0:N2})] > [Tope importe({1:N2})],\n[Tope importe({1:N2})] ,\n [Importe exento(antes del tope)({0:N2})])  
", ImporteHorasExtrasAntes, TopeImporte); TxtCCSysImporteExento.Text = string.Format("{0:N2}", ImporteHorasExtras); LblCCSysImporteGravado.Text = string.Format("
 [Total horas extras({0:N2})] - [Importe exento({1:N2})] 
", TotalHorasextras, ImporteHorasExtras); TxtCCSysImporteGravado.Text = string.Format("{0:N2}", TotalHorasextras - ImporteHorasExtras); } showModalCalculo(); } protected void LnkCalculoSubsidio_Click(object sender, EventArgs e) { showhidepnlscalculo(3); showModalCalculo(); } protected void LnkCalculoISR_Click(object sender, EventArgs e) { showhidepnlscalculo(4); showModalCalculo(); } #endregion #region Vacaciones protected int CvePersonalVacaciones { get { if (ViewState["CvePersonalVacaciones"] == null) { return 0; } else { return ViewState["CvePersonalVacaciones"].ToString().ToEntero(); } } set { ViewState["CvePersonalVacaciones"] = value; } } private void CargaVacaciones() { using (ClsNominas objRH = new ClsNominas()) { if (objRH.GetPersonalVacaciones(UsuarioActual.CveEmpresa, SRCvePersonal)) { GvVacaciones.DataSource = objRH.DtResultados; } else { GvVacaciones.DataSource = null; } } LnkSRVacacionesADD.Visible = false; PnlVacacionesAdd.Visible = false; GvVacaciones.DataBind(); UpGvVacaciones.Update(); } protected void LnkShowAddVacaciones_Click(object sender, EventArgs e) { LnkSRVacacionesADD.Visible = true; PnlVacacionesAdd.Visible = true; DdlFormapagovacaciones_SelectedIndexChanged(null, null); ChkVacPrimaVacacional.Checked = true; ChkVacCobrarIMSS.Checked = true; using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetPersonalVacResumen(UsuarioActual.Empresa.CveEmpresa, SRCvePersonal)) { DdlVacPeriodo.DataSource = objnom.DtResultados; DdlVacPeriodo.DataBind(); DataRow drow = objnom.DtResultados.FiltroPrimero("Selected =1"); if (drow != null) { DdlVacPeriodo.SelectedValueExist(drow["Ejercicio"].ToString()); } } } UPSRModalVacaciones.Update(); RegistraScript("$('#ModalSRVacaciones').modal()"); } protected void DdlFormapagovacaciones_SelectedIndexChanged(object sender, EventArgs e) { PnlVacfechas.Visible = false; PnlVacDias.Visible = false; PnlVacFechapago.Visible = false; PnlVacDiasPago.Visible = false; PnlVacChecks.Visible = false; TxtVacDiasPago.Text = "0"; switch (DdlFormapagovacaciones.SelectedValue.ToEntero()) { case 1://Pagar en fecha PnlVacfechas.Visible = true; PnlVacDias.Visible = true; PnlVacFechapago.Visible = true; PnlVacDiasPago.Visible = true; PnlVacChecks.Visible = true; break; case 2://Pagar en periodo disfrutadas PnlVacfechas.Visible = true; PnlVacDias.Visible = true; PnlVacChecks.Visible = true; break; case 3://Vacaciones trabajadas PnlVacfechas.Visible = true; PnlVacDias.Visible = true; PnlVacDiasPago.Visible = false; PnlVacFechapago.Visible = true; //PnlVacChecks.Visible = true; break; case 4://Solo pagar PnlVacFechapago.Visible = true; PnlVacDiasPago.Visible = true; PnlVacChecks.Visible = true; break; case 5://Solo disfrutar PnlVacfechas.Visible = true; break; case 6://Solo prima PnlVacFechapago.Visible = true; PnlVacDiasPago.Visible = true; break; } /* */ } protected void LnkSRVacacionesUP_Click(object sender, EventArgs e) { } protected void LnkSRVacacionesADD_Click(object sender, EventArgs e) { DateTime fInicio = TxtvacFechaInicio.Text.ToDate(); DateTime fFin = TxtvacFechaFin.Text.ToDate(); string fechapago = TxtvacFechaPago.Text.ToDate().ToString("yyyy/MM/dd"); int diasinhabil = TxtvacDiasFeriados.Text.ToEntero(); // Dim motivoVacaciones As String = TxtMotivoVacaciones.Text int VacCveSupervisor = 0; int VacFolioActual = 0; if (fInicio <= fFin) { using (ClsRH objRHx = new ClsRH()) { if (objRHx.VacacionesResumenGet(SRCvePersonal, UsuarioActual.Empresa.CveEmpresa)) { if (objRHx.DtResultados.Rows.Count > 0) { VacCveSupervisor = objRHx.DtResultados.Rows[0]["SupervisorCorreo"].ToString().ToEntero(); } } if (objRHx.VacacionesGet(SRCvePersonal, UsuarioActual.Empresa.CveEmpresa)) { if (objRHx.DtResultados.Rows.Count > 0) { VacFolioActual = objRHx.DtResultados.Compute("Max(Folio)", string.Empty).ToString().ToEntero(); } } } VacFolioActual = VacFolioActual + 1; ClsRH objRH = new ClsRH(); // Dim continuar As Boolean = objRH.SolicitudVacacionesAdd(CvePersonal, fInicio, fFin, 0, UsuarioActual.CveUsuario, VacCveSupervisor, VacFolioActual, motivoVacaciones) bool continuar = objRH.SolicitudVacacionesAdd(SRCvePersonal, fInicio, fFin, 0, UsuarioActual.CveUsuario, VacCveSupervisor, VacFolioActual, FechaPago: fechapago, diasinabiles: diasinhabil, CveTipoPago: DdlFormapagovacaciones.SelectedValue.ToEntero(), diasExtras: TxtVacDiasExtra.Text.ToEntero(), Ejercicio: DdlVacPeriodo.SelectedValue.ToEntero(), PrimaVacacional: (ChkVacPrimaVacacional.Checked ? 1 : 0), CobrarImss: (ChkVacCobrarIMSS.Checked ? 1 : 0), diasPago: TxtVacDiasPago.Text.ToEntero() ); if (objRH.DtResultados.Rows.Count > 0) { string ShowError = objRH.DtResultados.Rows[0]["ShowError"].ToString(); if (ShowError.Length > 0) { Alert(ShowError, TipoMensaje.MsgAdvertencia); continuar = false; } } objRH.Dispose(); if (continuar) { TxtvacFechaInicio.Text = ""; TxtvacFechaFin.Text = ""; TxtvacFechaPago.Text = ""; TxtvacDiasFeriados.Text = ""; CargaVacaciones(); //CargaVacacionesResumenPeriodoActual(); //VacacionesMandaCorreoSupervisor("Solicitud Vacaciones " + NombreCompleto, VacSupervisorCorreo, VacSupervisorNombre, NombreCompleto, fInicio, fFin); Alert("Las vacaciones se han solicitado"); RegistraScript("$('#ModalSRVacaciones').modal('hide')"); } } else { Alert("La fecha Inicial debe ser inferior a la fecha final.", TipoMensaje.MsgAdvertencia); } } protected void GvVacaciones_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { bool _Estatus = bool.Parse(e.Row.DBCampo("Estatus").ToString()); string _Documento = e.Row.DataKey("Documento"); int _CveAutoriza = e.Row.DataKey("CveAutoriza").ToEntero(); string RutaDocuemntoAutorizacion = string.Format(@"{0}Personal\{1}\Vacaciones\{2}", UsuarioActual.Empresa.Ruta, SRCvePersonal, _Documento); LinkButton lnkDescargaFormato = e.Row.FCLinkButton("ImgDescargaFormato"); LinkButton lnkDescargaAutorizacion = e.Row.FCLinkButton("ImgDescargaAutorizacion"); LinkButton lnkEditar = e.Row.FCLinkButton("ImgEditar"); lnkEditar.Visible = true; lnkDescargaFormato.Visible = true; if (_CveAutoriza > 0 | !_Estatus) { lnkEditar.Visible = false; lnkDescargaFormato.Visible = false; } // ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(lnkDescargaFormato) if (File.Exists(RutaDocuemntoAutorizacion) & _Estatus) { lnkDescargaAutorizacion.Visible = true; } else { lnkDescargaAutorizacion.Visible = false; } if (lnkDescargaAutorizacion != null && lnkDescargaAutorizacion.Visible) { ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkDescargaAutorizacion); } if (lnkDescargaFormato != null && lnkDescargaFormato.Visible) { ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkDescargaFormato); } } } protected void LnkEliminarSolicitud_Click(object sender, EventArgs e) { GridViewRow GvRow = (GridViewRow)((LinkButton)sender).NamingContainer; int CvePersonalVacaciones = GvRow.DataKey("CvePersonalVacaciones").ToEntero(); ClsRH objRH = new ClsRH(); if (objRH.RemoverSolicitudVacaciones(CvePersonalVacaciones)) { CargaVacaciones(); Alert("Las vacaciones se ha eliminado"); } objRH.Dispose(); } public void Edit_ClickVacacionDia(object sender, EventArgs e) { GridViewRow GvRow = (GridViewRow)((LinkButton)sender).NamingContainer; CvePersonalVacaciones = GvRow.DataKey("CvePersonalVacaciones").ToEntero(); //VacFolio = GvRow.DataKey("Folio").ToString().ToEntero; TxtFechaDiaVacacion.Text = GvRow.DataKey("FechaInicio").ToString().ToDate().ToString("dd/MM/yyyy"); TxtFechaDiaVacacionFin.Text = GvRow.DataKey("FechaFin").ToString().ToDate().ToString("dd/MM/yyyy"); RegistraScript("$('#divEditarDiaVacacion').modal({ backdrop: 'static', keyboard: false});"); UpModalEditarDiaVacacion.Update(); } protected void BtnEditarDiaVacacionModal_Click(object sender, EventArgs e) { using (ClsRH objRH = new ClsRH()) { string FileExtension = "-1"; List Filesgral = TxtFileFormatoVacaciones.getfiles().Archivos; string Documento = ""; foreach (Archivo fileItem in Filesgral) { try { FileExtension = System.IO.Path.GetExtension(string.Format(@"{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", ""); Documento = $"Vacaciones_{CvePersonalVacaciones}.{FileExtension}"; string[] tempArray; tempArray = fileItem.filename.ToString().Split("-".ToCharArray()); string rutaDestino = $@"{UsuarioActual.Empresa.Ruta}Personal\{SRCvePersonal}\Vacaciones\{Documento}"; if (!System.IO.Directory.Exists(UsuarioActual.Empresa.Ruta + @"Personal\" + SRCvePersonal + @"\Vacaciones\")) System.IO.Directory.CreateDirectory(UsuarioActual.Empresa.Ruta + @"Personal\" + SRCvePersonal + @"\Vacaciones\"); if (System.IO.File.Exists(rutaDestino)) System.IO.File.Delete(rutaDestino); System.IO.File.Move(fileItem.FileUrl, rutaDestino); TxtFileFormatoVacaciones.Text = ""; } catch (Exception ex) { this.OnError("Error al cargar Formato vacaciones", ex); } } if (Documento.Length > 0) { if (objRH.SolicitudVacacionesAddUpdate(CvePersonalVacaciones, SRCvePersonal, UsuarioActual.CveUsuario, Documento)) Alert("Las vacaciones se han autorizado."); CargaVacaciones(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); UpModalEditarDiaVacacion.Update(); // CargaVacacionesResumenPeriodoActual(); RegistraScript("$('#divEditarDiaVacacion').modal('hide');"); } else { Alert("debe ingresar un documento para poder autorizar la solicitud", TipoMensaje.MsgAdvertencia); } } } public void DownLoad_ClickSolicitudVacaciones(object sender, EventArgs e) { /* GridViewRow GvRow = (GridViewRow)(LinkButton)sender.NamingContainer; // Dim Folio As Integer = GvRow.DataKey("Folio").ToEntero // DescarSolicitudVacaciones(Folio) string RutaFormato = string.Format(@"{0}Formatos\SolicitudVacaciones.docx", UsuarioActual.Empresa.Ruta); string NombreEmpleado = string.Format("{0} {1} {2}", TxtAPaterno.Text, TxtAMaterno.Text, TxtNombres.Text); string Codigo = TxtCodigo.Text; string Departamento = DdlDepartamento.SelectedItem.Text; string JefeInmediato = DdlSupervisorOrganigrama.SelectedItem.Text; DateTime fechaIngreso = TxtFechaIngreso.Text.ToDate(); int Periodoingreso = fechaIngreso.ToString("MMdd").ToEntero(); int PeriodoInicio = GvRow.DataKey("FechaInicio").ToDate().ToString("MMdd").ToEntero(); string FechaInicio = GvRow.DataKey("FechaInicio").ToDateTime().ToString("dd/MM/yyyy"); string FechaFin = GvRow.DataKey("FechaFin").ToDateTime().ToString("dd/MM/yyyy"); string diasPermiso = GvRow.DataKey("Dias"); string MotivoPermiso = GvRow.DataKey("Motivo"); string Puesto = DdlPuesto.SelectedItem.Value; string Fecha = NowADS().ToString("dd/MM/yyyy"); string Solicitante = UsuarioActual.Nombre; int anio = GvRow.DataKey("FechaInicio").ToDate().Year; string FechaPeriodo = GvRow.DataKey("Periodo"); if (Periodoingreso > PeriodoInicio) anio = anio - 1; if (File.Exists(RutaFormato)) { clsGemBoxDocument objGemDocument = new clsGemBoxDocument(RutaFormato); List ListaTags = new List(); ListaTags = GetDatosTagsDocumentos(); ListaTags.Add(new TagsDocumentos("{Solicitante}", Solicitante)); ListaTags.Add(new TagsDocumentos("{Fecha}", Fecha)); ListaTags.Add(new TagsDocumentos("{NombreEmpleado}", NombreEmpleado)); ListaTags.Add(new TagsDocumentos("{Codigo}", Codigo)); ListaTags.Add(new TagsDocumentos("{Departamento}", Departamento)); ListaTags.Add(new TagsDocumentos("{JefeInmediato}", JefeInmediato)); ListaTags.Add(new TagsDocumentos("{FechaInicio}", FechaInicio)); ListaTags.Add(new TagsDocumentos("{FechaFin}", FechaFin)); ListaTags.Add(new TagsDocumentos("{diasPermiso}", diasPermiso)); ListaTags.Add(new TagsDocumentos("{MotivoPermiso}", MotivoPermiso)); ListaTags.Add(new TagsDocumentos("{Puesto}", Puesto)); ListaTags.Add(new TagsDocumentos("{anio}", anio.ToString())); ListaTags.Add(new TagsDocumentos("{FechaPeriodo}", FechaPeriodo)); objGemDocument.SustituirTags(ListaTags); // objGemDocument.GuardarStream() objGemDocument.GuardarStreamPDF(); byte[] bytesInStream = objGemDocument.GetBytesDocumento(); // Dim bytesInStream As Byte() = objGemDocument.memoryStream.ToArray objGemDocument.Dispose(); Response.Clear(); Response.ContentType = "application/force-download"; Response.AddHeader("content-disposition", "attachment; filename=" + CvePersonal + "_Solicitud_Vacaciones_" + NowADS().ToString("yyyyMMddhhmmss") + ".pdf"); Response.BinaryWrite(bytesInStream); Response.End(); } else Alert("No se encontro el Formato, favor de revisarlo con soporte tecnico.", TipoMensaje.MsgAdvertencia);*/ } #endregion public void cargaBitacora() { using (ClsGenerales ObjGral = new ClsGenerales()) { if (ObjGral.GetHistorialBitacora(-1, -1, -1, -1, -1, -1, -1, UsuarioActual.CveEmpresa, CvePersonal: SRCvePersonal, CvePeriodo: SRCvePeriodo)) { GvBitacora.DataSource = ObjGral.DtResultados; GvBitacora.DataBind(); } } } protected void LnkImportexCalculo_Click(object sender, EventArgs e) { SRCveConcepto = ((LinkButton)sender).CommandArgument.ToEntero(); //CvePeriodoSeleccionado //SRCvePersonal bool continuar = true; bool msgFin = true; if (SRCveConcepto > 0) { using (ClsNominas onom = new ClsNominas()) { if (continuar = onom.DeleteNom_NominasDetalles(SRCveConcepto, SRCvePersonal, CvePeriodoSeleccionado)) { msgFin = (onom.DtResultados.Rows.Count > 0 && onom.DtResultados.Rows[0]["AplicaFiniquito"].ToString().ToUpper().Contiene("1", "TRUE")); } } } if (continuar) { cargaDatos(CvePersonal: SRCvePersonal); cargasobrericiboconceptos(SRMostrarFormulas); UpGvConceptos.Update(); RegistraScript("$('#ModalUpConcepto').modal('hide');"); if(msgFin) { Alert("recuerda eliminar el finiquito del modulo de finiquito si deseas eliminar el valor, esto para poder activar al empleado!",TipoMensaje.ToastAdventencia); } else { Alert("el importe sera tomado del calculo y no del valor fijo"); } } } protected void LnkConcepto_Click(object sender, EventArgs e) { SRCveConcepto = ((LinkButton)sender).CommandArgument.ToEntero(); SRTipoConcepto = ((LinkButton)sender).CommandArgument; #region carga conceptos DataTable dtCon; if (SRCveConcepto > 0) { DataRow drow = dtConceptos.FiltroPrimero(string.Format("CveConcepto={0}", SRCveConcepto)); if (drow != null) { SRTipoConcepto = drow["Tipo"].ToString(); } else { SRCveConcepto = 0; SRTipoConcepto = "D"; } } if (SRTipoConcepto == "P") { dtCon = dtConceptos.FiltraParametros("Tipo ='P' AND EsPadre = 1 ").Copy(); //AND CveSistema <>12' } else { dtCon = dtConceptos.FiltraParametros("Tipo ='D' AND EsPadre = 1 ").Copy(); SRTipoConcepto = "D"; } dtCon.Columns.Add(new DataColumn("CodigoConcepto")); foreach (DataRow trow in dtCon.Rows) { trow["CodigoConcepto"] = string.Format("{0} - {1}", trow["Codigo"], trow["Concepto"]); } dtCon.AcceptChanges(); DataRow row = dtCon.NewRow(); row["CveConcepto"] = "-1"; row["CodigoConcepto"] = "Seleccione"; dtCon.Rows.InsertAt(row, 0); #endregion DdlmcConceptos.DataSource = dtCon; DdlmcConceptos.DataBind(); if (SRCveConcepto > 0) { DdlmcConceptos.SelectedValueExist(SRCveConcepto); } PnlConceptoPersonal.Visible = false; DdlmcConceptos_SelectedIndexChanged(DdlmcConceptos, null); RegistraScript(string.Format("$('#ModalUpConcepto').on('shown.bs.modal', function () {{$('#{0}').trigger('focus')}});$('#ModalUpConcepto').modal();", TxtmcImporte.ClientID)); UPpanelModalUpConcepto.Update(); } protected void LnkConceptoEmpleado_Click(object sender, EventArgs e) { SRCveConcepto = -1; SRTipoConcepto = "P"; SRCvePersonal = -1; using (ClsRH ObjPersonal = new ClsRH()) { if (ObjPersonal.GetPersonal(-1, UsuarioActual.CveEmpresa)) { DdlmcPersonal.DataSource = ObjPersonal.DtResultados; DdlmcPersonal.DataBind(); } } #region carga conceptos DataTable dtCon; dtCon = dtConceptos.FiltraParametros("Tipo IN('P','D') AND EsPadre = 1 ").Copy(); dtCon.Columns.Add(new DataColumn("CodigoConcepto")); foreach (DataRow trow in dtCon.Rows) { trow["CodigoConcepto"] = string.Format("{0} - {1}", trow["Codigo"], trow["Concepto"]); } dtCon.AcceptChanges(); #endregion DdlmcConceptos.DataSource = dtCon; DdlmcConceptos.DataBind(); if (SRCveConcepto > 0) { DdlmcConceptos.SelectedValueExist(SRCveConcepto); } PnlConceptoPersonal.Visible = true; DdlmcConceptos_SelectedIndexChanged(DdlmcConceptos, null); RegistraScript(string.Format("$('#ModalUpConcepto').on('shown.bs.modal', function () {{$('#{0}').trigger('focus')}});$('#ModalUpConcepto').modal();", TxtmcImporte.ClientID)); UPpanelModalUpConcepto.Update(); } protected void DdlmcConceptos_SelectedIndexChanged(object sender, EventArgs e) { int CvePersonal = SRCvePersonal; int CveConcepto = DdlmcConceptos.SelectedValue.ToEntero(); TxtmcImporte.Text = ""; TxtmcImporteGrabado.Text = ""; Txtmcvalor.Text = ""; ChkCalAutomaticoG.Checked = false; ChkCalAutomatico.Checked = false; ChkCalAutomaticoV.Checked = false; if (CveConcepto > 0) { DataRow drow = dtPerEmpleadosConceptos.FiltroPrimero(string.Format("CveConcepto={0} AND CvePersonal ={1}", CveConcepto, CvePersonal)); if (drow != null) { int TipoCalculo = drow["Estatus"].ToString().ToEntero(); ChkCalAutomaticoG.Checked = true; ChkCalAutomatico.Checked = true; ChkCalAutomaticoV.Checked = true; if (TipoCalculo >= 5) { TipoCalculo -= 5; ChkCalAutomaticoG.Checked = false; } if (TipoCalculo >= 3) { TipoCalculo -= 3; ChkCalAutomatico.Checked = false; } if (TipoCalculo >= 1) { ChkCalAutomaticoV.Checked = false; } TxtmcImporte.Text = string.Format("{0:N2}", drow["Importe"]); TxtmcImporteGrabado.Text = string.Format("{0:N2}", drow["ImporteGravado"]); Txtmcvalor.Text = string.Format("{0:N2}", drow["Valor"]); } else { ChkCalAutomaticoV.Checked = true; ChkCalAutomaticoG.Checked = true; } } else { if (e != null) { Alert("Seleccione un concepto.", TipoMensaje.MsgAdvertencia); } } UPpanelModalUpConcepto.Update(); ChkCalAutomaticoV_CheckedChanged(ChkCalAutomaticoV, null); ChkCalAutomatico_CheckedChanged(ChkCalAutomatico, null); ChkCalAutomaticoG_CheckedChanged(ChkCalAutomaticoG, null); } protected void ChkCalAutomaticoV_CheckedChanged(object sender, EventArgs e) { Txtmcvalor.Enabled = !ChkCalAutomaticoV.Checked; } protected void ChkCalAutomatico_CheckedChanged(object sender, EventArgs e) { TxtmcImporte.Enabled = !ChkCalAutomatico.Checked; } protected void ChkCalAutomaticoG_CheckedChanged(object sender, EventArgs e) { TxtmcImporteGrabado.Enabled = !ChkCalAutomaticoG.Checked; } protected void BtnAceptarMC_Click(object sender, EventArgs e) { int chkImporte = ChkCalAutomatico.Checked ? 0 : 1; int chkImporteGravado = ChkCalAutomaticoG.Checked ? 0 : 1; int chkImporteValor = ChkCalAutomaticoV.Checked ? 0 : 1; bool continuar = true; int CveNomina = 0; double Total = 0; int CveMoneda = 1; int CveMetodoPago = 0; int CvePersonal = SRCvePersonal; if (CvePersonal <= 0) { CvePersonal = DdlmcPersonal.SelectedValue.ToEntero(); } int CveConcepto = DdlmcConceptos.SelectedValue.ToEntero(); decimal ImporteConcepto = chkImporte == 1 ? TxtmcImporte.Text.Replace("$", "").Replace(",", "").ToDecimal() : 0; decimal ImporteGravadoConcepto = ChkCalAutomaticoG.Checked ? 0.0m : TxtmcImporteGrabado.Text.Replace("$", "").Replace(",", "").ToDecimal(); decimal ImporteExentoConcepto = ImporteConcepto - ImporteGravadoConcepto; decimal ImporteValor = Txtmcvalor.Text.Replace("$", "").Replace(",", "").ToDecimal(); if ((ImporteConcepto >= 0 && ImporteGravadoConcepto <= ImporteConcepto) || (ImporteConcepto < 0 && ImporteGravadoConcepto >= ImporteConcepto)) { if (CveConcepto > 0 && CvePersonal > 0) { using (ClsNominas objNomina = new ClsNominas()) { if (continuar) { if (objNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodoSeleccionado, -1, UsuarioActual.CveEmpresa)) { if (objNomina.DtResultados.Rows.Count > 0) { CveNomina = objNomina.CveNomina; } else { if (objNomina.AddNom_Nominas(-1, 1, CvePersonal, CvePeriodoSeleccionado, Total, 0, 0, Total, CveMoneda, 1, CveMetodoPago, NowADS(), "Deducciones nómina", "", "", "", "", 0, 0, 0, new DateTime(), new DateTime(), new DateTime(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, false)) { CveNomina = objNomina.CveNomina; } else { continuar = false; } } } } if (CveNomina == 0) { continuar = false; } if (continuar) { if (continuar) { if (!objNomina.AddUPNom_NominasDetalles(CveNomina, CvePeriodoSeleccionado, CvePersonal, CveConcepto, ImporteConcepto, ImporteGravadoConcepto, ImporteExentoConcepto, ImporteValor, UsuarioActual.CveUsuario, true, chkImporte, chkImporteGravado, chkImporteValor, false)) { continuar = false; } } } } if (continuar) { cargaDatos(CvePersonal: SRCvePersonal); if (PnlConceptoPersonal.Visible) { cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); } UpGvConceptos.Update(); RegistraScript("$('#ModalUpConcepto').modal('hide');"); Alert("El cambio se ha guardado correctamente."); } } else { if (CveConcepto > 0) { Alert("Debe seleccionar un empleado.", TipoMensaje.MsgAdvertencia); } else { Alert("Debe seleccionar un concepto.", TipoMensaje.MsgAdvertencia); } } } else { Alert("el importe gravado no puede ser mayor al importe total, en caso de que el importe total sea negativo no puede ser menor.", TipoMensaje.MsgAdvertencia); } } private void mostrarConceptos() { #region "Llenado de datos empleado" string DiasLaborados = ""; string DiasFaltados = ""; string DiasVacaciones = ""; string FechaInicio = ""; string FechaFin = ""; string DiasRetardos = ""; string DiasIncapacidad = ""; string SD = ""; string SDI = ""; string SalarioDiarioIMSS = ""; DataRow drow = dtPerEmpleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); if (drow != null) { DiasLaborados = string.Format("{0}", drow["DiasLaborados"].ToString().ToEntero()); DiasFaltados = string.Format("{0}", drow["DiasFaltados"].ToString().ToEntero()); DiasVacaciones = string.Format("{0}", drow["DiasVacacionesPorPagar"].ToString().ToEntero());//DiasVacaciones FechaInicio = string.Format("{0:dd/MM/yyyy}", drow["FechaInicio"]); FechaFin = string.Format("{0:dd/MM/yyyy}", drow["FechaFin"]); DiasRetardos = string.Format("{0}", drow["DiasRetardos"].ToString().ToEntero()); DiasIncapacidad = string.Format("{0}", drow["DiasIncapacidad"].ToString().ToEntero()); SD = string.Format("{0:###0.00##}", drow["SalarioDiario"]); SDI = string.Format("{0:###0.00##}", drow["SalarioDiarioIntegrado"]); SalarioDiarioIMSS = string.Format("{0:###0.00##}", drow["SalarioDiarioIMSS"]); } LblDiasLaborados.Text = DiasLaborados; LblDiasFaltados.Text = DiasFaltados; LblDiasVacaciones.Text = DiasVacaciones; LblFecha.Text = string.Format("{0} al {1}", FechaInicio, FechaFin); //LblDiasRetardos.Text = DiasRetardos; LblDiasIncapacidad.Text = DiasIncapacidad; LblSRSalarioDiario.Text = SD; LblSRSalarioDiarioIntegrado.Text = SDI; LblSRSbc.Text = SalarioDiarioIMSS; #endregion cargasobrericiboconceptos(true); CargaFonacot(); #region "Infonavit" { using (ClsRH objper = new ClsRH()) { objper.GetPersonalConceptos(SRCvePersonal, UsuarioActual.CveEmpresa); DataRow frow = objper.DtResultados.FiltroPrimero("CveSistema =3"); TxtInfoValor.Text = ""; DdlInfoTipoAplicacion.SelectedValueExist("-1"); TxtInfoDescripcion.Text = ""; TxtInfoNumCredito.Text = ""; TxtInfoFechaInicio.Text = ""; ChkInfo.Checked = false; if (frow != null) { TxtInfoValor.Text = String.Format("{0:###,###.####}", frow["Importe"]); DdlInfoTipoAplicacion.SelectedValueExist(frow["TipoAplicacion"].ToString()); TxtInfoDescripcion.Text = String.Format("{0}", frow["Descripcion02"]); TxtInfoNumCredito.Text = String.Format("{0}", frow["Descripcion01"]); TxtInfoFechaInicio.Text = String.Format("{0:dd/MM/yyyy}", frow["FInicioAplicacion"]); ChkInfo.Checked = frow["estatus"].ToString().ToUpper().Contiene("1", "TRUE"); } //frow = objper.DtResultados.FiltroPrimero("CveSistema =4"); //TxtFonValor.Text = ""; //DdlFonTipoAplicacion.SelectedValueExist("-1"); //TxtFonDescripcion.Text = ""; //TxtFonNumCredito.Text = ""; //TxtFonFechaInicio.Text = ""; //ChkFonacot.Checked = false; //if (frow != null) //{ // TxtFonValor.Text = String.Format("{0:###,###.##}", frow["Importe"]); // DdlFonTipoAplicacion.SelectedValueExist(frow["TipoAplicacion"].ToString()); // TxtFonDescripcion.Text = String.Format("{0}", frow["Descripcion02"]); // TxtFonNumCredito.Text = String.Format("{0}", frow["Descripcion01"]); // TxtFonFechaInicio.Text = String.Format("{0:dd/MM/yyyy}", frow["FInicioAplicacion"]); // ChkFonacot.Checked = frow["estatus"].ToString().ToUpper().Contiene("1", "TRUE"); //} } } #endregion UpModalConceptos.Update(); } #region fonacot public void LimpiarFonacot() { TxtFonValor.Text = ""; TxtFonImporteCredito.Text = ""; TxtFonPagosHechos.Text = ""; DdlFonTipoAplicacion.SelectedValueExist("-1"); TxtFonDescripcion.Text = ""; TxtFonNumCredito.Text = ""; TxtFonFechaInicio.Text = ""; ChkFonacot.Checked = false; } protected void CargaFonacot() { using (ClsNominas onom = new ClsNominas()) { onom.NomFonacotGet(UsuarioActual.CveEmpresa, -1, SRCvePersonal); GVNomFonacot.DataSource = onom.DtResultados; GVNomFonacot.DataBind(); } UpFonacotGrid.Update(); } protected void LnAddFonacot_Click(object sender, EventArgs e) { LimpiarFonacot(); CveFonacot = -1; RegistraScript("$('#ModalFonacot').modal();"); } protected void LnkEditarNomFonacot_Click(object sender, EventArgs e) { GridViewRow gvrow = (GridViewRow)(((LinkButton)sender).NamingContainer); CveFonacot = gvrow.DataKey("CveFonacot").ToEntero(); Int32 cvePersonal = gvrow.DataKey("CvePersonal").ToEntero(); string numeroCredito = gvrow.DataKey("NumeroCredito"); string descripcion = gvrow.DataKey("Descripcion"); Int32 periodo = gvrow.DataKey("Periodo").ToEntero(); Int32 cveTipoCalculo = gvrow.DataKey("CveTipoCalculo").ToEntero(); decimal importeCredito = gvrow.DataKey("ImporteCredito").ToDecimal(); decimal importeFijo = gvrow.DataKey("ImporteFijo").ToDecimal(); decimal pagosHechos = gvrow.DataKey("PagosHechos").ToDecimal(); decimal montoAcumulado = gvrow.DataKey("MontoAcumulado").ToDecimal(); decimal saldo = gvrow.DataKey("Saldo").ToDecimal(); Int32 cveEstatus = gvrow.DataKey("CveEstatus").ToEntero(); string observaciones = gvrow.DataKey("Observaciones"); if ((periodo < 10000000)) periodo = 20000101; LimpiarFonacot(); TxtFonValor.Text = importeFijo.ToString(); TxtFonImporteCredito.Text = importeCredito.ToString(); TxtFonPagosHechos.Text = pagosHechos.ToString(); DdlFonTipoAplicacion.SelectedValueExist(cveTipoCalculo.ToString()); TxtFonDescripcion.Text = descripcion; TxtFonNumCredito.Text = numeroCredito; TxtFonFechaInicio.Text = string.Format("{2}/{1}/{0}", periodo.ToString().Substring(0, 4), periodo.ToString().Substring(4, 2), periodo.ToString().Substring(6, 2)); ChkFonacot.Checked = (cveEstatus == 1); UpModalFonacot.Update(); RegistraScript("$('#ModalFonacot').modal();"); } protected void LnkEliminarNomFonacot_Click(object sender, EventArgs e) { GridViewRow gvrow = (GridViewRow)(((LinkButton)sender).NamingContainer); int cveFonacot = gvrow.DataKey("CveFonacot").ToEntero(); bool Continuar = false; using (ClsNominas onom = new ClsNominas()) { Continuar = onom.NomFonacotRemove(UsuarioActual.CveEmpresa, cveFonacot); } if ((Continuar)) { CargaFonacot(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); Alert("El registro fonacot se ha eliminado"); } } protected void LnkGuardarFonacot_Click(object sender, EventArgs e) { decimal importe = TxtFonValor.Text.ToDecimal(); decimal importeTotal = TxtFonImporteCredito.Text.ToDecimal(); decimal importePagado = TxtFonPagosHechos.Text.ToDecimal(); int TipoAplicacion = DdlFonTipoAplicacion.SelectedValue.ToEntero(); //int NoPagos = 0; //double SaldoIni = 0; string descripcion02 = TxtFonDescripcion.Text; string NumCredito = TxtFonNumCredito.Text; string fecha = TxtFonFechaInicio.Text.Replace("_", ""); int estatus = ChkFonacot.Checked ? 1 : 0; int periodo = 20000101; if (fecha.Length > 8) { fecha = fecha.ToDateTime().ToString("yyyy/MM/dd"); periodo = fecha.ToDateTime().ToString("yyyyMMdd").ToEntero(); } else fecha = ""; bool continuar = false; using (ClsNominas onom = new ClsNominas()) { if ((CveFonacot == -1)) continuar = onom.NomFonacotAdd(UsuarioActual.CveEmpresa, SRCvePersonal, NumCredito, descripcion02, periodo, TipoAplicacion, importeTotal, importe, importePagado, 0, 0, estatus, "", UsuarioActual.CveUsuario); else continuar = onom.NomFonacotUp(UsuarioActual.CveEmpresa, CveFonacot, SRCvePersonal, NumCredito, descripcion02, periodo, TipoAplicacion, importeTotal, importe, importePagado, 0, 0, estatus, "", UsuarioActual.CveUsuario); } // Old Borrar Caudillo 01/Marzo/2022 // Using ObjPersonal As ClsRH = New ClsRH() // If Not ObjPersonal.AddConcepto(CvePersonal, -1, importe, TipoAplicacion, NoPagos, SaldoIni, UsuarioActual.CveUsuario, 4, NumCredito, descripcion02, fecha, "", estatus, UsuarioActual.CveEmpresa) Then continuar = False // End Using if (continuar) { Alert("Se actualizo el calculo de fonacot"); CargaFonacot(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); RegistraScript("$('#ModalFonacot').modal('hide');"); } } #endregion protected void LnkMostrarocultarConceptos_Click(object sender, EventArgs e) { cargasobrericiboconceptos(!SRMostrarFormulas); } protected bool SRMostrarFormulas { get { if (ViewState["SRMostrarFormulas"] == null) { return false; } else { return (bool)ViewState["SRMostrarFormulas"]; } } set { ViewState["SRMostrarFormulas"] = value; } } public void cargasobrericiboconceptos(Boolean MostrarFormulas) { SRMostrarFormulas = MostrarFormulas; { DataTable dtper = dtPerConceptos.FiltraParametros(string.Format("Tipo IN ('P') AND EsPadre = 1 {0}", (MostrarFormulas ? "" : " AND EsFormula=0"))); DataTable dtded = dtPerConceptos.FiltraParametros(string.Format("Tipo IN ('D') AND EsPadre = 1 AND CveSistema NOT IN(101) {0}", (MostrarFormulas ? "" : " AND EsFormula=0"))); dtper.Columns.Add("BorradoLogico", typeof(int)); dtded.Columns.Add("BorradoLogico", typeof(int)); bool esfinperiodo = false; if (dtPerPeriodo.Rows.Count > 0) { esfinperiodo = (dtPerPeriodo.Rows[0]["EsFinMes"].ToString().ToEntero() == 1); } foreach (DataRow row in dtper.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)) != 0) && (dtPerEmpleadosConceptos.COUNT("CveConcepto", string.Format("CveConcepto={0} AND CvePersonal ={1} AND Estatus >0", CveConcepto, SRCvePersonal)) == 0) ) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtper.AcceptChanges(); foreach (DataRow row in dtded.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)) != 0) && (dtPerEmpleadosConceptos.COUNT("CveConcepto", string.Format("CveConcepto={0} AND CvePersonal ={1} AND Estatus >0", CveConcepto, SRCvePersonal)) == 0) ) { if (!(esfinperiodo && row["CveSistema"].ToString().ToEntero().Contiene(new int[] { 20, 21, 112, 202, 203, 204, 205, 206, 207, 50, 51 }))) { BorradoLogico = 1; } } row["BorradoLogico"] = BorradoLogico; } dtded.AcceptChanges(); dtper = dtper.FiltraParametros("BorradoLogico=0 OR EsFormula >0"); dtded = dtded.FiltraParametros("BorradoLogico=0 OR EsFormula >0"); int maxper = dtper.Rows.Count; int maxded = dtded.Rows.Count; int i = 0; List lconc = new List(); for (i = 0; i < maxper || i < maxded; i++) { NConcepto nConcepto = new NConcepto(); DataRow row; if (maxper > i) { row = dtper.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); decimal ImporteGravado = dtPerEmpleados.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.CveConceptoP = CveConcepto; nConcepto.ConceptoP = Concepto; nConcepto.NoConceptoP = Codigo; nConcepto.ImporteP = Importe; nConcepto.ImporteGravadoP = ImporteGravado; nConcepto.ValorP = dtPerEmpleados.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.isOnlyBisibleP = row["EsFormula"].ToString().ToEntero(); nConcepto.isSavedP = dtPerEmpleadosConceptos.COUNT("CveConcepto", string.Format("CveConcepto={0} AND CvePersonal ={1} AND Estatus >0", CveConcepto, SRCvePersonal)); nConcepto.isEditedP = dtPerEmpleadosConceptos.COUNT("CveConcepto", string.Format("CveConcepto={0} AND CvePersonal ={1} AND Estatus =2", CveConcepto, SRCvePersonal)); } if (maxded > i) { row = dtded.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); decimal ImporteGravado = dtPerEmpleados.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.CveConceptoD = CveConcepto; nConcepto.ConceptoD = Concepto; nConcepto.NoConceptoD = Codigo; nConcepto.ImporteD = Importe; nConcepto.ImporteGravadoD = ImporteGravado; nConcepto.ValorD = dtPerEmpleados.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.isOnlyBisibleD = row["EsFormula"].ToString().ToEntero(); nConcepto.isSavedD = dtPerEmpleadosConceptos.COUNT("CveConcepto", string.Format("CveConcepto={0} AND CvePersonal ={1} AND Estatus >0", CveConcepto, SRCvePersonal)); nConcepto.isEditedD = dtPerEmpleadosConceptos.COUNT("CveConcepto", string.Format("CveConcepto={0} AND CvePersonal ={1} AND Estatus =2", CveConcepto, SRCvePersonal)); } lconc.Add(nConcepto); } lconc.Add(new NConcepto()); NConcepto SubTotales = new NConcepto(); SubTotales.CveConceptoP = 0; SubTotales.ConceptoP = "Total Percepciones"; SubTotales.EstatusP = -2; SubTotales.ImporteP = dtPerEmpleados.SUM("SumaPercepciones", string.Format("CvePersonal = {0}", SRCvePersonal)); SubTotales.ImporteGravadoP = dtPerEmpleados.SUM("SumaPercepcionesG", string.Format("CvePersonal = {0}", SRCvePersonal)); ///Alert(SubTotales.ImporteP.ToString()); SubTotales.CveConceptoD = 0; SubTotales.ConceptoD = "Total Deducciones"; SubTotales.EstatusD = -2; SubTotales.ImporteD = dtPerEmpleados.SUM("SumaDeducciones", string.Format("CvePersonal = {0}", SRCvePersonal)); NConcepto especie = new NConcepto(); especie.CveConceptoD = 0; especie.ConceptoD = "Especie"; especie.EstatusD = -3; especie.ImporteD = dtPerEmpleados.SUM("SumaEspecie", string.Format("CvePersonal = {0}", SRCvePersonal)); NConcepto Totales = new NConcepto(); Totales.CveConceptoD = 0; Totales.ConceptoD = "Total"; Totales.EstatusD = -3; Totales.ImporteD = dtPerEmpleados.SUM("Total", string.Format("CvePersonal = {0}", SRCvePersonal)); lconc.Add(SubTotales); if (especie.ImporteD > 0) { lconc.Add(especie); } lconc.Add(Totales); GvConceptos.DataSource = lconc; GvConceptos.DataBind(); } } protected void BtnImprimirsobrerecibo_Click(object sender, EventArgs e) { string filtros = "EsPadre = 1 AND EsFormula =0"; string filtros2 = ""; if (UsuarioActual.CveEmpresa == 141) { filtros2 = " CveConcepto =4714"; } if (filtros2.Length > 0) { filtros = string.Format("(({0}) OR({1}))", filtros, filtros2); } DataTable dtper = dtConceptos.FiltraParametros(string.Format("Tipo IN ('P') AND {0}", filtros)); DataTable dtded = dtConceptos.FiltraParametros(string.Format("Tipo IN ('D') AND {0}", filtros)); dtper.Columns.Add("BorradoLogico", typeof(int)); dtded.Columns.Add("BorradoLogico", typeof(int)); foreach (DataRow row in dtper.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)) != 0)) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtper.AcceptChanges(); foreach (DataRow row in dtded.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)) != 0)) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtded.AcceptChanges(); dtper = dtper.FiltraParametros("BorradoLogico=0"); dtded = dtded.FiltraParametros("BorradoLogico=0"); int maxper = dtper.Rows.Count; int maxded = dtded.Rows.Count; int i = 0; List lconc = new List(); for (i = 0; i < maxper || i < maxded; i++) { NConcepto nConcepto = new NConcepto(); DataRow row; if (maxper > i) { row = dtper.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); decimal ImporteGravado = dtPerEmpleados.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.CveConceptoP = CveConcepto; nConcepto.ConceptoP = Concepto; nConcepto.NoConceptoP = Codigo; nConcepto.ImporteP = Importe; nConcepto.ImporteGravadoP = ImporteGravado; nConcepto.isOnlyBisibleP = row["EsFormula"].ToString().ToEntero(); nConcepto.CveSistemaP = row["CveSistema"].ToString().ToEntero(); nConcepto.ValorP = dtPerEmpleados.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); } if (maxded > i) { row = dtded.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtPerEmpleados.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); decimal ImporteGravado = dtPerEmpleados.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.CveConceptoD = CveConcepto; nConcepto.ConceptoD = Concepto; nConcepto.NoConceptoD = Codigo; nConcepto.ImporteD = Importe; nConcepto.ImporteGravadoD = ImporteGravado; nConcepto.CveSistemaD = row["CveSistema"].ToString().ToEntero(); nConcepto.isOnlyBisibleD = row["EsFormula"].ToString().ToEntero(); nConcepto.ValorD = dtPerEmpleados.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); } lconc.Add(nConcepto); } lconc.Add(new NConcepto()); NConcepto SubTotales = new NConcepto(); SubTotales.CveConceptoP = 0; SubTotales.ConceptoP = "Total Percepciones"; SubTotales.EstatusP = -2; SubTotales.ImporteP = dtPerEmpleados.SUM("SumaPercepciones", string.Format("CvePersonal = {0}", SRCvePersonal)); SubTotales.ImporteGravadoP = dtPerEmpleados.SUM("SumaPercepcionesG", string.Format("CvePersonal = {0}", SRCvePersonal)); ///Alert(SubTotales.ImporteP.ToString()); SubTotales.CveConceptoD = 0; SubTotales.ConceptoD = "Total Deducciones"; SubTotales.EstatusD = -2; SubTotales.ImporteD = dtPerEmpleados.SUM("SumaDeducciones", string.Format("CvePersonal = {0}", SRCvePersonal)); NConcepto especie = new NConcepto(); especie.CveConceptoD = 0; especie.ConceptoD = "Especie"; especie.EstatusD = -3; especie.ImporteD = dtPerEmpleados.SUM("SumaEspecie", string.Format("CvePersonal = {0}", SRCvePersonal)); NConcepto Totales = new NConcepto(); Totales.CveConceptoD = 0; Totales.ConceptoD = "Total"; Totales.EstatusD = -3; Totales.ImporteD = dtPerEmpleados.SUM("Total", string.Format("CvePersonal = {0}", SRCvePersonal)); lconc.Add(SubTotales); if (especie.ImporteD > 0) { lconc.Add(especie); } lconc.Add(Totales); DataTable dtCon = new DataTable(); dtCon.Columns.Add(new DataColumn("NoConceptoP", typeof(string))); dtCon.Columns.Add(new DataColumn("ConceptoP", typeof(string))); dtCon.Columns.Add(new DataColumn("LabelValorP", typeof(string))); dtCon.Columns.Add(new DataColumn("CveConceptoP", typeof(int))); dtCon.Columns.Add(new DataColumn("ImporteP", typeof(double))); dtCon.Columns.Add(new DataColumn("ValorP", typeof(double))); dtCon.Columns.Add(new DataColumn("EstatusP", typeof(int))); dtCon.Columns.Add(new DataColumn("isEditedP", typeof(int))); dtCon.Columns.Add(new DataColumn("isOnlyBisibleP", typeof(int))); dtCon.Columns.Add(new DataColumn("NoConceptoD", typeof(string))); dtCon.Columns.Add(new DataColumn("ConceptoD", typeof(string))); dtCon.Columns.Add(new DataColumn("LabelValorD", typeof(string))); dtCon.Columns.Add(new DataColumn("CveConceptoD", typeof(int))); dtCon.Columns.Add(new DataColumn("ImporteD", typeof(double))); dtCon.Columns.Add(new DataColumn("ValorD", typeof(double))); dtCon.Columns.Add(new DataColumn("EstatusD", typeof(int))); dtCon.Columns.Add(new DataColumn("isEditedD", typeof(int))); dtCon.Columns.Add(new DataColumn("isOnlyBisibleD", typeof(int))); dtCon.Columns.Add(new DataColumn("CveSistemaD", typeof(int))); dtCon.Columns.Add(new DataColumn("CveSistemaP", typeof(int))); foreach (NConcepto itc in lconc) { DataRow dr = dtCon.NewRow(); dr["NoConceptoP"] = itc.NoConceptoP; dr["ConceptoP"] = itc.ConceptoP; dr["LabelValorP"] = itc.LabelValorP; dr["CveConceptoP"] = itc.CveConceptoP; dr["ImporteP"] = itc.ImporteP; dr["ValorP"] = itc.ValorP; dr["EstatusP"] = itc.EstatusP; dr["isEditedP"] = itc.isEditedP; dr["isOnlyBisibleP"] = itc.isOnlyBisibleP; dr["NoConceptoD"] = itc.NoConceptoD; dr["ConceptoD"] = itc.ConceptoD; dr["LabelValorD"] = itc.LabelValorD; dr["CveConceptoD"] = itc.CveConceptoD; dr["ImporteD"] = itc.ImporteD; dr["ValorD"] = itc.ValorD; dr["EstatusD"] = itc.EstatusD; dr["isEditedD"] = itc.isEditedD; dr["isOnlyBisibleD"] = itc.isOnlyBisibleD; dr["CveSistemaD"] = itc.CveSistemaD; dr["CveSistemaP"] = itc.CveSistemaP; dtCon.Rows.Add(dr); } dtCon.AcceptChanges(); List lrds = new List(); Microsoft.Reporting.WebForms.ReportDataSource rds = new Microsoft.Reporting.WebForms.ReportDataSource(); rds.Name = "DataSet1"; rds.Value = dtCon;// lconc; lrds.Add(rds); List parametros = new List(); string CodigoEmpleado = ""; string NombreCompleto = ""; string RFC = ""; string CURP = ""; string TipoPeriodo = ""; string NSS = ""; string DiasLaborados = ""; string DiasFaltados = ""; string DiasVacaciones = ""; string FechaInicio = ""; string FechaFin = ""; string DiasRetardos = ""; string DiasIncapacidad = ""; string SubProyecto = ""; string Usuario = UsuarioActual.Nombre; string FolioFiscal = ""; { DataRow drow = dtPerEmpleados.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); if (drow != null) { SubProyecto = drow["SubProyecto"].ToString(); FolioFiscal = string.Format("{0}", drow["FolioFiscal"]); DiasLaborados = string.Format("{0}", drow["DiasLaborados"].ToString().ToEntero()); DiasFaltados = string.Format("{0}", drow["DiasFaltados"].ToString().ToEntero()); DiasVacaciones = string.Format("{0}", drow["DiasVacaciones"].ToString().ToEntero()); FechaInicio = string.Format("{0:dd/MM/yyyy}", drow["FechaInicio"]); FechaFin = string.Format("{0:dd/MM/yyyy}", drow["FechaFin"]); DiasRetardos = string.Format("{0}", drow["DiasRetardos"].ToString().ToEntero()); DiasIncapacidad = string.Format("{0}", drow["DiasIncapacidad"].ToString().ToEntero()); } } //string Codigo = ""; using (ClsRH objrh = new ClsRH()) { if (objrh.GetPersonal(SRCvePersonal, UsuarioActual.CveEmpresa) && objrh.DtResultados.Rows.Count > 0) { DataRow drow = objrh.DtResultados.Rows[0]; CodigoEmpleado = drow["Codigo"].ToString(); NombreCompleto = drow["NombreCompleto"].ToString(); RFC = drow["RFC"].ToString(); CURP = drow["CURP"].ToString(); TipoPeriodo = drow["TipoPeriodo"].ToString(); NSS = drow["NSS"].ToString(); } } parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasIncapacidad", DiasIncapacidad)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("Codigo", CodigoEmpleado)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("NombreCompleto", NombreCompleto)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("RFC", RFC)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("CURP", CURP)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("TipoPeriodo", TipoPeriodo)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("NSS", NSS)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasLaborados", DiasLaborados)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasFaltados", DiasFaltados)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasVacaciones", DiasVacaciones)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FechaInicio", FechaInicio)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FechaFin", FechaFin)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasRetardos", DiasRetardos)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("Empresa", UsuarioActual.Empresa.Empresa)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("SubProyecto", SubProyecto)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FechaPago", "")); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FolioFiscal", FolioFiscal)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("Usuario", Usuario)); //parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("", "")); //parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("", "")); //parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("", "")); string urlfile = System.IO.Path.Combine(string.Format("{0}Formatos/SobreRecibo.rdlc", UsuarioActual.Empresa.Ruta)); if (!System.IO.File.Exists(urlfile)) { urlfile = System.IO.Path.Combine(ModExtensiones.DirectorioBaseEmpresas, "Empresas/Grales/Formatos/SobreRecibo.rdlc"); } ImprimirPDF(urlfile, lrds, parametros, "SobreRecibo", "PDF", null); } protected void BtnGuardarInfornavit_Click(object sender, EventArgs e) { double importe = TxtInfoValor.Text.ToDouble(); int TipoAplicacion = DdlInfoTipoAplicacion.SelectedValue.ToEntero(); int NoPagos = 0; double SaldoIni = 0; string descripcion02 = TxtInfoDescripcion.Text; string descripcion01 = TxtInfoNumCredito.Text; string fecha = TxtInfoFechaInicio.Text.Replace("_", ""); int estatus = ChkInfo.Checked ? 1 : 0; if (fecha.Length > 8) fecha = fecha.ToDateTime().ToString("yyyy/MM/dd"); else fecha = ""; bool continuar = true; using (ClsRH ObjPersonal = new ClsRH()) { if (!ObjPersonal.AddConcepto(SRCvePersonal, -1, importe, TipoAplicacion, NoPagos, SaldoIni, UsuarioActual.CveUsuario, 3, descripcion01, descripcion02, fecha, "", estatus, UsuarioActual.CveEmpresa)) continuar = false; } if (continuar) { cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); Alert("Se actualizo el calculo de infonavit"); } } int CveConceptoPolgvc, CveConceptoDolgvc; protected void GvConceptos_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.RowIndex == 0) { CveConceptoPolgvc = 1; CveConceptoDolgvc = 1; } // Datakeys // Concepto,CveConcepto,Importe,Estatus,ConceptoD,CveConceptoD,ImporteD,EstatusD int CveConcepto = e.Row.DataKey("CveConceptoP").ToEntero(); int CveConceptoD = e.Row.DataKey("CveConceptoD").ToEntero(); // Dim Importe As Decimal = e.Row.DataKey("Importe").ToDecimal() // Dim ImporteD As Decimal = e.Row.DataKey("ImporteD").ToDecimal() int Estatus = e.Row.DataKey("EstatusP").ToEntero(); int EstatusD = e.Row.DataKey("EstatusD").ToEntero(); int isOnlyBisibleP = e.Row.DataKey("isOnlyBisibleP").ToEntero(); int isOnlyBisibleD = e.Row.DataKey("isOnlyBisibleD").ToEntero(); bool isEditedP = e.Row.DataKey("isEditedP").ToEntero() > 0; bool isEditedD = e.Row.DataKey("isEditedD").ToEntero() > 0; bool isSavedP = e.Row.DataKey("isSavedP").ToEntero() > 0; bool isSavedD = e.Row.DataKey("isSavedD").ToEntero() > 0; //isEditedD // Controles Label LtlConcepto = e.Row.FCLabel("LtlConcepto"); LinkButton LnkConcepto = e.Row.FCLinkButton("LnkConcepto"); Label LtlConceptoD = e.Row.FCLabel("LtlConceptoD"); LinkButton LnkConceptoD = e.Row.FCLinkButton("LnkConceptod"); Label LtlImporte = e.Row.FCLabel("LtlImporte"); LinkButton LnkImporte = e.Row.FCLinkButton("LnkImporte"); Label LtlImporteD = e.Row.FCLabel("LtlImporteD"); LinkButton LnkImporteD = e.Row.FCLinkButton("LnkImporteD"); LinkButton LnkImportexCalculo = e.Row.FCLinkButton("LnkImportexCalculo"); LinkButton LnkImporteDxCalculo = e.Row.FCLinkButton("LnkImporteDxCalculo"); //isEditedD if (isOnlyBisibleP == 1) { e.Row.CssClass = string.Format("{0} isOnlyBisibleP", e.Row.CssClass); } if (isOnlyBisibleD == 1) { e.Row.CssClass = string.Format("{0} isOnlyBisibleD", e.Row.CssClass); } if (isEditedP) { e.Row.CssClass = string.Format("{0} isEditedP", e.Row.CssClass); } if (isEditedD) { e.Row.CssClass = string.Format("{0} isEditedD", e.Row.CssClass); } if (Estatus == -1) { LtlConcepto.Visible = false; } else if (Estatus > 0) { LtlImporte.Visible = false; } if (EstatusD == -1) { LtlConceptoD.Visible = false; } else if (EstatusD > 0) { LtlImporteD.Visible = false; } LtlImporte.Visible = false; LtlImporteD.Visible = false; if (Estatus < -1 | EstatusD < -1) { e.Row.CssClass = "ConceptosTotales"; LtlImporte.Visible = true; LtlImporteD.Visible = true; } LnkImporte.CommandArgument = (CveConcepto > 0 ? CveConcepto.ToString() : "P"); LnkImporteD.CommandArgument = (CveConceptoD > 0 ? CveConceptoD.ToString() : "D"); if (LnkImportexCalculo != null) { LnkImportexCalculo.CommandArgument = LnkImporte.CommandArgument; LnkImporteDxCalculo.CommandArgument = LnkImporteD.CommandArgument; } LnkImporte.Text = (CveConcepto > 0 ? string.Format("${0:N2}", e.Row.DataKey("ImporteP").ToDecimal()) : (CveConceptoPolgvc > 0 ? "" : "")); LnkImporteD.Text = (CveConceptoD > 0 ? string.Format("${0:N2}", e.Row.DataKey("ImporteD").ToDecimal()) : (CveConceptoDolgvc > 0 ? "" : "")); if (NomAutorizado) { LtlImporte.Visible = true; LtlImporteD.Visible = true; LtlImporte.Text = ((CveConcepto > 0 || e.Row.CssClass == "ConceptosTotales") ? string.Format("${0:N2}", e.Row.DataKey("ImporteP").ToDecimal()) : (CveConceptoPolgvc > 0 ? "" : "")); LtlImporteD.Text = ((CveConceptoD > 0 || e.Row.CssClass == "ConceptosTotales") ? string.Format("${0:N2}", e.Row.DataKey("ImporteD").ToDecimal()) : (CveConceptoDolgvc > 0 ? "" : "")); LnkImporte.Visible = false; LnkImporteD.Visible = false; LnkImportexCalculo.Visible = false; LnkImporteDxCalculo.Visible = false; } else { LnkImportexCalculo.Visible = isSavedP; LnkImporteDxCalculo.Visible = isSavedD; } if (CveConcepto == 0 && (Estatus == 0 || Estatus == -1 || Estatus == -3)) { LtlImporte.Text = ""; } if (CveConceptoD == 0 && (EstatusD == 0 || EstatusD == -1)) { LtlImporteD.Text = ""; } LnkConcepto.Visible = !LtlConcepto.Visible; LnkConceptoD.Visible = !LtlConceptoD.Visible; LnkImporte.Visible = !LtlImporte.Visible; LnkImporteD.Visible = !LtlImporteD.Visible; LinkButton LnkConceptoO = e.Row.FCLinkButton("LnkConceptoO"); LinkButton LnkImporteO = e.Row.FCLinkButton("LnkImporteO"); if (LnkConceptoO != null) { LnkConceptoO.Visible = false; LnkImporteO.Visible = false; if (e.Row.DBCampo("ImporteO").ToDecimal() == 0) { e.Row.FCLabel("LtlConceptoO").Visible = false; e.Row.FCLabel("LtlImporteO").Visible = false; if (e.Row.DataKey("isOnlyBisibleO").ToEntero() == 1) { e.Row.CssClass = string.Format("{0} isOnlyBisibleO", e.Row.CssClass); } } } CveConceptoPolgvc = CveConcepto; CveConceptoDolgvc = CveConceptoD; } } protected void GvConceptosSimula_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.RowIndex == 0) { CveConceptoPolgvc = 1; CveConceptoDolgvc = 1; } // Datakeys // Concepto,CveConcepto,Importe,Estatus,ConceptoD,CveConceptoD,ImporteD,EstatusD int CveConcepto = e.Row.DataKey("CveConceptoP").ToEntero(); int CveConceptoD = e.Row.DataKey("CveConceptoD").ToEntero(); // Dim Importe As Decimal = e.Row.DataKey("Importe").ToDecimal() // Dim ImporteD As Decimal = e.Row.DataKey("ImporteD").ToDecimal() int Estatus = e.Row.DataKey("EstatusP").ToEntero(); int EstatusD = e.Row.DataKey("EstatusD").ToEntero(); int isOnlyBisibleP = e.Row.DataKey("isOnlyBisibleP").ToEntero(); int isOnlyBisibleD = e.Row.DataKey("isOnlyBisibleD").ToEntero(); bool isEditedP = e.Row.DataKey("isEditedP").ToEntero() > 0; bool isEditedD = e.Row.DataKey("isEditedD").ToEntero() > 0; //isEditedD // Controles Label LtlConcepto = e.Row.FCLabel("LtlConcepto"); LinkButton LnkConcepto = e.Row.FCLinkButton("LnkConcepto"); Label LtlConceptoD = e.Row.FCLabel("LtlConceptoD"); LinkButton LnkConceptoD = e.Row.FCLinkButton("LnkConceptod"); Label LtlImporte = e.Row.FCLabel("LtlImporte"); LinkButton LnkImporte = e.Row.FCLinkButton("LnkImporte"); Label LtlImporteD = e.Row.FCLabel("LtlImporteD"); LinkButton LnkImporteD = e.Row.FCLinkButton("LnkImporteD"); LinkButton LnkImportexCalculo = e.Row.FCLinkButton("LnkImportexCalculo"); LinkButton LnkImporteDxCalculo = e.Row.FCLinkButton("LnkImporteDxCalculo"); //isEditedD if (isOnlyBisibleP == 1) { e.Row.CssClass = string.Format("{0} isOnlyBisibleP", e.Row.CssClass); } if (isOnlyBisibleD == 1) { e.Row.CssClass = string.Format("{0} isOnlyBisibleD", e.Row.CssClass); } if (isEditedP) { e.Row.CssClass = string.Format("{0} isEditedP", e.Row.CssClass); } if (isEditedD) { e.Row.CssClass = string.Format("{0} isEditedD", e.Row.CssClass); } if (Estatus == -1) { LtlConcepto.Visible = false; } else if (Estatus > 0) { LtlImporte.Visible = false; } if (EstatusD == -1) { LtlConceptoD.Visible = false; } else if (EstatusD > 0) { LtlImporteD.Visible = false; } LtlImporte.Visible = false; LtlImporteD.Visible = false; if (Estatus < -1 | EstatusD < -1) { e.Row.CssClass = "ConceptosTotales"; LtlImporte.Visible = true; LtlImporteD.Visible = true; } LnkImporte.CommandArgument = (CveConcepto > 0 ? CveConcepto.ToString() : "P"); LnkImporteD.CommandArgument = (CveConceptoD > 0 ? CveConceptoD.ToString() : "D"); if (LnkImportexCalculo != null) { LnkImportexCalculo.CommandArgument = LnkImporte.CommandArgument; LnkImporteDxCalculo.CommandArgument = LnkImporteD.CommandArgument; LnkImportexCalculo.Visible = isEditedP; LnkImporteDxCalculo.Visible = isEditedD; } LnkImporte.Text = (CveConcepto > 0 ? string.Format("${0:N2}", e.Row.DataKey("ImporteP").ToDecimal()) : (CveConceptoPolgvc > 0 ? "" : "")); LnkImporteD.Text = (CveConceptoD > 0 ? string.Format("${0:N2}", e.Row.DataKey("ImporteD").ToDecimal()) : (CveConceptoDolgvc > 0 ? "" : "")); if (CveConcepto == 0 && (Estatus == 0 || Estatus == -1 || Estatus == -3)) { LtlImporte.Text = ""; } if (CveConceptoD == 0 && (EstatusD == 0 || EstatusD == -1)) { LtlImporteD.Text = ""; } LnkConcepto.Visible = !LtlConcepto.Visible; LnkConceptoD.Visible = !LtlConceptoD.Visible; LtlImporte.Visible = true; LtlImporteD.Visible = true; LtlImporte.Text = LnkImporte.Text; LtlImporteD.Text = LtlImporteD.Text; LnkImporte.Visible = !LtlImporte.Visible; LnkImporteD.Visible = !LtlImporteD.Visible; LinkButton LnkConceptoO = e.Row.FCLinkButton("LnkConceptoO"); LinkButton LnkImporteO = e.Row.FCLinkButton("LnkImporteO"); if (LnkConceptoO != null) { LnkConceptoO.Visible = false; LnkImporteO.Visible = false; if (e.Row.DBCampo("ImporteO").ToDecimal() == 0) { e.Row.FCLabel("LtlConceptoO").Visible = false; e.Row.FCLabel("LtlImporteO").Visible = false; if (e.Row.DataKey("isOnlyBisibleO").ToEntero() == 1) { e.Row.CssClass = string.Format("{0} isOnlyBisibleO", e.Row.CssClass); } } } CveConceptoPolgvc = CveConcepto; CveConceptoDolgvc = CveConceptoD; } } protected void BtnGuardarMetododepago_Click(object sender, EventArgs e) { using (ClsNominas nom = new ClsNominas()) { if (nom.NominaUpMetododepago(UsuarioActual.CveEmpresa, SRCvePersonal, SRCvePeriodo, ChkMetodoPago.Checked, DdlMetodoPago.SelectedValue.ToEntero(), DdlBanco.SelectedValue.ToEntero(), TxtBancoNumCuenta.Text, TxtCLABE.Text)) { Alert("La informacion se ha actualizado correctamente"); } else { } } } #endregion protected void LnkPersonalizarNomina_Click(object sender, EventArgs e) { DtNomPersonalizarxls.Rows.Clear(); DataTable dtColumnas = GetTablaColumnasConceptos(); DdlMOPXColumna.DataSource = dtColumnas; DdlMOPXColumna.DataBind(); { addcoltopersonalizar("Codigo", "0", "Codigo", ""); addcoltopersonalizar("Nombre", "0", "Empleado", ""); addcoltopersonalizar("Sueldo Mensual", "0", "", ""); addcoltopersonalizar("Sueldo diario", "0", "", ""); addcoltopersonalizar("Dias Pen Pago", "0", "", ""); foreach (DataRow row in dtConceptos.FiltraParametros("Tipo ='P' AND EsPadre = 1 AND EsFormula =0").Rows) { if (!(dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { addcoltopersonalizar(row["Concepto"].ToString(), "1", string.Format("[V_{0}]", row["CveConcepto"].ToString()), row["Codigo"].ToString()); } } //addcoltopersonalizar("Percepciones", "1", "Percepciones", ""); addcoltopersonalizar("Incapacidad Permisos Faltas", "0", "", ""); foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'D' AND EsPadre = 1 AND EsFormula =0").Rows)// { if (!(dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { addcoltopersonalizar(row["Concepto"].ToString(), "1", string.Format("[V_{0}]", row["CveConcepto"].ToString()), row["Codigo"].ToString()); } } //addcoltopersonalizar("Deducciones", "1", "Deducciones", ""); addcoltopersonalizar("Neto a Pagar", "1", "Total", ""); //foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'O' AND EsPadre = 1 AND EsFormula =0").Rows)//EsFormula =0 //{ // if (!(dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) // { // addcoltopersonalizar(row["Concepto"].ToString(), "1", string.Format("[V_{0}]", row["CveConcepto"].ToString()), row["Codigo"].ToString()); // } //} //addcoltopersonalizar("Obligaciones", "1", "Obligaciones", ""); } GvPersonalizarExcel.DataSource = DtNomPersonalizarxls; GvPersonalizarExcel.DataBind(); UpPersonalizarxls.Update(); RegistraScript(string.Format("$('#divPersonalizarNomina').modal();")); // } public void addcoltopersonalizar(string Columna, string Tipo, string ColumnaDB, string TipoDB) { DataRow drorden = DtNomPersonalizarxls.NewRow(); drorden["Columna"] = Columna; drorden["Tipo"] = Tipo; drorden["ColumnaDB"] = ColumnaDB; drorden["TipoDB"] = TipoDB; DtNomPersonalizarxls.Rows.Add(drorden); } protected void LnkMoPXAgregar_Click(object sender, EventArgs e) { { DataRow drorden = DtNomPersonalizarxls.NewRow(); drorden["Columna"] = DdlMOPXColumna.SelectedItem.Text; drorden["Tipo"] = "0"; drorden["ColumnaDB"] = DdlMOPXColumna.SelectedItem.Value; //drorden["TipoDB"] = DdlMOTipo.SelectedItem.Value; DtNomPersonalizarxls.Rows.Add(drorden); } GvPersonalizarExcel.DataSource = DtNomPersonalizarxls; GvPersonalizarExcel.DataBind(); UpPersonalizarxls.Update(); } protected void LnkEliminarPersonalizar_Click(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)((LinkButton)sender).NamingContainer; string Columna = gvRow.DataKey("Columna"); string ColumnaDB = gvRow.DataKey("ColumnaDB"); string TipoDB = gvRow.DataKey("TipoDB"); DataRow dr = null; foreach (DataRow item in DtNomPersonalizarxls.Rows) { if (item["ColumnaDB"].ToString() == ColumnaDB && item["Columna"].ToString() == Columna) { dr = item; } } if (dr != null) { dr.Delete(); DtNomPersonalizarxls.AcceptChanges(); } GvPersonalizarExcel.DataSource = DtNomPersonalizarxls; GvPersonalizarExcel.DataBind(); UpPersonalizarxls.Update(); } private void Titlecell(ClosedXML.Excel.IXLWorksheet libro, object Valor, int fi, int ff, bool topBorder = true, bool bottomBorder = true, ClosedXML.Excel.XLColor borderColor = null) { ClosedXML.Excel.IXLCell celda = libro.Cell(fi, ff); celda.Value = Valor; if (borderColor != null) { if (topBorder) { celda.Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.TopBorderColor = borderColor; } celda.Style.Border.LeftBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.LeftBorderColor = borderColor; celda.Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.RightBorderColor = borderColor; if (bottomBorder) { celda.Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.BottomBorderColor = borderColor; } } } //IXLRange private void TitleRange(ClosedXML.Excel.IXLWorksheet libro, object Valor, int fi, int ff, int fi2, int ff2, bool topBorder = true, bool bottomBorder = true, ClosedXML.Excel.XLColor borderColor = null) { ClosedXML.Excel.IXLRange celda = libro.Range(fi, ff, fi2, ff2).Merge(); celda.Value = Valor; if (borderColor != null) { if (topBorder) { celda.Style.Border.TopBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.TopBorderColor = borderColor; } celda.Style.Border.LeftBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.LeftBorderColor = borderColor; celda.Style.Border.RightBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.RightBorderColor = borderColor; if (bottomBorder) { celda.Style.Border.BottomBorder = ClosedXML.Excel.XLBorderStyleValues.Medium; celda.Style.Border.BottomBorderColor = borderColor; } } } protected void LnkFormatoPersonalizado_Click(object sender, EventArgs e) { try { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var PercborderColor = ClosedXML.Excel.XLColor.FromArgb(0, 102, 0); var dedcborderColor = ClosedXML.Excel.XLColor.FromArgb(99, 37, 35); ClosedXML.Excel.XLColor colorperp = ClosedXML.Excel.XLColor.FromArgb(51, 153, 102); ClosedXML.Excel.XLColor colorded = ClosedXML.Excel.XLColor.FromArgb(150, 54, 52); ClosedXML.Excel.IXLCell celda; var libro = wb.AddWorksheet("Nomina"); int column = 1; int filainicio = 3; libro.Cell(filainicio + 1, column).Value = " "; libro.Cell(filainicio + 2, column).Value = "Codigo"; libro.Cell(filainicio + 3, column).Value = " "; column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Cell(filainicio + 2, column).Value = "Empleado"; libro.Cell(filainicio + 3, column).Value = " "; libro.Column(column).Width = 35; libro.Cell(1, 1).Value = "Empresa"; libro.Range(1, 2, 1, 4).Merge().Value = UsuarioActual.Empresa.Empresa; libro.Cell(2, 1).Value = "período"; string periodo = DdlPeriodo.SelectedItem.Text; periodo = periodo.Substring(0, (periodo.Length > 27 ? 27 : periodo.Length)); libro.Range(2, 2, 2, 4).Merge().Value = periodo; int iniciotipe = column; int incioConceptos = iniciotipe + 1; column++; Titlecell(libro, "Mensual", filainicio + 2, column, true, false, PercborderColor); Titlecell(libro, "Sueldo", filainicio + 3, column, false, true, PercborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, PercborderColor); libro.Column(column).Width = 15; column++; Titlecell(libro, "Sueldo", filainicio + 2, column, true, false, PercborderColor); Titlecell(libro, "diario", filainicio + 3, column, false, true, PercborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, PercborderColor); libro.Column(column).Width = 15; column++; Titlecell(libro, "dias Pen", filainicio + 2, column, true, false, PercborderColor); Titlecell(libro, "Pago", filainicio + 3, column, false, true, PercborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, PercborderColor); libro.Column(column).Width = 15; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo ='P' AND EsPadre = 1 AND EsFormula =0").Rows) { column++; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } else { Titlecell(libro, row["Concepto"].ToString(), filainicio + 2, column, true, false, PercborderColor); Titlecell(libro, row["Codigo"].ToString(), filainicio + 3, column, false, true, PercborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, PercborderColor); libro.Column(column).Width = 15; } } column++; TitleRange(libro, "Percepciones", filainicio + 2, column, filainicio + 3, column, true, true, PercborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, PercborderColor); libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; TitleRange(libro, "Percepciones", filainicio + 1, iniciotipe + 1, filainicio + 1, column, true, true, PercborderColor); libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Merge().Value = "Percepciones"; } iniciotipe = column; int finPercepciones = iniciotipe; column++; TitleRange(libro, "Incapacidad", filainicio + 2, column, filainicio + 2, column, true, false, dedcborderColor); TitleRange(libro, "Perm. Faltas", filainicio + 3, column, filainicio + 3, column, false, true, dedcborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, dedcborderColor); libro.Column(column).Width = 15; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'D' AND EsPadre = 1 AND EsFormula =0").Rows) { column++; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } else { Titlecell(libro, row["Concepto"].ToString(), filainicio + 2, column, true, false, dedcborderColor); Titlecell(libro, row["Codigo"].ToString(), filainicio + 3, column, false, true, dedcborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, dedcborderColor); libro.Column(column).Width = 15; } } column++; TitleRange(libro, "Deducciones", filainicio + 2, column, filainicio + 3, column, true, true, dedcborderColor); libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; TitleRange(libro, "Deducciones", filainicio + 1, iniciotipe + 1, filainicio + 1, column, true, true, dedcborderColor); Titlecell(libro, "", filainicio + 4, column, true, true, dedcborderColor); } int findeducciones = column; //column++; //libro.Cell(filainicio + 1, column).Value = " "; //libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Despensa"; //libro.Column(column).Width = 15; column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Total"; libro.Column(column).Width = 15; iniciotipe = column; int maxnocolumn = column; libro.Range(filainicio + 1, 1, filainicio + 4, maxnocolumn).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(filainicio + 1, 1, filainicio + 4, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(filainicio + 1, incioConceptos, filainicio + 4, finPercepciones).Style.Fill.SetBackgroundColor(colorperp); libro.Range(filainicio + 1, finPercepciones + 1, filainicio + 4, findeducciones).Style.Fill.SetBackgroundColor(colorded); int Fila = filainicio + 3; int cveSupProyecto = -5; string subproyecto = ""; string oldsubproyecto = ""; int oldcveSupProyecto = -5; bool newsubproyecto = false; bool newsubproyectoTitulo = false; List filasborrar = new List(); DataTable dtsr = dtempleados.FiltraParametros("", "CveSubProyecto"); dtsr.Rows.Add(dtsr.NewRow()); foreach (DataRow erow in dtsr.Rows) { Fila++; newsubproyecto = false; newsubproyectoTitulo = false; if (cveSupProyecto != erow["CveSubProyecto"].ToString().ToEntero()) { if (oldcveSupProyecto != -5) { Fila += 2; newsubproyecto = true; } oldcveSupProyecto = cveSupProyecto; cveSupProyecto = erow["CveSubProyecto"].ToString().ToEntero(); subproyecto = erow["SubProyecto"].ToString(); if (cveSupProyecto != -5 && oldcveSupProyecto != -5) { Fila++; newsubproyectoTitulo = true; } } column = 1; libro.Cell(Fila, column).Value = string.Format("'{0}", erow["Codigo"]); column++; if (newsubproyectoTitulo) { filasborrar.Add(Fila - 1); libro.Cell(Fila - 1, column).Value = subproyecto; libro.Range(Fila - 1, 1, Fila - 1, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(155, 194, 230)); } if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = string.Format("Total {0}", oldsubproyecto); libro.Range(Fila - 3, 1, Fila - 3, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(155, 194, 230)); } oldsubproyecto = subproyecto; libro.Cell(Fila, column).Value = erow["Nombre"]; column++; libro.Cell(Fila, column).Value = ""; column++; libro.Cell(Fila, column).Value = erow["SalarioDiario"]; libro.Cell(Fila, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;\"\""; column++; libro.Cell(Fila, column).Value = ""; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'P' AND EsPadre = 1 AND EsFormula =0").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; libro.Cell(Fila, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;\"\""; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); libro.Cell(Fila -3, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;"; } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(colorperp); Titlecell(libro, erow["SumaPercepciones"], Fila, column, false, false, PercborderColor); libro.Cell(Fila, column).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Cell(Fila, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;\"\""; if (newsubproyecto) { libro.Cell(Fila - 2, column).Style.Fill.SetBackgroundColor(colorperp); Titlecell(libro,"", Fila - 2, column, false, false, PercborderColor); libro.Cell(Fila - 3, column).Style.Fill.SetBackgroundColor(colorperp); libro.Cell(Fila - 3, column).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Cell(Fila-3, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;"; Titlecell(libro, dtempleados.SUM("SumaPercepciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)), Fila - 3, column, true, true, PercborderColor); //libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaPercepciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } column++; libro.Cell(Fila, column).Value = ""; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'D' AND EsPadre = 1 AND EsFormula =0").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; libro.Cell(Fila, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;\"\""; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); libro.Cell(Fila-3, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;"; } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(colorded); Titlecell(libro, erow["SumaDeducciones"], Fila, column, false, false, dedcborderColor); libro.Cell(Fila, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;\"\""; libro.Cell(Fila, column).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; if (newsubproyecto) { libro.Cell(Fila - 2, column).Style.Fill.SetBackgroundColor(colorded); Titlecell(libro, "", Fila - 2, column, false, false, dedcborderColor); libro.Cell(Fila - 3, column).Style.Fill.SetBackgroundColor(colorded); libro.Cell(Fila -3, column).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Cell(Fila-3, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;"; Titlecell(libro, dtempleados.SUM("SumaDeducciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)), Fila - 3, column, true, true, dedcborderColor); //libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaDeducciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } //column++; //libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); //libro.Cell(Fila, column).Value = erow["SumaEspecie"]; //if (newsubproyecto) //{ // libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaEspecie", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); //} column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["Total"]; libro.Cell(Fila, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;\"\""; if (newsubproyecto) { libro.Cell(Fila-2, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila-3, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila-3, column).Style.NumberFormat.Format = "#,##0.00;-#,##0.00;"; libro.Cell(Fila - 3, column).Value = dtempleados.SUM("Total", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } //foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'O' AND EsPadre = 1 ").Rows) //{ // column++; // string Concepto = string.Format("V_{0}", row["CveConcepto"]); // libro.Cell(Fila, column).Value = erow[Concepto]; // if (newsubproyecto) // { // libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); // } //} //column++; //libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); //libro.Cell(Fila, column).Value = erow["SumaObligaciones"]; //if (newsubproyecto) //{ // libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaObligaciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); //} } libro.Rows(Fila-2, Fila).Delete(); { var columnsToDelete = new List(); foreach (var columnx in libro.Columns()) { if (columnx.IsHidden) { columnsToDelete.Add(columnx.ColumnNumber()); } } // Eliminar columnas de mayor a menor para evitar conflictos de índice columnsToDelete.Sort(); columnsToDelete.Reverse(); foreach (var columnNumber in columnsToDelete) { libro.Column(columnNumber).Delete(); } } int primera = filasborrar.First(); filasborrar.Remove(primera); filasborrar.Reverse(); foreach (int rownumber in filasborrar) { libro.Rows(rownumber-1, rownumber).Delete(); } libro.Rows(primera, primera).Delete(); 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} {1}.xlsx", "Nomina tabular", periodo)); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } catch (Exception ex) { Alert("Ocurrio un error al generar el Formato de nominas" + ex.ToString()); } } protected void LnkFormatoTabular_Click(object sender, EventArgs e) { try { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("Nomina"); int column = 1; int filainicio = 3; libro.Cell(filainicio + 1, column).Value = " "; libro.Cell(filainicio + 2, column).Value = "Codigo"; libro.Cell(filainicio + 3, column).Value = " "; column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Cell(filainicio + 2, column).Value = "Empleado"; libro.Cell(filainicio + 3, column).Value = " "; libro.Column(column).Width = 35; libro.Cell(1, 1).Value = "Empresa"; libro.Range(1, 2, 1, 4).Merge().Value = UsuarioActual.Empresa.Empresa; libro.Cell(2, 1).Value = "período"; string periodo = DdlPeriodo.SelectedItem.Text; periodo = periodo.Substring(0, (periodo.Length > 27 ? 27 : periodo.Length)); libro.Range(2, 2, 2, 4).Merge().Value = periodo; int iniciotipe = column; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo ='P' AND EsPadre = 1 ").Rows) { column++; libro.Cell(filainicio + 2, column).Value = row["Concepto"].ToString(); libro.Cell(filainicio + 3, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } } column++; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Percepciones"; libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Merge().Value = "Percepciones"; } iniciotipe = column; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'D' AND EsPadre = 1 ").Rows) { column++; libro.Cell(filainicio + 2, column).Value = row["Concepto"].ToString(); libro.Cell(filainicio + 3, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } } column++; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Deducciones"; libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Merge().Value = "Deducciones"; } column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Despensa"; libro.Column(column).Width = 15; column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Total"; libro.Column(column).Width = 15; iniciotipe = column; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'O' AND EsPadre = 1 ").Rows) { column++; libro.Cell(filainicio + 2, column).Value = row["Concepto"].ToString(); libro.Cell(filainicio + 3, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } } column++; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Obligaciones"; libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Merge().Value = "Obligaciones"; } //libro.Row(1).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; //libro.Row(2).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; //libro.Row(3).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; //libro.Row(1).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(177, 160, 199)); //libro.Row(2).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); //libro.Row(3).Cell(1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); //libro.Row(3).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); int maxnocolumn = column; int Fila = filainicio + 3; int cveSupProyecto = -5; string subproyecto = ""; int oldcveSupProyecto = -5; bool newsubproyecto = false; bool newsubproyectoTitulo = false; DataTable dtsr = dtempleados.FiltraParametros("", "CveSubProyecto"); dtsr.Rows.Add(dtsr.NewRow()); foreach (DataRow erow in dtsr.Rows) { Fila++; newsubproyecto = false; newsubproyectoTitulo = false; if (cveSupProyecto != erow["CveSubProyecto"].ToString().ToEntero()) { if (oldcveSupProyecto != -5) { Fila += 2; newsubproyecto = true; } oldcveSupProyecto = cveSupProyecto; cveSupProyecto = erow["CveSubProyecto"].ToString().ToEntero(); subproyecto = erow["SubProyecto"].ToString(); if (cveSupProyecto != -5 && oldcveSupProyecto != -5) { Fila++; newsubproyectoTitulo = true; } } column = 1; libro.Cell(Fila, column).Value = string.Format("'{0}", erow["Codigo"]); column++; if (newsubproyectoTitulo) { libro.Cell(Fila - 1, column).Value = subproyecto; libro.Range(Fila - 1, 1, Fila - 1, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(155, 194, 230)); } if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = "Total"; libro.Range(Fila - 3, 1, Fila - 3, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(155, 194, 230)); } libro.Cell(Fila, column).Value = erow["Nombre"]; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'P' AND EsPadre = 1 ").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaPercepciones"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaPercepciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'D' AND EsPadre = 1 ").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaDeducciones"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaDeducciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaEspecie"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaEspecie", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["Total"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("Total", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'O' AND EsPadre = 1 ").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaObligaciones"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaObligaciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } libro.Range(filainicio + 1, 1, filainicio + 4, maxnocolumn).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(filainicio + 1, 1, filainicio + 4, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); 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} {1}.xlsx", "Nomina tabular", periodo)); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } catch (Exception ex) { Alert("Ocurrio un error al generar el Formato de nominas" + ex.ToString()); } } protected void LnkFormatoFiscal_Click(object sender, EventArgs e) { DataTable dtnominas = null; using (ClsNominas onom = new ClsNominas()) { if (onom.GetNom_Nominas(-1, -1, CvePeriodoSeleccionado, -1, UsuarioActual.CveEmpresa)) { dtnominas = onom.DtResultados; } } try { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("Nomina"); int column = 1; int filainicio = 3; libro.Cell(filainicio + 1, column).Value = " "; libro.Cell(filainicio + 2, column).Value = "Codigo"; libro.Cell(filainicio + 3, column).Value = " "; column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Cell(filainicio + 2, column).Value = "Empleado"; libro.Cell(filainicio + 3, column).Value = " "; column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Cell(filainicio + 2, column).Value = "Folio Fiscal"; libro.Cell(filainicio + 3, column).Value = " "; libro.Column(column).Width = 35; libro.Cell(1, 1).Value = "Empresa"; libro.Range(1, 2, 1, 4).Merge().Value = UsuarioActual.Empresa.Empresa; libro.Cell(2, 1).Value = "período"; string periodo = DdlPeriodo.SelectedItem.Text; periodo = periodo.Substring(0, (periodo.Length > 27 ? 27 : periodo.Length)); libro.Range(2, 2, 2, 4).Merge().Value = periodo; int iniciotipe = column; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo ='P' AND EsPadre = 1 ").Rows) { column++; libro.Cell(filainicio + 2, column).Value = row["Concepto"].ToString(); libro.Cell(filainicio + 3, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } } column++; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Percepciones"; libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Merge().Value = "Percepciones"; } iniciotipe = column; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'D' AND EsPadre = 1 ").Rows) { column++; libro.Cell(filainicio + 2, column).Value = row["Concepto"].ToString(); libro.Cell(filainicio + 3, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } } column++; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Deducciones"; libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Merge().Value = "Deducciones"; } column++; libro.Cell(filainicio + 1, column).Value = " "; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Total"; libro.Column(column).Width = 15; iniciotipe = column; foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'O' AND EsPadre = 1 ").Rows) { column++; libro.Cell(filainicio + 2, column).Value = row["Concepto"].ToString(); libro.Cell(filainicio + 3, column).Value = row["Codigo"].ToString(); libro.Column(column).Width = 15; if ((dtempleados.SUM(string.Format("[V_{0}]", row["CveConcepto"].ToString())) == 0)) { libro.Column(column).Hide(); } } column++; libro.Range(filainicio + 2, column, filainicio + 3, column).Merge().Value = "Obligaciones"; libro.Column(column).Width = 15; if (iniciotipe < column) { libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; libro.Range(filainicio + 1, iniciotipe + 1, filainicio + 1, column).Merge().Value = "Obligaciones"; } //libro.Row(1).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; //libro.Row(2).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; //libro.Row(3).CellsUsed().Style.Font.FontColor = ClosedXML.Excel.XLColor.White; //libro.Row(1).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(177, 160, 199)); //libro.Row(2).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); //libro.Row(3).Cell(1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); //libro.Row(3).CellsUsed().Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); int maxnocolumn = column; int Fila = filainicio + 3; int cveSupProyecto = -5; string subproyecto = ""; int oldcveSupProyecto = -5; bool newsubproyecto = false; bool newsubproyectoTitulo = false; DataTable dtsr = dtempleados.FiltraParametros("", "CveSubProyecto"); dtsr.Rows.Add(dtsr.NewRow()); foreach (DataRow erow in dtsr.Rows) { Fila++; newsubproyecto = false; newsubproyectoTitulo = false; if (cveSupProyecto != erow["CveSubProyecto"].ToString().ToEntero()) { if (oldcveSupProyecto != -5) { Fila += 2; newsubproyecto = true; } oldcveSupProyecto = cveSupProyecto; cveSupProyecto = erow["CveSubProyecto"].ToString().ToEntero(); subproyecto = erow["SubProyecto"].ToString(); if (cveSupProyecto != -5 && oldcveSupProyecto != -5) { Fila++; newsubproyectoTitulo = true; } } column = 1; libro.Cell(Fila, column).Value = string.Format("'{0}", erow["Codigo"]); column++; if (newsubproyectoTitulo) { libro.Cell(Fila - 1, column).Value = subproyecto; libro.Range(Fila - 1, 1, Fila - 1, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(155, 194, 230)); } if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = "Total"; libro.Range(Fila - 3, 1, Fila - 3, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(155, 194, 230)); } libro.Cell(Fila, column).Value = erow["Nombre"]; column++; if (dtnominas != null) { DataRow drw = dtnominas.FiltroPrimero(string.Format("CvePersonal = {0}", erow["CvePersonal"].ToString().ToEntero())); if (drw != null) { libro.Cell(Fila, column).Value = drw["FolioFiscal"]; } } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'P' AND EsPadre = 1 ").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaPercepciones"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaPercepciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'D' AND EsPadre = 1 ").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaDeducciones"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaDeducciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaEspecie"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaEspecie", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["Total"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("Total", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo = 'O' AND EsPadre = 1 ").Rows) { column++; string Concepto = string.Format("V_{0}", row["CveConcepto"]); libro.Cell(Fila, column).Value = erow[Concepto]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM(Concepto, string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } column++; libro.Cell(Fila, column).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(166, 166, 166)); libro.Cell(Fila, column).Value = erow["SumaObligaciones"]; if (newsubproyecto) { libro.Cell(Fila - 3, column).Value = dtempleados.SUM("SumaObligaciones", string.Format("CveSubProyecto ={0} AND CvePersonal > 0 ", oldcveSupProyecto)); } } libro.Range(filainicio + 1, 1, filainicio + 4, maxnocolumn).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(filainicio + 1, 1, filainicio + 4, maxnocolumn).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); 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} {1}.xlsx", "Nomina Fiscal", periodo)); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } catch (Exception ex) { Alert("Ocurrio un error al generar el Formato de nominas" + ex.ToString()); } } protected void LnkConceptoD_Click(object sender, EventArgs e) { } protected void LnkconsultartablasSubsidio_Click(object sender, EventArgs e) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetFistablasValues(UsuarioActual.CveEmpresa, 2, TxtejerciciotablasSubsidio.Text.Trim().ToEntero())) { GVVigSubEmpMensual.DataSource = objnom.DtResultados; GVVigSubEmpMensual.DataBind(); } UpModalTablas.Update(); } } protected void LnkconsultartablasISR_Click(object sender, EventArgs e) { loadtablas(Txtejerciciotablasisr.Text.Trim().ToEntero()); } public void loadtablas(int Ejercicio = -1) { CargaVacacionesEmpresas(); using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetTablasNomina(UsuarioActual.CveEmpresa, Ejercicio) && objnom.DTSetResultados.Tables.Count > 1) { GVFactorDesctInfonavit.DataSource = objnom.DTSetResultados.Tables[0]; GVSalariosMinimos.DataSource = objnom.DTSetResultados.Tables[1]; GVIMMSRiesgot.DataSource = objnom.DTSetResultados.Tables[2]; GVInfonavitSegViv.DataSource = objnom.DTSetResultados.Tables[3]; GVVigISRMensual.DataSource = objnom.DTSetResultados.Tables[4]; GVVigISRSemanal.DataSource = objnom.DTSetResultados.Tables[7]; GVVigISRDecenal.DataSource = objnom.DTSetResultados.Tables[8]; GVVigISRQuincenal.DataSource = objnom.DTSetResultados.Tables[9]; GVVigISRAnual.DataSource = objnom.DTSetResultados.Tables[10]; } if (objnom.GetFistablasValues(UsuarioActual.CveEmpresa, 2, TxtejerciciotablasSubsidio.Text.Trim().ToEntero())) { GVVigSubEmpMensual.DataSource = objnom.DtResultados; } if (objnom.RH_TablasValoresGet(UsuarioActual.CveEmpresa, 1)) { GVUma.DataSource = objnom.DtResultados; } } GVFactorDesctInfonavit.DataBind(); GVSalariosMinimos.DataBind(); GVIMMSRiesgot.DataBind(); GVInfonavitSegViv.DataBind(); GVVigISRMensual.DataBind(); GVVigSubEmpMensual.DataBind(); GVVigISRSemanal.DataBind(); GVVigISRDecenal.DataBind(); GVVigISRQuincenal.DataBind(); GVVigISRAnual.DataBind(); GVUma.DataBind(); UpModalTablas.Update(); } protected void LnkAddUMA_Click(object sender, EventArgs e) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.RH_TablasValoresAdd(UsuarioActual.CveEmpresa, TxtFechaUma.Text.ToDateTime(), 1, TxtValorUma.Text.ToDecimal())) { if (objnom.RH_TablasValoresGet(UsuarioActual.CveEmpresa, 1)) { GVUma.DataSource = objnom.DtResultados; GVUma.DataBind(); } Alert("La UMA se ha actualizado."); } } } protected void LnkEliminarUma_Click(object sender, EventArgs e) { GridViewRow gvrow = (GridViewRow)((LinkButton)sender).NamingContainer; DateTime fecha = gvrow.DataKey("Fecha").ToDateTime(); //DateTime tipo = gvrow.DataKey("Tipo").ToDateTime(); using (ClsNominas objnom = new ClsNominas()) { if (objnom.RH_TablasValoresRemove(UsuarioActual.CveEmpresa, TxtFechaUma.Text.ToDateTime(), 1)) { if (objnom.RH_TablasValoresGet(UsuarioActual.CveEmpresa, 1)) { GVUma.DataSource = objnom.DtResultados; GVUma.DataBind(); } Alert("La UMA se ha eliminado."); } } } protected void LnkVerTablas_Click(object sender, EventArgs e) { Txtejerciciotablasisr.Text = DateTime.Now.Year.ToString(); loadtablas(Txtejerciciotablasisr.Text.Trim().ToEntero()); RegistraScript("$('#ModalTablas').modal();"); } protected void LnkVerCalculoISR_Click(object sender, EventArgs e) { DataTable dt = dtempleados.FiltraParametros("CvePersonal >0", "", new string[] { "CvePersonal", "Nombre", "Codigo", "SumaPercepcionesG" }); //dt.Columns.Add("SumaPercepcionesG"); dt.Columns.Add("LimiteInferior", typeof(decimal)); dt.Columns.Add("ExedenteLI", typeof(decimal)); dt.Columns.Add("PorcentajeSE", typeof(decimal)); dt.Columns.Add("ImpuestoMarginal", typeof(decimal)); dt.Columns.Add("cuotafija", typeof(decimal)); dt.Columns.Add("Impuestoantessubs", typeof(decimal)); dt.Columns.Add("subsidio", typeof(decimal)); dt.Columns.Add("Impuesto", typeof(decimal)); DataTable dtquin = null; using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetTablasNomina(UsuarioActual.CveEmpresa, DateTime.Now.Year) && objnom.DTSetResultados.Tables.Count > 1) { //GVFactorDesctInfonavit.DataSource = objnom.DTSetResultados.Tables[0]; //GVSalariosMinimos.DataSource = objnom.DTSetResultados.Tables[1]; //GVIMMSRiesgot.DataSource = objnom.DTSetResultados.Tables[2]; //GVInfonavitSegViv.DataSource = objnom.DTSetResultados.Tables[3]; //GVVigISRMensual.DataSource = objnom.DTSetResultados.Tables[4]; //GVVigSubEmpMensual.DataSource = objnom.DTSetResultados.Tables[5]; //GVVigISRSemanal.DataSource = objnom.DTSetResultados.Tables[7]; //GVVigISRDecenal.DataSource = objnom.DTSetResultados.Tables[8]; //GVVigISRQuincenal.DataSource = objnom.DTSetResultados.Tables[9]; dtquin = objnom.DTSetResultados.Tables[9]; } //if (objnom.RH_TablasValoresGet(UsuarioActual.CveEmpresa, 1)) //{ // GVUma.DataSource = objnom.DtResultados; //} } if (dtquin != null) { foreach (DataRow item in dt.Rows) { decimal SumaPercepcionesG = item["SumaPercepcionesG"].ToString().ToDecimal(); decimal Limiteinferior = 0; decimal CuotaFija = 0; decimal Porcentaje = 0; foreach (DataRow drow in dtquin.Rows) { decimal limite = drow["Limite inferior"].ToString().ToDecimal(); if (limite > SumaPercepcionesG) { break; } else { Limiteinferior = drow["Limite inferior"].ToString().ToDecimal(); CuotaFija = drow["Cuota fija"].ToString().ToDecimal(); Porcentaje = drow["Porcentaje"].ToString().ToDecimal(); } } decimal Impuestomarginal = (SumaPercepcionesG - Limiteinferior) * (Porcentaje / 100); decimal Impuestoantessubs = Impuestomarginal + CuotaFija; item["LimiteInferior"] = Limiteinferior; item["ExedenteLI"] = SumaPercepcionesG - Limiteinferior; item["PorcentajeSE"] = Porcentaje; item["ImpuestoMarginal"] = Impuestomarginal; item["cuotafija"] = CuotaFija; item["Impuestoantessubs"] = Impuestoantessubs; item["subsidio"] = 0; item["Impuesto"] = Impuestoantessubs; //[Limite inferior],FORMAT(CuotaFija,'###,####,###0.00') [Cuota fija],FORMAT(Porcentaje,'###,####,###0.00') Porcentaje } dt.AcceptChanges(); } UpCalculoISR.Update(); GVCalculoISR.DataSource = dt; GVCalculoISR.DataBind(); RegistraScript("$('#ModalCalculoISR').modal();"); } private void ImprimirReporte() { string RutaDocumento = System.IO.Path.Combine(UsuarioActual.Empresa.Ruta, "/Lista de Raya.docx"); if (!System.IO.File.Exists(RutaDocumento)) { RutaDocumento = System.IO.Path.Combine(ModExtensiones.DirectorioBaseEmpresas, "Empresas/Grales/Lista de Raya.docx"); } DataTable dtpersonas = null; using (ClsRH ObjRH = new ClsRH()) { if (ObjRH.GetPersonal(-1, UsuarioActual.CveEmpresa)) { dtpersonas = ObjRH.DtResultados; } } if (dtempleados != null && dtempleados.Rows.Count > 0 && dtpersonas != null) { if (System.IO.File.Exists(RutaDocumento)) { try { clsGemBoxDocument GemDocumen = new clsGemBoxDocument(RutaDocumento); List listaTags = new List(); string strEmpresa = UsuarioActual.Empresa.Empresa; string strFechaInicio = ""; string strFechaFin = ""; string strTipo = ""; string strPeriodoNum = ""; string strUbicacion = string.Format("{0}, {1}, {2}, {3}, C.P. {4}", UsuarioActual.Empresa.Direccion, UsuarioActual.Empresa.Colonia, UsuarioActual.Empresa.Ciudad, UsuarioActual.Empresa.Estado, UsuarioActual.Empresa.CP).ToLower(); string strRegPatImss = "";// objPersonal.DtResultados.Rows(0)("RegistroPatronal").ToString(); string strRFC = UsuarioActual.Empresa.RFC; string strfecha = NowADS().ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.CreateSpecificCulture("es-MX")); string strhora = NowADS().ToString("HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("es-MX")); int CvePeriodo = DdlPeriodo.SelectedValue.ToEntero(); DataRow rperiodo = dtPeriodos.FiltroPrimero(string.Format("CvePeriodo = {0}", CvePeriodo)); if (rperiodo != null) { strFechaInicio = string.Format("{0:dd/MM/yyyy}", rperiodo["FechaInicio"]); strFechaFin = string.Format("{0:dd/MM/yyyy}", rperiodo["FechaFin"]); strPeriodoNum = rperiodo["Numero"].ToString(); strTipo = DdlTipoPeriodo.SelectedItem.Text; } listaTags.Add(new TagsDocumentos("[Empresa]", strEmpresa)); listaTags.Add(new TagsDocumentos("[FechaInicio]", strFechaInicio)); listaTags.Add(new TagsDocumentos("[FechaFin]", strFechaFin)); listaTags.Add(new TagsDocumentos("[Tipo]", strTipo)); listaTags.Add(new TagsDocumentos("[PeriodoNum]", strPeriodoNum)); listaTags.Add(new TagsDocumentos("[Ubicacion]", strUbicacion)); listaTags.Add(new TagsDocumentos("[RegPatImss]", strRegPatImss)); listaTags.Add(new TagsDocumentos("[RFC]", strRFC)); listaTags.Add(new TagsDocumentos("[fecha]", strfecha)); listaTags.Add(new TagsDocumentos("[hora]", strhora)); GemBox.Document.DocumentModel document = GemDocumen.documento; var section = document.Sections[0]; GemBox.Document.Tables.TableRow row; GemBox.Document.Tables.Table sobrereciboTable; GemBox.Document.Tables.Table tconeptos; GemBox.Document.Paragraph paragraphh; int CveSubProyecto = 0; string SubProyecto = ""; GemBox.Document.ParagraphStyle styilo = (GemBox.Document.ParagraphStyle)document.Styles.GetOrAdd(GemBox.Document.StyleTemplateType.Normal); GemBox.Document.ParagraphStyle styilostrong = (GemBox.Document.ParagraphStyle)document.Styles.GetOrAdd(GemBox.Document.StyleTemplateType.NoSpacing); //GemBox.Document.Style styilonegrita = GemBox.Document.Style.CreateStyle(GemBox.Document.StyleTemplateType.Strong, document); //document.Styles.Add(styilonegrita); foreach (DataRow drow in dtempleados.FiltraParametros("CvePersonal > 0", "", new string[] { "CveSubProyecto", "SubProyecto" }).Rows) { CveSubProyecto = drow["CveSubProyecto"].ToString().ToEntero(); SubProyecto = drow["SubProyecto"].ToString(); paragraphh = new GemBox.Document.Paragraph(document, SubProyecto); paragraphh.ParagraphFormat.Style = styilostrong; section.Blocks.Add(paragraphh); paragraphh = new GemBox.Document.Paragraph(document, "........................................................................................................................................................................"); section.Blocks.Add(paragraphh); foreach (DataRow drow2 in dtempleados.FiltraParametros(string.Format("CveSubProyecto={0}", CveSubProyecto)).Rows) { int CvePersonal = drow2["CvePersonal"].ToString().ToEntero(); sobrereciboTable = new GemBox.Document.Tables.Table(document); sobrereciboTable.TableFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(100, GemBox.Document.Tables.TableWidthUnit.Percentage); section.Blocks.Add(sobrereciboTable); row = new GemBox.Document.Tables.TableRow(document); sobrereciboTable.Rows.Add(row); var cell = new GemBox.Document.Tables.TableCell(document); row.Cells.Add(cell); /* string SalarioDiariop = ""; string FechaIngreso = "", Nombre = "", DiasLaborados = "";*/ paragraphh = new GemBox.Document.Paragraph(document, string.Format("{1} : {0} Centro de costos: {2}", drow2["Nombre"].ToString(), drow2["Codigo"].ToString(), drow2["SubProyecto"])); cell.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; // DataRow drh = dtpersonas.FiltroPrimero(string.Format("CvePersonal ={0}", CvePersonal)); if (drh != null) { paragraphh = new GemBox.Document.Paragraph(document, string.Format("CURP:{0} RFC:{1} Afiliación IMSS:{2} Puesto: {3}", drh["CURP"], drh["RFC"], drh["NumeroSS"], drh["Puesto"])); cell.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; } paragraphh = new GemBox.Document.Paragraph(document, string.Format("Fecha Ingr:{0:dd/MM/yyyy}, S.D.:{1:N2}, S.D.I.:{2:N2}, S.B.C.:{3:N2} ", drow2["FechaIngreso"], drow2["SalarioDiario"], drow2["SalarioDiarioIntegrado"], drow2["SalarioDiarioIMSS"])); cell.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; paragraphh = new GemBox.Document.Paragraph(document, string.Format("Días pagados:{0:N0}, Retardos: {1}, Ausencias:{2},Incapacidad:{3},Vacaciones Disfrutadas:{4},Vacaciones Pagadas:{5} ", drow2["DiasPago"], drow2["DiasRetardos"], drow2["DiasFaltados"], drow2["DiasIncapacidad"], drow2["DiasVacaciones"], drow2["DiasVacacionesPorPagar"])); cell.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; row = new GemBox.Document.Tables.TableRow(document); sobrereciboTable.Rows.Add(row); cell = new GemBox.Document.Tables.TableCell(document); row.Cells.Add(cell); tconeptos = new GemBox.Document.Tables.Table(document); tconeptos.TableFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(100, GemBox.Document.Tables.TableWidthUnit.Percentage); cell.Blocks.Add(tconeptos); GemBox.Document.Tables.TableRow rowx; GemBox.Document.Tables.TableCell cellx; { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Percepción"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Valor"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Importe"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Deducción"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Valor"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Importe"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } //Percepción Valor Importe Deducción Valor Importe bool gonext = true; int cindex = 0; while (gonext) { cindex = cindex + 1; int CveConcepto; string Concepto = ""; string Codigo = ""; string importe = ""; string valor = ""; rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); DataRow rowconcept = dtempleadosConceptos.FiltroPrimero(string.Format("CvePersonal={0} AND Tipo =1 AND EsFormula =0 AND FilaRaya ={1} AND Importe <> 0 ", CvePersonal, cindex)); if (rowconcept != null) { CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); importe = string.Format("${0:N2}", rowconcept["Importe"]); valor = string.Format("{0:#,###.##}", rowconcept["Valor"]); Concepto = ""; rowconcept = dtConceptos.FiltroPrimero(string.Format("CveConcepto={0}", CveConcepto)); if (rowconcept != null) { Concepto = rowconcept["Concepto"].ToString(); Codigo = rowconcept["Codigo"].ToString(); } } else { gonext = false; } //percepciones { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, valor); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } CveConcepto = 0; Concepto = ""; importe = ""; Codigo = ""; valor = ""; rowconcept = dtempleadosConceptos.FiltroPrimero(string.Format("CvePersonal={0} AND Tipo =2 AND EsFormula =0 AND FilaRaya ={1} AND Importe <> 0", CvePersonal, cindex)); if (rowconcept != null) { CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); importe = string.Format("${0:N2}", rowconcept["Importe"]); valor = string.Format("{0:#,###.##}", rowconcept["Valor"]); //string valor = ""; Concepto = ""; rowconcept = dtConceptos.FiltroPrimero(string.Format("CveConcepto={0}", CveConcepto)); if (rowconcept != null) { Concepto = rowconcept["Concepto"].ToString(); Codigo = rowconcept["Codigo"].ToString(); } gonext = true; } //deducciones { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, valor); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } } { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); } //Total Percepciones y deducciones { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total Percepciones"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", drow2["SumaPercepciones"])); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total Deducciones"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", drow2["SumaDeducciones"])); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } if (drow2["SumaEspecie"].ToString().ToDecimal() > 0) { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Especie"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", drow2["SumaEspecie"])); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Neto a Pagar"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", drow2["Total"])); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } setborderclear(tconeptos); keeptablesamepage(sobrereciboTable); } paragraphh = new GemBox.Document.Paragraph(document, "........................................................................................................................................................................"); section.Blocks.Add(paragraphh); paragraphh = new GemBox.Document.Paragraph(document, string.Format("Total Centro de costos {0}", SubProyecto.ToUpper())); paragraphh.ParagraphFormat.Style = styilostrong; section.Blocks.Add(paragraphh); #region "totaldepto" { sobrereciboTable = new GemBox.Document.Tables.Table(document); sobrereciboTable.TableFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(100, GemBox.Document.Tables.TableWidthUnit.Percentage); section.Blocks.Add(sobrereciboTable); row = new GemBox.Document.Tables.TableRow(document); sobrereciboTable.Rows.Add(row); var cell = new GemBox.Document.Tables.TableCell(document); row.Cells.Add(cell); tconeptos = new GemBox.Document.Tables.Table(document); tconeptos.TableFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(100, GemBox.Document.Tables.TableWidthUnit.Percentage); cell.Blocks.Add(tconeptos); GemBox.Document.Tables.TableRow rowx; GemBox.Document.Tables.TableCell cellx; //Percepción Valor Importe Deducción Valor Importe bool gonext = true; int cindex = 0; int OrdenP = -999; int ordenD = -999; #region "Titulos" { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Percepción"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Valor"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Importe"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Deducción"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Valor"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Importe"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } #endregion #region "Conceptos agrupador" while (gonext) { cindex = cindex + 1; int CveConcepto; string Concepto = ""; string Codigo = ""; string importe = ""; rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); DataRow rowconcept; rowconcept = dtConceptos.FiltroPrimero(string.Format("Orden>{0} AND EsFormula =0 AND Tipo ='P'", OrdenP), "Orden"); bool continuarconcepto = rowconcept != null; while (continuarconcepto) { decimal sumaimporte = dtempleadosConceptos.SUM("Importe", string.Format("CvePersonal > 0 AND CveSubProyecto={0} AND CveConcepto={1} AND Importe <> 0", CveSubProyecto, rowconcept["CveConcepto"])); OrdenP = rowconcept["Orden"].ToString().ToEntero(); if (sumaimporte != 0) { CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); importe = string.Format("${0:N2}", sumaimporte); Concepto = rowconcept["Concepto"].ToString(); Codigo = rowconcept["Codigo"].ToString(); continuarconcepto = false; } else { rowconcept = dtConceptos.FiltroPrimero(string.Format("Orden>{0} AND EsFormula =0 AND Tipo ='P'", OrdenP), "Orden"); continuarconcepto = rowconcept != null; } } //while (rowconcept == null || importe == "") //{ // double sumaimporte = dtempleadosConceptos.SUM("Importe", string.Format("CveSubProyecto={0} AND CveConcepto={1} AND Importe <> 0", CveSubProyecto, rowconcept["CveConcepto"])); // OrdenP = rowconcept["Orden"].ToString().ToEntero(); // if (sumaimporte > 0) // { // CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); // importe = string.Format("${0:N2}", sumaimporte); // Concepto = rowconcept["Concepto"].ToString(); // Codigo = rowconcept["Codigo"].ToString(); // } //} if (importe == "") { gonext = false; } //percepciones { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } CveConcepto = 0; Concepto = ""; importe = ""; Codigo = ""; rowconcept = dtConceptos.FiltroPrimero(string.Format("Orden>{0} AND EsFormula =0 AND Tipo ='D'", ordenD), "Orden"); continuarconcepto = rowconcept != null; while (continuarconcepto) { decimal sumaimporte = dtempleadosConceptos.SUM("Importe", string.Format("CvePersonal > 0 AND CveSubProyecto={0} AND CveConcepto={1} AND Importe <> 0", CveSubProyecto, rowconcept["CveConcepto"])); ordenD = rowconcept["Orden"].ToString().ToEntero(); if (sumaimporte != 0) { CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); importe = string.Format("${0:N2}", sumaimporte); Concepto = rowconcept["Concepto"].ToString(); Codigo = rowconcept["Codigo"].ToString(); continuarconcepto = false; } else { rowconcept = dtConceptos.FiltroPrimero(string.Format("Orden>{0} AND EsFormula =0 AND Tipo ='D'", ordenD), "Orden"); continuarconcepto = rowconcept != null; } } if (importe != "") { gonext = true; } //deducciones { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } } #endregion { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); } { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total Percepciones"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("SumaPercepciones", string.Format(" CvePersonal > 0 AND CveSubProyecto={0}", CveSubProyecto)))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total Deducciones"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("SumaDeducciones", string.Format("CvePersonal > 0 AND CveSubProyecto={0}", CveSubProyecto)))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } if (dtempleados.SUM("SumaEspecie", string.Format("CvePersonal > 0 AND CveSubProyecto={0}", CveSubProyecto)) > 0) { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Especie"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("SumaEspecie", string.Format("CvePersonal > 0 AND CveSubProyecto={0}", CveSubProyecto)))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; //SumaEspecie } } //no empleados { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total de empleados"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("{0:N0}", dtempleados.COUNT("CvePersonal", string.Format("CvePersonal > 0 AND CveSubProyecto={0}", CveSubProyecto)))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; } } //Neto depto { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Neto del Centro de costos"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("Total", string.Format("CvePersonal > 0 AND CveSubProyecto={0}", CveSubProyecto)))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } setborderclear(tconeptos); keeptablesamepage(sobrereciboTable); } #endregion section.Blocks.Add(new GemBox.Document.Paragraph(document, new GemBox.Document.SpecialCharacter(document, GemBox.Document.SpecialCharacterType.PageBreak))); } paragraphh = new GemBox.Document.Paragraph(document, "TOTAL "); paragraphh.ParagraphFormat.Style = styilostrong; section.Blocks.Add(paragraphh); #region "total" { sobrereciboTable = new GemBox.Document.Tables.Table(document); sobrereciboTable.TableFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(100, GemBox.Document.Tables.TableWidthUnit.Percentage); section.Blocks.Add(sobrereciboTable); row = new GemBox.Document.Tables.TableRow(document); sobrereciboTable.Rows.Add(row); var cell = new GemBox.Document.Tables.TableCell(document); row.Cells.Add(cell); tconeptos = new GemBox.Document.Tables.Table(document); tconeptos.TableFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(100, GemBox.Document.Tables.TableWidthUnit.Percentage); cell.Blocks.Add(tconeptos); GemBox.Document.Tables.TableRow rowx; GemBox.Document.Tables.TableCell cellx; //Percepción Valor Importe Deducción Valor Importe bool gonext = true; int cindex = 0; int OrdenP = -999; int ordenD = -999; //Titulos { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Percepción"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Valor"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Importe"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Deducción"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Valor"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Importe"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } //conceptos percep,deduc while (gonext) { cindex = cindex + 1; int CveConcepto; string Concepto = ""; string Codigo = ""; string importe = ""; rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); DataRow rowconcept; while ((rowconcept = dtConceptos.FiltroPrimero(string.Format("Orden>{0} AND EsFormula =0 AND Tipo ='P'", OrdenP), "Orden")) != null && importe == "") { decimal sumaimporte = dtempleadosConceptos.SUM("Importe", string.Format("CvePersonal > 0 AND CveConcepto={0}", rowconcept["CveConcepto"])); OrdenP = rowconcept["Orden"].ToString().ToEntero(); if (sumaimporte != 0) { CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); importe = string.Format("${0:N2}", sumaimporte); Concepto = rowconcept["Concepto"].ToString(); Codigo = rowconcept["Codigo"].ToString(); } } if (importe == "") { gonext = false; } //percepciones { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } CveConcepto = 0; Concepto = ""; importe = ""; Codigo = ""; while ((rowconcept = dtConceptos.FiltroPrimero(string.Format("Orden>{0} AND EsFormula =0 AND Tipo ='D'", ordenD), "Orden")) != null && importe == "") { decimal sumaimporte = dtempleadosConceptos.SUM("Importe", string.Format("CvePersonal > 0 AND CveConcepto={0}", rowconcept["CveConcepto"])); ordenD = rowconcept["Orden"].ToString().ToEntero(); if (sumaimporte != 0) { CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); importe = string.Format("${0:N2}", sumaimporte); Concepto = rowconcept["Concepto"].ToString(); Codigo = rowconcept["Codigo"].ToString(); } } if (importe != "") { gonext = true; } //deducciones { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } } { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); } //Totales perceciones deducciones { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total Percepciones"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("SumaPercepciones", "CvePersonal > 0 "))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total Deducciones"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("SumaDeducciones", "CvePersonal > 0 "))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; //SumaEspecie } } { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total de empleados general"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("{0:N0}", dtempleados.COUNT("CvePersonal", "CvePersonal > 0"))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; } } //neto empresa { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Neto general"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("Total", "CvePersonal > 0"))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } gonext = true; int OrdenO = -999; //basura para espacio { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, " "); cellx.Blocks.Add(paragraphh); } rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, " "); cellx.Blocks.Add(paragraphh); } } rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Obligación"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Importe"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } while (gonext) { cindex = cindex + 1; int CveConcepto; string Concepto = ""; string Codigo = ""; string importe = ""; rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.ColumnSpan = 2; paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; //cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); //cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); //paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; //paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } } DataRow rowconcept; while ((rowconcept = dtConceptos.FiltroPrimero(string.Format("Orden>{0} AND EsFormula =0 AND Tipo ='O'", OrdenO), "Orden")) != null && importe == "") { decimal sumaimporte = dtempleadosConceptos.SUM("Valor", string.Format("CvePersonal > 0 AND CveConcepto={0}", rowconcept["CveConcepto"])); OrdenO = rowconcept["Orden"].ToString().ToEntero(); if (sumaimporte != 0) { CveConcepto = rowconcept["CveConcepto"].ToString().ToEntero(); importe = string.Format("${0:N2}", sumaimporte); Concepto = rowconcept["Concepto"].ToString(); Codigo = rowconcept["Codigo"].ToString(); } } if (importe == "") { gonext = false; } //Obligaciones { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Codigo); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, Concepto); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, importe); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; } } { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); } { rowx = new GemBox.Document.Tables.TableRow(document); tconeptos.Rows.Add(rowx); { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, " "); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } { cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(3, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(30, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, "Total Obligaciones"); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(6, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, ""); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilo; cellx = new GemBox.Document.Tables.TableCell(document); rowx.Cells.Add(cellx); cellx.CellFormat.PreferredWidth = new GemBox.Document.Tables.TableWidth(11, GemBox.Document.Tables.TableWidthUnit.Percentage); paragraphh = new GemBox.Document.Paragraph(document, string.Format("${0:N2}", dtempleados.SUM("SumaObligaciones"))); cellx.Blocks.Add(paragraphh); paragraphh.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; paragraphh.ParagraphFormat.Style = styilostrong; } } setborderclear(tconeptos); keeptablesamepage(tconeptos); keeptablesamepage(sobrereciboTable); } #endregion GemDocumen.SustituirTags(listaTags); GemDocumen.GuardarStreamPDF(); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(GemDocumen.GetBytesDocumento()); GemDocumen.Dispose(); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", $"attachment;filename=Lista de Raya.pdf"); Response.Buffer = true; memoryStream.WriteTo(Response.OutputStream); try { Response.End(); } catch (Exception) { } } catch (Exception e) { Extensiones.ModExtensiones.GuardaLog(string.Format("Nomina2(errorLayout):{0} ", e.ToString())); Alert("No se pudo generar la lista de raya favor de contactar a soporte tecnico.", Extensiones.ModExtensiones.TipoMensaje.ToastError); RegistraScript(string.Format("console.error('Nomina2(errorLayout):{0}'); ", e.ToString().Replace("'", "\\'"))); } } else { Alert("No se encontro la plantilla.", Extensiones.ModExtensiones.TipoMensaje.ToastAdventencia); } } else { Alert("es necesario calcular el periodo primero.", Extensiones.ModExtensiones.TipoMensaje.ToastAdventencia); } } #region "Gembox" private void keeptablesamepage(GemBox.Document.Tables.Table table) { //Mantener tabla unida { // Get all Paragraph formats in a Table element. IEnumerable formats = table.GetChildElements(true, GemBox.Document.ElementType.TableCell) .Cast() .SelectMany(cell => { if (cell.Blocks.Count == 0) cell.Blocks.Add(new GemBox.Document.Paragraph(cell.Document)); return cell.GetChildElements(true, GemBox.Document.ElementType.Paragraph); }) .Cast() .Select(p => p.ParagraphFormat); // Set KeepLinesTogether and KeepWithNext properties. foreach (GemBox.Document.ParagraphFormat format in formats) { format.KeepLinesTogether = true; format.KeepWithNext = true; } } } private void setborderclear(GemBox.Document.Tables.Table table) { table.TableFormat.Borders.SetBorders(GemBox.Document.MultipleBorderTypes.All, GemBox.Document.BorderStyle.None, GemBox.Document.Color.Empty, 0); foreach (var row in table.Rows) { foreach (var cell in row.Cells) { cell.CellFormat.Borders.ClearBorders(); } } } #endregion protected void LnkListaRaya_Click(object sender, EventArgs e) { ImprimirReporte(); } #region Movtos Permanentes protected void CargaTipoConcepto() { //DdlTipo.Items.Insert(0, new ListItem("Percepciones", "P")); //DdlTipo.Items.Insert(1, new ListItem("Deducciones", "D")); //DdlTipo.Items.Insert(2, new ListItem("Obligaciones", "O")); //DdlTipo.SelectedValueExist("-1"); CargaConcepto(); } protected void CargaConcepto() { DataTable dt = dtNomConceptos.FiltraParametros(" FormulaTotal = 'FNC.[MovimientosPermanentes]'"); DdlConcepto.Items.Clear(); if (DdlTipo.SelectedValue.Contiene("P", "D", "O")) { DdlConcepto.DataSource = dt.FiltraParametros(string.Format("Tipo ='{0}'", DdlTipo.SelectedValue)); } DataRow drow = dt.NewRow(); drow["CveConcepto"] = "-1"; drow["Concepto"] = "Seleccione"; dt.Rows.InsertAt(drow, 0); DdlConcepto.DataSource = dt; DdlConcepto.SelectedValueExist("-1"); DdlConcepto.DataBind(); //DdlConcepto.Items.Insert(0, new ListItem("Seleccione", "-1")); } private void CargaMovtoPermanente() { using (ClsNominas ObjMovt = new ClsNominas()) { ObjMovt.GetMovtoPermanente(UsuarioActual.CveEmpresa, SRCvePersonal); GVMovtoPermanente.DataSource = ObjMovt.DtResultados; } GVMovtoPermanente.DataBind(); UpMovtosPermanentes.Update(); } protected void DdlTipo_SelectedIndexChanged(object sender, EventArgs e) { CargaConcepto(); } protected void LnkAddMovtoPermanente_Click(object sender, EventArgs e) { CargaConcepto(); DdlTipoDescto_SelectedIndexChanged(null, null); pnlAddupMovto.Visible = true; LnkAddMovto.Visible = true; LnkUpMovto.Visible = false; LtlMovtoPermanenteaddup.Text = "Agregar Movimiento"; TxtDescripcion.Text = ""; TxtValor.Text = ""; TxtVecesAplicar.Text = ""; TxtMontoLimite.Text = ""; TxtFechaAplicacion.Text = ""; ChkEstatus.Visible = true; ChkEstatus.Checked = true; UpMovtosPermanentesModal.Update(); RegistraScript("$('#ModalMovtoPermanente').modal()"); } protected void LnkAddMovto_Click(object sender, EventArgs e) { int cveConcepto = DdlConcepto.SelectedValue.ToEntero(); string descripcion = TxtDescripcion.Text; int tipoDescuento = DdlTipoDescto.SelectedValue.ToEntero(); double valor = TxtValor.Text.ToDouble(); int vecesAplicar = TxtVecesAplicar.Text.ToEntero(); decimal montoLimite = TxtMontoLimite.Text.ToDecimal(); DateTime fechaInicioAplicacion = TxtFechaAplicacion.Text.ToDate(); bool estatus = ChkEstatus.Checked; int CveCuenta = DdlCtaContable.SelectedValue.ToEntero() * (DdlCtaContable.DataValueField == "Id" ? -1 : 1); bool Continuar; using (ClsNominas ObjMovt = new ClsNominas()) { Continuar = ObjMovt.AddMovtoPermanente(cveConcepto, SRCvePersonal, descripcion, tipoDescuento, valor, vecesAplicar, montoLimite, fechaInicioAplicacion, estatus, CveCuenta) > 0; } if (Continuar) { RegistraScript("$('#DModalMovtoPermanente').modal('hide');"); CargaMovtoPermanente(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpMovtosPermanentes.Update(); UpModalConceptos.Update(); Alert("Se ha agregado el movimiento permanente"); } RegistraScript("$('#ModalMovtoPermanente').modal('hide')"); } protected void LnkUpMovto_Click(object sender, EventArgs e) { int cveConcepto = DdlConcepto.SelectedValue.ToEntero(); string descripcion = TxtDescripcion.Text; int tipoDescuento = DdlTipoDescto.SelectedValue.ToEntero(); double valor = TxtValor.Text.ToDouble(); int vecesAplicar = TxtVecesAplicar.Text.ToEntero(); decimal montoLimite = TxtMontoLimite.Text.ToDecimal(); DateTime fechaInicioAplicacion = TxtFechaAplicacion.Text.ToDate(); bool estatus = ChkEstatus.Checked; int CveCuenta = DdlCtaContable.SelectedValue.ToEntero() * (DdlCtaContable.DataValueField == "Id" ? -1 : 1); bool Continuar; using (ClsNominas ObjMovt = new ClsNominas()) { Continuar = ObjMovt.UpMovtoPermanente(CcveMovtoPermanente, cveConcepto, SRCvePersonal, descripcion, tipoDescuento, valor, vecesAplicar, montoLimite, fechaInicioAplicacion, estatus, CveCuenta); } if (Continuar) { RegistraScript("$('#ModalMovtoPermanente').modal('hide');"); CargaMovtoPermanente(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpMovtosPermanentes.Update(); UpModalConceptos.Update(); Alert("Se ha actualizado el movimiento permanente"); } } protected void DdlTipoDescto_SelectedIndexChanged(object sender, EventArgs e) { pnlMonto.Visible = DdlTipoDescto.SelectedValue.ToEntero() > 2; pnlVecesAplicar.Visible = DdlTipoDescto.SelectedValue.ToEntero() < 3; } protected void LnkremoveMovtoPermanente_Click(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)(((LinkButton)sender).NamingContainer); CcveMovtoPermanente = gvRow.DataKey("CveMovtoPermanente").ToEntero(); bool Continuar = false; using (ClsNominas ObjMovt = new ClsNominas()) { Continuar = ObjMovt.RemoveMovtoPermanente(CcveMovtoPermanente); } if (Continuar) { RegistraScript("$('#ModalMovtoPermanente').modal('hide');"); CargaMovtoPermanente(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); UpMovtosPermanentes.Update(); Alert("Se ha eliminadó el movimiento permanente"); } } protected void LnkEditarMovtoPermanente_Click(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)(((LinkButton)sender).NamingContainer); CcveMovtoPermanente = gvRow.DataKey("CveMovtoPermanente").ToEntero(); int cveConcepto = gvRow.DataKey("CveConcepto").ToEntero(); int cvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); int CveCuenta = gvRow.DataKey("CveCuenta").ToEntero(); string descripcion = gvRow.DataKey("Descripcion"); int tipoDescuento = gvRow.DataKey("TipoDescuento").ToEntero(); double valor = gvRow.DataKey("Valor").ToDouble(); int vecesAplicar = gvRow.DataKey("VecesAplicar").ToEntero(); decimal montoLimite = gvRow.DataKey("MontoLimite").ToDecimal(); DateTime fechaInicioAplicacion = gvRow.DataKey("FechaInicioAplicacion").ToDate(); bool estatus = gvRow.DataKey("Estatus") == "1" || gvRow.DataKey("Estatus").ToUpper() == "TRUE"; DateTime fechaRegistro = gvRow.DataKey("FechaRegistro").ToDateTime(); string tipo = "P"; DataRow drow = dtNomConceptos.FiltroPrimero(string.Format("CveConcepto ='{0}'", cveConcepto)); if (drow != null) { tipo = drow["Tipo"].ToString(); DdlTipo.SelectedValueExist(tipo); DdlTipo_SelectedIndexChanged(null, null); } using (ClsNominas ObjMovt = new ClsNominas()) { ObjMovt.GetMovtoPermanenteSaldos(UsuarioActual.CveEmpresa, SRCvePersonal, CcveMovtoPermanente); GVMovtoPermanenteSaldos.DataSource = ObjMovt.DtResultados; GVMovtoPermanenteSaldos.DataBind(); } CargaConcepto(); DdlConcepto.SelectedValueExist(cveConcepto); TxtDescripcion.Text = descripcion.ToString(); DdlTipoDescto.SelectedValueExist(tipoDescuento.ToString()); DdlTipoDescto_SelectedIndexChanged(null, null); TxtValor.Text = valor.ToString(); TxtVecesAplicar.Text = vecesAplicar.ToString(); TxtMontoLimite.Text = montoLimite.ToString(); TxtFechaAplicacion.Text = $"{fechaInicioAplicacion:dd/MM/yyyy}"; DdlCtaContable.SelectedValueExist("-1"); ChkEstatus.Checked = estatus; RegistraScript("$('#ModalMovtoPermanente').modal()"); pnlAddupMovto.Visible = true; LnkAddMovto.Visible = false; LnkUpMovto.Visible = true; UpMovtosPermanentesModal.Update(); } #endregion protected void LnkAutorizar_Click(object sender, EventArgs e) { cargaDatos(false, -1); if (autorizarNomina(-1)) { using (ClsNominas objNomina = new ClsNominas()) { if (objNomina.GetPeriodos(-1, UsuarioActual.CveEmpresa, -1, -1, CvePeriodoSeleccionado) && objNomina.DtResultados.Rows.Count > 0) { DataRow drow = objNomina.DtResultados.Rows[0]; int Estatus = drow["Estatus"].ToString().ToEntero(); if (Estatus < 2) { objNomina.CambiaEstatusPeriodo(CvePeriodoSeleccionado, 2, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa); }; } } } } protected void LnkCancelarNomina_Click(object sender, EventArgs e) { DataTable dtr = dtempleados.FiltraParametros("CvePersonal > 0 AND NomAutorizado =1 AND SeTimbro=0", "", new string[] { "CveNomina" }); bool continuar = true; using (ClsNominas Nom = new ClsNominas()) { Nom.IniciaTransacSQL(); //AutorizaNom_Nominas foreach (DataRow drow in dtr.Rows) { if (continuar && (continuar = Nom.RemoveNom_Nominas(drow["CveNomina"].ToString().ToEntero(), false, UsuarioActual.CveUsuario))) { } } if (continuar) { Nom.Commit(); } } if (continuar) { Alert("Los movimientos de la nómina fueron eliminados", TipoMensaje.MsgInformacion); cargaDatos(); } } private bool autorizarNomina(int FiltroCvePersonal) { bool continuar = true; int chkImporte = 1; int chkImporteGravado = 1; int chkImporteValor = 1; string[] getcolumnas = new string[] { "CvePersonal", "Nombre", "CveMetodoPago", "SumaPercepciones", "Total", "SalarioDiario", "SalarioDiarioIMSS", "SalarioDiarioIntegrado", "DiasLaborados", "DiasFaltados", "DiasVacaciones", "DiasIncapacidad" }; DataTable dtr = dtempleados.FiltraParametros(string.Format("(CvePersonal={0} OR {0}=-1) AND CvePersonal > 0 AND NomAutorizado =0 AND SumaPercepciones > 0 AND Total >= 0", FiltroCvePersonal), "", getcolumnas); DataTable dtconp = null; //int CvePeriodoSeleccionado = DdlPeriodo.SelectedValue.ToEntero();//cambiar reparar #region PropNomina int CvePersonal = 0; int CveNomina = 0; int CveMetodoPago = 0; double SubTotal = 0; double Total = 0; int CveMoneda = 1; #endregion #region PropNominaDetalle int CveConcepto = 0; decimal ImporteConcepto = 0, ImporteGravadoConcepto = 0, ImporteExentoConcepto = 0, ImporteValor = 0; #endregion string erroralturizar = ""; DataTable dtrFail = dtempleados.FiltraParametros(string.Format("(CvePersonal= {0} OR {0}=-1) AND CvePersonal > 0 AND NomAutorizado = 0 AND SumaPercepciones > 0 AND Total < 0", FiltroCvePersonal), "", getcolumnas); StringBuilder strbuilder = new StringBuilder(); foreach (DataRow itf in dtrFail.Rows) { strbuilder.AppendLine(String.Format("
{0} con neto a pagar {1} ", itf["Nombre"], itf["Total"])); } if (dtrFail.Rows.Count > 0) { erroralturizar = string.Format("
no se autorizaron los siguientes empleados con neto a pagar negativo para evitar inconsistencias{0}", strbuilder.ToString()); } using (ClsNominas objNomina = new ClsNominas()) { objNomina.IniciaTransacSQL(); foreach (DataRow rtemp in dtr.Rows) { CveNomina = 0; CvePersonal = rtemp["CvePersonal"].ToString().ToEntero(); CveMetodoPago = rtemp["CveMetodoPago"].ToString().ToEntero(); SubTotal = rtemp["SumaPercepciones"].ToString().ToDouble(); Total = rtemp["Total"].ToString().ToDouble(); if (CvePersonal > 0) { if (continuar) { if (objNomina.GetNom_Nominas(-1, CvePersonal, CvePeriodoSeleccionado, -1, UsuarioActual.CveEmpresa)) { if (objNomina.DtResultados.Rows.Count > 0) { CveNomina = objNomina.CveNomina; } else { if (objNomina.AddNom_Nominas(-1, 1, CvePersonal, CvePeriodoSeleccionado, SubTotal, 0, 0, Total, CveMoneda, 1, CveMetodoPago, NowADS(), "Deducciones nómina", "", "", "", "", 0, 0, 0, new DateTime(), new DateTime(), new DateTime(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Autorizado: false)) { CveNomina = objNomina.CveNomina; } else { continuar = false; } } } } if (CveNomina == 0) { continuar = false; } if (continuar) { dtconp = dtempleadosConceptos.FiltraParametros(string.Format("CvePersonal={0} AND (Importe<>0 OR Valor <>0)", CvePersonal)); foreach (DataRow rcon in dtconp.Rows) { CveConcepto = rcon["CveConcepto"].ToString().ToEntero(); ImporteConcepto = chkImporte == 1 ? rcon["Importe"].ToString().ToDecimal() : 0; ImporteGravadoConcepto = rcon["ImporteGravado"].ToString().ToDecimal(); ImporteExentoConcepto = ImporteConcepto - ImporteGravadoConcepto; ImporteValor = rcon["Valor"].ToString().ToDecimal(); if (continuar) { if (!objNomina.AddUPNom_NominasDetalles(CveNomina, CvePeriodoSeleccionado, CvePersonal, CveConcepto, ImporteConcepto, ImporteGravadoConcepto, ImporteExentoConcepto, ImporteValor, UsuarioActual.CveUsuario, false, chkImporte, chkImporteGravado, chkImporteValor, true)) { continuar = false; } } } } if (continuar) { decimal SalarioDiario = rtemp["SalarioDiario"].ToString().ToDecimal(); decimal SalarioDiarioIMSS = rtemp["SalarioDiarioIMSS"].ToString().ToDecimal(); decimal SalarioDiarioIntegrado = rtemp["SalarioDiarioIntegrado"].ToString().ToDecimal(); int DiasLaborados = rtemp["DiasLaborados"].ToString().ToEntero(); int DiasFaltados = rtemp["DiasFaltados"].ToString().ToEntero(); int DiasVacaciones = rtemp["DiasVacaciones"].ToString().ToEntero(); int DiasIncapacidad = rtemp["DiasIncapacidad"].ToString().ToEntero(); continuar = objNomina.PA_Nom_NominasAutorizarUP(CvePersonal, CvePeriodoSeleccionado, SalarioDiario, SalarioDiarioIMSS, SalarioDiarioIntegrado, 0, 0, Total, SubTotal, DiasLaborados, DiasFaltados, DiasVacaciones, DiasIncapacidad); if (continuar) { continuar = objNomina.AutorizaNom_Nominas(CvePersonal, CvePeriodoSeleccionado, true); } } } } if (continuar) { objNomina.Commit(); } else { objNomina.RollBack(); } } if (dtr != null) { dtr.Dispose(); } if (dtconp != null) { dtconp.Dispose(); } if (continuar) { Alert(string.Format("La nomina se autorizó correctamente.{0}", erroralturizar)); cargaDatos(); } return continuar; } protected void LnkCargaAsistenciaMasiva_Click(object sender, EventArgs e) { DdlEjerciciosCM.SelectedValueExist(NowADS().Year); DdlEjerciciosCM_SelectedIndexChanged(DdlEjerciciosCM, null); if (DdlTipoPeriodo.SelectedValue.ToEntero() > 0) { DdlTipoPeriodoCM.SelectedValueExist(DdlTipoPeriodo.SelectedValue); } DdlTipoPeriodoCM_SelectedIndexChanged(DdlTipoPeriodoCM, null); if (DdlPeriodo.SelectedValue.ToEntero() > 0) { DdlPeriodoCM.SelectedValueExist(DdlPeriodo.SelectedValue); } RegistraScript("$('#DModalCargaASistenciaMasiva').modal();"); } protected void LnkCargarAsistenciaMasiva_Click(object sender, EventArgs e) { using (ClsRH ObjPersonal = new ClsRH()) { ObjPersonal.IniciaTransacSQL(); bool OcurrioError = false; if (!ObjPersonal.AddAsistenciaMasiva2(DdlPeriodoCM.SelectedValue.ToEntero(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1)) OcurrioError = true; if (OcurrioError) { ObjPersonal.RollBack(); Alert("Ocurrió un error al guardar las Asistencias.", ModExtensiones.TipoMensaje.MsgError); } else { ObjPersonal.Commit(); Alert("Las Asistencias se guardaron correctamente.", ModExtensiones.TipoMensaje.ToastInformacion); } } RegistraScript(string.Format("$('#DModalCargaASistenciaMasiva').modal('hide');")); if (chhkCargarSistenciaMasiva.Checked) { cargaDatos(true); } } private void cargaPeriodosCM() { int tipoPeriodo = DdlTipoPeriodoCM.SelectedValue.ToEntero(); int ejercicio = DdlEjerciciosCM.SelectedValue.ToEntero(); DataTable dtPeriodos = null; if (tipoPeriodo > 0) { using (ClsNominas objperiodos = new ClsNominas()) { if (objperiodos.GetPeriodos(tipoPeriodo, UsuarioActual.CveEmpresa, ejercicio, -1, -1)) { dtPeriodos = objperiodos.DtResultados; } } } DdlPeriodoCM.DataSource = dtPeriodos; DdlPeriodoCM.DataBind(); DdlPeriodoCM.Items.Insert(0, new ListItem("Seleccione", "-1")); UpModalAsistenciaMasiva.Update(); } protected void DdlEjerciciosCM_SelectedIndexChanged(object sender, EventArgs e) { cargaPeriodosCM(); } protected void DdlTipoPeriodoCM_SelectedIndexChanged(object sender, EventArgs e) { cargaPeriodosCM(); } protected void LnkGuardarASistencia_Click(object sender, EventArgs e) { int CvePersonal = TxtasiscvePersonal.Text.ToEntero(); DateTime fecha = TxtasisFecha.Text.ToDate(); using (ClsRH objpersonal = new ClsRH()) { if (objpersonal.AddAsistencia(CvePersonal, -1, DdlAsisSubProyecto.SelectedValue.ToEntero(), fecha, DdlTipoAsistencias.SelectedValue.ToEntero(), TxtPorPago.Text.Trim().ToDouble(), TxtHorasDobles.Text.Trim().ToDouble(), TxtHorasTriples.Text.Trim().ToDouble(), DdlMotivoHoraExtra.SelectedValue.ToEntero(), TxtObservaciones.Text.Trim(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "P")) { Alert(string.Format("se ha guardado la asistencia satisfactoriamente
{0}
{1:dd/MM/yyyy}", TxtPersonal.Text, TxtasisFecha.Text.ToDate()), TipoMensaje.ToastInformacion); RegistraScript("$('#DModalModAsistencia').modal('hide');"); } } if (chkAistenciaRecalcular.Checked) { cargaDatos(true); } } protected void btnasis_Click(object sender, EventArgs e) { int CvePersonal = TxtasiscvePersonal.Text.ToEntero(); DateTime fecha = TxtasisFecha.Text.ToDate(); TxtfechaMostrar.Text = string.Format("{0:dd/MM/yyyy}", fecha); DataRow drow = dtempleados.FiltroPrimero(string.Format("CvePersonal={0}", CvePersonal)); TxtPersonal.Text = drow["nombre"].ToString(); DdlAsisSubProyecto.SelectedValueExist("-1"); if (DdlTipoAsistencias.Items.Count == 1) { DdlTipoAsistencias.DataSource = get_GlobalDTAsistenciasInasistencias(UsuarioActual.CveEmpresa); DdlTipoAsistencias.DataBind(); } if (DdlMotivoHoraExtra.Items.Count == 1) { DdlMotivoHoraExtra.DataSource = get_GlobalDTMotivosHorasExtras(UsuarioActual.CveEmpresa).FiltraParametros(string.Format("CveEmpresa = {0}", UsuarioActual.CveEmpresa)); DdlMotivoHoraExtra.DataBind(); } using (ClsRH objpersonal = new ClsRH()) { if (objpersonal.GetAsistencias(CvePersonal, -1, -1, -1, -1, -1, -1, fecha, fecha, UsuarioActual.CveEmpresa)) { if (objpersonal.DtResultados.Rows.Count > 0) { DataRow dr = objpersonal.DtResultados.Rows[0]; DdlTipoAsistencias.SelectedValueExist(dr["CveAsistenciasInasistencias"].ToString()); DdlAsisSubProyecto.SelectedValueExist(dr["CveSubProyecto"].ToString()); TxtPorPago.Text = dr["PorcentajePago"].ToString(); TxtHorasDobles.Text = dr["HorasDobles"].ToString(); TxtHorasTriples.Text = dr["HorasTriples"].ToString(); DdlMotivoHoraExtra.SelectedValueExist(dr["CveMotivoHoraExtra"].ToString()); TxtObservaciones.Text = dr["Observacion"].ToString(); // CveAsistenciasInasistencias // PorcentajePago // HorasDobles // HorasTriples //CveMotivoHoraExtra //Observacion // } } } UpModalAsistencia.Update(); RegistraScript("$('#DModalModAsistencia').modal();"); } protected void LnkSimulador_Click(object sender, EventArgs e) { GvConceptossimulador.DataSource = new DataTable(); LblSalarioDiarioSimula.Text = ""; GvConceptossimulador.DataBind(); DdlTipoPeriodoSim.SelectedValueExist(4); DdlTipoPeriodoSim.SelectedValueExist(1); RegistraScript("$('#DSimulador').modal()"); UpSimulador.Update(); } #region "Propiedades Simula" private DataTable dtPeriodoSimula { get { if (ViewState["dtPeriodoSimula"] == null) { return null; } else { return (DataTable)ViewState["dtPeriodoSimula"]; } } set { ViewState["dtPeriodoSimula"] = value; } } private DataTable dtasistenciaSimula { get { if (ViewState["dtasistenciaSimula"] == null) { return null; } else { return (DataTable)ViewState["dtasistenciaSimula"]; } } set { ViewState["dtasistenciaSimula"] = value; } } private DataTable dtConceptosSimula { get { if (ViewState["dtConceptosSimula"] == null) { return null; } else { return (DataTable)ViewState["dtConceptosSimula"]; } } set { ViewState["dtConceptosSimula"] = value; } } private DataTable dtempleadosSimula { get { if (ViewState["dtempleadosSimula"] == null) { return null; } else { return (DataTable)ViewState["dtempleadosSimula"]; } } set { ViewState["dtempleadosSimula"] = value; } } private DataTable dtempleadosConceptosSimula { get { if (ViewState["dtempleadosConceptosSimula"] == null) { return null; } else { return (DataTable)ViewState["dtempleadosConceptosSimula"]; } } set { ViewState["dtempleadosConceptosSimula"] = value; } } #endregion protected void LnkSimularXNeto_Click(object sender, EventArgs e) { int CveProyecto = -1; int CveSubProyecto = 1; int CveTurno = -1; int CvePeriodo = (DdlTipoPeriodoSim.SelectedValue == "1") ? 12706 : 12551; int CveEmpresa = UsuarioActual.CveEmpresa; int Agrupador = -1; decimal Neto = TxtNetoaPagar.Text.ToDecimal(); decimal NetoSimulado = 0; decimal SDI = (Neto * 1.25M) / (DdlTipoPeriodoSim.SelectedValue == "1" ? 7 : 15); decimal SDIOLD = 0; decimal sumador = 100; decimal multiplicador = 1; bool ismayor = false; bool isfirst = true; bool continuarV = true; bool continuar = false; using (ClsNominas objnom = new ClsNominas()) { while (Neto != NetoSimulado && continuarV) { if (objnom.GetNominaEmpleado(CveProyecto, CveSubProyecto, CveTurno, CvePeriodo, CveEmpresa, Agrupador, -1, 1, Neto, ddlfiniquito.SelectedValue.ToEntero()) && objnom.DTSetResultados.Tables.Count > 1) { dtempleadosSimula = objnom.DTSetResultados.Tables[3]; dtempleadosConceptosSimula = objnom.DTSetResultados.Tables[4]; dtConceptosSimula = objnom.DTSetResultados.Tables[0]; dtPeriodoSimula = objnom.DTSetResultados.Tables[1]; dtasistenciaSimula = objnom.DTSetResultados.Tables[2]; continuar = true; NetoSimulado = dtempleadosSimula.SUM("Total", string.Format("CvePersonal = {0}", 1)).ToString().ToDecimal(); } if (continuar) { if (isfirst) { if (Neto > NetoSimulado) { ismayor = true; } else { ismayor = false; } isfirst = false; } else { if (!((Neto > NetoSimulado) == ismayor)) { SDI = SDIOLD; sumador = sumador * 0.1M; if (sumador < .00000001M) { continuarV = false; } } } multiplicador = (Neto > NetoSimulado) ? 1 : -1; SDIOLD = SDI; SDI = SDI + (multiplicador * sumador); } else { continuarV = false; } continuarV = false; } } if (continuar) { { DataTable dtx = dtConceptosSimula.Copy(); dtx.Columns.Add("BorradoLogico", typeof(int)); DataTable dtper = dtx.FiltraParametros("Tipo IN ('P') AND EsPadre = 1 "); DataTable dtded = dtx.FiltraParametros("Tipo IN ('D') AND EsPadre = 1 "); DataTable dtObl = dtx.FiltraParametros("Tipo IN ('O') AND EsPadre = 1 "); ////dtded.Columns.Add("BorradoLogico", typeof(int)); ////dtObl.Columns.Add("BorradoLogico", typeof(int)); foreach (DataRow row in dtper.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto)) > 0)) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtper.AcceptChanges(); foreach (DataRow row in dtded.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto)) > 0)) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtded.AcceptChanges(); foreach (DataRow row in dtObl.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto)) > 0)) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtObl.AcceptChanges(); dtper = dtper.FiltraParametros("BorradoLogico=0"); dtded = dtded.FiltraParametros("BorradoLogico=0"); dtObl = dtObl.FiltraParametros("BorradoLogico=0"); int maxper = dtper.Rows.Count; int maxded = dtded.Rows.Count; int maxObl = dtObl.Rows.Count; int i = 0; List lconc = new List(); for (i = 0; i < maxper || i < maxded || i < maxObl; i++) { NConcepto nConcepto = new NConcepto(); DataRow row; if (maxper > i) { row = dtper.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); decimal ImporteGravado = dtempleadosSimula.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); nConcepto.CveConceptoP = CveConcepto; nConcepto.ConceptoP = Concepto; nConcepto.NoConceptoP = Codigo; nConcepto.ImporteP = Importe; nConcepto.ImporteGravadoP = ImporteGravado; nConcepto.ValorP = dtempleadosSimula.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); } if (maxded > i) { row = dtded.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); decimal ImporteGravado = dtempleadosSimula.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); nConcepto.CveConceptoD = CveConcepto; nConcepto.ConceptoD = Concepto; nConcepto.NoConceptoD = Codigo; nConcepto.ImporteD = Importe; nConcepto.ImporteGravadoD = ImporteGravado; nConcepto.ValorD = dtempleadosSimula.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); } if (maxObl > i) { row = dtObl.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); decimal ImporteGravado = dtempleadosSimula.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); nConcepto.CveConceptoO = CveConcepto; nConcepto.ConceptoO = Concepto; nConcepto.NoConceptoO = Codigo; nConcepto.ImporteO = Importe; nConcepto.ImporteGravadoO = ImporteGravado; nConcepto.ValorO = dtempleadosSimula.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", 1)); } lconc.Add(nConcepto); } lconc.Add(new NConcepto()); NConcepto SubTotales = new NConcepto(); SubTotales.CveConceptoP = 0; SubTotales.ConceptoP = "Total Percepciones"; SubTotales.EstatusP = -2; SubTotales.ImporteP = dtempleadosSimula.SUM("SumaPercepciones", string.Format("CvePersonal = {0}", 1)); SubTotales.ImporteGravadoP = dtempleadosSimula.SUM("SumaPercepcionesG", string.Format("CvePersonal = {0}", 1)); ///Alert(SubTotales.ImporteP.ToString()); SubTotales.CveConceptoD = 0; SubTotales.ConceptoD = "Total Deducciones"; SubTotales.EstatusD = -2; SubTotales.ImporteD = dtempleadosSimula.SUM("SumaDeducciones", string.Format("CvePersonal = {0}", 1)); SubTotales.CveConceptoD = 0; SubTotales.ConceptoO = "Total Obligaciones"; SubTotales.EstatusO = -2; SubTotales.ImporteO = dtempleadosSimula.SUM("SumaObligaciones", string.Format("CvePersonal = {0}", 1)); //NConcepto Totales = new NConcepto(); //Totales.CveConceptoD = 0; //Totales.ConceptoD = "Total"; //Totales.EstatusD = -3; //Totales.ImporteD = dtempleados.SUM("Total", string.Format("CvePersonal = {0}", 1)); lconc.Add(SubTotales); //lconc.Add(Totales); LblSalarioDiarioSimula.Text = string.Format("${0:N4}", dtempleadosSimula.SUM("SalarioDiario", string.Format("CvePersonal = {0}", 1))); GvConceptossimulador.DataSource = lconc; GvConceptossimulador.DataBind(); } } UpSimulador.Update(); } protected void BtnImprimirsobrereciboSimula_Click(object sender, EventArgs e) { int SRCvePersonal = 1; DataTable dtper = dtConceptosSimula.FiltraParametros("Tipo IN ('P') AND EsPadre = 1 AND EsFormula =0"); DataTable dtded = dtConceptosSimula.FiltraParametros("Tipo IN ('D') AND EsPadre = 1 AND EsFormula =0"); dtper.Columns.Add("BorradoLogico", typeof(int)); dtded.Columns.Add("BorradoLogico", typeof(int)); foreach (DataRow row in dtper.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)) != 0)) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtper.AcceptChanges(); foreach (DataRow row in dtded.Rows) { int BorradoLogico = 0; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); if (!(dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)) != 0)) { BorradoLogico = 1; } row["BorradoLogico"] = BorradoLogico; } dtded.AcceptChanges(); dtper = dtper.FiltraParametros("BorradoLogico=0"); dtded = dtded.FiltraParametros("BorradoLogico=0"); int maxper = dtper.Rows.Count; int maxded = dtded.Rows.Count; int i = 0; List lconc = new List(); for (i = 0; i < maxper || i < maxded; i++) { NConcepto nConcepto = new NConcepto(); DataRow row; if (maxper > i) { row = dtper.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); decimal ImporteGravado = dtempleadosSimula.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.CveConceptoP = CveConcepto; nConcepto.ConceptoP = Concepto; nConcepto.NoConceptoP = Codigo; nConcepto.ImporteP = Importe; nConcepto.ImporteGravadoP = ImporteGravado; nConcepto.CveSistemaP = row["CveSistema"].ToString().ToEntero(); nConcepto.ValorP = dtempleadosSimula.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); } if (maxded > i) { row = dtded.Rows[i]; int CveConcepto = row["CveConcepto"].ToString().ToEntero(); string Concepto = row["Concepto"].ToString(); string Codigo = row["Codigo"].ToString(); //bool visible = (dtempleados.SUM(string.Format("[V_{0}]", CveConcepto)) > 0); decimal Importe = dtempleadosSimula.SUM(string.Format("[V_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); decimal ImporteGravado = dtempleadosSimula.SUM(string.Format("[VG_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); nConcepto.CveConceptoD = CveConcepto; nConcepto.ConceptoD = Concepto; nConcepto.NoConceptoD = Codigo; nConcepto.ImporteD = Importe; nConcepto.ImporteGravadoD = ImporteGravado; nConcepto.CveSistemaD = row["CveSistema"].ToString().ToEntero(); nConcepto.ValorD = dtempleadosSimula.SUM(string.Format("[VAL_{0}]", CveConcepto), string.Format("CvePersonal = {0}", SRCvePersonal)); } lconc.Add(nConcepto); } lconc.Add(new NConcepto()); NConcepto SubTotales = new NConcepto(); SubTotales.CveConceptoP = 0; SubTotales.ConceptoP = "Total Percepciones"; SubTotales.EstatusP = -2; SubTotales.ImporteP = dtempleadosSimula.SUM("SumaPercepciones", string.Format("CvePersonal = {0}", SRCvePersonal)); SubTotales.ImporteGravadoP = dtempleadosSimula.SUM("SumaPercepcionesG", string.Format("CvePersonal = {0}", SRCvePersonal)); ///Alert(SubTotales.ImporteP.ToString()); SubTotales.CveConceptoD = 0; SubTotales.ConceptoD = "Total Deducciones"; SubTotales.EstatusD = -2; SubTotales.ImporteD = dtempleadosSimula.SUM("SumaDeducciones", string.Format("CvePersonal = {0}", SRCvePersonal)); NConcepto especie = new NConcepto(); especie.CveConceptoD = 0; especie.ConceptoD = "Especie"; especie.EstatusD = -3; especie.ImporteD = dtempleadosSimula.SUM("SumaEspecie", string.Format("CvePersonal = {0}", SRCvePersonal)); NConcepto Totales = new NConcepto(); Totales.CveConceptoD = 0; Totales.ConceptoD = "Total"; Totales.EstatusD = -3; Totales.ImporteD = dtempleadosSimula.SUM("Total", string.Format("CvePersonal = {0}", SRCvePersonal)); lconc.Add(SubTotales); if (especie.ImporteD > 0) { lconc.Add(especie); } lconc.Add(Totales); DataTable dtCon = new DataTable(); dtCon.Columns.Add(new DataColumn("NoConceptoP", typeof(string))); dtCon.Columns.Add(new DataColumn("ConceptoP", typeof(string))); dtCon.Columns.Add(new DataColumn("LabelValorP", typeof(string))); dtCon.Columns.Add(new DataColumn("CveConceptoP", typeof(int))); dtCon.Columns.Add(new DataColumn("ImporteP", typeof(double))); dtCon.Columns.Add(new DataColumn("ValorP", typeof(double))); dtCon.Columns.Add(new DataColumn("EstatusP", typeof(int))); dtCon.Columns.Add(new DataColumn("isEditedP", typeof(int))); dtCon.Columns.Add(new DataColumn("isOnlyBisibleP", typeof(int))); dtCon.Columns.Add(new DataColumn("NoConceptoD", typeof(string))); dtCon.Columns.Add(new DataColumn("ConceptoD", typeof(string))); dtCon.Columns.Add(new DataColumn("LabelValorD", typeof(string))); dtCon.Columns.Add(new DataColumn("CveConceptoD", typeof(int))); dtCon.Columns.Add(new DataColumn("ImporteD", typeof(double))); dtCon.Columns.Add(new DataColumn("ValorD", typeof(double))); dtCon.Columns.Add(new DataColumn("EstatusD", typeof(int))); dtCon.Columns.Add(new DataColumn("isEditedD", typeof(int))); dtCon.Columns.Add(new DataColumn("isOnlyBisibleD", typeof(int))); dtCon.Columns.Add(new DataColumn("CveSistemaD", typeof(int))); dtCon.Columns.Add(new DataColumn("CveSistemaP", typeof(int))); foreach (NConcepto itc in lconc) { DataRow dr = dtCon.NewRow(); dr["NoConceptoP"] = itc.NoConceptoP; dr["ConceptoP"] = itc.ConceptoP; dr["LabelValorP"] = itc.LabelValorP; dr["CveConceptoP"] = itc.CveConceptoP; dr["ImporteP"] = itc.ImporteP; dr["ValorP"] = itc.ValorP; dr["EstatusP"] = itc.EstatusP; dr["isEditedP"] = itc.isEditedP; dr["isOnlyBisibleP"] = itc.isOnlyBisibleP; dr["NoConceptoD"] = itc.NoConceptoD; dr["ConceptoD"] = itc.ConceptoD; dr["LabelValorD"] = itc.LabelValorD; dr["CveConceptoD"] = itc.CveConceptoD; dr["ImporteD"] = itc.ImporteD; dr["ValorD"] = itc.ValorD; dr["EstatusD"] = itc.EstatusD; dr["isEditedD"] = itc.isEditedD; dr["isOnlyBisibleD"] = itc.isOnlyBisibleD; dr["CveSistemaD"] = itc.CveSistemaD; dr["CveSistemaP"] = itc.CveSistemaP; dtCon.Rows.Add(dr); } dtCon.AcceptChanges(); List lrds = new List(); Microsoft.Reporting.WebForms.ReportDataSource rds = new Microsoft.Reporting.WebForms.ReportDataSource(); rds.Name = "DataSet1"; rds.Value = dtCon;// lconc; lrds.Add(rds); List parametros = new List(); string CodigoEmpleado = ""; string NombreCompleto = ""; string RFC = ""; string CURP = ""; string TipoPeriodo = ""; string NSS = ""; string DiasLaborados = ""; string DiasFaltados = ""; string DiasVacaciones = ""; string FechaInicio = ""; string FechaFin = ""; string DiasRetardos = ""; string DiasIncapacidad = ""; string SubProyecto = ""; string Usuario = UsuarioActual.Nombre; string FolioFiscal = ""; { DataRow drow = dtempleadosSimula.FiltroPrimero(string.Format("CvePersonal = {0}", SRCvePersonal)); if (drow != null) { SubProyecto = drow["SubProyecto"].ToString(); FolioFiscal = string.Format("{0}", drow["FolioFiscal"]); DiasLaborados = string.Format("{0}", drow["DiasLaborados"].ToString().ToEntero()); DiasFaltados = string.Format("{0}", drow["DiasFaltados"].ToString().ToEntero()); DiasVacaciones = string.Format("{0}", drow["DiasVacaciones"].ToString().ToEntero()); FechaInicio = string.Format("{0:dd/MM/yyyy}", drow["FechaInicio"]); FechaFin = string.Format("{0:dd/MM/yyyy}", drow["FechaFin"]); DiasRetardos = string.Format("{0}", drow["DiasRetardos"].ToString().ToEntero()); DiasIncapacidad = string.Format("{0}", drow["DiasIncapacidad"].ToString().ToEntero()); } } CodigoEmpleado = "0000"; NombreCompleto = "Simulacion calculo"; RFC = "-"; CURP = "-"; TipoPeriodo = DdlTipoPeriodoSim.SelectedItem.Text; NSS = "-"; parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasIncapacidad", DiasIncapacidad)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("Codigo", CodigoEmpleado)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("NombreCompleto", NombreCompleto)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("RFC", RFC)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("CURP", CURP)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("TipoPeriodo", TipoPeriodo)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("NSS", NSS)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasLaborados", DiasLaborados)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasFaltados", DiasFaltados)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasVacaciones", DiasVacaciones)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FechaInicio", FechaInicio)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FechaFin", FechaFin)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("DiasRetardos", DiasRetardos)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("Empresa", UsuarioActual.Empresa.Empresa)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("SubProyecto", SubProyecto)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FechaPago", "")); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("FolioFiscal", FolioFiscal)); parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("Usuario", Usuario)); //parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("", "")); //parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("", "")); //parametros.Add(new Microsoft.Reporting.WebForms.ReportParameter("", "")); string urlfile = System.IO.Path.Combine(string.Format("{0}Formatos/SobreRecibo.rdlc", UsuarioActual.Empresa.Ruta)); if (!System.IO.File.Exists(urlfile)) { urlfile = System.IO.Path.Combine(ModExtensiones.DirectorioBaseEmpresas, "Empresas/Grales/Formatos/SobreRecibo.rdlc"); } ImprimirPDF(urlfile, lrds, parametros, "SobreRecibo", "PDF", null); } protected void DdlTipoPeriodoSim_SelectedIndexChanged(object sender, EventArgs e) { } protected void LnkDownArchivosSua_Click(object sender, EventArgs e) { TxtFechaInicio.Text = NowADS().AddDays(NowADS().Day - 1).ToString("dd/MM/yyy"); TXTFechaFin.Text = NowADS().AddDays(NowADS().Day - 1).AddMonths(1).AddDays(-1).ToString("dd/MM/yyy"); RegistraScript("$('#DmodalGetSua').modal();"); UpModalGetSUA.Update(); } protected void LnkGetTxtsSUA_Click(object sender, EventArgs e) { string concater = ""; string MovtosAfil = ""; string MovtosmodSalario = ""; string movtosBajas = ""; using (ClsRH ObjPersonal = new ClsRH()) { if (ObjPersonal.GetMovimientosToSUA(UsuarioActual.CveEmpresa, TxtFechaInicio.Text.ToDate().ToString("yyyy/MM/dd"), TXTFechaFin.Text.ToDate().ToString("yyyy/MM/dd"))) { //01: MovtosAfil concater = ""; foreach (var item in ObjPersonal.DtResultados.Select("Tipo=1")) { MovtosAfil = string.Format("{0}{1}{2}", MovtosAfil, concater, item["Movtotxt"]); concater = "\\r\\n"; } //02: MovtosmodSalario concater = ""; foreach (var item in ObjPersonal.DtResultados.Select("Tipo=2")) { MovtosmodSalario = string.Format("{0}{1}{2}", MovtosmodSalario, concater, item["Movtotxt"]); concater = "\\r\\n"; } //03: movtosBajas concater = ""; foreach (var item in ObjPersonal.DtResultados.Select("Tipo=3")) { movtosBajas = string.Format("{0}{1}{2}", movtosBajas, concater, item["Movtotxt"]); concater = "\\r\\n"; } } string script = "";// string.Format("SaveCsv(\"MovtosAfil.txt\", '{0}');SaveCsv(\"MovtosmodSalario.txt\", '{1}');SaveCsv(\"movtosBajas.txt\", '{2}');", MovtosAfil.Replace("'", "\\'"), MovtosmodSalario.Replace("'", "\\'"), movtosBajas.Replace("'", "\\'")); if (ChkSuaAltas.Checked) { script = string.Format("{1}SaveCsv(\"MovtosAfil.txt\", '{0}');", MovtosAfil.Replace("'", "\\'"), script); } if (ChkSuaBajas.Checked) { script = string.Format("{1}SaveCsv(\"movtosBajas.txt\", '{0}');", movtosBajas.Replace("'", "\\'"), script); } RegistraScript(script); RegistraScript("$('#DmodalGetSua').modal('hide');"); } } protected void LnkUpSuamodal_Click(object sender, EventArgs e) { TxtArchivoSua.Text = ""; GVProcesarSUA.DataSource = null; GVProcesarSUA.DataBind(); RegistraScript("$('#DmodalCompareSua').modal();shownew();"); UpArchivoSua.Update(); } protected void LnkUpSuaFile_Click(object sender, EventArgs e) { string fileurl = ""; GVProcesarSUA.DataSource = null; Files archivos = TxtArchivoSua.getfiles(); if (archivos.Archivos.Count > 0) { fileurl = archivos.Archivos[0].FileUrl; string SuaFiletext = System.IO.File.ReadAllText(fileurl, Encoding.GetEncoding("iso-8859-1")); using (ClsNominas ObjPersonal = new ClsNominas()) { if (ObjPersonal.ProcesarSUA(SuaFiletext, UsuarioActual.CveEmpresa)) { if (ObjPersonal.DTSetResultados.Tables.Count > 4) { DateTime dateperiodo; DateTime.TryParseExact(string.Format("{0}01", ObjPersonal.DTSetResultados.Tables[1].Rows[0]["Periodo"]), "yyyyMMdd", new System.Globalization.CultureInfo("es-MX"), System.Globalization.DateTimeStyles.None, out dateperiodo); LtlPeriodo.Text = dateperiodo.Date.ToString("MMMM yyyy", new System.Globalization.CultureInfo("es-MX")); DtSuaProcesado = ObjPersonal.DTSetResultados.Tables[3]; GVProcesarSUA.DataSource = ObjPersonal.DTSetResultados.Tables[3]; } } } } GVProcesarSUA.DataBind(); TxtArchivoSua.Text = ""; RegistraScript("showResult();"); UpArchivoSua.Update(); } protected void GVProcesarSUA_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.RowIndex == 0) { e.Row.CssClass = "Totales"; } string SalarioSUA = string.Format("{0:N2}", e.Row.DataKey("SalarioSUA").ToDecimal()); string SalarioSIG = string.Format("{0:N2}", e.Row.DataKey("SalarioSIG").ToDecimal()); int celda = 1; if (Math.Abs(SalarioSUA.ToDecimal() - SalarioSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 4; string CuotaExcedenteSUA = string.Format("{0:N2}", e.Row.DataKey("CuotaExcedenteSUA").ToDecimal()); string CuotaExcedenteSIG = string.Format("{0:N2}", e.Row.DataKey("CuotaExcedenteSIG").ToDecimal()); if (Math.Abs(CuotaExcedenteSUA.ToDecimal() - CuotaExcedenteSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string PrestacionesDineroSUA = string.Format("{0:N2}", e.Row.DataKey("PrestacionesDineroSUA").ToDecimal()); string PrestacionesSIG = string.Format("{0:N2}", e.Row.DataKey("PrestacionesSIG").ToDecimal()); if (Math.Abs(PrestacionesDineroSUA.ToDecimal() - PrestacionesSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string GastosMedPenSUA = string.Format("{0:N2}", e.Row.DataKey("GastosMedPenSUA").ToDecimal()); string GastosMedicosSIG = string.Format("{0:N2}", e.Row.DataKey("GastosMedicosSIG").ToDecimal()); if (Math.Abs(GastosMedPenSUA.ToDecimal() - GastosMedicosSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string InvalidezyVidaSUA = string.Format("{0:N2}", e.Row.DataKey("InvalidezyVidaSUA").ToDecimal()); string InvalidezyVidaSIG = string.Format("{0:N2}", e.Row.DataKey("InvalidezyVidaSIG").ToDecimal()); if (Math.Abs(InvalidezyVidaSUA.ToDecimal() - InvalidezyVidaSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string CesantiayVejezObreraSUA = string.Format("{0:N2}", e.Row.DataKey("CesantiayVejezObreraSUA").ToDecimal()); string CesantiayVejezObreraSIG = string.Format("{0:N2}", e.Row.DataKey("CesantiayVejezObreraSIG").ToDecimal()); if (Math.Abs(CesantiayVejezObreraSUA.ToDecimal() - CesantiayVejezObreraSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string CuotaFijaSUA = string.Format("{0:N2}", e.Row.DataKey("CuotaFijaSUA").ToDecimal()); string CuotaFijaSIG = string.Format("{0:N2}", e.Row.DataKey("CuotaFijaSIG").ToDecimal()); if (Math.Abs(CuotaFijaSUA.ToDecimal() - CuotaFijaSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string RiesgosdeTrabajoSUA = string.Format("{0:N2}", e.Row.DataKey("RiesgosdeTrabajoSUA").ToDecimal()); string RiesgoTrabajoSIG = string.Format("{0:N2}", e.Row.DataKey("RiesgoTrabajoSIG").ToDecimal()); if (Math.Abs(RiesgosdeTrabajoSUA.ToDecimal() - RiesgoTrabajoSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string GuarderiaSUA = string.Format("{0:N2}", e.Row.DataKey("GuarderiaSUA").ToDecimal()); string GuarderiaSIG = string.Format("{0:N2}", e.Row.DataKey("GuarderiaSIG").ToDecimal()); if (Math.Abs(GuarderiaSUA.ToDecimal() - GuarderiaSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string RetiroSUA = string.Format("{0:N2}", e.Row.DataKey("RetiroSUA").ToDecimal()); string RetiroSIG = string.Format("{0:N2}", e.Row.DataKey("RetiroSIG").ToDecimal()); if (Math.Abs(RetiroSUA.ToDecimal() - RetiroSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } celda = celda + 2; string CesantiayVejezPatronalSUA = string.Format("{0:N2}", e.Row.DataKey("CesantiayVejezPatronalSUA").ToDecimal()); string CesantiayVejezPatronalSIG = string.Format("{0:N2}", e.Row.DataKey("CesantiayVejezPatronalSIG").ToDecimal()); if (Math.Abs(CesantiayVejezPatronalSUA.ToDecimal() - CesantiayVejezPatronalSIG.ToDecimal()) > 1) { e.Row.Cells[celda].CssClass = "cellFail"; e.Row.Cells[celda + 1].CssClass = "cellFail"; } } } protected void LnkDownExcelSua_Click(object sender, EventArgs e) { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("SUA"); int Fila = 1; ClosedXML.Excel.IXLRange range = libro.Range(Fila, 2, Fila, 3); range.Merge(); range.Value = "Empresa"; range = libro.Range(Fila, 4, Fila, 21); range.Merge(); range.Value = UsuarioActual.Empresa.Empresa; Fila = Fila + 1; range = libro.Range(Fila, 2, Fila, 3); range.Merge(); range.Value = "PERIODO"; range = libro.Range(Fila, 4, Fila, 21); range.Merge(); range.Value = LtlPeriodo.Text; Fila = Fila + 1; libro.Column(1).Width = 50; range = libro.Range(Fila, 2, Fila, 3); range.Merge(); range.Value = "Salario"; range = libro.Range(Fila, 4, Fila, 5); range.Merge(); range.Value = "Días"; range = libro.Range(Fila, 6, Fila, 7); range.Merge(); range.Value = "Cuota Fija"; range = libro.Range(Fila, 8, Fila, 9); range.Merge(); range.Value = "Cuota Excedente"; range = libro.Range(Fila, 10, Fila, 11); range.Merge(); range.Value = "Prestaciones en Dinero"; range = libro.Range(Fila, 12, Fila, 13); range.Merge(); range.Value = "Gastos Medicos"; range = libro.Range(Fila, 14, Fila, 15); range.Merge(); range.Value = "Riesgos de Trabajo"; range = libro.Range(Fila, 16, Fila, 17); range.Merge(); range.Value = "Invalidez y Vida"; range = libro.Range(Fila, 18, Fila, 19); range.Merge(); range.Value = "Guarderia"; range = libro.Range(Fila, 20, Fila, 21); range.Merge(); range.Value = "Retiro"; Fila = Fila + 1; libro.Cell(Fila, 1).Value = "Empleado"; libro.Cell(Fila, 2).Value = "SUA"; //SalarioSUA libro.Cell(Fila, 3).Value = "SIG";//SalarioSIG libro.Cell(Fila, 4).Value = "SUA";//CuotaFijaSUA libro.Cell(Fila, 5).Value = "SIG";//CuotaFijaSIG libro.Cell(Fila, 6).Value = "SUA";//CuotaExcedenteSUA libro.Cell(Fila, 7).Value = "SIG";//CuotaExcedenteSIG libro.Cell(Fila, 8).Value = "SUA";//PrestacionesDineroSUA libro.Cell(Fila, 9).Value = "SIG";//PrestacionesSIG libro.Cell(Fila, 10).Value = "SUA";//GastosMedPenSUA libro.Cell(Fila, 11).Value = "SIG";//GastosMedicosSIG libro.Cell(Fila, 12).Value = "SUA";//RiesgosdeTrabajoSUA libro.Cell(Fila, 13).Value = "SIG";//RiesgoTrabajoSIG libro.Cell(Fila, 14).Value = "SUA";//InvalidezyVidaSUA libro.Cell(Fila, 15).Value = "SIG";//InvalidezyVidaSIG libro.Cell(Fila, 16).Value = "SUA";//GuarderiaSUA libro.Cell(Fila, 17).Value = "SIG";//GuarderiaSIG libro.Cell(Fila, 18).Value = "SUA";//RetiroSUA libro.Cell(Fila, 19).Value = "SIG";//RetiroSIG libro.Cell(Fila, 20).Value = "SUA";//RetiroSUA libro.Cell(Fila, 21).Value = "SIG";//RetiroSIG libro.Cell(Fila, 22).Value = "Motivo";//Motivo libro.Range(3, 1, 4, 22).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(3, 1, 4, 22).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(4, 1, 4, 22).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(4, 1, 4, 22).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(5, 1, 4, 22).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(5, 1, 4, 22).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); foreach (DataRow erow in DtSuaProcesado.Rows) { Fila++; libro.Cell(Fila, 1).Value = erow["CodigoNombreCompleto"]; libro.Cell(Fila, 2).Value = erow["SalarioSUA"].ToString().ToDecimal(); libro.Cell(Fila, 3).Value = erow["SalarioSIG"].ToString().ToDecimal(); libro.Cell(Fila, 4).Value = erow["DiasMes"].ToString().ToDecimal(); libro.Cell(Fila, 5).Value = erow["DiasAsistio"].ToString().ToDecimal(); libro.Cell(Fila, 6).Value = erow["CuotaFijaSUA"].ToString().ToDecimal(); libro.Cell(Fila, 7).Value = erow["CuotaFijaSIG"].ToString().ToDecimal(); libro.Cell(Fila, 8).Value = erow["CuotaExcedenteSUA"].ToString().ToDecimal(); libro.Cell(Fila, 9).Value = erow["CuotaExcedenteSIG"].ToString().ToDecimal(); libro.Cell(Fila, 10).Value = erow["PrestacionesDineroSUA"].ToString().ToDecimal(); libro.Cell(Fila, 11).Value = erow["PrestacionesSIG"].ToString().ToDecimal(); libro.Cell(Fila, 12).Value = erow["GastosMedPenSUA"].ToString().ToDecimal(); libro.Cell(Fila, 13).Value = erow["GastosMedicosSIG"].ToString().ToDecimal(); libro.Cell(Fila, 14).Value = erow["RiesgosdeTrabajoSUA"].ToString().ToDecimal(); libro.Cell(Fila, 15).Value = erow["RiesgoTrabajoSIG"].ToString().ToDecimal(); libro.Cell(Fila, 16).Value = erow["InvalidezyVidaSUA"].ToString().ToDecimal(); libro.Cell(Fila, 17).Value = erow["InvalidezyVidaSIG"].ToString().ToDecimal(); libro.Cell(Fila, 18).Value = erow["GuarderiaSUA"].ToString().ToDecimal(); libro.Cell(Fila, 19).Value = erow["GuarderiaSIG"].ToString().ToDecimal(); libro.Cell(Fila, 20).Value = erow["RetiroSUA"].ToString().ToDecimal(); libro.Cell(Fila, 21).Value = erow["RetiroSIG"].ToString().ToDecimal(); libro.Cell(Fila, 22).Value = erow["Motivo"].ToString(); decimal VSUA = erow["SalarioSUA"].ToString().ToDecimal(); decimal VSIG = erow["SalarioSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 2, Fila, 3).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["DiasMes"].ToString().ToDecimal(); VSIG = erow["DiasAsistio"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 4, Fila, 5).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["CuotaFijaSUA"].ToString().ToDecimal(); VSIG = erow["CuotaFijaSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 6, Fila, 7).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["CuotaExcedenteSUA"].ToString().ToDecimal(); VSIG = erow["CuotaExcedenteSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 8, Fila, 9).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["PrestacionesDineroSUA"].ToString().ToDecimal(); VSIG = erow["PrestacionesSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 10, Fila, 11).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["GastosMedPenSUA"].ToString().ToDecimal(); VSIG = erow["GastosMedicosSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 12, Fila, 13).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["RiesgosdeTrabajoSUA"].ToString().ToDecimal(); VSIG = erow["RiesgoTrabajoSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 14, Fila, 15).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["InvalidezyVidaSUA"].ToString().ToDecimal(); VSIG = erow["InvalidezyVidaSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 16, Fila, 17).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["GuarderiaSUA"].ToString().ToDecimal(); VSIG = erow["GuarderiaSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 18, Fila, 19).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } VSUA = erow["RetiroSUA"].ToString().ToDecimal(); VSIG = erow["RetiroSIG"].ToString().ToDecimal(); if (Math.Abs(VSUA - VSIG) > 1) { libro.Range(Fila, 20, Fila, 21).Style.Font.FontColor = ClosedXML.Excel.XLColor.Red; } } libro.SheetView.Freeze(4, 1); libro.Range(4, 1, Fila, 22).SetAutoFilter(true); libro.Range(5, 20, Fila, 21).SetDataType(ClosedXML.Excel.XLDataType.Number); //libro.Row(2).SetAutoFilter(); 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", "FormatoCargaNominas")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } #region Incapacidad private int CcvePersonalIncapacidad { get { return (ViewState["CcvePersonalIncapacidad"] == null) ? 0 : Convert.ToInt32(ViewState["CcvePersonalIncapacidad"]); } set { ViewState["CcvePersonalIncapacidad"] = value; } } protected void CargaPersonalIncapacidad() { LimpiaPersonalIncapacidad(); LnkAgregarIncapacidad.Visible = false; LnkActualizarIncapacidad.Visible = false; CcvePersonalIncapacidad = 0; using (ClsNominas ObjPers = new ClsNominas()) { ObjPers.PersonalIncapacidadGet(-1, SRCvePersonal, UsuarioActual.CveEmpresa); GVNom_PersonalIncapacidad.DataSource = ObjPers.DtResultados; } GVNom_PersonalIncapacidad.DataBind(); UpsrIncapacidadpersonal.Update(); } protected void LimpiaPersonalIncapacidad() { TxtSRINCfolio.Text = ""; TxtSRINCfechaInicio.Text = ""; TxtSRINCdiasAutorizados.Text = ""; TxtDiasPagoEmpresa.Text = UsuarioActual.CveEmpresa == 141 ? "3" : ""; DdlSRINCcveTipodeIncidencia.SelectedValue = "-1"; DdlSRINCcveRamoSeguro.SelectedValue = "-1"; DdlSRINCcveTipoRiesgo.SelectedValue = "-1"; TxtSRINCporcentajedeIncapacidad.Text = "100"; DdlSRINCcveSecuelaConsecuencia.SelectedValue = "-1"; DdlSRINCcveControlIncapacidad.SelectedValue = "-1"; TxtSRINCdescripcion.Text = ""; UpsrIncapacidadpersonal.Update(); } protected void LnkPersonalIncapacidad_Click(object sender, EventArgs e) { LimpiaPersonalIncapacidad(); #region GetDatos GridViewRow gvRow = (GridViewRow)(((LinkButton)sender).NamingContainer); CcvePersonalIncapacidad = gvRow.DataKey("CvePersonalIncapacidad").ToEntero(); int cvePersonal = gvRow.DataKey("CvePersonal").ToEntero(); string folio = gvRow.DataKey("Folio"); DateTime fechaInicio = gvRow.DataKey("FechaInicio").ToDateTime(); int diasAutorizados = gvRow.DataKey("DiasAutorizados").ToEntero(); int diasPagoEmpresa = gvRow.DataKey("DiasPagoEmpresa").ToEntero(); int cveTipodeIncidencia = gvRow.DataKey("CveTipodeIncidencia").ToEntero(); int cveRamoSeguro = gvRow.DataKey("CveRamoSeguro").ToEntero(); int cveTipoRiesgo = gvRow.DataKey("CveTipoRiesgo").ToEntero(); int porcentajedeIncapacidad = gvRow.DataKey("PorcentajedeIncapacidad").ToEntero(); int cveSecuelaConsecuencia = gvRow.DataKey("CveSecuelaConsecuencia").ToEntero(); int cveControlIncapacidad = gvRow.DataKey("CveControlIncapacidad").ToEntero(); string descripcion = gvRow.DataKey("Descripcion"); #endregion TxtSRINCfolio.Text = folio.ToString(); TxtSRINCfechaInicio.Text = $"{fechaInicio:dd/MM/yyyy}"; TxtSRINCdiasAutorizados.Text = diasAutorizados.ToString(); TxtDiasPagoEmpresa.Text = diasPagoEmpresa.ToString(); DdlSRINCcveTipodeIncidencia.SelectedValueExist(cveTipodeIncidencia.ToString()); DdlSRINCcveRamoSeguro.SelectedValueExist(cveRamoSeguro.ToString()); DdlSRINCcveTipoRiesgo.SelectedValueExist(cveTipoRiesgo.ToString()); TxtSRINCporcentajedeIncapacidad.Text = porcentajedeIncapacidad.ToString(); DdlSRINCcveSecuelaConsecuencia.SelectedValueExist(cveSecuelaConsecuencia.ToString()); DdlSRINCcveControlIncapacidad.SelectedValueExist(cveControlIncapacidad.ToString()); TxtSRINCdescripcion.Text = descripcion.ToString(); LnkAgregarIncapacidad.Visible = false; LnkActualizarIncapacidad.Visible = true; RegistraScript("$('#ModalSRIncapacidad').modal()"); } protected void LnkPersonalIncapacidadRemove_Click(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)(((LinkButton)sender).NamingContainer); CcvePersonalIncapacidad = gvRow.DataKey("CvePersonalIncapacidad").ToEntero(); bool Continuar; using (ClsNominas ObjPers = new ClsNominas()) { Continuar = ObjPers.PersonalIncapacidadRemove(UsuarioActual.CveUsuario, CcvePersonalIncapacidad); } if (Continuar) { CargaPersonalIncapacidad(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); UpsrIncapacidadpersonal.Update(); Alert("La incapacidad se ha eliminado.", TipoMensaje.ToastInformacion); } } protected void LnkshowaaddIncapacidad_Click(object sender, EventArgs e) { LimpiaPersonalIncapacidad(); LnkAgregarIncapacidad.Visible = true; LnkActualizarIncapacidad.Visible = false; CcvePersonalIncapacidad = 0; RegistraScript("$('#ModalSRIncapacidad').modal()"); } protected void LnkAgregarIncapacidad_Click(object sender, EventArgs e) { string folio = TxtSRINCfolio.Text; DateTime fechaInicio = TxtSRINCfechaInicio.Text.ToDateTime(); int diasAutorizados = TxtSRINCdiasAutorizados.Text.ToEntero(); int diasPagoEmpresa = TxtDiasPagoEmpresa.Text.ToEntero(); int cveTipodeIncidencia = DdlSRINCcveTipodeIncidencia.Text.ToEntero(); int cveRamoSeguro = DdlSRINCcveRamoSeguro.Text.ToEntero(); int cveTipoRiesgo = DdlSRINCcveTipoRiesgo.Text.ToEntero(); int porcentajedeIncapacidad = TxtSRINCporcentajedeIncapacidad.Text.ToEntero(); int cveSecuelaConsecuencia = DdlSRINCcveSecuelaConsecuencia.Text.ToEntero(); int cveControlIncapacidad = DdlSRINCcveControlIncapacidad.Text.ToEntero(); string descripcion = TxtSRINCdescripcion.Text; bool Continuar; using (ClsNominas ObjPers = new ClsNominas()) { Continuar = ObjPers.PersonalIncapacidadAdd(UsuarioActual.CveUsuario, SRCvePersonal, folio, fechaInicio, diasAutorizados, cveTipodeIncidencia, cveRamoSeguro, cveTipoRiesgo, porcentajedeIncapacidad, cveSecuelaConsecuencia, cveControlIncapacidad, descripcion, diasPagoEmpresa); } if (Continuar) { CargaPersonalIncapacidad(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); UpsrIncapacidadpersonal.Update(); Alert("La incapacidad se ha agregado.", TipoMensaje.ToastInformacion); RegistraScript("$('#ModalSRIncapacidad').modal('hide')"); } } protected void LnkActualizarIncapacidad_Click(object sender, EventArgs e) { string folio = TxtSRINCfolio.Text; DateTime fechaInicio = TxtSRINCfechaInicio.Text.ToDateTime(); int diasAutorizados = TxtSRINCdiasAutorizados.Text.ToEntero(); int diasPagoEmpresa = TxtDiasPagoEmpresa.Text.ToEntero(); int cveTipodeIncidencia = DdlSRINCcveTipodeIncidencia.Text.ToEntero(); int cveRamoSeguro = DdlSRINCcveRamoSeguro.Text.ToEntero(); int cveTipoRiesgo = DdlSRINCcveTipoRiesgo.Text.ToEntero(); int porcentajedeIncapacidad = TxtSRINCporcentajedeIncapacidad.Text.ToEntero(); int cveSecuelaConsecuencia = DdlSRINCcveSecuelaConsecuencia.Text.ToEntero(); int cveControlIncapacidad = DdlSRINCcveControlIncapacidad.Text.ToEntero(); string descripcion = TxtSRINCdescripcion.Text; bool Continuar; using (ClsNominas ObjPers = new ClsNominas()) { Continuar = ObjPers.PersonalIncapacidadUp(UsuarioActual.CveUsuario, CcvePersonalIncapacidad, folio, fechaInicio, diasAutorizados, cveTipodeIncidencia, cveRamoSeguro, cveTipoRiesgo, porcentajedeIncapacidad, cveSecuelaConsecuencia, cveControlIncapacidad, descripcion, diasPagoEmpresa); } if (Continuar) { CargaPersonalIncapacidad(); cargaDatos(CvePersonal: SRCvePersonal); cargaBitacora(); cargasobrericiboconceptos(SRMostrarFormulas); UpModalConceptos.Update(); UpsrIncapacidadpersonal.Update(); Alert("La incapacidad se ha actualizado.", TipoMensaje.ToastInformacion); RegistraScript("$('#ModalSRIncapacidad').modal('hide')"); } } #endregion private List GetDatosTagsDocumentos() { var ListaTagsDocumentost = new List(); if (SRCvePersonal != -1) { using (ClsRH objRH = new ClsRH()) { if (objRH.PersonalReclutamientoGet(SRCvePersonal, UsuarioActual.Empresa.CveEmpresa)) { DataRow drow = objRH.DtResultados.Rows[0]; ListaTagsDocumentost.Add(new TagsDocumentos("{Nombres}", drow["Nombres"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{APaterno}", drow["APaterno"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{AMaterno}", drow["AMaterno"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{RFC}", drow["RFC"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{NombreCompleto}", LblEmpleado.Text)); ListaTagsDocumentost.Add(new TagsDocumentos("{Estatura}", drow["Estatura"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Peso}", drow["Peso"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{LugarNacimiento}", drow["LugarNacimiento"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Edad}", drow["Edad"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{NombreTelEmergencia}", drow["NombreTelEmergencia"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{TipoSangre}", drow["TipoSangre"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Vivienda}", drow["Vivienda"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{ViviendaDueno}", drow["ViviendaDueno"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{CreditoInfonavit}", drow["CreditoInfonavit"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{RentaMensual}", drow["RentaMensual"].ToString().ToDecimal().ToString("###,###,###.00"))); ListaTagsDocumentost.Add(new TagsDocumentos("{TransportePublico}", drow["TransportePublico"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{TrabajadoAnteriormente}", drow["TrabajadoAnteriormente"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{TrabajadoAnteriormenteObservaciones}", drow["TrabajadoAnteriormenteObservaciones"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{ParientesEmpresa}", drow["ParientesEmpresa"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{AcusadoDelito}", drow["AcusadoDelito"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{AcusadoDelitoObservaciones}", drow["AcusadoDelitoObservaciones"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Direccion}", drow["Direccion"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Calle}", drow["Calle"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Colonia}", drow["Colonia"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{CP}", drow["CP"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Telefono}", drow["Telefono"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Celular}", drow["Celular"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Correo}", drow["Correo"].ToString())); // If Not IsDBNull(drow["CveSucursal"]) Then // ListaTagsDocumentost.Add(New TagsDocumentos("{CveSucursal}", DDLSucursal4.Text)) // End If ListaTagsDocumentost.Add(new TagsDocumentos("{NumeroSS}", drow["NumeroSS"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Licencia}", drow["Licencia"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{CartillaMilitar}", drow["CartillaMilitar"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{CURP}", drow["CURP"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{AutorizaAntidoping}", drow["AutorizaAntidoping"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Observaciones}", drow["Observaciones"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Direccion}", drow["Direccion"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{FechaIngreso}", drow["FechaIngreso"].ToString().ToDate().ToShortDateString())); ListaTagsDocumentost.Add(new TagsDocumentos("{Puesto}", drow["Puesto"].ToString())); ListaTagsDocumentost.Add(new TagsDocumentos("{CUIP}", "")); ListaTagsDocumentost.Add(new TagsDocumentos("{Denominacion}", "")); ListaTagsDocumentost.Add(new TagsDocumentos("{FechaNacimiento}", drow["FechaNacimiento"].ToString().ToDate().ToString("dd/MM/yyyy"))); string fechaActual = " " + NowADS().Day + " del mes " + NowADS().Month + " del año " + NowADS().Year; string FechaActualDF = NowADS().ToString("dd/MM/yyyy"); ListaTagsDocumentost.Add(new TagsDocumentos("{FechaActual}", fechaActual)); ListaTagsDocumentost.Add(new TagsDocumentos("{FechaActualDF}", FechaActualDF)); } } } return ListaTagsDocumentost; } public void DownLoad_ClickSolicitudPermiso(object sender, EventArgs e) { GridViewRow GvRow = (GridViewRow)((LinkButton)sender).NamingContainer; // Dim Folio As Integer = GvRow.DataKey("Folio").ToEntero // DescarSolicitudVacaciones(Folio) string RutaFormato = string.Format(@"{0}Formatos\PermisoSolicitud.docx", UsuarioActual.Empresa.Ruta); string NombreEmpleado = LblEmpleado.Text; string Codigo = LblCodigoEmpleado.Text; string Departamento = LblSRDepartamento.Text; string JefeInmediato = ""; string FechaInicio = GvRow.DataKey("FechaInicio").ToDateTime().ToString("dd/MM/yyyy"); string FechaFin = GvRow.DataKey("FechaFin").ToDateTime().ToString("dd/MM/yyyy"); string diasPermiso = $"{(GvRow.DataKey("FechaFin").ToDate() - GvRow.DataKey("FechaInicio").ToDate()).Days}"; string HorasPermiso = ""; // String.Format("{0}", ((GvRow.DataKey("FechaInicio").ToDateTime() - GvRow.DataKey("FechaFin").ToDateTime()).Hours)) string MotivoPermiso = string.Format("{0},{1}", GvRow.DataKey("Descripcion"), GvRow.DataKey("Motivo")); if (File.Exists(RutaFormato)) { clsGemBoxDocument objGemDocument = new clsGemBoxDocument(RutaFormato); List ListaTags = new List(); ListaTags = GetDatosTagsDocumentos(); ListaTags.Add(new TagsDocumentos("{NombreEmpleado}", NombreEmpleado)); ListaTags.Add(new TagsDocumentos("{Codigo}", Codigo)); ListaTags.Add(new TagsDocumentos("{Departamento}", Departamento)); ListaTags.Add(new TagsDocumentos("{JefeInmediato}", JefeInmediato)); ListaTags.Add(new TagsDocumentos("{FechaInicio}", FechaInicio)); ListaTags.Add(new TagsDocumentos("{FechaFin}", FechaFin)); ListaTags.Add(new TagsDocumentos("{diasPermiso}", diasPermiso)); ListaTags.Add(new TagsDocumentos("{HorasPermiso}", HorasPermiso)); ListaTags.Add(new TagsDocumentos("{MotivoPermiso}", MotivoPermiso)); objGemDocument.SustituirTags(ListaTags); // objGemDocument.GuardarStream() objGemDocument.GuardarStreamPDF(); byte[] bytesInStream = objGemDocument.GetBytesDocumento(); // Dim bytesInStream As Byte() = objGemDocument.memoryStream.ToArray objGemDocument.Dispose(); Response.Clear(); Response.ContentType = "application/force-download"; Response.AddHeader("content-disposition", "attachment; filename=" + SRCvePersonal + "_Solicituddepermiso_" + NowADS().ToString("yyyyMMddhhmmss") + ".pdf"); Response.BinaryWrite(bytesInStream); Response.End(); } else { Alert("No se encontro el formato de Permisos", TipoMensaje.ToastAdventencia); } } public void DownLoad_ClickSolicitudAutorizacion(object sender, EventArgs e) { GridViewRow GvRow = (GridViewRow)((LinkButton)sender).NamingContainer; string _Documento = GvRow.DataKey("Documento"); string RutaDocuemntoAutorizacion = string.Format(@"{0}Personal\{1}\Vacaciones\{2}", UsuarioActual.Empresa.Ruta, SRCvePersonal, _Documento); if (File.Exists(RutaDocuemntoAutorizacion)) { byte[] bytesInStream = File.ReadAllBytes(RutaDocuemntoAutorizacion); Response.Clear(); Response.ContentType = "application/force-download"; Response.AddHeader("content-disposition", "attachment; filename=" + _Documento); Response.AddHeader("content-disposition", "attachment; filename=" + _Documento); Response.BinaryWrite(bytesInStream); Response.End(); } else { Alert("No se encontro el documento que intenta descargar."); } } protected void BtnGeneratepdf_Click(object sender, EventArgs e) { byte[] pdf = new byte[1]; string nombre = $"recibos {LtlPeriodoseleccionado.Text}"; bool confiniquito = false; int CvePersonal = TxtCvePersonal.Text.ToEntero(); int CvePeriodo = TxtCvePeriodo.Text.ToEntero(); if (CvePersonal > 0) { using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetNom_Nominas(-1, TxtCvePersonal.Text.ToEntero(), TxtCvePeriodo.Text.ToEntero(), -1, UsuarioActual.CveEmpresa)) { nombre = $"{ObjNomina.Codigo}{ObjNomina.Nombre} {ObjNomina.SerieFolio}"; } if (ObjNomina.GetNom_NominasDetalles(-1, CvePersonal, CvePeriodo, "-1")) { confiniquito = ObjNomina.DtResultados.COUNT("CveConcepto", " CveSistema IN(10,11,32,47) AND Importe <>0") > 0; } } pdf = GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); if (confiniquito) { List pdfs = new List(); pdfs.Add(pdf); pdfs.Add(GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta, true)); pdf = MergeFiles(pdfs); } } else { List pdfs = new List(); //byte[] pdf2 = new byte[1]; bool notfirst = false; foreach (DataRow dr in dtempleados.FiltraParametros("", "CveSubProyecto").Rows) { CvePersonal = dr["CvePersonal"].ToString().ToEntero(); if (CvePersonal > 0) { pdfs.Add(GeneraPDFNomina(CvePersonal, CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta)); } //if (notfirst) //{ // pdf2 = GeneraPDFNomina(dr["CvePersonal"].ToString().ToEntero(), CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); // byte[] newByteArray2 = pdf.Concat(pdf2).ToArray(); //} //else //{ // pdf = GeneraPDFNomina(dr["CvePersonal"].ToString().ToEntero(), CvePeriodo, UsuarioActual.CveEmpresa, UsuarioActual.Empresa.Ruta); //} //notfirst = true; } pdf = MergeFiles(pdfs); } ImprimirbytesPDF(pdf, nombre); } public static byte[] MergeFiles(List sourceFiles) { //string destinationFile; try { using (MemoryStream ms = new MemoryStream()) { int f = 0; // we create a reader for a certain document PdfReader reader = new PdfReader(sourceFiles[f]); // we retrieve the total number of pages int n = reader.NumberOfPages; //Console.WriteLine("There are " + n + " pages in the original file."); // step 1: creation of a document-object iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document //PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create)); PdfWriter writer = PdfWriter.GetInstance(document, ms); // step 3: we open the document document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; int rotation; // step 4: we add content while (f < sourceFiles.Count) { int i = 0; while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } //Console.WriteLine("Processed page " + i); } f++; if (f < sourceFiles.Count) { reader = new PdfReader(sourceFiles[f]); // we retrieve the total number of pages n = reader.NumberOfPages; //Console.WriteLine("There are " + n + " pages in the original file."); } } // step 5: we close the document document.Close(); return ms.ToArray(); } } catch (Exception e) { string strOb = e.Message; } return null; } public static int CountPageNo(string strFileName) { // we create a reader for a certain document PdfReader reader = new PdfReader(strFileName); // we retrieve the total number of pages return reader.NumberOfPages; } protected void BtnGenerateXml_Click(object sender, EventArgs e) { string Ruta = ""; string PathXML = ""; string PathXMLF = ""; string Xmlname = ""; string XmlnameF = ""; string empleado = ""; Ruta = UsuarioActual.Empresa.Ruta; if (TxtCvePersonal.Text.ToEntero() != -1) { DataRow dr = dtempleados.FiltroPrimero(string.Format("CvePersonal ={0}", TxtCvePersonal.Text.ToEntero())); if (dr != null) { empleado = string.Format("{0} - {1}", dr["Codigo"], dr["Nombre"]); } using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetNom_Nominas(-1, TxtCvePersonal.Text.ToEntero(), TxtCvePeriodo.Text.ToEntero(), -1, UsuarioActual.CveEmpresa)) { PathXML = $"{Ruta}XML\\Nomina\\{ObjNomina.SerieFolio}.xml"; PathXMLF = $"{Ruta}XML\\Nomina\\{ObjNomina.Serie}F-{ObjNomina.Folio}.xml"; Xmlname = ObjNomina.SerieFolio; XmlnameF = $"{ObjNomina.Serie}F-{ObjNomina.Folio}"; } } try { string script = ""; if (!string.IsNullOrEmpty(PathXML) && System.IO.File.Exists(PathXML)) { LtlXml.Text = System.IO.File.ReadAllText(PathXML); script = string.Format("Savexml(\"{0} {1}.xml\", $('.ltlxml').html());", Xmlname, empleado); //System.IO.FileInfo file = new System.IO.FileInfo(PathXML); //string mimeType = "text/plain"; //try //{ // mimeType = MimeMapping.GetMimeMapping(PathXML); //} //catch (Exception) //{ //} //// Response.Write(path) //Response.Clear(); //Response.ClearHeaders(); //Response.ClearContent(); //Response.AddHeader("Content-Disposition", $"attachment; filename= {Uri.EscapeDataString(file.Name)}"); //Response.AddHeader("Content-Length", file.Length.ToString()); //Response.ContentType = mimeType; //Response.Flush(); //Response.TransmitFile(file.FullName); //Response.End(); } if (!string.IsNullOrEmpty(PathXMLF) && System.IO.File.Exists(PathXMLF)) { LtlXmlfin.Text = System.IO.File.ReadAllText(PathXMLF); script = string.Format("{1}Savexml(\"{0}(Indemnización) {2}.xml\", $('.ltlxmlfin').html());", Xmlname, script, empleado); } if (script.Trim().Length > 0) { RegistraScript(script); } else { Alert("No se encontro el archivo"); } } catch (Exception) { } } else { using (ClsNominas ObjNomina = new ClsNominas()) { if (ObjNomina.GetNom_Nominas(-1, -1, TxtCvePeriodo.Text.ToEntero(), -1, UsuarioActual.CveEmpresa)) { string script = ""; using (ZipFile descargaZIP = new ZipFile()) { descargaZIP.UseZip64WhenSaving = Zip64Option.AsNecessary; foreach (DataRow dbrow in ObjNomina.DtResultados.Rows) { Ruta = UsuarioActual.Empresa.Ruta; PathXML = $"{Ruta}XML\\Nomina\\{dbrow["SerieFolio"].ToString()}.xml"; PathXMLF = $"{Ruta}XML\\Nomina\\{dbrow["Serie"].ToString()}F-{dbrow["Folio"].ToString()}.xml"; if (!string.IsNullOrEmpty(PathXML) && System.IO.File.Exists(PathXML)) { FileInfo file = new FileInfo(PathXML); if (!descargaZIP.Any(x => x.FileName.Contains(file.Name))) { descargaZIP.AddFile(PathXML); } } if (!string.IsNullOrEmpty(PathXMLF) && System.IO.File.Exists(PathXMLF)) { FileInfo file = new FileInfo(PathXMLF); if (!descargaZIP.Any(x => x.FileName.Contains(file.Name))) { descargaZIP.AddFile(PathXMLF); } } } String PathZIP = $"{Ruta}XML\\Nomina\\{TxtCvePeriodo.Text.ToEntero()}.zip"; descargaZIP.Save(PathZIP); if (!string.IsNullOrEmpty(PathZIP) && System.IO.File.Exists(PathZIP)) { LtlZip.Text = System.IO.File.ReadAllText(PathZIP); script = string.Format("Savezip(\"{0}.zip\", $('.ltlzip').html());", DdlPeriodo.SelectedItem.Text); System.IO.File.Delete(PathZIP); } if (script.Trim().Length > 0) { RegistraScript(script); } else { Alert("No se encontro el archivo"); } //Response.Clear(); //Response.AddHeader("Content-Disposition", "attachment; filename=ArchivosXML.zip"); //Response.ContentType = "application/zip"; //descargaZIP.Save(Response.OutputStream); //Response.End(); } } } } } DataTable Contasource; DataTable ContaConceptossource; protected void LnkRegistrarProvision_Click(object sender, EventArgs e) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.RegistraProvision(CvePeriodoSeleccionado, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)) { int CvePrePolizaProvision = 0; int CvePrePolizaasmilidos = 0; int CvePrePolizaProrrateo = 0; if (objnom.DTSetResultados.Tables.Count > 1 && objnom.DTSetResultados.Tables[1].Rows.Count == 0) { if (objnom.DtResultados.Rows.Count > 0) { CvePrePolizaProvision = objnom.DtResultados.Rows[0]["CvePrePoliza"].ToString().ToEntero(); CvePrePolizaasmilidos = objnom.DtResultados.Rows[0]["CvePrePolizaAsimilables"].ToString().ToEntero(); CvePrePolizaProrrateo = objnom.DtResultados.Rows[0]["CvePrePolizaProrrateo"].ToString().ToEntero(); } string mensaje = string.Format("La provisión a sido generada.
Provisión
", CvePrePolizaProvision); if (CvePrePolizaasmilidos > 0) { mensaje = string.Format("{0} Asimilados
", mensaje, CvePrePolizaasmilidos); } if (CvePrePolizaProrrateo > 0) { mensaje = string.Format("{0} Prorrateo
", mensaje, CvePrePolizaProrrateo); } if (CvePrePolizaProvision > 0) { using (ClsContabilidad objconta = new ClsContabilidad()) { var objUsuario = UsuarioActual; if (objconta.ValidacionesPrePoliza(CvePrePolizaProvision, ref objUsuario)) { } } } Alert(mensaje); } else { if (objnom.DTSetResultados.Tables.Count > 1) { using (ClsContabilidad ObjContaz = new ClsContabilidad()) { if (ObjContaz.GetConta_ConceptosContables()) { ContaConceptossource = ObjContaz.DtResultados; } } if (UsuarioActual.Empresa.TipoContabilidad == 1) { using (ClsContabilidad ObjConta = new ClsContabilidad()) { if (ObjConta.GetCuentas(-1, "-1", 1, UsuarioActual.CveEmpresa)) { DdlCtaContable.DataSource = ObjConta.DtResultados; DdlCtaContable.DataBind(); Contasource = ObjConta.DtResultados; } } } else { using (ClsContPAQi ObjConta = new ClsContPAQi(UsuarioActual.Empresa)) { if (ObjConta.Conectado && ObjConta.GetCuentas(-1, "-1", 1)) { Contasource = ObjConta.DtResultados; DdlCtaContable.DataValueField = "Id"; DdlCtaContable.DataSource = ObjConta.DtResultados; DdlCtaContable.DataBind(); } } } DdlCtaContable.Items.Insert(0, new ListItem("Seleccione", "-1")); DdlCtaContable.SelectedValueExist("-1"); GVProvision.DataSource = objnom.DTSetResultados.Tables[1]; GVProvision.DataBind(); RegistraScript("$('#ModalRegistraProvision').modal();"); Alert("no se pudo registrar la provisión, existen cuentas sin vincular", TipoMensaje.MsgAdvertencia); UpRegistroProvision.Update(); } } } } } protected void LnkGuardarConceptosProvision_Click(object sender, EventArgs e) { bool continuar = true; using (ClsContabilidad ObjConta = new ClsContabilidad()) { int CveClasificacion = -1; ObjConta.IniciaTransacSQL(); foreach (GridViewRow gvrow in GVProvision.Rows) { int CveConceptoNomina = gvrow.DataKey("CveConcepto").ToEntero(); if (continuar && CveConceptoNomina > 0) { int CvePersonal = gvrow.DataKey("CvePersonal").ToEntero(); int CveconceptosContables = gvrow.FCDropDownList("DdlCconceptosContables").SelectedValue.ToEntero(); int CveCuenta = gvrow.FCDropDownList("Ddlcuentassd").SelectedValue.ToEntero(); if (CveconceptosContables > 0 && CveCuenta > 0) { if (!ObjConta.AddCuentasAsignaciones(CveconceptosContables, UsuarioActual.CveEmpresa, CveCuenta, CvePersonal: CvePersonal, CveClasificacion: CveClasificacion, CveConceptoNomina: CveConceptoNomina)) { continuar = false; } } else { continuar = false; } } } if (continuar) { ObjConta.Commit(); } else { ObjConta.RollBack(); } } if (continuar) { Alert("Las cuentas han sido asignadas correctamente."); RegistraScript("$('#ModalRegistraProvision').modal('hide');"); } } protected void GVProvision_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList ddllist = (DropDownList)e.Row.FindControl("Ddlcuentassd"); DropDownList DdlCconceptosContables = (DropDownList)e.Row.FindControl("DdlCconceptosContables"); DdlCconceptosContables.DataSource = ContaConceptossource; DdlCconceptosContables.DataBind(); DdlCconceptosContables.SelectedValueExist(e.Row.DataKey("CveConceptoContable")); ddllist.DataValueField = DdlCtaContable.DataValueField; ddllist.DataSource = Contasource; ddllist.DataBind(); ddllist.Items.Insert(0, new ListItem("Seleccione", "-1")); ddllist.SelectedValueExist("-1"); } } protected void LnkupPrimaRiesgo_Click(object sender, EventArgs e) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.PrimaRiesgoUP(UsuarioActual.CveEmpresa, TxtFechaPRT.Text.ToDateTime(), TxtPrimaRiesgo.Text.ToDecimal())) { } } loadtablas(); } protected void LnkAsistenciaIncidencias_Click(object sender, EventArgs e) { RegistraScript("$('#DmodalReporteInicidencia').modal()"); } protected void lnkreportepercepciones_Click(object sender, EventArgs e) { RegistraScript("$('#DmodalReportePercepcionesdeducciones').modal()"); } protected void LnkProcesarReporteIncidenciaTabular_Click(object sender, EventArgs e) { DateTime fechai = TxtRIFechaInicio.Text.ToDateTime(); DateTime fechaf = TxtRIFechaFin.Text.ToDateTime(); ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); int CveTipoPeriodo = 0; using (ClsNominas nom = new ClsNominas()) { if (nom.GetPeriodos(-1, UsuarioActual.CveEmpresa, -1, -1, CvePeriodoSeleccionado, -1) && (nom.DtResultados.Rows.Count > 0)) { fechai = nom.DtResultados.Rows[0]["FechaInicio"].ToString().ToDateTime(); fechaf = nom.DtResultados.Rows[0]["FechaFin"].ToString().ToDateTime(); CveTipoPeriodo = -nom.DtResultados.Rows[0]["CveTipoPeriodo"].ToString().ToEntero(); } if (nom.ReportedeincidenciasGET(UsuarioActual.CveEmpresa, fechai, fechaf, CveTipoPeriodo)) { var libro = wb.AddWorksheet(nom.DTSetResultados.Tables[2], "Incidencias"); libro.ColumnsUsed().AdjustToContents(); var libroin = wb.AddWorksheet(nom.DTSetResultados.Tables[1], "Descripción incidencias"); libroin.ColumnsUsed().AdjustToContents(); 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 incidencias"; libro.Range(3, 2, 3, 6).Merge().Value = $"del {fechai:dd/MM/yyyy} al {fechaf:dd/MM/yyyy}"; libro.Range(2, 7, 2, 9).Merge().Value = $"Fecha:{NowADS():dd/MM/yyyy}"; libro.Range(3, 7, 3, 9).Merge().Value = $"Hora:{NowADS():HH:mm}"; //ws.Row(1).InsertRowsAbove(1); } } 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=incidencias del {0:dd-MM-yyyy} al {1:dd-MM-yyyy}.xlsx", fechai, fechaf)); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } // protected void LnkshowProsesarASistencia_Click(object sender, EventArgs e) { RegistraScript("$('#DModalAsistenciaTabular').modal()"); } protected void LnkProcesarAsistenciaTabular_Click(object sender, EventArgs e) { //int chkImporteValor = 1; //int chkImporte = 1; //int chkImporteGravado = 0; DateTime fechai = TxtRIFechaInicio.Text.ToDateTime(); DateTime fechaf = TxtRIFechaFin.Text.ToDateTime(); List Filesgral = TxtAsistenciaTabular.getfiles().Archivos; bool continuar = Filesgral.Count > 0; string stringError = ""; Archivo fileItem = continuar ? Filesgral[0] : null; if (continuar) { string FileExtension = fileItem.Extension.ToUpper(); if (FileExtension == "XLS" | FileExtension == "XLSX" | FileExtension == "CSV") { } else { continuar = false; stringError = "No se inserto un archivo de tipo Excel"; } } if (!(CvePeriodoSeleccionado >= 0)) { continuar = false; stringError = "debe cargar el periodo a actualizar"; } DataTable DTEXcel = new DataTable(); if (continuar) { try { DataTable dtxz = Extensiones.ModExtensiones.ReadExcelFile(fileItem.FileUrl, true, 4); DTEXcel = dtxz.FiltraParametros(" LEN(Codigo)>0 AND Codigo <> 'Codigo'"); } catch (Exception ex) { continuar = false; stringError = "Ocurrio un Error al procesar el excel "; string.Format("{0} \r\n{0}", stringError, ex.ToString()).GuardaLog(); } } if (continuar && DTEXcel.Rows.Count == 0) { continuar = false; stringError = "No se encontraron cambios"; } if (continuar) { using (ClsNominas nom = new ClsNominas()) { if (nom.GetPeriodos(-1, UsuarioActual.CveEmpresa, -1, -1, CvePeriodoSeleccionado, -1) && (nom.DtResultados.Rows.Count > 0)) { fechai = nom.DtResultados.Rows[0]["FechaInicio"].ToString().ToDateTime(); fechaf = nom.DtResultados.Rows[0]["FechaFin"].ToString().ToDateTime(); } } for (int i = 2; i < DTEXcel.Columns.Count; i++) { DateTime FechaAsis = DTEXcel.Columns[i].ColumnName.ToDateTime(); if (FechaAsis < fechai || FechaAsis > fechaf) { continuar = false; stringError = "Las fechas no concuerdadn con el periodo seleccionado"; } } } if (continuar) { int CvePersonal = 0; string Codigo; DateTime FechaAsis; DataTable dtasis = get_GlobalDTAsistenciasInasistencias(UsuarioActual.CveEmpresa); List listaerrores = new List(); using (ClsRH ObjPersonal = new ClsRH()) { for (int j = 0; j < DTEXcel.Rows.Count; j++) { Codigo = DTEXcel.Rows[j]["Codigo"].ToString(); CvePersonal = -1; if (Codigo != "-1" && ObjPersonal.GetPersonal(CvePersonal, Codigo, "-1", "-1", "-1", -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, "-1", -1, -1, -1, -1, -1, -1, "-1", "-1", "-1", "-1", UsuarioActual.CveEmpresa) && ObjPersonal.DtResultados.Rows.Count == 1) { CvePersonal = ObjPersonal.CvePersonal; //CveMetodoPago = objpersonal.CveMetodoPago; } for (int i = 2; i < DTEXcel.Columns.Count; i++) { FechaAsis = DTEXcel.Columns[i].ColumnName.ToDateTime(); string tipoasistencia = DTEXcel.Rows[j][i].ToString(); DataRow drasis = dtasis.FiltroPrimero(string.Format("Tipo = '{0}'", tipoasistencia)); if (CvePersonal > 0 && drasis != null && ObjPersonal.AddAsistencia(CvePersonal, -2, -2, FechaAsis, drasis["CveAsistenciasInasistencias"].ToString().ToEntero(), 100, -2, -2, -2, TxtObservaciones.Text.Trim(), UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "Q")) { continuar = true; } if (CvePersonal > 0 && drasis == null && !listaerrores.Contains(tipoasistencia) && tipoasistencia != "" && tipoasistencia != "--" && tipoasistencia != "-") { listaerrores.Add(DTEXcel.Rows[j][i].ToString()); // stringError = String.Format("{0}
el empleado {1} tiene una asistencia invalidad el dia {2:dd/MM/yyyy}", stringError, Codigo, FechaAsis); } } } } if (continuar) { cargarasistencia(); if (listaerrores.Count > 0) { string strmsg = "Los siguientes tipos de asistencia no pudieron ser cargados porque no se encuentran registrados "; for (int i = 0; i < listaerrores.Count; i++) { strmsg = String.Format("{0}
{1}", strmsg, listaerrores[i]); } Alert(strmsg, TipoMensaje.MsgInformacion); } else { Alert("La Asistencia se guardó correctamente.", TipoMensaje.MsgInformacion); } UpDatos.Update(); } else { Alert(stringError, TipoMensaje.MsgAdvertencia); } } else { Alert(stringError, TipoMensaje.MsgAdvertencia); } RegistraScript("$('#DModalAsistenciaTabular').modal('hide')"); } protected void LnkProcesarReporteIncidencia_Click(object sender, EventArgs e) { DateTime fechai = TxtRIFechaInicio.Text.ToDateTime(); DateTime fechaf = TxtRIFechaFin.Text.ToDateTime(); ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); using (ClsNominas nom = new ClsNominas()) { if (nom.ReportedeincidenciasGET(UsuarioActual.CveEmpresa, fechai, fechaf, 4)) { var libro = wb.AddWorksheet(nom.DTSetResultados.Tables[2], "Incidencias"); libro.ColumnsUsed().AdjustToContents(); var libroin = wb.AddWorksheet(nom.DTSetResultados.Tables[1], "Descripción incidencias"); libroin.ColumnsUsed().AdjustToContents(); 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 incidencias"; libro.Range(3, 2, 3, 6).Merge().Value = $"del {fechai:dd/MM/yyyy} al {fechaf:dd/MM/yyyy}"; libro.Range(2, 7, 2, 9).Merge().Value = $"Fecha:{NowADS():dd/MM/yyyy}"; libro.Range(3, 7, 3, 9).Merge().Value = $"Hora:{NowADS():HH:mm}"; //ws.Row(1).InsertRowsAbove(1); } } 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=incidencias del {0:dd-MM-yyyy} al {1:dd-MM-yyyy}.xlsx", fechai, fechaf)); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } protected void LnkProcesarReporteAcumulados_Click(object sender, EventArgs e) { //DateTime fechai = TxtRIFechaInicio.Text.ToDateTime(); //DateTime fechaf = TxtRIFechaFin.Text.ToDateTime(); ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); using (ClsNominas nom = new ClsNominas()) { if (nom.ReportedeAcumuladosGET(UsuarioActual.CveEmpresa, TxtPeriodo.Text.ToEntero(), 4)) { DateTime datei = new DateTime(); DateTime datef = datei; try { datei = $"{TxtPeriodo.Text}01".ToDateTime(); datef = datei.AddMonths(1).AddDays(-1); } catch (Exception) { } DataTable dt = nom.DTSetResultados.Tables[0]; var libro = wb.AddWorksheet(dt, "Acumulados"); libro.Tables.FirstOrDefault().Theme = ClosedXML.Excel.XLTableTheme.None; int crow = 1; foreach (DataRow item in dt.Rows) { crow++; //220,230,241 //79,129,189 switch (item["Grupoid"].ToString()) { case "1": libro.Range(crow, 1, crow, 11).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(crow, 1, crow, 11).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; break; case "2": libro.Range(crow, 1, crow, 11).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(220, 230, 241)); //libro.Range(crow, 1, crow, 10).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; break; case "3": break; case "4": libro.Range(crow, 1, crow, 11).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(crow, 1, crow, 11).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; break; case "5": libro.Range(crow, 1, crow, 11).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(crow, 1, crow, 11).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; break; } } libro.Range(2, 3, crow, 11).Style.NumberFormat.Format = "$##,###,###,0.00"; libro.Range(2, 3, crow, 11).DataType = ClosedXML.Excel.XLDataType.Number; libro.Column(1).Delete(); libro.ColumnsUsed().AdjustToContents(); 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 Acumulados del {datei:dd/MM/yyyy} al {datef:dd/MM/yyyy}"; //libro.Range(3, 2, 3, 6).Merge().Value = $"del {fechai:dd/MM/yyyy} al {fechaf:dd/MM/yyyy}"; libro.Range(2, 7, 2, 9).Merge().Value = $"Fecha:{NowADS():dd/MM/yyyy}"; libro.Range(3, 7, 3, 9).Merge().Value = $"Hora:{NowADS():HH:mm}"; //ws.Row(1).InsertRowsAbove(1); } } 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=Acumulados.xlsx", "")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } protected void LnkReporteAcumulados_Click(object sender, EventArgs e) { RegistraScript("$('#DmodalReporteAcumulados').modal()"); } protected void LnkrRepPercpDed_Click(object sender, EventArgs e) { DateTime fechai = TxtRpdFechaInicio.Text.ToDateTime(); DateTime fechaf = TxtRpdFechaFin.Text.ToDateTime(); ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); using (ClsNominas nom = new ClsNominas()) { if (nom.ReportedePercepcionesDeduccionesGet(UsuarioActual.CveEmpresa, fechai, fechaf, 4)) { DataTable dt = nom.DTSetResultados.Tables[0]; var libro = wb.AddWorksheet(nom.DTSetResultados.Tables[0], "Percepciones y deducciones"); libro.Tables.FirstOrDefault().Theme = ClosedXML.Excel.XLTableTheme.None; int crow = 1; foreach (DataRow item in dt.Rows) { crow++; //220,230,241 //79,129,189 switch (item["Grupoid"].ToString()) { case "10": libro.Range(crow, 1, crow, 9).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(184, 204, 228)); break; case "8": case "11": libro.Range(crow, 1, crow, 9).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); libro.Range(crow, 1, crow, 11).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; break; case "6": libro.Range(crow, 1, crow, 9).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(216, 228, 188)); break; case "5": case "7": libro.Range(crow, 1, crow, 9).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(155, 187, 89)); libro.Range(crow, 1, crow, 9).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; break; case "2": //libro.Range(crow, 1, crow, 11).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(216, 228, 188)); break; case "1": case "3": libro.Range(crow, 1, crow, 9).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(75, 172, 198)); libro.Range(crow, 1, crow, 9).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; break; } } libro.Range(2, 4, crow, 9).Style.NumberFormat.Format = "$##,###,###,0.00"; libro.Range(2, 4, crow, 9).DataType = ClosedXML.Excel.XLDataType.Number; libro.Column(1).Delete(); libro.ColumnsUsed().AdjustToContents(); 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 percepciones y deducciones del {fechai:dd/MM/yyyy} al {fechaf:dd/MM/yyyy}"; libro.Range(1, 2, 2, 6).Style.Font.SetBold(true); libro.Range(1, 2, 2, 6).Style.Font.SetFontSize(16); libro.Range(2, 2, 2, 6).Style.Font.SetFontSize(14); libro.Range(1, 2, 2, 6).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Center; //libro.Range(3, 2, 3, 6).Merge().Value = $"del {fechai:dd/MM/yyyy} al {fechaf:dd/MM/yyyy}"; libro.Range(2, 7, 2, 9).Merge().Value = $"Fecha:{NowADS():dd/MM/yyyy}"; libro.Range(3, 7, 3, 9).Merge().Value = $"Hora:{NowADS():HH:mm}"; //ws.Row(1).InsertRowsAbove(1); } } 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=percepciones .xlsx", "")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } protected void GvBitacora_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { for (int j = 0; j < e.Row.Cells.Count; j++) { string encoded = e.Row.Cells[j].Text; e.Row.Cells[j].Text = Context.Server.HtmlDecode(encoded); } } } protected void LnkCancelarFolioFiscal_Click(object sender, EventArgs e) { Timbrado ObjTimbrado = new Timbrado(); string FolioFiscal = TxtFolioFiscal.Text; decimal Total = TxtTotal.Text.ToDecimal(); string RFCReceptor = TxtRFCReceptor.Text; string RFCEmisor = TxtRFCEmisor.Text; var resultado = ObjTimbrado.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, Total, RFCReceptor, RFCEmisor, 4); string.Format("CveNomina:{0},RFC{3}, FolioFiscal:{1},Resultado :{2}", -1, FolioFiscal, Newtonsoft.Json.JsonConvert.SerializeObject(resultado), RFCReceptor).GuardaLog(); if (resultado.Verificado) { Alert($"La nómina con folio fiscal '{FolioFiscal}' fue cancelada ante el SAT", TipoMensaje.MsgInformacion); } else { Alert(ObjTimbrado.MensajeErrorCFDI, TipoMensaje.MsgAdvertencia); } ObjTimbrado = null; } protected void LnkOpenCancelarTimbre_Click(object sender, EventArgs e) { RegistraScript(string.Format("$('#{0}').modal();", DmodalCancelartimbre.ClientID)); } protected void LnkOpenProrrateo_Click(object sender, EventArgs e) { using (ClsRH onom = new ClsRH()) { if (onom.GetPersonal(-1, UsuarioActual.CveEmpresa)) { DdlPRPersonal.DataSource = onom.DtResultados; DdlPRPersonal.DataBind(); } } using (ClsNominas onom = new ClsNominas()) { GVProrrateo.DataSource = null; if (onom.ProrrateosubproyectoGET(UsuarioActual.CveEmpresa)) { GVProrrateo.DataSource = onom.DtResultados; } GVProrrateo.DataBind(); } RegistraScript(string.Format("$('#DModalProrrateo').modal();")); UpModalProrrateo.Update(); } protected void LnkEliminarProrrateo_Click(object sender, EventArgs e) { GridViewRow gvrow = (GridViewRow)(((LinkButton)sender).NamingContainer); int CvePersonal, CveSubProyecto; CvePersonal = gvrow.DataKey("CvePersonal").ToEntero(); CveSubProyecto = gvrow.DataKey("CveSubProyecto").ToEntero(); using (ClsNominas onom = new ClsNominas()) { if (onom.ProrrateosubproyectoRemove(CvePersonal, CveSubProyecto)) { GVProrrateo.DataSource = null; if (onom.ProrrateosubproyectoGET(UsuarioActual.CveEmpresa)) { GVProrrateo.DataSource = onom.DtResultados; } GVProrrateo.DataBind(); Alert("Se ha eliminado satisfactoriamente."); } } } protected void GVProrrateo_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { int CvePersonal, CveSubProyecto; decimal Porcentaje; CvePersonal = e.Row.DataKey("CvePersonal").ToEntero(); CveSubProyecto = e.Row.DataKey("CveSubProyecto").ToEntero(); Porcentaje = e.Row.DataKey("Porcentaje").ToDecimal(); if (CveSubProyecto > 0) { } else { e.Row.FindControl("LnkEliminarProrrateo").Visible = false; e.Row.CssClass = Porcentaje == 1 ? "info" : "danger"; } } } protected void LnkAgregarProrrateo_Click(object sender, EventArgs e) { int CvePersonal, CveSubProyecto; decimal Porcentaje; CvePersonal = DdlPRPersonal.SelectedValue.ToEntero(); CveSubProyecto = DdlPRSubProyecto.SelectedValue.ToEntero(); Porcentaje = TxtPorcentaje.Text.ToDecimal(); using (ClsNominas onom = new ClsNominas()) { if (onom.ProrrateosubproyectoAdd(CvePersonal, CveSubProyecto, Porcentaje)) { GVProrrateo.DataSource = null; if (onom.ProrrateosubproyectoGET(UsuarioActual.CveEmpresa)) { GVProrrateo.DataSource = onom.DtResultados; } GVProrrateo.DataBind(); Alert("Se ha agregado satisfactoriamente."); } } UpModalProrrateo.Update(); } protected void LnkConsultartablasVacaciones_Click(object sender, EventArgs e) { CargaVacacionesEmpresas(); } protected void CargaVacacionesEmpresas() { int ejercicio = TxtEjercicioFiltroVacaciones.Text.Trim() == "" ? -1 : TxtEjercicioFiltroVacaciones.Text.Trim().ToEntero(); using (ClsRH ObjVaca = new ClsRH()) { ObjVaca.VacacionesEmpresasGet(UsuarioActual.CveEmpresa, -1, -1, ejercicio); GVVacacionesEmpresas.DataSource = ObjVaca.DtResultados; ObjVaca.Dispose(); } GVVacacionesEmpresas.DataBind(); upDatosVacaEmpre.Update(); } protected void BtnVacaADD_Click(object sender, EventArgs e) { int diasVacaciones = TxtVacadiasVacaciones.Text.ToEntero(); int Cinicio = TxtVacaInicio.Text.ToEntero(); int Cfin = TxtVacaFin.Text.ToEntero(); int ejercicio = TxtEjercicioVacaciones.Text.ToEntero(); bool Continuar = false; using (ClsRH ObjVaca = new ClsRH()) { Continuar = ObjVaca.VacacionesEmpresasAdd(UsuarioActual.CveEmpresa, Cinicio, Cfin, diasVacaciones, ejercicio); } if (Continuar) { RegistraScript("$('#DModalVacacionesEmpresas').modal('hide');"); CargaVacacionesEmpresas(); upDatosVacaEmpre.Update(); Alert("Las Vacaciones se han agregado."); } } protected void LnkEliminarVaca_Click(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)(((LinkButton)sender).NamingContainer); int CcveEmpresa = gvRow.DataKey("CveEmpresa").ToEntero(); int Cinicio = gvRow.DataKey("Inicio").ToEntero(); int Cfin = gvRow.DataKey("Fin").ToEntero(); int Ejercicio = gvRow.DataKey("Ejercicio").ToEntero(); bool Continuar = false; using (ClsRH ObjVaca = new ClsRH()) { Continuar = ObjVaca.VacacionesEmpresasRemove(CcveEmpresa, Cinicio, Cfin, Ejercicio); } if (Continuar) { CargaVacacionesEmpresas(); Alert("El Vacaciones_Empresas Se ha Eliminado"); } } #region Layouts enum Bancos { SinSelccion, Bancomer, Banorte, Banamex } Bancos Banco { get { if (ViewState["Banco"] == null) { ViewState["Banco"] = Bancos.SinSelccion; } return (Bancos)ViewState["Banco"]; } set { ViewState["Banco"] = (Bancos)value; } } string ConvenioPagoElectronico { get { if (ViewState["ConvenioPagoElectronico"] == null) { ViewState["ConvenioPagoElectronico"] = string.Empty; } return ViewState["ConvenioPagoElectronico"].ToString(); } set { ViewState["ConvenioPagoElectronico"] = (string)value; } } protected void LnkLayoutContable_Click(object sender, EventArgs e) { // RBLModalBancosLayout.SelectedValue = "1"; Banco = Bancos.SinSelccion; CargaCuentas(); DivModalLayoutBancosFecha.Visible = false; TxtModalLayoutBancosFecha.Text = ""; RegistraScript("$('#ModalLayoutBancos').modal('show');"); UpModalBancosLayout.Update(); } private void CargaCuentas() { DdlCuenta.Items.Clear(); DataTable DTCuentas = get_GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa: UsuarioActual.CveEmpresa).FiltraParametros(" CveTipoCuenta <> 1 AND UsaLayout = 'True' AND LEN(ConvenioPagoElectronico) > 0 "); DTCuentas.CaseSensitive = false; DdlCuenta.DataSource = DTCuentas.FiltraParametros(" Banco IN('BANCOMER','BANORTE','BBVA Bancomer','BBVA','BANAMEX')"); DdlCuenta.DataBind(); DdlCuenta.Items.Insert(0, new ListItem("Seleccione", "-1")); DdlCuenta.SelectedValueExist("-1"); } protected void DdlCuenta_SelectedIndexChanged(object sender, EventArgs e) { ConvenioPagoElectronico = string.Empty; DivModalLayoutBancosFecha.Visible = false; if (DdlCuenta.SelectedValue.ToEntero() > 0) { ConvenioPagoElectronico = get_GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa: UsuarioActual.CveEmpresa).FiltroPrimeroValor("ConvenioPagoElectronico", $" CveCuenta = {DdlCuenta.SelectedValue}").ToString(); if (DdlCuenta.SelectedItem.Text.ToUpper().Contains("BANCOMER") || DdlCuenta.SelectedItem.Text.ToUpper().Contains("BBVA")) { Banco = Bancos.Bancomer; } else if (DdlCuenta.SelectedItem.Text.ToUpper().Contains("BANORTE")) { Banco = Bancos.Banorte; DivModalLayoutBancosFecha.Visible = true; } else if (DdlCuenta.SelectedItem.Text.ToUpper().Contains("BANAMEX")) { Banco = Bancos.Banamex; DivModalLayoutBancosFecha.Visible = true; } else { ConvenioPagoElectronico = string.Empty; } } else { Banco = Bancos.SinSelccion; } } protected void BtnLayoutXLS_Click(object sender, EventArgs e) { using (ClsNominas objnom = new ClsNominas()) { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("Layout"); int row = 1; int column = 1; libro.Cell(row, column++).Value = "Código"; libro.Cell(row, column++).Value = "Nombre"; libro.Cell(row, column++).Value = "Banco"; libro.Cell(row, column++).Value = "Cuenta"; libro.Cell(row, column++).Value = "CLABE"; libro.Cell(row, column++).Value = "Neto"; int maxxolumn = column; libro.Range(1, 1, row, column - 1).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(1, 1, row, column - 1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); if (objnom.GetDispersionNomina(CvePeriodoSeleccionado, UsuarioActual.CveEmpresa, -1)) { foreach (DataRow dRow in objnom.DtResultados.Rows) { row++; column = 1; libro.Cell(row, column++).Value = dRow["Codigo"]; libro.Cell(row, column++).Value = dRow["Nombre"]; libro.Cell(row, column++).Value = string.Format("'{0}", dRow["BancoNombre"]); libro.Cell(row, column++).Value = string.Format("'{0}", dRow["NumeroCuenta"]); libro.Cell(row, column++).Value = string.Format("'{0}", dRow["CLABE"]); var importeCell = libro.Cell(row, column++); importeCell.Value = dRow["Importe"]; importeCell.Style.NumberFormat.Format = "#,##0.00"; } } libro.Columns().AdjustToContents(); // Adjust columns to fit content 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", "ListadePago")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } } protected void BtnEfectivaleXLS_Click(object sender, EventArgs e) { ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("Layout"); int row = 1; int column = 1; libro.Cell(row, column++).Value = "XSUBTOTAL"; //libro.Cell(row, column++).Value = ""; row = row + 1; column = 1; libro.Cell(row, column++).Value = "XCLIENTE"; libro.Cell(row, column++).Value = "XTIPOPEDIDO"; libro.Cell(row, column++).Value = "XNUMERO"; libro.Cell(row, column++).Value = "XIMPORTE"; int maxxolumn = column; libro.Range(row, 1, row, column - 1).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(row, 1, row, column - 1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); DataRow dcon; decimal subtotal = 0; DataTable dt = null; using (ClsNominas objnom = new ClsNominas()) { objnom.GetEfectivaleXLS(CvePeriodoSeleccionado, UsuarioActual.CveEmpresa, -1); dt = objnom.DtResultados; } if (dt != null && dt.Rows.Count > 0) { foreach (DataRow dRow in dt.Rows) { decimal importe = dRow["Importe"].ToString().ToDecimal(); subtotal = subtotal + importe; row++; column = 1; libro.Cell(row, column++).Value = string.Format("'{0}", dRow["XCLIENTE"]); libro.Cell(row, column++).Value = string.Format("'{0}", dRow["XTIPOPEDIDO"]); libro.Cell(row, column++).Value = string.Format("'{0}", dRow["CodigoDispersionVale"]); libro.Cell(row, column++).Value = importe; } } libro.Cell(1, 2).Value = subtotal; libro.Columns().AdjustToContents(); // Adjust columns to fit content 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", "ListadePago")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } protected void BtnModalBancosProcesar_Click(object sender, EventArgs e) { if (Banco == Bancos.Bancomer) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetDispersionNomina(CvePeriodoSeleccionado, UsuarioActual.CveEmpresa, 4)) { CrearLayoutNominaBancomer(objnom.DtResultados); } } } else if (Banco == Bancos.Banorte) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetDispersionNomina(CvePeriodoSeleccionado, UsuarioActual.CveEmpresa, 18)) { CrearLayoutNominaBanorte(objnom.DtResultados, ConvenioPagoElectronico, 1); } } } else if (Banco == Bancos.Banamex) { using (ClsNominas objnom = new ClsNominas()) { if (objnom.GetDispersionNomina(CvePeriodoSeleccionado, UsuarioActual.CveEmpresa, 1)) { CrearLayoutNominaBanamex(objnom.DtResultados); } } } } private void CrearLayoutNominaBancomer(DataTable DTNomina) { StringBuilder sb = new StringBuilder(); StringBuilder SbErrores = new StringBuilder(); bool ErroresValidaciones = false; int modalidadnomina = 1; if (UsuarioActual.CveEmpresa.Contiene(189, 193, 195, 196, 197, 172, 173,174)) modalidadnomina = 2; SbErrores.AppendLine("Se detectaron los siguientes errores en la generación del layout:
"); foreach (DataRow dRow in DTNomina.Rows) { string RFC = dRow["RFC"].ToString(); string Nombre = dRow["Nombre"].ToString(); string BancoNumCuenta = dRow["NumeroCuenta"].ToString(); decimal Importe = dRow["Importe"].ToString().ToDecimal(); if (RFC.Trim().Length == 0) SbErrores.AppendLine($"El RFC es requerido del empleado {Nombre}
"); System.Text.RegularExpressions.Match Coincidencia = System.Text.RegularExpressions.Regex.Match(RFC, @"/^([A-Z,Ñ,&]{3,4}([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])[A-Z|\d]{3})$/"); //if (!Coincidencia.Success) //{ // SbErrores.AppendLine($"El RFC {RFC} del empleado {Nombre} no es valido
"); // ErroresValidaciones = true; //} if (BancoNumCuenta.Trim().Length != 10) { SbErrores.AppendLine($"- {Nombre} numero de cuenta incorrecto, la cuenta debe de tener 10 caracteres
"); // Bancomer 10 caracteres ErroresValidaciones = true; } if (Importe <= 0) { SbErrores.AppendLine($"- {Nombre} el importe debe de ser mayor a 0 importe {Importe}"); // importe mayot a 0 ErroresValidaciones = true; } } if (!ErroresValidaciones) { int Count = 1; foreach (DataRow dRow in DTNomina.Rows) { StringBuilder SbLinea = new StringBuilder(); string RFC = dRow["RFC"].ToString(); string Nombre = dRow["Nombre"].ToString(); string BancoNumCuenta = dRow["NumeroCuenta"].ToString(); decimal Importe = dRow["Importe"].ToString().ToDecimal().RoundSQL(2); SbLinea.Append(Count.ToString("000000000")); SbLinea.Append(RFC.Trim().PadRight(16)); if (modalidadnomina == 2) SbLinea.Append("99"); else SbLinea.Append("03"); SbLinea.Append(BancoNumCuenta.Trim().PadRight(20)); SbLinea.Append(Importe.ToString("0000000000000.00").Replace(".", "")); if (Nombre.Trim().Length > 40) Nombre = Nombre.Substring(0, 40); SbLinea.Append(Nombre.Trim().PadRight(40)); if (modalidadnomina == 2) { SbLinea.Append("001"); SbLinea.Append("001"); } else { SbLinea.Append("012"); SbLinea.Append("000"); } sb.AppendLine(SbLinea.ToString()); Count = Count + 1; } Response.Clear(); Response.ClearHeaders(); Response.AppendHeader("Content-Length", sb.ToString()); Response.ContentType = "text/plain"; //Response.AppendHeader("Content-Disposition", $"attachment;filename=\"Nomina{NowADS().ToString("yyyyMMddhhmmss").ToString()}.txt\""); Response.AppendHeader("Content-Disposition", $"attachment;filename=\"Nomina_BBVA_{DdlPeriodo.SelectedItem.Text}.txt\""); Response.Write(sb.ToString()); //RegistraScript("$('#ModalLayoutBancos').modal('hide');"); // Response.Flush(); Response.End(); } else Alert(SbErrores.ToString(), TipoMensaje.MsgAdvertencia); } private void CrearLayoutNominaBanorte(DataTable DTNomina, string Emisora, int Consecutivo) { StringBuilder sb = new StringBuilder(); StringBuilder SbErrores = new StringBuilder(); char Cero = '0'; char Espacio = ' '; bool ErrorProceso = false; if (DTNomina.Rows.Count > 0) { //Tipo Registro A 1 1-1 sb.Append("H"); //Cleve de Servicio A 2 2-3 sb.Append("NE"); //Emisora N 5 4-8 sb.Append(Emisora.PadLeft(5, Cero)); //FechaProceso N 8 9-16 sb.Append(TxtModalLayoutBancosFecha.Text.ToDate().ToString("yyyyMMdd")); //Conmsecutivo N 2 17-18 sb.Append("01"); //Numero Total de Registros N 6 19-24 sb.Append(DTNomina.Rows.Count.ToString().PadLeft(6, Cero)); //Importe Total de Registros N 15 25-39 sb.Append(DTNomina.SUMD("Importe").ToString("0000000000000.00").Replace(".", "")); //Numero Total altas N 6 40-45 sb.Append("000000"); //Importe Total altas N 15 46-60 sb.Append("000000000000000"); //Numero Total Bajas N 6 61-66 sb.Append("000000"); //Importe Total Bajas N 15 67-81 sb.Append("000000000000000"); //Numero Total de cuentas a verificar N 6 82-87 sb.Append("000000"); //Accion N 1 88-88 sb.Append("0"); //filler 77 89-165 sb.Append(string.Empty.PadLeft(77, Espacio)); if (!ErrorProceso) { foreach (DataRow dRow in DTNomina.Rows) { // Codigo ReferenciaDelServicio ReferenciaLeyendaDelOrdenante Importe NumeroBancoReceptor TipoCuenta NumeroCuenta TipoMovimiento Accion ImporteIvaOperacion string Codigo = dRow["Codigo"].ToString().Trim(); string ReferenciaDelServicio = dRow["ReferenciaDelServicio"].ToString().Trim(); string ReferenciaLeyendaDelOrdenante = dRow["ReferenciaLeyendaDelOrdenante"].ToString().Trim(); decimal Importe = dRow["Importe"].ToString().ToDecimal(); string NumeroBancoReceptor = dRow["NumeroBancoReceptor"].ToString().Trim(); string TipoCuenta = dRow["TipoCuenta"].ToString().Trim(); string NumeroCuenta = dRow["NumeroCuenta"].ToString().Trim(); string TipoMovimiento = dRow["TipoMovimiento"].ToString().Trim(); string Accion = dRow["Accion"].ToString().Trim(); string ImporteIvaOperacion = dRow["ImporteIvaOperacion"].ToString().Trim(); //Linea Nueva sb.AppendLine(""); //Tipo de registro A 1 1-1 sb.Append("D"); //Fecha Aplicacion N 8 2-9 sb.Append(TxtModalLayoutBancosFecha.Text.ToDate().ToString("yyyyMMdd")); //CodigoEmpleado A 10 10-19 if (ErrorProceso == false && Codigo.Length > 0 && Codigo.Trim().Length <= 10) { sb.Append(Codigo.PadLeft(10, Cero)); } else { SbErrores.AppendLine($"{Codigo} Codigo {Codigo} debe de tener una logitud de entre 1 y 10
"); ErrorProceso = true; } //ReferenciaDelServicio A 40 20-29 sb.Append(ReferenciaDelServicio.PadLeft(40, Espacio)); //ReferenciaLeyendaDelOrdenante A 40 60-99 sb.Append(ReferenciaLeyendaDelOrdenante.PadLeft(40, Espacio)); //Importe N 15 100-114 sb.Append(Importe.ToString("0000000000000.00").Replace(".", "")); //NumeroBancoReceptor N 3 115-117 sb.Append(NumeroBancoReceptor.PadLeft(3, Cero)); //TipoCuenta N 2 118-119 sb.Append(TipoCuenta.PadLeft(2, Cero)); //NumeroCuenta N 18 120-137 sb.Append(NumeroCuenta.PadLeft(18, Cero)); //Tipo movimiento N 1 138-138 sb.Append(TipoMovimiento.PadLeft(1, Cero)); //Accion N 1 139-139 sb.Append(Accion.PadLeft(1, Espacio)); //ImporteIvaOperacion 140-147 sb.Append(ImporteIvaOperacion.PadLeft(8, Cero)); //filler 18 148-165 sb.Append(string.Empty.PadLeft(18, Espacio)); } if (!ErrorProceso) { sb.AppendLine(""); } } if (!ErrorProceso) { Response.Clear(); Response.ClearHeaders(); Response.AppendHeader("Content-Length", sb.ToString()); Response.ContentType = "text/plain"; Response.AppendHeader("Content-Disposition", $"attachment;filename=\"NI{Emisora.PadLeft(5, Cero)}{Consecutivo.ToString("00")}.PAG\""); Response.Write(sb.ToString()); RegistraScript("$('#ModalLayoutBancos').modal('hide');"); //Response.Flush(); Response.End(); } else { Alert($"Errores {SbErrores.ToString()}", TipoMensaje.ToastAdventencia); } } } private void CrearLayoutNominaBanamex(DataTable DTNomina) { StringBuilder sb = new StringBuilder(); StringBuilder SbErrores = new StringBuilder(); bool ErroresValidaciones = false; SbErrores.AppendLine("Se detectaron los siguientes errores en la generación del layout"); foreach (DataRow dRow in DTNomina.Rows) { //string RFC = dRow["RFC"].ToString(); string Nombre = dRow["Nombre"].ToString(); string BancoNumCuenta = dRow["NumeroCuenta"].ToString(); decimal Importe = dRow["Importe"].ToString().ToDecimal(); //if (RFC.Trim().Length == 0) // SbErrores.AppendLine($"El RFC es requerido del empleado {Nombre}
"); //System.Text.RegularExpressions.Match Coincidencia = System.Text.RegularExpressions.Regex.Match(RFC, @"/^([A-Z,Ñ,&]{3,4}([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])[A-Z|\d]{3})$/"); //if (!Coincidencia.Success) //{ // SbErrores.AppendLine($"El RFC {RFC} del empleado {Nombre} no es valido
"); // ErroresValidaciones = true; //} if (BancoNumCuenta.Trim().Length != 10 || BancoNumCuenta.Trim().Length != 16) { SbErrores.AppendLine($"Empleado {Nombre} numero de cuenta incorrecto, la cuenta debe de tener 10 caracteres
"); // Bancomer 10 caracteres ErroresValidaciones = true; } if (Importe <= 0) { SbErrores.AppendLine($"Empleado {Nombre} el importe debe de ser mayor a 0 importe {Importe}"); // importe mayot a 0 ErroresValidaciones = true; } } ErroresValidaciones = false; //LAYOUT “C” FORMATOS PARA IMPORTACIÓN (TEF / TEF INTELAR) //DOC: https://www.banamex.com/resources/bancanets/premium/esp/contenedor/archivos/TEF_Version_C_PagosCobros_Masivos.pdf if (!ErroresValidaciones) { DataRow RowCuenta = get_GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveCuenta: DdlCuenta.SelectedValue.ToEntero(), CveEmpresa: UsuarioActual.CveEmpresa).FiltroPrimero(""); var ClaveMoneda = "001"; // PESOS MEXICANOS //REGISTRO DE CONTROL - IMPORTACIÓN var TipoRegistro = "1"; var NumeroCliente = RowCuenta["ConvenioPagoElectronico"].ToString().Trim().PadLeft(12, '0'); //CONVENIO var Fecha = TxtModalLayoutBancosFecha.Text.ToDate(); var FechaPago = $"{Fecha.Day.ToString().PadLeft(2, '0')}{Fecha.ToString("MM")}{Fecha.Year.ToString().Replace("20", "")}"; var Secuencia = (1).ToString("0000"); var RazonSocial = (UsuarioActual.Empresa.Empresa).Replace("-Prueba", "").Trim().PadRight(36); var Descripcion = ("NOMINA").Trim().PadRight(20); var Naturaleza = "05"; //= 12 Pagos interbancarios CLABE, 05 Nomina banamex var Instrucciones = ("").Trim().PadRight(40); var Version = "C"; var Volumen = "0"; var Caracteristicas = "1"; // 0= Si es modificable, 1 = Solo lectura sb.AppendLine($"{TipoRegistro}{NumeroCliente}{FechaPago}{Secuencia}{RazonSocial}{Descripcion}{Naturaleza}{Instrucciones}{Version}{Volumen}{Caracteristicas}"); //REGISTRO GLOBAL - IMPORTACIÓN var TipoReg2 = "2"; var TipoOpe2 = "1"; //0 = Si es Abono, 1 = Si es Cargo var ImporteTotal = DTNomina.SUMD("Importe").ToString("0000000000000000.00").Replace(".", "");//16 enteros y 2 decimales var TipoCuenta = "01"; //CUENTA DE CHEQUES var Sucursal = RowCuenta["NumeroSucursal"].ToString(); var NumCuenta = RowCuenta["NumCuenta"].ToString().Trim().PadLeft(20, '0'); //OBTENER DE BANCOS CUENTAS var Espacio = ("").Trim().PadRight(20); sb.AppendLine($"{TipoReg2}{TipoOpe2}{ClaveMoneda}{ImporteTotal}{TipoCuenta}{Sucursal}{NumCuenta}{Espacio}"); //REGISTRO DE CARGOS O ABONOS INDIVIDUALES - IMPORTACIÓN int Count = 0; decimal SumaImportes = 0; foreach (DataRow dRow in DTNomina.Rows) { var TipoReg3 = "3"; //Registro de Movtos. Individuales var TipoOpe3 = "0"; //0 = Si es Abono, 1 = Si es Cargo (solo aplica para cobros) string Nombres = dRow["Nombres"].ToString().Replace("ñ,Ñ", "n").Replace("*,#,$,%,=,+", ""); string APaterno = dRow["APaterno"].ToString().Replace("ñ,Ñ", "n").Replace("*,#,$,%,=,+", ""); string AMaterno = dRow["AMaterno"].ToString().Replace("ñ,Ñ", "n").Replace("*,#,$,%,=,+", ""); //string BancoNumCuenta = dRow["BancoNumCuenta"].ToString(); string BancoNumCuenta = dRow["NumeroCuenta"].ToString(); decimal Importe = dRow["Importe"].ToString().ToDecimal().RoundSQL(2); var StrImporte = Importe.ToString("0000000000000000.00").Replace(".", ""); var StrTipoCuenta = "03";// 01- Cheques / CLABE, 03=Plástico var StrCuenta = BancoNumCuenta.Trim().PadLeft(20, '0'); //USARA TARJETA DE DEBITO var ReferenciaAlfa = (dRow["Codigo"].ToString()).PadRight(10); //si banamex debe ser de 10 digitos, y agregar 30 espacios var EspacioRefBen = ("").PadRight(30); var Beneficiario = ($"{Nombres},{APaterno}/{AMaterno}").PadRight(55); var Inst3 = ("PAGO").PadRight(40); var DescTEF = ("").PadRight(24); var ClaveBanco = ("0000").PadRight(4); //No se ocupa si es nomina banamex var ReferenciaNum = ("").PadRight(7, '0'); //QUE TOME DE LA CvePersonal como folio , SOLO PARA INTERBANCARIOS var Plazo = ""; // 00 - MISMO DIA , 24 HRS sb.AppendLine($"{TipoReg3}{TipoOpe3}{ClaveMoneda}{StrImporte}{StrTipoCuenta}{StrCuenta}{ReferenciaAlfa}{EspacioRefBen}{Beneficiario}{Inst3}{DescTEF}{ClaveBanco}{ReferenciaNum}{Plazo}00"); Count += 1; SumaImportes += Importe; } //REGISTRO DE TOTALES - IMPORTACIÓN var TipoReg4 = "4"; // LOS ABONOS A LOS EMPLEADOS var NumAbonos = Count.ToString("000000"); //EL CARGO QUE SE LE HIZO A LA CUENTA DE LA EMPRESA var NumCargos = (1).ToString("000000"); var StrImportes = SumaImportes.ToString("0000000000000000.00").Replace(".", ""); sb.Append($"{TipoReg4}{ClaveMoneda}{NumAbonos}{StrImportes}{NumCargos}{StrImportes}"); Response.Clear(); Response.ClearHeaders(); Response.AppendHeader("Content-Length", sb.ToString()); Response.ContentType = "text/plain"; //Response.AppendHeader("Content-Disposition", $"attachment;filename=\"Nomina{NowADS().ToString("yyyyMMddhhmmss").ToString()}.txt\""); Response.AppendHeader("Content-Disposition", $"attachment;filename=\"Nomina_Banamex_{DdlPeriodo.SelectedItem.Text}.txt\""); Response.Write(sb.ToString()); //RegistraScript("$('#ModalLayoutBancos').modal('hide');"); //Response.Flush(); Response.End(); } else Alert(SbErrores.ToString(), TipoMensaje.MsgAdvertencia); } #endregion protected void LnkBitacoraCorreo_Click(object sender, EventArgs e) { using (ClsRH objrh = new ClsRH()) { objrh.NomBitacoraCorreoGet(CvePeriodoSeleccionado, -1, UsuarioActual.CveEmpresa); GVViewCorreos.DataSource = objrh.DtResultados; GVViewCorreos.DataBind(); } UpviewCorreos.Update(); RegistraScript("$('#ModalViewCorreo').modal();"); } protected void LnkProcesarModal_Click(object sender, EventArgs e) { RegistraScript("$('#DmodalArchivoEBASUAPDFToExceL').modal();"); } protected void LnkProcesaPDFSUAEBA_Click(object sender, EventArgs e) { List Filesgral = TxtArchivoPDFSUAEBA.getfiles().Archivos; if (Filesgral.Count > 0) { string dirPDF = Filesgral[0].FileUrl; Boolean essua = false; using (iTextSharp.text.pdf.PdfReader readerx = new iTextSharp.text.pdf.PdfReader(dirPDF)) { if (readerx.NumberOfPages > 0) { string text = PdfTextExtractor.GetTextFromPage(readerx, 1); essua = text.Contains("SISTEMA ÚNICO DE AUTODETERMINACIÓN"); } } if (essua) { System.IO.Stream fs = (new CedulaSuaPDF()).writexls(dirPDF); 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", "SUA ")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } else { System.IO.Stream fs = (new CedulaEBAPDF()).writexls(dirPDF); 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", "EBA ")); Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } } } public class CedulaEBAPDF { public const string validaNSSptt = @"\d{2}\s\d{2}\s\d{2}\s\d{4}\s\d"; //^inicia//$termina // Regular expression pattern public const string ValidateCURPptt = @"[A-Z]{4}\d{6}[HM]{1}[A-Z]{5}[A-Z0-9]{2}";//^inicia//$termina public const string ValidateFechaptt = @"(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-\d{4}";//dd/MM/yyyy public const string Validatedigitptt = @"^[0-9\s.\t]*$";//digitos espacio y punto public int getindexpatch(string text, string pattern) { Match match = Regex.Match(text, pattern); return match.Success ? match.Index : -1; } public string getvaluepatch(string text, string pattern) { Match match = Regex.Match(text, pattern); return match.Success ? match.Value : null; } public System.IO.Stream writexls(string dirPDF) { cedulaEBA dataEBAPDF = readPDFcedulaEBA(dirPDF); ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("EBA DATA"); int row = 1; int column = 1; libro.Cell(row, column++).Value = "NSS"; libro.Cell(row, column++).Value = "CURP"; libro.Cell(row, column++).Value = "Nombre"; libro.Cell(row, column++).Value = "ORIGEN"; libro.Cell(row, column++).Value = "CLAVE"; libro.Cell(row, column++).Value = "FECHA"; libro.Cell(row, column++).Value = "DIAS"; libro.Cell(row, column++).Value = "SALARIO"; libro.Cell(row, column++).Value = "RETIRO"; libro.Cell(row, column++).Value = "CESANTIAPAT"; libro.Cell(row, column++).Value = "CESANTIAOBR"; libro.Cell(row, column++).Value = "SUMARCV"; libro.Cell(row, column++).Value = "APORTACION"; libro.Cell(row, column++).Value = " "; libro.Cell(row, column++).Value = "CUOTAFIJAOFD"; libro.Cell(row, column++).Value = "AMORTIZA"; libro.Cell(row, column++).Value = "SUMAINFONAVIT"; libro.Cell(row, column++).Value = "SUMA"; int maxxolumn = column; libro.Range(1, 1, row, column - 1).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(1, 1, row, column - 1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); row++; foreach (var empleado in dataEBAPDF.empleados) { column = 1; if (empleado.ldtos.Count > 0) { foreach (var data in empleado.ldtos) { column = 1; libro.Cell(row, column++).Value = string.Format("'{0}", empleado.NSS.Trim()); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Curp); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Nombre); if (!data.ORIGEN.Contains("Formato") && !data.ORIGEN.Contains("VERSION")) { libro.Cell(row, column++).Value = string.Format("{0}", data.ORIGEN); libro.Cell(row, column++).Value = string.Format("'{0}", data.CLAVE); libro.Cell(row, column++).Value = string.Format("'{0}", data.FECHA); libro.Cell(row, column++).Value = string.Format("{0}", data.DIAS);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.SALARIO);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.RETIRO);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.CESANTIAPAT);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.CESANTIAOBR);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.SUMARCV);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.APORTACION);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.CUOTAFIJAOFDSTR);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.CUOTAFIJAOFD);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.AMORTIZA);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.SUMAINFONAVIT);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); libro.Cell(row, column++).Value = string.Format("{0}", data.SUMA);//.Trim().Replace(",", "").Replace("$", "").ToDecimal()); } row++; } } else { libro.Cell(row, column++).Value = string.Format("'{0}", empleado.NSS.Trim()); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Curp); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Nombre); row++; } } libro.Range(2, 7, row, 13).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Right; libro.Range(2, 15, row, maxxolumn - 1).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Right; libro.Range(2, 7, row, 13).Style.NumberFormat.Format = "$ #,##0.00"; libro.Range(2, 15, row, maxxolumn - 1).Style.NumberFormat.Format = "$ #,##0.00"; libro.Columns().AdjustToContents(); libro.Range(2, 1, row, maxxolumn - 1).SetAutoFilter(); //wb.SaveAs(string.Format("{0}xlsx", dirPDF.Substring(0, dirPDF.Length - 3))); System.IO.Stream fs = new System.IO.MemoryStream(); wb.SaveAs(fs); return fs; } public cedulaEBA readPDFcedulaEBA(string dirPDF) { cedulaEBA objEBA = new cedulaEBA(); StringBuilder strb = new StringBuilder(); using (iTextSharp.text.pdf.PdfReader readerx = new iTextSharp.text.pdf.PdfReader(dirPDF)) { for (int page = 1; page <= readerx.NumberOfPages; page++) { string text = PdfTextExtractor.GetTextFromPage(readerx, page); string[] lines = text.Split('\n'); cedulaEBAEmpleados cempleado = null; int pasoCaptura = 0; bool esiniciodepagina = false; foreach (string line in lines) { strb.AppendLine(line); bool espaso1 = Regex.IsMatch(line, ValidateCURPptt); bool espaso2 = Regex.IsMatch(line, validaNSSptt); if (esiniciodepagina) { if (objEBA.empleados.Count > 0 && !espaso2 && !espaso1) { cempleado = objEBA.empleados[objEBA.empleados.Count - 1]; objEBA.empleados.RemoveAt(objEBA.empleados.Count - 1); pasoCaptura = 2; } esiniciodepagina = false; } if (pasoCaptura == 0 && line.Contains("FIJA O FD")) { esiniciodepagina = true; } if (!espaso2 && !espaso1 && pasoCaptura == 2) { pasoCaptura = 2; procesapaso2(line, cempleado); } if (espaso2) { //isTitulo = false; if (!(pasoCaptura == 1)) { if (null != cempleado) { objEBA.empleados.Add(cempleado); } cempleado = new cedulaEBAEmpleados(); } pasoCaptura = 2; if (espaso1) { cempleado.Curp = getvaluepatch(line, ValidateCURPptt); } cempleado.NSS = getvaluepatch(line, validaNSSptt); cempleado.Nombre = line.Replace(cempleado.NSS, "").Trim(); if (cempleado.Curp != null) { cempleado.Nombre = cempleado.Nombre.Replace(cempleado.Curp, "").Trim(); } } if (pasoCaptura == 1) { pasoCaptura = 2; procesapaso2(line, cempleado); } if (espaso1 && !espaso2) { //isTitulo = false; pasoCaptura = 1; if (null != cempleado) { objEBA.empleados.Add(cempleado); } cempleado = new cedulaEBAEmpleados(); cempleado.Curp = getvaluepatch(line, ValidateCURPptt); } //Console.WriteLine(line); } if (null != cempleado) { objEBA.empleados.Add(cempleado); } cempleado = null; strb.AppendLine("/*NEWPAGE*/"); } } return objEBA; } public cedulaEBAEmpleados procesapaso2(string line, cedulaEBAEmpleados empleado) { if (line.ToUpper().Contains("Página".ToUpper())) { } else { bool contienefecha = Regex.IsMatch(line, ValidateFechaptt); string[] splitedline = line.Split(' '); int l = splitedline.Length; cedulaEBAEmpleadosdatos dtos = null; cedulaEBAEmpleadosdatos dtosant = null; if (empleado.ldtos.Count > 0) { dtosant = empleado.ldtos[empleado.ldtos.Count - 1]; if (dtosant.CESANTIAPAT != null && !(dtosant.CUOTAFIJAOFD != null && (dtosant.CUOTAFIJAOFD.Contains("CF") || dtosant.CUOTAFIJAOFD.Contains("FD") || dtosant.CUOTAFIJAOFD.Contains("%")) ) ) { dtosant = null; } } int col = 0; if (dtosant == null || l > 6) { dtos = new cedulaEBAEmpleadosdatos(); if (col < l) { dtos.ORIGEN = splitedline[col++]; } if (contienefecha && col < l) { dtos.CLAVE = splitedline[col++]; } if (contienefecha && col < l) { dtos.FECHA = splitedline[col++]; } if (col < l) { dtos.DIAS = splitedline[col++]; } if (col < l) { dtos.SALARIO = splitedline[col++]; } if (col < l) { dtos.RETIRO = splitedline[col++]; } if (col < l) { dtos.SUMARCV = splitedline[col++]; } if (col < l) { dtos.APORTACION = splitedline[col++]; } if ((col + 3) < l) { dtos.CUOTAFIJAOFD = splitedline[col++].Trim(); if (dtos.CUOTAFIJAOFD.Contains("CF") || dtos.CUOTAFIJAOFD.Contains("FD") || dtos.CUOTAFIJAOFD.Contains("%")) { dtos.CUOTAFIJAOFDSTR = dtos.CUOTAFIJAOFD; if ((col + 3) < l) { dtos.CUOTAFIJAOFD = splitedline[col++].Trim(); } } } if (col < l) { dtos.AMORTIZA = splitedline[col++]; } if (col < l) { dtos.SUMAINFONAVIT = splitedline[col++]; } if (col < l) { dtos.SUMA = splitedline[col++]; } } else { empleado.ldtos.RemoveAt(empleado.ldtos.Count - 1); dtos = dtosant; if (dtosant.CESANTIAPAT != null) { if (col < l) { dtos.CUOTAFIJAOFD = splitedline[col++]; } else { dtos.CUOTAFIJAOFD = ""; } } else { if (col < l) { dtos.CESANTIAPAT = splitedline[col++]; } if (col < l) { dtos.CESANTIAOBR = splitedline[col++]; } } } empleado.ldtos.Add(dtos); } return empleado; } } public class cedulaEBA { public cedulaEBA() { empleados = new List(); } public string txtTitulo { get; set; } public string txtTodo { get; set; } public List empleados { get; set; } } public class cedulaEBAEmpleados { public cedulaEBAEmpleados() { ldtos = new List(); } public string NSS { get; set; } public string Nombre { get; set; } public string Curp { get; set; } public string centrocostos { get; set; } public List ldtos { get; set; } } public class cedulaEBAEmpleadosdatos { public string ORIGEN { get; set; } public string CLAVE { get; set; } public string FECHA { get; set; } public string DIAS { get; set; } public string SALARIO { get; set; } public string RETIRO { get; set; } public string SUMARCV { get; set; } public string APORTACION { get; set; } public string CUOTAFIJAOFD { get; set; } public string CUOTAFIJAOFDSTR { get; set; } public string AMORTIZA { get; set; } public string SUMAINFONAVIT { get; set; } public string SUMA { get; set; } public string CESANTIAPAT { get; set; } public string CESANTIAOBR { get; set; } } public class CedulaSuaPDF { public const string validaNSSptt = @"\d{2}-\d{2}-\d{2}-\d{4}-\d"; //^inicia//$termina // Regular expression pattern public const string ValidateCURPptt = @"[A-Z]{4}\d{6}[HM]{1}[A-Z]{5}[A-Z0-9]{2}";//^inicia//$termina public const string ValidateFechaptt = @"(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/\d{4}";//dd/MM/yyyy public const string Validatedigitptt = @"^[0-9\s.,\t]*$";//digitos espacio y punto public int getindexpatch(string text, string pattern) { Match match = Regex.Match(text, pattern); return match.Success ? match.Index : -1; } public string getvaluepatch(string text, string pattern) { Match match = Regex.Match(text, pattern); return match.Success ? match.Value : null; } public System.IO.Stream writexls(string dirPDF) { cedulaSUA dataEBAPDF = readPDFcedulaSUA(dirPDF); ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(); var libro = wb.AddWorksheet("EBA DATA"); int row = 2; int column = 1; libro.Cell(row, column++).Value = "NSS"; libro.Cell(row, column++).Value = "CURP"; libro.Cell(row, column++).Value = "Nombre"; libro.Cell(row, column++).Value = "Ubicación".ToUpper(); libro.Cell(row, column++).Value = "CLAVE"; libro.Cell(row, column++).Value = "FECHA"; libro.Cell(row, column++).Value = "DIAS"; libro.Cell(row, column++).Value = "SALARIO"; if (dataEBAPDF.ContieneLic) { libro.Cell(row, column++).Value = "LIC"; } libro.Cell(row, column++).Value = "INCAPACIDAD"; libro.Cell(row, column++).Value = "AUSENTISMO"; libro.Cell(row, column++).Value = "RETIRO"; libro.Range(1, column, 1, column + 2).Merge().Value = "Cesantía y Vejez".ToUpper(); libro.Cell(row, column++).Value = "PATRONAL"; libro.Cell(row, column++).Value = "OBRERA"; libro.Cell(row, column++).Value = "SUMA"; libro.Cell(row, column++).Value = "Aportación Patronal".ToUpper(); libro.Cell(row, column++).Value = "% o $ o FD"; libro.Cell(row, column++).Value = "% o $ o FD"; libro.Range(row, column - 2, row, column).Value = "% o $ o FD"; libro.Cell(row, column++).Value = "Amortización"; libro.Cell(row, column++).Value = "SUMA"; libro.Cell(row, column++).Value = "Créd. Vivienda".ToUpper(); libro.Cell(row, column++).Value = "Tipo Movto. de Crédito".ToUpper(); libro.Cell(row, column++).Value = "Fecha de Movto. de Crédito".ToUpper(); int maxxolumn = column; libro.Range(1, 1, row, column - 1).Style.Font.FontColor = ClosedXML.Excel.XLColor.White; libro.Range(1, 1, row, column - 1).Style.Fill.SetBackgroundColor(ClosedXML.Excel.XLColor.FromArgb(79, 129, 189)); row++; foreach (var empleado in dataEBAPDF.empleados) { column = 1; if (empleado.ldtos.Count > 0) { foreach (var data in empleado.ldtos) { column = 1; libro.Cell(row, column++).Value = string.Format("'{0}", empleado.NSS.Trim()); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Curp); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Nombre); libro.Cell(row, column++).Value = string.Format("{0}", empleado.centrocostos); libro.Cell(row, column++).Value = string.Format("'{0}", data.Clave); libro.Cell(row, column++).Value = string.Format("'{0}", data.Fecha); libro.Cell(row, column++).Value = string.Format("{0}", data.Dias); libro.Cell(row, column++).Value = string.Format("{0}", data.SDI); if (dataEBAPDF.ContieneLic) { libro.Cell(row, column++).Value = string.Format("{0}", data.Lic); } libro.Cell(row, column++).Value = string.Format("{0}", data.Inc); libro.Cell(row, column++).Value = string.Format("{0}", data.Aus); libro.Cell(row, column++).Value = string.Format("{0}", data.Retiro); libro.Cell(row, column++).Value = string.Format("{0}", data.Patronal); libro.Cell(row, column++).Value = string.Format("{0}", data.Obrera); libro.Cell(row, column++).Value = string.Format("{0}", data.Suma); libro.Cell(row, column++).Value = string.Format("{0}", data.AportacionPatronal); libro.Cell(row, column++).Value = string.Format("{0}", data.FD); libro.Cell(row, column++).Value = string.Format("{0}", data.FDimporte); libro.Cell(row, column++).Value = string.Format("{0}", data.Amortización); libro.Cell(row, column++).Value = string.Format("{0}", data.SumaB); libro.Cell(row, column++).Value = string.Format("'{0}", data.CredVivienda); libro.Cell(row, column++).Value = string.Format("{0}", data.tipodecredito); libro.Cell(row, column++).Value = string.Format("'{0}", data.fechamovto); row++; } } else { libro.Cell(row, column++).Value = string.Format("'{0}", empleado.NSS.Trim()); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Curp); libro.Cell(row, column++).Value = string.Format("{0}", empleado.Nombre); libro.Cell(row, column++).Value = string.Format("{0}", empleado.centrocostos); row++; } } libro.Range(2, 7, row, dataEBAPDF.ContieneLic ? 15 : 16).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Right; libro.Range(2, dataEBAPDF.ContieneLic ? 17 : 18, row, dataEBAPDF.ContieneLic ? 20 : 21).Style.Alignment.Horizontal = ClosedXML.Excel.XLAlignmentHorizontalValues.Right; //libro.Range(2, 7, row, 15).Style.NumberFormat.Format = "$ #,##0.00"; //libro.Range(2, 17, row, 20).Style.NumberFormat.Format = "$ #,##0.00"; libro.Columns().AdjustToContents(); libro.Range(2, 1, row, maxxolumn - 1).SetAutoFilter(); //wb.SaveAs(string.Format("{0}xlsx", dirPDF.Substring(0, dirPDF.Length - 3))); System.IO.Stream fs = new System.IO.MemoryStream(); wb.SaveAs(fs); return fs; } public cedulaSUA readPDFcedulaSUA(string dirPDF) { cedulaSUA objSUA = new cedulaSUA(); StringBuilder strb = new StringBuilder(); StringBuilder strtitulo = new StringBuilder(); bool isTitulo = true; using (iTextSharp.text.pdf.PdfReader readerx = new iTextSharp.text.pdf.PdfReader(dirPDF)) { for (int page = 1; page <= readerx.NumberOfPages; page++) { string text = PdfTextExtractor.GetTextFromPage(readerx, page); if (!isTitulo) { text = text.Replace(strtitulo.ToString(), ""); } cedulaSUAEmpleados cempleado = null; string[] lines = text.Split('\n'); int pasoCaptura = 0; foreach (string line in lines) { strb.AppendLine(line); bool espaso1 = Regex.IsMatch(line, validaNSSptt); if (!espaso1 && pasoCaptura == 4) { procesapaso4(line, cempleado, objSUA.ContieneLic); } if (!espaso1 && pasoCaptura == 3) { if (Regex.IsMatch(line, ValidateFechaptt) || Regex.IsMatch(line, Validatedigitptt)) { procesapaso4(line, cempleado, objSUA.ContieneLic); pasoCaptura = 4; } else { cempleado.centrocostos = line; pasoCaptura = 4; } } if (!espaso1 && pasoCaptura == 1) { if (Regex.IsMatch(line, ValidateFechaptt) || Regex.IsMatch(line, Validatedigitptt)) { procesapaso4(line, cempleado, objSUA.ContieneLic); pasoCaptura = 4; } else { if (Regex.IsMatch(line, ValidateCURPptt)) { cempleado.Curp = getvaluepatch(line, ValidateCURPptt); cempleado.centrocostos = line.Replace(cempleado.Curp, "").Trim(); pasoCaptura = cempleado.centrocostos.Length > 0 ? 4 : 3; } else { cempleado.centrocostos = line; pasoCaptura = 4; } } } if (espaso1) { isTitulo = false; pasoCaptura = 1; if (null != cempleado) { objSUA.empleados.Add(cempleado); } cempleado = new cedulaSUAEmpleados(); cempleado.NSS = getvaluepatch(line, validaNSSptt); string[] linesplited = line.Replace(cempleado.NSS, "").Trim().Split(' '); if (linesplited.Length > 2) { cempleado.Curp = linesplited[linesplited.Length - 1]; } //cempleado.Curp = getvaluepatch(line, ValidateCURPptt); string NombreCompleto; if (cempleado.Curp != null) { cempleado.Nombre = line.Replace(cempleado.NSS, "").Replace(cempleado.Curp, "").Trim(); //cempleado.Nombre = line.Substring(getindexpatch(line, validaNSSptt) + 15).Substring(0, getindexpatch(line, ValidateCURPptt) - 18).Trim(); //cempleado.centrocostos = line.Substring(getindexpatch(line, ValidateCURPptt) + 18); pasoCaptura = 3;// cempleado.centrocostos.Length > 0 ? 4 : 3; } else { NombreCompleto = line.Replace(cempleado.NSS, "").Trim(); } //string[] splitline = line.Split(nss); } if (isTitulo) { if (line.Contains("Clave Fecha Días SDI ") && line.Contains(" Lic. ")) { objSUA.ContieneLic = true; } strtitulo.AppendLine(line); } //Console.WriteLine(line); } if (null != cempleado) { objSUA.empleados.Add(cempleado); } cempleado = null; strb.AppendLine("/*NEWPAGE*/"); } } objSUA.txtTodo = strb.ToString(); return objSUA; } public cedulaSUAEmpleados procesapaso4(string line, cedulaSUAEmpleados empleado, bool ContieneLic) { if (line.ToUpper().Contains("Página".ToUpper())) { } else { bool contienefecha; if (line.Length > 20) { contienefecha = Regex.IsMatch(line.Substring(0, 20), ValidateFechaptt); } else { contienefecha = Regex.IsMatch(line, ValidateFechaptt); } string[] splitedline = line.Split(' '); int l = splitedline.Length; bool ismsfsd = (line.ToUpper().Contains("M/S".ToUpper()) && line.ToUpper().Contains("FSD".ToUpper()) && l < 6); cedulaSUAEmpleadosdatos dtos = null; cedulaSUAEmpleadosdatos dtosant = null; if (empleado.ldtos.Count > 0) { dtosant = empleado.ldtos[empleado.ldtos.Count - 1]; } if (dtosant == null || (contienefecha && !(dtosant != null && dtosant.Dias == null))) { dtos = new cedulaSUAEmpleadosdatos(); } else { empleado.ldtos.RemoveAt(empleado.ldtos.Count - 1); dtos = dtosant; } int col = 0; if (contienefecha && col < l) { dtos.Clave = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (contienefecha && col < l) { dtos.Fecha = splitedline[col++]; } if (dtos.Clave != null && dtos.Clave.Contains("FSD")) { dtos.tipodecredito = dtos.Clave; dtos.Clave = ""; dtos.fechamovto = dtos.Fecha; dtos.Fecha = ""; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { if (splitedline[col].Length > 8) { dtos.tipodecredito = dtos.CredVivienda; dtos.CredVivienda = splitedline[col++]; } else { dtos.Dias = splitedline[col++]; } } if (col < l && !ismsfsd) { dtos.SDI = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (ContieneLic && col < l && !ismsfsd) { dtos.Lic = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.Inc = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.Aus = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.Retiro = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.Patronal = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.Obrera = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.Suma = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.AportacionPatronal = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd && (col + 3) < l) { dtos.FD = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd && (col + 2) < l) { dtos.FDimporte = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.Amortización = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.SumaB = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l && !ismsfsd) { dtos.CredVivienda = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l) { dtos.tipodecredito = splitedline[col++]; } if (col < l && splitedline[col] == "") { col++; } if (col < l) { dtos.fechamovto = splitedline[col++]; } empleado.ldtos.Add(dtos); } return empleado; } } public class cedulaSUA { public cedulaSUA() { empleados = new List(); } public string txtTitulo { get; set; } public string txtTodo { get; set; } public bool ContieneLic { get; set; } public List empleados { get; set; } } public class cedulaSUAEmpleados { public cedulaSUAEmpleados() { ldtos = new List(); } public string NSS { get; set; } public string Nombre { get; set; } public string Curp { get; set; } public string centrocostos { get; set; } public List ldtos { get; set; } } public class cedulaSUAEmpleadosdatos { public string Clave { get; set; } public string Fecha { get; set; } public string Dias { get; set; } public string SDI { get; set; } public string Lic { get; set; } public string Inc { get; set; } public string Aus { get; set; } public string Retiro { get; set; } public string Patronal { get; set; } public string Obrera { get; set; } public string Suma { get; set; } public string AportacionPatronal { get; set; } public string FD { get; set; } public string FDimporte { get; set; } public string Amortización { get; set; } public string SumaB { get; set; } public string CredVivienda { get; set; } public string tipodecredito { get; set; } public string fechamovto { get; set; } } protected void LnkCargaMasiva_Click(object sender, EventArgs e) { int ejercicio = DdlEjercicioCM.SelectedValue.ToEntero(); int cveTipoPeriodo = DdlTipoPeriodoCMB.SelectedValue.ToEntero(); int cveSubTipoPeriodo = TxtCveSubTipoPeriodoCM.Text.ToEntero(); int numero = TxtNumeroCM.Text.ToEntero(); string fechaInicio = TxtFechaInicioCM.Text.ToDateTime().ToString("yyyy-MM-dd"); using (ClsNominas onom = new ClsNominas()) { if (onom.CargaPeriodosEjercicio(ejercicio, cveTipoPeriodo, cveSubTipoPeriodo, numero, fechaInicio, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario)) { Alert("Se cargo satisfactoriamente."); RegistraScript(string.Format("$('#divCargaMasiva').modal('hide');")); cargaPeriodos(); } } } //cargarGrid private DataTable GetTablaColumnas() { DataTable dtColumnas = new DataTable(); dtColumnas.Columns.Add("Columna"); dtColumnas.Columns.Add("ColumnaDB"); //Campos Fijos { { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Clave Personal"; dtcampos["ColumnaDB"] = "CvePersonal"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Código"; dtcampos["ColumnaDB"] = "Codigo"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Nombre"; dtcampos["ColumnaDB"] = "Nombre"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Clave SubProyecto"; dtcampos["ColumnaDB"] = "CveSubProyecto"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "SubProyecto"; dtcampos["ColumnaDB"] = "SubProyecto"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Deducciones"; dtcampos["ColumnaDB"] = "SumaDeducciones"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Especie"; dtcampos["ColumnaDB"] = "SumaEspecie"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Percepciones"; dtcampos["ColumnaDB"] = "SumaPercepciones"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Fecha Ingreso"; dtcampos["ColumnaDB"] = "FechaIngreso"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Salario Diario Integrado"; dtcampos["ColumnaDB"] = "SalarioDiarioIntegrado"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Salario Diario IMSS"; dtcampos["ColumnaDB"] = "SalarioDiarioIMSS"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Salario Diario"; dtcampos["ColumnaDB"] = "SalarioDiario"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Clave Departamento"; dtcampos["ColumnaDB"] = "CveDepartamento"; dtColumnas.Rows.Add(dtcampos); } { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = "Departamento"; dtcampos["ColumnaDB"] = "Departamento"; dtColumnas.Rows.Add(dtcampos); } } //Conceptos if (dtConceptos != null && dtConceptos.Rows.Count > 0) { foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('P') AND EsPadre = 1 ").Rows) { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = string.Format("P - {0} {1}", row["Codigo"], row["Concepto"]); dtcampos["ColumnaDB"] = string.Format("V_{0}", row["CveConcepto"]); dtColumnas.Rows.Add(dtcampos); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('D') AND EsPadre = 1 ").Rows) { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = string.Format("D - {0} {1}", row["Codigo"], row["Concepto"]); dtcampos["ColumnaDB"] = string.Format("V_{0}", row["CveConcepto"]); dtColumnas.Rows.Add(dtcampos); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('O') AND EsPadre = 1 ").Rows) { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = string.Format("O - {0} {1}", row["Codigo"], row["Concepto"]); dtcampos["ColumnaDB"] = string.Format("V_{0}", row["CveConcepto"]); dtColumnas.Rows.Add(dtcampos); } } return dtColumnas; } protected void LnkMostrarOrdenadores_Click(object sender, EventArgs e) { GvOrdenEmpleados.DataSource = DtNomOrden; GvOrdenEmpleados.DataBind(); DataTable dtColumnas = GetTablaColumnas(); DdlOrdenColumna.DataSource = dtColumnas; DdlOrdenColumna.DataBind(); upModalOrdenEmpleados.Update(); RegistraScript(string.Format("$('#divdOrdenempleados').modal();")); } protected void LnkAgregarOrden_Click(object sender, EventArgs e) { { DataRow drorden = DtNomOrden.NewRow(); drorden["Columna"] = DdlOrdenColumna.SelectedItem.Text; drorden["Tipo"] = DDlOrdenTipo.SelectedItem.Text; drorden["ColumnaDB"] = DdlOrdenColumna.SelectedItem.Value; drorden["TipoDB"] = DDlOrdenTipo.SelectedItem.Value; DtNomOrden.Rows.Add(drorden); } GvOrdenEmpleados.DataSource = DtNomOrden; GvOrdenEmpleados.DataBind(); upModalOrdenEmpleados.Update(); } //divdOrdenempleados protected void LnkEliminarOrden_Click(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)((LinkButton)sender).NamingContainer; string ColumnaDB = gvRow.DataKey("ColumnaDB"); string TipoDB = gvRow.DataKey("TipoDB"); DataRow dr = null; foreach (DataRow item in DtNomOrden.Rows) { if (item["ColumnaDB"].ToString() == ColumnaDB && item["TipoDB"].ToString() == TipoDB) { dr = item; } } if (dr != null) { dr.Delete(); DtNomOrden.AcceptChanges(); } GvOrdenEmpleados.DataSource = DtNomOrden; GvOrdenEmpleados.DataBind(); upModalOrdenEmpleados.Update(); } protected void LnkReordenaGridEmpleados_Click(object sender, EventArgs e) { RegistraScript(string.Format("$('#divdOrdenempleados').modal('hide');")); setGVNominas(); UpDatos.Update(); } private DataTable GetTablaColumnasConceptos() { DataTable dtColumnas = new DataTable(); dtColumnas.Columns.Add("Columna"); dtColumnas.Columns.Add("ColumnaDB"); //Campos Fijos //{ // { // DataRow dtcampos = dtColumnas.NewRow(); // dtcampos["Columna"] = "Percepciones"; // dtcampos["ColumnaDB"] = "SumaPercepciones"; // dtColumnas.Rows.Add(dtcampos); // } // { // DataRow dtcampos = dtColumnas.NewRow(); // dtcampos["Columna"] = "Deducciones"; // dtcampos["ColumnaDB"] = "SumaDeducciones"; // dtColumnas.Rows.Add(dtcampos); // } // { // DataRow dtcampos = dtColumnas.NewRow(); // dtcampos["Columna"] = "Especie"; // dtcampos["ColumnaDB"] = "SumaEspecie"; // dtColumnas.Rows.Add(dtcampos); // } //} //Conceptos if (dtConceptos != null && dtConceptos.Rows.Count > 0) { foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('P') AND EsPadre = 1 ").Rows) { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = string.Format("P - {0} {1}", row["Codigo"], row["Concepto"]); dtcampos["ColumnaDB"] = string.Format("V_{0}", row["CveConcepto"]); dtColumnas.Rows.Add(dtcampos); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('D') AND EsPadre = 1 ").Rows) { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = string.Format("D - {0} {1}", row["Codigo"], row["Concepto"]); dtcampos["ColumnaDB"] = string.Format("V_{0}", row["CveConcepto"]); dtColumnas.Rows.Add(dtcampos); } foreach (DataRow row in dtConceptos.FiltraParametros("Tipo IN ('O') AND EsPadre = 1 ").Rows) { DataRow dtcampos = dtColumnas.NewRow(); dtcampos["Columna"] = string.Format("O - {0} {1}", row["Codigo"], row["Concepto"]); dtcampos["ColumnaDB"] = string.Format("V_{0}", row["CveConcepto"]); dtColumnas.Rows.Add(dtcampos); } } return dtColumnas; } protected void LnkMostrarOcultarMostrar_Click(object sender, EventArgs e) { GvOrdenEmpleados.DataSource = DtNomOcultarMostrar; GvOrdenEmpleados.DataBind(); DataTable dtColumnas = GetTablaColumnasConceptos(); DdlMOColumna.DataSource = dtColumnas; DdlMOColumna.DataBind(); UpMostrarOcultarConceptos.Update(); RegistraScript(string.Format("$('#divdMostrarOcultarConceptos').modal();")); // } protected void LnkMoAgregar_Click(object sender, EventArgs e) { { DataRow drorden = DtNomOcultarMostrar.NewRow(); drorden["Columna"] = DdlMOColumna.SelectedItem.Text; drorden["Tipo"] = DdlMOTipo.SelectedItem.Text; drorden["ColumnaDB"] = DdlMOColumna.SelectedItem.Value; drorden["TipoDB"] = DdlMOTipo.SelectedItem.Value; DtNomOcultarMostrar.Rows.Add(drorden); } GVShowHideCol.DataSource = DtNomOcultarMostrar; GVShowHideCol.DataBind(); UpMostrarOcultarConceptos.Update(); } protected void LnkEliminarShowHide_Click(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)((LinkButton)sender).NamingContainer; string ColumnaDB = gvRow.DataKey("ColumnaDB"); string TipoDB = gvRow.DataKey("TipoDB"); DataRow dr = null; foreach (DataRow item in DtNomOcultarMostrar.Rows) { if (item["ColumnaDB"].ToString() == ColumnaDB && item["TipoDB"].ToString() == TipoDB) { dr = item; } } if (dr != null) { dr.Delete(); DtNomOcultarMostrar.AcceptChanges(); } GVShowHideCol.DataSource = DtNomOcultarMostrar; GVShowHideCol.DataBind(); UpMostrarOcultarConceptos.Update(); } protected void LnkReShowHide_Click(object sender, EventArgs e) { RegistraScript(string.Format("$('#divdMostrarOcultarConceptos').modal('hide');")); cargarGrid(); UpDatos.Update(); } protected void ddltipoPersonalizar_SelectedIndexChanged(object sender, EventArgs e) { } }