public async Task Authorization_Should_Authorize() { using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); var identityWorkId = Guid.NewGuid(); var instanceID = Guid.NewGuid(); var employee = await new EmployeeManagerUT().CreateDefaultAsync <Employee>(identityWorkId, instanceID); var middlewareManager = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator()); var overdraftDetails = await middlewareManager.FindByExpressionAsync(p => p.InstanceID == instanceID && p.ConceptPayment.Name == "Sueldo", identityWorkId, new string[] { "Overdraft" }); var randomValue = new Random(15000); for (int i = 0; i < overdraftDetails.Count; i++) { overdraftDetails[i].Amount = Convert.ToDecimal(randomValue.NextDouble()); overdraftDetails[i].Taxed = Convert.ToDecimal(randomValue.NextDouble()); overdraftDetails[i].Exempt = Convert.ToDecimal(randomValue.NextDouble()); overdraftDetails[i].IMSSTaxed = Convert.ToDecimal(randomValue.NextDouble()); overdraftDetails[i].IMSSExempt = Convert.ToDecimal(randomValue.NextDouble()); } var middlewareDetailManager = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator()); await middlewareDetailManager.UpdateAsync(overdraftDetails, identityWorkId); var authManager = new AuthorizationManager(); var authParams = new AuthorizationParams() { IdentityWorkID = identityWorkId, InstanceID = instanceID, PeriodDetailIDToAuthorize = overdraftDetails.FirstOrDefault().Overdraft.PeriodDetailID }; await authManager.AuthorizationAsync(authParams); var middlewareHistoricAccumulatedEmployeeManager = new MiddlewareManager <HistoricAccumulatedEmployee>(new BaseRecordManager <HistoricAccumulatedEmployee>(), new HistoricAccumulatedEmployeeValidator()); //Total de acumulados por empleado var resultHistoric = await middlewareHistoricAccumulatedEmployeeManager.GetAllAsync(identityWorkId, instanceID, new string[] { "AccumulatedType" }); Assert.True(resultHistoric.Count == 33); //Overdraft after authorization var overdraftDetailsAfter = await middlewareManager.FindByExpressionAsync(p => p.Overdraft.EmployeeID == employee.FirstOrDefault().ID, identityWorkId, new string[] { "Overdraft" }); Assert.True(overdraftDetailsAfter.FirstOrDefault().Overdraft.PeriodDetailID != overdraftDetails.FirstOrDefault().Overdraft.PeriodDetailID); }
public void BeforeUpdate(List <Employee> lstObjectsToValidate) { //all good var validator = new RuleValidator <Employee>(); validator.ValidateRules(lstObjectsToValidate, createRules); var identityWorkId = lstObjectsToValidate.Select(p => p.company).FirstOrDefault(); var lstObjectsIdsToValidate = lstObjectsToValidate.Select(p => p.ID); //creates var employeeManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator()); var employeesPrevious = employeeManager.FindByExpressionAsync(p => lstObjectsIdsToValidate.Contains(p.ID), Guid.Empty).Result; ConcurrentBag <Employee> employeeChangedPeriod = new ConcurrentBag <Employee>(); Parallel.ForEach(lstObjectsToValidate, employeeToUpdate => { var previous = employeesPrevious.FirstOrDefault(p => p.ID == employeeToUpdate.ID); //Si cambia el periodo o cambia la fecha de ingreso se vuelve a crear su overdraft (delete and create) if (previous.PeriodTypeID != employeeToUpdate.PeriodTypeID || previous.EntryDate != employeeToUpdate.EntryDate) { employeeChangedPeriod.Add(employeeToUpdate); } }); //verify if employee changed period if (employeeChangedPeriod.Any()) { new OverdraftManager().UpdateByEmployeesAsync(employeeChangedPeriod.ToList()).Wait(); } }
public async Task <List <Overdraft> > UpdateByEmployeesAsync(List <Employee> employees) { //all good var identityWorkId = employees.FirstOrDefault().company; //Get the overdrafts to delete var employeesID = employees.Select(p => p.ID).ToList(); var middlewareManager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator()); var middlewareOverdraftDetailManager = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator()); var overdraftsToDelete = await middlewareManager.FindByExpressionAsync(p => employeesID.Contains(p.EmployeeID), identityWorkId); if (overdraftsToDelete.Any()) { //delete previous overdraft (no timbrados ni autorizados ni cancelados) var overdraftIds = overdraftsToDelete.Where(p => p.OverdraftStatus == OverdraftStatus.None).Select(p => p.ID).ToList(); if (overdraftIds.Any()) { await middlewareOverdraftDetailManager.DeleteByExpresssionAsync(p => overdraftIds.Contains(p.OverdraftID), identityWorkId); await middlewareManager.DeleteAsync(overdraftIds, identityWorkId); } } return(await CreateByEmployeesAsync(employees)); }
private async Task <List <NOMAnswer> > GetAnswers(Guid identityWorkId, Guid instanceId, Guid nomSurveyReplyId) { ConcurrentBag <NOMAnswer> concurrentCollection = new ConcurrentBag <NOMAnswer>(); var middlewareManager = new MiddlewareManager <NOMEvaluationQuestion>(new BaseRecordManager <NOMEvaluationQuestion>(), new NOMEvaluationQuestionValidator()); var nomQuestions = await middlewareManager.FindByExpressionAsync(x => x.Active == true, Guid.Empty); Parallel.ForEach(nomQuestions, question => { concurrentCollection.Add(new NOMAnswer() { ID = Guid.NewGuid(), Active = true, company = identityWorkId, Timestamp = DateTime.UtcNow, InstanceID = instanceId, Description = question.Description + " Answer", CreationDate = DateTime.Now, Name = question.Name + " Answer", StatusID = 1, Value = 1, NOMSurveyReplyID = nomSurveyReplyId, NOMEvaluationQuestionID = question.ID, }); }); return(concurrentCollection.ToList()); }
public async Task <EmployeeBenefitsDTO> GetEmployeeBenefits(string instanceID, string companyID, string employeeID) { var middlewareManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator()); var employee = (await middlewareManager.GetByIdsAsync(new List <Guid>() { Guid.Parse(employeeID) }, Guid.Parse(companyID), new string[] { })).FirstOrDefault(); var entryDate = employee.EntryDate; var employeeTrustLevel = employee.EmployeeTrustLevel == EmployeeTrustLevel.Unionized ? "Sindicalizado" : "Confianza"; var now = DateTime.Now; var currentYear = entryDate.Year - now.Year + 1; var benefitManager = new MiddlewareManager <BenefitType>(new BaseRecordManager <BenefitType>(), new BenefitTypeValidator()); var benefit = (await benefitManager.FindByExpressionAsync(x => x.Name == employeeTrustLevel && x.Antiquity == currentYear, Guid.Parse(companyID), new string[] { })).FirstOrDefault(); var res = new EmployeeBenefitsDTO() { VacationalBonusPerSeniority = Math.Round(benefit.HolidayPremiumPortion, 2).ToString(), VacationsPerSeniority = Math.Round(benefit.Holidays, 2).ToString(), YearlyBonusPerSeniority = Math.Round(benefit.DaysOfChristmasBonus, 2).ToString(), PendingVacationDays = "4", }; return(res); }
public async Task <IEnumerable <U> > Get(Expression <Func <T, bool> > predicate, Guid identityWorkID, string[] includes, IValidator <T> validator, IMapper mapper) { var mgr = new MiddlewareManager <T>(new BaseRecordManager <T>(), validator); var registers = await mgr.FindByExpressionAsync(predicate, identityWorkID, includes); return(mapper.Map <List <T>, List <U> >(registers)); }
public void BeforeDelete(List <Guid> lstObjectsToValidate) { var nullablelst = lstObjectsToValidate.Cast <Guid?>(); var employeeManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator()); var employees = employeeManager.FindByExpressionAsync(p => lstObjectsToValidate.Contains(p.ID) || nullablelst.Contains(p.ImmediateLeaderEmployeeID), Guid.Empty).Result; var employeesToDelete = employees.Where(x => lstObjectsToValidate.Contains(x.ID)); var employeesToSetLeaderNull = employees.Where(x => nullablelst.Contains(x.ImmediateLeaderEmployeeID)); if (null != employeesToDelete && employeesToDelete.Any()) { var statusToCheck = new List <OverdraftStatus>() { OverdraftStatus.Authorized, OverdraftStatus.Canceled, OverdraftStatus.Stamped }; var identityWorkId = employeesToDelete.FirstOrDefault().company; var instanceID = employeesToDelete.FirstOrDefault().InstanceID; var employeesIds = employeesToDelete.Select(p => p.ID); var overdreaftMiddlewareManager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator()); var overdrafts = overdreaftMiddlewareManager.FindByExpressionAsync(p => employeesIds.Contains(p.EmployeeID), identityWorkId, new string[] { "OverdraftDetails" }).Result; var badOverdrafts = overdrafts.Where(x => statusToCheck.Contains(x.OverdraftStatus)); if (badOverdrafts != null && badOverdrafts.Any()) { throw new CotorraException(106, "106", "No es posible eliminar al empleado, ya que tiene nóminas autorizadas timbradas o canceladas. Por favor revisa cambiar el status del empleado en lugar de eliminarlo.", null); } DeleteEmployeeInformation(lstObjectsToValidate, instanceID, identityWorkId); } }
public async Task <ActionResult <string> > GetTimeZoneByZipCode(string zipCode) { //Obtener los zipCodes var zipCodeMiddlewareManager = new MiddlewareManager <catCFDI_CodigoPostal>( new BaseRecordManager <catCFDI_CodigoPostal>(), new catCFDI_CodigoPostalValidator()); var zipCodes = await zipCodeMiddlewareManager.FindByExpressionAsync(p => p.c_CodigoPostal == zipCode , Guid.Empty); //Zip Code manager Dictionary <string, string> timeZones = new Dictionary <string, string>(); timeZones.Add("Tiempo del Centro", "Central Standard Time (Mexico)"); timeZones.Add("Tiempo del Pacífico", "Pacific Standard Time (Mexico)"); timeZones.Add("Tiempo del Pacífico en Frontera", "Pacific Standard Time"); timeZones.Add("Tiempo del Noroeste", "Mountain Standard Time (Mexico)"); timeZones.Add("Tiempo del Pacífico Sonora", "Pacific Standard Time (Mexico)"); timeZones.Add("Tiempo del Centro en Frontera", "Central Standard Time"); timeZones.Add("Tiempo del Noroeste en Frontera", "Pacific Standard Time"); timeZones.Add("Tiempo del Sureste", "Eastern Standard Time"); timeZones.TryGetValue(zipCodes.FirstOrDefault().DescripcionHusoHorario, out string timeZone); TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo(timeZone); var dateTimeNow = DateTime.Now; var result = TimeZoneInfo.ConvertTime(dateTimeNow, tzi); return(new JsonResult(new { timezone = timeZone, datetime = result })); }
public async Task Should_Create_NOMEvaluationQuestion_And_Get_ToValidate_Finally_do_Delete() { using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); //Arrange var identityWorkId = Guid.NewGuid(); var instanceId = Guid.NewGuid(); var NOMEvaluationQuestions = await new NOMEvaluationQuestionManagerUT().CreateDefaultAsync <NOMEvaluationQuestion>(identityWorkId, instanceId); //Act var middlewareManager = new MiddlewareManager <NOMEvaluationQuestion>(new BaseRecordManager <NOMEvaluationQuestion>(), new NOMEvaluationQuestionValidator()); //Asserts //Get var result = await middlewareManager .FindByExpressionAsync(p => p.ID == NOMEvaluationQuestions.FirstOrDefault().ID, Guid.Empty); Assert.True(result.Any()); //Delete await middlewareManager.DeleteAsync(NOMEvaluationQuestions.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.FirstOrDefault().ID == NOMEvaluationQuestions.FirstOrDefault().ID); //Get it again to verify if the registry it was deleted var result2 = await middlewareManager .GetByIdsAsync(NOMEvaluationQuestions.Select(p => p.ID).ToList(), identityWorkId); Assert.True(!result2.Any()); }
public async Task <List <T> > FindAsync(Expression <Func <T, bool> > predicate, Guid identityWorkId, string[] objectsToInclude = null) { var middlewareManager = new MiddlewareManager <T>(new BaseRecordManager <T>(), Validator); var lstReturn = await middlewareManager.FindByExpressionAsync(predicate, identityWorkId, objectsToInclude); return(lstReturn); }
public async Task ATS_Result_should_be_one_when_answer_phase_1_is_1_and_answer_phase_2_is_0_and_phase_3_has_more_than_2() { using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); //Arrange var identityWorkId = Guid.NewGuid(); var instanceId = Guid.NewGuid(); var employeeId = Guid.NewGuid(); var periodId = Guid.NewGuid(); var evaluationSurveyId = Guid.Parse("6EC14905-F634-418F-B0D2-EF2F315835E8");//ATS var middlewareManager = new NOMSurveyManager(); var nomSurveyReply = BuildNomSurveyReply(identityWorkId, instanceId, employeeId, periodId, evaluationSurveyId); var answerPhase1 = new NOMAnswerManagerUT().BuildAnswer(identityWorkId, instanceId, nomSurveyReply.ID); var answerPhase2 = new NOMAnswerManagerUT().BuildAnswer(identityWorkId, instanceId, nomSurveyReply.ID); var answerPhase31 = new NOMAnswerManagerUT().BuildAnswer(identityWorkId, instanceId, nomSurveyReply.ID); var answerPhase32 = new NOMAnswerManagerUT().BuildAnswer(identityWorkId, instanceId, nomSurveyReply.ID); var answerPhase33 = new NOMAnswerManagerUT().BuildAnswer(identityWorkId, instanceId, nomSurveyReply.ID); var nomEvaluationPhaseManager = new MiddlewareManager <NOMEvaluationPhase>(new BaseRecordManager <NOMEvaluationPhase>(), new NOMEvaluationPhaseValidator()); var aTSPhases = await nomEvaluationPhaseManager.FindByExpressionAsync(x => x.NOMEvaluationSurveyID == evaluationSurveyId && x.Active == true, Guid.Empty); var listATSPhasesIDs = aTSPhases.Select(x => x.ID); var PhaseI = aTSPhases.FirstOrDefault(x => x.Number == 1); var PhaseII = aTSPhases.FirstOrDefault(x => x.Number == 2); var PhaseIII = aTSPhases.FirstOrDefault(x => x.Number == 3); var questionMiddleWare = new MiddlewareManager <NOMEvaluationQuestion>(new BaseRecordManager <NOMEvaluationQuestion>(), new NOMEvaluationQuestionValidator()); var aTSQuestions = questionMiddleWare.FindByExpression(e => listATSPhasesIDs.Contains(e.NOMEvaluationPhaseID), Guid.Empty); var phaseIATSQuestions = questionMiddleWare.FindByExpression(e => e.Active && e.NOMEvaluationPhaseID == PhaseI.ID, Guid.Empty); var phaseIIATSQuestions = questionMiddleWare.FindByExpression(e => e.Active && e.NOMEvaluationPhaseID == PhaseII.ID, Guid.Empty); var phaseIIIATSQuestions = questionMiddleWare.FindByExpression(e => e.Active && e.NOMEvaluationPhaseID == PhaseIII.ID, Guid.Empty); answerPhase1.NOMEvaluationQuestionID = phaseIATSQuestions.FirstOrDefault().ID; answerPhase1.Value = 1; answerPhase2.NOMEvaluationQuestionID = phaseIIATSQuestions.FirstOrDefault().ID; answerPhase2.Value = 0; answerPhase31.NOMEvaluationQuestionID = phaseIIIATSQuestions.FirstOrDefault().ID; answerPhase31.Value = 1; answerPhase32.NOMEvaluationQuestionID = phaseIIIATSQuestions.FirstOrDefault().ID; answerPhase32.Value = 1; answerPhase33.NOMEvaluationQuestionID = phaseIIIATSQuestions.FirstOrDefault().ID; answerPhase33.Value = 1; //Act var processed = middlewareManager.ProcessFinalizationATS(nomSurveyReply, new List <NOMAnswer>() { answerPhase1, answerPhase2, answerPhase31, answerPhase32, answerPhase33 }, aTSQuestions, aTSPhases); //Arrange Assert.NotNull(processed); Assert.Equal(1, processed.Result); Assert.Equal(EvaluationStateType.Answered, processed.EvaluationState); }
private async Task ValidateInhabilitiesOnDate(Guid identityWorkID, Guid instanceID, Guid employeeID, List <Inhability> inhabilities) { var middlewareManager = new MiddlewareManager <Inhability>(new BaseRecordManager <Inhability>(), new InhabilityValidator()); var result = await middlewareManager.FindByExpressionAsync(p => p.InstanceID == instanceID && p.EmployeeID == employeeID , identityWorkID); inhabilities.ForEach(toSave => { var badEntities = result.Where(x => x.ID != toSave.ID && ((toSave.InitialDate >= x.InitialDate && toSave.FinalDate <= x.FinalDate) || (toSave.InitialDate >= x.InitialDate && toSave.InitialDate <= x.FinalDate) || (toSave.FinalDate <= x.FinalDate && toSave.FinalDate >= x.InitialDate))); if (badEntities.Any()) { throw new CotorraException(601, "601", "Ya se han registrado incapacidades en esas fechas para el empleado", null); } }); result.ForEach(toSave => { var badEntities = inhabilities.Where(x => x.ID != toSave.ID && ((toSave.InitialDate >= x.InitialDate && toSave.FinalDate <= x.FinalDate) || (toSave.InitialDate >= x.InitialDate && toSave.InitialDate <= x.FinalDate) || (toSave.FinalDate <= x.FinalDate && toSave.FinalDate >= x.InitialDate))); if (badEntities.Any()) { throw new CotorraException(601, "601", "Ya se han registrado incapacidades en esas fechas para el empleado", null); } }); }
/// <summary> /// Incidents Validation /// </summary> /// <param name="identityWorkID"></param> /// <param name="instanceID"></param> /// <param name="employeeID"></param> /// <param name="initialDate"></param> /// <returns></returns> private async Task ValidateIncidents(Guid identityWorkID, Guid instanceID, Guid employeeID, List <Inhability> inhabilities) { var incidentValidator = new IncidentValidator(); var middlewareManager = new MiddlewareManager <Incident>(new BaseRecordManager <Incident>(), incidentValidator); incidentValidator.MiddlewareManager = middlewareManager; var initialDate = inhabilities.Select(x => x.InitialDate); var finalDate = inhabilities.Select(x => x.FinalDate); var orderList = initialDate.OrderBy(p => p); var orderListFinal = finalDate.OrderBy(p => p); var result = await middlewareManager.FindByExpressionAsync(p => p.InstanceID == instanceID && p.EmployeeID == employeeID && p.Date.Date >= orderList.FirstOrDefault().Date && p.Date.Date <= orderListFinal.LastOrDefault().Date, identityWorkID); inhabilities.ForEach(toSave => { var badEntities = result.Where(x => (toSave.InitialDate <= x.Date && toSave.FinalDate >= x.Date)); if (badEntities.Any()) { throw new CotorraException(1, "1", $"Ya capturaste incidencias para la fecha de la incapacidad {badEntities.FirstOrDefault().Date.ToShortDateString()}", null); } }); }
public async Task <IReadOnlyList <Result <DepartmentDTO> > > GetDepartments(IReadOnlyList <IDDataloaderParam> data) { var instanceID = data.FirstOrDefault().instanceID; var companyID = data.FirstOrDefault().companyID; var ids = data.Select(x => Guid.Parse(x.id)).ToList(); List <Result <DepartmentDTO> > result = new List <Result <DepartmentDTO> >(); var config = new MapperConfiguration(cfg => { cfg.CreateMap <Department, DepartmentDTO>(); }); var _mapper = config.CreateMapper(); DepartmentDTO DepartmentDTO = new DepartmentDTO(); var middlewareManager = new MiddlewareManager <Department>(new BaseRecordManager <Department>(), new DepartmentValidator()); var departments = await middlewareManager.FindByExpressionAsync(p => p.InstanceID == Guid.Parse(instanceID) && p.company == Guid.Parse(companyID) && ids.Contains(p.ID) && p.Active, Guid.Empty); departments.ForEach(department => { var DepartmentDTO = _mapper.Map <Department, DepartmentDTO>(department); DepartmentDTO.Name = department.Name; result.Add(DepartmentDTO); }); return(result); }
public async Task <IReadOnlyList <Result <EmployeeDTO> > > GetEmplooyees(IReadOnlyList <IDDataloaderParam> data) { var instanceID = data.FirstOrDefault().instanceID; var companyID = data.FirstOrDefault().companyID; var ids = data.Select(x => Guid.Parse(x.id)).ToList(); List <Result <EmployeeDTO> > result = new List <Result <EmployeeDTO> >(); var config = new MapperConfiguration(cfg => { cfg.CreateMap <Employee, EmployeeDTO>(); }); var _mapper = config.CreateMapper(); EmployeeDTO employeeDTO = new EmployeeDTO(); var middlewareManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator()); var employees = await middlewareManager.FindByExpressionAsync(p => p.InstanceID == Guid.Parse(instanceID) && p.company == Guid.Parse(companyID) && ids.Contains(p.ID) && p.Active, Guid.Empty, new string[] { "JobPosition", "Department" }); employees.ForEach(employee => { var employeeDTO = _mapper.Map <Employee, EmployeeDTO>(employee); employeeDTO.DepartmentDTO.Name = employee.Department.Name; employeeDTO.JobPositionDTO.Name = employee.JobPosition.Name; result.Add(employeeDTO); }); return(result); }
public async Task SalaryAdjustment_Fail_PeriodClosed() { using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); Guid identityWorkId = Guid.NewGuid(); Guid instanceID = Guid.NewGuid(); try { var employee = await new EmployeeManagerUT().CreateDefaultAsync <Employee>( identityWorkId, instanceID); var middlewareManagerPeriodDetail = new MiddlewareManager <PeriodDetail>(new BaseRecordManager <PeriodDetail>(), new PeriodDetailValidator()); var periodDetails = await middlewareManagerPeriodDetail.FindByExpressionAsync(p => p.InstanceID == instanceID, identityWorkId); var CotorriaPeriodDetail = periodDetails.FirstOrDefault(); CotorriaPeriodDetail.PeriodStatus = PeriodStatus.Authorized; await middlewareManagerPeriodDetail.UpdateAsync(new List <PeriodDetail> { CotorriaPeriodDetail }, identityWorkId); Guid sbcID = Guid.NewGuid(); var creationDate = DateTime.Now; EmployeeSBCAdjustment sbc = BuildEmployeeSBCAdjustment(sbcID, Guid.NewGuid(), identityWorkId, instanceID, creationDate, employee.FirstOrDefault().ID, 123.23M, 123.23M, 123.23M); EmployeeSalaryIncrease employeeSalaryIncrease = new EmployeeSalaryIncrease() { Active = true, company = identityWorkId, CreationDate = creationDate, DailySalary = 145.65M, DeleteDate = null, Description = "", EmployeeID = employee.FirstOrDefault().ID, ID = Guid.NewGuid(), user = Guid.NewGuid(), InstanceID = instanceID, ModificationDate = periodDetails.OrderBy(p => p.InitialDate).FirstOrDefault().InitialDate.AddDays(2), Name = "", StatusID = 1, Timestamp = DateTime.Now, EmployeeSBCAdjustment = sbc, EmployeeSBCAdjustmentID = sbc.ID }; var middlewareManager = new MiddlewareManager <EmployeeSalaryIncrease>(new BaseRecordManager <EmployeeSalaryIncrease>()); await middlewareManager.CreateAsync(new List <EmployeeSalaryIncrease>() { employeeSalaryIncrease }, identityWorkId); Assert.True(true, "No debió de pasar"); } catch (CotorraException ex) { Assert.True(ex.Code == "4005"); } catch { Assert.True(true, "No debió de pasar"); } }
public async Task Should_Get_All() { using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); //Act var middlewareManager = new MiddlewareManager <NOMEvaluationPhase>(new BaseRecordManager <NOMEvaluationPhase>(), new NOMEvaluationPhaseValidator()); var all = await middlewareManager.FindByExpressionAsync(x => x.Active == true, Guid.Empty); Assert.True(all.Any()); }
public async Task <GetPreviewUrlResult> GetPreviewUrlByUUIDAsync(Guid instanceId, Guid UUID) { GetPreviewUrlResult result = new GetPreviewUrlResult(); result.UUID = UUID; BlobStorageUtil blobManagerUtil = new BlobStorageUtil(instanceId); await blobManagerUtil.InitializeAsync(); //check if XML exists if (await blobManagerUtil.ExistsFile($"{UUID.ToString()}.xml")) { result.XMLUri = blobManagerUtil.GetBlobSasUri(instanceId, $"{UUID.ToString()}.xml"); //check if PDF exists if (!await blobManagerUtil.ExistsFile($"{UUID.ToString()}.pdf")) { ////Transform var overdraftDetailManager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator()); var overdrafts = await overdraftDetailManager.FindByExpressionAsync(p => p.InstanceID == instanceId && p.UUID == UUID, Guid.Empty); var identityWorkId = overdrafts.FirstOrDefault().company; var previewTransformParams = new PreviewTransformParams() { FiscalStampingVersion = FiscalStampingVersion.CFDI33_Nom12, IdentityWorkID = identityWorkId, InstanceID = instanceId, PreviewTransformParamsDetails = new List <PreviewTransformParamsDetail>() { new PreviewTransformParamsDetail() { Overdraft = null, OverdraftID = overdrafts.FirstOrDefault().ID } }, }; var trasformationResult = await TransformAsync(previewTransformParams); var pdfResult = trasformationResult.PreviewTransformResultDetails.FirstOrDefault().TransformPDFResult; //Upload await blobManagerUtil.UploadDocumentAsync($"{UUID.ToString()}.pdf", pdfResult); } } else { throw new CotorraException(109, "109", "No fue posible recuperar el XML generado.", null); } result.PDFUri = blobManagerUtil.GetBlobSasUri(instanceId, $"{UUID.ToString()}.pdf"); return(result); }
private async Task <List <PayrollCompanyConfiguration> > getPayrollCompanyConfigurationAsync(PreviewTransformParams previewTransformParams) { var middlewarePayrollCompanyConfigurationManager = new MiddlewareManager <PayrollCompanyConfiguration>(new BaseRecordManager <PayrollCompanyConfiguration>(), new PayrollCompanyConfigurationValidator()); var payrollCompanyConfiguration = await middlewarePayrollCompanyConfigurationManager.FindByExpressionAsync(p => p.InstanceID == previewTransformParams.InstanceID && p.Active, previewTransformParams.IdentityWorkID); return(payrollCompanyConfiguration); }
public async Task Should_Get_ATSPhases() { using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); //Act var middlewareManager = new MiddlewareManager <NOMEvaluationPhase>(new BaseRecordManager <NOMEvaluationPhase>(), new NOMEvaluationPhaseValidator()); var ATS = await middlewareManager.FindByExpressionAsync(x => x.NOMEvaluationSurveyID == Guid.Parse("6EC14905-F634-418F-B0D2-EF2F315835E8") && x.Active == true, Guid.Empty); Assert.True(ATS.Any()); }
public async Task <NOMSurveyReply> GetAsync(string token, Guid identityWorkID) { var decode = HttpUtility.UrlDecode(token); Guid id = Guid.Parse(StringCipher.Decrypt(decode)); var middlewareManager = new MiddlewareManager <NOMSurveyReply>(new BaseRecordManager <NOMSurveyReply>(), new NOMSurveyReplyValidator()); var resultPrevious = await middlewareManager.FindByExpressionAsync(p => p.ID == id, identityWorkID, new string[] { "NOMAnswer" }); return(resultPrevious.FirstOrDefault()); }
public async Task DeleteAsync(List <Guid> id, Guid identityWorkID) { var nmAnswerMiddlewareManager = new MiddlewareManager <NOMAnswer>(new BaseRecordManager <NOMAnswer>(), new NOMAnswerValidator()); var answers = await nmAnswerMiddlewareManager.FindByExpressionAsync(p => id.Contains(p.NOMSurveyReplyID), identityWorkID); var middlewareManager = new MiddlewareManager <NOMSurveyReply>(new BaseRecordManager <NOMSurveyReply>(), new NOMSurveyReplyValidator()); await nmAnswerMiddlewareManager.DeleteAsync(answers.Select(p => p.ID).ToList(), identityWorkID); await middlewareManager.DeleteAsync(id, identityWorkID); }
public async Task <HistoricEmployeeSalaryAdjustment> UpdateModificationDateAsync(Guid employeeID, DateTime modifiedDate, Guid identityWorkID) { var middlewareHistoricAdjustmentManager = new MiddlewareManager <HistoricEmployeeSalaryAdjustment> (new BaseRecordManager <HistoricEmployeeSalaryAdjustment>(), new HistoricEmployeeSalaryAdjustmentValidator()); var historics = await middlewareHistoricAdjustmentManager.FindByExpressionAsync(p => p.EmployeeID == employeeID, identityWorkID); historics.FirstOrDefault().ModificationDate = modifiedDate; await middlewareHistoricAdjustmentManager.UpdateAsync(historics, identityWorkID); return(historics.FirstOrDefault()); }
public object BeforeDelete(List <Guid> lstObjectsToValidate, Guid identityWorkID) { //Desaplicar los ajustes de salario del periodo actual (si aplica) BeforeDeleteCommon(lstObjectsToValidate); var toDelete = MiddlewareManager.FindByExpressionAsync(x => lstObjectsToValidate.Contains(x.ID) && x.Active, Guid.Empty).Result; var sbcToDelete = _middlewareManagerSBCAdjustment.FindByExpression(x => toDelete.Select(y => y.EmployeeSBCAdjustmentID).Contains(x.ID), toDelete.FirstOrDefault().company); return(sbcToDelete); }
/// <summary> /// Payroll authorization /// </summary> /// <returns></returns> public async Task <List <Overdraft> > AuthorizationAsync(AuthorizationParams authorizationParams) { List <Overdraft> overdraftToCalculate = null; try { //VerifyPeriod - Si el periodo detalle siguiente no existe (porke fue el último) //habilitar el siguiente año await VerifyPeriod(authorizationParams); using (var connection = new SqlConnection(ConnectionManager.ConfigConnectionString)) { if (connection.State != ConnectionState.Open) { await connection.OpenAsync(); } using (var command = connection.CreateCommand()) { command.CommandType = CommandType.StoredProcedure; command.CommandText = "AuthorizeOverdraft"; command.Parameters.AddWithValue("@PeriodDetailId", authorizationParams.PeriodDetailIDToAuthorize); command.Parameters.AddWithValue("@InstanceId", authorizationParams.InstanceID); command.Parameters.AddWithValue("@company", authorizationParams.IdentityWorkID); command.Parameters.AddWithValue("@user", authorizationParams.user); //Execute SP de autorización await command.ExecuteNonQueryAsync(); } } //Encontrar los nuevos sobre recibos para hacerles el cálculo var periodDetailManager = new MiddlewareManager <PeriodDetail>(new BaseRecordManager <PeriodDetail>(), new PeriodDetailValidator()); var periodDetail = await periodDetailManager.FindByExpressionAsync(p => p.PeriodStatus == PeriodStatus.Calculating, authorizationParams.IdentityWorkID); var lstPeriodIds = periodDetail.Select(p => p.PeriodID); //11. Calculation overdrafts (Fire and Forget) await new OverdraftCalculationManager().CalculationFireAndForgetByPeriodIdsAsync(lstPeriodIds, authorizationParams.IdentityWorkID, authorizationParams.InstanceID, authorizationParams.user); } catch (Exception ex) { Trace.WriteLine($"Ocurrió un error al autorizar la nómina: {ex.ToString()}"); throw new CotorraException(70000, "70000", "Ocurrió un error al autorizar la nómina", ex); } return(overdraftToCalculate); }
public async Task Should_Create_Overdraft_And_Get_ToValidate_Finally_do_Delete() { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled); //Act Guid identityWorkId = Guid.NewGuid(); Guid instanceId = Guid.NewGuid(); var middlewareManager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator()); var overdr = await middlewareManager.FindByExpressionAsync(p => p.ID == Guid.Parse("24062420-7C73-4453-B837-A9B25AC26595"), identityWorkId, new string[] { "OverdraftDetails" }); var detail = overdr.FirstOrDefault().OverdraftDetails .Where(p => p.ID == Guid.Parse("c1314de9-13cf-4531-8641-23b04a4ce187")); var middlewareManagerDetail = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator()); var detail2 = await middlewareManagerDetail.FindByExpressionAsync(p => p.ID == Guid.Parse("c1314de9-13cf-4531-8641-23b04a4ce187"), identityWorkId); var overdrafts = await new OverdraftManagerUT().CreateDefaultOverdraftAsync(identityWorkId, instanceId); //Asserts //Get var result = await middlewareManager .GetByIdsAsync(overdrafts.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.Any()); //Delete var middlewareOverdraftDetailManager = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator()); await middlewareOverdraftDetailManager.DeleteAsync(overdrafts.SelectMany(p => p.OverdraftDetails).Select(p => p.ID).ToList(), identityWorkId); await middlewareManager.DeleteAsync(overdrafts.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.FirstOrDefault().ID == overdrafts.FirstOrDefault().ID); //Get it again to verify if the registry it was deleted var result2 = await middlewareManager .GetByIdsAsync(overdrafts.Select(p => p.ID).ToList(), identityWorkId); Assert.False(result2.Any()); }
public async Task DispatchAsync(Guid actionID, Guid idRegister) { var middlewareManager = new MiddlewareManager <Action>(new BaseRecordGeneralManager <Action>(), new ActionValidator()); var action = (await middlewareManager .FindByExpressionAsync(p => p.ID == actionID && p.Active == true, Guid.Empty, new string[] { "ActionSubscriptions" })).FirstOrDefault(); IDataResolver dataResolver = DataResolverFactory.GetResolver(action); var data = await dataResolver.ResolveDataAsync(action, idRegister); DisperseAsync(action.ActionSubscriptions, data); }
public async Task <List <T> > CreateDefaultAsync <T>(Guid identityWorkId, Guid instanceId) where T : BaseEntity { var middlewareEmployeeManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator()); var employees = (await middlewareEmployeeManager.FindByExpressionAsync(p => p.Active && p.InstanceID == instanceId, identityWorkId)); if (!employees.Any()) { employees = (await new EmployeeManagerUT().CreateDefaultAsync <Employee>(identityWorkId: identityWorkId, instanceID: instanceId)); } var middlewareConceptManager = new MiddlewareManager <ConceptPayment>(new BaseRecordManager <ConceptPayment>(), new ConceptPaymentValidator()); var concepts = (await middlewareConceptManager.FindByExpressionAsync(p => p.Active && p.InstanceID == instanceId, identityWorkId)); if (!concepts.Any()) { concepts = (await new ConceptManagerUT().CreateDefaultSalaryPaymentConceptsAsync(identityWorkId, instanceId)); } var fonacotMovements = new List <FonacotMovement>(); fonacotMovements.Add(new FonacotMovement() { ID = Guid.NewGuid(), Active = true, company = identityWorkId, Timestamp = DateTime.UtcNow, InstanceID = instanceId, Description = "Departamento de nominas", CreationDate = DateTime.Now, Name = "Nominas", StatusID = 1, ConceptPaymentID = concepts.FirstOrDefault().ID, CreditNumber = "AA010101", DeleteDate = null, EmployeeID = employees.FirstOrDefault().ID, FonacotMovementStatus = FonacotMovementStatus.Active, Month = 1, Year = 2020, Observations = "Observations", RetentionType = RetentionType.FixedAmount, user = Guid.Empty, }); var middlewareManager = new MiddlewareManager <FonacotMovement>(new BaseRecordManager <FonacotMovement>(), new FonacotMovementValidator()); await middlewareManager.CreateAsync(fonacotMovements, identityWorkId); return(fonacotMovements as List <T>); }
public async Task <List <T> > CreateDefaultAsync <T>(Guid identityWorkId, Guid instanceID) where T : BaseEntity { var permanentMovements = new List <PermanentMovement>(); List <ConceptPayment> conceptPayments = null; var employees = await(new EmployeeManagerUT().CreateDefaultAsync <Employee>(identityWorkId: identityWorkId, instanceID: instanceID, randomValues: true)); var middlewareConceptPaymentManager = new MiddlewareManager <ConceptPayment>(new BaseRecordManager <ConceptPayment>(), new ConceptPaymentValidator()); conceptPayments = await middlewareConceptPaymentManager.FindByExpressionAsync(p => p.InstanceID == instanceID, identityWorkId); if (!conceptPayments.Any()) { conceptPayments = await(new ConceptManagerUT().CreateDefaultSalaryPaymentConceptsAsync(identityWorkId, instanceID)); } permanentMovements.Add(new PermanentMovement() { AccumulatedAmount = 0, Active = true, Amount = 500, company = identityWorkId, ConceptPaymentID = conceptPayments.FirstOrDefault(p => p.ConceptType == ConceptType.SalaryPayment && p.Name == "Sueldo").ID, EmployeeID = employees.FirstOrDefault().ID, ControlNumber = 0, CreationDate = DateTime.UtcNow, DeleteDate = null, Description = "", ID = Guid.NewGuid(), InitialApplicationDate = DateTime.UtcNow, LimitAmount = 0, Name = "Movimiento permamente sueldito", PermanentMovementStatus = PermanentMovementStatus.Active, PermanentMovementType = PermanentMovementType.Amount, RegistryDate = DateTime.UtcNow, StatusID = 1, TimesApplied = 0, TimesToApply = 5, user = Guid.NewGuid(), InstanceID = instanceID, Timestamp = DateTime.UtcNow }); var middlewareManager = new MiddlewareManager <PermanentMovement>(new BaseRecordManager <PermanentMovement>(), new PermanentMovementValidator()); await middlewareManager.CreateAsync(permanentMovements, identityWorkId); return(permanentMovements as List <T>); }
/// <summary> /// Incident Type Validations /// </summary> /// <param name="identityWorkID"></param> /// <param name="instanceID"></param> /// <param name="employeeID"></param> /// <param name="incidentTypeIds"></param> /// <returns></returns> private async Task ValidateIncidentType(Guid identityWorkID, Guid instanceID, Guid employeeID, List <Guid> incidentTypeIds) { var incidentTypeValidator = new IncidentTypeValidator(); var middlewareManager = new MiddlewareManager <IncidentType>(new BaseRecordManager <IncidentType>(), incidentTypeValidator); incidentTypeValidator.MiddlewareManager = middlewareManager; var result = await middlewareManager.FindByExpressionAsync(p => p.InstanceID == instanceID && incidentTypeIds.Contains(p.ID) && p.ItConsiders != ItConsiders.Inhability, identityWorkID); if (result.Any()) { throw new CotorraException(2, "2", $"El tipo de incidente no puede ser diferente el campo Considera al valor Incapacidad, verifique {result.FirstOrDefault().ID}", null); } }