private async Task SaveIMSSEmployeeTableDefaultAsync(InitializationParams initializationParams, Guid companyID, Guid instanceID, Guid user)
        {
            var memoryTest        = new MemoryStorageContext();
            var result            = memoryTest.GetDefaultIMSSEmployeeTable(companyID, instanceID, user);
            var middlewareManager = new MiddlewareManager <IMSSEmployeeTable>(new BaseRecordManager <IMSSEmployeeTable>(),
                                                                              new IMSSEmployeeTableValidator());

            await middlewareManager.CreateAsync(result, companyID);
        }
        private async Task SaveAnualIncomeTaxDefaultAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user)
        {
            var memoryTest        = new MemoryStorageContext();
            var result            = memoryTest.GetDefaultAnualIncomeTax(companyID, instanceID, user);
            var middlewareManager = new MiddlewareManager <AnualIncomeTax>(new BaseRecordManager <AnualIncomeTax>(),
                                                                           new AnualIncomeTaxValidator());

            await middlewareManager.CreateAsync(result, companyID);
        }
        private async Task SaveSettlementCatalogDefaultAsync(InitializationParams initializationParams, Guid companyID, Guid instanceID, Guid user)
        {
            var memoryTest        = new MemoryStorageContext();
            var result            = memoryTest.GetDefaultSettlementCatalogTable(companyID, instanceID, user);
            var middlewareManager = new MiddlewareManager <SettlementCatalog>(new BaseRecordManager <SettlementCatalog>(),
                                                                              new SettlementCatalogValidator());

            await middlewareManager.CreateAsync(result, companyID);
        }
        private async Task SaveMonthlyEmploymentSubsidyDefaultAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user)
        {
            var memoryTest        = new MemoryStorageContext();
            var result            = memoryTest.GetDefaultMonthlyEmploymentSubsidy(companyID, instanceID, user);
            var middlewareManager = new MiddlewareManager <MonthlyEmploymentSubsidy>(new BaseRecordManager <MonthlyEmploymentSubsidy>(),
                                                                                     new MonthlyEmploymentSubsidyValidator());

            await middlewareManager.CreateAsync(result, companyID);
        }
        private async Task <List <IncidentTypeRelationship> > SaveIncidentTypeRelationshipDefaultAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user, List <IncidentType> incidentTypes)
        {
            var memoryTest        = new MemoryStorageContext();
            var result            = memoryTest.GetDefaultIncidentTypeRelationship(companyID, instanceID, user, incidentTypes);
            var middlewareManager = new MiddlewareManager <IncidentTypeRelationship>(new BaseRecordManager <IncidentTypeRelationship>(),
                                                                                     new IncidentTypeRelationshipValidator());

            await middlewareManager.CreateAsync(result, companyID);

            return(result);
        }
        private async Task <List <AccumulatedType> > SaveAccumulatedTypeDefaultAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user)
        {
            var memoryTest        = new MemoryStorageContext();
            var result            = memoryTest.GetDefaultAccumulatedType(companyID, instanceID, user);
            var middlewareManager = new MiddlewareManager <AccumulatedType>(new BaseRecordManager <AccumulatedType>(),
                                                                            new AccumulatedTypeValidator());

            await middlewareManager.CreateAsync(result, companyID);

            return(result);
        }
        private async Task <List <Overdraft> > GetOverdraftsAsync(Guid instanceID, Guid identityWorkID, Guid periodDetailID, List <OverdraftStatus> statusOverdrafts, int bankCode)
        {
            var manager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator());


            var overdrafts = await manager.FindByExpressionAsync(x => x.InstanceID == instanceID &&
                                                                 x.OverdraftType == OverdraftType.Ordinary && statusOverdrafts.Contains(x.OverdraftStatus) &&
                                                                 x.PeriodDetailID == periodDetailID && x.Employee.Bank.Code == bankCode,
                                                                 identityWorkID, new string[] { "OverdraftDetails", "OverdraftDetails.ConceptPayment", "Employee" });

            return(overdrafts);
        }
Exemple #8
0
        public EmployeeConceptsRelationDetailManager()
        {
            _mgrEmployeeConceptsRelationDetail = new MiddlewareManager <EmployeeConceptsRelationDetail>(
                new BaseRecordManager <EmployeeConceptsRelationDetail>(),
                new EmployeeConceptsRelationDetailValidator()
                );

            _clientOverdraftDetail = new MiddlewareManager <OverdraftDetail>(
                new BaseRecordManager <OverdraftDetail>(),
                new OverdraftDetailValidator()
                );
        }
        private async Task <List <Overdraft> > GetOverdrafts(Guid employeeID, Guid instanceID, Guid identityWorkID, List <OverdraftType> overdraftType)
        {
            var manager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator());
            List <Overdraft> overdrafts = null;

            overdrafts = await manager.FindByExpressionAsync(x =>
                                                             x.InstanceID == instanceID &&
                                                             x.EmployeeID == employeeID &&
                                                             overdraftType.Contains(x.OverdraftType) &&
                                                             x.OverdraftStatus == OverdraftStatus.None,
                                                             identityWorkID, new string[] { "OverdraftDetails", "OverdraftDetails.ConceptPayment" });

            return(overdrafts);
        }
        private async Task DeleteOverdrafts(List <Overdraft> overdrafts, Guid identityWorkID)
        {
            if (overdrafts != null && overdrafts.Any())
            {
                var detailManager = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator());
                var overManager   = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator());

                var detailToDelete = overdrafts.SelectMany(x => x.OverdraftDetails).Select(x => x.ID).ToList();

                if (detailToDelete.Any())
                {
                    await detailManager.DeleteAsync(detailToDelete, identityWorkID);
                }

                await overManager.DeleteAsync(overdrafts.Select(x => x.ID).ToList(), identityWorkID);
            }
        }
        private async Task <List <Overdraft> > GetOverdrafts(Guid employeeID, Guid instanceID, Guid identityWorkID, Guid periodDetailID, List <OverdraftType> overdraftType)
        {
            var manager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator());
            List <Overdraft> overdrafts = null;

            if (periodDetailID != Guid.Empty)
            {
                overdrafts = await manager.FindByExpressionAsync(x => x.InstanceID == instanceID && x.EmployeeID == employeeID &&
                                                                 x.PeriodDetailID == periodDetailID && overdraftType.Contains(x.OverdraftType) &&
                                                                 x.OverdraftStatus == OverdraftStatus.None,
                                                                 identityWorkID, new string[] { "OverdraftDetails", "OverdraftDetails.ConceptPayment" });
            }
            else
            {
                throw new CotorraException(108, "108", "No se estableció el periodo correspondiente", null);
            }
            return(overdrafts);
        }
Exemple #12
0
        private async Task <List <Overdraft> > GetOverdraftByIDs(List <Guid> ids, Guid identityWorkID)
        {
            var manager    = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator());
            var overdrafts = await manager.FindByExpressionAsync(p =>
                                                                 ids.Contains(p.ID) &&
                                                                 p.company == identityWorkID &&
                                                                 p.Active,
                                                                 identityWorkID, new string[] {
                "OverdraftDetails",
                "OverdraftDetails.ConceptPayment",
                "PeriodDetail",
                "PeriodDetail.Period",
                "Employee",
                "Employee.HistoricEmployeeSalaryAdjustments",
            });

            return(overdrafts);
        }
        private async Task SaveEmployerRegistrationAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user)
        {
            if (parameters.EmployerRegistration != null && parameters.EmployerRegistration.ID != Guid.Empty)
            {
                parameters.EmployerRegistration.CompanyID  = companyID;
                parameters.EmployerRegistration.InstanceID = instanceID;
                parameters.EmployerRegistration.company    = companyID;
                parameters.EmployerRegistration.user       = user;
                parameters.EmployerRegistration.Name       = parameters.EmployerRegistration.Code;

                var result = new List <EmployerRegistration> {
                    parameters.EmployerRegistration
                };
                var middlewareManager = new MiddlewareManager <EmployerRegistration>(new BaseRecordManager <EmployerRegistration>(),
                                                                                     new EmployerRegistrationValidator());

                await middlewareManager.CreateAsync(result, companyID);
            }
        }
        public async Task <List <Overdraft> > Calculate(CalculateSettlementProcessParams parameters)
        {
            Guid identityWorkID = parameters.IdentityWorkID;
            Guid instanceId     = parameters.InstanceID;
            Guid periodDetailID = parameters.PeriodDetailID;
            Guid employeeID     = parameters.EmployeeID;
            var  oversGenerated = new List <Overdraft>();

            var codes = parameters.ConceptsToApply.Select(x => x.Code).ToList();

            codes.Add(ISRFINIQUITOCONCEPTCODE);

            var allConcepts = await GetAllConceptsSettlement(codes, COMPENSATIONSATCODES, identityWorkID,
                                                             instanceId);

            var employeeManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator());
            var employee        = employeeManager.FindByExpressionAsync(x => x.ID == employeeID && x.InstanceID == instanceId && x.Active == true, identityWorkID);

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var previousSettlementOverdrafts = await GetOverdrafts(parameters.EmployeeID,
                                                                       parameters.InstanceID, parameters.IdentityWorkID,
                                                                       new List <OverdraftType>() { OverdraftType.OrdinarySettlement,
                                                                                                    OverdraftType.CompensationSettlement });
                await UpdateEmployee(parameters, (await employee).FirstOrDefault());

                await DeleteOverdrafts(previousSettlementOverdrafts, parameters.IdentityWorkID);

                oversGenerated.Add(await GenerateOrdinaryOverdraft(parameters, allConcepts));
                var compensation = await GenerateCompensationOverdraft(parameters, allConcepts);

                if (compensation != null)
                {
                    oversGenerated.Add(compensation);
                }

                scope.Complete();
            }

            oversGenerated.ForEach(over => over.OverdraftDetails = over.OverdraftDetails.OrderBy(x => x.ConceptPayment.Code).ToList());
            return(oversGenerated);
        }
        private async Task <List <PeriodType> > SavePeriodTypeDefaultAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user)
        {
            var memoryTest = new MemoryStorageContext();
            List <PeriodType> lstPeriodTypes = new List <PeriodType>();

            //Quincenal
            var forceUpdate = parameters.PayrollCompanyConfiguration.PaymentPeriodicity == PaymentPeriodicity.Biweekly;

            lstPeriodTypes.AddRange(memoryTest.GetDefaultPeriodType(companyID, instanceID, user,
                                                                    PaymentPeriodicity.Biweekly,
                                                                    parameters.PayrollCompanyConfiguration.PaymentDays,
                                                                    parameters.PayrollCompanyConfiguration.AdjustmentPay, forceUpdate));

            //Mensual
            forceUpdate = parameters.PayrollCompanyConfiguration.PaymentPeriodicity == PaymentPeriodicity.Monthly;
            lstPeriodTypes.AddRange(memoryTest.GetDefaultPeriodType(companyID, instanceID, user,
                                                                    PaymentPeriodicity.Monthly,
                                                                    parameters.PayrollCompanyConfiguration.PaymentDays,
                                                                    parameters.PayrollCompanyConfiguration.AdjustmentPay, forceUpdate));

            //Semanal
            forceUpdate = parameters.PayrollCompanyConfiguration.PaymentPeriodicity == PaymentPeriodicity.Weekly;
            lstPeriodTypes.AddRange(memoryTest.GetDefaultPeriodType(companyID, instanceID, user,
                                                                    PaymentPeriodicity.Weekly,
                                                                    parameters.PayrollCompanyConfiguration.PaymentDays,
                                                                    parameters.PayrollCompanyConfiguration.AdjustmentPay, forceUpdate, parameters.PayrollCompanyConfiguration.WeeklySeventhDay));

            //Extraordinario
            forceUpdate = parameters.PayrollCompanyConfiguration.PaymentPeriodicity == PaymentPeriodicity.OtherPeriodicity;
            lstPeriodTypes.AddRange(memoryTest.GetDefaultPeriodType(companyID, instanceID, user,
                                                                    PaymentPeriodicity.OtherPeriodicity,
                                                                    parameters.PayrollCompanyConfiguration.PaymentDays,
                                                                    parameters.PayrollCompanyConfiguration.AdjustmentPay, forceUpdate));

            var middlewareManager = new MiddlewareManager <PeriodType>(new BaseRecordManager <PeriodType>(),
                                                                       new PeriodTypeValidator());

            await middlewareManager.CreateAsync(lstPeriodTypes, companyID);

            return(lstPeriodTypes);
        }
        private async Task SavePeriodDefaultAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user,
                                                  List <PeriodType> periodTypes)
        {
            var memoryTest = new MemoryStorageContext();

            var result = memoryTest.GetDefaultPeriod(companyID, instanceID, user,
                                                     parameters.PayrollCompanyConfiguration.PeriodInitialDate,
                                                     parameters.PayrollCompanyConfiguration.PeriodInitialDate.AddYears(1).Date,
                                                     parameters.PayrollCompanyConfiguration.CurrentExerciseYear,
                                                     periodTypes.FirstOrDefault(p => p.PaymentPeriodicity == parameters.PayrollCompanyConfiguration.PaymentPeriodicity));

            result.AddRange(memoryTest.GetDefaultPeriod(companyID, instanceID, user,
                                                        parameters.PayrollCompanyConfiguration.PeriodInitialDate,
                                                        parameters.PayrollCompanyConfiguration.PeriodInitialDate.AddYears(1).Date,
                                                        parameters.PayrollCompanyConfiguration.CurrentExerciseYear,
                                                        periodTypes.FirstOrDefault(p => p.ExtraordinaryPeriod)));

            var middlewareManager = new MiddlewareManager <Period>(new BaseRecordManager <Period>(),
                                                                   new PeriodValidator());

            await middlewareManager.CreateAsync(result, companyID);
        }
        private async Task SaveConceptPaymentDefaultAsync(InitializationParams parameters, Guid companyID, Guid instanceID, Guid user, List <AccumulatedType> accumulatedTypes)
        {
            //Get Memory Default Data
            var memoryTest  = new MemoryStorageContext();
            var resultTuple = memoryTest.GetDefaultConcept <ConceptPayment>(companyID, instanceID, user, accumulatedTypes);

            //Results
            var resultConcepts     = resultTuple.Item1.Cast <ConceptPayment>().ToList();
            var resultRelationship = resultTuple.Item2.ToList();

            //middlewareManagers
            var middlewareManager = new MiddlewareManager <ConceptPayment>(new BaseRecordManager <ConceptPayment>(),
                                                                           new ConceptPaymentValidator());

            var middlewareManagerConceptPaymentRelationship = new MiddlewareManager <ConceptPaymentRelationship>(new BaseRecordManager <ConceptPaymentRelationship>(),
                                                                                                                 new ConceptPaymentRelationshipValidator());

            //Create ConceptPayment
            await middlewareManager.CreateAsync(resultConcepts, companyID);

            //Create ConceptPayment relationship with accumulates
            await middlewareManagerConceptPaymentRelationship.CreateAsync(resultRelationship, companyID);
        }
        /// <summary>
        /// Create or Get the EmployeeIdentiyRegistration
        /// </summary>
        /// <param name="middlewareManagerRegis"></param>
        /// <param name="employee"></param>
        /// <param name="company"></param>
        /// <returns></returns>
        private async Task <EmployeeIdentityRegistration> createEmployeeIdentityRegistration(MiddlewareManager <EmployeeIdentityRegistration> middlewareManagerRegis,
                                                                                             Employee employee, Guid company)
        {
            var currentProcess = await middlewareManagerRegis.FindByExpressionAsync(p =>
                                                                                    p.EmployeeID == employee.ID && p.Email == employee.Email &&
                                                                                    p.EmployeeIdentityRegistrationStatus != EmployeeIdentityRegistrationStatus.Completed, company);

            List <EmployeeIdentityRegistration> lstToCreate = null;

            //No debe de existir un registro pendiente
            //Paso 1. Crear el registro
            if (!currentProcess.Any())
            {
                lstToCreate = new List <EmployeeIdentityRegistration>()
                {
                    new EmployeeIdentityRegistration()
                    {
                        Active       = true,
                        CreationDate = DateTime.UtcNow,
                        DeleteDate   = null,
                        Description  = "",
                        Email        = employee.Email,
                        EmployeeID   = employee.ID,
                        ID           = Guid.NewGuid(),
                        EmployeeIdentityRegistrationStatus = EmployeeIdentityRegistrationStatus.MailSent,
                        ActivationCode = CodeGenerator.GetRandomCode(8),
                        IdentityUserID = null,
                        Name           = "",
                        StatusID       = 1,
                        Timestamp      = DateTime.UtcNow
                    }
                };
                await middlewareManagerRegis.CreateAsync(lstToCreate, company);
            }
            else
            {
                //El registro ya se relacionó correctamente
                lstToCreate = currentProcess;
            }

            return(lstToCreate.FirstOrDefault());
        }
Exemple #19
0
        /// <summary>
        /// Generates the settlement letter indicates writer.
        /// </summary>
        /// <param name="activeOverdraft">The active overdraft.</param>
        /// <param name="identityWorkID">The identity work identifier.</param>
        /// <param name="instanceID">The instance identifier.</param>
        /// <param name="writer">The writer.</param>
        /// <returns></returns>
        public async Task <string> GenerateSettlementLetter(List <Overdraft> activeOverdrafts, Guid identityWorkID, Guid instanceID, string token, IMSSpreadsheetWriter writer)
        {
            var instanceMgr = new InstanceManager();
            var instance    = await instanceMgr.GetByIDAsync(token, instanceID);

            var payrrollCompanyConfigurationMgr = new MiddlewareManager <PayrollCompanyConfiguration>(
                new BaseRecordManager <PayrollCompanyConfiguration>(),
                new PayrollCompanyConfigurationValidator());

            var address = (await payrrollCompanyConfigurationMgr.FindByExpressionAsync(x => x.InstanceID == instanceID,
                                                                                       identityWorkID, new string[] { "Address" })).FirstOrDefault().Address;
            var fullAddress = string.Empty;

            if (address != null)
            {
                fullAddress = $" {address.Street}, {address.ZipCode}, {address.Municipality}, {address.FederalEntity}";
            }

            var overdraftManager         = new OverdraftManager();
            OverdraftTotalsResult totals = new OverdraftTotalsResult();

            activeOverdrafts.ForEach(activeOverdraft =>
            {
                var totalSalaryPayments = activeOverdraft.OverdraftDetails.Where(p => p.ConceptPayment.ConceptType == ConceptType.SalaryPayment &&
                                                                                 p.ConceptPayment.Print &&
                                                                                 !p.ConceptPayment.Kind).
                                          Select(y => y.Amount).Sum();



                var totalDeductionPayments = activeOverdraft.OverdraftDetails.Where(p => p.ConceptPayment.ConceptType == ConceptType.DeductionPayment &&
                                                                                    p.ConceptPayment.Print &&
                                                                                    !p.ConceptPayment.Kind).
                                             Select(y => y.Amount).Sum();


                totals.TotalSalaryPayments    += Math.Round(totalSalaryPayments, 2);
                totals.TotalDeductionPayments += Math.Round(totalDeductionPayments, 2);
                totals.Total += Math.Round(totals.TotalSalaryPayments - totals.TotalDeductionPayments, 2);
            });

            string header =
                $"Recibí de la empresa {instance.Name} con domicilio en \n" +
                $"{fullAddress} " +
                $"la cantidad de: \n";
            string header2 = " por concepto de mi finiquito con motivo de la terminación\n" +
                             "de mi relación laboral con la empresa con fecha indicada en el documento, cantidad \n" +
                             "que resulta de los siguientes conceptos:";

            string footer =
                "Así mismo manifiesto que hasta el momento en que se da por terminada la relación laboral\n" +
                "no se me adeuda ninguna cantidad de dinero por concepto de salarios devengados,\n" +
                "diferencia de los mismos, participacion de utilidades, comisiones, horas extras, \n" +
                "vacaciones, septimos días, días festivos, prima dominical, vacacional y de antigüedad\n" +
                "y demás prestaciones que otorga la Ley Federal Del Trabajo, ya que las mismas siempre\n" +
                "me fueron íntegramente cubiertas en los términos de la ley. También hago constar para\n" +
                "todos los efectos legales conducentes, que durante la vigencia de mi relación\n" +
                "obrero-patronal no fui objeto de riesgo profesional alguno, motivo por el cual libero\n" +
                "a mi patron de toda responsabilidad laboral y de seguridad\n" +
                "social o de cualquier otro concpeto derivado del contrato de trabajo.";
            string date = DateTime.Now.ToString("MM/dd/yyyy");



            var newHeader = ConcatenateHeader(header, header2, totals);
            var filename  = "CartaFiniquito - " + activeOverdrafts.FirstOrDefault().Employee.FullName + ".xlsx";

            IWorkbook wb  = GenerateSettlementLetter(activeOverdrafts, newHeader, footer, date, activeOverdrafts.FirstOrDefault().Employee.FullName, totals);
            var       url = await WriteSettlementLetterAsync(instanceID, filename, wb, writer);

            return(url);
        }
        public async Task <PayrollStampingResult> PayrollIndividualStampingAsync(PayrollIndividualStampingParams payrollIndividualStampingParams)
        {
            //Obtiene todos los historic overdrafts del periodo seleccionado
            var historicOverdraftManager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(),
                                                                             new OverdraftValidator());
            var incidentsManager = new MiddlewareManager <Incident>(new BaseRecordManager <Incident>(),
                                                                    new IncidentValidator());
            var inhabilitiesManager = new MiddlewareManager <Inhability>(
                new BaseRecordManager <Inhability>(),
                new InhabilityValidator());

            var historicOverdraftsToStamp = await historicOverdraftManager.FindByExpressionAsync(p =>
                                                                                                 p.company == payrollIndividualStampingParams.IdentityWorkID &&
                                                                                                 p.InstanceID == payrollIndividualStampingParams.InstanceID &&
                                                                                                 p.PeriodDetailID == payrollIndividualStampingParams.PeriodDetailID &&
                                                                                                 p.ID == payrollIndividualStampingParams.OverdraftID &&
                                                                                                 p.OverdraftStatus == OverdraftStatus.Authorized &&
                                                                                                 p.Active,
                                                                                                 payrollIndividualStampingParams.IdentityWorkID, new string[] {
                "OverdraftPreviousCancelRelationship",
                "OverdraftDetails",
                "OverdraftDetails.ConceptPayment",
                "PeriodDetail",
                "PeriodDetail.Period",
                "HistoricEmployee",
                "HistoricEmployee.Employee",
                "HistoricEmployee.Employee.Workshift",
                "HistoricEmployee.Employee.EmployerRegistration"
            });

            var incidents = await incidentsManager.FindByExpressionAsync(p =>
                                                                         p.PeriodDetailID == payrollIndividualStampingParams.PeriodDetailID &&
                                                                         p.InstanceID == payrollIndividualStampingParams.InstanceID,
                                                                         payrollIndividualStampingParams.IdentityWorkID,
                                                                         new string[] { "IncidentType" });

            var initialDate = historicOverdraftsToStamp.FirstOrDefault().PeriodDetail.InitialDate;
            var finalDate   = historicOverdraftsToStamp.FirstOrDefault().PeriodDetail.FinalDate;

            //Incapacidades dentro del periodo
            var inhabilities = await inhabilitiesManager.FindByExpressionAsync(p =>
                                                                               p.InstanceID == payrollIndividualStampingParams.InstanceID &&
                                                                               (
                                                                                   (p.InitialDate >= initialDate && p.InitialDate.AddDays(p.AuthorizedDays - 1) <= finalDate) ||
                                                                                   (p.InitialDate >= initialDate && p.InitialDate.AddDays(p.AuthorizedDays - 1) > finalDate) ||
                                                                                   (p.InitialDate < initialDate && p.InitialDate.AddDays(p.AuthorizedDays - 1) <= finalDate) ||
                                                                                   (p.InitialDate <initialDate && p.InitialDate.AddDays(p.AuthorizedDays - 1)> finalDate)
                                                                               ),
                                                                               payrollIndividualStampingParams.IdentityWorkID);

            //Obtiene la información fiscal del patrón, certificados
            var employerFiscalInformationManager = new MiddlewareManager <EmployerFiscalInformation>(new BaseRecordManager <EmployerFiscalInformation>(),
                                                                                                     new EmployerFiscalInformationValidator());
            var employerFiscalInformations = await employerFiscalInformationManager.FindByExpressionAsync(p =>
                                                                                                          p.company == payrollIndividualStampingParams.IdentityWorkID &&
                                                                                                          p.InstanceID == payrollIndividualStampingParams.InstanceID,
                                                                                                          payrollIndividualStampingParams.IdentityWorkID);

            if (!employerFiscalInformations.Any())
            {
                throw new CotorraException(105, "105", "No se han configurado los certificados (CSD) de la empresa para poder timbrar. Ve al menú Catálogos -> Certificados -> Agregar nuevo", null);
            }

            //Obtiene la configuración general de la empresa
            var payrollCompanyConfigurationManager = new MiddlewareManager <PayrollCompanyConfiguration>(new BaseRecordManager <PayrollCompanyConfiguration>(),
                                                                                                         new PayrollCompanyConfigurationValidator());
            var payrollConfigurations = await payrollCompanyConfigurationManager.FindByExpressionAsync(p =>
                                                                                                       p.company == payrollIndividualStampingParams.IdentityWorkID &&
                                                                                                       p.InstanceID == payrollIndividualStampingParams.InstanceID, payrollIndividualStampingParams.IdentityWorkID,
                                                                                                       new string[] { "Address" });

            if (!historicOverdraftsToStamp.Any())
            {
                throw new CotorraException(101, "101", "No hay ningún sobrerecibo a timbrar en estatus autorizado, con los parámetros proporcionados.", null);
            }

            var payrollStampingParams = _mapper.Map <PayrollIndividualStampingParams, PayrollStampingParams>(payrollIndividualStampingParams);

            return(await payrollStampingCoreAsync(payrollStampingParams,
                                                  historicOverdraftsToStamp, incidents, inhabilities,
                                                  employerFiscalInformations, payrollConfigurations));
        }
        public async Task <List <Vacation> > BreakAsync(Vacation vacation, Guid identityWorkID, Guid instanceID, HolidayPaymentConfiguration config)
        {
            var             initialVacationDate = vacation.InitialDate;
            var             finalVacationDate   = vacation.FinalDate;
            List <Vacation> result = new List <Vacation>();
            MiddlewareManager <PeriodType> middlewareManager         = new MiddlewareManager <PeriodType>(new BaseRecordManager <PeriodType>(), new PeriodTypeValidator());
            MiddlewareManager <Employee>   employeeMiddlewareManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator());

            var employee = (await employeeMiddlewareManager.FindByExpressionAsync(p => p.ID == vacation.EmployeeID &&
                                                                                  p.Active == true && p.InstanceID == instanceID, identityWorkID, new string[] { "PeriodType", "PeriodType.Periods", "PeriodType.Periods.PeriodDetails" })).FirstOrDefault();

            var periodTypes = employee.PeriodType;

            if (periodTypes != null)
            {
                var allDetails = periodTypes.Periods.SelectMany(x => x.PeriodDetails).ToList();

                var periodDetails = allDetails.Where(p =>
                                                     (initialVacationDate >= p.InitialDate &&
                                                      initialVacationDate <= p.FinalDate) ||
                                                     (finalVacationDate >= p.FinalDate &&
                                                      p.InitialDate >= initialVacationDate) ||
                                                     finalVacationDate >= p.InitialDate &&
                                                     finalVacationDate <= p.FinalDate).OrderBy("InitialDate").ToList();

                var totalCards = periodDetails.Count();

                if (totalCards == 1)
                {
                    result.Add(vacation);
                    return(result);
                }

                int index = 0;
                periodDetails.ForEach(periodDetail =>
                {
                    Vacation clonedVacation = (Vacation)vacation.Clone();
                    clonedVacation.ID       = Guid.NewGuid();
                    if (index == 0)
                    {
                        if (periodDetail.InitialDate != initialVacationDate)
                        {
                            clonedVacation.InitialDate = initialVacationDate;
                        }
                        else
                        {
                            clonedVacation.InitialDate = periodDetail.InitialDate;
                        }
                        clonedVacation.FinalDate = periodDetail.FinalDate;
                    }

                    else if (index == totalCards - 1)
                    {
                        if (periodDetail.FinalDate != finalVacationDate)
                        {
                            clonedVacation.FinalDate = finalVacationDate;
                        }
                        else
                        {
                            clonedVacation.FinalDate = periodDetail.FinalDate;
                        }
                        clonedVacation.InitialDate = periodDetail.InitialDate;
                    }
                    else
                    {
                        clonedVacation.InitialDate = periodDetail.InitialDate;
                        clonedVacation.FinalDate   = periodDetail.FinalDate;
                    }

                    index++;
                    result.Add(clonedVacation);
                    SetDaysOffAndVacationDays(clonedVacation, vacation, config);
                });


                return(result);
            }

            return(result);
        }
        private async Task <PayrollStampingResult> payrollStampingCoreAsync(PayrollStampingParams payrollStampingParams,
                                                                            List <Overdraft> historicOverdraftsToStamp,
                                                                            List <Incident> incidents,
                                                                            List <Inhability> inhabilities,
                                                                            List <EmployerFiscalInformation> employerFiscalInformations,
                                                                            List <PayrollCompanyConfiguration> payrollConfigurations)
        {
            var payrollStampingResult = new PayrollStampingResult();

            List <string> zipCodesToFind =
                historicOverdraftsToStamp.Select(p => p.HistoricEmployee.EmployerRegistrationZipCode).ToList();

            zipCodesToFind.AddRange(payrollConfigurations.Select(p => p.Address?.ZipCode));

            //Obtener los zipCodes
            var zipCodeMiddlewareManager = new MiddlewareManager <catCFDI_CodigoPostal>(
                new BaseRecordManager <catCFDI_CodigoPostal>(),
                new catCFDI_CodigoPostalValidator());
            var zipCodes = await zipCodeMiddlewareManager.FindByExpressionAsync(p =>
                                                                                zipCodesToFind.Contains(p.c_CodigoPostal)
                                                                                , payrollStampingParams.IdentityWorkID);

            //Round for currency
            var roundUtil = new RoundUtil(payrollStampingParams.Currency.ToString());

            //Zip Code manager
            var zipCodeManager = new ZipCodeManager(zipCodes);

            //Blob Storage Util
            var blobStorageUtil = new BlobStorageUtil(payrollStampingParams.InstanceID);
            await blobStorageUtil.InitializeAsync();

            ISendMailProvider sendMailProvider = FactoryMailProvider.CreateInstance(SendMailProvider.SendGrid);

            var tasks = new List <Task <List <PayrollStampingResultDetail> > >();

            foreach (var overdraftToStamp in historicOverdraftsToStamp)
            {
                tasks.Add(doWorkAsync(overdraftToStamp, roundUtil, zipCodeManager,
                                      payrollStampingParams, blobStorageUtil, sendMailProvider, incidents,
                                      inhabilities, employerFiscalInformations, payrollConfigurations));
            }

            ConcurrentBag <PayrollStampingResultDetail> payrollStampingDetails = new ConcurrentBag <PayrollStampingResultDetail>();

            foreach (var task in await Task.WhenAll(tasks))
            {
                foreach (var insideTask in task)
                {
                    payrollStampingDetails.Add(insideTask);
                }
            }
            payrollStampingResult.PayrollStampingResultDetails = payrollStampingDetails.ToList();

            //Update DB indicate that Overdraft was stamped correctly / PeriodDetail
            await saveOverdraftStampedAsync(payrollStampingParams, payrollStampingResult);

            //Errors preparation
            if (payrollStampingResult.PayrollStampingResultDetails.Any(p => p.PayrollStampingResultStatus == PayrollStampingResultStatus.Fail))
            {
                var errorMessages = payrollStampingResult.PayrollStampingResultDetails.Select(p => p.Message);
                throw new CotorraException(109, "109", string.Join("\n", errorMessages), null);
            }

            return(payrollStampingResult);
        }
 private async Task SaveOverdraft(Overdraft settlementOverdraft, Guid identityWorkID)
 {
     var manager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator());
     await manager.CreateAsync(new List <Overdraft>() { settlementOverdraft }, identityWorkID);
 }
 private async Task UpdateEmployee(CalculateSettlementProcessParams parameters, Employee employee)
 {
     employee.SettlementSalaryBase = parameters.SettlementBaseSalary;
     var employeeManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator());
     await employeeManager.UpdateAsync(new List <Employee>() { employee }, parameters.IdentityWorkID);
 }
Exemple #25
0
        public async Task <CancelPayrollStampingResult> CancelPayrollStampingAsync(CancelPayrollStampingParams cancelPayrollStampingParams)
        {
            //Create cancelation instance
            ICancelStamping cancelStamping = CancelStampingFactory.CreateInstance(cancelPayrollStampingParams.FiscalStampingVersion);

            //Get overdrafts and validate
            var overdraftMiddlewareManager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(),
                                                                               new OverdraftValidator());
            var overdraftsIds      = cancelPayrollStampingParams.OverdraftIDs;
            var overdraftsToCancel = await overdraftMiddlewareManager.FindByExpressionAsync(p =>
                                                                                            p.company == cancelPayrollStampingParams.IdentityWorkID &&
                                                                                            p.InstanceID == cancelPayrollStampingParams.InstanceID &&
                                                                                            overdraftsIds.Contains(p.ID) &&
                                                                                            p.OverdraftStatus == OverdraftStatus.Stamped &&
                                                                                            p.Active,
                                                                                            cancelPayrollStampingParams.IdentityWorkID);

            if (!overdraftsToCancel.Any())
            {
                throw new CotorraException(106, "106", "No existen recibos a cancelar con los datos proporcionados.", null);
            }

            //Get configuration company
            var payrollMiddlewareManager = new MiddlewareManager <PayrollCompanyConfiguration>(new BaseRecordManager <PayrollCompanyConfiguration>(),
                                                                                               new PayrollCompanyConfigurationValidator());
            var payrollCompanyConfiguration = await payrollMiddlewareManager.FindByExpressionAsync(p => p.InstanceID == cancelPayrollStampingParams.InstanceID,
                                                                                                   cancelPayrollStampingParams.IdentityWorkID, new string[] { "Address" });

            if (!payrollCompanyConfiguration.Any())
            {
                throw new CotorraException(106, "106", "No existe configuración de la compañia.", null);
            }

            //Get configuration company
            var fiscalInformationManager = new MiddlewareManager <EmployerFiscalInformation>(new BaseRecordManager <EmployerFiscalInformation>(),
                                                                                             new EmployerFiscalInformationValidator());
            var employerFiscalInformations = await fiscalInformationManager.FindByExpressionAsync(p =>
                                                                                                  p.InstanceID == cancelPayrollStampingParams.InstanceID,
                                                                                                  cancelPayrollStampingParams.IdentityWorkID);

            if (!employerFiscalInformations.Any())
            {
                throw new CotorraException(106, "106", "No hay certificados válidos registrados para la compañia.", null);
            }

            //Zipcode Manager
            IEnumerable <string> zipCodesToFind = payrollCompanyConfiguration.Select(p => p.Address?.ZipCode);
            var zipCodeMiddlewareManager        = new MiddlewareManager <catCFDI_CodigoPostal>(
                new BaseRecordManager <catCFDI_CodigoPostal>(),
                new catCFDI_CodigoPostalValidator());
            var zipCodes = await zipCodeMiddlewareManager.FindByExpressionAsync(p =>
                                                                                zipCodesToFind.Contains(p.c_CodigoPostal)
                                                                                , cancelPayrollStampingParams.IdentityWorkID);

            if (!zipCodes.Any())
            {
                throw new CotorraException(106, "106", "No hay codigo postal registrado para la compañia.", null);
            }

            //UUIDs to Cancel
            var uuids = overdraftsToCancel.Select(p => p.UUID).ToList();

            //3. Sign XML
            var certificateCER = employerFiscalInformations.FirstOrDefault().CertificateCER;
            var certificateKey = employerFiscalInformations.FirstOrDefault().CertificateKEY;
            var certPassword   = employerFiscalInformations.FirstOrDefault().CertificatePwd;

            //Decrypt and get certificate
            (var certificatebytesCER, var certificatebytesKEY, var certPasswordResult) = Crypto(cancelPayrollStampingParams,
                                                                                                certificateCER, certificateKey, certPassword);

            //Cancel Document Details
            var cancelDocumentParamsDetails = new List <CancelDocumentParamsDetail>();

            uuids.ForEach(p =>
            {
                var cancelDetail         = new CancelDocumentParamsDetail();
                cancelDetail.OverdraftID = overdraftsToCancel.FirstOrDefault(q => q.UUID == p).ID;
                cancelDetail.UUID        = p;
                cancelDocumentParamsDetails.Add(cancelDetail);
            });

            CancelDocumentParams cancelDocumentParams = new CancelDocumentParams()
            {
                ZipCodes       = zipCodes,
                IssuerZipCode  = payrollCompanyConfiguration.FirstOrDefault().Address?.ZipCode,
                IssuerRFC      = payrollCompanyConfiguration.FirstOrDefault().RFC,
                CertificateCER = certificatebytesCER,
                CertificateKey = certificatebytesKEY,
                Password       = certPasswordResult,
                IdentityWorkID = cancelPayrollStampingParams.IdentityWorkID,
                InstanceID     = cancelPayrollStampingParams.InstanceID,
                user           = cancelPayrollStampingParams.user,
                CancelDocumentParamsDetails = cancelDocumentParamsDetails
            };

            //cancel cfdi document
            var result = await cancelStamping.CancelDocumetAsync(cancelDocumentParams);

            if (result.WithErrors)
            {
                throw new CotorraException(107, "107", $"Error al cancelar el recibo: {result.Message}", null);
            }

            //Fill Save Cancelation Object
            var cancelationRequestXMLID  = Guid.NewGuid();
            var cancelationResponseXMLID = Guid.NewGuid();

            var cancelSPFiscalParams = new List <CancelationStoreProcedureParams>();

            result.CancelPayrollStampingResultDetails.ForEach(p => {
                var cancelationStoreProcedure         = new CancelationStoreProcedureParams();
                cancelationStoreProcedure.OverdraftID = overdraftsToCancel.FirstOrDefault(q => q.UUID == p.UUID).ID;
                cancelationStoreProcedure.CancelationFiscalDocumentStatus =
                    p.PayrollStampingResultStatus == PayrollStampingResultStatus.Success ?
                    CancelationFiscalDocumentStatus.Done : CancelationFiscalDocumentStatus.ErrorInRequest;
                cancelSPFiscalParams.Add(cancelationStoreProcedure);
            });

            //Database
            await saveCancelFiscalStamping(cancelPayrollStampingParams, cancelationRequestXMLID, cancelationResponseXMLID, cancelSPFiscalParams);

            //Save XML of cancelation  in blob (request)
            var blobStorageUtil = new BlobStorageUtil(cancelDocumentParams.InstanceID);
            await blobStorageUtil.InitializeAsync();

            await blobStorageUtil.UploadDocumentAsync($"{cancelationRequestXMLID}.xml", result.CancelacionXMLRequest);

            //Save XML of cancelation acknowledgement in blob (response)
            await blobStorageUtil.InitializeAsync();

            await blobStorageUtil.UploadDocumentAsync($"{cancelationResponseXMLID}.xml", result.CancelacionXMLAcknowledgeResponse);

            return(result);
        }