コード例 #1
0
 /*Obtener el catalogo de planillas, el catalogo de ingresos de la planilla
  * y el catalogo de deducciones de la planilla, filtrando por el id de la planilla*/
 private string ObtenerCatalogoDePlanilla(int?id, string response, out tbCatalogoDePlanillas tbCatalogoDePlanillas)
 {
     response = "ok";
     tbCatalogoDePlanillas = db.tbCatalogoDePlanillas.Find(id); //Buscar por el id en el catalogo de planillas
     return(response);
 }
コード例 #2
0
        /*Obtener el catalogo de planillas, el catalogo de ingresos de la planilla
         * y el catalogo de deducciones de la planilla, filtrando por el id de la planilla*/
        private string ObtenerCatalogoDePlanillaIngresosDeducciones(int?id, string response, out tbCatalogoDePlanillas tbCatalogoDePlanillas, out List <CatalogoDeIngresosDeduccionesViewModel> listaCatalogoIngresos, out List <CatalogoDeIngresosDeduccionesViewModel> listaCatalogoDeducciones)
        {
            #region Declaración de variables
            IEnumerable <object> listCatalogoDeDeducciones = null;                          //Aqui se almacena la lista del catalogo de deducciones
            IEnumerable <object> listCatalogoDeIngresos    = null;                          //Aqui se almacena la lista del catalogo de ingresos

            listaCatalogoIngresos    = new List <CatalogoDeIngresosDeduccionesViewModel>(); //Generar la salida del catalogo de ingresos
            listaCatalogoDeducciones = new List <CatalogoDeIngresosDeduccionesViewModel>(); //Generar salida del catalogo de deducciones
            #endregion

            tbCatalogoDePlanillas = db.tbCatalogoDePlanillas.Find(id); //Buscar por el id en el catalogo de planillas
            try
            {
                #region Obtener el catalogo de ingresos
                listCatalogoDeIngresos = db.UDP_Plani_CatalogoDeIngresosEdit_Select(id); //Obtener la lista del catalogo de ingresos filtrando por el id de la planilla

                //Recorrer el resultado de la variable listCatalogoDeIngresos
                foreach (UDP_Plani_CatalogoDeIngresosEdit_Select_Result result in listCatalogoDeIngresos)
                {
                    CatalogoDeIngresosDeduccionesViewModel catalogoIngresos = new CatalogoDeIngresosDeduccionesViewModel(); //Almacenar los ingresos de la planilla
                    catalogoIngresos.id          = result.cin_IdIngreso;                                                    //Se utilizara para identificar que checkbox ha sido clickeado
                    catalogoIngresos.descripcion = result.cin_DescripcionIngreso;                                           //Descripcion del ingreso

                    //Si la propiedad checked del resultado es verdadera entonces sera true, caso contrario false, esto para saber cuando marcar el checkbox
                    if (result.@checked == 1)
                    {
                        catalogoIngresos.check = true;
                    }
                    else
                    {
                        catalogoIngresos.check = false;
                    }

                    //Agregar a la lista del catalogo de ingresos el objeto que se acaba de crear
                    listaCatalogoIngresos.Add(catalogoIngresos);
                }
                #endregion

                #region Obtener el catalogo de deducciones
                //Obtener la lista del catalogo de deducciones filtrando por el id de la planilla
                listCatalogoDeDeducciones = db.UDP_Plani_CatalogoDeduccionesEdit_Select(id);

                //Recorrer el resultado de la variable listCatalogoDeDeducciones
                foreach (UDP_Plani_CatalogoDeduccionesEdit_Select_Result result in listCatalogoDeDeducciones.ToList())
                {
                    CatalogoDeIngresosDeduccionesViewModel catalogoDeduccion = new CatalogoDeIngresosDeduccionesViewModel(); //Almacenar las deducciones de la planilla
                    catalogoDeduccion.id          = result.cde_IdDeducciones;                                                //Se utilizara para identificar que checkbox ha sido clickeado
                    catalogoDeduccion.descripcion = result.cde_DescripcionDeduccion;                                         //Descripcion de la deducción

                    //Si la propiedad checked del resultado es verdadera entonces sera true, caso contrario false, esto para saber cuando marcar el checkbox
                    if (result.@checked == 1)
                    {
                        catalogoDeduccion.check = true;
                    }
                    else
                    {
                        catalogoDeduccion.check = false;
                    }

                    //Agregar a la lista del catalogo de ingresos el objeto que se acaba de crear
                    listaCatalogoDeducciones.Add(catalogoDeduccion);
                }
                #endregion
            }
            catch (Exception)
            {
                response = "error"; //Retornar con un error en el lado del cliente
            }

            return(response);
        }
コード例 #3
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));
        }
コード例 #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
            });
        }
コード例 #5
0
        public ActionResult PrevisualizarPlanilla(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 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;
            #endregion

            #region inicia proceso de previsualizacion 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();
                    }

                    // procesar todas las planillas seleccionadas
                    foreach (var iter in oIDSPlanillas)
                    {
                        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();


                            // procesar planilla empleado por empleado
                            foreach (var empleadoActual in oEmpleados)
                            {
                                using (var dbContextTransaccion = db.Database.BeginTransaction())
                                {
                                    try
                                    {
                                        #region inicia proceso de previsualización

                                        #region variables reporte view model

                                        string codColaborador = string.Empty,
                                         nombreColaborador    = string.Empty,
                                         tipoPlanilla         = string.Empty;

                                        decimal SalarioBase  = 0,
                                                salarioHora  = 0,
                                                totalSalario = 0,
                                                totalISR     = 0,
                                                totalAFP     = 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();
                                        string moneda = db.tbSueldos.Where(x => x.emp_Id == empleadoActual.emp_Id).Select(x => x.tbTipoMonedas.tmon_Descripcion).FirstOrDefault();

                                        #endregion

                                        V_InformacionColaborador InformacionDelEmpleadoActual;
                                        decimal resultSeptimoDia = 0;
                                        int     userId           = (int)Session["UserLogin"];

                                        // procesa ingresos
                                        Ingresos.PrevisualizarProcesarIngresos(userId,
                                                                               fechaInicio,
                                                                               fechaFin,
                                                                               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,
                                                                               out InformacionDelEmpleadoActual,
                                                                               out resultSeptimoDia);

                                        // procesar deducciones
                                        Deducciones.PrevisualizarProcesarDeducciones(tmon_IdMonedaDeduccionesDePlanilla,
                                                                                     monedas,
                                                                                     userId,
                                                                                     fechaInicio,
                                                                                     fechaFin,
                                                                                     listaErrores,
                                                                                     ref errores,
                                                                                     db,
                                                                                     oDeducciones,
                                                                                     empleadoActual,
                                                                                     SalarioBase,
                                                                                     totalIngresosEmpleado,
                                                                                     ref colaboradorDeducciones,
                                                                                     ref totalAFP,
                                                                                     ref totalInstitucionesFinancieras,
                                                                                     ref totalOtrasDeducciones,
                                                                                     ref adelantosSueldo,
                                                                                     out totalDeduccionesEmpleado,
                                                                                     ref totalDeduccionesIndividuales,
                                                                                     out netoAPagarColaborador,
                                                                                     InformacionDelEmpleadoActual);

                                        //Deducciones.ProcesarDeduccionesParaPrevisualizacion(fechaInicio, fechaFin, db, oDeducciones, empleadoActual, SalarioBase, totalIngresosEmpleado, ref colaboradorDeducciones, ref totalAFP, ref totalInstitucionesFinancieras, ref totalOtrasDeducciones, ref adelantosSueldo, out totalDeduccionesEmpleado, ref totalDeduccionesIndividuales, out netoAPagarColaborador);

                                        // procesar isr
                                        TimeSpan tDias = fechaFin - fechaInicio;
                                        totalISR = CalculoISR.CalcularISR(db, empleadoActual, totalSalario, totalISR, tDias.Days + 1);

                                        #region crear registro de la planilla del colaborador para el reporte

                                        // reporte
                                        ReportePlanilla.ReportePlanillaPrevisualizacion(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;
                                        #endregion


                                        #endregion
                                    }
                                    // catch por si hubo un error al generar la planilla de un empleado
                                    catch (Exception ex)
                                    {
                                        // mensaje del error en el registro del colaborador
                                        errores++;
                                    }
                                }
                            }
                        }
                        // catch si se produjo un error al procesar una sola planilla
                        catch (Exception ex)
                        {
                            errores++;
                        }
                    }
                }

                // 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   = "El proceso de generación de planillas falló, contacte al adminstrador.";
                response.Encabezado = "Error";
                response.Tipo       = "error";
            }
            #endregion

            // retornar resultado del proceso
            return(Json(new { Data = reporte, listaDeErrores = listaErrores, Response = response }, JsonRequestBehavior.AllowGet));
        }