// se usa este actualmente
        public static void PrevisualizarProcesarDeducciones(int monedaDeducciones, List <ViewModelTasasDeCambio> objMonedas, int userId, DateTime fechaInicio, DateTime fechaFin, List <ViewModelListaErrores> listaErrores, ref int errores, ERP_GMEDINAEntities db, List <V_PlanillaDeducciones> oDeducciones, tbEmpleados empleadoActual, decimal SalarioBase, decimal?totalIngresosEmpleado, ref decimal?colaboradorDeducciones, ref decimal totalAFP, ref decimal?totalInstitucionesFinancieras, ref decimal?totalOtrasDeducciones, ref decimal?adelantosSueldo, out decimal?totalDeduccionesEmpleado, ref decimal?totalDeduccionesIndividuales, out decimal?netoAPagarColaborador, V_InformacionColaborador InformacionDelEmpleadoActual)
        {
            #region Procesar deducciones

            // instancia del helper
            Models.Helpers objHelpers = new Models.Helpers();

            // id del usuario logueado
            int idUser = userId;

            // validar que la planilla tenga deducciones
            if (oDeducciones.Count > 0)
            {
                // obtener id del tipo de moneda del sueldo del colaborador
                int idMonedaColaborador = db.tbSueldos.Where(x => x.emp_Id == InformacionDelEmpleadoActual.emp_Id && x.sue_Estado == true).Select(x => x.tmon_Id).FirstOrDefault();

                ViewModelTasasDeCambio tasaDeCambio = new ViewModelTasasDeCambio();

                // si el tipo de moneda del colaborador es distinto de la moneda de las deducciones seleccionada en el frontend, hacer la conversion
                if (idMonedaColaborador != monedaDeducciones)
                {
                    // no tengo idea de que estaba haciendo aquí gg
                    tasaDeCambio = objMonedas.Where(x => x.tmon_Id == idMonedaColaborador).FirstOrDefault();
                }

                // deducciones de la planilla
                foreach (var iterDeducciones in oDeducciones)
                {
                    try
                    {
                        decimal?porcentajeColaborador     = iterDeducciones.cde_PorcentajeColaborador;
                        decimal?porcentajeEmpresa         = iterDeducciones.cde_PorcentajeEmpresa;
                        decimal?montoDeduccionColaborador = SalarioBase;

                        // si el tipo de moneda del colaborador es distinto de la moneda de las deducciones seleccionada en el frontend, hacer la conversion
                        if (idMonedaColaborador != monedaDeducciones)
                        {
                            montoDeduccionColaborador = (SalarioBase * tasaDeCambio.tmon_Cambio);
                        }

                        try
                        {
                            // verificar techos deducciones
                            List <tbTechosDeducciones> oTechosDeducciones = db.tbTechosDeducciones
                                                                            .Where(x => x.cde_IdDeducciones == iterDeducciones.cde_IdDeducciones &&
                                                                                   x.tddu_Activo == true)
                                                                            .OrderBy(x => x.tddu_Techo)
                                                                            .ToList();
                            if (oTechosDeducciones.Count() > 0)
                            {
                                foreach (var techosDeduccionesIter in oTechosDeducciones)
                                {
                                    try
                                    {
                                        if (SalarioBase > techosDeduccionesIter.tddu_Techo)
                                        {
                                            montoDeduccionColaborador = techosDeduccionesIter.tddu_Techo;
                                            porcentajeColaborador     = techosDeduccionesIter.tddu_PorcentajeColaboradores;
                                            porcentajeEmpresa         = techosDeduccionesIter.tddu_PorcentajeEmpresa;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        listaErrores.Add(new ViewModelListaErrores
                                        {
                                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                                            Error             = $"Error al cargar techo de la deducción: {iterDeducciones.cde_DescripcionDeduccion}. Detalles del techo: Techo {techosDeduccionesIter.tddu_Techo}, porcentaje colaborador : {techosDeduccionesIter.tddu_PorcentajeColaboradores}, porcentaje empresa: {techosDeduccionesIter.tddu_PorcentajeEmpresa}.",
                                            PosibleSolucion   = "Verifique que la información de esta deducción y sus respectivos techos esté completa y/o correcta."
                                        });
                                        errores++;
                                    }
                                }
                                // si la moneda de las deducciones es distintas al tipo de moneda del colaborador, convertir a la moneda del colaborador
                                // antes de agregarlo al reporte final

                                if (idMonedaColaborador != monedaDeducciones)
                                {
                                    colaboradorDeducciones = Math.Round(((decimal)colaboradorDeducciones) / tasaDeCambio.tmon_Cambio, 2);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            listaErrores.Add(new ViewModelListaErrores
                            {
                                Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                                NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                                Error             = $"Error al cargar techos de la deducción: {iterDeducciones.cde_DescripcionDeduccion}.",
                                PosibleSolucion   = "Verifique que la información de esta deducción y sus respectivos techos esté completa y/o correcta."
                            });
                            errores++;
                        }

                        //sumar las deducciones
                        colaboradorDeducciones += Math.Round((decimal)(montoDeduccionColaborador * porcentajeColaborador) / 100, 2);
                    }
                    catch (Exception ex)
                    {
                        listaErrores.Add(new ViewModelListaErrores
                        {
                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                            Error             = $"Error al procesar deducción {iterDeducciones.cde_DescripcionDeduccion}.",
                            PosibleSolucion   = "Verifique que la información de esta deducción y sus respectivos techos (si los tiene) esté completa y/o correcta."
                        });
                        errores++;
                    }
                }
            }


            //instituciones financieras
            List <tbDeduccionInstitucionFinanciera> oDeduInstiFinancieras = db.tbDeduccionInstitucionFinanciera
                                                                            .Where(x => x.emp_Id == empleadoActual.emp_Id &&
                                                                                   x.deif_Activo == true &&
                                                                                   x.deif_Pagado == false &&
                                                                                   x.deif_FechaCrea >= fechaInicio &&
                                                                                   x.deif_FechaCrea <= fechaFin)
                                                                            .ToList();

            if (oDeduInstiFinancieras.Count > 0)
            {
                // sumarlas todas
                foreach (var oDeduInstiFinancierasIterador in oDeduInstiFinancieras)
                {
                    try
                    {
                        totalInstitucionesFinancieras += Math.Round((decimal)oDeduInstiFinancierasIterador.deif_Monto, 2);
                    }
                    catch (Exception ex)
                    {
                        listaErrores.Add(new ViewModelListaErrores
                        {
                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                            Error             = $"Error al procesar deduccion por institución financiera {oDeduInstiFinancierasIterador.tbInstitucionesFinancieras.insf_DescInstitucionFinanc} - {oDeduInstiFinancierasIterador.deif_Comentarios} - {oDeduInstiFinancierasIterador.deif_Monto}.",
                            PosibleSolucion   = "Verifique que la información de esta deducción sea correcta de acuerdo al formato leído por el sistema."
                        });
                        errores++;
                    }
                }
            }
            // deducciones afp
            List <tbDeduccionAFP> oDeduccionAfp = db.tbDeduccionAFP
                                                  .Where(af => af.emp_Id == empleadoActual.emp_Id &&
                                                         af.dafp_Activo == true)
                                                  .ToList();

            // respaldo de where's comentados de deduccion afp
            // af.dafp_Pagado != true &&
            // af.dafp_FechaCrea >= fechaInicio &&
            // af.dafp_FechaCrea <= fechaFin

            if (oDeduccionAfp.Count > 0)
            {
                // sumarlas todas
                foreach (var oDeduccionAfpIter in oDeduccionAfp)
                {
                    try
                    {
                        totalAFP += Math.Round(oDeduccionAfpIter.dafp_AporteLps, 2);
                    }
                    catch (Exception ex)
                    {
                        listaErrores.Add(new ViewModelListaErrores
                        {
                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                            Error             = $"Error al procesar deduccion AFP. {oDeduccionAfpIter.tbAFP.afp_Descripcion} - {oDeduccionAfpIter.dafp_AporteLps}",
                            PosibleSolucion   = "Verifique que la información de esta deducción esté correcta y/o completa."
                        });
                        errores++;
                    }
                }
            }

            // deducciones por equipo de trabajo
            List <tbDeduccionesExtraordinarias> oDeduccionesExtrasColaborador = db.tbDeduccionesExtraordinarias
                                                                                .Where(DEX => DEX.tbEquipoEmpleados.emp_Id == empleadoActual.emp_Id &&
                                                                                       DEX.dex_MontoRestante > 0 &&
                                                                                       DEX.dex_Activo == true)
                                                                                .ToList();

            if (oDeduccionesExtrasColaborador.Count > 0)
            {
                // sumarlas todas
                foreach (var oDeduccionesExtrasColaboradorIterador in oDeduccionesExtrasColaborador)
                {
                    try
                    {
                        totalOtrasDeducciones += oDeduccionesExtrasColaboradorIterador.dex_MontoRestante <= oDeduccionesExtrasColaboradorIterador.dex_Cuota ? oDeduccionesExtrasColaboradorIterador.dex_MontoRestante : oDeduccionesExtrasColaboradorIterador.dex_Cuota;
                    }
                    catch (Exception ex)
                    {
                        listaErrores.Add(new ViewModelListaErrores
                        {
                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                            Error             = $"Error al procesar deduccion extra. {oDeduccionesExtrasColaboradorIterador.dex_ObservacionesComentarios} - {oDeduccionesExtrasColaboradorIterador.dex_Cuota}",
                            PosibleSolucion   = "Verifique que la información de esta deducción esté correcta y/o completa."
                        });
                        errores++;
                    }
                }
            }

            // adelantos de sueldo
            List <tbAdelantoSueldo> oAdelantosSueldo = db.tbAdelantoSueldo
                                                       .Where(x => x.emp_Id == empleadoActual.emp_Id &&
                                                              x.adsu_Activo == true && x.adsu_Deducido == false &&
                                                              x.adsu_FechaAdelanto >= fechaInicio &&
                                                              x.adsu_FechaAdelanto <= fechaFin)
                                                       .ToList();

            if (oAdelantosSueldo.Count > 0)
            {
                // sumarlas todas
                foreach (var oAdelantosSueldoIterador in oAdelantosSueldo)
                {
                    try
                    {
                        adelantosSueldo += Math.Round((decimal)oAdelantosSueldoIterador.adsu_Monto, 2);
                    }
                    catch (Exception ex)
                    {
                        listaErrores.Add(new ViewModelListaErrores
                        {
                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                            Error             = $"Error al procesar adelanto de sueldo. {oAdelantosSueldoIterador.adsu_RazonAdelanto} - {oAdelantosSueldoIterador.adsu_Monto}",
                            PosibleSolucion   = "Verifique que la información de dicho adelanto esté completa y/o correcta."
                        });
                        errores++;
                    }
                }
            }

            // deducciones individuales
            List <tbDeduccionesIndividuales> oDeduccionesIndiColaborador = db.tbDeduccionesIndividuales
                                                                           .Where(DEX => DEX.emp_Id == empleadoActual.emp_Id &&
                                                                                  DEX.dei_Monto > 0 &&
                                                                                  DEX.dei_Pagado != true &&
                                                                                  DEX.dei_Activo == true)
                                                                           .ToList();

            if (oDeduccionesIndiColaborador.Count > 0)
            {
                // sumarlas todas
                foreach (var oDeduccionesIndiColaboradorIterador in oDeduccionesIndiColaborador)
                {
                    try
                    {
                        totalDeduccionesIndividuales += oDeduccionesIndiColaboradorIterador.dei_Monto <= oDeduccionesIndiColaboradorIterador.dei_MontoCuota ? oDeduccionesIndiColaboradorIterador.dei_MontoCuota : oDeduccionesIndiColaboradorIterador.dei_MontoCuota;
                    }
                    catch (Exception ex)
                    {
                        listaErrores.Add(new ViewModelListaErrores
                        {
                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                            Error             = $"Error al procesar deducción individual. {oDeduccionesIndiColaboradorIterador.dei_Motivo} - {oDeduccionesIndiColaboradorIterador.dei_MontoCuota}",
                            PosibleSolucion   = "Verifique que la de dicha deducción esté completa y/o correcta."
                        });
                        errores++;
                    }
                }
            }

            // totales
            totalDeduccionesEmpleado = Math.Round((decimal)totalOtrasDeducciones, 2) + totalInstitucionesFinancieras + colaboradorDeducciones + totalAFP + adelantosSueldo + totalDeduccionesIndividuales;
            netoAPagarColaborador    = totalIngresosEmpleado - totalDeduccionesEmpleado;

            #endregion
        }
        public static void EnviarComprobanteDePagoColaborador(string moneda, bool?enviarEmail, DateTime fechaInicio, DateTime fechaFin, General utilities, ref List <IngresosDeduccionesVoucher> ListaIngresosVoucher, ref List <IngresosDeduccionesVoucher> ListaDeduccionesVoucher, ComprobantePagoModel oComprobantePagoModel, List <ViewModelListaErrores> listaErrores, ref int errores, ERP_GMEDINAEntities db, tbEmpleados empleadoActual, decimal?totalIngresosEmpleado, decimal?totalDeduccionesEmpleado, decimal?netoAPagarColaborador, V_InformacionColaborador InformacionDelEmpleadoActual)
        {
            #region Enviar comprobante de pago por email
            if (enviarEmail != null && enviarEmail == true)
            {
                oComprobantePagoModel.moneda            = moneda;
                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       = $"{fechaInicio.ToString("dd/MM/yyyy")}- {fechaFin.ToString("dd/MM/yyyy")}";
                oComprobantePagoModel.Ingresos          = ListaIngresosVoucher;
                oComprobantePagoModel.Deducciones       = ListaDeduccionesVoucher;
                oComprobantePagoModel.totalIngresos     = totalIngresosEmpleado;
                oComprobantePagoModel.totalDeducciones  = totalDeduccionesEmpleado;
                oComprobantePagoModel.NetoPagar         = netoAPagarColaborador;

                // enviar comprobante de pago
                try
                {
                    if (!utilities.SendEmail(oComprobantePagoModel))
                    {
                        listaErrores.Add(new ViewModelListaErrores
                        {
                            Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                            NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                            Error             = "Error al Enviar comprobante de pago.",
                            PosibleSolucion   = "Verifique que la información del perfil del colaborador esté completa y/o correcta."
                        });
                        errores++;
                    }
                    else
                    {
                        ListaDeduccionesVoucher = new List <IngresosDeduccionesVoucher>();
                        ListaIngresosVoucher    = new List <IngresosDeduccionesVoucher>();
                    }
                }
                catch (Exception ex)
                {
                    listaErrores.Add(new ViewModelListaErrores
                    {
                        Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                        NombreColaborador = InformacionDelEmpleadoActual.per_Nombres + " " + InformacionDelEmpleadoActual.per_Apellidos,
                        Error             = "Error al Enviar comprobante de pago.",
                        PosibleSolucion   = "Verifique que la información del perfil del colaborador esté completa y/o correcta."
                    });
                    errores++;
                }
            }
            #endregion
        }
 public static void ReporteColaboradorPlanilla(string moneda, ref ReportePlanillaViewModel oPlanillaEmpleado, tbEmpleados empleadoActual, decimal SalarioBase, int horasTrabajadas, decimal salarioHora, decimal totalSalario, decimal?totalComisiones, int horasExtrasTrabajadas, decimal?totalHorasExtras, decimal?totalHorasPermiso, decimal?totalBonificaciones, decimal?totalIngresosIndivuales, decimal?totalVacaciones, decimal?totalIngresosEmpleado, decimal totalISR, decimal?colaboradorDeducciones, decimal totalAFP, decimal?totalInstitucionesFinancieras, decimal?totalOtrasDeducciones, decimal?adelantosSueldo, decimal?totalDeduccionesEmpleado, decimal?totalDeduccionesIndividuales, decimal?netoAPagarColaborador, V_InformacionColaborador InformacionDelEmpleadoActual)
 {
     oPlanillaEmpleado.CodColaborador                = InformacionDelEmpleadoActual.emp_Id.ToString();
     oPlanillaEmpleado.NombresColaborador            = $"{empleadoActual.tbPersonas.per_Nombres} {empleadoActual.tbPersonas.per_Apellidos}";
     oPlanillaEmpleado.Moneda                        = moneda;
     oPlanillaEmpleado.SalarioBase                   = SalarioBase;
     oPlanillaEmpleado.horasTrabajadas               = horasTrabajadas;
     oPlanillaEmpleado.SalarioHora                   = salarioHora;
     oPlanillaEmpleado.totalSalario                  = totalSalario;
     oPlanillaEmpleado.tipoPlanilla                  = empleadoActual.tbCatalogoDePlanillas.cpla_DescripcionPlanilla;
     oPlanillaEmpleado.totalComisiones               = totalComisiones;
     oPlanillaEmpleado.horasExtras                   = horasExtrasTrabajadas;
     oPlanillaEmpleado.totalHorasPermiso             = totalHorasPermiso;
     oPlanillaEmpleado.TotalIngresosHorasExtras      = totalHorasExtras;
     oPlanillaEmpleado.totalBonificaciones           = totalBonificaciones;
     oPlanillaEmpleado.totalIngresosIndivuales       = totalIngresosIndivuales;
     oPlanillaEmpleado.totalVacaciones               = totalVacaciones;
     oPlanillaEmpleado.totalIngresos                 = Math.Round((decimal)totalIngresosEmpleado, 2);
     oPlanillaEmpleado.totalISR                      = totalISR;
     oPlanillaEmpleado.totalDeduccionesColaborador   = colaboradorDeducciones;
     oPlanillaEmpleado.totalAFP                      = totalAFP;
     oPlanillaEmpleado.totalInstitucionesFinancieras = totalInstitucionesFinancieras;
     oPlanillaEmpleado.otrasDeducciones              = Math.Round((decimal)totalOtrasDeducciones, 2);
     oPlanillaEmpleado.adelantosSueldo               = Math.Round((decimal)adelantosSueldo, 2);
     oPlanillaEmpleado.totalDeduccionesIndividuales  = totalDeduccionesIndividuales;
     oPlanillaEmpleado.totalDeducciones              = Math.Round((decimal)totalDeduccionesEmpleado, 2);
     oPlanillaEmpleado.totalAPagar                   = Math.Round((decimal)netoAPagarColaborador, 2);
 }
Esempio n. 4
0
        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 static int GuardarHistorialDePago(DateTime fechaInicio, DateTime fechaFin, List <ViewModelListaErrores> listaErrores, ref int errores, string codigoDePlanillaGenerada, ERP_GMEDINAEntities db, ref int contador, ref int idDetalleDeduccionHisotorialesContador, ref int idDetalleIngresoHisotorialesContador, tbEmpleados empleadoActual, decimal totalSalario, decimal?totalComisiones, int horasExtrasTrabajadas, int cantidadUnidadesBonos, decimal?totalHorasExtras, decimal?totalHorasPermiso, decimal?totalBonificaciones, decimal?totalIngresosIndivuales, decimal?totalVacaciones, decimal totalISR, decimal totalAFP, decimal?adelantosSueldo, decimal?totalDeduccionesIndividuales, decimal?netoAPagarColaborador, ref IEnumerable <object> listHistorialPago, ref string MensajeError, List <tbHistorialDeduccionPago> lisHistorialDeducciones, List <tbHistorialDeIngresosPago> lisHistorialIngresos, V_InformacionColaborador InformacionDelEmpleadoActual, decimal resultSeptimoDia)
        {
            #region guardar en el historial de pago

            int idHistorialPago = db.tbHistorialDePago
                                  .Select(x => x.hipa_IdHistorialDePago)
                                  .DefaultIfEmpty(0)
                                  .Max();
            int idUser = (int)HttpContext.Current.Session["UserLogin"];

            try
            {
                tbHistorialDePago oHistorialPagoEncabezado = new tbHistorialDePago();
                oHistorialPagoEncabezado.hipa_IdHistorialDePago = idHistorialPago + contador;
                oHistorialPagoEncabezado.emp_Id           = empleadoActual.emp_Id;
                oHistorialPagoEncabezado.hipa_SueldoNeto  = Math.Round((decimal)netoAPagarColaborador, 2);
                oHistorialPagoEncabezado.hipa_FechaInicio = fechaInicio;
                oHistorialPagoEncabezado.hipa_FechaFin    = fechaFin;
                oHistorialPagoEncabezado.hipa_FechaPago   = DateTime.Now;
                oHistorialPagoEncabezado.hipa_Anio        = DateTime.Now.Year;
                oHistorialPagoEncabezado.hipa_Mes         = DateTime.Now.Month;
                oHistorialPagoEncabezado.peri_IdPeriodo   = 1;

                oHistorialPagoEncabezado.hipa_UsuarioCrea = idUser;
                oHistorialPagoEncabezado.hipa_FechaCrea   = DateTime.Now;

                oHistorialPagoEncabezado.hipa_TotalISR     = totalISR;
                oHistorialPagoEncabezado.hipa_ISRPendiente = true;
                oHistorialPagoEncabezado.hipa_AFP          = totalAFP;

                //Nuevos campos
                oHistorialPagoEncabezado.hipa_TotalHorasConPermisoJustificado = totalHorasPermiso;
                oHistorialPagoEncabezado.hipa_TotalComisiones  = totalComisiones;
                oHistorialPagoEncabezado.hipa_TotalHorasExtras = totalHorasExtras;
                oHistorialPagoEncabezado.hipa_TotalVacaciones  = totalVacaciones;
                oHistorialPagoEncabezado.hipa_TotalSeptimoDia  = resultSeptimoDia;
                oHistorialPagoEncabezado.hipa_AdelantoSueldo   = adelantosSueldo;
                oHistorialPagoEncabezado.hipa_TotalSalario     = totalSalario;

                // nuevos campos
                oHistorialPagoEncabezado.hipa_TotalDeduccionesIndividuales = totalDeduccionesIndividuales;
                oHistorialPagoEncabezado.hipa_TotalIngresosIndividuales    = totalIngresosIndivuales;
                oHistorialPagoEncabezado.hipa_TotalSueldoBruto             = totalSalario;
                oHistorialPagoEncabezado.hipa_CantidadUnidadesHorasExtras  = horasExtrasTrabajadas;

                oHistorialPagoEncabezado.hipa_CantidadUnidadesBonos = cantidadUnidadesBonos;

                oHistorialPagoEncabezado.hipa_TotalBonos = totalBonificaciones;

                //Ejecutar el procedimiento almacenado
                listHistorialPago = db.UDP_Plani_tbHistorialDePago_Insert(oHistorialPagoEncabezado.emp_Id,
                                                                          oHistorialPagoEncabezado.hipa_SueldoNeto,
                                                                          oHistorialPagoEncabezado.hipa_FechaInicio,
                                                                          oHistorialPagoEncabezado.hipa_FechaFin,
                                                                          oHistorialPagoEncabezado.hipa_FechaPago,
                                                                          oHistorialPagoEncabezado.hipa_Anio,
                                                                          oHistorialPagoEncabezado.hipa_Mes,
                                                                          oHistorialPagoEncabezado.peri_IdPeriodo,
                                                                          oHistorialPagoEncabezado.hipa_UsuarioCrea,
                                                                          oHistorialPagoEncabezado.hipa_FechaCrea,
                                                                          oHistorialPagoEncabezado.hipa_TotalISR,
                                                                          oHistorialPagoEncabezado.hipa_ISRPendiente,
                                                                          oHistorialPagoEncabezado.hipa_AFP,
                                                                          // nuevos campos
                                                                          oHistorialPagoEncabezado.hipa_TotalHorasConPermisoJustificado,
                                                                          oHistorialPagoEncabezado.hipa_TotalComisiones,
                                                                          oHistorialPagoEncabezado.hipa_TotalHorasExtras,
                                                                          oHistorialPagoEncabezado.hipa_TotalVacaciones,
                                                                          oHistorialPagoEncabezado.hipa_TotalSeptimoDia,
                                                                          oHistorialPagoEncabezado.hipa_AdelantoSueldo,
                                                                          oHistorialPagoEncabezado.hipa_TotalSalario,
                                                                                                                                      // nuevos campos

                                                                          oHistorialPagoEncabezado.hipa_TotalDeduccionesIndividuales, // deducciones individuales
                                                                          oHistorialPagoEncabezado.hipa_TotalIngresosIndividuales,    // ingresos individuales
                                                                          oHistorialPagoEncabezado.hipa_TotalSueldoBruto,             // sueldo bruto
                                                                          oHistorialPagoEncabezado.hipa_CantidadUnidadesHorasExtras,  // cantidad unidades horas extras
                                                                          oHistorialPagoEncabezado.hipa_CantidadUnidadesBonos,        // cantidad unidades bonos
                                                                          oHistorialPagoEncabezado.hipa_TotalBonos,                   // total bonos
                                                                          codigoDePlanillaGenerada                                    // codigo identificador de la planilla
                                                                          );

                // obtener resultado del procedimiento almacenado
                foreach (UDP_Plani_tbHistorialDePago_Insert_Result Resultado in listHistorialPago)
                {
                    MensajeError = Resultado.MensajeError;
                }


                if (MensajeError.StartsWith("-1"))
                {
                    // el procedimiento almacenado falló
                    errores++;
                }
                // si el encabezado del historial de pago se registró correctamente, guardar los detalles
                else
                {
                    // guardar en el detalle de deducciones del historial de pago
                    foreach (var hisorialDeduccioneIterado in lisHistorialDeducciones)
                    {
                        int idDetalle = db.tbHistorialDeduccionPago
                                        .Select(x => x.hidp_IdHistorialdeDeduPago)
                                        .DefaultIfEmpty(0)
                                        .Max();

                        hisorialDeduccioneIterado.hidp_IdHistorialdeDeduPago = idDetalle + idDetalleDeduccionHisotorialesContador;
                        hisorialDeduccioneIterado.hipa_IdHistorialDePago     = int.Parse(MensajeError);
                        hisorialDeduccioneIterado.hidp_UsuarioCrea           = idUser;
                        hisorialDeduccioneIterado.hidp_FechaCrea             = DateTime.Now;
                        db.tbHistorialDeduccionPago.Add(hisorialDeduccioneIterado);
                        idDetalleDeduccionHisotorialesContador++;
                    }
                    // guardar en el detalle de ingresos del historial de pago
                    foreach (var hisorialIngresosIterado in lisHistorialIngresos)
                    {
                        int idDetalle = db.tbHistorialDeIngresosPago
                                        .Select(x => x.hip_IdHistorialDeIngresosPago)
                                        .DefaultIfEmpty(0)
                                        .Max();

                        hisorialIngresosIterado.hip_IdHistorialDeIngresosPago = idDetalle + idDetalleIngresoHisotorialesContador;
                        hisorialIngresosIterado.hipa_IdHistorialDePago        = int.Parse(MensajeError);
                        hisorialIngresosIterado.hip_FechaInicio = fechaInicio;
                        hisorialIngresosIterado.hip_FechaFinal  = fechaFin;
                        hisorialIngresosIterado.hip_UsuarioCrea = idUser;
                        hisorialIngresosIterado.hip_FechaCrea   = DateTime.Now;
                        db.tbHistorialDeIngresosPago.Add(hisorialIngresosIterado);
                        idDetalleIngresoHisotorialesContador++;
                    }
                }
            }
            catch (Exception ex)
            {
                listaErrores.Add(new ViewModelListaErrores
                {
                    Identidad         = InformacionDelEmpleadoActual.per_Identidad,
                    NombreColaborador = InformacionDelEmpleadoActual.per_Nombres,
                    Error             = "Error al guardar en el historial de pago",
                    PosibleSolucion   = "Verifique que la información del perfil del colaborador esté completa y/o correcta."
                });
                errores++;
            }

            contador++;
            #endregion
            return(idHistorialPago);
        }
Esempio n. 6
0
        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));
        }