public ActionResult Create([Bind(Include = "emp_Id,Nombres,per_Identidad,per_Sexo,per_Edad,per_Direccion,per_Telefono,per_CorreoElectronico,per_EstadoCivil,salarioBase,tmon_Id,tmon_Descripcion,cpla_IdPlanilla,cpla_DescripcionPlanilla")] V_PreviewPlanilla v_PreviewPlanilla) { if (ModelState.IsValid) { db.V_PreviewPlanilla.Add(v_PreviewPlanilla); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(v_PreviewPlanilla)); }
public ActionResult Create([Bind(Include = "isr_Id,isr_RangoInicial,isr_RangoFinal,isr_Porcentaje,tde_IdTipoDedu,isr_UsuarioCrea,isr_FechaCrea,isr_UsuarioModifica,isr_FechaModifica,isr_Activo")] tbISR tbISR) { if (ModelState.IsValid) { db.tbISR.Add(tbISR); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.isr_UsuarioCrea = new SelectList(db.tbUsuario, "usu_Id", "usu_NombreUsuario", tbISR.isr_UsuarioCrea); ViewBag.isr_UsuarioModifica = new SelectList(db.tbUsuario, "usu_Id", "usu_NombreUsuario", tbISR.isr_UsuarioModifica); ViewBag.tde_IdTipoDedu = new SelectList(db.tbTipoDeduccion, "tde_IdTipoDedu", "tde_Descripcion", tbISR.tde_IdTipoDedu); return(View(tbISR)); }
public ActionResult Create([Bind(Include = "emp_Id,per_Id,car_Id,area_Id,depto_Id,jor_Id,cpla_IdPlanilla,fpa_IdFormaPago,emp_CuentaBancaria,emp_Reingreso,emp_Fechaingreso,emp_RazonSalida,emp_CargoAnterior,emp_FechaDeSalida,emp_Estado,emp_RazonInactivo,emp_UsuarioCrea,emp_FechaCrea,emp_UsuarioModifica,emp_FechaModifica")] tbEmpleados tbEmpleados) { if (ModelState.IsValid) { db.tbEmpleados.Add(tbEmpleados); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.emp_UsuarioCrea = new SelectList(db.tbUsuario, "usu_Id", "usu_NombreUsuario", tbEmpleados.emp_UsuarioCrea); ViewBag.emp_UsuarioModifica = new SelectList(db.tbUsuario, "usu_Id", "usu_NombreUsuario", tbEmpleados.emp_UsuarioModifica); ViewBag.area_Id = new SelectList(db.tbAreas, "area_Id", "area_Descripcion", tbEmpleados.area_Id); ViewBag.car_Id = new SelectList(db.tbCargos, "car_Id", "car_Descripcion", tbEmpleados.car_Id); ViewBag.per_Id = new SelectList(db.tbPersonas, "per_Id", "per_Identidad", tbEmpleados.per_Id); return(View(tbEmpleados)); }
public ActionResult DeleteConfirmed(int id) { tbEmpleadoBonos tbEmpleadoBonos = db.tbEmpleadoBonos.Find(id); db.tbEmpleadoBonos.Remove(tbEmpleadoBonos); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { tbCatalogoDeIngresos tbCatalogoDeIngresos = db.tbCatalogoDeIngresos.Find(id); db.tbCatalogoDeIngresos.Remove(tbCatalogoDeIngresos); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { tbTechosDeducciones tbTechosDeducciones = db.tbTechosDeducciones.Find(id); db.tbTechosDeducciones.Remove(tbTechosDeducciones); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(byte id) { tbTipoIdentificacion tbTipoIdentificacion = db.tbTipoIdentificacion.Find(id); db.tbTipoIdentificacion.Remove(tbTipoIdentificacion); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { tbSolicitudCredito tbSolicitudCredito = db.tbSolicitudCredito.Find(id); db.tbSolicitudCredito.Remove(tbSolicitudCredito); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { tbPagosArqueo tbPagosArqueo = db.tbPagosArqueo.Find(id); db.tbPagosArqueo.Remove(tbPagosArqueo); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { tbDeduccionesExtraordinarias tbDeduccionesExtraordinarias = db.tbDeduccionesExtraordinarias.Find(id); db.tbDeduccionesExtraordinarias.Remove(tbDeduccionesExtraordinarias); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult DeleteConfirmed(int id) { try { db = new ERP_GMEDINAEntities(); tbHistorialAmonestaciones tbHistorialAmonestaciones = db.tbHistorialAmonestaciones.Find(id); db.tbHistorialAmonestaciones.Remove(tbHistorialAmonestaciones); db.SaveChanges(); } catch { } return(RedirectToAction("Index")); }
public JsonResult InsertDecimoTercerMes(List <tbDecimoTercerMes> DecimoTercer) { if (DecimoTercer != null) { using (var dbContextTransaction = db.Database.BeginTransaction()) { try { IEnumerable <object> list = null; string MessageError = ""; //se construyen los lotes dependiendo de la cantidad de registros que reciba el controlador if (DecimoTercer.Count == 0) { return(Json("No hay registros en el objeto", JsonRequestBehavior.AllowGet)); } int CantidadRegistros = DecimoTercer.Count; //Declaración y validación del Número de lotes int NúmeroLotes = (CantidadRegistros <= 1) ? 1 : (CantidadRegistros <= 10) ? 5 : (CantidadRegistros <= 50) ? 10 : (CantidadRegistros <= 100) ? 20 : (CantidadRegistros <= 500) ? 50 : (CantidadRegistros > 500 || CantidadRegistros <= 1000) ? 100 : 0; int i = 0; //Ciclo para insertar los registros. foreach (tbDecimoTercerMes DC in DecimoTercer) { i++; list = db.UDP_Plani_tbDecimoTercerMes_Insert(DC.emp_Id, DC.dtm_Monto); //RECORRER EL TIPO COMPLEJO DEL PROCEDIMIENTO ALMACENADO PARA EVALUAR EL RESULTADO DEL SP foreach (UDP_Plani_tbDecimoTercerMes_Insert_Result resultado in list) { MessageError = Convert.ToString(resultado); } if (MessageError.StartsWith("-1")) { return(Json("-1", JsonRequestBehavior.AllowGet)); } if (i % NúmeroLotes == 0) { db.SaveChanges(); } } dbContextTransaction.Commit(); } catch { try { dbContextTransaction.Rollback(); } catch (System.Data.Entity.Core.EntityException) { return(Json("-1", JsonRequestBehavior.AllowGet)); } return(Json("-1", JsonRequestBehavior.AllowGet)); } } int RegistrosInsertados = db.SaveChanges(); return(Json(RegistrosInsertados)); } else { return(Json("-1", JsonRequestBehavior.AllowGet)); } }
public ActionResult _CargaDocumento(HttpPostedFileBase archivoexcel, string cboINFS, string cboIdDeduccion) { string response = String.Empty; string MensajeError = ""; //Verificacion del objetto recibido (archivo excel), si esta vacio retornara un error, de lo contrario continuara con el proceso. if (archivoexcel != null && archivoexcel.ContentLength > 0) { //Guardado del archivo en el servidor string path = Path.Combine(Server.MapPath("~/Content/PlanillasInstitucionesFinancieras"), Path.GetFileName(archivoexcel.FileName)); archivoexcel.SaveAs(path); try { List <int> idsDeducciones = db.tbCatalogoDeDeducciones.Where(x => x.cde_Activo == true).Select(x => x.cde_IdDeducciones).ToList(); List <int> idsINFS = db.tbInstitucionesFinancieras.Where(x => x.insf_Activo == true).Select(x => x.insf_IdInstitucionFinanciera).ToList(); int idCatDeduc = Convert.ToInt16(cboIdDeduccion); int IdInsF = Convert.ToInt16(cboINFS); if (!idsDeducciones.Contains(idCatDeduc)) { response = "error"; } else if (!idsDeducciones.Contains(IdInsF)) { response = "error"; } else { //Deserealizacion del archivo excel cargado al sistema. SLDocument sl = new SLDocument(path); //Recorremos el archivo para obtener la informaicon. using (var db = new ERP_GMEDINAEntities()) { int iRow = 2; while (!string.IsNullOrEmpty(sl.GetCellValueAsString(iRow, 1))) { string identidad = sl.GetCellValueAsString(iRow, 1); decimal monto = sl.GetCellValueAsDecimal(iRow, 2); string comentario = sl.GetCellValueAsString(iRow, 3); var oMiExcel = new tbDeduccionInstitucionFinanciera(); var IdEmpleado = (from P in db.tbPersonas join E in db.tbEmpleados on P.per_Id equals E.per_Id where P.per_Identidad == identidad select new { empleadoID = E.emp_Id, }).FirstOrDefault(); var sql = (from infs in db.tbDeduccionInstitucionFinanciera select infs.deif_IdDeduccionInstFinanciera).Max(); var iddeducfin = sql + 1; //Validamos si encontro empleados que correspondan a los numeros de identidad proporcionados, de lo contrario mostrara error. if (IdEmpleado != null) { var IdEmple = IdEmpleado.empleadoID; oMiExcel.deif_IdDeduccionInstFinanciera = iddeducfin; oMiExcel.emp_Id = IdEmple; oMiExcel.insf_IdInstitucionFinanciera = IdInsF; oMiExcel.deif_Monto = monto; oMiExcel.deif_Comentarios = comentario; oMiExcel.cde_IdDeducciones = idCatDeduc; oMiExcel.deif_UsuarioCrea = 1; oMiExcel.deif_FechaCrea = DateTime.Now; oMiExcel.deif_UsuarioModifica = null; oMiExcel.deif_FechaModifica = null; oMiExcel.deif_Activo = true; oMiExcel.deif_Pagado = false; db.tbDeduccionInstitucionFinanciera.Add(oMiExcel); db.SaveChanges(); } else { return(RedirectToAction("CargaDocumento")); } iRow++; } } response = "bien"; } } catch (Exception) { response = "error"; } } else { MensajeError = "Error: Debe seleccionar un archivo para poder cargarlo al sistema."; } List <tbCatalogoDeDeducciones> OCatalogoDeducciones = db.tbCatalogoDeDeducciones.Where(x => x.cde_Activo == true).ToList(); ViewBag.Deducciones = OCatalogoDeducciones; var listaINFS = from INFS in db.tbInstitucionesFinancieras select new { idinfs = INFS.insf_IdInstitucionFinanciera, descinfs = INFS.insf_DescInstitucionFinanc }; var list = new SelectList(listaINFS, "idinfs", "descinfs"); ViewData["INFS"] = list; if (response == "error") { ViewBag.MensajeError = "error"; } else { ViewBag.MensajeError = "bien"; } return(View("CargaDocumento")); }
public JsonResult InsertDecimoTercerMes(List <tbDecimoTercerMes> DecimoTercer) { //Contexto de base de datos para que se use solo cuando sea necesario. using (ERP_GMEDINAEntities entities = new ERP_GMEDINAEntities()) { try { //se construyen los lotes dependiendo de la cantidad de registros que reciba el controlador int numeroLotes = 1; int CantidadRegistros = DecimoTercer.Count; if (CantidadRegistros == 1) { numeroLotes = 1; } else if (CantidadRegistros <= 10) { numeroLotes = 5; } else if (CantidadRegistros <= 50) { numeroLotes = 10; } else if (CantidadRegistros <= 100) { numeroLotes = 20; } else if (CantidadRegistros <= 500) { numeroLotes = 50; } else if (CantidadRegistros <= 1000 || CantidadRegistros >= 1000) { numeroLotes = 100; } //Corroborar si la lista viene nula. if (DecimoTercer == null) { DecimoTercer = new List <tbDecimoTercerMes>(); } int i = 0; //Ciclo para insertar los registros. foreach (tbDecimoTercerMes DC in DecimoTercer) { i++; entities.UDP_Plani_tbDecimoTercerMes_Insert(DC.emp_Id, DC.dtm_Monto); if (i % numeroLotes == 0) { entities.SaveChanges(); } } } catch (Exception ex) { ex.Message.ToString(); } int RegistrosInsertados = entities.SaveChanges(); return(Json(RegistrosInsertados)); } }
public ActionResult GenerarPlanilla(int?ID) { #region declaracion de variables //correo electronico General utilities = new General(); List <IngresosDeduccionesVoucher> ListaIngresosVoucher = new List <IngresosDeduccionesVoucher>(); List <IngresosDeduccionesVoucher> ListaDeduccionesVoucher = new List <IngresosDeduccionesVoucher>(); ComprobantePagoModel oComprobantePagoModel = new ComprobantePagoModel(); IngresosDeduccionesVoucher ingresosColaborador = new IngresosDeduccionesVoucher(); IngresosDeduccionesVoucher deduccionesColaborador = new IngresosDeduccionesVoucher(); //enviar resultados al lado del cliente iziToast response = new iziToast(); int errores = 0; //procesar planilla empleados decimal totalPagarEmpleado = 0; decimal totalIngresosEmpleado = 0; decimal totalDeduccionesEmpleado = 0; decimal SalarioBase = 0; decimal bonos = 0, comisiones = 0, otrosIngresos = 0, deduccionesPorInstitucionesFinancieras = 0, DeduccionesExtraordinarias = 0; #endregion // INCIA PROCESO DE GENERACIÓN DE PLANILLAS try { #region CREAR ARCHIVO EXCEL DE LA PLANILLA tbCatalogoDePlanillas oNombrePlanilla = ID != null?db.tbCatalogoDePlanillas.Where(X => X.cpla_IdPlanilla == ID).FirstOrDefault() : null; string nombrePlanilla = oNombrePlanilla != null ? oNombrePlanilla.cpla_DescripcionPlanilla : "General"; string nombreDocumento = $"Planilla {nombrePlanilla} {Convert.ToString(DateTime.Now.Year)}-{Convert.ToString(DateTime.Now.Month)}-{Convert.ToString(DateTime.Now.Day)} {Convert.ToString(DateTime.Now.Hour)}-{Convert.ToString(DateTime.Now.Minute)}.xlsx"; string nombreDocumento2 = nombreDocumento; string pathFile = AppDomain.CurrentDomain.BaseDirectory + nombreDocumento2; string direccion = pathFile; SLDocument oSLDocument = new SLDocument(); System.Data.DataTable dt = new System.Data.DataTable(); dt.Columns.Add("Nombres", typeof(string)); dt.Columns.Add("Apellidos", typeof(string)); dt.Columns.Add("Sueldo base", typeof(decimal)); dt.Columns.Add("Bonos", typeof(decimal)); dt.Columns.Add("Comisiones", typeof(decimal)); dt.Columns.Add("Deducciones extras", typeof(decimal)); dt.Columns.Add("Deducciones Cooperativas", typeof(decimal)); dt.Columns.Add("IHSS", typeof(decimal)); dt.Columns.Add("ISR", typeof(decimal)); dt.Columns.Add("AFP", typeof(decimal)); dt.Columns.Add("RAP", typeof(decimal)); dt.Columns.Add("TOTAL A PAGAR", typeof(decimal)); #endregion using (ERP_GMEDINAEntities db = new ERP_GMEDINAEntities()) { List <tbCatalogoDePlanillas> oIDSPlanillas = new List <tbCatalogoDePlanillas>(); using (var dbContextTransaccion = db.Database.BeginTransaction()) { //ID DE TODAS LAS PLANILLAS, PARA PROCESARLAS 1 POR 1 if (ID != null) { oIDSPlanillas = db.tbCatalogoDePlanillas.Where(X => X.cpla_IdPlanilla == ID).ToList(); } else { oIDSPlanillas = db.tbCatalogoDePlanillas.ToList(); } //PROCESAR LAS PLANILLAS 1 POR 1 foreach (var iter in oIDSPlanillas) { try { //OBTENER PLANILLA ACTUAL tbCatalogoDePlanillas oPlanilla = db.tbCatalogoDePlanillas.Find(iter.cpla_IdPlanilla); //OBTENER LOS INGRESOS DE LA PLANILLA ACTUAL List <V_PlanillaIngresos> oIngresos = db.V_PlanillaIngresos.Where(x => x.cpla_IdPlanilla == oPlanilla.cpla_IdPlanilla).ToList(); //OBTENER LAS DEDUCCIONES DE LA PLANILLA ACTUAL List <V_PlanillaDeducciones> oDeducciones = db.V_PlanillaDeducciones.Where(x => x.cpla_IdPlanilla == oPlanilla.cpla_IdPlanilla).ToList(); //OBTNER LA LISTA DE EMPLEADOS QUE PERTENECEN A LA PLANILLA ACTUAL List <tbEmpleados> oEmpleados = db.tbEmpleados.Where(emp => emp.cpla_IdPlanilla == oPlanilla.cpla_IdPlanilla).ToList(); //================== PROCESAR PLANILLA COLABORADOR POR COLABORADOR ============================== foreach (var empleadoActual in oEmpleados) { try { //INFORMACION DEL COLABORADOR ACTUAL V_InformacionColaborador InformacionDelEmpleadoActual = db.V_InformacionColaborador.Where(x => x.emp_Id == empleadoActual.emp_Id).FirstOrDefault(); //EL SALARIO BASE SalarioBase = InformacionDelEmpleadoActual.SalarioBase; ListaIngresosVoucher.Add(new IngresosDeduccionesVoucher { concepto = "Salario base", monto = SalarioBase }); //VARIABLES NECESARIAS PARA PROCESAR LA PLANILLA DEL COLABORADOR ACTUAL bonos = 0; comisiones = 0; otrosIngresos = 0; deduccionesPorInstitucionesFinancieras = 0; DeduccionesExtraordinarias = 0; //OBTENER LAS DEDUCCIONES EXTRAS DEL COLABORADOR ACTUAL (SI LAS TIENE Y NO HA TERMINADO DE PAGARLAS) List <V_DeduccionesExtrasColaboradores> oDeduccionesExtrasColaborador = db.V_DeduccionesExtrasColaboradores.Where(DEX => DEX.emp_Id == empleadoActual.emp_Id && DEX.dex_MontoRestante > 0 && DEX.dex_Activo == true).ToList(); //VERIFICAR SI LA LISTA DE DEDUCCIONES EXTRAS DEL COLABORADOR NO VIENE NULA if (oDeduccionesExtrasColaborador.Count > 0) { //SI TIENE DEDUCCIONES EXTRAS, HAY QUE IR SUMANDOLAS TODAS foreach (var oDeduccionesExtrasColaboradorIterador in oDeduccionesExtrasColaborador) { DeduccionesExtraordinarias += oDeduccionesExtrasColaboradorIterador.dex_Cuota; //CÓDIGO PARA RESTAR LA CUOTA PAGADA DE LA CANTIDAD RESTANTE DE LA DEDUCCIÓN oDeduccionesExtrasColaboradorIterador.dex_MontoRestante = oDeduccionesExtrasColaboradorIterador.dex_MontoRestante - oDeduccionesExtrasColaboradorIterador.dex_Cuota; //db.Entry(oDeduccionesExtrasColaboradorIterador).State = EntityState.Modified; ListaDeduccionesVoucher.Add(new IngresosDeduccionesVoucher { concepto = oDeduccionesExtrasColaboradorIterador.dex_ObservacionesComentarios, monto = oDeduccionesExtrasColaboradorIterador.dex_Cuota }); } //db.SaveChanges(); } //OBTENER LAS DEDUCCIONES POR INSTITUCIONES FINANCIERAS DEL COLABORADOR ACTUAL List <V_DeduccionesInstitucionesFinancierasColaboradres> oDeduInstiFinancieras = db.V_DeduccionesInstitucionesFinancierasColaboradres.Where(x => x.emp_Id == empleadoActual.emp_Id && x.deif_Activo == true).ToList(); //VERIFICAR SI LA LISTA DE DEDUCCIONES POR INSTITUCIONES FINANCIERAS DEL COLABORADOR NO VIENE NULA if (oDeduInstiFinancieras.Count > 0) { //SI TIENE DEDUCCIONES DE INSTITUCIONES FINANCIERAS, HAY QUE IR SUMANDOLAS TODAS foreach (var oDeduInstiFinancierasIterador in oDeduInstiFinancieras) { deduccionesPorInstitucionesFinancieras += oDeduInstiFinancierasIterador.deif_Monto; //CÓDIGO PARA RESTAR LA CUOTA PAGADA DE LA CANTIDAD RESTANTE DE LA DEDUCCIÓN oDeduInstiFinancierasIterador.deif_Activo = false; //db.Entry(oDeduInstiFinancierasIterador).State = EntityState.Modified; ListaDeduccionesVoucher.Add(new IngresosDeduccionesVoucher { concepto = $"{oDeduInstiFinancierasIterador.insf_DescInstitucionFinanc} {oDeduInstiFinancierasIterador.deif_Comentarios}", monto = oDeduInstiFinancierasIterador.deif_Monto }); } //db.SaveChanges(); } //OBTENER LOS BONOS DEL COLABORADOR SI LOS TIENE List <V_BonosColaborador> oBonosColaboradores = db.V_BonosColaborador.Where(x => x.emp_Id == empleadoActual.emp_Id && x.cb_Activo == true && x.cb_Pagado == false).ToList(); if (oBonosColaboradores.Count > 0) { //SI TIENE BONOS, HAY QUE IR SUMANDOLAS TODAS foreach (var oBonosColaboradoresIterador in oBonosColaboradores) { bonos += oBonosColaboradoresIterador.cb_Monto; //CÓDIGO PARA RESTAR LA CUOTA PAGADA DE LA CANTIDAD RESTANTE DE LA DEDUCCIÓN oBonosColaboradoresIterador.cb_Pagado = true; //db.Entry(oBonosColaboradoresIterador).State = EntityState.Modified; ListaIngresosVoucher.Add(new IngresosDeduccionesVoucher { concepto = oBonosColaboradoresIterador.cin_DescripcionIngreso, monto = oBonosColaboradoresIterador.cb_Monto }); } //db.SaveChanges(); } //OBTENER LAS COMISIONES DEL COLABORADOR SI LOS TIENE List <V_ComisionesColaborador> oComisionesColaboradores = db.V_ComisionesColaborador.Where(x => x.emp_Id == empleadoActual.emp_Id && x.cc_Activo == true && x.cc_Pagado == false).ToList(); if (oComisionesColaboradores.Count > 0) { //SI TIENE BONOS, HAY QUE IR SUMANDOLAS TODAS foreach (var oComisionesColaboradoresIterador in oComisionesColaboradores) { comisiones += oComisionesColaboradoresIterador.cc_Monto; //CÓDIGO PARA RESTAR LA CUOTA PAGADA DE LA CANTIDAD RESTANTE DE LA DEDUCCIÓN oComisionesColaboradoresIterador.cc_Pagado = true; //db.Entry(oComisionesColaboradoresIterador).State = EntityState.Modified; ListaIngresosVoucher.Add(new IngresosDeduccionesVoucher { concepto = oComisionesColaboradoresIterador.cin_DescripcionIngreso, monto = oComisionesColaboradoresIterador.cc_Monto }); } //db.SaveChanges(); } totalIngresosEmpleado = SalarioBase + bonos + comisiones; totalDeduccionesEmpleado = DeduccionesExtraordinarias - deduccionesPorInstitucionesFinancieras; totalPagarEmpleado = totalIngresosEmpleado - totalDeduccionesEmpleado; //REGISTRO EN LA HOJA DE EXCEL dt.Rows.Add(empleadoActual.tbPersonas.per_Nombres, empleadoActual.tbPersonas.per_Apellidos, SalarioBase, bonos, comisiones, DeduccionesExtraordinarias, deduccionesPorInstitucionesFinancieras, 0, 0, 0, 0, totalPagarEmpleado); #region Enviar comprobante de pago por email oComprobantePagoModel.EmailAsunto = "Comprobante de pago"; oComprobantePagoModel.NombreColaborador = empleadoActual.tbPersonas.per_Nombres + " " + empleadoActual.tbPersonas.per_Apellidos; oComprobantePagoModel.idColaborador = empleadoActual.emp_Id; oComprobantePagoModel.EmailDestino = empleadoActual.tbPersonas.per_CorreoElectronico; oComprobantePagoModel.PeriodoPago = "1/11/2019 - 30/11/2019"; oComprobantePagoModel.Ingresos = ListaIngresosVoucher; oComprobantePagoModel.Deducciones = ListaDeduccionesVoucher; oComprobantePagoModel.totalIngresos = totalIngresosEmpleado; oComprobantePagoModel.totalDeducciones = totalDeduccionesEmpleado; oComprobantePagoModel.NetoPagar = totalPagarEmpleado; //Enviar comprobante de pago try { if (!utilities.SendEmail(oComprobantePagoModel)) { errores++; } else { ListaDeduccionesVoucher = new List <IngresosDeduccionesVoucher>(); ListaIngresosVoucher = new List <IngresosDeduccionesVoucher>(); } } catch (Exception ex) { errores++; } #endregion } //CATCH FOR EACH EMPLEADO POR EMPLEADO catch (Exception ex) { // AGREGAR EL EMPLEADO ACTUAL AL QUE FALLÓ LA GENERACIÓN DE SU PLANILLA dt.Rows.Add(empleadoActual.tbPersonas.per_Nombres + ' ' + empleadoActual.tbPersonas.per_Apellidos, "Ocurrió un error al generar la planilla de este empleado." ); errores++; } } db.SaveChanges(); dbContextTransaccion.Commit(); } //CATCH FOR EACH DE LAS PLANILLAS catch (Exception ex) { // SI ALGO FALLA, HACER UN ROLLBACK dbContextTransaccion.Rollback(); errores++; dt.Rows.Add("Ocurrió un error al generar la planilla de xxyy."); } } } } response.Response = $"El proceso de generación de planilla se realizó, con {errores} errores"; response.Encabezado = "Exito"; response.Tipo = "success"; try { oSLDocument.ImportDataTable(1, 1, dt, true); oSLDocument.SaveAs(direccion); } catch (Exception ex) { response.Response = "Planilla generada, error al crear documento excel."; response.Encabezado = "Advertencia"; response.Tipo = "warning"; } //=========================================================================== } // CATCH DEL PROCESO DE GENERACIÓN DE PLANILLAS catch (Exception ex) { response.Response = "El proceso de generación de planillas falló, contacte al adminstrador."; response.Encabezado = "Error"; response.Tipo = "error"; } return(new JsonResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public async Task <ActionResult> GenerarPlanilla(int?ID, bool?enviarEmail, DateTime fechaInicio, DateTime fechaFin, List <ViewModelTasasDeCambio> monedas, int tmon_IdMonedaDeduccionesDePlanilla) { #region declaracion de instancias // helper General utilities = new General(); // instancias para el comprobante de pago List <IngresosDeduccionesVoucher> ListaIngresosVoucher = new List <IngresosDeduccionesVoucher>(); List <IngresosDeduccionesVoucher> ListaDeduccionesVoucher = new List <IngresosDeduccionesVoucher>(); ComprobantePagoModel oComprobantePagoModel = new ComprobantePagoModel(); IngresosDeduccionesVoucher ingresosColaborador = new IngresosDeduccionesVoucher(); IngresosDeduccionesVoucher deduccionesColaborador = new IngresosDeduccionesVoucher(); // instancias para el reporte final ReportePlanillaViewModel oPlanillaEmpleado; List <ReportePlanillaViewModel> reporte = new List <ReportePlanillaViewModel>(); ViewModelListaErrores oError; List <ViewModelListaErrores> listaErrores = new List <ViewModelListaErrores>(); // instancia para resultado del proceso en izitoast General.iziToast response = new General.iziToast(); int errores = 0; string codigoDePlanillaGenerada = String.Empty; #endregion #region inicia proceso de generación de planilla try { using (ERP_GMEDINAEntities db = new ERP_GMEDINAEntities()) { List <tbCatalogoDePlanillas> oIDSPlanillas = new List <tbCatalogoDePlanillas>(); List <int> planillasConColaboradores = db.V_ColaboradoresPorPlanilla.Where(x => x.CantidadColaboradores > 0).Select(x => x.cpla_IdPlanilla).ToList(); // seleccionar las planillas que se van a generar if (ID != null) { oIDSPlanillas = db.tbCatalogoDePlanillas .Where(X => X.cpla_IdPlanilla == ID) .ToList(); } else { oIDSPlanillas = db.tbCatalogoDePlanillas .Where(x => x.cpla_Activo == true && planillasConColaboradores.Contains(x.cpla_IdPlanilla)) .ToList(); } if (oIDSPlanillas != null) { // procesar todas las planillas seleccionadas foreach (var iter in oIDSPlanillas) { codigoDePlanillaGenerada = $"PLANI_{Function.DatetimeNow().Year}{Function.DatetimeNow().Month}{Function.DatetimeNow().Day}_{Function.DatetimeNow().Hour}{Function.DatetimeNow().Minute}{Function.DatetimeNow().Second}"; try { // planilla actual del foreach tbCatalogoDePlanillas oPlanilla = db.tbCatalogoDePlanillas .Find(iter.cpla_IdPlanilla); // ingresos de la planilla actual List <V_PlanillaIngresos> oIngresos = db.V_PlanillaIngresos .Where(x => x.cpla_IdPlanilla == oPlanilla.cpla_IdPlanilla) .ToList(); // deducciones de la planilla actual List <V_PlanillaDeducciones> oDeducciones = db.V_PlanillaDeducciones .Where(x => x.cpla_IdPlanilla == oPlanilla.cpla_IdPlanilla) .ToList(); // empleados de la planilla actual List <tbEmpleados> oEmpleados = db.tbEmpleados .Where(emp => emp.cpla_IdPlanilla == oPlanilla.cpla_IdPlanilla && emp.emp_Estado == true) .ToList(); int contador = 1, idHistorialPago = 0, idDetalleDeduccionHisotorialesContador = 1, idDetalleIngresoHisotorialesContador = 1; string identidadEmpleado = string.Empty, NombresEmpleado = string.Empty; // procesar planilla empleado por empleado foreach (var empleadoActual in oEmpleados) { using (var dbContextTransaccion = db.Database.BeginTransaction()) { try { #region variables reporte view model string codColaborador = string.Empty, nombreColaborador = string.Empty, tipoPlanilla = string.Empty; decimal SalarioBase = 0, salarioHora = 0, totalAFP = 0, totalISR = 0, totalSalario = 0; int horasTrabajadas = 0, horasExtrasTrabajadas = 0, cantidadUnidadesBonos = 0; decimal?totalComisiones = 0, totalHorasExtras = 0, totalHorasPermiso = 0, totalBonificaciones = 0, totalIngresosIndivuales = 0, totalVacaciones = 0, totalIngresosEmpleado = 0, colaboradorDeducciones = 0, totalInstitucionesFinancieras = 0, totalOtrasDeducciones = 0, adelantosSueldo = 0, totalDeduccionesEmpleado = 0, totalDeduccionesIndividuales = 0, netoAPagarColaborador = 0; oPlanillaEmpleado = new ReportePlanillaViewModel(); oError = new ViewModelListaErrores(); string moneda = db.tbSueldos.Where(x => x.emp_Id == empleadoActual.emp_Id && x.sue_Estado == true).Select(x => x.tbTipoMonedas.tmon_Descripcion).FirstOrDefault(); // variables para insertar en los historiales de pago IEnumerable <object> listHistorialPago = null; string MensajeError = ""; List <tbHistorialDeduccionPago> lisHistorialDeducciones = new List <tbHistorialDeduccionPago>(); List <tbHistorialDeIngresosPago> lisHistorialIngresos = new List <tbHistorialDeIngresosPago>(); #endregion V_InformacionColaborador InformacionDelEmpleadoActual = null; decimal resultSeptimoDia = 0; int userId = (int)Session["UserLogin"]; //Procesar Ingresos await Task.Run(() => Ingresos.ProcesarIngresos(userId, fechaInicio, fechaFin, ListaIngresosVoucher, listaErrores, ref errores, db, empleadoActual, ref SalarioBase, out horasTrabajadas, ref salarioHora, ref totalSalario, ref totalComisiones, out horasExtrasTrabajadas, ref cantidadUnidadesBonos, ref totalHorasExtras, ref totalHorasPermiso, ref totalBonificaciones, ref totalIngresosIndivuales, ref totalVacaciones, out totalIngresosEmpleado, lisHistorialIngresos, out InformacionDelEmpleadoActual, out resultSeptimoDia)); //Procesar Deducciones await Task.Run(() => Deducciones.ProcesarDeducciones(tmon_IdMonedaDeduccionesDePlanilla, monedas, userId, fechaInicio, fechaFin, ListaDeduccionesVoucher, listaErrores, ref errores, db, oDeducciones, empleadoActual, SalarioBase, totalIngresosEmpleado, ref colaboradorDeducciones, ref totalAFP, ref totalInstitucionesFinancieras, ref totalOtrasDeducciones, ref adelantosSueldo, out totalDeduccionesEmpleado, ref totalDeduccionesIndividuales, out netoAPagarColaborador, lisHistorialDeducciones, InformacionDelEmpleadoActual)); //ISR TimeSpan tDias = fechaFin - fechaInicio; totalISR = CalculoISR.CalcularISR(db, empleadoActual, totalSalario, totalISR, tDias.Days + 1); idHistorialPago = GuardarEnHistorialDePago.GuardarHistorialDePago(fechaInicio, fechaFin, listaErrores, ref errores, codigoDePlanillaGenerada, db, ref contador, ref idDetalleDeduccionHisotorialesContador, ref idDetalleIngresoHisotorialesContador, empleadoActual, totalSalario, totalComisiones, horasExtrasTrabajadas, cantidadUnidadesBonos, totalHorasExtras, totalHorasPermiso, totalBonificaciones, totalIngresosIndivuales, totalVacaciones, totalISR, totalAFP, adelantosSueldo, totalDeduccionesIndividuales, netoAPagarColaborador, ref listHistorialPago, ref MensajeError, lisHistorialDeducciones, lisHistorialIngresos, InformacionDelEmpleadoActual, resultSeptimoDia); // guardar cambios en la bbdd db.SaveChanges(); dbContextTransaccion.Commit(); //EnviarComprobanteDePago await Task.Run(() => EnviarComprobanteDePago.EnviarComprobanteDePagoColaborador(moneda, enviarEmail, fechaInicio, fechaFin, utilities, ref ListaIngresosVoucher, ref ListaDeduccionesVoucher, oComprobantePagoModel, listaErrores, ref errores, db, empleadoActual, totalIngresosEmpleado, totalDeduccionesEmpleado, netoAPagarColaborador, InformacionDelEmpleadoActual)); #region crear registro de la planilla del colaborador para el reporte await Task.Run(() => ReportePlanilla.ReporteColaboradorPlanilla(moneda, ref oPlanillaEmpleado, empleadoActual, SalarioBase, horasTrabajadas, salarioHora, totalSalario, totalComisiones, horasExtrasTrabajadas, totalHorasExtras, totalHorasPermiso, totalBonificaciones, totalIngresosIndivuales, totalVacaciones, totalIngresosEmpleado, totalISR, colaboradorDeducciones, totalAFP, totalInstitucionesFinancieras, totalOtrasDeducciones, adelantosSueldo, totalDeduccionesEmpleado, totalDeduccionesIndividuales, netoAPagarColaborador, InformacionDelEmpleadoActual)); reporte.Add(oPlanillaEmpleado); oPlanillaEmpleado = null; identidadEmpleado = InformacionDelEmpleadoActual.per_Identidad; NombresEmpleado = InformacionDelEmpleadoActual.per_Nombres; #endregion } #endregion // catch por si hubo un error al generar la planilla de un empleado catch (Exception ex) { // si hay un error, hacer un rollback dbContextTransaccion.Rollback(); // mensaje del error en el registro del colaborador errores++; listaErrores.Add(new ViewModelListaErrores { Identidad = identidadEmpleado, NombreColaborador = NombresEmpleado, Error = "Error al procesar planilla del colaborador.", PosibleSolucion = "Verifique información registrada al colaborador y vuelva a intentarlo." }); } } // termina transaccion } } // catch si se produjo un error al procesar una sola planilla catch (Exception ex) { listaErrores.Add(new ViewModelListaErrores { Identidad = $"Planilla {iter.cpla_DescripcionPlanilla}", NombreColaborador = "", Error = $"Ocurrió un error al procesar la planilla {iter.cpla_DescripcionPlanilla}" }); errores++; } } // for each idsPlanillas } // if idsPlanilla != null } // using entities model // enviar resultado al cliente response.Response = $"El proceso de generación de planilla se realizó, con {errores} errores"; response.Encabezado = "Exito"; response.Tipo = errores == 0 ? "success" : "warning"; } // catch se produjo un error fatal en el proceso generar planilla catch (Exception ex) { response.Response = ""; response.Encabezado = "Error"; response.Tipo = "error"; listaErrores.Add(new ViewModelListaErrores { Identidad = $"Planilla", NombreColaborador = "", Error = $"El proceso de generación de planillas falló, contacte al adminstrador.", PosibleSolucion = "Vuelva a intentarlo" }); } // retornar resultado del proceso return(Json(new { Data = reporte, listaDeErrores = listaErrores, Response = response }, JsonRequestBehavior.AllowGet)); }