From 76bdc664961042d97e48d29c369c399477d65c0e Mon Sep 17 00:00:00 2001 From: Miguel Lehmann Date: Tue, 19 Nov 2024 20:05:17 +0100 Subject: [PATCH] run backend formatter and start fixing lint changes --- .../src/main/java/ch/puzzle/okr/ErrorKey.java | 5 +- .../puzzle/okr/FlywayMultitenantConfig.java | 1 + .../java/ch/puzzle/okr/ForwardFilter.java | 17 +- .../java/ch/puzzle/okr/OkrApplication.java | 4 +- .../okr/OkrApplicationContextInitializer.java | 1 + .../ch/puzzle/okr/OkrErrorAttributes.java | 5 +- .../ch/puzzle/okr/OpenAPI30Configuration.java | 12 +- .../java/ch/puzzle/okr/SecurityConfig.java | 59 ++- .../ch/puzzle/okr/SpringCachingConfig.java | 1 + .../java/ch/puzzle/okr/UserKeyGenerator.java | 7 +- .../okr/controller/ActionController.java | 19 +- .../okr/controller/AlignmentController.java | 30 +- .../okr/controller/CacheController.java | 12 +- .../okr/controller/CheckInController.java | 54 +- .../controller/ClientConfigController.java | 6 +- .../okr/controller/CompletedController.java | 24 +- .../okr/controller/KeyResultController.java | 70 +-- .../okr/controller/ObjectiveController.java | 76 +-- .../okr/controller/OverviewController.java | 35 +- .../okr/controller/QuarterController.java | 27 +- .../puzzle/okr/controller/TeamController.java | 85 ++- .../puzzle/okr/controller/UserController.java | 53 +- .../okr/deserializer/CheckInDeserializer.java | 21 +- .../deserializer/KeyResultDeserializer.java | 23 +- .../java/ch/puzzle/okr/dto/ActionDto.java | 5 +- .../ch/puzzle/okr/dto/ClientConfigDto.java | 6 +- .../main/java/ch/puzzle/okr/dto/ErrorDto.java | 9 +- .../java/ch/puzzle/okr/dto/ObjectiveDto.java | 10 +- .../main/java/ch/puzzle/okr/dto/UserDto.java | 6 +- .../ch/puzzle/okr/dto/checkin/CheckInDto.java | 1 + .../okr/dto/checkin/CheckInMetricDto.java | 11 +- .../okr/dto/checkin/CheckInOrdinalDto.java | 12 +- .../okr/dto/keyresult/KeyResultDto.java | 5 +- .../KeyResultLastCheckInMetricDto.java | 6 +- .../KeyResultLastCheckInOrdinalDto.java | 10 +- .../okr/dto/keyresult/KeyResultMetricDto.java | 15 +- .../dto/keyresult/KeyResultOrdinalDto.java | 17 +- .../overview/OverviewKeyResultMetricDto.java | 6 +- .../overview/OverviewKeyResultOrdinalDto.java | 7 +- .../OverviewLastCheckInMetricDto.java | 5 +- .../OverviewLastCheckInOrdinalDto.java | 5 +- .../dto/overview/OverviewObjectiveDto.java | 9 +- .../exception/OkrResponseStatusException.java | 9 +- .../ch/puzzle/okr/mapper/ActionMapper.java | 35 +- .../okr/mapper/AlignmentSelectionMapper.java | 37 +- .../ch/puzzle/okr/mapper/CompletedMapper.java | 8 +- .../ch/puzzle/okr/mapper/ObjectiveMapper.java | 39 +- .../ch/puzzle/okr/mapper/OverviewMapper.java | 106 ++-- .../java/ch/puzzle/okr/mapper/TeamMapper.java | 8 +- .../java/ch/puzzle/okr/mapper/UserMapper.java | 36 +- .../okr/mapper/checkin/CheckInMapper.java | 7 +- .../mapper/checkin/CheckInMetricMapper.java | 40 +- .../mapper/checkin/CheckInOrdinalMapper.java | 41 +- .../okr/mapper/keyresult/KeyResultMapper.java | 11 +- .../keyresult/KeyResultMetricMapper.java | 110 ++-- .../keyresult/KeyResultOrdinalMapper.java | 111 ++-- .../java/ch/puzzle/okr/models/Action.java | 25 +- .../java/ch/puzzle/okr/models/Completed.java | 14 +- .../java/ch/puzzle/okr/models/Objective.java | 59 ++- .../java/ch/puzzle/okr/models/Quarter.java | 17 +- .../main/java/ch/puzzle/okr/models/Team.java | 14 +- .../main/java/ch/puzzle/okr/models/User.java | 28 +- .../java/ch/puzzle/okr/models/UserTeam.java | 19 +- .../okr/models/alignment/Alignment.java | 10 +- .../models/alignment/AlignmentSelection.java | 22 +- .../alignment/AlignmentSelectionId.java | 4 +- .../models/alignment/KeyResultAlignment.java | 3 +- .../models/alignment/ObjectiveAlignment.java | 5 +- .../authorization/AuthorizationUser.java | 23 +- .../ch/puzzle/okr/models/checkin/CheckIn.java | 49 +- .../okr/models/checkin/CheckInMetric.java | 8 +- .../okr/models/checkin/CheckInOrdinal.java | 8 +- .../okr/models/keyresult/KeyResult.java | 52 +- .../okr/models/keyresult/KeyResultMetric.java | 22 +- .../models/keyresult/KeyResultOrdinal.java | 23 +- .../keyresult/KeyResultWithActionList.java | 4 +- .../puzzle/okr/models/overview/Overview.java | 18 +- .../okr/models/overview/OverviewId.java | 13 +- ...FlywayMultitenantMigrationInitializer.java | 38 +- .../okr/multitenancy/HibernateContext.java | 4 +- .../SchemaMultiTenantConnectionProvider.java | 41 +- .../multitenancy/TenantConfigProvider.java | 58 ++- .../okr/multitenancy/TenantContext.java | 7 +- .../TenantClientCustomization.java | 6 +- .../TenantClientCustomizationProvider.java | 26 +- .../okr/repository/ActionRepository.java | 5 +- .../okr/repository/AlignmentRepository.java | 5 +- .../AlignmentSelectionRepository.java | 8 +- .../okr/repository/CheckInRepository.java | 5 +- .../okr/repository/CompletedRepository.java | 1 + .../okr/repository/KeyResultRepository.java | 5 +- .../okr/repository/ObjectiveRepository.java | 5 +- .../okr/repository/QuarterRepository.java | 7 +- .../okr/repository/ReadOnlyRepository.java | 4 +- .../puzzle/okr/repository/TeamRepository.java | 5 +- .../puzzle/okr/repository/UserRepository.java | 7 +- .../okr/repository/UserTeamRepository.java | 1 + .../okr/security/AuthenticationEvents.java | 4 +- .../ch/puzzle/okr/security/JwtHelper.java | 80 +-- .../okr/security/TenantJWSKeySelector.java | 25 +- .../security/TenantJwtIssuerValidator.java | 13 +- .../okr/security/helper/ClaimHelper.java | 4 +- .../okr/security/helper/JwtStatusLogger.java | 26 +- .../okr/security/helper/TokenHelper.java | 4 +- .../ch/puzzle/okr/service/CacheService.java | 10 +- .../ActionAuthorizationService.java | 8 +- .../AuthorizationRegistrationService.java | 15 +- .../authorization/AuthorizationService.java | 125 +++-- .../AuthorizationServiceBase.java | 9 +- .../CheckInAuthorizationService.java | 4 +- .../CompletedAuthorizationService.java | 7 +- .../KeyResultAuthorizationService.java | 16 +- .../ObjectiveAuthorizationService.java | 4 +- .../OverviewAuthorizationService.java | 33 +- .../TeamAuthorizationService.java | 12 +- .../UserAuthorizationService.java | 17 +- .../business/ActionBusinessService.java | 15 +- .../AlignmentSelectionBusinessService.java | 10 +- .../business/BusinessServiceInterface.java | 4 +- .../business/CheckInBusinessService.java | 11 +- .../business/CompletedBusinessService.java | 7 +- .../business/KeyResultBusinessService.java | 32 +- .../business/ObjectiveBusinessService.java | 70 +-- .../business/OverviewBusinessService.java | 39 +- .../business/QuarterBusinessService.java | 36 +- .../service/business/TeamBusinessService.java | 77 ++- .../service/business/UserBusinessService.java | 24 +- .../clientconfig/ClientConfigService.java | 57 +- .../persistence/ActionPersistenceService.java | 5 +- .../AlignmentPersistenceService.java | 5 +- .../AlignmentSelectionPersistenceService.java | 5 +- .../persistence/AuthorizationCriteria.java | 28 +- .../CheckInPersistenceService.java | 5 +- .../CompletedPersistenceService.java | 1 + .../KeyResultPersistenceService.java | 6 +- .../ObjectivePersistenceService.java | 29 +- .../OverviewPersistenceService.java | 19 +- .../service/persistence/PersistenceBase.java | 30 +- .../QuarterPersistenceService.java | 7 +- .../persistence/TeamPersistenceService.java | 5 +- .../persistence/UserPersistenceService.java | 7 +- .../UserTeamPersistenceService.java | 5 +- .../validation/ActionValidationService.java | 25 +- .../validation/CheckInValidationService.java | 20 +- .../CompletedValidationService.java | 4 +- .../KeyResultValidationService.java | 20 +- .../ObjectiveValidationService.java | 40 +- .../validation/OverviewValidationService.java | 3 +- .../validation/QuarterValidationService.java | 31 +- .../validation/TeamValidationService.java | 19 +- .../validation/UserValidationService.java | 1 + .../service/validation/ValidationBase.java | 64 ++- .../ch/puzzle/okr/util/CollectionUtils.java | 4 +- .../util/quarter/generate/QuarterData.java | 4 +- .../util/quarter/generate/QuarterLabel.java | 4 +- .../okr/util/quarter/generate/Quarters.java | 4 +- .../quarter/generate/h2/QuarterFunction.java | 27 +- .../java/ch/puzzle/okr/ForwardFilterTest.java | 14 +- .../puzzle/okr/SpringCachingConfigTest.java | 14 +- .../ch/puzzle/okr/UserKeyGeneratorTest.java | 8 +- .../okr/architecture/OkrArchitectureTest.java | 167 ++++-- .../okr/controller/ActionControllerIT.java | 104 ++-- .../okr/controller/AlignmentControllerIT.java | 102 ++-- .../okr/controller/CacheControllerIT.java | 10 +- .../okr/controller/CheckInControllerIT.java | 168 +++--- .../controller/ClientConfigControllerIT.java | 44 +- .../okr/controller/CompletedControllerIT.java | 63 ++- .../okr/controller/KeyResultControllerIT.java | 450 +++++++++------- .../okr/controller/ObjectiveControllerIT.java | 319 ++++++++---- .../okr/controller/OverviewControllerIT.java | 201 +++++--- .../okr/controller/QuarterControllerIT.java | 78 ++- .../okr/controller/TeamControllerIT.java | 195 ++++--- .../okr/controller/UserControllerIT.java | 172 ++++--- .../deserializer/CheckInDeserializerTest.java | 106 ++-- .../KeyResultDeserializerTest.java | 164 +++--- .../puzzle/okr/mapper/ActionMapperTest.java | 56 +- .../mapper/AlignmentSelectionMapperTest.java | 129 +++-- .../okr/mapper/CompletedMapperTest.java | 27 +- .../okr/mapper/ObjectiveMapperTest.java | 58 ++- .../puzzle/okr/mapper/OverviewMapperTest.java | 320 +++++++++--- .../ch/puzzle/okr/mapper/TeamMapperTest.java | 9 +- .../ch/puzzle/okr/mapper/UserMapperTest.java | 53 +- .../okr/mapper/checkin/CheckInMapperTest.java | 9 +- .../checkin/CheckInMetricMapperTest.java | 1 + .../checkin/CheckInOrdinalMapperTest.java | 1 + .../mapper/checkin/helper/AssertHelper.java | 14 +- .../checkin/helper/TestDataConstants.java | 4 +- .../checkin/helper/TestDataDtoHelper.java | 36 +- .../mapper/checkin/helper/TestDataHelper.java | 43 +- .../mapper/keyresult/KeyResultMapperTest.java | 29 +- .../keyresult/KeyResultMetricMapperTest.java | 13 +- .../keyresult/KeyResultOrdinalMapperTest.java | 13 +- .../mapper/keyresult/helper/AssertHelper.java | 54 +- .../keyresult/helper/TestDataConstants.java | 8 +- .../keyresult/helper/TestDataDtoHelper.java | 108 ++-- .../keyresult/helper/TestDataHelper.java | 132 ++--- .../authorization/AuthorizationUserTest.java | 37 +- ...ayMultitenantMigrationInitializerTest.java | 26 +- .../multitenancy/HibernateContextTest.java | 31 +- ...TenantConnectionProviderInternalsTest.java | 5 +- ...hemaMultiTenantConnectionProviderTest.java | 9 +- .../TenantConfigProviderTestIT.java | 43 +- ...TenantClientCustomizationProviderTest.java | 11 +- ...nantClientCustomizationProviderTestIT.java | 22 +- .../security/AuthenticationEventsTest.java | 7 +- .../ch/puzzle/okr/security/JwtHelperTest.java | 48 +- .../security/TenantJWSKeySelectorTest.java | 18 +- .../TenantJwtIssuerValidatorTest.java | 21 +- .../okr/security/helper/ClaimHelperTest.java | 9 +- .../okr/security/helper/TokenHelperTest.java | 6 +- .../okr/security/helper/UrlHelperTest.java | 6 +- .../ActionAuthorizationServiceTest.java | 47 +- .../AuthorizationRegistrationServiceIT.java | 78 +-- .../AuthorizationServiceTest.java | 432 +++++++++++----- .../CheckInAuthorizationServiceTest.java | 22 +- .../CompletedAuthorizationServiceTest.java | 20 +- .../KeyResultAuthorizationServiceTest.java | 44 +- .../ObjectiveAuthorizationServiceTest.java | 50 +- .../OverviewAuthorizationServiceTest.java | 35 +- .../TeamAuthorizationServiceTest.java | 40 +- .../UserAuthorizationServiceTest.java | 33 +- .../authorization/UserUpdateHelperTest.java | 37 +- .../business/ActionBusinessServiceTest.java | 64 ++- ...AlignmentSelectionBusinessServiceTest.java | 17 +- .../business/CheckInBusinessServiceTest.java | 52 +- .../CompletedBusinessServiceTest.java | 40 +- .../business/KeyResultBusinessServiceIT.java | 148 ++++-- .../KeyResultBusinessServiceTest.java | 236 ++++++--- .../ObjectiveBusinessServiceTest.java | 166 ++++-- .../business/OverviewBusinessServiceTest.java | 140 +++-- .../business/QuarterBusinessServiceTest.java | 125 +++-- .../business/TeamBusinessServiceTest.java | 214 ++++++-- .../business/UserBusinessServiceTest.java | 112 ++-- .../clientconfig/ClientConfigServiceIT.java | 26 +- .../clientconfig/ClientConfigServiceTest.java | 54 +- .../ActionPersistenceServiceIT.java | 48 +- .../AlignmentPersistenceServiceIT.java | 77 ++- ...lignmentSelectionPersistenceServiceIT.java | 38 +- .../persistence/AuthorizationCriteriaIT.java | 25 +- .../AuthorizationCriteriaParametersTest.java | 155 +++--- .../AuthorizationCriteriaTest.java | 39 +- .../CheckInPersistenceServiceIT.java | 16 +- .../CompletedPersistenceServiceIT.java | 45 +- .../KeyResultPersistenceServiceIT.java | 140 +++-- .../ObjectivePersistenceServiceIT.java | 110 ++-- .../OverviewPersistenceServiceIT.java | 77 +-- .../persistence/PersistenceBaseTestIT.java | 18 +- .../QuarterPersistenceServiceIT.java | 27 +- .../persistence/TeamPersistenceServiceIT.java | 13 +- .../persistence/UserPersistenceServiceIT.java | 61 ++- .../UserTeamPersistenceServiceIT.java | 39 +- .../ActionValidationServiceTest.java | 235 +++++---- .../CheckInValidationServiceTest.java | 248 +++++---- .../CompletedValidationServiceTest.java | 98 ++-- .../KeyResultValidationServiceTest.java | 263 ++++++---- .../ObjectiveValidationServiceTest.java | 485 ++++++++++++------ .../QuarterValidationServiceTest.java | 31 +- .../validation/TeamValidationServiceTest.java | 92 ++-- .../validation/UserValidationServiceTest.java | 287 +++++++---- .../validation/ValidationBaseTest.java | 92 ++-- .../ch/puzzle/okr/test/AssertionHelper.java | 15 +- .../puzzle/okr/test/CheckInTestHelpers.java | 82 ++- .../puzzle/okr/test/KeyResultTestHelpers.java | 425 ++++++++------- .../okr/test/SpringIntegrationTest.java | 6 +- .../okr/test/TestContextInitializer.java | 1 + .../java/ch/puzzle/okr/test/TestHelper.java | 89 ++-- .../quarter/check/QuarterRangeChecker.java | 4 +- .../check/QuarterRangeCheckerTest.java | 14 +- .../quarter/generate/QuarterLabelTest.java | 60 +-- .../util/quarter/generate/QuartersTest.java | 194 ++++--- frontend/cypress/e2e/checkIn.cy.ts | 4 +- frontend/cypress/e2e/duplicated-scoring.cy.ts | 4 +- frontend/cypress/e2e/teammanagement.cy.ts | 8 +- frontend/cypress/support/scoringSupport.ts | 10 +- .../action-plan/action-plan.component.ts | 8 +- .../application-banner.component.spec.ts | 6 +- .../application-banner.component.ts | 2 +- .../application-top-bar.component.ts | 4 +- .../key-result-form.component.spec.ts | 8 +- .../keyresult-dialog.component.spec.ts | 16 +- .../keyresult-dialog.component.ts | 2 +- .../keyresult-type.component.spec.ts | 16 +- .../keyresult-type.component.ts | 2 +- .../objective-detail.component.spec.ts | 2 +- .../objective/objective.component.spec.ts | 2 +- .../objective/objective.component.ts | 2 +- .../components/overview/overview.component.ts | 3 +- frontend/src/app/guards/auth.guard.ts | 4 +- .../interceptors/error-interceptor.service.ts | 4 +- .../interceptors/error.interceptor.spec.ts | 2 +- .../interceptors/oauth.interceptor.spec.ts | 2 +- .../services/customization.service.spec.ts | 2 +- frontend/src/app/services/dialog.service.ts | 2 +- .../objective-menu-actions.service.spec.ts | 20 +- frontend/src/app/shared/common.spec.ts | 5 +- frontend/src/app/shared/common.ts | 6 +- .../custom/scoring/scoring.component.spec.ts | 3 +- .../custom/scoring/scoring.component.ts | 10 +- .../complete-dialog.component.spec.ts | 12 +- .../complete-dialog.component.ts | 2 +- .../confirm-dialog.component.spec.ts | 4 +- .../confirm-dialog.component.ts | 5 +- .../example-dialog.component.spec.ts | 4 +- .../objective-form.component.spec.ts | 16 +- .../objective-form.component.ts | 11 +- .../unit-value-transformation.pipe.ts | 1 - frontend/src/app/shared/testData.ts | 24 +- frontend/src/app/shared/types/menu-entry.ts | 11 - frontend/src/app/shared/validators.ts | 2 +- .../add-edit-team-dialog.component.spec.ts | 4 - .../add-edit-team-dialog.component.ts | 4 +- .../add-user-team.component.spec.ts | 2 - .../member-list-table.component.ts | 5 +- .../member-list/member-list.component.spec.ts | 2 +- .../new-user/new-user.component.ts | 4 +- .../search-team-management.component.spec.ts | 8 +- .../team-list/team-list.component.spec.ts | 4 - ...team-management-mobile-filter.component.ts | 3 +- frontend/src/global.ts | 6 +- 319 files changed, 8118 insertions(+), 5144 deletions(-) delete mode 100644 frontend/src/app/shared/types/menu-entry.ts diff --git a/backend/src/main/java/ch/puzzle/okr/ErrorKey.java b/backend/src/main/java/ch/puzzle/okr/ErrorKey.java index f5a67168eb..8d72b8c704 100644 --- a/backend/src/main/java/ch/puzzle/okr/ErrorKey.java +++ b/backend/src/main/java/ch/puzzle/okr/ErrorKey.java @@ -1,8 +1,5 @@ package ch.puzzle.okr; public enum ErrorKey { - ATTRIBUTE_NULL, ATTRIBUTE_CHANGED, ATTRIBUTE_SET_FORBIDDEN, ATTRIBUTE_NOT_SET, ATTRIBUTE_CANNOT_CHANGE, - ATTRIBUTE_MUST_BE_DRAFT, KEY_RESULT_CONVERSION, ALREADY_EXISTS_SAME_NAME, CONVERT_TOKEN, DATA_HAS_BEEN_UPDATED, - MODEL_NULL, MODEL_WITH_ID_NOT_FOUND, NOT_AUTHORIZED_TO_READ, NOT_AUTHORIZED_TO_WRITE, NOT_AUTHORIZED_TO_DELETE, - TOKEN_NULL, TRIED_TO_DELETE_LAST_ADMIN, TRIED_TO_REMOVE_LAST_OKR_CHAMPION + ATTRIBUTE_NULL, ATTRIBUTE_CHANGED, ATTRIBUTE_SET_FORBIDDEN, ATTRIBUTE_NOT_SET, ATTRIBUTE_CANNOT_CHANGE, ATTRIBUTE_MUST_BE_DRAFT, KEY_RESULT_CONVERSION, ALREADY_EXISTS_SAME_NAME, CONVERT_TOKEN, DATA_HAS_BEEN_UPDATED, MODEL_NULL, MODEL_WITH_ID_NOT_FOUND, NOT_AUTHORIZED_TO_READ, NOT_AUTHORIZED_TO_WRITE, NOT_AUTHORIZED_TO_DELETE, TOKEN_NULL, TRIED_TO_DELETE_LAST_ADMIN, TRIED_TO_REMOVE_LAST_OKR_CHAMPION } diff --git a/backend/src/main/java/ch/puzzle/okr/FlywayMultitenantConfig.java b/backend/src/main/java/ch/puzzle/okr/FlywayMultitenantConfig.java index 8ef156dd9a..8bc22f7755 100644 --- a/backend/src/main/java/ch/puzzle/okr/FlywayMultitenantConfig.java +++ b/backend/src/main/java/ch/puzzle/okr/FlywayMultitenantConfig.java @@ -1,6 +1,7 @@ package ch.puzzle.okr; import ch.puzzle.okr.multitenancy.FlywayMultitenantMigrationInitializer; + import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; diff --git a/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java b/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java index 2e517f4d59..243f84d92a 100644 --- a/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java +++ b/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java @@ -1,25 +1,24 @@ package ch.puzzle.okr; +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.filter.GenericFilterBean; + import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.filter.GenericFilterBean; - -import java.io.IOException; -import java.util.Arrays; public class ForwardFilter extends GenericFilterBean { private static final Logger logger = LoggerFactory.getLogger(ForwardFilter.class); @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, + ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; logger.debug(String.format("====> pass through the filter '%s'", request.getRequestURI())); filterChain.doFilter(servletRequest, servletResponse); diff --git a/backend/src/main/java/ch/puzzle/okr/OkrApplication.java b/backend/src/main/java/ch/puzzle/okr/OkrApplication.java index 830bac19ad..35c4585e55 100644 --- a/backend/src/main/java/ch/puzzle/okr/OkrApplication.java +++ b/backend/src/main/java/ch/puzzle/okr/OkrApplication.java @@ -10,7 +10,7 @@ public class OkrApplication { public static void main(String[] args) { new SpringApplicationBuilder(OkrApplication.class) // - .initializers(new OkrApplicationContextInitializer()) // - .run(args); + .initializers(new OkrApplicationContextInitializer()) // + .run(args); } } diff --git a/backend/src/main/java/ch/puzzle/okr/OkrApplicationContextInitializer.java b/backend/src/main/java/ch/puzzle/okr/OkrApplicationContextInitializer.java index 285adea577..88cc54488a 100644 --- a/backend/src/main/java/ch/puzzle/okr/OkrApplicationContextInitializer.java +++ b/backend/src/main/java/ch/puzzle/okr/OkrApplicationContextInitializer.java @@ -1,6 +1,7 @@ package ch.puzzle.okr; import ch.puzzle.okr.multitenancy.HibernateContext; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContextInitializer; diff --git a/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java b/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java index 0a721ff03b..a00d5292f5 100644 --- a/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java +++ b/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java @@ -1,13 +1,14 @@ package ch.puzzle.okr; +import java.util.Map; + import ch.puzzle.okr.exception.OkrResponseStatusException; + import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; -import java.util.Map; - @Component public class OkrErrorAttributes extends DefaultErrorAttributes { diff --git a/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java b/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java index a7613f5b26..eb56cb7316 100644 --- a/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java +++ b/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java @@ -1,11 +1,12 @@ package ch.puzzle.okr; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; @Configuration public class OpenAPI30Configuration { @@ -13,8 +14,11 @@ public class OpenAPI30Configuration { public OpenAPI customizeOpenAPI() { final String securitySchemeName = "bearerAuth"; return new OpenAPI().addSecurityItem(new SecurityRequirement().addList(securitySchemeName)) - .components(new Components().addSecuritySchemes(securitySchemeName, new SecurityScheme() - .name(securitySchemeName).type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT"))); + .components(new Components().addSecuritySchemes(securitySchemeName, + new SecurityScheme().name(securitySchemeName) + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT"))); } } diff --git a/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java b/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java index 051f3309f0..4ba6d90352 100644 --- a/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java +++ b/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java @@ -1,10 +1,5 @@ package ch.puzzle.okr; -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; -import com.nimbusds.jwt.proc.DefaultJWTProcessor; -import com.nimbusds.jwt.proc.JWTClaimsSetAwareJWSKeySelector; -import com.nimbusds.jwt.proc.JWTProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -33,6 +28,12 @@ import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter; import org.springframework.security.web.header.writers.StaticHeadersWriter; +import com.nimbusds.jose.proc.SecurityContext; +import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; +import com.nimbusds.jwt.proc.DefaultJWTProcessor; +import com.nimbusds.jwt.proc.JWTClaimsSetAwareJWSKeySelector; +import com.nimbusds.jwt.proc.JWTProcessor; + import static org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP; import static org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER; import static org.springframework.security.web.header.writers.XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK; @@ -50,17 +51,20 @@ public class SecurityConfig { @Bean @Order(1) // Must be First order! Otherwise unauthorized Requests are sent to Controllers - public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, @Value("${connect.src}") String connectSrc) - throws Exception { + public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, @Value("${connect.src}") String connectSrc) throws Exception { this.connectSrc = connectSrc; setHeaders(http); http.addFilterAfter(new ForwardFilter(), BasicAuthenticationFilter.class); logger.debug("*** apiSecurityFilterChain reached"); return http.cors(Customizer.withDefaults()) - .authorizeHttpRequests(e -> e.requestMatchers("/api/**").authenticated().anyRequest().permitAll()) - .exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))) - .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())).build(); + .authorizeHttpRequests(e -> e.requestMatchers("/api/**") + .authenticated() + .anyRequest() + .permitAll()) + .exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))) + .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) + .build(); } @Bean @@ -81,22 +85,24 @@ JWTProcessor jwtProcessor(JWTClaimsSetAwareJWSKeySelector jwtProcessor, OAuth2TokenValidator jwtValidator) { NimbusJwtDecoder decoder = new NimbusJwtDecoder(jwtProcessor); OAuth2TokenValidator validator = new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefault(), - jwtValidator); + jwtValidator); decoder.setJwtValidator(validator); return decoder; } private HttpSecurity setHeaders(HttpSecurity http) throws Exception { - return http.headers(headers -> headers - .contentSecurityPolicy(c -> c.policyDirectives(okrContentSecurityPolicy())) - .crossOriginEmbedderPolicy(c -> c.policy(REQUIRE_CORP)) - .crossOriginOpenerPolicy(c -> c.policy(OPENER_SAME_ORIGIN)) - .crossOriginResourcePolicy(c -> c.policy(RESOURCE_SAME_ORIGIN)) - .addHeaderWriter(new StaticHeadersWriter("X-Permitted-Cross-Domain-Policies", "none")) - .frameOptions(HeadersConfigurer.FrameOptionsConfig::deny) - .xssProtection(c -> c.headerValue(ENABLED_MODE_BLOCK)) - .httpStrictTransportSecurity(c -> c.includeSubDomains(true).maxAgeInSeconds(31536000)) - .referrerPolicy(c -> c.policy(NO_REFERRER)).permissionsPolicy(c -> c.policy(okrPermissionPolicy()))); + return http.headers(headers -> headers.contentSecurityPolicy(c -> c.policyDirectives(okrContentSecurityPolicy())) + .crossOriginEmbedderPolicy(c -> c.policy(REQUIRE_CORP)) + .crossOriginOpenerPolicy(c -> c.policy(OPENER_SAME_ORIGIN)) + .crossOriginResourcePolicy(c -> c.policy(RESOURCE_SAME_ORIGIN)) + .addHeaderWriter(new StaticHeadersWriter("X-Permitted-Cross-Domain-Policies", + "none")) + .frameOptions(HeadersConfigurer.FrameOptionsConfig::deny) + .xssProtection(c -> c.headerValue(ENABLED_MODE_BLOCK)) + .httpStrictTransportSecurity(c -> c.includeSubDomains(true) + .maxAgeInSeconds(31536000)) + .referrerPolicy(c -> c.policy(NO_REFERRER)) + .permissionsPolicy(c -> c.policy(okrPermissionPolicy()))); } private String okrContentSecurityPolicy() { @@ -115,18 +121,11 @@ private String okrContentSecurityPolicy() { } private String okrPermissionPolicy() { - return "accelerometer=(), ambient-light-sensor=(), autoplay=(), " - + "battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), " - + "execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=()," - + " geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), " - + "midi=(), navigation-override=(), payment=(), picture-in-picture=()," - + " publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(self), " - + "usb=(), web-share=(), xr-spatial-tracking=()"; + return "accelerometer=(), ambient-light-sensor=(), autoplay=(), " + "battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), " + "execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=()," + " geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), " + "midi=(), navigation-override=(), payment=(), picture-in-picture=()," + " publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(self), " + "usb=(), web-share=(), xr-spatial-tracking=()"; } @Bean - public AuthenticationEventPublisher authenticationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { + public AuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { return new DefaultAuthenticationEventPublisher(applicationEventPublisher); } diff --git a/backend/src/main/java/ch/puzzle/okr/SpringCachingConfig.java b/backend/src/main/java/ch/puzzle/okr/SpringCachingConfig.java index 62bae32213..256107f4e7 100644 --- a/backend/src/main/java/ch/puzzle/okr/SpringCachingConfig.java +++ b/backend/src/main/java/ch/puzzle/okr/SpringCachingConfig.java @@ -2,6 +2,7 @@ import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantContext; + import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; diff --git a/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java b/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java index 144a056e30..ef6dbf9d31 100644 --- a/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java +++ b/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java @@ -1,11 +1,12 @@ package ch.puzzle.okr; +import java.lang.reflect.Method; +import java.text.MessageFormat; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantContext; -import org.springframework.cache.interceptor.KeyGenerator; -import java.lang.reflect.Method; -import java.text.MessageFormat; +import org.springframework.cache.interceptor.KeyGenerator; public class UserKeyGenerator implements KeyGenerator { @Override diff --git a/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java b/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java index d6b9855b7b..5edfefb8d6 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java @@ -1,17 +1,19 @@ package ch.puzzle.okr.controller; +import java.util.List; + import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.service.authorization.ActionAuthorizationService; + +import org.springframework.web.bind.annotation.*; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.web.bind.annotation.*; - -import java.util.List; @RestController @RequestMapping("api/v2/action") @@ -25,20 +27,15 @@ public ActionController(ActionAuthorizationService actionAuthorizationService, A } @Operation(summary = "Update Actions", description = "Update Actions of KeyResult") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Updated Actions of KeyResult", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ActionDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't update Actions, attributes are not set", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Updated Actions of KeyResult", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ActionDto.class))}), @ApiResponse(responseCode = "400", description = "Can't update Actions, attributes are not set", content = @Content)}) @PutMapping - public void updateActions( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Action as json to update existing Actions.", required = true) @RequestBody List actionDtoList) { + public void updateActions(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Action as json to update existing Actions.", required = true) @RequestBody List actionDtoList) { List actionList = actionMapper.toActions(actionDtoList); actionAuthorizationService.updateEntities(actionList); } @Operation(summary = "Delete Action by Id", description = "Delete Action by Id") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Action by Id"), - @ApiResponse(responseCode = "404", description = "Did not find the Action with requested id") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Action by Id"), @ApiResponse(responseCode = "404", description = "Did not find the Action with requested id")}) @DeleteMapping("/{actionId}") public void deleteActionById(@PathVariable long actionId) { actionAuthorizationService.deleteActionByActionId(actionId); diff --git a/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java b/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java index 85b6a77ec1..6b19e52c1c 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java @@ -1,13 +1,11 @@ package ch.puzzle.okr.controller; +import java.util.List; + import ch.puzzle.okr.dto.alignment.AlignmentObjectiveDto; import ch.puzzle.okr.mapper.AlignmentSelectionMapper; import ch.puzzle.okr.service.business.AlignmentSelectionBusinessService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -15,7 +13,11 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.List; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; @RestController @RequestMapping("api/v2/alignments") @@ -23,23 +25,17 @@ public class AlignmentController { private final AlignmentSelectionMapper alignmentSelectionMapper; private final AlignmentSelectionBusinessService alignmentSelectionBusinessService; - public AlignmentController(AlignmentSelectionMapper alignmentSelectionMapper, - AlignmentSelectionBusinessService alignmentSelectionBusinessService) { + public AlignmentController(AlignmentSelectionMapper alignmentSelectionMapper, AlignmentSelectionBusinessService alignmentSelectionBusinessService) { this.alignmentSelectionMapper = alignmentSelectionMapper; this.alignmentSelectionBusinessService = alignmentSelectionBusinessService; } @Operation(summary = "Get all objectives and their key results to select the alignment", description = "Get a list of objectives with their key results to select the alignment") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Returned a list of objectives with their key results to select the alignment", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = AlignmentObjectiveDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't return list of objectives with their key results to select the alignment", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned a list of objectives with their key results to select the alignment", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = AlignmentObjectiveDto.class))}), @ApiResponse(responseCode = "400", description = "Can't return list of objectives with their key results to select the alignment", content = @Content)}) @GetMapping("/selections") - public ResponseEntity> getAlignmentSelections( - @RequestParam(required = false, defaultValue = "", name = "quarter") Long quarterFilter, - @RequestParam(required = false, defaultValue = "", name = "team") Long teamFilter) { + public ResponseEntity> getAlignmentSelections(@RequestParam(required = false, defaultValue = "", name = "quarter") Long quarterFilter, @RequestParam(required = false, defaultValue = "", name = "team") Long teamFilter) { return ResponseEntity.status(HttpStatus.OK) - .body(alignmentSelectionMapper.toDto(alignmentSelectionBusinessService - .getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterFilter, teamFilter))); + .body(alignmentSelectionMapper.toDto(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterFilter, + teamFilter))); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java b/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java index ee46548003..7c025652ac 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java @@ -1,13 +1,15 @@ package ch.puzzle.okr.controller; import ch.puzzle.okr.service.CacheService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; + import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; + @RestController @RequestMapping("api/v2/caches") public class CacheController { @@ -18,14 +20,14 @@ public CacheController(CacheService cacheService) { } @Operation(summary = "Delete authorization users cache", description = "Delete authorization users cache") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Authorization users cache deleted") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Authorization users cache deleted")}) @PostMapping("emptyAuthorizationUsersCache") public void emptyAuthorizationUsersCache() { cacheService.emptyAuthorizationUsersCache(); } @Operation(summary = "Delete all caches", description = "Delete all caches") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "All caches deleted") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "All caches deleted")}) @PostMapping("emptyAllCaches") public void emptyAllCaches() { cacheService.emptyAllCaches(); diff --git a/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java b/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java index 83c6030f2e..dd58e2cda2 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java @@ -4,15 +4,17 @@ import ch.puzzle.okr.mapper.checkin.CheckInMapper; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.service.authorization.CheckInAuthorizationService; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("api/v2/checkIns") @@ -27,56 +29,38 @@ public CheckInController(CheckInMapper checkInMapper, CheckInAuthorizationServic } @Operation(summary = "Get Check-in", description = "Get Check-in by ID") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Returned a Check-in with a specified ID", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), - @ApiResponse(responseCode = "401", description = "Not authorized to read Check-in", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find a Check-in with a specified ID", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned a Check-in with a specified ID", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to read Check-in", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find a Check-in with a specified ID", content = @Content)}) @GetMapping("/{id}") public ResponseEntity getCheckInById(@PathVariable long id) { return ResponseEntity.status(HttpStatus.OK) - .body(checkInMapper.toDto(this.checkInAuthorizationService.getEntityById(id))); + .body(checkInMapper.toDto(this.checkInAuthorizationService.getEntityById(id))); } @Operation(summary = "Update Check-in", description = "Update a Check-in by ID") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Updated Check-in in db", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't create new Check-in, attributes are not set", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to update Check-in", content = @Content), - @ApiResponse(responseCode = "404", description = "Given ID of Check-in wasn't found.", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update Check-in since Check-in was updated or deleted by another user.", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Updated Check-in in db", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Check-in, attributes are not set", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to update Check-in", content = @Content), @ApiResponse(responseCode = "404", description = "Given ID of Check-in wasn't found.", content = @Content), @ApiResponse(responseCode = "422", description = "Can't update Check-in since Check-in was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateCheckIn( - @Parameter(description = "The ID for updating a Check-in.", required = true) @PathVariable Long id, - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to update an existing Check-in.", required = true) @RequestBody CheckInDto checkInDto) { + public ResponseEntity updateCheckIn(@Parameter(description = "The ID for updating a Check-in.", required = true) @PathVariable Long id, @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to update an existing Check-in.", required = true) @RequestBody CheckInDto checkInDto) { CheckIn checkIn = checkInMapper.toCheckIn(checkInDto); - CheckInDto updatedCheckIn = this.checkInMapper - .toDto(this.checkInAuthorizationService.updateEntity(id, checkIn)); - return ResponseEntity.status(HttpStatus.OK).body(updatedCheckIn); + CheckInDto updatedCheckIn = this.checkInMapper.toDto(this.checkInAuthorizationService.updateEntity(id, + checkIn)); + return ResponseEntity.status(HttpStatus.OK) + .body(updatedCheckIn); } @Operation(summary = "Create Check-in", description = "Create a new Check-in") - @ApiResponses(value = { - @ApiResponse(responseCode = "201", description = "Created new Check-in.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't create new Check-in, not allowed to give an ID", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to create Check-in", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Created new Check-in.", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Check-in, not allowed to give an ID", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to create Check-in", content = @Content)}) @PostMapping - public ResponseEntity createCheckIn( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to create a new Check-in.", required = true) @RequestBody CheckInDto checkInDto) { + public ResponseEntity createCheckIn(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to create a new Check-in.", required = true) @RequestBody CheckInDto checkInDto) { CheckIn checkIn = checkInMapper.toCheckIn(checkInDto); CheckInDto createdCheckIn = checkInMapper.toDto(checkInAuthorizationService.createEntity(checkIn)); - return ResponseEntity.status(HttpStatus.CREATED).body(createdCheckIn); + return ResponseEntity.status(HttpStatus.CREATED) + .body(createdCheckIn); } @Operation(summary = "Delete Check-in by ID", description = "Delete Check-in by ID") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Check-in by ID"), - @ApiResponse(responseCode = "401", description = "Not authorized to delete Check-in", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Check-in with requested ID") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Check-in by ID"), @ApiResponse(responseCode = "401", description = "Not authorized to delete Check-in", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the Check-in with requested ID")}) @DeleteMapping("/{id}") - public void deleteCheckInById( - @Parameter(description = "The ID of an Check-in to delete it.", required = true) @PathVariable long id) { + public void deleteCheckInById(@Parameter(description = "The ID of an Check-in to delete it.", required = true) @PathVariable long id) { this.checkInAuthorizationService.deleteEntityById(id); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java b/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java index ec45e2f782..6bce730715 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java @@ -2,13 +2,15 @@ import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.service.clientconfig.ClientConfigService; -import jakarta.servlet.http.HttpServletRequest; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; +import jakarta.servlet.http.HttpServletRequest; + @Controller public class ClientConfigController { @@ -21,7 +23,7 @@ public ClientConfigController(ClientConfigService configService) { @GetMapping("/config") public ResponseEntity getConfig(HttpServletRequest request) { return ResponseEntity.status(HttpStatus.OK) - .body(configService.getConfigBasedOnActiveEnv(request.getServerName())); + .body(configService.getConfigBasedOnActiveEnv(request.getServerName())); } @RequestMapping(value = "/**/{[path:[^\\.]*}") diff --git a/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java b/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java index 4b8e10e5dc..39687fbbcc 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java @@ -4,14 +4,16 @@ import ch.puzzle.okr.mapper.CompletedMapper; import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.service.authorization.CompletedAuthorizationService; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("api/v2/completed") @@ -20,29 +22,23 @@ public class CompletedController { private final CompletedAuthorizationService completedAuthorizationService; private final CompletedMapper completedMapper; - public CompletedController(CompletedAuthorizationService completedAuthorizationService, - CompletedMapper completedMapper) { + public CompletedController(CompletedAuthorizationService completedAuthorizationService, CompletedMapper completedMapper) { this.completedAuthorizationService = completedAuthorizationService; this.completedMapper = completedMapper; } @Operation(summary = "Create Completed", description = "Create a new Completed Reference.") - @ApiResponses(value = { - @ApiResponse(responseCode = "201", description = "Created new Completed.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = Completed.class)) }), - @ApiResponse(responseCode = "401", description = "Not authorized to create Completed Reference", content = @Content), - @ApiResponse(responseCode = "404", description = "Could not create Completed Reference", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Created new Completed.", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Completed.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to create Completed Reference", content = @Content), @ApiResponse(responseCode = "404", description = "Could not create Completed Reference", content = @Content)}) @PostMapping public ResponseEntity createCompleted(@RequestBody CompletedDto completedDto) { Completed completed = completedMapper.toCompleted(completedDto); Completed createdCompleted = completedAuthorizationService.createCompleted(completed); - return ResponseEntity.status(HttpStatus.CREATED).body(completedMapper.toDto(createdCompleted)); + return ResponseEntity.status(HttpStatus.CREATED) + .body(completedMapper.toDto(createdCompleted)); } @Operation(summary = "Delete Completed by Objective Id", description = "Delete Completed Reference by Objective Id") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Completed by Objective Id"), - @ApiResponse(responseCode = "401", description = "Not authorized to delete Completed Reference", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Completed with requested Objective id") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Completed by Objective Id"), @ApiResponse(responseCode = "401", description = "Not authorized to delete Completed Reference", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the Completed with requested Objective id")}) @DeleteMapping("/{objectiveId}") public void deleteCompletedByObjectiveId(@PathVariable long objectiveId) { completedAuthorizationService.deleteCompletedByObjectiveId(objectiveId); diff --git a/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java b/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java index 0940bdc333..98e1982421 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.controller; +import java.util.List; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; @@ -12,16 +14,16 @@ import ch.puzzle.okr.models.keyresult.KeyResultWithActionList; import ch.puzzle.okr.service.authorization.ActionAuthorizationService; import ch.puzzle.okr.service.authorization.KeyResultAuthorizationService; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.List; import static org.springframework.http.HttpStatus.*; @@ -35,9 +37,7 @@ public class KeyResultController { private final CheckInMapper checkInMapper; private final ActionMapper actionMapper; - public KeyResultController(KeyResultAuthorizationService keyResultAuthorizationService, - ActionAuthorizationService actionAuthorizationService, KeyResultMapper keyResultMapper, - CheckInMapper checkInMapper, ActionMapper actionMapper) { + public KeyResultController(KeyResultAuthorizationService keyResultAuthorizationService, ActionAuthorizationService actionAuthorizationService, KeyResultMapper keyResultMapper, CheckInMapper checkInMapper, ActionMapper actionMapper) { this.keyResultAuthorizationService = keyResultAuthorizationService; this.actionAuthorizationService = actionAuthorizationService; this.keyResultMapper = keyResultMapper; @@ -46,12 +46,7 @@ public KeyResultController(KeyResultAuthorizationService keyResultAuthorizationS } @Operation(summary = "Get KeyResult by Id", description = "Get KeyResult by Id") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Got KeyResult by Id", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { KeyResultMetricDto.class, - KeyResultOrdinalDto.class })) }), - @ApiResponse(responseCode = "401", description = "Not authorized to read a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Got KeyResult by Id", content = {@Content(mediaType = "application/json", schema = @Schema(allOf = {KeyResultMetricDto.class, KeyResultOrdinalDto.class}))}), @ApiResponse(responseCode = "401", description = "Not authorized to read a KeyResult", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id", content = @Content)}) @GetMapping("/{id}") public KeyResultDto getKeyResultById(@PathVariable long id) { KeyResult keyResult = keyResultAuthorizationService.getEntityById(id); @@ -60,60 +55,43 @@ public KeyResultDto getKeyResultById(@PathVariable long id) { } @Operation(summary = "Get Check-ins from KeyResult", description = "Get all Check-ins from one KeyResult by keyResultId.") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Returned all Check-ins from KeyResult.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), - @ApiResponse(responseCode = "401", description = "Not authorized to read Check-ins from a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find a KeyResult with a specified ID to get Check-ins from.", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned all Check-ins from KeyResult.", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to read Check-ins from a KeyResult", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find a KeyResult with a specified ID to get Check-ins from.", content = @Content)}) @GetMapping("/{id}/checkins") - public List getCheckInsFromKeyResult( - @Parameter(description = "The ID for getting all Check-ins from a KeyResult.", required = true) @PathVariable long id) { - return keyResultAuthorizationService.getAllCheckInsByKeyResult(id).stream().map(checkInMapper::toDto).toList(); + public List getCheckInsFromKeyResult(@Parameter(description = "The ID for getting all Check-ins from a KeyResult.", required = true) @PathVariable long id) { + return keyResultAuthorizationService.getAllCheckInsByKeyResult(id) + .stream() + .map(checkInMapper::toDto) + .toList(); } @Operation(summary = "Create KeyResult", description = "Create a new KeyResult.") - @ApiResponses(value = { - @ApiResponse(responseCode = "201", description = "Created new KeyResult.", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { KeyResultDto.class, - KeyResultOrdinalDto.class })) }), - @ApiResponse(responseCode = "401", description = "Not authorized to create a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find an Objective on which the KeyResult tries to refer to.", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Created new KeyResult.", content = {@Content(mediaType = "application/json", schema = @Schema(allOf = {KeyResultDto.class, KeyResultOrdinalDto.class}))}), @ApiResponse(responseCode = "401", description = "Not authorized to create a KeyResult", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find an Objective on which the KeyResult tries to refer to.", content = @Content)}) @PostMapping public ResponseEntity createKeyResult(@RequestBody KeyResultDto keyResultDto) { KeyResult keyResult = keyResultAuthorizationService.createEntity(keyResultMapper.toKeyResult(keyResultDto)); List actionList = actionMapper.toActions(keyResultDto.getActionList(), keyResult); List savedActions = actionAuthorizationService.createEntities(actionList); KeyResultDto createdKeyResult = keyResultMapper.toDto(keyResult, savedActions); - return ResponseEntity.status(CREATED).body(createdKeyResult); + return ResponseEntity.status(CREATED) + .body(createdKeyResult); } @Operation(summary = "Update KeyResult", description = "Update a KeyResult by ID.") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Updated KeyResult in db.", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { KeyResultDto.class, - KeyResultOrdinalDto.class })) }), - @ApiResponse(responseCode = "226", description = "Updated KeyResult in db but keyResultType was not changed", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = KeyResultDto.class)) }), - @ApiResponse(responseCode = "401", description = "Not authorized to update a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find a KeyResult with a specified ID to update.", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update KeyResult since KeyResult was updated or deleted by another user.", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Updated KeyResult in db.", content = {@Content(mediaType = "application/json", schema = @Schema(allOf = {KeyResultDto.class, KeyResultOrdinalDto.class}))}), @ApiResponse(responseCode = "226", description = "Updated KeyResult in db but keyResultType was not changed", content = {@Content(mediaType = "application/json", schema = @Schema(allOf = KeyResultDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to update a KeyResult", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find a KeyResult with a specified ID to update.", content = @Content), @ApiResponse(responseCode = "422", description = "Can't update KeyResult since KeyResult was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateKeyResult( - @Parameter(description = "The ID for updating a KeyResult.", required = true) @PathVariable long id, - @RequestBody KeyResultDto keyResultDto) { + public ResponseEntity updateKeyResult(@Parameter(description = "The ID for updating a KeyResult.", required = true) @PathVariable long id, @RequestBody KeyResultDto keyResultDto) { KeyResult keyResult = keyResultMapper.toKeyResult(keyResultDto); List actionList = actionMapper.toActions(keyResultDto.getActionList(), keyResult); boolean isKeyResultImUsed = keyResultAuthorizationService.isImUsed(id, keyResult); - KeyResultWithActionList updatedKeyResult = keyResultAuthorizationService.updateEntities(id, keyResult, - actionList); + KeyResultWithActionList updatedKeyResult = keyResultAuthorizationService.updateEntities(id, + keyResult, + actionList); return ResponseEntity.status(isKeyResultImUsed ? IM_USED : OK) - .body(keyResultMapper.toDto(updatedKeyResult.keyResult(), updatedKeyResult.actionList())); + .body(keyResultMapper.toDto(updatedKeyResult.keyResult(), updatedKeyResult.actionList())); } @Operation(summary = "Delete KeyResult by Id", description = "Delete KeyResult by Id") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted KeyResult by Id"), - @ApiResponse(responseCode = "401", description = "Not authorized to delete a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted KeyResult by Id"), @ApiResponse(responseCode = "401", description = "Not authorized to delete a KeyResult", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id")}) @DeleteMapping("/{id}") public void deleteKeyResultById(@PathVariable long id) { keyResultAuthorizationService.deleteEntityById(id); diff --git a/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java b/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java index 61e0f2cab8..32868f8b6b 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java @@ -4,15 +4,17 @@ import ch.puzzle.okr.mapper.ObjectiveMapper; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.service.authorization.ObjectiveAuthorizationService; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; import static org.springframework.http.HttpStatus.IM_USED; import static org.springframework.http.HttpStatus.OK; @@ -23,80 +25,56 @@ public class ObjectiveController { private final ObjectiveAuthorizationService objectiveAuthorizationService; private final ObjectiveMapper objectiveMapper; - public ObjectiveController(ObjectiveAuthorizationService objectiveAuthorizationService, - ObjectiveMapper objectiveMapper) { + public ObjectiveController(ObjectiveAuthorizationService objectiveAuthorizationService, ObjectiveMapper objectiveMapper) { this.objectiveAuthorizationService = objectiveAuthorizationService; this.objectiveMapper = objectiveMapper; } @Operation(summary = "Get Objective", description = "Get an Objective by ID") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Returned an Objective with a specified ID", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), - @ApiResponse(responseCode = "401", description = "Not authorized to read an Objective", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find an Objective with a specified ID", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned an Objective with a specified ID", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to read an Objective", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find an Objective with a specified ID", content = @Content)}) @GetMapping("/{id}") - public ResponseEntity getObjective( - @Parameter(description = "The ID for getting an Objective.", required = true) @PathVariable Long id) { + public ResponseEntity getObjective(@Parameter(description = "The ID for getting an Objective.", required = true) @PathVariable Long id) { return ResponseEntity.status(HttpStatus.OK) - .body(objectiveMapper.toDto(objectiveAuthorizationService.getEntityById(id))); + .body(objectiveMapper.toDto(objectiveAuthorizationService.getEntityById(id))); } @Operation(summary = "Delete Objective by ID", description = "Delete Objective by ID") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Objective by ID"), - @ApiResponse(responseCode = "401", description = "Not authorized to delete an Objective", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Objective with requested ID") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Objective by ID"), @ApiResponse(responseCode = "401", description = "Not authorized to delete an Objective", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the Objective with requested ID")}) @DeleteMapping("/{id}") - public void deleteObjectiveById( - @Parameter(description = "The ID of an Objective to delete it.", required = true) @PathVariable long id) { + public void deleteObjectiveById(@Parameter(description = "The ID of an Objective to delete it.", required = true) @PathVariable long id) { objectiveAuthorizationService.deleteEntityById(id); } @Operation(summary = "Create Objective", description = "Create a new Objective") - @ApiResponses(value = { - @ApiResponse(responseCode = "201", description = "Created new Objective", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't create new Objective, not allowed to give an ID", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to create an Objective", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Created new Objective", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Objective, not allowed to give an ID", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to create an Objective", content = @Content)}) @PostMapping - public ResponseEntity createObjective( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective as json to create a new Objective.", required = true) @RequestBody ObjectiveDto objectiveDTO) { + public ResponseEntity createObjective(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective as json to create a new Objective.", required = true) @RequestBody ObjectiveDto objectiveDTO) { Objective objective = objectiveMapper.toObjective(objectiveDTO); ObjectiveDto createdObjective = objectiveMapper.toDto(objectiveAuthorizationService.createEntity(objective)); - return ResponseEntity.status(HttpStatus.CREATED).body(createdObjective); + return ResponseEntity.status(HttpStatus.CREATED) + .body(createdObjective); } @Operation(summary = "Duplicate Objective", description = "Duplicate a given Objective") - @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Duplicated a given Objective", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }) }) + @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Duplicated a given Objective", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))})}) @PostMapping("/{id}") - public ResponseEntity duplicateObjective( - @Parameter(description = "The ID for duplicating an Objective.", required = true) @PathVariable Long id, - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective which should be duplicated as json", required = true) @RequestBody ObjectiveDto objectiveDTO) { + public ResponseEntity duplicateObjective(@Parameter(description = "The ID for duplicating an Objective.", required = true) @PathVariable Long id, @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective which should be duplicated as json", required = true) @RequestBody ObjectiveDto objectiveDTO) { Objective objective = objectiveMapper.toObjective(objectiveDTO); - ObjectiveDto duplicatedObjectiveDto = objectiveMapper - .toDto(objectiveAuthorizationService.duplicateEntity(id, objective)); - return ResponseEntity.status(HttpStatus.CREATED).body(duplicatedObjectiveDto); + ObjectiveDto duplicatedObjectiveDto = objectiveMapper.toDto(objectiveAuthorizationService.duplicateEntity(id, + objective)); + return ResponseEntity.status(HttpStatus.CREATED) + .body(duplicatedObjectiveDto); } @Operation(summary = "Update Objective", description = "Update Objective by ID") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Updated Objective in db", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), - @ApiResponse(responseCode = "226", description = "Updated Objective in db but quarter was not changed", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't create new Objective, attributes are not set or tried to set quarter", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to update an Objective", content = @Content), - @ApiResponse(responseCode = "404", description = "Given ID of Objective wasn't found", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update Objective since Objective was updated or deleted by another user.", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Updated Objective in db", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "226", description = "Updated Objective in db but quarter was not changed", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Objective, attributes are not set or tried to set quarter", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to update an Objective", content = @Content), @ApiResponse(responseCode = "404", description = "Given ID of Objective wasn't found", content = @Content), @ApiResponse(responseCode = "422", description = "Can't update Objective since Objective was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateObjective( - @Parameter(description = "The ID for updating an Objective.", required = true) @PathVariable Long id, - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The objective as json to update an existing Objective.", required = true) @RequestBody ObjectiveDto objectiveDTO) { + public ResponseEntity updateObjective(@Parameter(description = "The ID for updating an Objective.", required = true) @PathVariable Long id, @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The objective as json to update an existing Objective.", required = true) @RequestBody ObjectiveDto objectiveDTO) { Objective objective = objectiveMapper.toObjective(objectiveDTO); boolean isObjectiveImUsed = objectiveAuthorizationService.isImUsed(objective); - ObjectiveDto updatedObjective = objectiveMapper - .toDto(objectiveAuthorizationService.updateEntity(id, objective)); - return ResponseEntity.status(isObjectiveImUsed ? IM_USED : OK).body(updatedObjective); + ObjectiveDto updatedObjective = objectiveMapper.toDto(objectiveAuthorizationService.updateEntity(id, + objective)); + return ResponseEntity.status(isObjectiveImUsed ? IM_USED : OK) + .body(updatedObjective); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java b/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java index ff8dfe009d..1ba5dbca55 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java @@ -1,13 +1,11 @@ package ch.puzzle.okr.controller; +import java.util.List; + import ch.puzzle.okr.dto.overview.OverviewDto; import ch.puzzle.okr.mapper.OverviewMapper; import ch.puzzle.okr.service.authorization.OverviewAuthorizationService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -15,7 +13,11 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.List; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; @RestController @RequestMapping("api/v2/overview") @@ -23,25 +25,18 @@ public class OverviewController { private final OverviewMapper overviewMapper; private final OverviewAuthorizationService overviewAuthorizationService; - public OverviewController(OverviewMapper overviewMapper, - OverviewAuthorizationService overviewAuthorizationService) { + public OverviewController(OverviewMapper overviewMapper, OverviewAuthorizationService overviewAuthorizationService) { this.overviewMapper = overviewMapper; this.overviewAuthorizationService = overviewAuthorizationService; } @Operation(summary = "Get all teams and their objectives", description = "Get a List of teams with their objectives") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Returned a List of teams and their objectives", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = OverviewDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't return list of teams with their objectives", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to read teams with their objectives", content = @Content), - @ApiResponse(responseCode = "404", description = "The quarter or one of the teams were not found", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned a List of teams and their objectives", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = OverviewDto.class))}), @ApiResponse(responseCode = "400", description = "Can't return list of teams with their objectives", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to read teams with their objectives", content = @Content), @ApiResponse(responseCode = "404", description = "The quarter or one of the teams were not found", content = @Content)}) @GetMapping("") - public ResponseEntity> getOverview( - @RequestParam(required = false, defaultValue = "", name = "team") List teamFilter, - @RequestParam(required = false, defaultValue = "", name = "quarter") Long quarterFilter, - @RequestParam(required = false, defaultValue = "", name = "objectiveQuery") String objectiveQuery) { - return ResponseEntity.status(HttpStatus.OK).body(overviewMapper - .toDto(overviewAuthorizationService.getFilteredOverview(quarterFilter, teamFilter, objectiveQuery))); + public ResponseEntity> getOverview(@RequestParam(required = false, defaultValue = "", name = "team") List teamFilter, @RequestParam(required = false, defaultValue = "", name = "quarter") Long quarterFilter, @RequestParam(required = false, defaultValue = "", name = "objectiveQuery") String objectiveQuery) { + return ResponseEntity.status(HttpStatus.OK) + .body(overviewMapper.toDto(overviewAuthorizationService.getFilteredOverview(quarterFilter, + teamFilter, + objectiveQuery))); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java b/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java index 1cc1383dbc..8edef72bf9 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java @@ -1,20 +1,21 @@ package ch.puzzle.okr.controller; -import ch.puzzle.okr.dto.TeamDto; +import java.util.List; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.business.QuarterBusinessService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.List; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; @RestController @RequestMapping("api/v2/quarters") @@ -27,18 +28,18 @@ public QuarterController(QuarterBusinessService quarterBusinessService) { } @Operation(summary = "Get quarters", description = "Get a List of quarters depending on current date") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned a List of quarters", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class)) }) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned a List of quarters", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class))})}) @GetMapping("") public ResponseEntity> getCurrentQuarters() { - return ResponseEntity.status(HttpStatus.OK).body(this.quarterBusinessService.getQuarters()); + return ResponseEntity.status(HttpStatus.OK) + .body(this.quarterBusinessService.getQuarters()); } @Operation(summary = "Get current quarter", description = "Get the current quarter depending on current date") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned the current quarter", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class)) }) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned the current quarter", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class))})}) @GetMapping("/current") public ResponseEntity getCurrentQuarter() { - return ResponseEntity.status(HttpStatus.OK).body(this.quarterBusinessService.getCurrentQuarter()); + return ResponseEntity.status(HttpStatus.OK) + .body(this.quarterBusinessService.getCurrentQuarter()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java b/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java index ccaad22741..e6f502133f 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java @@ -1,21 +1,23 @@ package ch.puzzle.okr.controller; +import java.util.List; + import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.mapper.TeamMapper; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.service.authorization.TeamAuthorizationService; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.List; import static org.springframework.http.HttpStatus.OK; @@ -31,84 +33,61 @@ public TeamController(TeamAuthorizationService teamAuthorizationService, TeamMap } @Operation(summary = "Get Teams", description = "Get all Teams from db") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned all Teams", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned all Teams", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class))}),}) @GetMapping public List getAllTeams() { - return teamAuthorizationService.getAllTeams().stream().map(teamMapper::toDto).toList(); + return teamAuthorizationService.getAllTeams() + .stream() + .map(teamMapper::toDto) + .toList(); } @Operation(summary = "Create Team", description = "Create a new Team") - @ApiResponses(value = { - @ApiResponse(responseCode = "201", description = "Created new Team", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't create new Team, not allowed to give an ID", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to create a Team", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Created new Team", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Team, not allowed to give an ID", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to create a Team", content = @Content)}) @PostMapping - public ResponseEntity createTeam( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Team as json to create a new Team.", required = true) @RequestBody TeamDto teamDto) { + public ResponseEntity createTeam(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Team as json to create a new Team.", required = true) @RequestBody TeamDto teamDto) { Team createdTeam = teamAuthorizationService.createEntity(teamMapper.toTeam(teamDto)); - return ResponseEntity.status(HttpStatus.CREATED).body(teamMapper.toDto(createdTeam)); + return ResponseEntity.status(HttpStatus.CREATED) + .body(teamMapper.toDto(createdTeam)); } @Operation(summary = "Update Team", description = "Update a Team by ID.") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Updated Team in db.", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { TeamDto.class })) }), - @ApiResponse(responseCode = "401", description = "Not authorized to update a Team", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find a Team with a specified ID to update.", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update Team since Team was updated or deleted by another user.", content = @Content) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Updated Team in db.", content = {@Content(mediaType = "application/json", schema = @Schema(allOf = {TeamDto.class}))}), @ApiResponse(responseCode = "401", description = "Not authorized to update a Team", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find a Team with a specified ID to update.", content = @Content), @ApiResponse(responseCode = "422", description = "Can't update Team since Team was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateTeam( - @Parameter(description = "The ID for updating a Team.", required = true) @PathVariable long id, - @RequestBody TeamDto teamDto) { + public ResponseEntity updateTeam(@Parameter(description = "The ID for updating a Team.", required = true) @PathVariable long id, @RequestBody TeamDto teamDto) { Team updatedTeam = teamAuthorizationService.updateEntity(teamMapper.toTeam(teamDto), id); - return ResponseEntity.status(OK).body(teamMapper.toDto(updatedTeam)); + return ResponseEntity.status(OK) + .body(teamMapper.toDto(updatedTeam)); } @Operation(summary = "Delete Team by ID", description = "Delete Team by ID") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Team by ID"), - @ApiResponse(responseCode = "401", description = "Not authorized to delete an Team", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Team by ID"), @ApiResponse(responseCode = "401", description = "Not authorized to delete an Team", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @DeleteMapping("/{id}") - public void deleteTeamById( - @Parameter(description = "The ID of an Team to delete it.", required = true) @PathVariable long id) { + public void deleteTeamById(@Parameter(description = "The ID of an Team to delete it.", required = true) @PathVariable long id) { teamAuthorizationService.deleteEntity(id); } @Operation(summary = "Add users to a team", description = "Add users to a team") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Added users to team"), - @ApiResponse(responseCode = "401", description = "Not authorized to add users to the team", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Added users to team"), @ApiResponse(responseCode = "401", description = "Not authorized to add users to the team", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @PutMapping("/{id}/addusers") - public void addUsersToTeam( - @Parameter(description = "The ID of an Team to add to users to it.", required = true) @PathVariable long id, - @RequestBody List userDtoList) { - var userIds = userDtoList.stream().map(UserDto::id).toList(); + public void addUsersToTeam(@Parameter(description = "The ID of an Team to add to users to it.", required = true) @PathVariable long id, @RequestBody List userDtoList) { + var userIds = userDtoList.stream() + .map(UserDto::id) + .toList(); teamAuthorizationService.addUsersToTeam(id, userIds); } @Operation(summary = "Remove User from Team", description = "Remove User with given UserID from Team") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Removed User from Team"), - @ApiResponse(responseCode = "401", description = "Not authorized to remove user from team", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Removed User from Team"), @ApiResponse(responseCode = "401", description = "Not authorized to remove user from team", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @PutMapping("/{id}/user/{userId}/removeuser") - public void removeUserFromTeam( - @Parameter(description = "The ID of an team to remove the user from it.", required = true) @PathVariable long id, - @Parameter(description = "The User ID to remove from the team.", required = true) @PathVariable long userId) { + public void removeUserFromTeam(@Parameter(description = "The ID of an team to remove the user from it.", required = true) @PathVariable long id, @Parameter(description = "The User ID to remove from the team.", required = true) @PathVariable long userId) { teamAuthorizationService.removeUserFromTeam(id, userId); } - @Operation(summary = "Update or add team membership", description = "If user is already member of this team, isAdmin is set. otherwise new team membership " - + "is added with isAdmin true or false") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Update or add team membership"), - @ApiResponse(responseCode = "401", description = "Not authorized to update or add team membership", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @Operation(summary = "Update or add team membership", description = "If user is already member of this team, isAdmin is set. otherwise new team membership " + "is added with isAdmin true or false") + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Update or add team membership"), @ApiResponse(responseCode = "401", description = "Not authorized to update or add team membership", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @PutMapping("/{id}/user/{userId}/updateaddteammembership/{isAdmin}") - public void updateOrAddTeamMembership( - @Parameter(description = "The ID of an team to update or add membership", required = true) @PathVariable long id, - @Parameter(description = "The User ID to update or add membership", required = true) @PathVariable long userId, - @Parameter(description = "The parameter if user should be admin or not", required = true) @PathVariable boolean isAdmin) { + public void updateOrAddTeamMembership(@Parameter(description = "The ID of an team to update or add membership", required = true) @PathVariable long id, @Parameter(description = "The User ID to update or add membership", required = true) @PathVariable long userId, @Parameter(description = "The parameter if user should be admin or not", required = true) @PathVariable boolean isAdmin) { teamAuthorizationService.updateOrAddTeamMembership(id, userId, isAdmin); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/UserController.java b/backend/src/main/java/ch/puzzle/okr/controller/UserController.java index bc6d772a9a..009510422d 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/UserController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/UserController.java @@ -1,16 +1,13 @@ package ch.puzzle.okr.controller; +import java.util.List; + import ch.puzzle.okr.dto.NewUserDto; import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.mapper.UserMapper; import ch.puzzle.okr.service.authorization.AuthorizationService; import ch.puzzle.okr.service.authorization.UserAuthorizationService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; + import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -19,7 +16,12 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.List; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; @RestController @RequestMapping("api/v1/users") @@ -29,58 +31,51 @@ public class UserController { private final AuthorizationService authorizationService; private final UserMapper userMapper; - public UserController(UserAuthorizationService userAuthorizationService, AuthorizationService authorizationService, - UserMapper userMapper) { + public UserController(UserAuthorizationService userAuthorizationService, AuthorizationService authorizationService, UserMapper userMapper) { this.userAuthorizationService = userAuthorizationService; this.authorizationService = authorizationService; this.userMapper = userMapper; } @Operation(summary = "Get Users", description = "Get all Users from db.") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned all Users.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned all Users.", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @GetMapping public List getAllUsers() { - return userAuthorizationService.getAllUsers().stream().map(userMapper::toDto).toList(); + return userAuthorizationService.getAllUsers() + .stream() + .map(userMapper::toDto) + .toList(); } @Operation(summary = "Get Current User", description = "Get all current logged in user.") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Returned current logged in user.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned current logged in user.", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @GetMapping(path = "/current") public UserDto getCurrentUser() { - var currentUser = this.authorizationService.updateOrAddAuthorizationUser().user(); + var currentUser = this.authorizationService.updateOrAddAuthorizationUser() + .user(); return userMapper.toDto(currentUser); } @Operation(summary = "Get User by ID", description = "Get user by given ID.") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned user", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned user", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @GetMapping(path = "/{id}") - public UserDto getUserById( - @Parameter(description = "The ID for requested user.", required = true) @PathVariable long id) { + public UserDto getUserById(@Parameter(description = "The ID for requested user.", required = true) @PathVariable long id) { var user = this.userAuthorizationService.getById(id); return userMapper.toDto(user); } @Operation(summary = "Set OKR Champion property for user", description = "Sets the property okrChampion of user to true or false") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned user", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned user", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @PutMapping(path = "/{id}/isokrchampion/{isOkrChampion}") - public UserDto setOkrChampion( - @Parameter(description = "The ID for requested user.", required = true) @PathVariable long id, - @Parameter(description = "okrChampion property of user is set to this flag.", required = true) @PathVariable boolean isOkrChampion) { + public UserDto setOkrChampion(@Parameter(description = "The ID for requested user.", required = true) @PathVariable long id, @Parameter(description = "okrChampion property of user is set to this flag.", required = true) @PathVariable boolean isOkrChampion) { var user = this.userAuthorizationService.setIsOkrChampion(id, isOkrChampion); return userMapper.toDto(user); } @Operation(summary = "Create users", description = "Creates a user entity for every user in the method body") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned users", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned users", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @PostMapping(path = "/createall") - public List createUsers( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The users to create", required = true) @RequestBody List newUserDtoList) { + public List createUsers(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The users to create", required = true) @RequestBody List newUserDtoList) { var createdUsers = this.userAuthorizationService.createUsers(userMapper.toUserList(newUserDtoList)); return userMapper.toDtos(createdUsers); } diff --git a/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java b/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java index f7442819cb..36ea9cf674 100644 --- a/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java +++ b/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java @@ -1,21 +1,23 @@ package ch.puzzle.okr.deserializer; +import java.io.IOException; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.business.KeyResultBusinessService; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ResponseStatusException; + import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; -import org.springframework.web.server.ResponseStatusException; - -import java.io.IOException; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; @@ -30,12 +32,13 @@ public CheckInDeserializer(KeyResultBusinessService keyResultBusinessService) { } @Override - public CheckInDto deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) - throws IOException, JacksonException { + public CheckInDto deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, + JacksonException { ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec(); ObjectNode root = mapper.readTree(jsonParser); if (root.has("keyResultId")) { - KeyResult keyResultOfCheckIn = keyResultBusinessService.getEntityById(root.get("keyResultId").asLong()); + KeyResult keyResultOfCheckIn = keyResultBusinessService.getEntityById(root.get("keyResultId") + .asLong()); if (KEY_RESULT_TYPE_METRIC.equals(keyResultOfCheckIn.getKeyResultType())) { return mapper.readValue(root.toString(), CheckInMetricDto.class); } else if (KEY_RESULT_TYPE_ORDINAL.equals(keyResultOfCheckIn.getKeyResultType())) { @@ -45,7 +48,7 @@ public CheckInDto deserialize(JsonParser jsonParser, DeserializationContext dese } } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, - "missing keyResult ID to deserialize checkIn DTO"); + "missing keyResult ID to deserialize checkIn DTO"); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java b/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java index d873168391..0e31909646 100644 --- a/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java +++ b/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java @@ -1,33 +1,38 @@ package ch.puzzle.okr.deserializer; +import java.io.IOException; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; + +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.springframework.http.HttpStatus; -import org.springframework.web.server.ResponseStatusException; - -import java.io.IOException; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; public class KeyResultDeserializer extends JsonDeserializer { @Override - public KeyResultDto deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) - throws IOException, JacksonException { + public KeyResultDto deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, + JacksonException { ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec(); ObjectNode root = mapper.readTree(jsonParser); String keyResultAttribute = "keyResultType"; - if (root.has(keyResultAttribute) && root.get(keyResultAttribute).asText().equals(KEY_RESULT_TYPE_METRIC)) { + if (root.has(keyResultAttribute) && root.get(keyResultAttribute) + .asText() + .equals(KEY_RESULT_TYPE_METRIC)) { return mapper.readValue(root.toString(), KeyResultMetricDto.class); - } else if (root.has(keyResultAttribute) - && root.get(keyResultAttribute).asText().equals(KEY_RESULT_TYPE_ORDINAL)) { + } else if (root.has(keyResultAttribute) && root.get(keyResultAttribute) + .asText() + .equals(KEY_RESULT_TYPE_ORDINAL)) { return mapper.readValue(root.toString(), KeyResultOrdinalDto.class); } throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "unsupported keyResult DTO to deserialize"); diff --git a/backend/src/main/java/ch/puzzle/okr/dto/ActionDto.java b/backend/src/main/java/ch/puzzle/okr/dto/ActionDto.java index 2cfe1d6836..2208107c6c 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/ActionDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/ActionDto.java @@ -1,5 +1,6 @@ package ch.puzzle.okr.dto; -public record ActionDto(Long id, int version, String action, int priority, boolean isChecked, Long keyResultId, - boolean writeable) { +public record ActionDto( + Long id, int version, String action, int priority, boolean isChecked, Long keyResultId, boolean writeable +) { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/ClientConfigDto.java b/backend/src/main/java/ch/puzzle/okr/dto/ClientConfigDto.java index 702a4de5c4..9503c652a8 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/ClientConfigDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/ClientConfigDto.java @@ -2,6 +2,8 @@ import java.util.Map; -public record ClientConfigDto(String activeProfile, String issuer, String clientId, String favicon, String logo, - String triangles, String backgroundLogo, String title, Map customStyles) { +public record ClientConfigDto( + String activeProfile, String issuer, String clientId, String favicon, String logo, String triangles, + String backgroundLogo, String title, Map customStyles +) { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java b/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java index 07ad03f1ae..41c88da2f9 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java @@ -1,9 +1,9 @@ package ch.puzzle.okr.dto; -import ch.puzzle.okr.ErrorKey; - import java.util.List; +import ch.puzzle.okr.ErrorKey; + public record ErrorDto(String errorKey, List params) { public static ErrorDto of(ErrorKey errorKey, String param) { @@ -15,6 +15,9 @@ public static ErrorDto of(ErrorKey errorKey, List params) { } public static ErrorDto of(String messageKey, List params) { - return new ErrorDto(messageKey, params.stream().map(Object::toString).toList()); + return new ErrorDto(messageKey, + params.stream() + .map(Object::toString) + .toList()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java b/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java index bf230fdcc8..a8dde4fefc 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java @@ -1,9 +1,11 @@ package ch.puzzle.okr.dto; -import ch.puzzle.okr.models.State; - import java.time.LocalDateTime; -public record ObjectiveDto(Long id, int version, String title, Long teamId, Long quarterId, String quarterLabel, - String description, State state, LocalDateTime createdOn, LocalDateTime modifiedOn, boolean writeable) { +import ch.puzzle.okr.models.State; + +public record ObjectiveDto( + Long id, int version, String title, Long teamId, Long quarterId, String quarterLabel, String description, + State state, LocalDateTime createdOn, LocalDateTime modifiedOn, boolean writeable +) { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/UserDto.java b/backend/src/main/java/ch/puzzle/okr/dto/UserDto.java index 119a7554cd..11c6dbe257 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/UserDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/UserDto.java @@ -2,6 +2,8 @@ import java.util.List; -public record UserDto(Long id, int version, String firstname, String lastname, String email, - List userTeamList, boolean isOkrChampion) { +public record UserDto( + Long id, int version, String firstname, String lastname, String email, List userTeamList, + boolean isOkrChampion +) { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInDto.java b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInDto.java index cd25b0e7b6..0a76b8ef02 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInDto.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.dto.checkin; import ch.puzzle.okr.deserializer.CheckInDeserializer; + import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize(using = CheckInDeserializer.class) diff --git a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java index 03036b4cdd..8217025ec9 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java @@ -1,11 +1,12 @@ package ch.puzzle.okr.dto.checkin; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.time.LocalDateTime; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + @JsonDeserialize(as = CheckInMetricDto.class) -public record CheckInMetricDto(Long id, int version, String changeInfo, String initiatives, Integer confidence, - Long keyResultId, LocalDateTime createdOn, LocalDateTime modifiedOn, Double value, boolean writeable) - implements CheckInDto { +public record CheckInMetricDto( + Long id, int version, String changeInfo, String initiatives, Integer confidence, Long keyResultId, + LocalDateTime createdOn, LocalDateTime modifiedOn, Double value, boolean writeable +) implements CheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java index 118fe55179..24aab4ab0e 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java @@ -1,12 +1,14 @@ package ch.puzzle.okr.dto.checkin; +import java.time.LocalDateTime; + import ch.puzzle.okr.models.checkin.Zone; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import java.time.LocalDateTime; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize(as = CheckInOrdinalDto.class) -public record CheckInOrdinalDto(Long id, int version, String changeInfo, String initiatives, Integer confidence, - Long keyResultId, LocalDateTime createdOn, LocalDateTime modifiedOn, Zone value, boolean writeable) - implements CheckInDto { +public record CheckInOrdinalDto( + Long id, int version, String changeInfo, String initiatives, Integer confidence, Long keyResultId, + LocalDateTime createdOn, LocalDateTime modifiedOn, Zone value, boolean writeable +) implements CheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java index b461737716..942018e119 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.dto.keyresult; +import java.util.List; + import ch.puzzle.okr.deserializer.KeyResultDeserializer; import ch.puzzle.okr.dto.ActionDto; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import java.util.List; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize(using = KeyResultDeserializer.class) public interface KeyResultDto { diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInMetricDto.java index d4a7caef3b..ee37cc6ea2 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInMetricDto.java @@ -2,6 +2,8 @@ import java.time.LocalDateTime; -public record KeyResultLastCheckInMetricDto(Long id, int version, Double value, Integer confidence, - LocalDateTime createdOn, String changeInfo, String initiatives) implements KeyResultLastCheckIn { +public record KeyResultLastCheckInMetricDto( + Long id, int version, Double value, Integer confidence, LocalDateTime createdOn, String changeInfo, + String initiatives +) implements KeyResultLastCheckIn { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java index ad67cf798a..4aa1ff52dc 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java @@ -1,9 +1,11 @@ package ch.puzzle.okr.dto.keyresult; -import ch.puzzle.okr.models.checkin.Zone; - import java.time.LocalDateTime; -public record KeyResultLastCheckInOrdinalDto(Long id, int version, Zone value, Integer confidence, - LocalDateTime createdOn, String changeInfo, String initiatives) implements KeyResultLastCheckIn { +import ch.puzzle.okr.models.checkin.Zone; + +public record KeyResultLastCheckInOrdinalDto( + Long id, int version, Zone value, Integer confidence, LocalDateTime createdOn, String changeInfo, + String initiatives +) implements KeyResultLastCheckIn { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java index b69b360f1d..0b0f6bdc56 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java @@ -1,17 +1,20 @@ package ch.puzzle.okr.dto.keyresult; +import java.time.LocalDateTime; +import java.util.List; + import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.models.Unit; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import java.time.LocalDateTime; -import java.util.List; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize(as = KeyResultMetricDto.class) -public record KeyResultMetricDto(Long id, int version, String keyResultType, String title, String description, - Double baseline, Double stretchGoal, Unit unit, KeyResultUserDto owner, KeyResultObjectiveDto objective, +public record KeyResultMetricDto( + Long id, int version, String keyResultType, String title, String description, Double baseline, + Double stretchGoal, Unit unit, KeyResultUserDto owner, KeyResultObjectiveDto objective, KeyResultLastCheckInMetricDto lastCheckIn, LocalDateTime createdOn, LocalDateTime modifiedOn, boolean writeable, - List actionList) implements KeyResultDto { + List actionList +) implements KeyResultDto { @Override public List getActionList() { return actionList; diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java index 4f0365b947..a64205c5e8 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java @@ -1,16 +1,19 @@ package ch.puzzle.okr.dto.keyresult; -import ch.puzzle.okr.dto.ActionDto; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.time.LocalDateTime; import java.util.List; +import ch.puzzle.okr.dto.ActionDto; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + @JsonDeserialize(as = KeyResultOrdinalDto.class) -public record KeyResultOrdinalDto(Long id, int version, String keyResultType, String title, String description, - String commitZone, String targetZone, String stretchZone, KeyResultUserDto owner, - KeyResultObjectiveDto objective, KeyResultLastCheckInOrdinalDto lastCheckIn, LocalDateTime createdOn, - LocalDateTime modifiedOn, boolean writeable, List actionList) implements KeyResultDto { +public record KeyResultOrdinalDto( + Long id, int version, String keyResultType, String title, String description, String commitZone, + String targetZone, String stretchZone, KeyResultUserDto owner, KeyResultObjectiveDto objective, + KeyResultLastCheckInOrdinalDto lastCheckIn, LocalDateTime createdOn, LocalDateTime modifiedOn, + boolean writeable, List actionList +) implements KeyResultDto { @Override public List getActionList() { return actionList; diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultMetricDto.java index 2b397339ad..17f874d54a 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultMetricDto.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.dto.overview; -public record OverviewKeyResultMetricDto(Long id, String title, String keyResultType, String unit, Double baseline, - Double stretchGoal, OverviewLastCheckInMetricDto lastCheckIn) implements OverviewKeyResultDto { +public record OverviewKeyResultMetricDto( + Long id, String title, String keyResultType, String unit, Double baseline, Double stretchGoal, + OverviewLastCheckInMetricDto lastCheckIn +) implements OverviewKeyResultDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java index 6097da2724..05ee6df2b1 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.dto.overview; -public record OverviewKeyResultOrdinalDto(Long id, String title, String keyResultType, String commitZone, - String targetZone, String stretchZone, OverviewLastCheckInOrdinalDto lastCheckIn) - implements OverviewKeyResultDto { +public record OverviewKeyResultOrdinalDto( + Long id, String title, String keyResultType, String commitZone, String targetZone, String stretchZone, + OverviewLastCheckInOrdinalDto lastCheckIn +) implements OverviewKeyResultDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java index 94e15589d8..eae0cfcb94 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java @@ -2,6 +2,7 @@ import java.time.LocalDateTime; -public record OverviewLastCheckInMetricDto(Long id, Double value, Integer confidence, LocalDateTime createdOn) - implements OverviewLastCheckInDto { +public record OverviewLastCheckInMetricDto( + Long id, Double value, Integer confidence, LocalDateTime createdOn +) implements OverviewLastCheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java index 9ea12ae0ac..e7e3f0d577 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java @@ -2,6 +2,7 @@ import java.time.LocalDateTime; -public record OverviewLastCheckInOrdinalDto(Long id, String value, Integer confidence, LocalDateTime createdOn) - implements OverviewLastCheckInDto { +public record OverviewLastCheckInOrdinalDto( + Long id, String value, Integer confidence, LocalDateTime createdOn +) implements OverviewLastCheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java index 403a7073b6..3f21145243 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java @@ -1,9 +1,10 @@ package ch.puzzle.okr.dto.overview; -import ch.puzzle.okr.models.State; - import java.util.List; -public record OverviewObjectiveDto(Long id, String title, State state, OverviewQuarterDto quarter, - List keyResults) { +import ch.puzzle.okr.models.State; + +public record OverviewObjectiveDto( + Long id, String title, State state, OverviewQuarterDto quarter, List keyResults +) { } diff --git a/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java b/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java index 11f666040e..c44b8f319b 100644 --- a/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java +++ b/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java @@ -1,12 +1,13 @@ package ch.puzzle.okr.exception; +import java.util.List; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.dto.ErrorDto; + import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.springframework.http.HttpStatus.UNAUTHORIZED; public class OkrResponseStatusException extends ResponseStatusException { @@ -51,7 +52,9 @@ public OkrResponseStatusException(HttpStatus status, ErrorDto error) { } public OkrResponseStatusException(HttpStatus status, List errors) { - super(status, errors.get(0).errorKey()); + super(status, + errors.get(0) + .errorKey()); this.errors = errors; } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java index 67d6d97e40..29f5a2c1ea 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java @@ -1,12 +1,13 @@ package ch.puzzle.okr.mapper; +import java.util.List; + import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.business.KeyResultBusinessService; -import org.springframework.stereotype.Component; -import java.util.List; +import org.springframework.stereotype.Component; @Component public class ActionMapper { @@ -18,23 +19,37 @@ public ActionMapper(KeyResultBusinessService keyResultBusinessService) { } public ActionDto toDto(Action action) { - return new ActionDto(action.getId(), action.getVersion(), action.getAction(), action.getPriority(), - action.isChecked(), action.getKeyResult().getId(), action.isWriteable()); + return new ActionDto(action.getId(), + action.getVersion(), + action.getAction(), + action.getPriority(), + action.isChecked(), + action.getKeyResult() + .getId(), + action.isWriteable()); } public List toActions(List actionDtos, KeyResult keyResult) { - return actionDtos.stream().map(actionDto -> toAction(actionDto, keyResult)).toList(); + return actionDtos.stream() + .map(actionDto -> toAction(actionDto, keyResult)) + .toList(); } public List toActions(List actionDtos) { return actionDtos.stream() - .map(actionDto -> toAction(actionDto, keyResultBusinessService.getEntityById(actionDto.keyResultId()))) - .toList(); + .map(actionDto -> toAction(actionDto, + keyResultBusinessService.getEntityById(actionDto.keyResultId()))) + .toList(); } private Action toAction(ActionDto actionDto, KeyResult keyResult) { - return Action.Builder.builder().withId(actionDto.id()).withVersion(actionDto.version()) - .withAction(actionDto.action()).withPriority(actionDto.priority()).withIsChecked(actionDto.isChecked()) - .withKeyResult(keyResult).build(); + return Action.Builder.builder() + .withId(actionDto.id()) + .withVersion(actionDto.version()) + .withAction(actionDto.action()) + .withPriority(actionDto.priority()) + .withIsChecked(actionDto.isChecked()) + .withKeyResult(keyResult) + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java index 547181b95e..9ad620b18c 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java @@ -1,15 +1,16 @@ package ch.puzzle.okr.mapper; -import ch.puzzle.okr.dto.alignment.AlignmentKeyResultDto; -import ch.puzzle.okr.dto.alignment.AlignmentObjectiveDto; -import ch.puzzle.okr.models.alignment.AlignmentSelection; -import org.springframework.stereotype.Component; - import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; +import ch.puzzle.okr.dto.alignment.AlignmentKeyResultDto; +import ch.puzzle.okr.dto.alignment.AlignmentObjectiveDto; +import ch.puzzle.okr.models.alignment.AlignmentSelection; + +import org.springframework.stereotype.Component; + @Component public class AlignmentSelectionMapper { @@ -19,14 +20,16 @@ public List toDto(List alignments) { return alignmentDtos; } - private Optional getMatchingObjectiveDto(Long objectiveId, - List objectives) { - return objectives.stream().filter(objectiveDto -> Objects.equals(objectiveId, objectiveDto.id())).findFirst(); + private Optional getMatchingObjectiveDto(Long objectiveId, List objectives) { + return objectives.stream() + .filter(objectiveDto -> Objects.equals(objectiveId, objectiveDto.id())) + .findFirst(); } private void processObjectives(List objectiveDtos, AlignmentSelection alignment) { - Optional objectiveDto = getMatchingObjectiveDto( - alignment.getAlignmentSelectionId().getObjectiveId(), objectiveDtos); + Optional objectiveDto = getMatchingObjectiveDto(alignment.getAlignmentSelectionId() + .getObjectiveId(), + objectiveDtos); if (objectiveDto.isPresent()) { processKeyResults(objectiveDto.get(), alignment); } else { @@ -37,19 +40,21 @@ private void processObjectives(List objectiveDtos, Alignm } private void processKeyResults(AlignmentObjectiveDto objectiveDto, AlignmentSelection alignment) { - if (isValidId(alignment.getAlignmentSelectionId().getKeyResultId())) { - objectiveDto.keyResults().add(createKeyResultDto(alignment)); + if (isValidId(alignment.getAlignmentSelectionId() + .getKeyResultId())) { + objectiveDto.keyResults() + .add(createKeyResultDto(alignment)); } } private AlignmentObjectiveDto createObjectiveDto(AlignmentSelection alignment) { - return new AlignmentObjectiveDto(alignment.getAlignmentSelectionId().getObjectiveId(), - alignment.getObjectiveTitle(), new ArrayList<>()); + return new AlignmentObjectiveDto(alignment.getAlignmentSelectionId() + .getObjectiveId(), alignment.getObjectiveTitle(), new ArrayList<>()); } private AlignmentKeyResultDto createKeyResultDto(AlignmentSelection alignment) { - return new AlignmentKeyResultDto(alignment.getAlignmentSelectionId().getKeyResultId(), - alignment.getKeyResultTitle()); + return new AlignmentKeyResultDto(alignment.getAlignmentSelectionId() + .getKeyResultId(), alignment.getKeyResultTitle()); } private boolean isValidId(Long id) { diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java index 9003754951..7c42dc16ff 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java @@ -2,6 +2,7 @@ import ch.puzzle.okr.dto.CompletedDto; import ch.puzzle.okr.models.Completed; + import org.springframework.stereotype.Component; @Component @@ -12,7 +13,10 @@ public CompletedDto toDto(Completed completed) { } public Completed toCompleted(CompletedDto completedDto) { - return Completed.Builder.builder().withId(completedDto.id()).withObjective(completedDto.objective()) - .withComment(completedDto.comment()).build(); + return Completed.Builder.builder() + .withId(completedDto.id()) + .withObjective(completedDto.objective()) + .withComment(completedDto.comment()) + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java index a65574c408..fe3e6ea190 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java @@ -1,12 +1,13 @@ package ch.puzzle.okr.mapper; +import java.time.LocalDateTime; + import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.service.business.QuarterBusinessService; import ch.puzzle.okr.service.business.TeamBusinessService; -import org.springframework.stereotype.Component; -import java.time.LocalDateTime; +import org.springframework.stereotype.Component; @Component public class ObjectiveMapper { @@ -20,17 +21,33 @@ public ObjectiveMapper(TeamBusinessService teamBusinessService, QuarterBusinessS } public ObjectiveDto toDto(Objective objective) { - return new ObjectiveDto(objective.getId(), objective.getVersion(), objective.getTitle(), - objective.getTeam().getId(), objective.getQuarter().getId(), objective.getQuarter().getLabel(), - objective.getDescription(), objective.getState(), objective.getCreatedOn(), objective.getModifiedOn(), - objective.isWriteable()); + return new ObjectiveDto(objective.getId(), + objective.getVersion(), + objective.getTitle(), + objective.getTeam() + .getId(), + objective.getQuarter() + .getId(), + objective.getQuarter() + .getLabel(), + objective.getDescription(), + objective.getState(), + objective.getCreatedOn(), + objective.getModifiedOn(), + objective.isWriteable()); } public Objective toObjective(ObjectiveDto objectiveDto) { - return Objective.Builder.builder().withId(objectiveDto.id()).withVersion(objectiveDto.version()) - .withTitle(objectiveDto.title()).withTeam(teamBusinessService.getTeamById(objectiveDto.teamId())) - .withDescription(objectiveDto.description()).withModifiedOn(LocalDateTime.now()) - .withState(objectiveDto.state()).withCreatedOn(objectiveDto.createdOn()) - .withQuarter(quarterBusinessService.getQuarterById(objectiveDto.quarterId())).build(); + return Objective.Builder.builder() + .withId(objectiveDto.id()) + .withVersion(objectiveDto.version()) + .withTitle(objectiveDto.title()) + .withTeam(teamBusinessService.getTeamById(objectiveDto.teamId())) + .withDescription(objectiveDto.description()) + .withModifiedOn(LocalDateTime.now()) + .withState(objectiveDto.state()) + .withCreatedOn(objectiveDto.createdOn()) + .withQuarter(quarterBusinessService.getQuarterById(objectiveDto.quarterId())) + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java index 2051b17b89..e01c027f32 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java @@ -1,15 +1,16 @@ package ch.puzzle.okr.mapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.dto.overview.*; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.overview.Overview; -import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; +import org.springframework.stereotype.Component; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; @@ -27,16 +28,22 @@ public List toDto(List overviews) { } private Optional getMatchingOverviewDto(Long teamId, List result) { - return result.stream().filter(overviewDto -> Objects.equals(teamId, overviewDto.team().id())).findFirst(); + return result.stream() + .filter(overviewDto -> Objects.equals(teamId, + overviewDto.team() + .id())) + .findFirst(); } - private Optional getMatchingObjectiveDto(Long objectiveId, - List objectives) { - return objectives.stream().filter(objectiveDto -> Objects.equals(objectiveId, objectiveDto.id())).findFirst(); + private Optional getMatchingObjectiveDto(Long objectiveId, List objectives) { + return objectives.stream() + .filter(objectiveDto -> Objects.equals(objectiveId, objectiveDto.id())) + .findFirst(); } private void processTeams(List overviewDtos, Overview overview) { - Optional overviewDto = getMatchingOverviewDto(overview.getOverviewId().getTeamId(), overviewDtos); + Optional overviewDto = getMatchingOverviewDto(overview.getOverviewId() + .getTeamId(), overviewDtos); if (overviewDto.isPresent()) { processObjectives(overviewDto.get(), overview); } else { @@ -45,36 +52,46 @@ private void processTeams(List overviewDtos, Overview overview) { } private void processObjectives(OverviewDto overviewDto, Overview overview) { - Optional overviewObjectiveDto = getMatchingObjectiveDto( - overview.getOverviewId().getObjectiveId(), overviewDto.objectives()); + Optional overviewObjectiveDto = getMatchingObjectiveDto(overview.getOverviewId() + .getObjectiveId(), + overviewDto.objectives()); if (overviewObjectiveDto.isPresent()) { processKeyResults(overviewObjectiveDto.get(), overview); } else { - overviewDto.objectives().add(createObjectiveDto(overview)); + overviewDto.objectives() + .add(createObjectiveDto(overview)); } } private void processKeyResults(OverviewObjectiveDto overviewObjectiveDto, Overview overview) { - overviewObjectiveDto.keyResults().add(createKeyResultDto(overview)); + overviewObjectiveDto.keyResults() + .add(createKeyResultDto(overview)); } private OverviewDto createOverviewDto(Overview overview) { List objectives = new ArrayList<>(); - if (isValidId(overview.getOverviewId().getObjectiveId())) { + if (isValidId(overview.getOverviewId() + .getObjectiveId())) { objectives.add(createObjectiveDto(overview)); } - return new OverviewDto(new OverviewTeamDto(overview.getOverviewId().getTeamId(), overview.getTeamName()), - objectives, overview.isWriteable()); + return new OverviewDto(new OverviewTeamDto(overview.getOverviewId() + .getTeamId(), overview.getTeamName()), + objectives, + overview.isWriteable()); } private OverviewObjectiveDto createObjectiveDto(Overview overview) { List keyResults = new ArrayList<>(); - if (isValidId(overview.getOverviewId().getKeyResultId())) { + if (isValidId(overview.getOverviewId() + .getKeyResultId())) { keyResults.add(createKeyResultDto(overview)); } - return new OverviewObjectiveDto(overview.getOverviewId().getObjectiveId(), overview.getObjectiveTitle(), - overview.getObjectiveState(), - new OverviewQuarterDto(overview.getQuarterId(), overview.getQuarterLabel()), keyResults); + return new OverviewObjectiveDto(overview.getOverviewId() + .getObjectiveId(), + overview.getObjectiveTitle(), + overview.getObjectiveState(), + new OverviewQuarterDto(overview.getQuarterId(), overview.getQuarterLabel()), + keyResults); } private OverviewKeyResultDto createKeyResultDto(Overview overview) { @@ -83,31 +100,50 @@ private OverviewKeyResultDto createKeyResultDto(Overview overview) { } else if (Objects.equals(overview.getKeyResultType(), KEY_RESULT_TYPE_ORDINAL)) { return createKeyResultOrdinalDto(overview); } else { - throw new OkrResponseStatusException(BAD_REQUEST, ErrorKey.KEY_RESULT_CONVERSION, - overview.getKeyResultType()); + throw new OkrResponseStatusException(BAD_REQUEST, + ErrorKey.KEY_RESULT_CONVERSION, + overview.getKeyResultType()); } } private OverviewKeyResultMetricDto createKeyResultMetricDto(Overview overview) { OverviewLastCheckInMetricDto lastCheckIn = null; - if (isValidId(overview.getOverviewId().getCheckInId())) { - lastCheckIn = new OverviewLastCheckInMetricDto(overview.getOverviewId().getCheckInId(), - overview.getCheckInValue(), overview.getConfidence(), overview.getCheckInCreatedOn()); + if (isValidId(overview.getOverviewId() + .getCheckInId())) { + lastCheckIn = new OverviewLastCheckInMetricDto(overview.getOverviewId() + .getCheckInId(), + overview.getCheckInValue(), + overview.getConfidence(), + overview.getCheckInCreatedOn()); } - return new OverviewKeyResultMetricDto(overview.getOverviewId().getKeyResultId(), overview.getKeyResultTitle(), - overview.getKeyResultType(), overview.getUnit(), overview.getBaseline(), overview.getStretchGoal(), - lastCheckIn); + return new OverviewKeyResultMetricDto(overview.getOverviewId() + .getKeyResultId(), + overview.getKeyResultTitle(), + overview.getKeyResultType(), + overview.getUnit(), + overview.getBaseline(), + overview.getStretchGoal(), + lastCheckIn); } private OverviewKeyResultOrdinalDto createKeyResultOrdinalDto(Overview overview) { OverviewLastCheckInOrdinalDto lastCheckIn = null; - if (isValidId(overview.getOverviewId().getCheckInId())) { - lastCheckIn = new OverviewLastCheckInOrdinalDto(overview.getOverviewId().getCheckInId(), - overview.getCheckInZone(), overview.getConfidence(), overview.getCheckInCreatedOn()); + if (isValidId(overview.getOverviewId() + .getCheckInId())) { + lastCheckIn = new OverviewLastCheckInOrdinalDto(overview.getOverviewId() + .getCheckInId(), + overview.getCheckInZone(), + overview.getConfidence(), + overview.getCheckInCreatedOn()); } - return new OverviewKeyResultOrdinalDto(overview.getOverviewId().getKeyResultId(), overview.getKeyResultTitle(), - overview.getKeyResultType(), overview.getCommitZone(), overview.getTargetZone(), - overview.getStretchZone(), lastCheckIn); + return new OverviewKeyResultOrdinalDto(overview.getOverviewId() + .getKeyResultId(), + overview.getKeyResultTitle(), + overview.getKeyResultType(), + overview.getCommitZone(), + overview.getTargetZone(), + overview.getStretchZone(), + lastCheckIn); } private boolean isValidId(Long id) { diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java index 792bc027e6..55312f687d 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java @@ -2,6 +2,7 @@ import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.models.Team; + import org.springframework.stereotype.Component; @Component @@ -15,7 +16,10 @@ public TeamDto toDto(Team team) { } public Team toTeam(TeamDto teamDto) { - return Team.Builder.builder().withId(teamDto.id()).withVersion(teamDto.version()).withName(teamDto.name()) - .build(); + return Team.Builder.builder() + .withId(teamDto.id()) + .withVersion(teamDto.version()) + .withName(teamDto.name()) + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java index 8d2f3c1892..fd92b6f682 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java @@ -1,13 +1,14 @@ package ch.puzzle.okr.mapper; +import java.util.List; +import java.util.stream.Collectors; + import ch.puzzle.okr.dto.NewUserDto; import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.dto.UserTeamDto; import ch.puzzle.okr.models.User; -import org.springframework.stereotype.Component; -import java.util.List; -import java.util.stream.Collectors; +import org.springframework.stereotype.Component; @Component public class UserMapper { @@ -19,20 +20,33 @@ public UserMapper(TeamMapper teamMapper) { } public List toDtos(List userList) { - return userList.stream().map(this::toDto).toList(); + return userList.stream() + .map(this::toDto) + .toList(); } public UserDto toDto(User user) { - var userTeams = user.getUserTeamList().stream().map( - ut -> new UserTeamDto(ut.getId(), user.getVersion(), teamMapper.toDto(ut.getTeam()), ut.isTeamAdmin())) - .collect(Collectors.toList()); - - return new UserDto(user.getId(), user.getVersion(), user.getFirstname(), user.getLastname(), user.getEmail(), - userTeams, user.isOkrChampion()); + var userTeams = user.getUserTeamList() + .stream() + .map(ut -> new UserTeamDto(ut.getId(), + user.getVersion(), + teamMapper.toDto(ut.getTeam()), + ut.isTeamAdmin())) + .collect(Collectors.toList()); + + return new UserDto(user.getId(), + user.getVersion(), + user.getFirstname(), + user.getLastname(), + user.getEmail(), + userTeams, + user.isOkrChampion()); } public List toUserList(List newUserList) { - return newUserList.stream().map(this::toUser).toList(); + return newUserList.stream() + .map(this::toUser) + .toList(); } public User toUser(NewUserDto newUserDto) { diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java index 34ab137035..91d7e7fdd0 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java @@ -6,6 +6,7 @@ import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.checkin.CheckInMetric; import ch.puzzle.okr.models.checkin.CheckInOrdinal; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ResponseStatusException; @@ -27,7 +28,8 @@ public CheckInDto toDto(CheckIn checkIn) { return checkInOrdinalMapper.toDto(checkInOrdinal); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, - String.format("The CheckIn %s can't be converted to a metric or ordinal CheckIn", checkIn)); + String.format("The CheckIn %s can't be converted to a metric or ordinal CheckIn", + checkIn)); } } @@ -38,7 +40,8 @@ public CheckIn toCheckIn(CheckInDto checkInDto) { return checkInOrdinalMapper.toCheckInOrdinal((CheckInOrdinalDto) checkInDto); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, - String.format("The provided CheckInDto %s is neither metric nor ordinal", checkInDto)); + String.format("The provided CheckInDto %s is neither metric nor ordinal", + checkInDto)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java index 814adc85f2..160d833fba 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java @@ -4,6 +4,7 @@ import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.checkin.CheckInMetric; import ch.puzzle.okr.service.business.KeyResultBusinessService; + import org.springframework.stereotype.Component; @Component @@ -16,28 +17,29 @@ public CheckInMetricMapper(KeyResultBusinessService keyResultBusinessService) { public CheckInMetricDto toDto(CheckInMetric checkInMetric) { return new CheckInMetricDto(checkInMetric.getId(), // - checkInMetric.getVersion(), // - checkInMetric.getChangeInfo(), // - checkInMetric.getInitiatives(), // - checkInMetric.getConfidence(), // - checkInMetric.getKeyResult().getId(), // - checkInMetric.getCreatedOn(), // - checkInMetric.getModifiedOn(), // - checkInMetric.getValue(), // - checkInMetric.isWriteable()); + checkInMetric.getVersion(), // + checkInMetric.getChangeInfo(), // + checkInMetric.getInitiatives(), // + checkInMetric.getConfidence(), // + checkInMetric.getKeyResult() + .getId(), // + checkInMetric.getCreatedOn(), // + checkInMetric.getModifiedOn(), // + checkInMetric.getValue(), // + checkInMetric.isWriteable()); } public CheckIn toCheckInMetric(CheckInMetricDto checkInMetricDto) { return CheckInMetric.Builder.builder() // - .withValue(checkInMetricDto.value()) // - .withId(checkInMetricDto.id()) // - .withVersion(checkInMetricDto.version()) // - .withChangeInfo(checkInMetricDto.changeInfo()) // - .withInitiatives(checkInMetricDto.initiatives()) // - .withConfidence(checkInMetricDto.confidence()) // - .withCreatedOn(checkInMetricDto.createdOn()) // - .withModifiedOn(checkInMetricDto.modifiedOn()) // - .withKeyResult(keyResultBusinessService.getEntityById(checkInMetricDto.keyResultId())) // - .build(); + .withValue(checkInMetricDto.value()) // + .withId(checkInMetricDto.id()) // + .withVersion(checkInMetricDto.version()) // + .withChangeInfo(checkInMetricDto.changeInfo()) // + .withInitiatives(checkInMetricDto.initiatives()) // + .withConfidence(checkInMetricDto.confidence()) // + .withCreatedOn(checkInMetricDto.createdOn()) // + .withModifiedOn(checkInMetricDto.modifiedOn()) // + .withKeyResult(keyResultBusinessService.getEntityById(checkInMetricDto.keyResultId())) // + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java index f64b9c81c4..c402ce2b8b 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java @@ -4,6 +4,7 @@ import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.checkin.CheckInOrdinal; import ch.puzzle.okr.service.business.KeyResultBusinessService; + import org.springframework.stereotype.Component; @Component @@ -15,28 +16,30 @@ public CheckInOrdinalMapper(KeyResultBusinessService keyResultBusinessService) { } public CheckInOrdinalDto toDto(CheckInOrdinal checkInOrdinal) { - return new CheckInOrdinalDto(checkInOrdinal.getId(), checkInOrdinal.getVersion(), // - checkInOrdinal.getChangeInfo(), // - checkInOrdinal.getInitiatives(), // - checkInOrdinal.getConfidence(), // - checkInOrdinal.getKeyResult().getId(), // - checkInOrdinal.getCreatedOn(), // - checkInOrdinal.getModifiedOn(), // - checkInOrdinal.getZone(), // - checkInOrdinal.isWriteable()); + return new CheckInOrdinalDto(checkInOrdinal.getId(), + checkInOrdinal.getVersion(), // + checkInOrdinal.getChangeInfo(), // + checkInOrdinal.getInitiatives(), // + checkInOrdinal.getConfidence(), // + checkInOrdinal.getKeyResult() + .getId(), // + checkInOrdinal.getCreatedOn(), // + checkInOrdinal.getModifiedOn(), // + checkInOrdinal.getZone(), // + checkInOrdinal.isWriteable()); } public CheckIn toCheckInOrdinal(CheckInOrdinalDto checkInOrdinalDto) { return CheckInOrdinal.Builder.builder() // - .withZone(checkInOrdinalDto.value()) // - .withId(checkInOrdinalDto.id()) // - .withVersion(checkInOrdinalDto.version()) // - .withChangeInfo(checkInOrdinalDto.changeInfo()) // - .withInitiatives(checkInOrdinalDto.initiatives()) // - .withConfidence(checkInOrdinalDto.confidence()) // - .withCreatedOn(checkInOrdinalDto.createdOn()) // - .withModifiedOn(checkInOrdinalDto.modifiedOn()) // - .withKeyResult(keyResultBusinessService.getEntityById(checkInOrdinalDto.keyResultId())) // - .build(); + .withZone(checkInOrdinalDto.value()) // + .withId(checkInOrdinalDto.id()) // + .withVersion(checkInOrdinalDto.version()) // + .withChangeInfo(checkInOrdinalDto.changeInfo()) // + .withInitiatives(checkInOrdinalDto.initiatives()) // + .withConfidence(checkInOrdinalDto.confidence()) // + .withCreatedOn(checkInOrdinalDto.createdOn()) // + .withModifiedOn(checkInOrdinalDto.modifiedOn()) // + .withKeyResult(keyResultBusinessService.getEntityById(checkInOrdinalDto.keyResultId())) // + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java index 9078dbd04d..3c4d6869ac 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult; +import java.util.List; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; @@ -7,11 +9,10 @@ import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; + import org.springframework.stereotype.Component; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.springframework.http.HttpStatus.BAD_REQUEST; @Component @@ -32,7 +33,8 @@ public KeyResultDto toDto(KeyResult keyResult, List actionList) { return keyResultOrdinalMapper.toDto(keyResultOrdinal, actionList); } else { throw new ResponseStatusException(BAD_REQUEST, - String.format("The KeyResult %s can't be converted to a metric or ordinal KeyResult", keyResult)); + String.format("The KeyResult %s can't be converted to a metric or ordinal KeyResult", + keyResult)); } } @@ -43,7 +45,8 @@ public KeyResult toKeyResult(KeyResultDto keyResultDto) { return keyResultOrdinalMapper.toKeyResultOrdinal((KeyResultOrdinalDto) keyResultDto); } else { throw new ResponseStatusException(BAD_REQUEST, - String.format("The provided KeyResultDto %s is neither metric nor ordinal", keyResultDto)); + String.format("The provided KeyResultDto %s is neither metric nor ordinal", + keyResultDto)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java index e285304f06..11131e7c73 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult; +import java.util.List; + import ch.puzzle.okr.dto.keyresult.*; import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.models.Action; @@ -10,9 +12,8 @@ import ch.puzzle.okr.service.business.CheckInBusinessService; import ch.puzzle.okr.service.business.ObjectiveBusinessService; import ch.puzzle.okr.service.business.UserBusinessService; -import org.springframework.stereotype.Component; -import java.util.List; +import org.springframework.stereotype.Component; @Component public class KeyResultMetricMapper { @@ -22,9 +23,7 @@ public class KeyResultMetricMapper { private final CheckInBusinessService checkInBusinessService; private final ActionMapper actionMapper; - public KeyResultMetricMapper(UserBusinessService userBusinessService, - ObjectiveBusinessService objectiveBusinessService, CheckInBusinessService checkInBusinessService, - ActionMapper actionMapper) { + public KeyResultMetricMapper(UserBusinessService userBusinessService, ObjectiveBusinessService objectiveBusinessService, CheckInBusinessService checkInBusinessService, ActionMapper actionMapper) { this.userBusinessService = userBusinessService; this.objectiveBusinessService = objectiveBusinessService; this.checkInBusinessService = checkInBusinessService; @@ -33,54 +32,73 @@ public KeyResultMetricMapper(UserBusinessService userBusinessService, public KeyResultDto toDto(KeyResultMetric keyResult, List actionList) { KeyResultUserDto ownerDto = new KeyResultUserDto( // - keyResult.getOwner().getId(), // - keyResult.getOwner().getFirstname(), // - keyResult.getOwner().getLastname()); + keyResult.getOwner() + .getId(), // + keyResult.getOwner() + .getFirstname(), // + keyResult.getOwner() + .getLastname()); KeyResultQuarterDto quarterDto = new KeyResultQuarterDto( // - keyResult.getObjective().getQuarter().getId(), // - keyResult.getObjective().getQuarter().getLabel(), // - keyResult.getObjective().getQuarter().getStartDate(), // - keyResult.getObjective().getQuarter().getEndDate()); + keyResult.getObjective() + .getQuarter() + .getId(), // + keyResult.getObjective() + .getQuarter() + .getLabel(), // + keyResult.getObjective() + .getQuarter() + .getStartDate(), // + keyResult.getObjective() + .getQuarter() + .getEndDate()); KeyResultObjectiveDto objectiveDto = new KeyResultObjectiveDto( // - keyResult.getObjective().getId(), // - keyResult.getObjective().getState().toString(), // - quarterDto); + keyResult.getObjective() + .getId(), // + keyResult.getObjective() + .getState() + .toString(), // + quarterDto); KeyResultLastCheckInMetricDto lastCheckInDto = getLastCheckInDto(keyResult.getId()); return new KeyResultMetricDto( // - keyResult.getId(), // - keyResult.getVersion(), // - keyResult.getKeyResultType(), // - keyResult.getTitle(), // - keyResult.getDescription(), // - keyResult.getBaseline(), // - keyResult.getStretchGoal(), // - keyResult.getUnit(), // - ownerDto, objectiveDto, // - lastCheckInDto, // - keyResult.getCreatedOn(), // - keyResult.getModifiedOn(), // - keyResult.isWriteable(), // - actionList.stream().map(actionMapper::toDto).toList()); + keyResult.getId(), // + keyResult.getVersion(), // + keyResult.getKeyResultType(), // + keyResult.getTitle(), // + keyResult.getDescription(), // + keyResult.getBaseline(), // + keyResult.getStretchGoal(), // + keyResult.getUnit(), // + ownerDto, + objectiveDto, // + lastCheckInDto, // + keyResult.getCreatedOn(), // + keyResult.getModifiedOn(), // + keyResult.isWriteable(), // + actionList.stream() + .map(actionMapper::toDto) + .toList()); } public KeyResult toKeyResultMetric(KeyResultMetricDto keyResultMetricDto) { return KeyResultMetric.Builder.builder() // - .withBaseline(keyResultMetricDto.baseline()) // - .withStretchGoal(keyResultMetricDto.stretchGoal()) // - .withUnit(keyResultMetricDto.unit()) // - .withId(keyResultMetricDto.id()) // - .withVersion(keyResultMetricDto.version()) // - .withObjective(objectiveBusinessService.getEntityById(keyResultMetricDto.objective().id())) // - .withTitle(keyResultMetricDto.title()) // - .withDescription(keyResultMetricDto.description()) // - .withOwner(userBusinessService.getUserById(keyResultMetricDto.owner().id())) // - .withCreatedOn(keyResultMetricDto.createdOn()) // - .withModifiedOn(keyResultMetricDto.modifiedOn()) // - .build(); + .withBaseline(keyResultMetricDto.baseline()) // + .withStretchGoal(keyResultMetricDto.stretchGoal()) // + .withUnit(keyResultMetricDto.unit()) // + .withId(keyResultMetricDto.id()) // + .withVersion(keyResultMetricDto.version()) // + .withObjective(objectiveBusinessService.getEntityById(keyResultMetricDto.objective() + .id())) // + .withTitle(keyResultMetricDto.title()) // + .withDescription(keyResultMetricDto.description()) // + .withOwner(userBusinessService.getUserById(keyResultMetricDto.owner() + .id())) // + .withCreatedOn(keyResultMetricDto.createdOn()) // + .withModifiedOn(keyResultMetricDto.modifiedOn()) // + .build(); } public KeyResultLastCheckInMetricDto getLastCheckInDto(Long keyResultId) { @@ -88,8 +106,12 @@ public KeyResultLastCheckInMetricDto getLastCheckInDto(Long keyResultId) { if (lastCheckIn == null) { return null; } - return new KeyResultLastCheckInMetricDto(lastCheckIn.getId(), lastCheckIn.getVersion(), - ((CheckInMetric) lastCheckIn).getValue(), lastCheckIn.getConfidence(), lastCheckIn.getCreatedOn(), - lastCheckIn.getChangeInfo(), lastCheckIn.getInitiatives()); + return new KeyResultLastCheckInMetricDto(lastCheckIn.getId(), + lastCheckIn.getVersion(), + ((CheckInMetric) lastCheckIn).getValue(), + lastCheckIn.getConfidence(), + lastCheckIn.getCreatedOn(), + lastCheckIn.getChangeInfo(), + lastCheckIn.getInitiatives()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java index e62c93b482..39a5954d35 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult; +import java.util.List; + import ch.puzzle.okr.dto.keyresult.*; import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.models.Action; @@ -10,9 +12,8 @@ import ch.puzzle.okr.service.business.CheckInBusinessService; import ch.puzzle.okr.service.business.ObjectiveBusinessService; import ch.puzzle.okr.service.business.UserBusinessService; -import org.springframework.stereotype.Component; -import java.util.List; +import org.springframework.stereotype.Component; @Component public class KeyResultOrdinalMapper { @@ -22,9 +23,7 @@ public class KeyResultOrdinalMapper { private final CheckInBusinessService checkInBusinessService; private final ActionMapper actionMapper; - public KeyResultOrdinalMapper(UserBusinessService userBusinessService, - ObjectiveBusinessService objectiveBusinessService, CheckInBusinessService checkInBusinessService, - ActionMapper actionMapper) { + public KeyResultOrdinalMapper(UserBusinessService userBusinessService, ObjectiveBusinessService objectiveBusinessService, CheckInBusinessService checkInBusinessService, ActionMapper actionMapper) { this.userBusinessService = userBusinessService; this.objectiveBusinessService = objectiveBusinessService; this.checkInBusinessService = checkInBusinessService; @@ -33,55 +32,73 @@ public KeyResultOrdinalMapper(UserBusinessService userBusinessService, public KeyResultDto toDto(KeyResultOrdinal keyResult, List actionList) { KeyResultUserDto ownerDto = new KeyResultUserDto( // - keyResult.getOwner().getId(), // - keyResult.getOwner().getFirstname(), // - keyResult.getOwner().getLastname()); + keyResult.getOwner() + .getId(), // + keyResult.getOwner() + .getFirstname(), // + keyResult.getOwner() + .getLastname()); KeyResultQuarterDto quarterDto = new KeyResultQuarterDto( // - keyResult.getObjective().getQuarter().getId(), // - keyResult.getObjective().getQuarter().getLabel(), // - keyResult.getObjective().getQuarter().getStartDate(), // - keyResult.getObjective().getQuarter().getEndDate()); + keyResult.getObjective() + .getQuarter() + .getId(), // + keyResult.getObjective() + .getQuarter() + .getLabel(), // + keyResult.getObjective() + .getQuarter() + .getStartDate(), // + keyResult.getObjective() + .getQuarter() + .getEndDate()); KeyResultObjectiveDto objectiveDto = new KeyResultObjectiveDto( // - keyResult.getObjective().getId(), // - keyResult.getObjective().getState().toString(), // - quarterDto); + keyResult.getObjective() + .getId(), // + keyResult.getObjective() + .getState() + .toString(), // + quarterDto); KeyResultLastCheckInOrdinalDto lastCheckInDto = getLastCheckInDto(keyResult.getId()); return new KeyResultOrdinalDto( // - keyResult.getId(), // - keyResult.getVersion(), // - keyResult.getKeyResultType(), // - keyResult.getTitle(), // - keyResult.getDescription(), // - keyResult.getCommitZone(), // - keyResult.getTargetZone(), // - keyResult.getStretchZone(), // - ownerDto, // - objectiveDto, // - lastCheckInDto, // - keyResult.getCreatedOn(), // - keyResult.getModifiedOn(), // - keyResult.isWriteable(), // - actionList.stream().map(actionMapper::toDto).toList()); + keyResult.getId(), // + keyResult.getVersion(), // + keyResult.getKeyResultType(), // + keyResult.getTitle(), // + keyResult.getDescription(), // + keyResult.getCommitZone(), // + keyResult.getTargetZone(), // + keyResult.getStretchZone(), // + ownerDto, // + objectiveDto, // + lastCheckInDto, // + keyResult.getCreatedOn(), // + keyResult.getModifiedOn(), // + keyResult.isWriteable(), // + actionList.stream() + .map(actionMapper::toDto) + .toList()); } public KeyResult toKeyResultOrdinal(KeyResultOrdinalDto keyResultOrdinalDto) { return KeyResultOrdinal.Builder.builder() // - .withCommitZone(keyResultOrdinalDto.commitZone()) // - .withTargetZone(keyResultOrdinalDto.targetZone()) // - .withStretchZone(keyResultOrdinalDto.stretchZone()) // - .withId(keyResultOrdinalDto.id()) // - .withVersion(keyResultOrdinalDto.version()) // - .withObjective(objectiveBusinessService.getEntityById(keyResultOrdinalDto.objective().id())) // - .withTitle(keyResultOrdinalDto.title()) // - .withDescription(keyResultOrdinalDto.description()) // - .withOwner(userBusinessService.getUserById(keyResultOrdinalDto.owner().id())) // - .withCreatedOn(keyResultOrdinalDto.createdOn()) // - .withModifiedOn(keyResultOrdinalDto.modifiedOn()) // - .build(); + .withCommitZone(keyResultOrdinalDto.commitZone()) // + .withTargetZone(keyResultOrdinalDto.targetZone()) // + .withStretchZone(keyResultOrdinalDto.stretchZone()) // + .withId(keyResultOrdinalDto.id()) // + .withVersion(keyResultOrdinalDto.version()) // + .withObjective(objectiveBusinessService.getEntityById(keyResultOrdinalDto.objective() + .id())) // + .withTitle(keyResultOrdinalDto.title()) // + .withDescription(keyResultOrdinalDto.description()) // + .withOwner(userBusinessService.getUserById(keyResultOrdinalDto.owner() + .id())) // + .withCreatedOn(keyResultOrdinalDto.createdOn()) // + .withModifiedOn(keyResultOrdinalDto.modifiedOn()) // + .build(); } public KeyResultLastCheckInOrdinalDto getLastCheckInDto(Long keyResultId) { @@ -89,8 +106,12 @@ public KeyResultLastCheckInOrdinalDto getLastCheckInDto(Long keyResultId) { if (lastCheckIn == null) { return null; } - return new KeyResultLastCheckInOrdinalDto(lastCheckIn.getId(), lastCheckIn.getVersion(), - ((CheckInOrdinal) lastCheckIn).getZone(), lastCheckIn.getConfidence(), lastCheckIn.getCreatedOn(), - lastCheckIn.getChangeInfo(), lastCheckIn.getInitiatives()); + return new KeyResultLastCheckInOrdinalDto(lastCheckIn.getId(), + lastCheckIn.getVersion(), + ((CheckInOrdinal) lastCheckIn).getZone(), + lastCheckIn.getConfidence(), + lastCheckIn.getCreatedOn(), + lastCheckIn.getChangeInfo(), + lastCheckIn.getInitiatives()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/models/Action.java b/backend/src/main/java/ch/puzzle/okr/models/Action.java index eabed114da..10aba1cc35 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Action.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Action.java @@ -1,11 +1,12 @@ package ch.puzzle.okr.models; +import java.util.Objects; + import ch.puzzle.okr.models.keyresult.KeyResult; import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.Objects; @Entity public class Action implements WriteableInterface { @@ -17,18 +18,14 @@ public class Action implements WriteableInterface { @Version private int version; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Size(max = 4096, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Size(max = 4096, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String action; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private int priority; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private int priority; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private boolean isChecked; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private boolean isChecked; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private KeyResult keyResult; private transient boolean writeable; @@ -105,8 +102,7 @@ public void setWriteable(boolean writeable) { @Override public String toString() { - return "Action{" + "id=" + id + ", version=" + version + ", action='" + action + '\'' + ", priority=" + priority - + ", isChecked=" + isChecked + ", keyResult=" + keyResult + ", writeable=" + writeable + '}'; + return "Action{" + "id=" + id + ", version=" + version + ", action='" + action + '\'' + ", priority=" + priority + ", isChecked=" + isChecked + ", keyResult=" + keyResult + ", writeable=" + writeable + '}'; } @Override @@ -116,9 +112,10 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Action action1 = (Action) o; - return version == action1.version && priority == action1.priority && isChecked == action1.isChecked - && writeable == action1.writeable && Objects.equals(id, action1.id) - && Objects.equals(action, action1.action) && Objects.equals(keyResult, action1.keyResult); + return version == action1.version && priority == action1.priority && isChecked == action1.isChecked && writeable == action1.writeable && Objects.equals(id, + action1.id) && Objects.equals(action, + action1.action) && Objects.equals(keyResult, + action1.keyResult); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/Completed.java b/backend/src/main/java/ch/puzzle/okr/models/Completed.java index 7900c2910e..e6880cbf97 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Completed.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Completed.java @@ -1,9 +1,10 @@ package ch.puzzle.okr.models; +import java.util.Objects; + import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.Objects; @Entity public class Completed { @@ -15,8 +16,7 @@ public class Completed { @Version private int version; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @OneToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @OneToOne private Objective objective; @Size(max = 4096, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) @@ -58,8 +58,7 @@ public void setComment(String comment) { @Override public String toString() { - return "Completed{" + "id=" + id + ", version=" + version + ", objective=" + objective + ", comment='" + comment - + '\'' + '}'; + return "Completed{" + "id=" + id + ", version=" + version + ", objective=" + objective + ", comment='" + comment + '\'' + '}'; } @Override @@ -69,8 +68,9 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Completed completed = (Completed) o; - return Objects.equals(id, completed.id) && version == completed.version - && Objects.equals(objective, completed.objective) && Objects.equals(comment, completed.comment); + return Objects.equals(id, completed.id) && version == completed.version && Objects.equals(objective, + completed.objective) && Objects.equals(comment, + completed.comment); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/Objective.java b/backend/src/main/java/ch/puzzle/okr/models/Objective.java index 85a96b59dd..7cab2338be 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Objective.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Objective.java @@ -1,15 +1,15 @@ package ch.puzzle.okr.models; +import java.time.LocalDateTime; +import java.util.Objects; + import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.time.LocalDateTime; -import java.util.Objects; - @Entity -@Table(indexes = { @Index(name = "idx_objective_title", columnList = "title") }) +@Table(indexes = {@Index(name = "idx_objective_title", columnList = "title")}) public class Objective implements WriteableInterface { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "sequence_objective") @@ -20,31 +20,25 @@ public class Objective implements WriteableInterface { private int version; @NotBlank(message = MessageKey.ATTRIBUTE_NOT_BLANK) - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String title; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Enumerated(EnumType.STRING) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Enumerated(EnumType.STRING) private State state; @Size(max = 4096, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String description; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private Team team; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private Quarter quarter; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private User createdBy; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private LocalDateTime createdOn; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private LocalDateTime createdOn; private LocalDateTime modifiedOn; @@ -162,10 +156,7 @@ public void setWriteable(boolean writeable) { @Override public String toString() { - return "Objective{" + "id=" + id + ", version=" + version + ", title='" + title + '\'' + ", createdBy=" - + createdBy + ", team=" + team + ", quarter=" + quarter + ", description='" + description + '\'' - + ", modifiedOn=" + modifiedOn + ", state=" + state + ", createdOn=" + createdOn + ", modifiedBy=" - + modifiedBy + ", writeable=" + writeable + '\'' + '}'; + return "Objective{" + "id=" + id + ", version=" + version + ", title='" + title + '\'' + ", createdBy=" + createdBy + ", team=" + team + ", quarter=" + quarter + ", description='" + description + '\'' + ", modifiedOn=" + modifiedOn + ", state=" + state + ", createdOn=" + createdOn + ", modifiedBy=" + modifiedBy + ", writeable=" + writeable + '\'' + '}'; } @Override @@ -175,18 +166,30 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Objective objective = (Objective) o; - return Objects.equals(id, objective.id) && version == objective.version - && Objects.equals(title, objective.title) && Objects.equals(createdBy, objective.createdBy) - && Objects.equals(team, objective.team) && Objects.equals(quarter, objective.quarter) - && Objects.equals(description, objective.description) - && Objects.equals(modifiedOn, objective.modifiedOn) && state == objective.state - && Objects.equals(createdOn, objective.createdOn) && Objects.equals(modifiedBy, objective.modifiedBy); + return Objects.equals(id, objective.id) && version == objective.version && Objects.equals(title, + objective.title) && Objects.equals(createdBy, + objective.createdBy) && Objects.equals(team, + objective.team) && Objects.equals(quarter, + objective.quarter) && Objects.equals(description, + objective.description) && Objects.equals(modifiedOn, + objective.modifiedOn) && state == objective.state && Objects.equals(createdOn, + objective.createdOn) && Objects.equals(modifiedBy, + objective.modifiedBy); } @Override public int hashCode() { - return Objects.hash(id, version, title, createdBy, team, quarter, description, modifiedOn, state, createdOn, - modifiedBy); + return Objects.hash(id, + version, + title, + createdBy, + team, + quarter, + description, + modifiedOn, + state, + createdOn, + modifiedBy); } public static final class Builder { diff --git a/backend/src/main/java/ch/puzzle/okr/models/Quarter.java b/backend/src/main/java/ch/puzzle/okr/models/Quarter.java index 537e0aa955..57cc87f746 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Quarter.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Quarter.java @@ -1,11 +1,11 @@ package ch.puzzle.okr.models; -import jakarta.persistence.*; -import jakarta.validation.constraints.NotNull; - import java.time.LocalDate; import java.util.Objects; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; + @Entity public class Quarter { @Id @@ -13,8 +13,7 @@ public class Quarter { @SequenceGenerator(name = "sequence_quarter", allocationSize = 1) private Long id; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Column(unique = true) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Column(unique = true) private String label; private LocalDate startDate; @@ -61,8 +60,7 @@ public void setEndDate(LocalDate endDate) { @Override public String toString() { - return "Quarter{" + "id=" + id + ", label='" + label + '\'' + ", startDate=" + startDate + ", endDate=" - + endDate + '}'; + return "Quarter{" + "id=" + id + ", label='" + label + '\'' + ", startDate=" + startDate + ", endDate=" + endDate + '}'; } @Override @@ -72,8 +70,9 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Quarter quarter = (Quarter) o; - return Objects.equals(id, quarter.id) && Objects.equals(label, quarter.label) - && Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate); + return Objects.equals(id, quarter.id) && Objects.equals(label, quarter.label) && Objects.equals(startDate, + quarter.startDate) && Objects.equals(endDate, + quarter.endDate); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/Team.java b/backend/src/main/java/ch/puzzle/okr/models/Team.java index 0099a9ba43..28d311a015 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Team.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Team.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.models; +import java.util.List; +import java.util.Objects; + import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.List; -import java.util.Objects; - @Entity public class Team implements WriteableInterface { @Id @@ -16,8 +16,7 @@ public class Team implements WriteableInterface { private Long id; @NotBlank(message = MessageKey.ATTRIBUTE_NOT_BLANK) - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String name; @Version @@ -84,8 +83,9 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Team team = (Team) o; - return Objects.equals(id, team.id) && Objects.equals(version, team.version) && Objects.equals(name, team.name) - && Objects.equals(writeable, team.writeable); + return Objects.equals(id, team.id) && Objects.equals(version, team.version) && Objects.equals(name, + team.name) && Objects.equals(writeable, + team.writeable); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/User.java b/backend/src/main/java/ch/puzzle/okr/models/User.java index 5bfa5e425b..408fd549da 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/User.java +++ b/backend/src/main/java/ch/puzzle/okr/models/User.java @@ -1,15 +1,15 @@ package ch.puzzle.okr.models; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + import jakarta.persistence.*; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - @Entity // table cannot be named "user" since it is a reserved keyword of Postgres @Table(name = "person") @@ -23,20 +23,17 @@ public class User { private int version; @NotBlank(message = MessageKey.ATTRIBUTE_NOT_BLANK) - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Size(min = 2, max = 50, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Size(min = 2, max = 50, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String firstname; @NotBlank(message = MessageKey.ATTRIBUTE_NOT_BLANK) - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Size(min = 2, max = 50, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Size(min = 2, max = 50, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String lastname; @Column(unique = true, nullable = false) @Email(message = MessageKey.ATTRIBUTE_NOT_VALID) @NotBlank(message = MessageKey.ATTRIBUTE_NOT_BLANK) - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String email; @OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = CascadeType.ALL) @@ -108,8 +105,7 @@ public void setOkrChampion(boolean okrChampion) { @Override public String toString() { - return "User{" + "id=" + id + ", version=" + version + ", firstname='" + firstname + '\'' + ", lastname='" - + lastname + '\'' + ", email='" + email + '\'' + ", isOkrChampion='" + isOkrChampion + '\'' + '}'; + return "User{" + "id=" + id + ", version=" + version + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' + ", email='" + email + '\'' + ", isOkrChampion='" + isOkrChampion + '\'' + '}'; } @Override @@ -119,9 +115,11 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; User user = (User) o; - return Objects.equals(id, user.id) && Objects.equals(version, user.version) - && Objects.equals(firstname, user.firstname) && Objects.equals(lastname, user.lastname) - && Objects.equals(email, user.email) && Objects.equals(isOkrChampion, user.isOkrChampion); + return Objects.equals(id, user.id) && Objects.equals(version, user.version) && Objects.equals(firstname, + user.firstname) && Objects.equals(lastname, + user.lastname) && Objects.equals(email, + user.email) && Objects.equals(isOkrChampion, + user.isOkrChampion); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java b/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java index 3f14e7c811..71c19ac805 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java +++ b/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java @@ -1,9 +1,9 @@ package ch.puzzle.okr.models; -import jakarta.persistence.*; - import java.util.Objects; +import jakarta.persistence.*; + @Entity @Table(name = "person_team") public class UserTeam { @@ -16,12 +16,10 @@ public class UserTeam { @Version private int version; - @ManyToOne() - @JoinColumn(name = "person_id") + @ManyToOne() @JoinColumn(name = "person_id") private User user; - @ManyToOne() - @JoinColumn(name = "team_id") + @ManyToOne() @JoinColumn(name = "team_id") private Team team; @Column(nullable = false, columnDefinition = "boolean default false") @@ -87,8 +85,10 @@ public boolean equals(Object o) { return false; } UserTeam userTeam = (UserTeam) o; - return version == userTeam.version && isTeamAdmin == userTeam.isTeamAdmin && Objects.equals(id, userTeam.id) - && Objects.equals(user, userTeam.user) && Objects.equals(team, userTeam.team); + return version == userTeam.version && isTeamAdmin == userTeam.isTeamAdmin && Objects.equals(id, + userTeam.id) && Objects.equals(user, + userTeam.user) && Objects.equals(team, + userTeam.team); } @Override @@ -98,8 +98,7 @@ public int hashCode() { @Override public String toString() { - return "UserTeam{" + "id=" + id + ", version=" + version + ", user=" + user + ", team=" + team - + ", isTeamAdmin=" + isTeamAdmin + '}'; + return "UserTeam{" + "id=" + id + ", version=" + version + ", user=" + user + ", team=" + team + ", isTeamAdmin=" + isTeamAdmin + '}'; } public static class Builder { diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java index cf3a64f7fc..cb5f8a6f5e 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.models.alignment; +import java.util.Objects; + import ch.puzzle.okr.models.Objective; import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; -import java.util.Objects; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @@ -17,8 +18,7 @@ public abstract class Alignment { private Long id; @Version private int version; - @NotNull(message = "Aligned objective must not be null") - @ManyToOne + @NotNull(message = "Aligned objective must not be null") @ManyToOne private Objective alignedObjective; protected Alignment() { @@ -58,8 +58,8 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Alignment alignment = (Alignment) o; - return Objects.equals(id, alignment.id) && version == alignment.version - && Objects.equals(alignedObjective, alignment.alignedObjective); + return Objects.equals(id, alignment.id) && version == alignment.version && Objects.equals(alignedObjective, + alignment.alignedObjective); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java index 0246817184..738342f9dd 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.models.alignment; -import jakarta.persistence.EmbeddedId; -import jakarta.persistence.Entity; +import java.util.Objects; + import org.hibernate.annotations.Immutable; -import java.util.Objects; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; @Entity @Immutable @@ -60,11 +61,11 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; AlignmentSelection alignmentSelection = (AlignmentSelection) o; - return Objects.equals(alignmentSelectionId, alignmentSelection.alignmentSelectionId) - && Objects.equals(teamId, alignmentSelection.teamId) - && Objects.equals(objectiveTitle, alignmentSelection.objectiveTitle) - && Objects.equals(quarterId, alignmentSelection.quarterId) - && Objects.equals(keyResultTitle, alignmentSelection.keyResultTitle); + return Objects.equals(alignmentSelectionId, alignmentSelection.alignmentSelectionId) && Objects.equals(teamId, + alignmentSelection.teamId) && Objects.equals(objectiveTitle, + alignmentSelection.objectiveTitle) && Objects.equals(quarterId, + alignmentSelection.quarterId) && Objects.equals(keyResultTitle, + alignmentSelection.keyResultTitle); } @Override @@ -74,10 +75,7 @@ public int hashCode() { @Override public String toString() { - return "AlignmentSelection{" + "alignmentSelectionId=" + alignmentSelectionId + ", teamId='" + teamId - + ", teamName='" + teamName + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", quarterId=" - + quarterId + ", quarterLabel='" + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' - + '}'; + return "AlignmentSelection{" + "alignmentSelectionId=" + alignmentSelectionId + ", teamId='" + teamId + ", teamName='" + teamName + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", quarterId=" + quarterId + ", quarterLabel='" + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' + '}'; } public static final class Builder { diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java index 75c52cf2b8..4e934bd742 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java @@ -1,10 +1,10 @@ package ch.puzzle.okr.models.alignment; -import jakarta.persistence.Embeddable; - import java.io.Serializable; import java.util.Objects; +import jakarta.persistence.Embeddable; + @Embeddable public class AlignmentSelectionId implements Serializable { diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java index 1797ca005b..d3aa4bf54b 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java @@ -1,9 +1,10 @@ package ch.puzzle.okr.models.alignment; +import java.util.Objects; + import ch.puzzle.okr.models.keyresult.KeyResult; import jakarta.persistence.*; -import java.util.Objects; @Entity @DiscriminatorValue("keyResult") diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java index f15422894f..8794ffb020 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java @@ -1,12 +1,13 @@ package ch.puzzle.okr.models.alignment; +import java.util.Objects; + import ch.puzzle.okr.models.Objective; + import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; -import java.util.Objects; - @Entity @DiscriminatorValue("objective") public class ObjectiveAlignment extends Alignment implements AlignmentInterface { diff --git a/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java b/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java index 829ba69765..302a657865 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java +++ b/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java @@ -1,20 +1,31 @@ package ch.puzzle.okr.models.authorization; -import ch.puzzle.okr.models.User; - import java.util.List; +import ch.puzzle.okr.models.User; + public record AuthorizationUser(User user) { public List extractTeamIds() { - return this.user.getUserTeamList().stream().map(userTeam -> userTeam.getTeam().getId()).toList(); + return this.user.getUserTeamList() + .stream() + .map(userTeam -> userTeam.getTeam() + .getId()) + .toList(); } public boolean isUserMemberInTeam(Long teamId) { - return this.user.getUserTeamList().stream().anyMatch(ut -> ut.getTeam().getId().equals(teamId)); + return this.user.getUserTeamList() + .stream() + .anyMatch(ut -> ut.getTeam() + .getId() + .equals(teamId)); } public boolean isUserAdminInTeam(Long teamId) { - return this.user.getUserTeamList().stream() - .anyMatch(ut -> ut.isTeamAdmin() && ut.getTeam().getId().equals(teamId)); + return this.user.getUserTeamList() + .stream() + .anyMatch(ut -> ut.isTeamAdmin() && ut.getTeam() + .getId() + .equals(teamId)); } } diff --git a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java index 7105ca5950..e8ca61fedd 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java +++ b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.models.checkin; +import java.time.LocalDateTime; +import java.util.Objects; + import ch.puzzle.okr.models.MessageKey; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.WriteableInterface; @@ -8,9 +11,6 @@ import jakarta.persistence.*; import jakarta.validation.constraints.*; -import java.time.LocalDateTime; -import java.util.Objects; - @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "check_in_type") @@ -31,19 +31,15 @@ public abstract class CheckIn implements WriteableInterface { @Max(value = 10, message = MessageKey.ATTRIBUTE_MAX_VALUE) @Min(value = 0, message = MessageKey.ATTRIBUTE_MIN_VALUE) - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private Integer confidence; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private Integer confidence; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private KeyResult keyResult; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private User createdBy; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private LocalDateTime createdOn; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private LocalDateTime createdOn; private LocalDateTime modifiedOn; @@ -133,10 +129,7 @@ public void setWriteable(boolean writeable) { @Override public String toString() { - return "CheckIn{" + "id=" + id + ", version=" + version + ", changeInfo='" + changeInfo + '\'' - + ", initiatives='" + initiatives + '\'' + ", confidence=" + confidence + ", keyResult=" + keyResult - + ", createdBy=" + createdBy + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn - + ", checkInType='" + checkInType + '\'' + ", writeable=" + writeable + '\'' + '}'; + return "CheckIn{" + "id=" + id + ", version=" + version + ", changeInfo='" + changeInfo + '\'' + ", initiatives='" + initiatives + '\'' + ", confidence=" + confidence + ", keyResult=" + keyResult + ", createdBy=" + createdBy + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + ", checkInType='" + checkInType + '\'' + ", writeable=" + writeable + '\'' + '}'; } @Override @@ -146,17 +139,29 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; CheckIn checkIn = (CheckIn) o; - return Objects.equals(id, checkIn.id) && version == checkIn.version - && Objects.equals(changeInfo, checkIn.changeInfo) && Objects.equals(initiatives, checkIn.initiatives) - && Objects.equals(confidence, checkIn.confidence) && Objects.equals(keyResult, checkIn.keyResult) - && Objects.equals(createdBy, checkIn.createdBy) && Objects.equals(createdOn, checkIn.createdOn) - && Objects.equals(modifiedOn, checkIn.modifiedOn) && Objects.equals(checkInType, checkIn.checkInType); + return Objects.equals(id, checkIn.id) && version == checkIn.version && Objects.equals(changeInfo, + checkIn.changeInfo) && Objects.equals(initiatives, + checkIn.initiatives) && Objects.equals(confidence, + checkIn.confidence) && Objects.equals(keyResult, + checkIn.keyResult) && Objects.equals(createdBy, + checkIn.createdBy) && Objects.equals(createdOn, + checkIn.createdOn) && Objects.equals(modifiedOn, + checkIn.modifiedOn) && Objects.equals(checkInType, + checkIn.checkInType); } @Override public int hashCode() { - return Objects.hash(id, version, changeInfo, initiatives, confidence, keyResult, createdBy, createdOn, - modifiedOn, checkInType); + return Objects.hash(id, + version, + changeInfo, + initiatives, + confidence, + keyResult, + createdBy, + createdOn, + modifiedOn, + checkInType); } /* Constructor */ diff --git a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java index 25faccff0e..69ba056f59 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java +++ b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java @@ -1,19 +1,19 @@ package ch.puzzle.okr.models.checkin; +import java.util.Objects; + import ch.puzzle.okr.models.MessageKey; + import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.validation.constraints.NotNull; -import java.util.Objects; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; @Entity @DiscriminatorValue(KEY_RESULT_TYPE_METRIC) public class CheckInMetric extends CheckIn { - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private Double valueMetric; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private Double valueMetric; /* Getter and Setter */ public Double getValue() { diff --git a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java index 62485b5101..01d47bc7c1 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java +++ b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java @@ -1,21 +1,21 @@ package ch.puzzle.okr.models.checkin; +import java.util.Objects; + import ch.puzzle.okr.models.MessageKey; + import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.validation.constraints.NotNull; -import java.util.Objects; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; @Entity @DiscriminatorValue(KEY_RESULT_TYPE_ORDINAL) public class CheckInOrdinal extends CheckIn { - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Enumerated(EnumType.STRING) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Enumerated(EnumType.STRING) private Zone zone; /* Getter and Setter */ diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java index 2db94c8b9e..b7bc061b35 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.models.keyresult; +import java.time.LocalDateTime; +import java.util.Objects; + import ch.puzzle.okr.models.MessageKey; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; @@ -9,8 +12,6 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.time.LocalDateTime; -import java.util.Objects; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @@ -24,28 +25,23 @@ public abstract class KeyResult implements WriteableInterface { @Version private int version; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private Objective objective; @NotBlank(message = MessageKey.ATTRIBUTE_NOT_BLANK) - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Size(min = 2, max = 250, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String title; @Size(max = 4096, message = MessageKey.ATTRIBUTE_SIZE_BETWEEN) private String description; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private User owner; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @ManyToOne + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @ManyToOne private User createdBy; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private LocalDateTime createdOn; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private LocalDateTime createdOn; private LocalDateTime modifiedOn; @@ -138,10 +134,7 @@ public void setWriteable(boolean writeable) { @Override public String toString() { - return "KeyResult{" + "id=" + id + ", version=" + version + ", objective=" + objective + ", title='" + title - + '\'' + ", description='" + description + '\'' + ", owner=" + owner + ", createdBy=" + createdBy - + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + ", keyResultType='" + keyResultType - + ", writeable=" + writeable + '\'' + '}'; + return "KeyResult{" + "id=" + id + ", version=" + version + ", objective=" + objective + ", title='" + title + '\'' + ", description='" + description + '\'' + ", owner=" + owner + ", createdBy=" + createdBy + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + ", keyResultType='" + keyResultType + ", writeable=" + writeable + '\'' + '}'; } @Override @@ -151,18 +144,29 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; KeyResult keyResult = (KeyResult) o; - return Objects.equals(id, keyResult.id) && version == keyResult.version - && Objects.equals(objective, keyResult.objective) && Objects.equals(title, keyResult.title) - && Objects.equals(description, keyResult.description) && Objects.equals(owner, keyResult.owner) - && Objects.equals(createdBy, keyResult.createdBy) && Objects.equals(createdOn, keyResult.createdOn) - && Objects.equals(modifiedOn, keyResult.modifiedOn) - && Objects.equals(keyResultType, keyResult.keyResultType); + return Objects.equals(id, keyResult.id) && version == keyResult.version && Objects.equals(objective, + keyResult.objective) && Objects.equals(title, + keyResult.title) && Objects.equals(description, + keyResult.description) && Objects.equals(owner, + keyResult.owner) && Objects.equals(createdBy, + keyResult.createdBy) && Objects.equals(createdOn, + keyResult.createdOn) && Objects.equals(modifiedOn, + keyResult.modifiedOn) && Objects.equals(keyResultType, + keyResult.keyResultType); } @Override public int hashCode() { - return Objects.hash(id, version, objective, title, description, owner, createdBy, createdOn, modifiedOn, - keyResultType); + return Objects.hash(id, + version, + objective, + title, + description, + owner, + createdBy, + createdOn, + modifiedOn, + keyResultType); } protected KeyResult() { diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java index 773501abc4..d0e3075be5 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java @@ -1,25 +1,23 @@ package ch.puzzle.okr.models.keyresult; +import java.util.Objects; + import ch.puzzle.okr.models.MessageKey; import ch.puzzle.okr.models.Unit; import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; -import java.util.Objects; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; @Entity @DiscriminatorValue(KEY_RESULT_TYPE_METRIC) public class KeyResultMetric extends KeyResult { - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private Double baseline; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private Double baseline; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - private Double stretchGoal; + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) private Double stretchGoal; - @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) - @Enumerated(EnumType.STRING) + @NotNull(message = MessageKey.ATTRIBUTE_NOT_NULL) @Enumerated(EnumType.STRING) private Unit unit; public Double getBaseline() { @@ -53,9 +51,10 @@ public KeyResultMetric() { @Override public boolean equals(Object o) { if (o instanceof KeyResultMetric) { - return super.equals(o) && Objects.equals(baseline, ((KeyResultMetric) o).baseline) - && Objects.equals(stretchGoal, ((KeyResultMetric) o).stretchGoal) - && Objects.equals(unit, ((KeyResultMetric) o).unit); + return super.equals(o) && Objects.equals(baseline, ((KeyResultMetric) o).baseline) && Objects.equals( + stretchGoal, + ((KeyResultMetric) o).stretchGoal) && Objects.equals(unit, + ((KeyResultMetric) o).unit); } return false; } @@ -67,8 +66,7 @@ public int hashCode() { @Override public String toString() { - return super.toString() + "KeyResultMetric{" + "baseline=" + baseline + ", stretchGoal=" + stretchGoal - + ", unit='" + unit + '\'' + '}'; + return super.toString() + "KeyResultMetric{" + "baseline=" + baseline + ", stretchGoal=" + stretchGoal + ", unit='" + unit + '\'' + '}'; } private KeyResultMetric(Builder builder) { diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java index d95f92a302..2774397338 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java @@ -1,27 +1,24 @@ package ch.puzzle.okr.models.keyresult; +import java.util.Objects; + import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import java.util.Objects; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; @Entity @DiscriminatorValue(KEY_RESULT_TYPE_ORDINAL) public class KeyResultOrdinal extends KeyResult { - @NotNull(message = "CommitZone must not be null") - @Size(max = 400, message = "Attribute commitZone has a max length of 400 characters") + @NotNull(message = "CommitZone must not be null") @Size(max = 400, message = "Attribute commitZone has a max length of 400 characters") private String commitZone; - @NotNull(message = "TargetZone must not be null") - @Size(max = 400, message = "Attribute targetZone has a max length of 400 characters") + @NotNull(message = "TargetZone must not be null") @Size(max = 400, message = "Attribute targetZone has a max length of 400 characters") private String targetZone; - @NotNull(message = "StretchZone must not be null") - @Size(max = 400, message = "Attribute stretchZone has a max length of 400 characters") + @NotNull(message = "StretchZone must not be null") @Size(max = 400, message = "Attribute stretchZone has a max length of 400 characters") private String stretchZone; public String getCommitZone() { @@ -55,9 +52,10 @@ public KeyResultOrdinal() { @Override public boolean equals(Object o) { if (o instanceof KeyResultOrdinal) { - return super.equals(o) && Objects.equals(commitZone, ((KeyResultOrdinal) o).commitZone) - && Objects.equals(targetZone, ((KeyResultOrdinal) o).targetZone) - && Objects.equals(stretchZone, ((KeyResultOrdinal) o).stretchZone); + return super.equals(o) && Objects.equals(commitZone, ((KeyResultOrdinal) o).commitZone) && Objects.equals( + targetZone, + ((KeyResultOrdinal) o).targetZone) && Objects.equals(stretchZone, + ((KeyResultOrdinal) o).stretchZone); } return false; } @@ -69,8 +67,7 @@ public int hashCode() { @Override public String toString() { - return super.toString() + "KeyResultOrdinal{" + "commitZone='" + commitZone + '\'' + ", targetZone='" - + targetZone + '\'' + ", stretchZone='" + stretchZone + '\'' + '}'; + return super.toString() + "KeyResultOrdinal{" + "commitZone='" + commitZone + '\'' + ", targetZone='" + targetZone + '\'' + ", stretchZone='" + stretchZone + '\'' + '}'; } private KeyResultOrdinal(Builder builder) { diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java index 1fae579ab3..cf195e19ae 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java @@ -1,8 +1,8 @@ package ch.puzzle.okr.models.keyresult; -import ch.puzzle.okr.models.Action; - import java.util.List; +import ch.puzzle.okr.models.Action; + public record KeyResultWithActionList(KeyResult keyResult, List actionList) { } diff --git a/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java b/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java index b2b3eb6d79..d345b16e40 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java +++ b/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java @@ -1,14 +1,16 @@ package ch.puzzle.okr.models.overview; +import java.time.LocalDateTime; + import ch.puzzle.okr.models.State; import ch.puzzle.okr.models.WriteableInterface; + +import org.hibernate.annotations.Immutable; + import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; -import org.hibernate.annotations.Immutable; - -import java.time.LocalDateTime; @Entity @Immutable @@ -157,15 +159,7 @@ public void setWriteable(boolean writeable) { @Override public String toString() { - return "Overview{" + "overviewId=" + overviewId + ", teamVersion='" + teamVersion + ", teamName='" + teamName - + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", objectiveState=" + objectiveState - + ", objectiveCreatedOn=" + objectiveCreatedOn + ", quarterId=" + quarterId + ", quarterLabel='" - + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' + ", keyResultType='" - + keyResultType + '\'' + ", baseline=" + baseline + ", stretchGoal=" + stretchGoal + ", unit='" + unit - + '\'' + ", commitZone='" + commitZone + '\'' + ", targetZone='" + targetZone + '\'' + ", stretchZone='" - + stretchZone + '\'' + ", checkInValue=" + checkInValue + ", checkInZone='" + checkInZone + '\'' - + ", confidence=" + confidence + ", createdOn=" + checkInCreatedOn + ", writeable=" + writeable + '\'' - + '}'; + return "Overview{" + "overviewId=" + overviewId + ", teamVersion='" + teamVersion + ", teamName='" + teamName + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", objectiveState=" + objectiveState + ", objectiveCreatedOn=" + objectiveCreatedOn + ", quarterId=" + quarterId + ", quarterLabel='" + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' + ", keyResultType='" + keyResultType + '\'' + ", baseline=" + baseline + ", stretchGoal=" + stretchGoal + ", unit='" + unit + '\'' + ", commitZone='" + commitZone + '\'' + ", targetZone='" + targetZone + '\'' + ", stretchZone='" + stretchZone + '\'' + ", checkInValue=" + checkInValue + ", checkInZone='" + checkInZone + '\'' + ", confidence=" + confidence + ", createdOn=" + checkInCreatedOn + ", writeable=" + writeable + '\'' + '}'; } public static final class Builder { diff --git a/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java b/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java index 62bfb85e60..ce70a260d9 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java +++ b/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java @@ -1,10 +1,10 @@ package ch.puzzle.okr.models.overview; -import jakarta.persistence.Embeddable; - import java.io.Serializable; import java.util.Objects; +import jakarta.persistence.Embeddable; + @Embeddable public class OverviewId implements Comparable, Serializable { @@ -49,8 +49,7 @@ public Long getCheckInId() { @Override public String toString() { - return "OverviewId{" + "teamId=" + teamId + ", objectiveId=" + objectiveId + ", keyResultId=" + keyResultId - + ", checkInId=" + checkInId + '}'; + return "OverviewId{" + "teamId=" + teamId + ", objectiveId=" + objectiveId + ", keyResultId=" + keyResultId + ", checkInId=" + checkInId + '}'; } @Override @@ -60,8 +59,10 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; OverviewId that = (OverviewId) o; - return Objects.equals(teamId, that.teamId) && Objects.equals(objectiveId, that.objectiveId) - && Objects.equals(keyResultId, that.keyResultId) && Objects.equals(checkInId, that.checkInId); + return Objects.equals(teamId, that.teamId) && Objects.equals(objectiveId, that.objectiveId) && Objects.equals( + keyResultId, + that.keyResultId) && Objects.equals(checkInId, + that.checkInId); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java index d58c195c77..376fb94123 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java @@ -1,37 +1,39 @@ package ch.puzzle.okr.multitenancy; -import jakarta.persistence.EntityNotFoundException; import org.flywaydb.core.Flyway; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import jakarta.persistence.EntityNotFoundException; + @Component public class FlywayMultitenantMigrationInitializer { private final TenantConfigProviderInterface tenantConfigProvider; private final String[] scriptLocations; - public FlywayMultitenantMigrationInitializer(TenantConfigProviderInterface tenantConfigProvider, - final @Value("${spring.flyway.locations}") String[] scriptLocations) { + public FlywayMultitenantMigrationInitializer(TenantConfigProviderInterface tenantConfigProvider, final @Value("${spring.flyway.locations}") String[] scriptLocations) { this.tenantConfigProvider = tenantConfigProvider; this.scriptLocations = scriptLocations; } public void migrateFlyway() { - this.tenantConfigProvider.getTenantConfigs().forEach((tenantConfig) -> { - TenantConfigProvider.DataSourceConfig dataSourceConfig = this.tenantConfigProvider - .getTenantConfigById(tenantConfig.tenantId()) - .map(TenantConfigProvider.TenantConfig::dataSourceConfig).orElseThrow( - () -> new EntityNotFoundException("Cannot find tenant for configuring flyway migration")); - - Flyway tenantSchemaFlyway = Flyway.configure() // - .dataSource(dataSourceConfig.url(), dataSourceConfig.name(), dataSourceConfig.password()) // - .locations(scriptLocations) // - .baselineOnMigrate(Boolean.TRUE) // - .schemas(dataSourceConfig.schema()) // - .load(); - - tenantSchemaFlyway.migrate(); - }); + this.tenantConfigProvider.getTenantConfigs() + .forEach((tenantConfig) -> { + TenantConfigProvider.DataSourceConfig dataSourceConfig = this.tenantConfigProvider.getTenantConfigById(tenantConfig.tenantId()) + .map(TenantConfigProvider.TenantConfig::dataSourceConfig) + .orElseThrow(() -> new EntityNotFoundException("Cannot find tenant for configuring flyway migration")); + + Flyway tenantSchemaFlyway = Flyway.configure() // + .dataSource(dataSourceConfig.url(), + dataSourceConfig.name(), + dataSourceConfig.password()) // + .locations(scriptLocations) // + .baselineOnMigrate(Boolean.TRUE) // + .schemas(dataSourceConfig.schema()) // + .load(); + + tenantSchemaFlyway.migrate(); + }); } } \ No newline at end of file diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java index 42e068ece0..197b5fe371 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java @@ -1,9 +1,9 @@ package ch.puzzle.okr.multitenancy; -import org.springframework.core.env.ConfigurableEnvironment; - import java.util.Properties; +import org.springframework.core.env.ConfigurableEnvironment; + public class HibernateContext { public static final String HIBERNATE_CONNECTION_URL = "hibernate.connection.url"; public static final String HIBERNATE_CONNECTION_USERNAME = "hibernate.connection.username"; diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java index 05ff90ce53..fa0d8a40e2 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java @@ -1,6 +1,12 @@ package ch.puzzle.okr.multitenancy; +import java.sql.Connection; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.*; + import ch.puzzle.okr.exception.ConnectionProviderException; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; @@ -8,11 +14,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.Connection; -import java.sql.SQLException; -import java.text.MessageFormat; -import java.util.*; - import static ch.puzzle.okr.multitenancy.TenantContext.DEFAULT_TENANT_ID; public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { @@ -35,12 +36,14 @@ protected Connection getConnection(String tenantIdentifier, Connection connectio String schema = convertTenantIdToSchemaName(tenantIdentifier); logger.debug("Setting schema to {}", schema); - connection.createStatement().execute(String.format("SET SCHEMA '%s';", schema)); + connection.createStatement() + .execute(String.format("SET SCHEMA '%s';", schema)); return connection; } private String convertTenantIdToSchemaName(String tenantIdentifier) { - return Objects.equals(tenantIdentifier, DEFAULT_TENANT_ID) ? tenantIdentifier + return Objects.equals(tenantIdentifier, DEFAULT_TENANT_ID) + ? tenantIdentifier : MessageFormat.format("okr_{0}", tenantIdentifier); } @@ -56,26 +59,26 @@ protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { protected ConnectionProvider getConnectionProvider(String tenantIdentifier) { return Optional.ofNullable(tenantIdentifier) // - .map(connectionProviderMap::get) // - .orElseGet(() -> createNewConnectionProvider(tenantIdentifier)); + .map(connectionProviderMap::get) // + .orElseGet(() -> createNewConnectionProvider(tenantIdentifier)); } private ConnectionProvider createNewConnectionProvider(String tenantIdentifier) { return Optional.ofNullable(tenantIdentifier) // - .map(this::createConnectionProvider) // - .map(connectionProvider -> { - connectionProviderMap.put(tenantIdentifier, connectionProvider); - return connectionProvider; - }) // - .orElseThrow(() -> new ConnectionProviderException( - String.format("Cannot create new connection provider for tenant: %s", tenantIdentifier))); + .map(this::createConnectionProvider) // + .map(connectionProvider -> { + connectionProviderMap.put(tenantIdentifier, connectionProvider); + return connectionProvider; + }) // + .orElseThrow(() -> new ConnectionProviderException(String.format("Cannot create new connection provider for tenant: %s", + tenantIdentifier))); } private ConnectionProvider createConnectionProvider(String tenantIdentifier) { return Optional.ofNullable(tenantIdentifier) // - .map(this::getHibernatePropertiesForTenantIdentifier) // - .map(this::initConnectionProvider) // - .orElse(null); + .map(this::getHibernatePropertiesForTenantIdentifier) // + .map(this::initConnectionProvider) // + .orElse(null); } protected Properties getHibernatePropertiesForTenantIdentifier(String tenantIdentifier) { diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java index 97521d9d7a..5c94ccce89 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java @@ -1,12 +1,12 @@ package ch.puzzle.okr.multitenancy; +import java.text.MessageFormat; +import java.util.*; + import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import java.text.MessageFormat; -import java.util.*; - @Component public class TenantConfigProvider implements TenantConfigProviderInterface { private static final String EMAIL_DELIMITER = ","; @@ -18,39 +18,53 @@ public TenantConfigProvider(final @Value("${okr.tenant-ids}") String[] tenantIds for (String tenantId : tenantIds) { OauthConfig c = readOauthConfig(tenantId); tenantConfigs.put(tenantId, - createTenantConfig(c.jwkSetUri(), c.frontendClientIssuerUrl(), c.frontendClientId(), tenantId)); + createTenantConfig(c.jwkSetUri(), + c.frontendClientIssuerUrl(), + c.frontendClientId(), + tenantId)); } } private OauthConfig readOauthConfig(String tenantId) { - return new OauthConfig( - env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.resourceserver.jwt.jwk-set-uri", - tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.issuer-url", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.client-id", tenantId))); + return new OauthConfig(env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.resourceserver.jwt.jwk-set-uri", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.issuer-url", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.client-id", + tenantId))); } - private TenantConfig createTenantConfig(String jwkSetUriTemplate, String frontendClientIssuerUrl, - String frontendClientId, String tenantId) { - return new TenantConfig(tenantId, getOkrChampionEmailsFromTenant(tenantId), jwkSetUriTemplate, - frontendClientIssuerUrl, frontendClientId, this.readDataSourceConfig(tenantId)); + private TenantConfig createTenantConfig(String jwkSetUriTemplate, String frontendClientIssuerUrl, String frontendClientId, String tenantId) { + return new TenantConfig(tenantId, + getOkrChampionEmailsFromTenant(tenantId), + jwkSetUriTemplate, + frontendClientIssuerUrl, + frontendClientId, + this.readDataSourceConfig(tenantId)); } private String[] getOkrChampionEmailsFromTenant(String tenantId) { return Arrays.stream(env.getProperty(MessageFormat.format("okr.tenants.{0}.user.champion.emails", tenantId), "") - .split(EMAIL_DELIMITER)).map(String::trim).toArray(String[]::new); + .split(EMAIL_DELIMITER)) + .map(String::trim) + .toArray(String[]::new); } public List getTenantConfigs() { - return this.tenantConfigs.values().stream().toList(); + return this.tenantConfigs.values() + .stream() + .toList(); } private DataSourceConfig readDataSourceConfig(String tenantId) { return new DataSourceConfig(env.getProperty("okr.datasource.driver-class-name"), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.url", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.username", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.password", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.schema", tenantId))); + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.url", tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.username", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.password", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.schema", + tenantId))); } public Optional getTenantConfigById(String tenantId) { @@ -61,8 +75,10 @@ public Optional getJwkSetUri(String tenantId) { return getTenantConfigById(tenantId).map(TenantConfig::jwkSetUri); } - public record TenantConfig(String tenantId, String[] okrChampionEmails, String jwkSetUri, String issuerUrl, - String clientId, DataSourceConfig dataSourceConfig) { + public record TenantConfig( + String tenantId, String[] okrChampionEmails, String jwkSetUri, String issuerUrl, String clientId, + DataSourceConfig dataSourceConfig + ) { } public record DataSourceConfig(String driverClassName, String url, String name, String password, String schema) { diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java index 7c560ecf8c..64e69b3f85 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java @@ -1,17 +1,18 @@ package ch.puzzle.okr.multitenancy; +import java.util.Optional; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Optional; - public class TenantContext { public static final String DEFAULT_TENANT_ID = "public"; private static final Logger logger = LoggerFactory.getLogger(TenantContext.class); private static final ThreadLocal CURRENT_TENANT = new ThreadLocal<>(); public static String getCurrentTenant() { - return Optional.ofNullable(CURRENT_TENANT.get()).orElse(DEFAULT_TENANT_ID); + return Optional.ofNullable(CURRENT_TENANT.get()) + .orElse(DEFAULT_TENANT_ID); } public static void setCurrentTenant(String tenant) { diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomization.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomization.java index b7dc7e004f..ee0f8e4ed7 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomization.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomization.java @@ -2,6 +2,8 @@ import java.util.Map; -public record TenantClientCustomization(String favicon, String logo, String triangles, String backgroundLogo, - String title, Map customStyles) { +public record TenantClientCustomization( + String favicon, String logo, String triangles, String backgroundLogo, String title, + Map customStyles +) { } diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java index 2c74a9ae07..d4617185a7 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java @@ -1,9 +1,5 @@ package ch.puzzle.okr.multitenancy.customization; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - import java.io.Serializable; import java.text.MessageFormat; import java.util.HashMap; @@ -11,6 +7,10 @@ import java.util.Map; import java.util.Optional; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + @Component public class TenantClientCustomizationProvider { private static final String CUSTOM_STYLES_PREFIX = "okr.tenants.{0}.clientcustomization.customstyles"; @@ -33,13 +33,17 @@ public TenantClientCustomizationProvider(final @Value("${okr.tenant-ids}") Strin } private TenantClientCustomization readClientCustomizationConfig(String tenantId) { - return new TenantClientCustomization( - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.favicon", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.logo", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.triangles", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.background-logo", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.title", tenantId)), - getCustomCssStyles(tenantId) // + return new TenantClientCustomization(env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.favicon", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.logo", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.triangles", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.background-logo", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.title", + tenantId)), + getCustomCssStyles(tenantId) // ); } diff --git a/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java index c6baa06bb4..66925a4315 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java @@ -1,9 +1,10 @@ package ch.puzzle.okr.repository; +import java.util.List; + import ch.puzzle.okr.models.Action; -import org.springframework.data.repository.CrudRepository; -import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface ActionRepository extends CrudRepository { List getActionsByKeyResultIdOrderByPriorityAsc(Long keyResultId); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java index d6ebcc70a7..7681f0ce45 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java @@ -1,14 +1,15 @@ package ch.puzzle.okr.repository; +import java.util.List; + import ch.puzzle.okr.models.alignment.Alignment; import ch.puzzle.okr.models.alignment.KeyResultAlignment; import ch.puzzle.okr.models.alignment.ObjectiveAlignment; + import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; -import java.util.List; - public interface AlignmentRepository extends CrudRepository { List findByAlignedObjectiveId(Long alignedObjectiveId); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java index 50896b44f3..6bfcb3393e 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java @@ -1,15 +1,15 @@ package ch.puzzle.okr.repository; +import java.util.List; + import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; + import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import java.util.List; - public interface AlignmentSelectionRepository extends ReadOnlyRepository { @Query(value = "from AlignmentSelection where quarterId = :quarter_id and teamId != :ignoredTeamId") - List getAlignmentSelectionByQuarterIdAndTeamIdNot(@Param("quarter_id") Long quarterId, - @Param("ignoredTeamId") Long ignoredTeamId); + List getAlignmentSelectionByQuarterIdAndTeamIdNot(@Param("quarter_id") Long quarterId, @Param("ignoredTeamId") Long ignoredTeamId); } diff --git a/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java index 74622032a2..f7f0651eda 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java @@ -1,9 +1,10 @@ package ch.puzzle.okr.repository; +import java.util.List; + import ch.puzzle.okr.models.checkin.CheckIn; -import org.springframework.data.repository.CrudRepository; -import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface CheckInRepository extends CrudRepository { List findCheckInsByKeyResultIdOrderByCreatedOnDesc(Long keyResultId); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/CompletedRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/CompletedRepository.java index 007f61c3b4..fec6c1c91f 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/CompletedRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/CompletedRepository.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.Completed; + import org.springframework.data.repository.CrudRepository; public interface CompletedRepository extends CrudRepository { diff --git a/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java index b5aa92dbac..331b522e27 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java @@ -1,9 +1,10 @@ package ch.puzzle.okr.repository; +import java.util.List; + import ch.puzzle.okr.models.keyresult.KeyResult; -import org.springframework.data.repository.CrudRepository; -import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface KeyResultRepository extends CrudRepository { List findByObjectiveId(Long objectiveId); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java index 009b34ac96..27785befba 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java @@ -1,13 +1,14 @@ package ch.puzzle.okr.repository; +import java.util.List; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.models.Team; + import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; -import java.util.List; - @Repository public interface ObjectiveRepository extends CrudRepository { diff --git a/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java index a742c2d236..6a7a46f35f 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java @@ -1,14 +1,15 @@ package ch.puzzle.okr.repository; +import java.time.LocalDate; +import java.util.List; + import ch.puzzle.okr.models.Quarter; + import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import java.time.LocalDate; -import java.util.List; - @Repository public interface QuarterRepository extends CrudRepository { diff --git a/backend/src/main/java/ch/puzzle/okr/repository/ReadOnlyRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/ReadOnlyRepository.java index d8ea9209e0..b4eeea2360 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/ReadOnlyRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/ReadOnlyRepository.java @@ -5,9 +5,9 @@ /** * @param - * the Identifier or primary key of the entity + * the Identifier or primary key of the entity * @param - * the Type or entity of the repository + * the Type or entity of the repository */ @NoRepositoryBean public interface ReadOnlyRepository extends Repository { diff --git a/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java index 14e48978ed..57757e98a6 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java @@ -1,9 +1,10 @@ package ch.puzzle.okr.repository; +import java.util.List; + import ch.puzzle.okr.models.Team; -import org.springframework.data.repository.CrudRepository; -import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface TeamRepository extends CrudRepository { diff --git a/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java index 2bf83e1f1d..91a3871acd 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java @@ -1,11 +1,12 @@ package ch.puzzle.okr.repository; -import ch.puzzle.okr.models.User; -import org.springframework.data.repository.CrudRepository; - import java.util.List; import java.util.Optional; +import ch.puzzle.okr.models.User; + +import org.springframework.data.repository.CrudRepository; + public interface UserRepository extends CrudRepository { Optional findByEmail(String email); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/UserTeamRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/UserTeamRepository.java index c0a9736eb0..72348c3fcd 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/UserTeamRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/UserTeamRepository.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.UserTeam; + import org.springframework.data.repository.CrudRepository; public interface UserTeamRepository extends CrudRepository { diff --git a/backend/src/main/java/ch/puzzle/okr/security/AuthenticationEvents.java b/backend/src/main/java/ch/puzzle/okr/security/AuthenticationEvents.java index 067de50dc6..c33211ec4f 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/AuthenticationEvents.java +++ b/backend/src/main/java/ch/puzzle/okr/security/AuthenticationEvents.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.security; import ch.puzzle.okr.multitenancy.TenantContext; + import org.springframework.context.event.EventListener; import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.security.oauth2.jwt.Jwt; @@ -16,7 +17,8 @@ public AuthenticationEvents(JwtHelper jwtHelper) { @EventListener public void onSuccess(AuthenticationSuccessEvent success) { - Jwt token = (Jwt) success.getAuthentication().getPrincipal(); + Jwt token = (Jwt) success.getAuthentication() + .getPrincipal(); TenantContext.setCurrentTenant(jwtHelper.getTenantFromToken(token)); } diff --git a/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java b/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java index fe15d284f1..eb2fbec58d 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java +++ b/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java @@ -1,25 +1,28 @@ package ch.puzzle.okr.security; +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantConfigProvider; import ch.puzzle.okr.security.helper.ClaimHelper; import ch.puzzle.okr.security.helper.TokenHelper; -import com.nimbusds.jwt.JWTClaimsSet; -import jakarta.persistence.EntityNotFoundException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.stereotype.Component; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Function; +import com.nimbusds.jwt.JWTClaimsSet; + +import jakarta.persistence.EntityNotFoundException; import static ch.puzzle.okr.Constants.USER; import static org.springframework.http.HttpStatus.BAD_REQUEST; @@ -28,8 +31,7 @@ public class JwtHelper { public static final String CLAIM_TENANT = "tenant"; public static final String CLAIM_ISS = "iss"; - public static final String ERROR_MESSAGE = "Missing `" + CLAIM_TENANT + "` and '" + CLAIM_ISS - + "' claims in JWT token!"; + public static final String ERROR_MESSAGE = "Missing `" + CLAIM_TENANT + "` and '" + CLAIM_ISS + "' claims in JWT token!"; private static final Logger logger = LoggerFactory.getLogger(JwtHelper.class); @@ -38,10 +40,7 @@ public class JwtHelper { private final String lastname; private final String email; - public JwtHelper(TenantConfigProvider tenantConfigProvider, - @Value("${okr.jwt.claim.firstname}") final String tokenClaimsKeyFirstname, - @Value("${okr.jwt.claim.lastname}") final String tokenClaimsKeyLastname, - @Value("${okr.jwt.claim.email}") final String tokenClaimsKeyEmail) { + public JwtHelper(TenantConfigProvider tenantConfigProvider, @Value("${okr.jwt.claim.firstname}") final String tokenClaimsKeyFirstname, @Value("${okr.jwt.claim.lastname}") final String tokenClaimsKeyLastname, @Value("${okr.jwt.claim.email}") final String tokenClaimsKeyEmail) { this.tenantConfigProvider = tenantConfigProvider; this.firstname = tokenClaimsKeyFirstname; this.lastname = tokenClaimsKeyLastname; @@ -54,10 +53,13 @@ public User getUserFromJwt(Jwt token) { try { return User.Builder.builder() // - .withFirstname(claims.get(firstname).toString()) // - .withLastname(claims.get(lastname).toString()) // - .withEmail(claims.get(email).toString()) // - .build(); + .withFirstname(claims.get(firstname) + .toString()) // + .withLastname(claims.get(lastname) + .toString()) // + .withEmail(claims.get(email) + .toString()) // + .build(); } catch (Exception e) { logger.warn("can not convert user from claims {}", claims); throw new OkrResponseStatusException(BAD_REQUEST, ErrorKey.CONVERT_TOKEN, USER); @@ -67,51 +69,51 @@ public User getUserFromJwt(Jwt token) { public String getTenantFromToken(Jwt token) { TokenHelper helper = new TokenHelper(); List>> getTenantFromTokenFunctions = Arrays.asList( // - helper::getTenantFromTokenUsingClaimIss, // - helper::getTenantFromTokenUsingClaimTenant // + helper::getTenantFromTokenUsingClaimIss, // + helper::getTenantFromTokenUsingClaimTenant // ); return getFirstMatchingTenantUsingListOfHelperFunctions(token, getTenantFromTokenFunctions); } - private String getFirstMatchingTenantUsingListOfHelperFunctions(Jwt token, - List>> getTenantFunctions) { + private String getFirstMatchingTenantUsingListOfHelperFunctions(Jwt token, List>> getTenantFunctions) { return getTenantFunctions.stream() // - .map(func -> func.apply(token)) // - .filter(Optional::isPresent) // - .map(Optional::get) // - .map(this::getMatchingTenantFromConfigOrThrow) // - .findFirst() // - .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); + .map(func -> func.apply(token)) // + .filter(Optional::isPresent) // + .map(Optional::get) // + .map(this::getMatchingTenantFromConfigOrThrow) // + .findFirst() // + .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); } public String getTenantFromJWTClaimsSet(JWTClaimsSet claimSet) { ClaimHelper helper = new ClaimHelper(); List>> getTenantFromClaimsSetFunctions = Arrays.asList( // - helper::getTenantFromClaimsSetUsingClaimIss, // - helper::getTenantFromClaimsSetUsingClaimTenant // + helper::getTenantFromClaimsSetUsingClaimIss, // + helper::getTenantFromClaimsSetUsingClaimTenant // ); return getFirstMatchingTenantUsingListOfHelperFunctions(claimSet, getTenantFromClaimsSetFunctions); } - private String getFirstMatchingTenantUsingListOfHelperFunctions(JWTClaimsSet claimSet, - List>> getTenantFunctions) { + private String getFirstMatchingTenantUsingListOfHelperFunctions(JWTClaimsSet claimSet, List>> getTenantFunctions) { return getTenantFunctions.stream() // - .map(func -> func.apply(claimSet)) // - .filter(Optional::isPresent) // - .map(Optional::get) // - .map(this::getMatchingTenantFromConfigOrThrow).findFirst() // - .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); + .map(func -> func.apply(claimSet)) // + .filter(Optional::isPresent) // + .map(Optional::get) // + .map(this::getMatchingTenantFromConfigOrThrow) + .findFirst() // + .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); } private String getMatchingTenantFromConfigOrThrow(String tenant) { // Ensure we return only tenants for realms which really exist return this.tenantConfigProvider.getTenantConfigById(tenant) - .orElseThrow(() -> new EntityNotFoundException(MessageFormat.format("Cannot find tenant {0}", tenant))) - .tenantId(); + .orElseThrow(() -> new EntityNotFoundException(MessageFormat.format("Cannot find tenant {0}", + tenant))) + .tenantId(); } } \ No newline at end of file diff --git a/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java b/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java index f900296174..bc1e355927 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java +++ b/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java @@ -1,6 +1,15 @@ package ch.puzzle.okr.security; +import java.net.URL; +import java.security.Key; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import ch.puzzle.okr.multitenancy.TenantConfigProvider; + +import org.springframework.stereotype.Component; + import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.KeySourceException; import com.nimbusds.jose.proc.JWSAlgorithmFamilyJWSKeySelector; @@ -8,13 +17,6 @@ import com.nimbusds.jose.proc.SecurityContext; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.proc.JWTClaimsSetAwareJWSKeySelector; -import org.springframework.stereotype.Component; - -import java.net.URL; -import java.security.Key; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; @Component public class TenantJWSKeySelector implements JWTClaimsSetAwareJWSKeySelector { @@ -30,11 +32,10 @@ public TenantJWSKeySelector(final TenantConfigProvider tenantConfigProvider, Jwt } @Override - public List selectKeys(JWSHeader jwsHeader, JWTClaimsSet jwtClaimsSet, - SecurityContext securityContext) throws KeySourceException { + public List selectKeys(JWSHeader jwsHeader, JWTClaimsSet jwtClaimsSet, SecurityContext securityContext) throws KeySourceException { return this.selectors.computeIfAbsent(toTenant(jwtClaimsSet), this::fromTenant) // - .selectJWSKeys(jwsHeader, securityContext); + .selectJWSKeys(jwsHeader, securityContext); } private String toTenant(JWTClaimsSet claimSet) { @@ -43,8 +44,8 @@ private String toTenant(JWTClaimsSet claimSet) { private JWSKeySelector fromTenant(String tenantId) { return this.tenantConfigProvider.getJwkSetUri(tenantId)// - .map(this::fromUri) // - .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); + .map(this::fromUri) // + .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); } JWSKeySelector fromUri(String uri) { diff --git a/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java b/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java index 1dadd96b3f..dbd915a79f 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java +++ b/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java @@ -1,15 +1,16 @@ package ch.puzzle.okr.security; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import ch.puzzle.okr.multitenancy.TenantConfigProvider; + import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtIssuerValidator; import org.springframework.stereotype.Component; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - @Component public class TenantJwtIssuerValidator implements OAuth2TokenValidator { private final TenantConfigProvider tenantConfigProvider; @@ -32,9 +33,9 @@ public OAuth2TokenValidatorResult validate(Jwt token) { private JwtIssuerValidator createValidatorForTenant(String tenant) { return this.tenantConfigProvider.getTenantConfigById(tenant) // - .map(TenantConfigProvider.TenantConfig::issuerUrl) // - .map(this::createValidator) // - .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); + .map(TenantConfigProvider.TenantConfig::issuerUrl) // + .map(this::createValidator) // + .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); } JwtIssuerValidator createValidator(String issuer) { diff --git a/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java b/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java index 9ceb7a4034..d205f36b7d 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java +++ b/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java @@ -1,10 +1,10 @@ package ch.puzzle.okr.security.helper; -import com.nimbusds.jwt.JWTClaimsSet; - import java.text.ParseException; import java.util.Optional; +import com.nimbusds.jwt.JWTClaimsSet; + import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; import static ch.puzzle.okr.security.helper.JwtStatusLogger.logStatus; diff --git a/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java b/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java index ca5d678458..2761ed7707 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java +++ b/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java @@ -1,10 +1,10 @@ package ch.puzzle.okr.security.helper; +import java.text.ParseException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.text.ParseException; - public class JwtStatusLogger { private static final Logger logger = LoggerFactory.getLogger(ClaimHelper.class); @@ -15,17 +15,27 @@ public static void logStatus(String claim, Object context, String result) { public static void logStatus(String claim, Object context, boolean isOk) { if (isOk) { - logger.info("Tenant: get claim '{}' from {}{}", claim, context.getClass().getSimpleName(), - statusToSymbol(isOk)); + logger.info("Tenant: get claim '{}' from {}{}", + claim, + context.getClass() + .getSimpleName(), + statusToSymbol(isOk)); } else { - logger.warn("Tenant: get claim '{}' from {}{}", claim, context.getClass().getSimpleName(), - statusToSymbol(isOk)); + logger.warn("Tenant: get claim '{}' from {}{}", + claim, + context.getClass() + .getSimpleName(), + statusToSymbol(isOk)); } } public static void logStatus(String claim, Object context, ParseException e) { - logger.warn("Tenant: get claim '{}' from {}{}", claim, context.getClass().getSimpleName(), - statusToSymbol(false), e); + logger.warn("Tenant: get claim '{}' from {}{}", + claim, + context.getClass() + .getSimpleName(), + statusToSymbol(false), + e); } private static String statusToSymbol(boolean isOk) { diff --git a/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java b/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java index 513241cb06..6e706a83f5 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java +++ b/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java @@ -1,9 +1,9 @@ package ch.puzzle.okr.security.helper; -import org.springframework.security.oauth2.jwt.Jwt; - import java.util.Optional; +import org.springframework.security.oauth2.jwt.Jwt; + import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; import static ch.puzzle.okr.security.helper.JwtStatusLogger.logStatus; diff --git a/backend/src/main/java/ch/puzzle/okr/service/CacheService.java b/backend/src/main/java/ch/puzzle/okr/service/CacheService.java index de907468c1..015303f8b5 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/CacheService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/CacheService.java @@ -29,9 +29,11 @@ public void emptyAuthorizationUsersCache() { } public void emptyAllCaches() { - cacheManager.getCacheNames().forEach(cacheName -> { - cacheManager.getCache(cacheName).clear(); - logger.info("emptying {} cache", cacheName); - }); + cacheManager.getCacheNames() + .forEach(cacheName -> { + cacheManager.getCache(cacheName) + .clear(); + logger.info("emptying {} cache", cacheName); + }); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java index a6a54a4de4..14a7e4221a 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java @@ -1,12 +1,13 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.business.ActionBusinessService; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; @Service public class ActionAuthorizationService { @@ -14,8 +15,7 @@ public class ActionAuthorizationService { private final ActionBusinessService actionBusinessService; private final AuthorizationService authorizationService; - public ActionAuthorizationService(ActionBusinessService actionBusinessService, - AuthorizationService authorizationService) { + public ActionAuthorizationService(ActionBusinessService actionBusinessService, AuthorizationService authorizationService) { this.actionBusinessService = actionBusinessService; this.authorizationService = authorizationService; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java index fc1213b565..9689d45f18 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java @@ -5,10 +5,12 @@ import ch.puzzle.okr.multitenancy.TenantConfigProvider; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.service.business.UserBusinessService; -import jakarta.persistence.EntityNotFoundException; + import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; +import jakarta.persistence.EntityNotFoundException; + import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; @Service @@ -19,8 +21,7 @@ public class AuthorizationRegistrationService { private final UserUpdateHelper helper = new UserUpdateHelper(); - public AuthorizationRegistrationService(UserBusinessService userBusinessService, - TenantConfigProvider tenantConfigProvider) { + public AuthorizationRegistrationService(UserBusinessService userBusinessService, TenantConfigProvider tenantConfigProvider) { this.userBusinessService = userBusinessService; this.tenantConfigProvider = tenantConfigProvider; } @@ -41,9 +42,8 @@ private User setFirstLastNameFromToken(User userFromDB, User userFromToken) { // okr champion is set in application properties private User setOkrChampionFromProperties(User user) { - TenantConfigProvider.TenantConfig tenantConfig = this.tenantConfigProvider - .getTenantConfigById(TenantContext.getCurrentTenant()) - .orElseThrow(() -> new EntityNotFoundException("Cannot find tenant")); + TenantConfigProvider.TenantConfig tenantConfig = this.tenantConfigProvider.getTenantConfigById(TenantContext.getCurrentTenant()) + .orElseThrow(() -> new EntityNotFoundException("Cannot find tenant")); return helper.setOkrChampionFromProperties(user, tenantConfig); } @@ -52,7 +52,8 @@ public static class UserUpdateHelper { public User setOkrChampionFromProperties(User user, TenantConfigProvider.TenantConfig tenantConfig) { for (var mail : tenantConfig.okrChampionEmails()) { - if (mail.trim().equals(user.getEmail())) { + if (mail.trim() + .equals(user.getEmail())) { user.setOkrChampion(true); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java index 699213eb37..bb899ef977 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java @@ -11,6 +11,7 @@ import ch.puzzle.okr.security.JwtHelper; import ch.puzzle.okr.service.persistence.ActionPersistenceService; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; + import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; @@ -28,9 +29,7 @@ public class AuthorizationService { private final ActionPersistenceService actionPersistenceService; private final JwtHelper jwtHelper; - public AuthorizationService(AuthorizationRegistrationService authorizationRegistrationService, - ObjectivePersistenceService objectivePersistenceService, ActionPersistenceService actionPersistenceService, - JwtHelper jwtHelper) { + public AuthorizationService(AuthorizationRegistrationService authorizationRegistrationService, ObjectivePersistenceService objectivePersistenceService, ActionPersistenceService actionPersistenceService, JwtHelper jwtHelper) { this.authorizationRegistrationService = authorizationRegistrationService; this.actionPersistenceService = actionPersistenceService; this.objectivePersistenceService = objectivePersistenceService; @@ -44,8 +43,7 @@ public static boolean hasRoleWriteForTeam(AuthorizationUser authorizationUser, L return authorizationUser.isUserAdminInTeam(teamId); } - public static void checkRoleWriteAndReadAll(AuthorizationUser user, - OkrResponseStatusException notAuthorizedException) { + public static void checkRoleWriteAndReadAll(AuthorizationUser user, OkrResponseStatusException notAuthorizedException) { if (hasRoleWriteAndReadAll(user)) { return; } @@ -53,7 +51,8 @@ public static void checkRoleWriteAndReadAll(AuthorizationUser user, } public static boolean hasRoleWriteAndReadAll(AuthorizationUser user) { - return user.user().isOkrChampion(); + return user.user() + .isOkrChampion(); } public AuthorizationUser updateOrAddAuthorizationUser() { @@ -67,40 +66,54 @@ public AuthorizationUser updateOrAddAuthorizationUser() { } public void hasRoleReadByObjectiveId(Long objectiveId, AuthorizationUser authorizationUser) { - objectivePersistenceService.findObjectiveById(objectiveId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); + objectivePersistenceService.findObjectiveById(objectiveId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); } public void hasRoleReadByKeyResultId(Long keyResultId, AuthorizationUser authorizationUser) { - objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); } public void hasRoleReadByCheckInId(Long checkInId, AuthorizationUser authorizationUser) { - objectivePersistenceService.findObjectiveByCheckInId(checkInId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + objectivePersistenceService.findObjectiveByCheckInId(checkInId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); } public void hasRoleCreateOrUpdate(Objective objective, AuthorizationUser authorizationUser) { - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); } public void hasRoleCreateOrUpdate(KeyResult keyResult, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveById(keyResult.getObjective().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + Objective objective = objectivePersistenceService.findObjectiveById(keyResult.getObjective() + .getId(), + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, KEY_RESULT)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, KEY_RESULT)); } public void hasRoleCreateOrUpdate(CheckIn checkIn, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(checkIn.getKeyResult().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(checkIn.getKeyResult() + .getId(), + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, CHECK_IN)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, CHECK_IN)); } public boolean hasRoleWriteForTeam(Objective objective, AuthorizationUser authorizationUser) { @@ -108,59 +121,79 @@ public boolean hasRoleWriteForTeam(Objective objective, AuthorizationUser author } public boolean hasRoleWriteForTeam(KeyResult keyResult, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveById(keyResult.getObjective().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + Objective objective = objectivePersistenceService.findObjectiveById(keyResult.getObjective() + .getId(), + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); return hasRoleWriteForTeam(authorizationUser, objective.getTeam()); } public boolean hasRoleWriteForTeam(CheckIn checkIn, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(checkIn.getKeyResult().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(checkIn.getKeyResult() + .getId(), + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); return hasRoleWriteForTeam(authorizationUser, objective.getTeam()); } public void hasRoleCreateOrUpdateByObjectiveId(Long objectiveId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); + Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + OBJECTIVE)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); } public void hasRoleDeleteByObjectiveId(Long objectiveId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); + Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + OBJECTIVE)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, OBJECTIVE)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, OBJECTIVE)); } public void hasRoleDeleteByKeyResultId(Long keyResultId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, KEY_RESULT)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, KEY_RESULT)); } public void hasRoleDeleteByActionId(Long actionId, AuthorizationUser authorizationUser) { Action action = actionPersistenceService.findById(actionId); - hasRoleWriteForTeam(authorizationUser, action.getKeyResult().getObjective().getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, ACTION)); + hasRoleWriteForTeam(authorizationUser, + action.getKeyResult() + .getObjective() + .getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, ACTION)); } public void hasRoleDeleteByCheckInId(Long checkInId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveByCheckInId(checkInId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + Objective objective = objectivePersistenceService.findObjectiveByCheckInId(checkInId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, CHECK_IN)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, CHECK_IN)); } - private void hasRoleWriteForTeam(AuthorizationUser authorizationUser, Team team, - OkrResponseStatusException notAuthorizedException) { + private void hasRoleWriteForTeam(AuthorizationUser authorizationUser, Team team, OkrResponseStatusException notAuthorizedException) { if (hasRoleWriteForTeam(authorizationUser, team)) { return; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java index 51cd7ab046..3525311f74 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java @@ -6,18 +6,17 @@ /** * @param - * the Identifier or primary key of the entity + * the Identifier or primary key of the entity * @param - * the Type or entity of the repository + * the Type or entity of the repository * @param - * the Business Service of this entity + * the Business Service of this entity */ public abstract class AuthorizationServiceBase { private final BusinessServiceInterface businessService; private final AuthorizationService authorizationService; - protected AuthorizationServiceBase(BusinessServiceInterface businessService, - AuthorizationService authorizationService) { + protected AuthorizationServiceBase(BusinessServiceInterface businessService, AuthorizationService authorizationService) { this.businessService = businessService; this.authorizationService = authorizationService; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java index bb6196d6f6..f95a573bc5 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java @@ -3,13 +3,13 @@ import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.service.business.CheckInBusinessService; + import org.springframework.stereotype.Service; @Service public class CheckInAuthorizationService extends AuthorizationServiceBase { - public CheckInAuthorizationService(CheckInBusinessService checkInBusinessService, - AuthorizationService authorizationService) { + public CheckInAuthorizationService(CheckInBusinessService checkInBusinessService, AuthorizationService authorizationService) { super(checkInBusinessService, authorizationService); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java index a59467a3ca..aab416f816 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java @@ -3,6 +3,7 @@ import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.CompletedBusinessService; + import org.springframework.stereotype.Service; @Service @@ -10,15 +11,15 @@ public class CompletedAuthorizationService { private final CompletedBusinessService completedBusinessService; private final AuthorizationService authorizationService; - public CompletedAuthorizationService(CompletedBusinessService completedBusinessService, - AuthorizationService authorizationService) { + public CompletedAuthorizationService(CompletedBusinessService completedBusinessService, AuthorizationService authorizationService) { this.completedBusinessService = completedBusinessService; this.authorizationService = authorizationService; } public Completed createCompleted(Completed completed) { AuthorizationUser authorizationUser = authorizationService.updateOrAddAuthorizationUser(); - authorizationService.hasRoleCreateOrUpdateByObjectiveId(completed.getObjective().getId(), authorizationUser); + authorizationService.hasRoleCreateOrUpdateByObjectiveId(completed.getObjective() + .getId(), authorizationUser); return completedBusinessService.createCompleted(completed); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java index a2197e89b5..eebe25558e 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java @@ -1,23 +1,23 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultWithActionList; import ch.puzzle.okr.service.business.KeyResultBusinessService; + import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.springframework.http.HttpStatus.BAD_REQUEST; @Service public class KeyResultAuthorizationService extends AuthorizationServiceBase { - public KeyResultAuthorizationService(KeyResultBusinessService keyResultBusinessService, - AuthorizationService authorizationService) { + public KeyResultAuthorizationService(KeyResultBusinessService keyResultBusinessService, AuthorizationService authorizationService) { super(keyResultBusinessService, authorizationService); } @@ -52,15 +52,17 @@ public List getAllCheckInsByKeyResult(Long keyResultId) { @Override public KeyResult updateEntity(Long id, KeyResult keyResult) { throw new ResponseStatusException(BAD_REQUEST, - "unsupported method in class " + getClass().getSimpleName() + ", use updateEntities() instead"); + "unsupported method in class " + getClass().getSimpleName() + ", use updateEntities() instead"); } public KeyResultWithActionList updateEntities(Long id, KeyResult entity, List actionList) { AuthorizationUser authorizationUser = getAuthorizationService().updateOrAddAuthorizationUser(); hasRoleCreateOrUpdate(entity, authorizationUser); KeyResultWithActionList updatedEntities = getBusinessService().updateEntities(id, entity, actionList); - updatedEntities.keyResult().setWriteable(true); - updatedEntities.actionList().forEach(action -> action.setWriteable(true)); + updatedEntities.keyResult() + .setWriteable(true); + updatedEntities.actionList() + .forEach(action -> action.setWriteable(true)); return updatedEntities; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java index 22dd21de0c..f65c51c18d 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java @@ -3,13 +3,13 @@ import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.ObjectiveBusinessService; + import org.springframework.stereotype.Service; @Service public class ObjectiveAuthorizationService extends AuthorizationServiceBase { - public ObjectiveAuthorizationService(ObjectiveBusinessService objectiveBusinessService, - AuthorizationService authorizationService) { + public ObjectiveAuthorizationService(ObjectiveBusinessService objectiveBusinessService, AuthorizationService authorizationService) { super(objectiveBusinessService, authorizationService); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java index 3f4487b31b..7ff161dd18 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java @@ -1,15 +1,16 @@ package ch.puzzle.okr.service.authorization; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.service.business.OverviewBusinessService; + import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; @Service @@ -18,16 +19,17 @@ public class OverviewAuthorizationService { private final OverviewBusinessService overviewBusinessService; private final AuthorizationService authorizationService; - public OverviewAuthorizationService(OverviewBusinessService overviewBusinessService, - AuthorizationService authorizationService) { + public OverviewAuthorizationService(OverviewBusinessService overviewBusinessService, AuthorizationService authorizationService) { this.overviewBusinessService = overviewBusinessService; this.authorizationService = authorizationService; } public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery) { AuthorizationUser authorizationUser = authorizationService.updateOrAddAuthorizationUser(); - List overviews = overviewBusinessService.getFilteredOverview(quarterId, teamIds, objectiveQuery, - authorizationUser); + List overviews = overviewBusinessService.getFilteredOverview(quarterId, + teamIds, + objectiveQuery, + authorizationUser); setRoleCreateOrUpdateTeam(overviews, authorizationUser); return overviews; } @@ -39,18 +41,19 @@ private void setRoleCreateOrUpdateTeam(List overviews, AuthorizationUs } } - private void setRoleCreateOrUpdateTeam(Overview overview, AuthorizationUser authorizationUser, - Map teamAccess) { + private void setRoleCreateOrUpdateTeam(Overview overview, AuthorizationUser authorizationUser, Map teamAccess) { if (hasOverviewTeamIdAndObjectiveId(overview)) { - Long teamId = overview.getOverviewId().getTeamId(); + Long teamId = overview.getOverviewId() + .getTeamId(); teamAccess.putIfAbsent(teamId, isWriteable(authorizationUser, overview)); overview.setWriteable(teamAccess.get(teamId)); } } private boolean hasOverviewTeamIdAndObjectiveId(Overview overview) { - return overview.getOverviewId() != null && overview.getOverviewId().getObjectiveId() != null - && overview.getOverviewId().getTeamId() != null; + return overview.getOverviewId() != null && overview.getOverviewId() + .getObjectiveId() != null && overview.getOverviewId() + .getTeamId() != null; } public boolean hasWriteAllAccess() { @@ -59,6 +62,8 @@ public boolean hasWriteAllAccess() { } private boolean isWriteable(AuthorizationUser authorizationUser, Overview overview) { - return AuthorizationService.hasRoleWriteForTeam(authorizationUser, overview.getOverviewId().getTeamId()); + return AuthorizationService.hasRoleWriteForTeam(authorizationUser, + overview.getOverviewId() + .getTeamId()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java index 33e2cecd33..d391aa5733 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java @@ -1,13 +1,14 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.TeamBusinessService; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.TEAM; import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; @@ -17,8 +18,7 @@ public class TeamAuthorizationService { private final TeamBusinessService teamBusinessService; private final AuthorizationService authorizationService; - public TeamAuthorizationService(TeamBusinessService teamBusinessService, - AuthorizationService authorizationService) { + public TeamAuthorizationService(TeamBusinessService teamBusinessService, AuthorizationService authorizationService) { this.teamBusinessService = teamBusinessService; this.authorizationService = authorizationService; } @@ -71,7 +71,9 @@ public List getAllTeams() { public void removeUserFromTeam(long entityId, long userId) { // user is allowed to remove own membership of any team - if (userId != authorizationService.updateOrAddAuthorizationUser().user().getId()) { + if (userId != authorizationService.updateOrAddAuthorizationUser() + .user() + .getId()) { checkUserAuthorization(OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, TEAM), entityId); } teamBusinessService.removeUserFromTeam(entityId, userId); diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java index 2cd0a29259..8f96029897 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java @@ -1,13 +1,14 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.UserTeam; import ch.puzzle.okr.service.business.UserBusinessService; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.USER; @@ -18,8 +19,7 @@ public class UserAuthorizationService { private final TeamAuthorizationService teamAuthorizationService; - public UserAuthorizationService(UserBusinessService userBusinessService, AuthorizationService authorizationService, - TeamAuthorizationService teamAuthorizationService) { + public UserAuthorizationService(UserBusinessService userBusinessService, AuthorizationService authorizationService, TeamAuthorizationService teamAuthorizationService) { this.userBusinessService = userBusinessService; this.authorizationService = authorizationService; this.teamAuthorizationService = teamAuthorizationService; @@ -32,7 +32,8 @@ public List getAllUsers() { } private void setTeamWritableForUser(User user) { - user.getUserTeamList().forEach(this::setTeamWritableForUserTeam); + user.getUserTeamList() + .forEach(this::setTeamWritableForUserTeam); } private void setTeamWritableForUserTeam(UserTeam userTeam) { @@ -49,13 +50,15 @@ public User getById(long id) { public User setIsOkrChampion(long id, boolean isOkrChampion) { var user = userBusinessService.getUserById(id); AuthorizationService.checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), - OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, USER)); + OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, + USER)); return userBusinessService.setIsOkrChampion(user, isOkrChampion); } public List createUsers(List userList) { AuthorizationService.checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), - OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, USER)); + OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, + USER)); return userBusinessService.createUsers(userList); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java index 9a684f6a54..d9a93f18f5 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java @@ -1,13 +1,15 @@ package ch.puzzle.okr.service.business; +import java.util.ArrayList; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.service.persistence.ActionPersistenceService; import ch.puzzle.okr.service.validation.ActionValidationService; -import jakarta.transaction.Transactional; + import org.springframework.stereotype.Service; -import java.util.ArrayList; -import java.util.List; +import jakarta.transaction.Transactional; @Service public class ActionBusinessService { @@ -31,7 +33,9 @@ public Action getEntityById(Long id) { @Transactional public List createEntities(List actionList) { - return actionList.stream().map(this::createEntity).toList(); + return actionList.stream() + .map(this::createEntity) + .toList(); } @Transactional @@ -45,7 +49,8 @@ public List updateEntities(List actionList) { List savedActions = new ArrayList<>(); actionList.forEach(action -> { if (action.getKeyResult() == null) { - action.setKeyResult(actionPersistenceService.findById(action.getId()).getKeyResult()); + action.setKeyResult(actionPersistenceService.findById(action.getId()) + .getKeyResult()); } if (action.getId() == null) { savedActions.add(createEntity(action)); diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java index 8e6feefed1..d0ce752ad7 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java @@ -1,23 +1,23 @@ package ch.puzzle.okr.service.business; +import java.util.List; + import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.service.persistence.AlignmentSelectionPersistenceService; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; @Service public class AlignmentSelectionBusinessService { private final AlignmentSelectionPersistenceService alignmentSelectionPersistenceService; - public AlignmentSelectionBusinessService( - AlignmentSelectionPersistenceService alignmentSelectionPersistenceService) { + public AlignmentSelectionBusinessService(AlignmentSelectionPersistenceService alignmentSelectionPersistenceService) { this.alignmentSelectionPersistenceService = alignmentSelectionPersistenceService; } public List getAlignmentSelectionByQuarterIdAndTeamIdNot(Long quarterId, Long ignoredTeamId) { return alignmentSelectionPersistenceService.getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterId, - ignoredTeamId); + ignoredTeamId); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/BusinessServiceInterface.java b/backend/src/main/java/ch/puzzle/okr/service/business/BusinessServiceInterface.java index 36ef2f5765..db2a6d6b30 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/BusinessServiceInterface.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/BusinessServiceInterface.java @@ -4,9 +4,9 @@ /** * @param - * the Type or entity of the repository + * the Type or entity of the repository * @param - * the Identifier or primary key of the entity + * the Identifier or primary key of the entity */ public interface BusinessServiceInterface { T getEntityById(ID id); diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java index db6e892cb0..55c21eb32c 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java @@ -1,22 +1,23 @@ package ch.puzzle.okr.service.business; +import java.time.LocalDateTime; +import java.util.List; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.service.persistence.CheckInPersistenceService; import ch.puzzle.okr.service.validation.CheckInValidationService; -import jakarta.transaction.Transactional; + import org.springframework.stereotype.Service; -import java.time.LocalDateTime; -import java.util.List; +import jakarta.transaction.Transactional; @Service public class CheckInBusinessService implements BusinessServiceInterface { private final CheckInPersistenceService checkInPersistenceService; private final CheckInValidationService validator; - public CheckInBusinessService(CheckInPersistenceService checkInPersistenceService, - CheckInValidationService validator) { + public CheckInBusinessService(CheckInPersistenceService checkInPersistenceService, CheckInValidationService validator) { this.checkInPersistenceService = checkInPersistenceService; this.validator = validator; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/CompletedBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/CompletedBusinessService.java index 95588231c0..abf18ecc25 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/CompletedBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/CompletedBusinessService.java @@ -3,16 +3,17 @@ import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.service.persistence.CompletedPersistenceService; import ch.puzzle.okr.service.validation.CompletedValidationService; -import jakarta.transaction.Transactional; + import org.springframework.stereotype.Service; +import jakarta.transaction.Transactional; + @Service public class CompletedBusinessService { private final CompletedPersistenceService completedPersistenceService; private final CompletedValidationService validator; - public CompletedBusinessService(CompletedPersistenceService completedPersistenceService, - CompletedValidationService validator) { + public CompletedBusinessService(CompletedPersistenceService completedPersistenceService, CompletedValidationService validator) { this.completedPersistenceService = completedPersistenceService; this.validator = validator; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/KeyResultBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/KeyResultBusinessService.java index 309a09d524..dda271b980 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/KeyResultBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/KeyResultBusinessService.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.service.business; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; @@ -7,14 +11,12 @@ import ch.puzzle.okr.models.keyresult.KeyResultWithActionList; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; -import jakarta.transaction.Transactional; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Objects; +import jakarta.transaction.Transactional; @Service public class KeyResultBusinessService implements BusinessServiceInterface { @@ -25,9 +27,7 @@ public class KeyResultBusinessService implements BusinessServiceInterface acti public void deleteEntityById(Long id) { validator.validateOnDelete(id); checkInBusinessService.getCheckInsByKeyResultId(id) - .forEach(checkIn -> checkInBusinessService.deleteEntityById(checkIn.getId())); + .forEach(checkIn -> checkInBusinessService.deleteEntityById(checkIn.getId())); actionBusinessService.getActionsByKeyResultId(id) - .forEach(action -> actionBusinessService.deleteEntityById(action.getId())); + .forEach(action -> actionBusinessService.deleteEntityById(action.getId())); keyResultPersistenceService.deleteById(id); } @@ -115,12 +115,14 @@ public List getAllKeyResultsByObjective(Long objectiveId) { } public boolean hasKeyResultAnyCheckIns(Long id) { - return !checkInBusinessService.getCheckInsByKeyResultId(id).isEmpty(); + return !checkInBusinessService.getCheckInsByKeyResultId(id) + .isEmpty(); } public boolean isImUsed(Long id, KeyResult keyResult) { - return hasKeyResultAnyCheckIns(id) - && !keyResultPersistenceService.findById(id).getKeyResultType().equals(keyResult.getKeyResultType()); + return hasKeyResultAnyCheckIns(id) && !keyResultPersistenceService.findById(id) + .getKeyResultType() + .equals(keyResult.getKeyResultType()); } private boolean isKeyResultTypeChangeable(Long id) { diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java index 2dc987df98..14a2feb974 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.service.business; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; @@ -7,15 +11,13 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.validation.ObjectiveValidationService; -import jakarta.transaction.Transactional; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Objects; +import jakarta.transaction.Transactional; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; @@ -29,9 +31,7 @@ public class ObjectiveBusinessService implements BusinessServiceInterface keyResultBusinessService.hasKeyResultAnyCheckIns(kr.getId())); + return keyResultBusinessService.getAllKeyResultsByObjective(savedObjective.getId()) + .stream() + .anyMatch(kr -> keyResultBusinessService.hasKeyResultAnyCheckIns(kr.getId())); } private static boolean hasQuarterChanged(Objective objective, Objective savedObjective) { @@ -105,11 +106,11 @@ public Objective createEntity(Objective objective, AuthorizationUser authorizati * CheckIns are not copied. * * @param id - * ID of the source Objective + * ID of the source Objective * @param objective - * New Objective with no KeyResults + * New Objective with no KeyResults * @param authorizationUser - * AuthorizationUser + * AuthorizationUser * * @return New Objective with copied KeyResults form the source Objective */ @@ -122,12 +123,13 @@ public Objective duplicateObjective(Long id, Objective objective, AuthorizationU return duplicatedObjective; } - private void duplicateKeyResult(AuthorizationUser authorizationUser, KeyResult keyResult, - Objective duplicatedObjective) { - if (keyResult.getKeyResultType().equals(KEY_RESULT_TYPE_METRIC)) { + private void duplicateKeyResult(AuthorizationUser authorizationUser, KeyResult keyResult, Objective duplicatedObjective) { + if (keyResult.getKeyResultType() + .equals(KEY_RESULT_TYPE_METRIC)) { KeyResult keyResultMetric = makeCopyOfKeyResultMetric(keyResult, duplicatedObjective); keyResultBusinessService.createEntity(keyResultMetric, authorizationUser); - } else if (keyResult.getKeyResultType().equals(KEY_RESULT_TYPE_ORDINAL)) { + } else if (keyResult.getKeyResultType() + .equals(KEY_RESULT_TYPE_ORDINAL)) { KeyResult keyResultOrdinal = makeCopyOfKeyResultOrdinal(keyResult, duplicatedObjective); keyResultBusinessService.createEntity(keyResultOrdinal, authorizationUser); } @@ -135,26 +137,26 @@ private void duplicateKeyResult(AuthorizationUser authorizationUser, KeyResult k private KeyResult makeCopyOfKeyResultMetric(KeyResult keyResult, Objective duplicatedObjective) { return KeyResultMetric.Builder.builder() // - .withObjective(duplicatedObjective) // - .withTitle(keyResult.getTitle()) // - .withDescription(keyResult.getDescription()) // - .withOwner(keyResult.getOwner()) // - .withUnit(((KeyResultMetric) keyResult).getUnit()) // - .withBaseline(0D) // - .withStretchGoal(1D) // - .build(); + .withObjective(duplicatedObjective) // + .withTitle(keyResult.getTitle()) // + .withDescription(keyResult.getDescription()) // + .withOwner(keyResult.getOwner()) // + .withUnit(((KeyResultMetric) keyResult).getUnit()) // + .withBaseline(0D) // + .withStretchGoal(1D) // + .build(); } private KeyResult makeCopyOfKeyResultOrdinal(KeyResult keyResult, Objective duplicatedObjective) { return KeyResultOrdinal.Builder.builder() // - .withObjective(duplicatedObjective) // - .withTitle(keyResult.getTitle()) // - .withDescription(keyResult.getDescription()) // - .withOwner(keyResult.getOwner()) // - .withCommitZone("-") // - .withTargetZone("-") // - .withStretchZone("-") // - .build(); + .withObjective(duplicatedObjective) // + .withTitle(keyResult.getTitle()) // + .withDescription(keyResult.getDescription()) // + .withOwner(keyResult.getOwner()) // + .withCommitZone("-") // + .withTargetZone("-") // + .withStretchZone("-") // + .build(); } @Transactional @@ -162,8 +164,8 @@ public void deleteEntityById(Long id) { validator.validateOnDelete(id); completedBusinessService.deleteCompletedByObjectiveId(id); keyResultBusinessService // - .getAllKeyResultsByObjective(id) // - .forEach(keyResult -> keyResultBusinessService.deleteEntityById(keyResult.getId())); + .getAllKeyResultsByObjective(id) // + .forEach(keyResult -> keyResultBusinessService.deleteEntityById(keyResult.getId())); objectivePersistenceService.deleteById(id); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java index da721f6c27..831a6f3a3f 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java @@ -1,14 +1,15 @@ package ch.puzzle.okr.service.business; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.service.persistence.OverviewPersistenceService; import ch.puzzle.okr.service.validation.OverviewValidationService; -import org.springframework.stereotype.Service; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; +import org.springframework.stereotype.Service; @Service public class OverviewBusinessService { @@ -16,17 +17,16 @@ public class OverviewBusinessService { private final QuarterBusinessService quarterBusinessService; private final OverviewValidationService validator; - public OverviewBusinessService(OverviewPersistenceService overviewPersistenceService, - QuarterBusinessService quarterBusinessService, OverviewValidationService validator) { + public OverviewBusinessService(OverviewPersistenceService overviewPersistenceService, QuarterBusinessService quarterBusinessService, OverviewValidationService validator) { this.overviewPersistenceService = overviewPersistenceService; this.quarterBusinessService = quarterBusinessService; this.validator = validator; } - public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery, - AuthorizationUser authorizationUser) { + public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery, AuthorizationUser authorizationUser) { if (Objects.isNull(quarterId)) { - quarterId = quarterBusinessService.getCurrentQuarter().getId(); + quarterId = quarterBusinessService.getCurrentQuarter() + .getId(); } teamIds = teamIds == null ? List.of() : teamIds; validator.validateOnGet(quarterId, teamIds); @@ -35,8 +35,10 @@ public List getFilteredOverview(Long quarterId, List teamIds, St return List.of(); } - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, teamIds, objectiveQuery, - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + teamIds, + objectiveQuery, + authorizationUser); return sortOverview(overviews, authorizationUser); } @@ -49,19 +51,24 @@ private record OverviewComparator(AuthorizationUser authorizationUser) implement @Override public int compare(Overview o1, Overview o2) { - boolean containsUserTeam1 = authorizationUser.isUserMemberInTeam(o1.getOverviewId().getTeamId()); - boolean containsUserTeam2 = authorizationUser.isUserMemberInTeam(o2.getOverviewId().getTeamId()); + boolean containsUserTeam1 = authorizationUser.isUserMemberInTeam(o1.getOverviewId() + .getTeamId()); + boolean containsUserTeam2 = authorizationUser.isUserMemberInTeam(o2.getOverviewId() + .getTeamId()); if (containsUserTeam1 != containsUserTeam2) { return containsUserTeam1 ? -1 : 1; } if (!Objects.equals(o1.getTeamName(), o2.getTeamName())) { - return o1.getTeamName().compareTo(o2.getTeamName()); + return o1.getTeamName() + .compareTo(o2.getTeamName()); } if (Objects.equals(o1.getObjectiveCreatedOn(), o2.getObjectiveCreatedOn())) { - return o1.getOverviewId().compareTo(o2.getOverviewId()); + return o1.getOverviewId() + .compareTo(o2.getOverviewId()); } - return o1.getObjectiveCreatedOn().compareTo(o2.getObjectiveCreatedOn()); + return o1.getObjectiveCreatedOn() + .compareTo(o2.getObjectiveCreatedOn()); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java index 5f6c35053b..e26a0cf348 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java @@ -1,8 +1,15 @@ package ch.puzzle.okr.service.business; +import java.time.LocalDateTime; +import java.time.YearMonth; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; import ch.puzzle.okr.service.validation.QuarterValidationService; + import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -10,12 +17,6 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import java.time.LocalDateTime; -import java.time.YearMonth; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; @Service @@ -31,8 +32,7 @@ public class QuarterBusinessService { @Value("${okr.quarter.label.format}") private String quarterFormat; - public QuarterBusinessService(QuarterPersistenceService quarterPersistenceService, - QuarterValidationService validator) { + public QuarterBusinessService(QuarterPersistenceService quarterPersistenceService, QuarterValidationService validator) { this.quarterPersistenceService = quarterPersistenceService; this.validator = validator; } @@ -66,21 +66,26 @@ private String createQuarterLabel(YearMonth startOfQuarter, int quarter) { int yearStart = getStartOfBusinessYear(startOfQuarter, quarter); int yearEnd = yearStart + 1; - return StringUtils.replaceEach(quarterFormat, new String[] { "xxxx", "yyyy", "xx", "yy", "zz" }, - new String[] { String.valueOf(yearStart), String.valueOf(yearEnd), shortenYear(yearStart), - shortenYear(yearEnd), String.valueOf(quarter) }); + return StringUtils.replaceEach(quarterFormat, + new String[]{"xxxx", "yyyy", "xx", "yy", "zz"}, + new String[]{String.valueOf(yearStart), String.valueOf(yearEnd), shortenYear(yearStart), shortenYear(yearEnd), String.valueOf(quarter)}); } private int getStartOfBusinessYear(YearMonth startOfQuarter, int quarter) { // Subtract the amount of months, based on the quarter we are in // i.e. quarter=2, subtract (2 - 1) * 3 = 3 Months to get start - return startOfQuarter.minusMonths((quarter - 1) * 3L).getYear(); + return startOfQuarter.minusMonths((quarter - 1) * 3L) + .getYear(); } private void generateQuarter(LocalDateTime start, String label) { YearMonth yearMonth = YearMonth.from(start); - Quarter quarter = Quarter.Builder.builder().withLabel(label).withStartDate(start.toLocalDate()) - .withEndDate(yearMonth.plusMonths(2).atEndOfMonth()).build(); + Quarter quarter = Quarter.Builder.builder() + .withLabel(label) + .withStartDate(start.toLocalDate()) + .withEndDate(yearMonth.plusMonths(2) + .atEndOfMonth()) + .build(); validator.validateOnGeneration(quarter); quarterPersistenceService.save(quarter); } @@ -120,7 +125,8 @@ public void scheduledGenerationQuarters() { if (inLastMonthOfQuarter(currentQuarter, nextQuarter)) { logger.info("Generated quarters on last day of month"); String label = createQuarterLabel(nextQuarterYearMonth, nextQuarter); - generateQuarter(nextQuarterYearMonth.atDay(1).atStartOfDay(), label); + generateQuarter(nextQuarterYearMonth.atDay(1) + .atStartOfDay(), label); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java index f05a069673..9638024e1c 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java @@ -1,5 +1,10 @@ package ch.puzzle.okr.service.business; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; @@ -11,14 +16,11 @@ import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.service.persistence.UserTeamPersistenceService; import ch.puzzle.okr.service.validation.TeamValidationService; -import jakarta.transaction.Transactional; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; +import jakarta.transaction.Transactional; @Service public class TeamBusinessService { @@ -34,10 +36,7 @@ public class TeamBusinessService { private final TeamValidationService validator; private final CacheService cacheService; - public TeamBusinessService(TeamPersistenceService teamPersistenceService, - ObjectiveBusinessService objectiveBusinessService, TeamValidationService validator, - CacheService cacheService, UserPersistenceService userPersistenceService, - UserTeamPersistenceService userTeamPersistenceService) { + public TeamBusinessService(TeamPersistenceService teamPersistenceService, ObjectiveBusinessService objectiveBusinessService, TeamValidationService validator, CacheService cacheService, UserPersistenceService userPersistenceService, UserTeamPersistenceService userTeamPersistenceService) { this.teamPersistenceService = teamPersistenceService; this.objectiveBusinessService = objectiveBusinessService; this.userPersistenceService = userPersistenceService; @@ -73,7 +72,7 @@ public Team updateTeam(Team team, Long id) { public void deleteTeam(Long id) { validator.validateOnDelete(id); objectiveBusinessService.getEntitiesByTeamId(id) - .forEach(objective -> objectiveBusinessService.deleteEntityById(objective.getId())); + .forEach(objective -> objectiveBusinessService.deleteEntityById(objective.getId())); deleteUserTeamList(id); cacheService.emptyAuthorizationUsersCache(); teamPersistenceService.deleteById(id); @@ -82,10 +81,12 @@ public void deleteTeam(Long id) { private void deleteUserTeamList(Long id) { var team = teamPersistenceService.findById(id); // remove userTeam from each user, otherwise they are still in the session and are not deleted - team.getUserTeamList().forEach(userTeam -> { - var user = userTeam.getUser(); - user.getUserTeamList().remove(userTeam); - }); + team.getUserTeamList() + .forEach(userTeam -> { + var user = userTeam.getUser(); + user.getUserTeamList() + .remove(userTeam); + }); userTeamPersistenceService.deleteAll(team.getUserTeamList()); team.setUserTeamList(List.of()); cacheService.emptyAuthorizationUsersCache(); @@ -107,8 +108,13 @@ public void addUsersToTeam(long teamId, List userIdList) { var team = teamPersistenceService.findById(teamId); for (var userId : userIdList) { var user = userPersistenceService.findById(userId); - var userTeam = UserTeam.Builder.builder().withTeam(team).withUser(user).withTeamAdmin(false).build(); - user.getUserTeamList().add(userTeam); + var userTeam = UserTeam.Builder.builder() + .withTeam(team) + .withUser(user) + .withTeamAdmin(false) + .build(); + user.getUserTeamList() + .add(userTeam); userPersistenceService.save(user); } cacheService.emptyAuthorizationUsersCache(); @@ -122,21 +128,28 @@ public void removeUserFromTeam(long teamId, long userId) { checkTeamHasAtLeastOneAdmin(team, user); var userTeamList = user.getUserTeamList(); - var userTeamToRemove = userTeamList.stream().filter(ut -> ut.getTeam().getId() == teamId).findFirst() - .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, - "No team found to remove from userTeam list")); + var userTeamToRemove = userTeamList.stream() + .filter(ut -> ut.getTeam() + .getId() == teamId) + .findFirst() + .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + "No team found to remove from userTeam list")); userTeamList.remove(userTeamToRemove); - team.getUserTeamList().remove(userTeamToRemove); + team.getUserTeamList() + .remove(userTeamToRemove); userTeamPersistenceService.delete(userTeamToRemove); userPersistenceService.save(user); cacheService.emptyAuthorizationUsersCache(); } private void checkTeamHasAtLeastOneAdmin(Team team, User user) { - team.getUserTeamList().stream() - .filter(ut -> ut.isTeamAdmin() && !Objects.equals(ut.getUser().getId(), user.getId())).findAny() - .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, - ErrorKey.TRIED_TO_DELETE_LAST_ADMIN)); + team.getUserTeamList() + .stream() + .filter(ut -> ut.isTeamAdmin() && !Objects.equals(ut.getUser() + .getId(), user.getId())) + .findAny() + .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.TRIED_TO_DELETE_LAST_ADMIN)); } @Transactional @@ -144,7 +157,9 @@ public void updateOrAddTeamMembership(long teamId, long userId, boolean isAdmin) var user = userPersistenceService.findById(userId); List userTeamList = user.getUserTeamList(); for (var ut : userTeamList) { - if (ut.getTeam().getId().equals(teamId)) { + if (ut.getTeam() + .getId() + .equals(teamId)) { updateTeamMembership(isAdmin, ut, user); return; } @@ -166,7 +181,11 @@ private void updateTeamMembership(boolean isAdmin, UserTeam ut, User user) { private void addTeamMembership(long teamId, boolean isAdmin, User user, List userTeamList) { var team = teamPersistenceService.findById(teamId); - var userTeam = UserTeam.Builder.builder().withTeam(team).withTeamAdmin(isAdmin).withUser(user).build(); + var userTeam = UserTeam.Builder.builder() + .withTeam(team) + .withTeamAdmin(isAdmin) + .withUser(user) + .build(); userTeamList.add(userTeam); } @@ -180,9 +199,11 @@ public int compare(Team t1, Team t2) { return isUserTeam1 ? -1 : 1; } if (Objects.equals(t1.getName(), t2.getName())) { - return t1.getId().compareTo(t2.getId()); + return t1.getId() + .compareTo(t2.getId()); } - return t1.getName().compareTo(t2.getName()); + return t1.getName() + .compareTo(t2.getName()); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java index 6155e4fd0d..7a7f214ab5 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java @@ -1,18 +1,20 @@ package ch.puzzle.okr.service.business; +import java.util.List; +import java.util.Objects; +import java.util.stream.StreamSupport; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.service.CacheService; import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.service.validation.UserValidationService; -import jakarta.transaction.Transactional; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Objects; -import java.util.stream.StreamSupport; +import jakarta.transaction.Transactional; @Service public class UserBusinessService { @@ -23,8 +25,7 @@ public class UserBusinessService { private final CacheService cacheService; - public UserBusinessService(UserPersistenceService userPersistenceService, UserValidationService validationService, - CacheService cacheService) { + public UserBusinessService(UserPersistenceService userPersistenceService, UserValidationService validationService, CacheService cacheService) { this.userPersistenceService = userPersistenceService; this.validationService = validationService; this.cacheService = cacheService; @@ -55,9 +56,11 @@ public User setIsOkrChampion(User user, boolean okrChampion) { // checks if at least one okr champion remains after removing given one private void checkAtLeastOneOkrChampionExists(User user) { var champions = userPersistenceService.findAllOkrChampions(); - champions.stream().filter(c -> c.isOkrChampion() && !Objects.equals(c.getId(), user.getId())).findAny() - .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, - ErrorKey.TRIED_TO_REMOVE_LAST_OKR_CHAMPION)); + champions.stream() + .filter(c -> c.isOkrChampion() && !Objects.equals(c.getId(), user.getId())) + .findAny() + .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.TRIED_TO_REMOVE_LAST_OKR_CHAMPION)); } public User saveUser(User user) { @@ -67,6 +70,7 @@ public User saveUser(User user) { @Transactional public List createUsers(List userList) { var userIter = userPersistenceService.saveAll(userList); - return StreamSupport.stream(userIter.spliterator(), false).toList(); + return StreamSupport.stream(userIter.spliterator(), false) + .toList(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java b/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java index 16f4c1c4da..9e42146b6f 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java @@ -1,17 +1,19 @@ package ch.puzzle.okr.service.clientconfig; +import java.text.MessageFormat; +import java.util.Optional; + import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.multitenancy.TenantConfigProvider; import ch.puzzle.okr.multitenancy.customization.TenantClientCustomization; import ch.puzzle.okr.multitenancy.customization.TenantClientCustomizationProvider; -import jakarta.persistence.EntityNotFoundException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import java.text.MessageFormat; -import java.util.Optional; +import jakarta.persistence.EntityNotFoundException; @Service public class ClientConfigService { @@ -23,8 +25,7 @@ public class ClientConfigService { @Value("${spring.profiles.active}") private String activeProfile; - public ClientConfigService(final TenantClientCustomizationProvider clientCustomizationProvider, - final TenantConfigProvider tenantConfigProvider) { + public ClientConfigService(final TenantClientCustomizationProvider clientCustomizationProvider, final TenantConfigProvider tenantConfigProvider) { this.tenantConfigProvider = tenantConfigProvider; this.tenantClientCustomizationProvider = clientCustomizationProvider; } @@ -33,31 +34,41 @@ public ClientConfigDto getConfigBasedOnActiveEnv(String hostName) { String subdomain = hostName.split("\\.")[0]; String domainPrefixByHyphen = hostName.split("-")[0]; - Optional tenantConfig = getTenantConfig(hostName, subdomain, - domainPrefixByHyphen); + Optional tenantConfig = getTenantConfig(hostName, + subdomain, + domainPrefixByHyphen); if (tenantConfig.isEmpty()) { - throw new EntityNotFoundException( - MessageFormat.format("Could not find tenant config for subdomain:{0}", subdomain)); + throw new EntityNotFoundException(MessageFormat.format("Could not find tenant config for subdomain:{0}", + subdomain)); } Optional tenantClientCustomization = getTenantClientCustomization(hostName, - subdomain, domainPrefixByHyphen); + subdomain, + domainPrefixByHyphen); if (tenantClientCustomization.isEmpty()) { - throw new EntityNotFoundException( - MessageFormat.format("Could not find tenant client customization for subdomain:{0}", subdomain)); + throw new EntityNotFoundException(MessageFormat.format("Could not find tenant client customization for subdomain:{0}", + subdomain)); } return new ClientConfigDto(activeProfile, // - tenantConfig.get().issuerUrl(), // - tenantConfig.get().clientId(), // - tenantClientCustomization.get().favicon(), // - tenantClientCustomization.get().logo(), // - tenantClientCustomization.get().triangles(), // - tenantClientCustomization.get().backgroundLogo(), // - tenantClientCustomization.get().title(), // - tenantClientCustomization.get().customStyles()); // + tenantConfig.get() + .issuerUrl(), // + tenantConfig.get() + .clientId(), // + tenantClientCustomization.get() + .favicon(), // + tenantClientCustomization.get() + .logo(), // + tenantClientCustomization.get() + .triangles(), // + tenantClientCustomization.get() + .backgroundLogo(), // + tenantClientCustomization.get() + .title(), // + tenantClientCustomization.get() + .customStyles()); // } private Optional getTenantConfig(String hostname, String... tenantsFromUrl) { @@ -73,11 +84,9 @@ private Optional getTenantConfig(String hostn return Optional.empty(); } - private Optional getTenantClientCustomization(String hostname, - String... tenantsFromUrl) { + private Optional getTenantClientCustomization(String hostname, String... tenantsFromUrl) { for (String tenant : tenantsFromUrl) { - Optional tenantCustomization = tenantClientCustomizationProvider - .getTenantClientCustomizationsById(tenant); + Optional tenantCustomization = tenantClientCustomizationProvider.getTenantClientCustomizationsById(tenant); if (tenantCustomization.isPresent()) { logger.info("get client customization for " + tenant + ": OK"); return tenantCustomization; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java index 3c3a1ff83c..ec7b7d58e2 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.repository.ActionRepository; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.ACTION; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java index 03bb2ad444..a9c6e8e411 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java @@ -1,12 +1,13 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.alignment.Alignment; import ch.puzzle.okr.models.alignment.KeyResultAlignment; import ch.puzzle.okr.models.alignment.ObjectiveAlignment; import ch.puzzle.okr.repository.AlignmentRepository; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.ALIGNMENT; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java index 3a439073b8..e121cb7144 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.repository.AlignmentSelectionRepository; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; @Service public class AlignmentSelectionPersistenceService { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java index 50649665db..0ad7a190b4 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java @@ -1,12 +1,14 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.authorization.AuthorizationUser; -import jakarta.persistence.TypedQuery; + import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; -import java.util.List; +import jakarta.persistence.TypedQuery; import static ch.puzzle.okr.models.State.*; import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; @@ -29,12 +31,12 @@ public String appendOverview(List teamIds, String objectiveQuery, Authoriz sb.append("\n and o.overviewId.teamId in (:" + PARAM_TEAM_IDS + ")"); } if (shouldAddObjectiveFilter(objectiveQuery)) { - sb.append("\n and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:" + PARAM_OBJECTIVE_QUERY - + ",'%'))"); + sb.append("\n and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:" + PARAM_OBJECTIVE_QUERY + ",'%'))"); } String authorizationWhereClause = append(user, alias, "objectiveState", "overviewId.teamId"); if (!authorizationWhereClause.isEmpty()) { - sb.append("\n").append(authorizationWhereClause.substring(0, authorizationWhereClause.length() - 1)); + sb.append("\n") + .append(authorizationWhereClause.substring(0, authorizationWhereClause.length() - 1)); sb.append(format(" or %s.overviewId.objectiveId = -1)", alias)); } return sb.toString(); @@ -50,19 +52,25 @@ private String append(AuthorizationUser user, String alias, String stateColumn, sb.append(format(" or %s.%s=:%s", alias, stateColumn, PARAM_ALL_DRAFT_STATE)); } else { // users can read draft state of teams with admin role - sb.append(format(" or (%s.%s=:%s and %s.%s IN (:%s))", alias, stateColumn, PARAM_TEAM_DRAFT_STATE, alias, - teamIdColumn, PARAM_USER_TEAM_IDS)); + sb.append(format(" or (%s.%s=:%s and %s.%s IN (:%s))", + alias, + stateColumn, + PARAM_TEAM_DRAFT_STATE, + alias, + teamIdColumn, + PARAM_USER_TEAM_IDS)); } // all users can read published state sb.append(format(" or %s.%s IN (:%s)", alias, stateColumn, PARAM_PUBLISHED_STATES)); if (!sb.isEmpty()) { - sb.delete(0, 4).insert(0, " and (").append(")"); + sb.delete(0, 4) + .insert(0, " and (") + .append(")"); } return sb.toString(); } - public void setParameters(TypedQuery typedQuery, List teamIds, String objectiveQuery, - AuthorizationUser user) { + public void setParameters(TypedQuery typedQuery, List teamIds, String objectiveQuery, AuthorizationUser user) { if (shouldAddTeamFilter(teamIds)) { typedQuery.setParameter(PARAM_TEAM_IDS, teamIds); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java index 5a96b8dcb5..d5fb1c05d1 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.repository.CheckInRepository; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.CHECK_IN; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java index 48a5d2c195..8217320b99 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java @@ -2,6 +2,7 @@ import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.repository.CompletedRepository; + import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.COMPLETED; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java index 14e223bff5..e05d33f3bc 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java @@ -1,11 +1,13 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.repository.KeyResultRepository; -import jakarta.transaction.Transactional; + import org.springframework.stereotype.Service; -import java.util.List; +import jakarta.transaction.Transactional; import static ch.puzzle.okr.Constants.KEY_RESULT; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java index 9e7a2bcd34..0d18d17fe4 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java @@ -1,19 +1,21 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.repository.ObjectiveRepository; -import jakarta.persistence.EntityManager; -import jakarta.persistence.NoResultException; -import jakarta.persistence.TypedQuery; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import java.util.List; +import jakarta.persistence.EntityManager; +import jakarta.persistence.NoResultException; +import jakarta.persistence.TypedQuery; import static ch.puzzle.okr.Constants.OBJECTIVE; @@ -28,8 +30,7 @@ public class ObjectivePersistenceService extends PersistenceBase authorizationCriteria; - protected ObjectivePersistenceService(ObjectiveRepository repository, EntityManager entityManager, - AuthorizationCriteria authorizationCriteria) { + protected ObjectivePersistenceService(ObjectiveRepository repository, EntityManager entityManager, AuthorizationCriteria authorizationCriteria) { super(repository); this.entityManager = entityManager; this.authorizationCriteria = authorizationCriteria; @@ -45,9 +46,9 @@ public String getModelName() { * where teamId = team.id and quarterId = quarter.id." * * @param team - * Team + * Team * @param quarter - * Quarter + * Quarter * * @return number of Objectives of team in quarter */ @@ -55,8 +56,7 @@ public Integer countByTeamAndQuarter(Team team, Quarter quarter) { return getRepository().countByTeamAndQuarter(team, quarter); } - public Objective findObjectiveById(Long objectiveId, AuthorizationUser authorizationUser, - OkrResponseStatusException noResultException) { + public Objective findObjectiveById(Long objectiveId, AuthorizationUser authorizationUser, OkrResponseStatusException noResultException) { return findByAnyId(objectiveId, authorizationUser, SELECT_OBJECTIVE_BY_ID, noResultException); } @@ -64,18 +64,15 @@ public List findObjectiveByTeamId(Long teamId) { return getRepository().findObjectivesByTeamId(teamId); } - public Objective findObjectiveByKeyResultId(Long keyResultId, AuthorizationUser authorizationUser, - OkrResponseStatusException noResultException) { + public Objective findObjectiveByKeyResultId(Long keyResultId, AuthorizationUser authorizationUser, OkrResponseStatusException noResultException) { return findByAnyId(keyResultId, authorizationUser, SELECT_OBJECTIVE_BY_KEY_RESULT_ID, noResultException); } - public Objective findObjectiveByCheckInId(Long checkInId, AuthorizationUser authorizationUser, - OkrResponseStatusException noResultException) { + public Objective findObjectiveByCheckInId(Long checkInId, AuthorizationUser authorizationUser, OkrResponseStatusException noResultException) { return findByAnyId(checkInId, authorizationUser, SELECT_OBJECTIVE_BY_CHECK_IN_ID, noResultException); } - private Objective findByAnyId(Long id, AuthorizationUser authorizationUser, String queryString, - OkrResponseStatusException noResultException) { + private Objective findByAnyId(Long id, AuthorizationUser authorizationUser, String queryString, OkrResponseStatusException noResultException) { checkIdNull(id); String fullQueryString = queryString + authorizationCriteria.appendObjective(authorizationUser); logger.debug("select objective by id={}: {}", id, fullQueryString); diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java index 197cdc5d9d..f0fbd13c91 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java @@ -1,14 +1,16 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; -import jakarta.persistence.EntityManager; -import jakarta.persistence.TypedQuery; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import java.util.List; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; @Service public class OverviewPersistenceService { @@ -19,16 +21,15 @@ public class OverviewPersistenceService { private final EntityManager entityManager; private final AuthorizationCriteria authorizationCriteria; - public OverviewPersistenceService(EntityManager entityManager, - AuthorizationCriteria authorizationCriteria) { + public OverviewPersistenceService(EntityManager entityManager, AuthorizationCriteria authorizationCriteria) { this.entityManager = entityManager; this.authorizationCriteria = authorizationCriteria; } - public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery, - AuthorizationUser authorizationUser) { - String queryString = SELECT_OVERVIEW - + authorizationCriteria.appendOverview(teamIds, objectiveQuery, authorizationUser); + public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery, AuthorizationUser authorizationUser) { + String queryString = SELECT_OVERVIEW + authorizationCriteria.appendOverview(teamIds, + objectiveQuery, + authorizationUser); logger.debug("select overview by quarterId={} and teamIds={}: {}", quarterId, teamIds, queryString); TypedQuery typedQuery = entityManager.createQuery(queryString, Overview.class); typedQuery.setParameter("quarterId", quarterId); diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java index f10ea423fc..34fb7ee515 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java @@ -1,28 +1,29 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.stream.StreamSupport; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.data.repository.CrudRepository; import org.springframework.http.HttpStatus; -import java.util.List; -import java.util.Spliterator; -import java.util.Spliterators; -import java.util.stream.StreamSupport; - import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.NOT_FOUND; /** * @param - * the Type or entity of the repository + * the Type or entity of the repository * @param - * the Identifier or primary key of the entity + * the Identifier or primary key of the entity * @param - * the Repository of the entity + * the Repository of the entity */ public abstract class PersistenceBase { @@ -41,7 +42,8 @@ public R getRepository() { public T findById(ID id) throws OkrResponseStatusException { checkIdNull(id); - return repository.findById(id).orElseThrow(() -> createEntityNotFoundException(id)); + return repository.findById(id) + .orElseThrow(() -> createEntityNotFoundException(id)); } public void checkIdNull(ID id) { @@ -59,8 +61,9 @@ public T save(T model) throws OkrResponseStatusException { return repository.save(model); } catch (OptimisticLockingFailureException ex) { logger.info("optimistic locking exception while saving {}", model, ex); - throw new OkrResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, ErrorKey.DATA_HAS_BEEN_UPDATED, - getModelName()); + throw new OkrResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, + ErrorKey.DATA_HAS_BEEN_UPDATED, + getModelName()); } } @@ -75,7 +78,8 @@ public void deleteById(ID id) { public abstract String getModelName(); private List iteratorToList(Iterable iterable) { - return StreamSupport - .stream(Spliterators.spliteratorUnknownSize(iterable.iterator(), Spliterator.ORDERED), false).toList(); + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterable.iterator(), Spliterator.ORDERED), + false) + .toList(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java index 5646a15998..9042a68927 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java @@ -1,11 +1,12 @@ package ch.puzzle.okr.service.persistence; +import java.time.LocalDate; +import java.util.List; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.repository.QuarterRepository; -import org.springframework.stereotype.Service; -import java.time.LocalDate; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.QUARTER; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java index 533949d848..80dce4e34e 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.Team; import ch.puzzle.okr.repository.TeamRepository; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.TEAM; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java index 6d5befc699..42b9a20a22 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java @@ -1,11 +1,12 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; +import java.util.Optional; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.repository.UserRepository; -import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Optional; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.USER; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java index 326feabe4d..436c473bf1 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java @@ -1,10 +1,11 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.UserTeam; import ch.puzzle.okr.repository.UserTeamRepository; -import org.springframework.stereotype.Service; -import java.util.List; +import org.springframework.stereotype.Service; import static ch.puzzle.okr.Constants.USER_TEAM; diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java index 4e591099ff..d9dc9c4337 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.validation; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.Constants; import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; @@ -7,19 +10,16 @@ import ch.puzzle.okr.models.MessageKey; import ch.puzzle.okr.repository.ActionRepository; import ch.puzzle.okr.service.persistence.ActionPersistenceService; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Objects; - @Service public class ActionValidationService extends ValidationBase { private final KeyResultValidationService keyResultValidationService; - public ActionValidationService(ActionPersistenceService actionPersistenceService, - KeyResultValidationService keyResultValidationService) { + public ActionValidationService(ActionPersistenceService actionPersistenceService, KeyResultValidationService keyResultValidationService) { super(actionPersistenceService); this.keyResultValidationService = keyResultValidationService; } @@ -48,13 +48,18 @@ public void validateOnUpdate(Long id, Action model) { void throwExceptionWhenKeyResultHasChanged(Action action, Action savedAction) { if (action.getKeyResult() == null || savedAction.getKeyResult() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, MessageKey.ATTRIBUTE_NOT_NULL, - List.of(Constants.KEY_RESULT, Constants.ACTION)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + MessageKey.ATTRIBUTE_NOT_NULL, + List.of(Constants.KEY_RESULT, Constants.ACTION)); } - if (!Objects.equals(action.getKeyResult().getId(), savedAction.getKeyResult().getId())) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CANNOT_CHANGE, - List.of(Constants.KEY_RESULT, Constants.ACTION)); + if (!Objects.equals(action.getKeyResult() + .getId(), + savedAction.getKeyResult() + .getId())) { + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CANNOT_CHANGE, + List.of(Constants.KEY_RESULT, Constants.ACTION)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java index 87f3f14839..86709209de 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java @@ -1,20 +1,20 @@ package ch.puzzle.okr.service.validation; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.Constants; import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.repository.CheckInRepository; import ch.puzzle.okr.service.persistence.CheckInPersistenceService; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Objects; - @Service -public class CheckInValidationService - extends ValidationBase { +public class CheckInValidationService extends ValidationBase { public CheckInValidationService(CheckInPersistenceService checkInPersistenceService) { super(checkInPersistenceService); @@ -38,9 +38,13 @@ public void validateOnUpdate(Long id, CheckIn model) { } private static void throwExceptionWhenKeyResultHasChanged(CheckIn checkIn, CheckIn savedCheckIn) { - if (!Objects.equals(checkIn.getKeyResult().getId(), savedCheckIn.getKeyResult().getId())) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CANNOT_CHANGE, - List.of(Constants.KEY_RESULT, Constants.CHECK_IN)); + if (!Objects.equals(checkIn.getKeyResult() + .getId(), + savedCheckIn.getKeyResult() + .getId())) { + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CANNOT_CHANGE, + List.of(Constants.KEY_RESULT, Constants.CHECK_IN)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java index 702db8e4d7..b810365afb 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java @@ -3,11 +3,11 @@ import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.repository.CompletedRepository; import ch.puzzle.okr.service.persistence.CompletedPersistenceService; + import org.springframework.stereotype.Service; @Service -public class CompletedValidationService - extends ValidationBase { +public class CompletedValidationService extends ValidationBase { public CompletedValidationService(CompletedPersistenceService completedPersistenceService) { super(completedPersistenceService); diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java index ea5a3b68e9..c686899cde 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java @@ -1,20 +1,20 @@ package ch.puzzle.okr.service.validation; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.Constants; import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.repository.KeyResultRepository; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Objects; - @Service -public class KeyResultValidationService - extends ValidationBase { +public class KeyResultValidationService extends ValidationBase { public KeyResultValidationService(KeyResultPersistenceService keyResultPersistenceService) { super(keyResultPersistenceService); @@ -38,9 +38,13 @@ public void validateOnUpdate(Long id, KeyResult model) { } private static void throwExceptionWhenObjectiveHasChanged(KeyResult keyResult, KeyResult savedKeyResult) { - if (!Objects.equals(keyResult.getObjective().getId(), savedKeyResult.getObjective().getId())) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CANNOT_CHANGE, - List.of(Constants.OBJECTIVE, Constants.KEY_RESULT)); + if (!Objects.equals(keyResult.getObjective() + .getId(), + savedKeyResult.getObjective() + .getId())) { + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CANNOT_CHANGE, + List.of(Constants.OBJECTIVE, Constants.KEY_RESULT)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java index 72f518c738..53fd08a752 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.validation; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -7,18 +10,15 @@ import ch.puzzle.okr.models.Team; import ch.puzzle.okr.repository.ObjectiveRepository; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Objects; - import static ch.puzzle.okr.Constants.*; import static ch.puzzle.okr.service.validation.QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull; @Service -public class ObjectiveValidationService - extends ValidationBase { +public class ObjectiveValidationService extends ValidationBase { public ObjectiveValidationService(ObjectivePersistenceService objectivePersistenceService) { super(objectivePersistenceService); @@ -49,36 +49,44 @@ public void validateOnUpdate(Long id, Objective model) { private void throwExceptionWhenModifiedByIsSet(Objective model) { if (model.getModifiedBy() != null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_SET_FORBIDDEN, - List.of("ModifiedBy", model.getModifiedBy())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_SET_FORBIDDEN, + List.of("ModifiedBy", model.getModifiedBy())); } } private void throwExceptionWhenModifiedByIsNull(Objective model) { if (model.getModifiedBy() == null) { - throw new OkrResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorKey.ATTRIBUTE_NOT_SET, - "modifiedBy"); + throw new OkrResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, + ErrorKey.ATTRIBUTE_NOT_SET, + "modifiedBy"); } } private void throwExceptionWhenTeamHasChanged(Team team, Team savedTeam) { if (!Objects.equals(team, savedTeam)) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CANNOT_CHANGE, - List.of(TEAM, OBJECTIVE)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CANNOT_CHANGE, + List.of(TEAM, OBJECTIVE)); } } private void throwExceptionWhenNotDraftInBacklogQuarter(Objective model) { if (isInvalidBacklogObjective(model)) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_MUST_BE_DRAFT, - List.of(OBJECTIVE, STATE_DRAFT, model.getState())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_MUST_BE_DRAFT, + List.of(OBJECTIVE, STATE_DRAFT, model.getState())); } } private boolean isInvalidBacklogObjective(Objective model) { - return model.getQuarter().getLabel().equals(BACK_LOG_QUARTER_LABEL) // - && model.getQuarter().getStartDate() == null // - && model.getQuarter().getEndDate() == null // + return model.getQuarter() + .getLabel() + .equals(BACK_LOG_QUARTER_LABEL) // + && model.getQuarter() + .getStartDate() == null // + && model.getQuarter() + .getEndDate() == null // && (model.getState() != State.DRAFT); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java index af0013b52d..49f776a130 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java @@ -1,8 +1,9 @@ package ch.puzzle.okr.service.validation; -import org.springframework.stereotype.Service; import java.util.List; +import org.springframework.stereotype.Service; + @Service public class OverviewValidationService { private final TeamValidationService teamValidator; diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java index baa9df7252..0aaa5593af 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java @@ -1,20 +1,20 @@ package ch.puzzle.okr.service.validation; +import java.util.List; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.repository.QuarterRepository; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; - import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; @Service -public class QuarterValidationService - extends ValidationBase { +public class QuarterValidationService extends ValidationBase { public QuarterValidationService(QuarterPersistenceService quarterPersistenceService) { super(quarterPersistenceService); @@ -31,13 +31,16 @@ public void validateOnUpdate(Long id, Quarter model) { } public static void throwExceptionWhenStartEndDateQuarterIsNull(Quarter model) { - if (!model.getLabel().equals(BACK_LOG_QUARTER_LABEL)) { + if (!model.getLabel() + .equals(BACK_LOG_QUARTER_LABEL)) { if (model.getStartDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("StartDate", model.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("StartDate", model.getLabel())); } else if (model.getEndDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("EndDate", model.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("EndDate", model.getLabel())); } } @@ -45,11 +48,13 @@ public static void throwExceptionWhenStartEndDateQuarterIsNull(Quarter model) { public void validateOnGeneration(Quarter quarter) { if (quarter.getStartDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("StartDate", quarter.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("StartDate", quarter.getLabel())); } else if (quarter.getEndDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("EndDate", quarter.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("EndDate", quarter.getLabel())); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java index 8b08e1d4a2..3ee029bf52 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java @@ -1,16 +1,17 @@ package ch.puzzle.okr.service.validation; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.repository.TeamRepository; import ch.puzzle.okr.service.persistence.TeamPersistenceService; + import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Objects; - import static ch.puzzle.okr.Constants.TEAM; @Service @@ -39,11 +40,15 @@ public void validateOnUpdate(Long id, Team model) { } private void checkIfTeamWithNameAlreadyExists(String name, Long id) { - List filteredTeam = this.getPersistenceService().findTeamsByName(name).stream() - .filter(team -> !Objects.equals(team.getId(), id)).toList(); + List filteredTeam = this.getPersistenceService() + .findTeamsByName(name) + .stream() + .filter(team -> !Objects.equals(team.getId(), id)) + .toList(); if (!filteredTeam.isEmpty()) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ALREADY_EXISTS_SAME_NAME, - List.of(TEAM, name)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ALREADY_EXISTS_SAME_NAME, + List.of(TEAM, name)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java index 487530aa3e..7cb0111341 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java @@ -5,6 +5,7 @@ import ch.puzzle.okr.models.User; import ch.puzzle.okr.repository.UserRepository; import ch.puzzle.okr.service.persistence.UserPersistenceService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.oauth2.jwt.Jwt; diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java b/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java index e18cd9e982..a521690e7d 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java @@ -1,32 +1,34 @@ package ch.puzzle.okr.service.validation; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.MessageKey; import ch.puzzle.okr.service.persistence.PersistenceBase; + +import org.springframework.http.HttpStatus; + import jakarta.validation.ConstraintViolation; import jakarta.validation.Validation; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; -import org.springframework.http.HttpStatus; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * @param - * the Type or entity of the repository + * the Type or entity of the repository * @param - * the Identifier or primary key of the entity + * the Identifier or primary key of the entity * @param - * the Repository of the entity + * the Repository of the entity * @param - * the Persistence Service of this repository and entity + * the Persistence Service of this repository and entity */ public abstract class ValidationBase> { private final Validator validator; @@ -62,29 +64,33 @@ public T doesEntityExist(ID id) { public void throwExceptionWhenModelIsNull(T model) { if (model == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.MODEL_NULL, - persistenceService.getModelName()); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.MODEL_NULL, + persistenceService.getModelName()); } } public void throwExceptionWhenIdIsNull(ID id) { if (id == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("ID", persistenceService.getModelName())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("ID", persistenceService.getModelName())); } } protected void throwExceptionWhenIdIsNotNull(ID id) { if (id != null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, MessageKey.ATTRIBUTE_NOT_NULL, - List.of("ID", persistenceService.getModelName())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + MessageKey.ATTRIBUTE_NOT_NULL, + List.of("ID", persistenceService.getModelName())); } } protected void throwExceptionWhenIdHasChanged(ID id, ID modelId) { if (!Objects.equals(id, modelId)) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CHANGED, - List.of("ID", id, modelId)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CHANGED, + List.of("ID", id, modelId)); } } @@ -102,13 +108,17 @@ private void processViolations(Set> violations) { private List createErrorDtos(Set> violations) { return violations.stream() // - .map(e -> { // - String path = e.getPropertyPath().toString(); // - List attributes = new ArrayList<>(List.of(path, persistenceService.getModelName())); // - attributes.addAll(getAttributes(e.getMessage(), e.getMessageTemplate())); // - String errorKey = e.getMessageTemplate().replaceAll("_\\{.*", ""); // - return ErrorDto.of(errorKey, attributes); // - }).toList(); + .map(e -> { // + String path = e.getPropertyPath() + .toString(); // + List attributes = new ArrayList<>(List.of(path, + persistenceService.getModelName())); // + attributes.addAll(getAttributes(e.getMessage(), e.getMessageTemplate())); // + String errorKey = e.getMessageTemplate() + .replaceAll("_\\{.*", ""); // + return ErrorDto.of(errorKey, attributes); // + }) + .toList(); } // example: diff --git a/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java b/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java index 5c3a002a28..d3cc589812 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java +++ b/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java @@ -8,7 +8,7 @@ public class CollectionUtils { public static List iterableToList(Iterable iterable) { return StreamSupport // - .stream(iterable.spliterator(), false) // - .collect(Collectors.toList()); + .stream(iterable.spliterator(), false) // + .collect(Collectors.toList()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java index 2bab507122..7ce2f5c24e 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java @@ -1,9 +1,9 @@ package ch.puzzle.okr.util.quarter.generate; -import org.springframework.context.annotation.Profile; - import java.time.LocalDate; +import org.springframework.context.annotation.Profile; + /** * Quarter data for H2 database.
*
diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java index 4b44aaf00b..fcca3c1e06 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java @@ -1,9 +1,9 @@ package ch.puzzle.okr.util.quarter.generate; -import org.springframework.context.annotation.Profile; - import java.time.LocalDate; +import org.springframework.context.annotation.Profile; + /** * Quarter label for H2 database.
*
diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java index 0c7679714b..65e94fd29f 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java @@ -1,11 +1,11 @@ package ch.puzzle.okr.util.quarter.generate; -import org.springframework.context.annotation.Profile; - import java.time.LocalDate; import java.util.ArrayList; import java.util.List; +import org.springframework.context.annotation.Profile; + /** * Static initialize quarters for H2 database.
*
diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java index fec72a232a..6a1df814c1 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java @@ -1,16 +1,17 @@ package ch.puzzle.okr.util.quarter.generate.h2; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; + import ch.puzzle.okr.util.quarter.generate.QuarterData; import ch.puzzle.okr.util.quarter.generate.Quarters; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; -import java.time.LocalDate; -import java.util.HashMap; -import java.util.Map; - /** * Quarter functions for H2 database.
*
@@ -40,38 +41,44 @@ private static void registerCurrentQuarterForDate(LocalDate date, int dbId) { } public static String currentQuarterLabel() { - var label = QUARTERS.get(CURRENT_QUARTER_DB_ID).label(); + var label = QUARTERS.get(CURRENT_QUARTER_DB_ID) + .label(); logger.info("currentQuarterLabel : {}", label); return label; } public static String currentQuarterStartDate() { - var start = QUARTERS.get(CURRENT_QUARTER_DB_ID).startDateAsIsoString(); + var start = QUARTERS.get(CURRENT_QUARTER_DB_ID) + .startDateAsIsoString(); logger.info("currentQuarterStartDate: {}", start); return start; } public static String currentQuarterEndDate() { - var end = QUARTERS.get(CURRENT_QUARTER_DB_ID).endDateAsIsoString(); + var end = QUARTERS.get(CURRENT_QUARTER_DB_ID) + .endDateAsIsoString(); logger.info("currentQuarterEndDate : {}", end); return end; } public static String nextQuarterLabel() { - var label = QUARTERS.get(NEXT_QUARTER_DB_ID).label(); + var label = QUARTERS.get(NEXT_QUARTER_DB_ID) + .label(); logger.info("nextQuarterLabel : {}", label); return label; } public static String nextQuarterStartDate() { - var start = QUARTERS.get(NEXT_QUARTER_DB_ID).startDateAsIsoString(); + var start = QUARTERS.get(NEXT_QUARTER_DB_ID) + .startDateAsIsoString(); logger.info("nextQuarterStartDate : {}", start); return start; } public static String nextQuarterEndDate() { - var end = QUARTERS.get(NEXT_QUARTER_DB_ID).endDateAsIsoString(); + var end = QUARTERS.get(NEXT_QUARTER_DB_ID) + .endDateAsIsoString(); logger.info("nextQuarterEndDate : {}", end); return end; } diff --git a/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java b/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java index 1c27667c3e..d8870aca1c 100644 --- a/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java +++ b/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java @@ -1,12 +1,8 @@ package ch.puzzle.okr; -import jakarta.servlet.FilterChain; -import jakarta.servlet.RequestDispatcher; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.HttpServletRequest; +import java.io.IOException; + import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -15,7 +11,11 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import java.io.IOException; +import jakarta.servlet.FilterChain; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; import static org.mockito.Mockito.*; diff --git a/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java b/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java index 1ca5d0825a..b7e33605d7 100644 --- a/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java +++ b/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java @@ -6,6 +6,7 @@ import ch.puzzle.okr.service.authorization.AuthorizationRegistrationService; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -38,7 +39,8 @@ void setUp() { @AfterEach void tearDown() { TenantContext.setCurrentTenant(null); - cacheManager.getCache(AUTHORIZATION_USER_CACHE).clear(); + cacheManager.getCache(AUTHORIZATION_USER_CACHE) + .clear(); } @DisplayName("before calling updateOrAddAuthorizationUser the User is not in the cache") @@ -63,13 +65,13 @@ void testUserIsCached() { assertEqualUsers(expectedUser, cachedUser); } - private void assertEqualUsers(AuthorizationUser expectedAuthorizationUser, - AuthorizationUser actualAuthorizationUser) { + private void assertEqualUsers(AuthorizationUser expectedAuthorizationUser, AuthorizationUser actualAuthorizationUser) { User expcetedUser = expectedAuthorizationUser.user(); User actualUser = actualAuthorizationUser.user(); - assertTrue(expcetedUser.getFirstname().equals(actualUser.getFirstname()) - && expcetedUser.getLastname().equals(actualUser.getLastname()) - && expcetedUser.getEmail().equals(actualUser.getEmail())); + assertTrue(expcetedUser.getFirstname() + .equals(actualUser.getFirstname()) && expcetedUser.getLastname() + .equals(actualUser.getLastname()) && expcetedUser.getEmail() + .equals(actualUser.getEmail())); } } \ No newline at end of file diff --git a/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java b/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java index 05d38792e5..23bc370f4d 100644 --- a/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java +++ b/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java @@ -1,12 +1,13 @@ package ch.puzzle.okr; +import java.lang.reflect.Method; + import ch.puzzle.okr.multitenancy.TenantContext; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; - import static ch.puzzle.okr.test.KeyResultTestHelpers.user; class UserKeyGeneratorTest { @@ -19,7 +20,8 @@ void setUp() { @Test void generate_shouldReturnTenantAndUserInfo() { Object notUsedObject = new Object(); - Method notUsedMethod = notUsedObject.getClass().getEnclosingMethod(); + Method notUsedMethod = notUsedObject.getClass() + .getEnclosingMethod(); UserKeyGenerator generator = new UserKeyGenerator(); String userKey = (String) generator.generate(notUsedObject, notUsedMethod, user); diff --git a/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java b/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java index cde1091ed1..d4fcb9b16c 100644 --- a/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java +++ b/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java @@ -1,10 +1,5 @@ package ch.puzzle.okr.architecture; -import com.tngtech.archunit.core.domain.JavaClasses; -import com.tngtech.archunit.core.importer.ClassFileImporter; -import com.tngtech.archunit.core.importer.ImportOption; -import com.tngtech.archunit.lang.ArchRule; -import com.tngtech.archunit.library.Architectures; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -13,6 +8,12 @@ import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.RestController; +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.lang.ArchRule; +import com.tngtech.archunit.library.Architectures; + import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; import static com.tngtech.archunit.library.Architectures.layeredArchitecture; @@ -22,8 +23,13 @@ class OkrArchitectureTest { @Test void repositoryAccessedOnlyByPersistenceService() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..repository..").should().onlyBeAccessed() - .byAnyPackage("..service.persistence..").andShould().beInterfaces(); + ArchRule rule = classes().that() + .resideInAPackage("..repository..") + .should() + .onlyBeAccessed() + .byAnyPackage("..service.persistence..") + .andShould() + .beInterfaces(); rule.check(importedClasses); } @@ -31,8 +37,11 @@ void repositoryAccessedOnlyByPersistenceService() { @Test void mapperAccessedByControllerOrAuthorization() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..mapper..").should().onlyBeAccessed() - .byAnyPackage("..controller..", "..mapper..", "..authorization.."); + ArchRule rule = classes().that() + .resideInAPackage("..mapper..") + .should() + .onlyBeAccessed() + .byAnyPackage("..controller..", "..mapper..", "..authorization.."); rule.check(importedClasses); } @@ -40,8 +49,11 @@ void mapperAccessedByControllerOrAuthorization() { @Test void authorizationServiceAccessedByControllerOrAuthorization() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..service.authorization..").should().onlyBeAccessed() - .byAnyPackage("..controller..", "..authorization.."); + ArchRule rule = classes().that() + .resideInAPackage("..service.authorization..") + .should() + .onlyBeAccessed() + .byAnyPackage("..controller..", "..authorization.."); rule.check(importedClasses); } @@ -49,8 +61,11 @@ void authorizationServiceAccessedByControllerOrAuthorization() { @Test void businessServiceAccessedByControllerOrAuthorizationServiceOrMapper() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..service.business..").should().onlyBeAccessed() - .byAnyPackage("..controller..", "..authorization..", "..mapper..", "..business"); + ArchRule rule = classes().that() + .resideInAPackage("..service.business..") + .should() + .onlyBeAccessed() + .byAnyPackage("..controller..", "..authorization..", "..mapper..", "..business"); rule.check(importedClasses); } @@ -59,8 +74,13 @@ void businessServiceAccessedByControllerOrAuthorizationServiceOrMapper() { void controllerCallsNoRepository() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = noClasses().that().resideInAPackage("ch.puzzle.okr.controller..").should().dependOnClassesThat() - .resideInAPackage("..repository..").andShould().notBeInterfaces(); + ArchRule rule = noClasses().that() + .resideInAPackage("ch.puzzle.okr.controller..") + .should() + .dependOnClassesThat() + .resideInAPackage("..repository..") + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @@ -69,8 +89,13 @@ void controllerCallsNoRepository() { void repositoryCallsNoService() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = noClasses().that().resideInAPackage("ch.puzzle.okr.repository").should().dependOnClassesThat() - .resideInAPackage("..service..").andShould().beInterfaces(); + ArchRule rule = noClasses().that() + .resideInAPackage("ch.puzzle.okr.repository") + .should() + .dependOnClassesThat() + .resideInAPackage("..service..") + .andShould() + .beInterfaces(); rule.check(importedClasses); } @@ -79,8 +104,14 @@ void repositoryCallsNoService() { void servicesAreAnnotatedWithService() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().areNotAnonymousClasses().and().resideInAPackage("ch.puzzle.okr.service") - .should().beAnnotatedWith(Service.class).andShould().notBeInterfaces(); + ArchRule rule = classes().that() + .areNotAnonymousClasses() + .and() + .resideInAPackage("ch.puzzle.okr.service") + .should() + .beAnnotatedWith(Service.class) + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @@ -89,9 +120,16 @@ void servicesAreAnnotatedWithService() { void controllersAreAnnotatedWithRestController() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().areNotAnonymousClasses().and().resideInAPackage("ch.puzzle.okr.controller..") - .should().beAnnotatedWith(RestController.class).orShould().beAnnotatedWith(Controller.class).andShould() - .notBeInterfaces(); + ArchRule rule = classes().that() + .areNotAnonymousClasses() + .and() + .resideInAPackage("ch.puzzle.okr.controller..") + .should() + .beAnnotatedWith(RestController.class) + .orShould() + .beAnnotatedWith(Controller.class) + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @@ -100,32 +138,47 @@ void controllersAreAnnotatedWithRestController() { void mappersAreAnnotatedWithComponent() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().areNotAnonymousClasses().and().resideInAPackage("ch.puzzle.okr.mapper") - .should().beAnnotatedWith(Component.class).andShould().notBeInterfaces(); + ArchRule rule = classes().that() + .areNotAnonymousClasses() + .and() + .resideInAPackage("ch.puzzle.okr.mapper") + .should() + .beAnnotatedWith(Component.class) + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @ParameterizedTest @CsvFileSource(resources = "/repositoriesAndPersistenceServices.csv", numLinesToSkip = 1) - void repositoriesShouldOnlyBeCalledFromPersistenceServicesAndValidationService(String repository, - String persistenceService, String validationService) { + void repositoriesShouldOnlyBeCalledFromPersistenceServicesAndValidationService(String repository, String persistenceService, String validationService) { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().haveSimpleName(repository).should().onlyHaveDependentClassesThat() - .haveSimpleName(persistenceService).orShould().haveSimpleName(repository).orShould() - .haveSimpleName(validationService); + ArchRule rule = classes().that() + .haveSimpleName(repository) + .should() + .onlyHaveDependentClassesThat() + .haveSimpleName(persistenceService) + .orShould() + .haveSimpleName(repository) + .orShould() + .haveSimpleName(validationService); rule.check(importedClasses); } @ParameterizedTest - @ValueSource(strings = { "controller", "service", "mapper", "repository", "dto", "exception" }) + @ValueSource(strings = {"controller", "service", "mapper", "repository", "dto", "exception"}) void classesInRightPackages(String passedName) { JavaClasses importedClasses = new ClassFileImporter().importPackages("ch.puzzle.okr"); - ArchRule rule = classes().that().haveSimpleNameEndingWith(StringUtils.capitalize(passedName)).and() - .areTopLevelClasses().should().resideInAPackage("ch.puzzle.okr." + passedName + ".."); + ArchRule rule = classes().that() + .haveSimpleNameEndingWith(StringUtils.capitalize(passedName)) + .and() + .areTopLevelClasses() + .should() + .resideInAPackage("ch.puzzle.okr." + passedName + ".."); rule.check(importedClasses); } @@ -134,28 +187,44 @@ void classesInRightPackages(String passedName) { void serviceLayerCheck() { JavaClasses importedClasses = getMainSourceClasses(); Architectures.LayeredArchitecture layeredArchitecture = layeredArchitecture().consideringAllDependencies() // - .layer("Controller").definedBy("..controller..") // - .layer("AuthorizationService").definedBy("..service.authorization..") // - .layer("BusinessService").definedBy("..service.business..") // - .layer("ValidationService").definedBy("..service.validation..") // - .layer("PersistenceService").definedBy("..service.persistence..") // - .layer("Repository").definedBy("..repository..") // - .layer("Mapper").definedBy("..mapper..") // - - .whereLayer("Controller").mayNotBeAccessedByAnyLayer() // - .whereLayer("AuthorizationService").mayOnlyBeAccessedByLayers("Controller") // - .whereLayer("BusinessService") - .mayOnlyBeAccessedByLayers("Controller", "AuthorizationService", "Mapper", "BusinessService") // - .whereLayer("ValidationService").mayOnlyBeAccessedByLayers("BusinessService") // - .whereLayer("PersistenceService") - .mayOnlyBeAccessedByLayers("BusinessService", "PersistenceService", "ValidationService") // - .whereLayer("Repository").mayOnlyBeAccessedByLayers("PersistenceService"); // + .layer("Controller") + .definedBy("..controller..") // + .layer("AuthorizationService") + .definedBy("..service.authorization..") // + .layer("BusinessService") + .definedBy("..service.business..") // + .layer("ValidationService") + .definedBy("..service.validation..") // + .layer("PersistenceService") + .definedBy("..service.persistence..") // + .layer("Repository") + .definedBy("..repository..") // + .layer("Mapper") + .definedBy("..mapper..") // + + .whereLayer("Controller") + .mayNotBeAccessedByAnyLayer() // + .whereLayer("AuthorizationService") + .mayOnlyBeAccessedByLayers("Controller") // + .whereLayer("BusinessService") + .mayOnlyBeAccessedByLayers("Controller", + "AuthorizationService", + "Mapper", + "BusinessService") // + .whereLayer("ValidationService") + .mayOnlyBeAccessedByLayers("BusinessService") // + .whereLayer("PersistenceService") + .mayOnlyBeAccessedByLayers("BusinessService", + "PersistenceService", + "ValidationService") // + .whereLayer("Repository") + .mayOnlyBeAccessedByLayers("PersistenceService"); // layeredArchitecture.check(importedClasses); } private static JavaClasses getMainSourceClasses() { return new ClassFileImporter().withImportOption(new ImportOption.DoNotIncludeTests()) - .importPackages("ch.puzzle.okr"); + .importPackages("ch.puzzle.okr"); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java index f7fececa04..e22b002221 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java @@ -1,9 +1,12 @@ package ch.puzzle.okr.controller; +import java.util.List; + import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.authorization.ActionAuthorizationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,8 +23,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; @@ -33,37 +34,37 @@ @WebMvcTest(ActionController.class) class ActionControllerIT { public static final String SUCCESSFUL_UPDATE_BODY = """ - [ - { - "id":1, - "version":1, - "action":"Neuer Drucker", - "priority":0, - "isChecked":true, - "keyResultId":8 - }, - { - "id":2, - "version":1, - "action":"Neues Papier", - "priority":1, - "isChecked":false, - "keyResultId":8 - } - ] - """; + [ + { + "id":1, + "version":1, + "action":"Neuer Drucker", + "priority":0, + "isChecked":true, + "keyResultId":8 + }, + { + "id":2, + "version":1, + "action":"Neues Papier", + "priority":1, + "isChecked":false, + "keyResultId":8 + } + ] + """; public static final String SUCCESSFUL_UPDATE_BODY_SINGLE_ACTION = """ - [ - { - "id":1, - "version":1, - "action":"Neuer Drucker", - "priority":0, - "isChecked":true, - "keyResultId":8 - } - ] - """; + [ + { + "id":1, + "version":1, + "action":"Neuer Drucker", + "priority":0, + "isChecked":true, + "keyResultId":8 + } + ] + """; @MockBean ActionAuthorizationService actionAuthorizationService; @MockBean @@ -74,16 +75,27 @@ class ActionControllerIT { @BeforeEach void setUp() { - Action action = Action.Builder.builder().withId(3L).withAction("Neues Haus").withPriority(1).withIsChecked(true) - .withKeyResult(KeyResultMetric.Builder.builder().withId(10L).withTitle("KR Title").build()).build(); - BDDMockito.given(actionMapper.toActions(any())).willReturn(List.of(action, action)); + Action action = Action.Builder.builder() + .withId(3L) + .withAction("Neues Haus") + .withPriority(1) + .withIsChecked(true) + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(10L) + .withTitle("KR Title") + .build()) + .build(); + BDDMockito.given(actionMapper.toActions(any())) + .willReturn(List.of(action, action)); } @Test void updateSuccessfulActions() throws Exception { - mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()); verify(actionMapper, times(1)).toActions(any()); verify(actionAuthorizationService, times(1)).updateEntities(any()); @@ -91,9 +103,11 @@ void updateSuccessfulActions() throws Exception { @Test void updateSuccessfulOnlyOneAction() throws Exception { - mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY_SINGLE_ACTION).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY_SINGLE_ACTION) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()); verify(actionMapper, times(1)).toActions(any()); verify(actionAuthorizationService, times(1)).updateEntities(any()); @@ -102,15 +116,17 @@ void updateSuccessfulOnlyOneAction() throws Exception { @Test void shouldDeleteAction() throws Exception { mvc.perform(delete("/api/v2/action/1").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status() + .isOk()); } @Test void throwExceptionWhenActionWithIdCantBeFoundWhileDeleting() throws Exception { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Action not found")).when(actionAuthorizationService) - .deleteActionByActionId(anyLong()); + .deleteActionByActionId(anyLong()); mvc.perform(delete("/api/v2/action/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java index c0372930db..0f18c9b75c 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java @@ -1,9 +1,14 @@ package ch.puzzle.okr.controller; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import ch.puzzle.okr.mapper.AlignmentSelectionMapper; import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; import ch.puzzle.okr.service.business.AlignmentSelectionBusinessService; + import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; @@ -19,10 +24,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import static org.mockito.ArgumentMatchers.any; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -39,22 +40,47 @@ class AlignmentControllerIT { private AlignmentSelectionMapper alignmentSelectionMapper; static String alignmentObjectiveName = "Objective 5"; - static List alignmentSelectionPuzzle = List.of( - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(1L, 20L)) - .withObjectiveTitle("Objective 1").withKeyResultTitle("KeyResult 20").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(1L, 40L)) - .withObjectiveTitle("Objective 1").withKeyResultTitle("KeyResult 40").build()); - static List alignmentSelectionOKR = List.of( - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 21L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 21").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 41L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 41").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 61L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 61").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 81L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 81").build()); + static List alignmentSelectionPuzzle = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(1L, + 20L)) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("KeyResult 20") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(1L, + 40L)) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("KeyResult 40") + .build()); + static List alignmentSelectionOKR = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 21L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 21") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 41L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 41") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 61L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 61") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 81L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 81") + .build()); static AlignmentSelection alignmentSelectionEmptyKeyResults = AlignmentSelection.Builder.builder() - .withAlignmentSelectionId(AlignmentSelectionId.of(8L, null)).withObjectiveTitle("Objective 8").build(); + .withAlignmentSelectionId(AlignmentSelectionId.of(8L, + null)) + .withObjectiveTitle("Objective 8") + .build(); @Test void shouldGetAllObjectivesWithKeyResults() throws Exception { @@ -63,35 +89,45 @@ void shouldGetAllObjectivesWithKeyResults() throws Exception { alignmentSelections.addAll(alignmentSelectionOKR); alignmentSelections.add(alignmentSelectionEmptyKeyResults); BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) - .willReturn(alignmentSelections); + .willReturn(alignmentSelections); mvc.perform(get("/api/v2/alignments/selections?quarter=2&team=4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(3))) - .andExpect(jsonPath("$[0].id", Is.is(1))).andExpect(jsonPath("$[0].keyResults[0].id", Is.is(20))) - .andExpect(jsonPath("$[0].keyResults[1].id", Is.is(40))).andExpect(jsonPath("$[1].id", Is.is(5))) - .andExpect(jsonPath("$[1].keyResults[0].id", Is.is(21))) - .andExpect(jsonPath("$[1].keyResults[1].id", Is.is(41))) - .andExpect(jsonPath("$[1].keyResults[2].id", Is.is(61))) - .andExpect(jsonPath("$[1].keyResults[3].id", Is.is(81))).andExpect(jsonPath("$[2].id", Is.is(8))) - .andExpect(jsonPath("$[2].keyResults.size()", Is.is(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(3))) + .andExpect(jsonPath("$[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].keyResults[0].id", Is.is(20))) + .andExpect(jsonPath("$[0].keyResults[1].id", Is.is(40))) + .andExpect(jsonPath("$[1].id", Is.is(5))) + .andExpect(jsonPath("$[1].keyResults[0].id", Is.is(21))) + .andExpect(jsonPath("$[1].keyResults[1].id", Is.is(41))) + .andExpect(jsonPath("$[1].keyResults[2].id", Is.is(61))) + .andExpect(jsonPath("$[1].keyResults[3].id", Is.is(81))) + .andExpect(jsonPath("$[2].id", Is.is(8))) + .andExpect(jsonPath("$[2].keyResults.size()", Is.is(0))); } @Test void shouldGetAllObjectivesWithKeyResultsIfAllObjectivesFiltered() throws Exception { BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(any(), any())) - .willReturn(Collections.emptyList()); + .willReturn(Collections.emptyList()); mvc.perform(get("/api/v2/alignments/selections").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnObjectiveWithEmptyKeyResultListWhenNoKeyResultsInFilteredQuarter() throws Exception { BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) - .willReturn(List.of(alignmentSelectionEmptyKeyResults)); + .willReturn(List.of(alignmentSelectionEmptyKeyResults)); mvc.perform(get("/api/v2/alignments/selections?quarter=2&team=4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(1))) - .andExpect(jsonPath("$[0].id", Is.is(8))).andExpect(jsonPath("$[0].keyResults.size()", Is.is(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(1))) + .andExpect(jsonPath("$[0].id", Is.is(8))) + .andExpect(jsonPath("$[0].keyResults.size()", Is.is(0))); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java index 6fbe6bc0be..bc9c9500ab 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.controller; import ch.puzzle.okr.service.CacheService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @@ -27,16 +28,17 @@ class CacheControllerIT { @Test void shouldEmptyAuthorisationUsersCache() throws Exception { - mvc.perform( - post("/api/v2/caches/emptyAuthorizationUsersCache").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + mvc.perform(post("/api/v2/caches/emptyAuthorizationUsersCache").with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()); verify(cacheService, times(1)).emptyAuthorizationUsersCache(); } @Test void shouldEmptyAllCaches() throws Exception { mvc.perform(post("/api/v2/caches/emptyAllCaches").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()); verify(cacheService, times(1)).emptyAllCaches(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java index cbb63560fb..b0afea8715 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java @@ -1,12 +1,15 @@ package ch.puzzle.okr.controller; +import java.time.LocalDateTime; + import ch.puzzle.okr.mapper.checkin.CheckInMapper; import ch.puzzle.okr.models.checkin.Zone; +import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; -import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.authorization.CheckInAuthorizationService; import ch.puzzle.okr.service.business.KeyResultBusinessService; + import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -25,8 +28,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; - import static ch.puzzle.okr.test.CheckInTestHelpers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; @@ -48,117 +49,155 @@ class CheckInControllerIT { @BeforeEach void setUp() { - BDDMockito.given(checkInMapper.toDto(checkInMetric)).willReturn(checkInMetricDto); - BDDMockito.given(checkInMapper.toDto(checkInOrdinal)).willReturn(checkInOrdinalDto); + BDDMockito.given(checkInMapper.toDto(checkInMetric)) + .willReturn(checkInMetricDto); + BDDMockito.given(checkInMapper.toDto(checkInOrdinal)) + .willReturn(checkInOrdinalDto); } @Test void shouldGetMetricCheckInWithId() throws Exception { - BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())).willReturn(checkInMetric); + BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())) + .willReturn(checkInMetric); mvc.perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_INITIATIVES, Is.is(INITIATIVES_1))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_INITIATIVES, Is.is(INITIATIVES_1))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); } @Test void shouldGetOrdinalCheckInWithId() throws Exception { - BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())).willReturn(checkInOrdinal); + BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())) + .willReturn(checkInOrdinal); mvc.perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) - .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) + .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); } @Test void shouldNotFindTheCheckInWithId() throws Exception { BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); mvc.perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldReturnUpdatedCheckIn() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); - BDDMockito.given(checkInAuthorizationService.updateEntity(anyLong(), any())).willReturn(checkInMetric); - BDDMockito.given(checkInMapper.toCheckIn(any())).willReturn(checkInMetric); + .willReturn(KeyResultMetric.Builder.builder() + .withId(1L) + .build()); + BDDMockito.given(checkInAuthorizationService.updateEntity(anyLong(), any())) + .willReturn(checkInMetric); + BDDMockito.given(checkInMapper.toCheckIn(any())) + .willReturn(checkInMetric); mvc.perform(put(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))); } @Test void shouldReturnNotFound() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); - BDDMockito.given(checkInMapper.toCheckIn(any())).willReturn(checkInMetric); + .willReturn(KeyResultMetric.Builder.builder() + .withId(1L) + .build()); + BDDMockito.given(checkInMapper.toCheckIn(any())) + .willReturn(checkInMetric); BDDMockito.given(checkInAuthorizationService.updateEntity(anyLong(), any())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found")); mvc.perform(put(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldCreateKeyResultMetric() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); - BDDMockito.given(checkInAuthorizationService.createEntity(any())).willReturn(checkInMetric); + .willReturn(KeyResultMetric.Builder.builder() + .withId(1L) + .build()); + BDDMockito.given(checkInAuthorizationService.createEntity(any())) + .willReturn(checkInMetric); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); } @Test void shouldCreateKeyResultOrdinal() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultOrdinal.Builder.builder().withId(1L).build()); - BDDMockito.given(checkInAuthorizationService.createEntity(any())).willReturn(checkInOrdinal); + .willReturn(KeyResultOrdinal.Builder.builder() + .withId(1L) + .build()); + BDDMockito.given(checkInAuthorizationService.createEntity(any())) + .willReturn(checkInOrdinal); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) - .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_2))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) - .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) + .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_2))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) + .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); } @Test void shouldThrowExceptionWhenKeyResultIdMissing() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); - BDDMockito.given(checkInAuthorizationService.createEntity(any())).willReturn(checkInOrdinal); + .willReturn(KeyResultMetric.Builder.builder() + .withId(1L) + .build()); + BDDMockito.given(checkInAuthorizationService.createEntity(any())) + .willReturn(checkInOrdinal); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON_WITHOUT_KEY_RESULT_ID)) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON_WITHOUT_KEY_RESULT_ID)) + .andExpect(MockMvcResultMatchers.status() + .is4xxClientError()); } @DisplayName("Should return client error for KeyResult not of type metric or ordinal") @@ -168,16 +207,19 @@ class NonMetricOrOrdinalKeyResult extends KeyResult { } BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(new NonMetricOrOrdinalKeyResult()); + .willReturn(new NonMetricOrOrdinalKeyResult()); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status() + .is4xxClientError()); } @Test void shouldDeleteCheckInById() throws Exception { mvc.perform(delete(CHECK_IN_5_URL).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status() + .isOk()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java index e6b5244a6b..03e3928b5d 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java @@ -1,7 +1,10 @@ package ch.puzzle.okr.controller; +import java.util.Map; + import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.service.clientconfig.ClientConfigService; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -15,8 +18,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.util.Map; - import static ch.puzzle.okr.controller.OverviewControllerIT.JSON_PATH_ROOT; import static org.mockito.ArgumentMatchers.anyString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -34,27 +35,36 @@ public class ClientConfigControllerIT { @Test void shouldGetClientConfig() throws Exception { - BDDMockito.given(configService.getConfigBasedOnActiveEnv(anyString())).willReturn(createClientConfigDto()); + BDDMockito.given(configService.getConfigBasedOnActiveEnv(anyString())) + .willReturn(createClientConfigDto()); mvc.perform(get("/config").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.aMapWithSize(9))) - .andExpect(jsonPath("$.activeProfile", Matchers.is("Active_Profile"))) - .andExpect(jsonPath("$.issuer", Matchers.is("Issuer"))) - .andExpect(jsonPath("$.clientId", Matchers.is("Client_Id"))) - .andExpect(jsonPath("$.favicon", Matchers.is("Favicon"))) - .andExpect(jsonPath("$.logo", Matchers.is("Logo"))) - .andExpect(jsonPath("$.triangles", Matchers.is("Triangles"))) - .andExpect(jsonPath("$.backgroundLogo", Matchers.is("Background_Logo"))) - .andExpect(jsonPath("$.title", Matchers.is("Title"))) - .andExpect(jsonPath("$.customStyles.font-family", Matchers.is("verdana"))) - .andExpect(jsonPath("$.customStyles.font-size", Matchers.is("20px"))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.aMapWithSize(9))) + .andExpect(jsonPath("$.activeProfile", Matchers.is("Active_Profile"))) + .andExpect(jsonPath("$.issuer", Matchers.is("Issuer"))) + .andExpect(jsonPath("$.clientId", Matchers.is("Client_Id"))) + .andExpect(jsonPath("$.favicon", Matchers.is("Favicon"))) + .andExpect(jsonPath("$.logo", Matchers.is("Logo"))) + .andExpect(jsonPath("$.triangles", Matchers.is("Triangles"))) + .andExpect(jsonPath("$.backgroundLogo", Matchers.is("Background_Logo"))) + .andExpect(jsonPath("$.title", Matchers.is("Title"))) + .andExpect(jsonPath("$.customStyles.font-family", Matchers.is("verdana"))) + .andExpect(jsonPath("$.customStyles.font-size", Matchers.is("20px"))); } private ClientConfigDto createClientConfigDto() { Map customStyles = Map.of("font-family", "verdana", "font-size", "20px"); - return new ClientConfigDto("Active_Profile", "Issuer", "Client_Id", "Favicon", "Logo", "Triangles", - "Background_Logo", "Title", customStyles); + return new ClientConfigDto("Active_Profile", + "Issuer", + "Client_Id", + "Favicon", + "Logo", + "Triangles", + "Background_Logo", + "Title", + customStyles); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java index d172d16d2f..62eaa68acc 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java @@ -5,6 +5,7 @@ import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.service.authorization.CompletedAuthorizationService; + import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,56 +36,74 @@ @WebMvcTest(CompletedController.class) class CompletedControllerIT { public static final String SUCCESSFUL_CREATE_BODY = """ - { - "id":null, - "objectiveId":3, - "comment":"Wir haben es gut geschafft" - } - """; + { + "id":null, + "objectiveId":3, + "comment":"Wir haben es gut geschafft" + } + """; @MockBean CompletedAuthorizationService completedAuthorizationService; @MockBean private CompletedMapper completedMapper; private static final String WELL_DONE = "Wir haben es gut geschafft"; - Completed successfulCompleted = Completed.Builder.builder().withId(1L) - .withObjective(Objective.Builder.builder().withId(3L).withTitle("Gute Lernende").build()) - .withComment(WELL_DONE).build(); + Completed successfulCompleted = Completed.Builder.builder() + .withId(1L) + .withObjective(Objective.Builder.builder() + .withId(3L) + .withTitle("Gute Lernende") + .build()) + .withComment(WELL_DONE) + .build(); CompletedDto completedDto = new CompletedDto(22L, - Objective.Builder.builder().withId(3L).withTitle("Gute Lernende").build(), WELL_DONE); + Objective.Builder.builder() + .withId(3L) + .withTitle("Gute Lernende") + .build(), + WELL_DONE); String baseUrl = "/api/v2/completed"; @Autowired private MockMvc mvc; @BeforeEach void setUp() { - BDDMockito.given(completedMapper.toDto(any())).willReturn(completedDto); - BDDMockito.given(completedMapper.toCompleted(any())).willReturn(successfulCompleted); + BDDMockito.given(completedMapper.toDto(any())) + .willReturn(completedDto); + BDDMockito.given(completedMapper.toCompleted(any())) + .willReturn(successfulCompleted); } @Test void createSuccessfulCompleted() throws Exception { - BDDMockito.given(this.completedAuthorizationService.createCompleted(any())).willReturn(successfulCompleted); + BDDMockito.given(this.completedAuthorizationService.createCompleted(any())) + .willReturn(successfulCompleted); - mvc.perform(post(baseUrl).content(SUCCESSFUL_CREATE_BODY).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) - .andExpect(jsonPath(JSON_PATH_ID, Is.is(22))).andExpect(jsonPath("$.objective.id", Is.is(3))) - .andExpect(jsonPath("$.comment", Is.is(WELL_DONE))); + mvc.perform(post(baseUrl).content(SUCCESSFUL_CREATE_BODY) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(22))) + .andExpect(jsonPath("$.objective.id", Is.is(3))) + .andExpect(jsonPath("$.comment", Is.is(WELL_DONE))); } @Test void shouldDeleteCompleted() throws Exception { mvc.perform(delete("/api/v2/completed/1").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status() + .isOk()); } @Test void throwExceptionWhenCompletedWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Completed not found")) - .when(completedAuthorizationService).deleteCompletedByObjectiveId(anyLong()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Completed not found")).when( + completedAuthorizationService) + .deleteCompletedByObjectiveId(anyLong()); mvc.perform(delete("/api/v2/completed/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java index ae97be5da3..428760a4e1 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.controller; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.mapper.checkin.CheckInMapper; import ch.puzzle.okr.mapper.keyresult.KeyResultMapper; @@ -10,6 +14,7 @@ import ch.puzzle.okr.service.authorization.KeyResultAuthorizationService; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.persistence.UserPersistenceService; + import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; @@ -28,10 +33,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; import static ch.puzzle.okr.test.KeyResultTestHelpers.*; @@ -66,116 +67,146 @@ class KeyResultControllerIT { @BeforeEach void setUp() { - BDDMockito.given(checkInMapper.toDto(checkIn1)).willReturn(checkInDto1); - BDDMockito.given(checkInMapper.toDto(checkIn2)).willReturn(checkInDto2); + BDDMockito.given(checkInMapper.toDto(checkIn1)) + .willReturn(checkInDto1); + BDDMockito.given(checkInMapper.toDto(checkIn2)) + .willReturn(checkInDto2); } @Test void shouldGetMetricKeyResultWithId() throws Exception { - BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())).willReturn(metricKeyResult); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); + BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())) + .willReturn(metricKeyResult); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultMetricDto); mvc.perform(get(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))); } @Test void shouldGetOrdinalKeyResultWithId() throws Exception { - BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())).willReturn(ordinalKeyResult); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultOrdinalDto); + BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())) + .willReturn(ordinalKeyResult); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultOrdinalDto); mvc.perform(get(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_LABEL, Is.is(QUARTER_LABEL))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_LABEL, Is.is(QUARTER_LABEL))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))); } @Test void shouldNotFindTheKeyResultWithGivenId() throws Exception { BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 55 not found")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 55 not found")); mvc.perform(get(URL_TO_KEY_RESULT_55).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()).andExpect(status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()) + .andExpect(status().isNotFound()); } @Test void shouldReturnCheckInsFromKeyResult() throws Exception { List checkInList = Arrays.asList(checkIn1, checkIn2); - BDDMockito.given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())).willReturn(checkInList); - BDDMockito.given(checkInMapper.toDto(checkIn1)).willReturn(checkInDto1); - BDDMockito.given(checkInMapper.toDto(checkIn2)).willReturn(checkInDto2); + BDDMockito.given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) + .willReturn(checkInList); + BDDMockito.given(checkInMapper.toDto(checkIn1)) + .willReturn(checkInDto1); + BDDMockito.given(checkInMapper.toDto(checkIn2)) + .willReturn(checkInDto2); mvc.perform(get(URL_TO_KEY_RESULT_5_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(2))) - .andExpect(jsonPath("$[0].id", Is.is(1))).andExpect(jsonPath("$[0].value", Is.is(23.0))) - .andExpect(jsonPath("$[0].keyResultId", Is.is(5))) - .andExpect(jsonPath("$[0].changeInfo", Is.is("Changeinfo1"))) - .andExpect(jsonPath("$[0].initiatives", Is.is("Initiatives1"))).andExpect(jsonPath("$[1].id", Is.is(4))) - .andExpect(jsonPath("$[1].value", Is.is(12.0))).andExpect(jsonPath("$[1].keyResultId", Is.is(5))) - .andExpect(jsonPath("$[1].changeInfo", Is.is("Changeinfo2"))) - .andExpect(jsonPath("$[1].initiatives", Is.is("Initiatives2"))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(2))) + .andExpect(jsonPath("$[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].value", Is.is(23.0))) + .andExpect(jsonPath("$[0].keyResultId", Is.is(5))) + .andExpect(jsonPath("$[0].changeInfo", Is.is("Changeinfo1"))) + .andExpect(jsonPath("$[0].initiatives", Is.is("Initiatives1"))) + .andExpect(jsonPath("$[1].id", Is.is(4))) + .andExpect(jsonPath("$[1].value", Is.is(12.0))) + .andExpect(jsonPath("$[1].keyResultId", Is.is(5))) + .andExpect(jsonPath("$[1].changeInfo", Is.is("Changeinfo2"))) + .andExpect(jsonPath("$[1].initiatives", Is.is("Initiatives2"))); } @Test void shouldGetAllCheckInsIfNoCheckInExistsInKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) - .willReturn(Collections.emptyList()); + .willReturn(Collections.emptyList()); mvc.perform(get(URL_TO_KEY_RESULT_1_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnErrorWhenKeyResultDoesntExistWhenGettingCheckInsFromKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 1 not found")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 1 not found")); mvc.perform(get(URL_TO_KEY_RESULT_1_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()).andExpect(status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()) + .andExpect(status().isNotFound()); } @Test void createMetricKeyResult() throws Exception { - BDDMockito.given(keyResultAuthorizationService.createEntity(any())).willReturn(metricKeyResult); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); - BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(metricKeyResult); - - mvc.perform(post(URL_BASE).content(CREATE_BODY_METRIC).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) - .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); + BDDMockito.given(keyResultAuthorizationService.createEntity(any())) + .willReturn(metricKeyResult); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultMetricDto); + BDDMockito.given(keyResultMapper.toKeyResult(any())) + .willReturn(metricKeyResult); + + mvc.perform(post(URL_BASE).content(CREATE_BODY_METRIC) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) + .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(actionAuthorizationService, times(1)).createEntities(List.of()); @@ -183,23 +214,29 @@ void createMetricKeyResult() throws Exception { @Test void createOrdinalKeyResult() throws Exception { - BDDMockito.given(keyResultAuthorizationService.createEntity(any())).willReturn(ordinalKeyResult); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultOrdinalDto); - BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(ordinalKeyResult); - - mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); + BDDMockito.given(keyResultAuthorizationService.createEntity(any())) + .willReturn(ordinalKeyResult); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultOrdinalDto); + BDDMockito.given(keyResultMapper.toKeyResult(any())) + .willReturn(ordinalKeyResult); + + mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(actionAuthorizationService, times(1)).createEntities(List.of()); @@ -207,32 +244,50 @@ void createOrdinalKeyResult() throws Exception { @Test void shouldCreateActionsWhenCreatingKeyResult() throws Exception { - Action action1 = Action.Builder.builder().withVersion(1).withAction("Neue Katze").withPriority(0) - .withKeyResult(ordinalKeyResult).withIsChecked(false).build(); - Action action2 = Action.Builder.builder().withVersion(1).withAction("Neuer Hund").withPriority(1) - .withKeyResult(ordinalKeyResult).withIsChecked(false).build(); + Action action1 = Action.Builder.builder() + .withVersion(1) + .withAction("Neue Katze") + .withPriority(0) + .withKeyResult(ordinalKeyResult) + .withIsChecked(false) + .build(); + Action action2 = Action.Builder.builder() + .withVersion(1) + .withAction("Neuer Hund") + .withPriority(1) + .withKeyResult(ordinalKeyResult) + .withIsChecked(false) + .build(); action1.setWriteable(false); action2.setWriteable(false); List actionList = List.of(action1, action2); - BDDMockito.given(keyResultAuthorizationService.createEntity(any())).willReturn(ordinalKeyResult); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultOrdinalDto); - BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(ordinalKeyResult); - BDDMockito.given(actionAuthorizationService.createEntities(actionList)).willReturn(actionList); - BDDMockito.given(actionMapper.toActions(anyList(), any())).willReturn(actionList); - - mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL_ACTION_LIST).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); + BDDMockito.given(keyResultAuthorizationService.createEntity(any())) + .willReturn(ordinalKeyResult); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultOrdinalDto); + BDDMockito.given(keyResultMapper.toKeyResult(any())) + .willReturn(ordinalKeyResult); + BDDMockito.given(actionAuthorizationService.createEntities(actionList)) + .willReturn(actionList); + BDDMockito.given(actionMapper.toActions(anyList(), any())) + .willReturn(actionList); + + mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL_ACTION_LIST) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(actionAuthorizationService, times(1)).createEntities(actionList); @@ -240,71 +295,91 @@ void shouldCreateActionsWhenCreatingKeyResult() throws Exception { @Test void shouldThrowExceptionWhenKeyResultTypeMissing() throws Exception { - mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_MISSING).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_MISSING) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is4xxClientError()); } @Test void shouldThrowExceptionWhenKeyResultTypeUnknown() throws Exception { - mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_UNKNOWN).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_UNKNOWN) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is4xxClientError()); } @Test void createEntityWithEnumKeys() throws Exception { - BDDMockito.given(keyResultAuthorizationService.createEntity(any())).willReturn(ordinalKeyResult); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultOrdinalDto); - BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(ordinalKeyResult); - - mvc.perform(post(URL_BASE).content(CREATE_BODY_WITH_ENUM_KEYS).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))); + BDDMockito.given(keyResultAuthorizationService.createEntity(any())) + .willReturn(ordinalKeyResult); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultOrdinalDto); + BDDMockito.given(keyResultMapper.toKeyResult(any())) + .willReturn(ordinalKeyResult); + + mvc.perform(post(URL_BASE).content(CREATE_BODY_WITH_ENUM_KEYS) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))); } @Test void createEntityShouldThrowErrorWhenInvalidDto() throws Exception { BDDMockito.given(keyResultMapper.toKeyResult(any())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Error")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Error")); - mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldReturnUpdatedKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) - .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); - BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(metricKeyResult); - BDDMockito.given(keyResultAuthorizationService.isImUsed(any(), any())).willReturn(false); + .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultMetricDto); + BDDMockito.given(keyResultMapper.toKeyResult(any())) + .willReturn(metricKeyResult); + BDDMockito.given(keyResultAuthorizationService.isImUsed(any(), any())) + .willReturn(false); BDDMockito.given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) - .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); - BDDMockito.given(actionAuthorizationService.getActionsByKeyResult(any())).willReturn(anyList()); + .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); + BDDMockito.given(actionAuthorizationService.getActionsByKeyResult(any())) + .willReturn(anyList()); mvc.perform(put(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))).andReturn(); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andReturn(); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(keyResultAuthorizationService, times(1)).updateEntities(anyLong(), any(), anyList()); @@ -313,22 +388,29 @@ void shouldReturnUpdatedKeyResult() throws Exception { @Test void shouldReturnUpdatedKeyResultWithImUsed() throws Exception { BDDMockito.given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) - .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); - BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); - BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(metricKeyResult); - BDDMockito.given(keyResultAuthorizationService.isImUsed(any(), any())).willReturn(true); + .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); + BDDMockito.given(keyResultMapper.toDto(any(), anyList())) + .willReturn(keyResultMetricDto); + BDDMockito.given(keyResultMapper.toKeyResult(any())) + .willReturn(metricKeyResult); + BDDMockito.given(keyResultAuthorizationService.isImUsed(any(), any())) + .willReturn(true); mvc.perform(put(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isImUsed()).andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))).andReturn(); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status() + .isImUsed()) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andReturn(); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(keyResultAuthorizationService, times(1)).updateEntities(anyLong(), any(), anyList()); @@ -336,35 +418,45 @@ void shouldReturnUpdatedKeyResultWithImUsed() throws Exception { @Test void shouldReturnNotFoundWhenUpdatingKeyResult() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Keyresult not found")) - .when(keyResultAuthorizationService).updateEntities(any(), any(), anyList()); - - mvc.perform(put(URL_TO_KEY_RESULT_1000).content(PUT_BODY_METRIC).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Keyresult not found")).when( + keyResultAuthorizationService) + .updateEntities(any(), + any(), + anyList()); + + mvc.perform(put(URL_TO_KEY_RESULT_1000).content(PUT_BODY_METRIC) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldReturnBadRequestWhenUpdatingKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.updateEntity(any(), any())) - .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Bad request while updating keyresult")); + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Bad request while updating keyresult")); mvc.perform(put(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); } @Test void shouldDeleteKeyResult() throws Exception { mvc.perform(delete(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status() + .isOk()); } @Test void throwExceptionWhenKeyResultWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Keyresult not found")) - .when(keyResultAuthorizationService).deleteEntityById(anyLong()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Keyresult not found")).when( + keyResultAuthorizationService) + .deleteEntityById(anyLong()); mvc.perform(delete(URL_TO_KEY_RESULT_1000).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java index c2d0fde2a8..d7ef11ad98 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java @@ -1,10 +1,13 @@ package ch.puzzle.okr.controller; +import java.time.LocalDateTime; + import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.mapper.ObjectiveMapper; import ch.puzzle.okr.models.*; import ch.puzzle.okr.service.authorization.AuthorizationService; import ch.puzzle.okr.service.authorization.ObjectiveAuthorizationService; + import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -23,9 +26,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDate; -import java.time.LocalDateTime; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; @@ -45,43 +45,81 @@ class ObjectiveControllerIT { private static final String URL_OBJECTIVE_5 = "/api/v2/objectives/5"; private static final String URL_OBJECTIVE_10 = "/api/v2/objectives/10"; private static final String JSON = """ - { - "title": "FullObjective", "ownerId": 1, "ownerFirstname": "Bob", "ownerLastname": "Kaufmann", - "teamId": 1, "teamName": "Team1", "quarterId": 1, "quarterNumber": 3, "quarterYear": 2020, - "description": "This is our description", "progress": 33.3 - } - """; + { + "title": "FullObjective", "ownerId": 1, "ownerFirstname": "Bob", "ownerLastname": "Kaufmann", + "teamId": 1, "teamName": "Team1", "quarterId": 1, "quarterNumber": 3, "quarterYear": 2020, + "description": "This is our description", "progress": 33.3 + } + """; private static final String CREATE_NEW_OBJECTIVE = """ - { - "title": "FullObjective", "ownerId": 1, "teamId": 1, "teamName": "Team1", - "quarterId": 1, "quarterNumber": 3, "quarterYear": 2020, "description": "This is our description" - } - """; + { + "title": "FullObjective", "ownerId": 1, "teamId": 1, "teamName": "Team1", + "quarterId": 1, "quarterNumber": 3, "quarterYear": 2020, "description": "This is our description" + } + """; private static final String CREATE_NEW_OBJECTIVE_WITH_NULL_VALUES = """ - { - "title": null, "ownerId": 1, "ownerFirstname": "Bob", "ownerLastname": "Kaufmann", - "teamId": 1, "teamName": "Team1", "quarterId": 1, "quarterNumber": 3, "quarterYear": 2020, - "description": "This is our description", "progress": 33.3 - } - """; + { + "title": null, "ownerId": 1, "ownerFirstname": "Bob", "ownerLastname": "Kaufmann", + "teamId": 1, "teamName": "Team1", "quarterId": 1, "quarterNumber": 3, "quarterYear": 2020, + "description": "This is our description", "progress": 33.3 + } + """; private static final String RESPONSE_NEW_OBJECTIVE = """ - {"id":null,"version":1,"title":"Program Faster","teamId":1,"quarterId":1,"quarterLabel":"GJ 22/23-Q2","description":"Just be faster","state":"DRAFT","createdOn":null,"modifiedOn":null,"writeable":true}"""; + {"id":null,"version":1,"title":"Program Faster","teamId":1,"quarterId":1,"quarterLabel":"GJ 22/23-Q2","description":"Just be faster","state":"DRAFT","createdOn":null,"modifiedOn":null,"writeable":true}"""; private static final String JSON_PATH_TITLE = "$.title"; - private static final Objective objective1 = Objective.Builder.builder().withId(5L).withTitle(OBJECTIVE_TITLE_1) - .build(); - private static final Objective objective2 = Objective.Builder.builder().withId(7L).withTitle(OBJECTIVE_TITLE_2) - .build(); - private static final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - private static final Team team = Team.Builder.builder().withId(1L).withName("Team1").build(); - private static final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - private static final Objective fullObjective = Objective.Builder.builder().withId(42L).withTitle("FullObjective") - .withCreatedBy(user).withTeam(team).withQuarter(quarter).withDescription(DESCRIPTION) - .withModifiedOn(LocalDateTime.MAX).build(); - private static final ObjectiveDto objective1Dto = new ObjectiveDto(5L, 1, OBJECTIVE_TITLE_1, 1L, 1L, "GJ 22/23-Q2", - DESCRIPTION, State.DRAFT, LocalDateTime.MAX, LocalDateTime.MAX, true); - private static final ObjectiveDto objective2Dto = new ObjectiveDto(7L, 1, OBJECTIVE_TITLE_2, 1L, 1L, "GJ 22/23-Q2", - DESCRIPTION, State.DRAFT, LocalDateTime.MIN, LocalDateTime.MIN, true); + private static final Objective objective1 = Objective.Builder.builder() + .withId(5L) + .withTitle(OBJECTIVE_TITLE_1) + .build(); + private static final Objective objective2 = Objective.Builder.builder() + .withId(7L) + .withTitle(OBJECTIVE_TITLE_2) + .build(); + private static final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + private static final Team team = Team.Builder.builder() + .withId(1L) + .withName("Team1") + .build(); + private static final Quarter quarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .build(); + private static final Objective fullObjective = Objective.Builder.builder() + .withId(42L) + .withTitle("FullObjective") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription(DESCRIPTION) + .withModifiedOn(LocalDateTime.MAX) + .build(); + private static final ObjectiveDto objective1Dto = new ObjectiveDto(5L, + 1, + OBJECTIVE_TITLE_1, + 1L, + 1L, + "GJ 22/23-Q2", + DESCRIPTION, + State.DRAFT, + LocalDateTime.MAX, + LocalDateTime.MAX, + true); + private static final ObjectiveDto objective2Dto = new ObjectiveDto(7L, + 1, + OBJECTIVE_TITLE_2, + 1L, + 1L, + "GJ 22/23-Q2", + DESCRIPTION, + State.DRAFT, + LocalDateTime.MIN, + LocalDateTime.MIN, + true); @Autowired private MockMvc mvc; @@ -94,135 +132,212 @@ class ObjectiveControllerIT { @BeforeEach void setUp() { - BDDMockito.given(objectiveMapper.toDto(objective1)).willReturn(objective1Dto); - BDDMockito.given(objectiveMapper.toDto(objective2)).willReturn(objective2Dto); + BDDMockito.given(objectiveMapper.toDto(objective1)) + .willReturn(objective1Dto); + BDDMockito.given(objectiveMapper.toDto(objective2)) + .willReturn(objective2Dto); } @Test void getObjectiveById() throws Exception { - BDDMockito.given(objectiveAuthorizationService.getEntityById(anyLong())).willReturn(objective1); + BDDMockito.given(objectiveAuthorizationService.getEntityById(anyLong())) + .willReturn(objective1); mvc.perform(get(URL_OBJECTIVE_5).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$.id", Is.is(5))) - .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(OBJECTIVE_TITLE_1))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$.id", Is.is(5))) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(OBJECTIVE_TITLE_1))); } @Test void getObjectiveByIdFail() throws Exception { BDDMockito.given(objectiveAuthorizationService.getEntityById(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); mvc.perform(get(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldReturnObjectiveWhenCreatingNewObjective() throws Exception { - ObjectiveDto testObjective = new ObjectiveDto(null, 1, "Program Faster", 1L, 1L, "GJ 22/23-Q2", - "Just be faster", State.DRAFT, null, null, true); + ObjectiveDto testObjective = new ObjectiveDto(null, + 1, + "Program Faster", + 1L, + 1L, + "GJ 22/23-Q2", + "Just be faster", + State.DRAFT, + null, + null, + true); - BDDMockito.given(objectiveMapper.toDto(any())).willReturn(testObjective); - BDDMockito.given(objectiveAuthorizationService.createEntity(any())).willReturn(fullObjective); + BDDMockito.given(objectiveMapper.toDto(any())) + .willReturn(testObjective); + BDDMockito.given(objectiveAuthorizationService.createEntity(any())) + .willReturn(fullObjective); mvc.perform(post(URL_BASE_OBJECTIVE).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(CREATE_NEW_OBJECTIVE)) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) - .andExpect(MockMvcResultMatchers.content().string(RESPONSE_NEW_OBJECTIVE)); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(CREATE_NEW_OBJECTIVE)) + .andExpect(MockMvcResultMatchers.status() + .is2xxSuccessful()) + .andExpect(MockMvcResultMatchers.content() + .string(RESPONSE_NEW_OBJECTIVE)); verify(objectiveAuthorizationService, times(1)).createEntity(any()); } @Test void shouldReturnResponseStatusExceptionWhenCreatingObjectiveWithNullValues() throws Exception { - BDDMockito.given(objectiveAuthorizationService.createEntity(any())).willThrow( - new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing attribute title when creating objective")); + BDDMockito.given(objectiveAuthorizationService.createEntity(any())) + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Missing attribute title when creating objective")); mvc.perform(post(URL_BASE_OBJECTIVE).contentType(MediaType.APPLICATION_JSON) - .content(CREATE_NEW_OBJECTIVE_WITH_NULL_VALUES).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + .content(CREATE_NEW_OBJECTIVE_WITH_NULL_VALUES) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); } @Test void shouldReturnUpdatedObjective() throws Exception { - ObjectiveDto testObjective = new ObjectiveDto(1L, 1, TITLE, 1L, 1L, "GJ 22/23-Q2", EVERYTHING_FINE_DESCRIPTION, - State.NOTSUCCESSFUL, LocalDateTime.MIN, LocalDateTime.MAX, true); - Objective objective = Objective.Builder.builder().withId(1L).withDescription(EVERYTHING_FINE_DESCRIPTION) - .withTitle(TITLE).build(); - - BDDMockito.given(objectiveMapper.toDto(any())).willReturn(testObjective); - BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willReturn(objective); - BDDMockito.given(objectiveAuthorizationService.isImUsed(any())).willReturn(false); - - mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON).content(JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath("$.id", Is.is(1))) - .andExpect(jsonPath("$.description", Is.is(EVERYTHING_FINE_DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))); + ObjectiveDto testObjective = new ObjectiveDto(1L, + 1, + TITLE, + 1L, + 1L, + "GJ 22/23-Q2", + EVERYTHING_FINE_DESCRIPTION, + State.NOTSUCCESSFUL, + LocalDateTime.MIN, + LocalDateTime.MAX, + true); + Objective objective = Objective.Builder.builder() + .withId(1L) + .withDescription(EVERYTHING_FINE_DESCRIPTION) + .withTitle(TITLE) + .build(); + + BDDMockito.given(objectiveMapper.toDto(any())) + .willReturn(testObjective); + BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())) + .willReturn(objective); + BDDMockito.given(objectiveAuthorizationService.isImUsed(any())) + .willReturn(false); + + mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON) + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$.id", Is.is(1))) + .andExpect(jsonPath("$.description", Is.is(EVERYTHING_FINE_DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))); } @Test void shouldReturnImUsed() throws Exception { - ObjectiveDto testObjectiveDto = new ObjectiveDto(1L, 1, TITLE, 1L, 1L, "GJ 22/23-Q2", - EVERYTHING_FINE_DESCRIPTION, State.SUCCESSFUL, LocalDateTime.MAX, LocalDateTime.MAX, true); - Objective objectiveImUsed = Objective.Builder.builder().withId(1L).withDescription(EVERYTHING_FINE_DESCRIPTION) - .withQuarter(Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build()).withTitle(TITLE) - .build(); - - BDDMockito.given(objectiveMapper.toObjective(any())).willReturn(objectiveImUsed); - BDDMockito.given(objectiveMapper.toDto(any())).willReturn(testObjectiveDto); - BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willReturn(objectiveImUsed); - BDDMockito.given(objectiveAuthorizationService.isImUsed(any())).willReturn(true); - - mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON).content(JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isImUsed()); + ObjectiveDto testObjectiveDto = new ObjectiveDto(1L, + 1, + TITLE, + 1L, + 1L, + "GJ 22/23-Q2", + EVERYTHING_FINE_DESCRIPTION, + State.SUCCESSFUL, + LocalDateTime.MAX, + LocalDateTime.MAX, + true); + Objective objectiveImUsed = Objective.Builder.builder() + .withId(1L) + .withDescription(EVERYTHING_FINE_DESCRIPTION) + .withQuarter(Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .build()) + .withTitle(TITLE) + .build(); + + BDDMockito.given(objectiveMapper.toObjective(any())) + .willReturn(objectiveImUsed); + BDDMockito.given(objectiveMapper.toDto(any())) + .willReturn(testObjectiveDto); + BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())) + .willReturn(objectiveImUsed); + BDDMockito.given(objectiveAuthorizationService.isImUsed(any())) + .willReturn(true); + + mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON) + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isImUsed()); } @Test void shouldReturnNotFound() throws Exception { - BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willThrow( - new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed objective -> Attribut is invalid")); + BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())) + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, + "Failed objective -> Attribut is invalid")); - mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON).content(JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON) + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldReturnBadRequest() throws Exception { - BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willThrow( - new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed objective -> Attribut is invalid")); + BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())) + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Failed objective -> Attribut is invalid")); mvc.perform(put(URL_OBJECTIVE_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); } @Test void shouldDeleteObjective() throws Exception { mvc.perform(delete(URL_OBJECTIVE_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status() + .isOk()); } @Test void throwExceptionWhenObjectiveWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Objective not found")) - .when(objectiveAuthorizationService).deleteEntityById(anyLong()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Objective not found")).when( + objectiveAuthorizationService) + .deleteEntityById(anyLong()); mvc.perform(delete("/api/v2/objectives/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldReturnIsCreatedWhenObjectiveWasDuplicated() throws Exception { - BDDMockito.given(objectiveAuthorizationService.duplicateEntity(anyLong(), any())).willReturn(objective1); - BDDMockito.given(objectiveAuthorizationService.getAuthorizationService()).willReturn(authorizationService); - BDDMockito.given(objectiveMapper.toDto(objective1)).willReturn(objective1Dto); + BDDMockito.given(objectiveAuthorizationService.duplicateEntity(anyLong(), any())) + .willReturn(objective1); + BDDMockito.given(objectiveAuthorizationService.getAuthorizationService()) + .willReturn(authorizationService); + BDDMockito.given(objectiveMapper.toDto(objective1)) + .willReturn(objective1Dto); mvc.perform(post("/api/v2/objectives/{id}", objective1.getId()).contentType(MediaType.APPLICATION_JSON) - .content(JSON).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(jsonPath("$.id", Is.is(objective1Dto.id().intValue()))) - .andExpect(jsonPath("$.description", Is.is(objective1Dto.description()))) - .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(objective1Dto.title()))); + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isCreated()) + .andExpect(jsonPath("$.id", + Is.is(objective1Dto.id() + .intValue()))) + .andExpect(jsonPath("$.description", Is.is(objective1Dto.description()))) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(objective1Dto.title()))); verify(objectiveMapper, times(1)).toObjective(any()); verify(objectiveMapper, times(1)).toDto(any()); diff --git a/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java index 48b57a8ede..599d0abe79 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java @@ -1,9 +1,15 @@ package ch.puzzle.okr.controller; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import ch.puzzle.okr.mapper.OverviewMapper; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.service.authorization.OverviewAuthorizationService; + import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; @@ -19,11 +25,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.models.State.DRAFT; import static ch.puzzle.okr.models.State.ONGOING; @@ -54,37 +55,92 @@ class OverviewControllerIT { public static final String JSON_PATH_TEAM_ID = "$[0].team.id"; public static final String JSON_PATH_ROOT = "$"; - static List overviewPuzzle = List.of( - Overview.Builder.builder().withOverviewId(OverviewId.of(1L, 1L, 20L, 20L)).withTeamName(PUZZLE) - .withObjectiveTitle("Objective 1").withObjectiveState(DRAFT).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(CHF).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build(), - Overview.Builder.builder().withOverviewId(OverviewId.of(1L, 2L, 21L, 41L)).withTeamName(PUZZLE) - .withObjectiveTitle("Objective 1").withObjectiveState(DRAFT).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(EUR).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build()); - static List overviewOKR = List.of( - Overview.Builder.builder().withOverviewId(OverviewId.of(2L, 5L, 20L, 40L)).withTeamName("OKR") - .withObjectiveTitle("Objective 5").withObjectiveState(DRAFT).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(CHF).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build(), - Overview.Builder.builder().withOverviewId(OverviewId.of(2L, 7L, 21L, 41L)).withTeamName("OKR") - .withObjectiveTitle("Objective 7").withObjectiveState(ONGOING).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(FTE).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build()); - - static Overview overviewKuchen = Overview.Builder.builder().withOverviewId(OverviewId.of(3L, 8L, 20L, 40L)) - .withTeamName(TEAM_KUCHEN).withObjectiveTitle("Objective 8").withObjectiveState(ONGOING).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION).withKeyResultType(KEY_RESULT_TYPE_METRIC) - .withUnit(EUR).withBaseline(5.0).withStretchGoal(20.0).withCheckInValue(15.0).withConfidence(5) - .withCheckInCreatedOn(LocalDateTime.now()).build(); - - static Overview simpleOverview = Overview.Builder.builder().withOverviewId(OverviewId.of(4L, -1L, -1L, -1L)) - .withTeamName(TEAM_KUCHEN).build(); + static List overviewPuzzle = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.of(1L, 1L, 20L, 20L)) + .withTeamName(PUZZLE) + .withObjectiveTitle("Objective 1") + .withObjectiveState(DRAFT) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(CHF) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.of(1L, 2L, 21L, 41L)) + .withTeamName(PUZZLE) + .withObjectiveTitle("Objective 1") + .withObjectiveState(DRAFT) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(EUR) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build()); + static List overviewOKR = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.of(2L, 5L, 20L, 40L)) + .withTeamName("OKR") + .withObjectiveTitle("Objective 5") + .withObjectiveState(DRAFT) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(CHF) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.of(2L, 7L, 21L, 41L)) + .withTeamName("OKR") + .withObjectiveTitle("Objective 7") + .withObjectiveState(ONGOING) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(FTE) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build()); + + static Overview overviewKuchen = Overview.Builder.builder() + .withOverviewId(OverviewId.of(3L, 8L, 20L, 40L)) + .withTeamName(TEAM_KUCHEN) + .withObjectiveTitle("Objective 8") + .withObjectiveState(ONGOING) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(EUR) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build(); + + static Overview simpleOverview = Overview.Builder.builder() + .withOverviewId(OverviewId.of(4L, -1L, -1L, -1L)) + .withTeamName(TEAM_KUCHEN) + .build(); @Test void shouldGetAllTeamsWithObjective() throws Exception { @@ -93,32 +149,38 @@ void shouldGetAllTeamsWithObjective() throws Exception { overviews.addAll(overviewOKR); overviews.add(overviewKuchen); BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(overviews); - BDDMockito.given(overviewAuthorizationService.hasWriteAllAccess()).willReturn(true); + .willReturn(overviews); + BDDMockito.given(overviewAuthorizationService.hasWriteAllAccess()) + .willReturn(true); mvc.perform(get("/api/v2/overview?quarter=2&team=1,2,3,4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(3))) - .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) - .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) - .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))).andExpect(jsonPath("$[1].team.id", Is.is(2))) - .andExpect(jsonPath("$[1].team.name", Is.is("OKR"))) - .andExpect(jsonPath("$[1].objectives[0].id", Is.is(5))) - .andExpect(jsonPath("$[1].objectives[1].id", Is.is(7))).andExpect(jsonPath("$[2].team.id", Is.is(3))) - .andExpect(jsonPath("$[2].team.name", Is.is(TEAM_KUCHEN))) - .andExpect(jsonPath("$[2].objectives[0].id", Is.is(8))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(3))) + .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) + .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))) + .andExpect(jsonPath("$[1].team.id", Is.is(2))) + .andExpect(jsonPath("$[1].team.name", Is.is("OKR"))) + .andExpect(jsonPath("$[1].objectives[0].id", Is.is(5))) + .andExpect(jsonPath("$[1].objectives[1].id", Is.is(7))) + .andExpect(jsonPath("$[2].team.id", Is.is(3))) + .andExpect(jsonPath("$[2].team.name", Is.is(TEAM_KUCHEN))) + .andExpect(jsonPath("$[2].objectives[0].id", Is.is(8))); } @Test void shouldGetAllTeamsWithObjectiveIfNoTeamsExists() throws Exception { BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(Collections.emptyList()); - BDDMockito.given(overviewAuthorizationService.hasWriteAllAccess()).willReturn(true); + .willReturn(Collections.emptyList()); + BDDMockito.given(overviewAuthorizationService.hasWriteAllAccess()) + .willReturn(true); mvc.perform(get("/api/v2/overview").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(0))); } @Test @@ -126,29 +188,32 @@ void shouldReturnOnlyFilteredObjectivesByQuarterAndTeam() throws Exception { List overviews = new ArrayList<>(overviewPuzzle); overviews.add(overviewKuchen); BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(overviews); + .willReturn(overviews); mvc.perform(get("/api/v2/overview?quarter=2&team=1,3").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(2))) - .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) - .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) - .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))).andExpect(jsonPath("$[1].team.id", Is.is(3))) - .andExpect(jsonPath("$[1].team.name", Is.is(TEAM_KUCHEN))) - .andExpect(jsonPath("$[1].objectives[0].id", Is.is(8))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(2))) + .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) + .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))) + .andExpect(jsonPath("$[1].team.id", Is.is(3))) + .andExpect(jsonPath("$[1].team.name", Is.is(TEAM_KUCHEN))) + .andExpect(jsonPath("$[1].objectives[0].id", Is.is(8))); } @Test void shouldReturnTeamWithEmptyObjectiveListWhenNoObjectiveInFilteredQuarter() throws Exception { BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(List.of(simpleOverview)); + .willReturn(List.of(simpleOverview)); mvc.perform(get("/api/v2/overview?quarter=2&team=4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(1))) - .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(4))) - .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(TEAM_KUCHEN))) - .andExpect(jsonPath("$[0].objectives.size()", Is.is(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(1))) + .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(4))) + .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(TEAM_KUCHEN))) + .andExpect(jsonPath("$[0].objectives.size()", Is.is(0))); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java index 5a582cd117..ca4c8533c6 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java @@ -1,7 +1,13 @@ package ch.puzzle.okr.controller; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.business.QuarterBusinessService; + import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; @@ -17,11 +23,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -32,12 +33,24 @@ @WebMvcTest(QuarterController.class) class QuarterControllerIT { - static Quarter quarter1 = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2") - .withStartDate(LocalDate.of(2022, 9, 1)).withEndDate(LocalDate.of(2022, 12, 31)).build(); - static Quarter quarter2 = Quarter.Builder.builder().withId(2L).withLabel("GJ 22/23-Q3") - .withStartDate(LocalDate.of(2023, 1, 1)).withEndDate(LocalDate.of(2023, 3, 31)).build(); - static Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID) - .withLabel(BACK_LOG_QUARTER_LABEL).withStartDate(null).withEndDate(null).build(); + static Quarter quarter1 = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .withStartDate(LocalDate.of(2022, 9, 1)) + .withEndDate(LocalDate.of(2022, 12, 31)) + .build(); + static Quarter quarter2 = Quarter.Builder.builder() + .withId(2L) + .withLabel("GJ 22/23-Q3") + .withStartDate(LocalDate.of(2023, 1, 1)) + .withEndDate(LocalDate.of(2023, 3, 31)) + .build(); + static Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); static List quaterList = Arrays.asList(quarter1, quarter2, backlogQuarter); @Autowired @@ -47,32 +60,49 @@ class QuarterControllerIT { @Test void shouldGetAllQuarters() throws Exception { - BDDMockito.given(quarterBusinessService.getQuarters()).willReturn(quaterList); + BDDMockito.given(quarterBusinessService.getQuarters()) + .willReturn(quaterList); mvc.perform(get("/api/v2/quarters").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(3))) - .andExpect(jsonPath("$[0].id", Is.is(1))).andExpect(jsonPath("$[0].label", Is.is("GJ 22/23-Q2"))) - .andExpect(jsonPath("$[0].startDate", Is.is(LocalDate.of(2022, 9, 1).toString()))) - .andExpect(jsonPath("$[0].endDate", Is.is(LocalDate.of(2022, 12, 31).toString()))) - .andExpect(jsonPath("$[1].id", Is.is(2))).andExpect(jsonPath("$[1].label", Is.is("GJ 22/23-Q3"))) - .andExpect(jsonPath("$[1].startDate", Is.is(LocalDate.of(2023, 1, 1).toString()))) - .andExpect(jsonPath("$[1].endDate", Is.is(LocalDate.of(2023, 3, 31).toString()))) - .andExpect(jsonPath("$[2].id", Is.is((int) BACK_LOG_QUARTER_ID))) - .andExpect(jsonPath("$[2].label", Is.is(BACK_LOG_QUARTER_LABEL))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(3))) + .andExpect(jsonPath("$[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].label", Is.is("GJ 22/23-Q2"))) + .andExpect(jsonPath("$[0].startDate", + Is.is(LocalDate.of(2022, 9, 1) + .toString()))) + .andExpect(jsonPath("$[0].endDate", + Is.is(LocalDate.of(2022, 12, 31) + .toString()))) + .andExpect(jsonPath("$[1].id", Is.is(2))) + .andExpect(jsonPath("$[1].label", Is.is("GJ 22/23-Q3"))) + .andExpect(jsonPath("$[1].startDate", + Is.is(LocalDate.of(2023, 1, 1) + .toString()))) + .andExpect(jsonPath("$[1].endDate", + Is.is(LocalDate.of(2023, 3, 31) + .toString()))) + .andExpect(jsonPath("$[2].id", Is.is((int) BACK_LOG_QUARTER_ID))) + .andExpect(jsonPath("$[2].label", Is.is(BACK_LOG_QUARTER_LABEL))); } @Test void shouldGetAllTeamsIfNoTeamsExists() throws Exception { - BDDMockito.given(quarterBusinessService.getQuarters()).willReturn(Collections.emptyList()); + BDDMockito.given(quarterBusinessService.getQuarters()) + .willReturn(Collections.emptyList()); mvc.perform(get("/api/v2/quarters").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldCallCurrentQuarterAfterRequest() throws Exception { mvc.perform(get("/api/v2/quarters/current").contentType(MediaType.APPLICATION_JSON)); - BDDMockito.verify(quarterBusinessService, Mockito.times(1)).getCurrentQuarter(); + BDDMockito.verify(quarterBusinessService, Mockito.times(1)) + .getCurrentQuarter(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java index 999c8cacf1..8f36c23eaf 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java @@ -1,9 +1,14 @@ package ch.puzzle.okr.controller; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.mapper.TeamMapper; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.service.authorization.TeamAuthorizationService; + import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; @@ -22,10 +27,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; @@ -41,34 +42,40 @@ class TeamControllerIT { private static final String URL_TEAM_1 = "/api/v2/teams/1"; public static final String PUZZLE = "Puzzle"; public static final String SUB_URL_USER_5 = "/user/5"; - static Team teamPuzzle = Team.Builder.builder().withId(5L).withName(PUZZLE).build(); - static Team teamOKR = Team.Builder.builder().withId(7L).withName("OKR").build(); + static Team teamPuzzle = Team.Builder.builder() + .withId(5L) + .withName(PUZZLE) + .build(); + static Team teamOKR = Team.Builder.builder() + .withId(7L) + .withName("OKR") + .build(); static List teamList = Arrays.asList(teamPuzzle, teamOKR); static TeamDto teamPuzzleDto = new TeamDto(5L, 3, PUZZLE, false); static TeamDto teamOkrDto = new TeamDto(7L, 4, "OKR", false); private static final String CREATE_NEW_TEAM = """ - { - "id": null, "name": "OKR-Team", "organisations": [] - } - """; + { + "id": null, "name": "OKR-Team", "organisations": [] + } + """; private static final String CREATE_NEW_TEAM_WITH_NULL_VALUES = """ - { - "id": null, "name": null, "organisations": null - } - """; + { + "id": null, "name": null, "organisations": null + } + """; private static final String RESPONSE_NEW_TEAM = """ - {"id":7,"version":4,"name":"OKR","writeable":false}"""; + {"id":7,"version":4,"name":"OKR","writeable":false}"""; private static final String UPDATE_TEAM = """ - { - "id": 1, "name": "OKR-Team", "organisations": [] - } - """; + { + "id": 1, "name": "OKR-Team", "organisations": [] + } + """; private static final String ADD_USERS = """ - [{"id":31,"version":1,"firstname":"Findus","lastname":"Peterson","email":"peterson@puzzle.ch","userTeamList":[{"id":31,"version":1,"team":{"id":8,"version":1,"name":"we are cube.³","isWriteable":false},"isTeamAdmin":true}],"isOkrChampion":false},{"id":41,"version":1,"firstname":"Paco","lastname":"Egiman","email":"egiman@puzzle.ch","userTeamList":[{"id":41,"version":1,"team":{"id":4,"version":1,"name":"/BBT","isWriteable":false},"isTeamAdmin":false}],"isOkrChampion":false}] - """; + [{"id":31,"version":1,"firstname":"Findus","lastname":"Peterson","email":"peterson@puzzle.ch","userTeamList":[{"id":31,"version":1,"team":{"id":8,"version":1,"name":"we are cube.³","isWriteable":false},"isTeamAdmin":true}],"isOkrChampion":false},{"id":41,"version":1,"firstname":"Paco","lastname":"Egiman","email":"egiman@puzzle.ch","userTeamList":[{"id":41,"version":1,"team":{"id":4,"version":1,"name":"/BBT","isWriteable":false},"isTeamAdmin":false}],"isOkrChampion":false}] + """; @Autowired private MockMvc mvc; @@ -79,122 +86,166 @@ class TeamControllerIT { @BeforeEach void setUp() { - BDDMockito.given(teamMapper.toDto(teamPuzzle)).willReturn(teamPuzzleDto); - BDDMockito.given(teamMapper.toDto(teamOKR)).willReturn(teamOkrDto); + BDDMockito.given(teamMapper.toDto(teamPuzzle)) + .willReturn(teamPuzzleDto); + BDDMockito.given(teamMapper.toDto(teamOKR)) + .willReturn(teamOkrDto); } @Test void shouldGetAllTeams() throws Exception { - BDDMockito.given(teamAuthorizationService.getAllTeams()).willReturn(teamList); + BDDMockito.given(teamAuthorizationService.getAllTeams()) + .willReturn(teamList); mvc.perform(get("/api/v2/teams?quarterId=1").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(2))) - .andExpect(jsonPath("$[0].id", Is.is(5))).andExpect(jsonPath("$[0].name", Is.is(PUZZLE))) - .andExpect(jsonPath("$[1].id", Is.is(7))).andExpect(jsonPath("$[1].name", Is.is("OKR"))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(2))) + .andExpect(jsonPath("$[0].id", Is.is(5))) + .andExpect(jsonPath("$[0].name", Is.is(PUZZLE))) + .andExpect(jsonPath("$[1].id", Is.is(7))) + .andExpect(jsonPath("$[1].name", Is.is("OKR"))); } @Test void shouldGetAllTeamsWhenNoQuarterParamIsPassed() throws Exception { - BDDMockito.given(teamAuthorizationService.getAllTeams()).willReturn(teamList); - mvc.perform(get(BASE_URL).contentType(MediaType.APPLICATION_JSON)).andExpectAll(); - BDDMockito.verify(teamMapper).toDto(teamOKR); - BDDMockito.verify(teamMapper).toDto(teamPuzzle); + BDDMockito.given(teamAuthorizationService.getAllTeams()) + .willReturn(teamList); + mvc.perform(get(BASE_URL).contentType(MediaType.APPLICATION_JSON)) + .andExpectAll(); + BDDMockito.verify(teamMapper) + .toDto(teamOKR); + BDDMockito.verify(teamMapper) + .toDto(teamPuzzle); } @Test void shouldGetAllTeamsIfTeamModelIsNull() throws Exception { - BDDMockito.given(teamAuthorizationService.getAllTeams()).willReturn(Collections.emptyList()); + BDDMockito.given(teamAuthorizationService.getAllTeams()) + .willReturn(Collections.emptyList()); mvc.perform(get("/api/v2/teams?quarterId=1").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnCreatedTeam() throws Exception { - BDDMockito.given(teamAuthorizationService.createEntity(any())).willReturn(teamOKR); - - mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON).content(CREATE_NEW_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(MockMvcResultMatchers.content().string(RESPONSE_NEW_TEAM)); + BDDMockito.given(teamAuthorizationService.createEntity(any())) + .willReturn(teamOKR); + + mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON) + .content(CREATE_NEW_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isCreated()) + .andExpect(MockMvcResultMatchers.content() + .string(RESPONSE_NEW_TEAM)); } @Test void shouldReturnResponseStatusExceptionWhenCreatingObjectiveWithNullValues() throws Exception { - BDDMockito.given(teamAuthorizationService.createEntity(any())).willThrow( - new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing attribute name when creating team")); - - mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON).content(CREATE_NEW_TEAM_WITH_NULL_VALUES) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + BDDMockito.given(teamAuthorizationService.createEntity(any())) + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Missing attribute name when creating team")); + + mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON) + .content(CREATE_NEW_TEAM_WITH_NULL_VALUES) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); } @Test void shouldReturnUpdatedTeam() throws Exception { TeamDto teamDto = new TeamDto(1L, 0, "OKR-Team", false); - Team team = Team.Builder.builder().withId(1L).withName("OKR-Team").build(); - - BDDMockito.given(teamMapper.toDto(any())).willReturn(teamDto); - BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())).willReturn(team); + Team team = Team.Builder.builder() + .withId(1L) + .withName("OKR-Team") + .build(); - mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON).content(UPDATE_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath("$.id", Is.is(teamDto.id().intValue()))) - .andExpect(jsonPath("$.version", Is.is(teamDto.version()))) - .andExpect(jsonPath("$.name", Is.is(teamDto.name()))); + BDDMockito.given(teamMapper.toDto(any())) + .willReturn(teamDto); + BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())) + .willReturn(team); + + mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$.id", + Is.is(teamDto.id() + .intValue()))) + .andExpect(jsonPath("$.version", Is.is(teamDto.version()))) + .andExpect(jsonPath("$.name", Is.is(teamDto.name()))); } @Test void shouldReturnNotFound() throws Exception { BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed team -> Attribut is invalid")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed team -> Attribut is invalid")); - mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON).content(UPDATE_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void shouldReturnBadRequest() throws Exception { BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed team -> Attribut is invalid")); + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed team -> Attribut is invalid")); - mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON).content(UPDATE_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); } @Test void shouldDeleteTeam() throws Exception { mvc.perform(delete(URL_TEAM_1).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status() + .isOk()); } @Test void throwExceptionWhenOTeamWithIdCantBeFoundWhileDeleting() throws Exception { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Team not found")).when(teamAuthorizationService) - .deleteEntity(anyLong()); + .deleteEntity(anyLong()); mvc.perform(delete(URL_TEAM_1).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status() + .isNotFound()); } @Test void addUsersToTeam_shouldReturnOk() throws Exception { - mvc.perform(put(URL_TEAM_1 + "/addusers").contentType(MediaType.APPLICATION_JSON).content(ADD_USERS) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()); + mvc.perform(put(URL_TEAM_1 + "/addusers").contentType(MediaType.APPLICATION_JSON) + .content(ADD_USERS) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isOk()); } @Test void removeUserFromTeam_shouldReturnOk() throws Exception { mvc.perform(put(URL_TEAM_1 + SUB_URL_USER_5 + "/removeuser").contentType(MediaType.APPLICATION_JSON) - .content(ADD_USERS).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .content(ADD_USERS) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isOk()); } @Test void updateOrAddTeamMembership_shouldReturnOk() throws Exception { - mvc.perform(put(URL_TEAM_1 + SUB_URL_USER_5 + "/updateaddteammembership/true") - .contentType(MediaType.APPLICATION_JSON).content(ADD_USERS) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()); + mvc.perform(put(URL_TEAM_1 + SUB_URL_USER_5 + "/updateaddteammembership/true").contentType(MediaType.APPLICATION_JSON) + .content(ADD_USERS) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status() + .isOk()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java index 33d0af9aac..8f2f391e7a 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java @@ -1,11 +1,17 @@ package ch.puzzle.okr.controller; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.mapper.UserMapper; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.authorization.AuthorizationService; import ch.puzzle.okr.service.authorization.UserAuthorizationService; + import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; @@ -22,11 +28,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import static ch.puzzle.okr.controller.ActionControllerIT.SUCCESSFUL_UPDATE_BODY; import static org.mockito.ArgumentMatchers.any; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -42,10 +43,18 @@ class UserControllerIT { private static final String FIRSTNAME_2 = "Bob"; private static final String LASTNAME_2 = "Baumeister"; private static final String EMAIL_2 = "baumeister@puzzle.ch"; - static User userAlice = User.Builder.builder().withId(2L).withFirstname(FIRSTNAME_1).withLastname(LASTNAME_1) - .withEmail(EMAIL_1).build(); - static User userBob = User.Builder.builder().withId(9L).withFirstname(FIRSTNAME_2).withLastname(LASTNAME_2) - .withEmail(EMAIL_2).build(); + static User userAlice = User.Builder.builder() + .withId(2L) + .withFirstname(FIRSTNAME_1) + .withLastname(LASTNAME_1) + .withEmail(EMAIL_1) + .build(); + static User userBob = User.Builder.builder() + .withId(9L) + .withFirstname(FIRSTNAME_2) + .withLastname(LASTNAME_2) + .withEmail(EMAIL_2) + .build(); static List userList = Arrays.asList(userAlice, userBob); static UserDto userAliceDto = new UserDto(2L, 3, FIRSTNAME_1, LASTNAME_1, EMAIL_1, new ArrayList<>(), false); static UserDto userBobDto = new UserDto(9L, 4, FIRSTNAME_2, LASTNAME_2, EMAIL_2, new ArrayList<>(), false); @@ -60,107 +69,128 @@ class UserControllerIT { @BeforeEach void setUp() { - BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); - BDDMockito.given(userMapper.toDto(userBob)).willReturn(userBobDto); + BDDMockito.given(userMapper.toDto(userAlice)) + .willReturn(userAliceDto); + BDDMockito.given(userMapper.toDto(userBob)) + .willReturn(userBobDto); } @Test void shouldGetAllUsers() throws Exception { - BDDMockito.given(userAuthorizationService.getAllUsers()).willReturn(userList); + BDDMockito.given(userAuthorizationService.getAllUsers()) + .willReturn(userList); mvc.perform(get("/api/v1/users").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(2))) - .andExpect(jsonPath("$[0].id", Is.is(2))).andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) - .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) - .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))).andExpect(jsonPath("$[1].id", Is.is(9))) - .andExpect(jsonPath("$[1].firstname", Is.is(FIRSTNAME_2))) - .andExpect(jsonPath("$[1].lastname", Is.is(LASTNAME_2))) - .andExpect(jsonPath("$[1].email", Is.is(EMAIL_2))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(2))) + .andExpect(jsonPath("$[0].id", Is.is(2))) + .andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) + .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) + .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))) + .andExpect(jsonPath("$[1].id", Is.is(9))) + .andExpect(jsonPath("$[1].firstname", Is.is(FIRSTNAME_2))) + .andExpect(jsonPath("$[1].lastname", Is.is(LASTNAME_2))) + .andExpect(jsonPath("$[1].email", Is.is(EMAIL_2))); } @Test void shouldGetAllUsersIfNoUserExists() throws Exception { - BDDMockito.given(userAuthorizationService.getAllUsers()).willReturn(Collections.emptyList()); + BDDMockito.given(userAuthorizationService.getAllUsers()) + .willReturn(Collections.emptyList()); mvc.perform(get("/api/v1/users").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnCurrentUser() throws Exception { BDDMockito.given(authorizationService.updateOrAddAuthorizationUser()) - .willReturn(new AuthorizationUser(userAlice)); - BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); + .willReturn(new AuthorizationUser(userAlice)); + BDDMockito.given(userMapper.toDto(userAlice)) + .willReturn(userAliceDto); mvc.perform(get("/api/v1/users/current").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // - .andExpect(jsonPath("$.id", Is.is(2))) // - .andExpect(jsonPath("$.version", Is.is(3))) // - .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) // + .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // + .andExpect(jsonPath("$.id", Is.is(2))) // + .andExpect(jsonPath("$.version", Is.is(3))) // + .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); } @Test void shouldReturnUserById() throws Exception { - BDDMockito.given(userAuthorizationService.getById(2)).willReturn(userAlice); - BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); + BDDMockito.given(userAuthorizationService.getById(2)) + .willReturn(userAlice); + BDDMockito.given(userMapper.toDto(userAlice)) + .willReturn(userAliceDto); mvc.perform(get("/api/v1/users/2").contentType(MediaType.APPLICATION_JSON)) // - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // - .andExpect(jsonPath("$.id", Is.is(2))) // - .andExpect(jsonPath("$.version", Is.is(3))) // - .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) // + .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // + .andExpect(jsonPath("$.id", Is.is(2))) // + .andExpect(jsonPath("$.version", Is.is(3))) // + .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); } @Test void shouldSetOkrChampion() throws Exception { - BDDMockito.given(userAuthorizationService.setIsOkrChampion(2, true)).willReturn(userAlice); - BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); + BDDMockito.given(userAuthorizationService.setIsOkrChampion(2, true)) + .willReturn(userAlice); + BDDMockito.given(userMapper.toDto(userAlice)) + .willReturn(userAliceDto); mvc.perform(put("/api/v1/users/2/isokrchampion/true") // - .content(SUCCESSFUL_UPDATE_BODY) // - .contentType(MediaType.APPLICATION_JSON) // - .with(SecurityMockMvcRequestPostProcessors.csrf()) // + .content(SUCCESSFUL_UPDATE_BODY) // + .contentType(MediaType.APPLICATION_JSON) // + .with(SecurityMockMvcRequestPostProcessors.csrf()) // ) // - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // - .andExpect(jsonPath("$.id", Is.is(2))) // - .andExpect(jsonPath("$.version", Is.is(3))) // - .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) // + .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // + .andExpect(jsonPath("$.id", Is.is(2))) // + .andExpect(jsonPath("$.version", Is.is(3))) // + .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); } @Test void shouldCreateUsers() throws Exception { - BDDMockito.given(userAuthorizationService.createUsers(any())).willReturn(List.of(userAlice)); - BDDMockito.given(userMapper.toDtos(List.of(userAlice))).willReturn(List.of(userAliceDto)); + BDDMockito.given(userAuthorizationService.createUsers(any())) + .willReturn(List.of(userAlice)); + BDDMockito.given(userMapper.toDtos(List.of(userAlice))) + .willReturn(List.of(userAliceDto)); mvc.perform(post("/api/v1/users/createall") // - .content(SUCCESSFUL_UPDATE_BODY) // - .contentType(MediaType.APPLICATION_JSON) // - .with(SecurityMockMvcRequestPostProcessors.csrf()) // + .content(SUCCESSFUL_UPDATE_BODY) // + .contentType(MediaType.APPLICATION_JSON) // + .with(SecurityMockMvcRequestPostProcessors.csrf()) // ) // - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.hasSize(1))) // - .andExpect(jsonPath("$[0].id", Is.is(2))) // - .andExpect(jsonPath("$[0].version", Is.is(3))) // - .andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$[0].userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$[0].isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status() + .isOk()) // + .andExpect(jsonPath("$", Matchers.hasSize(1))) // + .andExpect(jsonPath("$[0].id", Is.is(2))) // + .andExpect(jsonPath("$[0].version", Is.is(3))) // + .andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$[0].userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$[0].isOkrChampion", Is.is(false))); } } \ No newline at end of file diff --git a/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java b/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java index 62145a9cc8..997a9e41ab 100644 --- a/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java @@ -8,9 +8,7 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.business.KeyResultBusinessService; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.ObjectMapper; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -21,6 +19,10 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.ObjectMapper; + import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -46,26 +48,27 @@ void setUp() { void deserializeShouldReturnCheckInMetricDtoForMetricJson() throws Exception { // arrange String jsonMetric = """ - { - "id": 42, - "version": 0, - "changeInfo": "Change_Info", - "initiatives": "Initiatives", - "confidence": 5, - "keyResultId": 1000, - "createdOn": null, - "modifiedOn": null, - "value": 23.0, - "writeable": false - } - """; + { + "id": 42, + "version": 0, + "changeInfo": "Change_Info", + "initiatives": "Initiatives", + "confidence": 5, + "keyResultId": 1000, + "createdOn": null, + "modifiedOn": null, + "value": 23.0, + "writeable": false + } + """; when(keyResultBusinessService.getEntityById(1000L)) // - .thenReturn(KeyResultMetric.Builder.builder() // - .withId(1000L) // - .build()); + .thenReturn(KeyResultMetric.Builder.builder() // + .withId(1000L) // + .build()); - JsonParser jsonParser = objectMapper.getFactory().createParser(jsonMetric); + JsonParser jsonParser = objectMapper.getFactory() + .createParser(jsonMetric); DeserializationContext ctxt = mock(DeserializationContext.class); // act @@ -93,26 +96,27 @@ private static void assertCheckInMetricDto(CheckInMetricDto checkInMetricDto) { void deserializeShouldReturnCheckInOrdinalDtoForOrdinalJson() throws Exception { // arrange String jsonOrdinal = """ - { - "id": 43, - "version": 0, - "changeInfo": "Change_Info", - "initiatives": "Initiatives", - "confidence": 7, - "keyResultId": 1001, - "createdOn": null, - "modifiedOn": null, - "value": "STRETCH", - "writeable": false - } - """; + { + "id": 43, + "version": 0, + "changeInfo": "Change_Info", + "initiatives": "Initiatives", + "confidence": 7, + "keyResultId": 1001, + "createdOn": null, + "modifiedOn": null, + "value": "STRETCH", + "writeable": false + } + """; when(keyResultBusinessService.getEntityById(1001L)) // - .thenReturn(KeyResultOrdinal.Builder.builder() // - .withId(1001L) // - .build()); + .thenReturn(KeyResultOrdinal.Builder.builder() // + .withId(1001L) // + .build()); - JsonParser jsonParser = objectMapper.getFactory().createParser(jsonOrdinal); + JsonParser jsonParser = objectMapper.getFactory() + .createParser(jsonOrdinal); DeserializationContext ctxt = mock(DeserializationContext.class); // act @@ -140,11 +144,11 @@ private void assertCheckInOrdinalDto(CheckInOrdinalDto checkInOrdinalDto) { void deserializeShouldThrowResponseStatusExceptionIfKeyResultIsUnsupportedType() throws Exception { // arrange String json = """ - { - "id": 0, - "keyResultId": 1002 - } - """; + { + "id": 0, + "keyResultId": 1002 + } + """; KeyResult unsupportedKeyResult = new KeyResult() { @Override @@ -155,7 +159,8 @@ public String getKeyResultType() { when(keyResultBusinessService.getEntityById(1002L)).thenReturn(unsupportedKeyResult); - JsonParser jsonParser = objectMapper.getFactory().createParser(json); + JsonParser jsonParser = objectMapper.getFactory() + .createParser(json); DeserializationContext ctxt = mock(DeserializationContext.class); // act + assert @@ -172,13 +177,14 @@ public String getKeyResultType() { void deserializeShouldThrowResponseStatusExceptionIfJsonHasNoKeyResultId() throws Exception { // arrange String jsonWithoutKeyResultId = """ - { - "id": 0, - "changeInfo": "THIS_JSON_WILL_NOT_BE_USED" - } - """; - - JsonParser jsonParser = objectMapper.getFactory().createParser(jsonWithoutKeyResultId); + { + "id": 0, + "changeInfo": "THIS_JSON_WILL_NOT_BE_USED" + } + """; + + JsonParser jsonParser = objectMapper.getFactory() + .createParser(jsonWithoutKeyResultId); DeserializationContext ctxt = mock(DeserializationContext.class); // act + assert diff --git a/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java b/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java index b8ddead732..190fb67b30 100644 --- a/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java @@ -2,9 +2,7 @@ import ch.puzzle.okr.dto.keyresult.*; import ch.puzzle.okr.models.Unit; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.ObjectMapper; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,6 +12,10 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.ObjectMapper; + import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; @@ -35,34 +37,35 @@ void setUp() { void deserializeShouldReturnKeyResultMetricDtoForMetricJson() throws Exception { // arrange String jsonMetric = """ - { - "id": 42, - "version": 0, - "keyResultType": "metric", - "title": "TITLE_METRIC", - "description": "BESCHREIBUNG", - "baseline": 1.0, - "stretchGoal": 5.0, - "unit": "NUMBER", - "owner": { - "id": 1000, - "firstname": "Jaya", - "lastname": "Norris" - }, - "objective": { - "id": 1000, - "state": "ongoing-icon.svg", - "keyResultQuarterDto": null - }, - "lastCheckIn": null, - "createdOn": null, - "modifiedOn": null, - "writeable": false, - "actionList": [] - } - """; - - JsonParser jsonParser = objectMapper.getFactory().createParser(jsonMetric); + { + "id": 42, + "version": 0, + "keyResultType": "metric", + "title": "TITLE_METRIC", + "description": "BESCHREIBUNG", + "baseline": 1.0, + "stretchGoal": 5.0, + "unit": "NUMBER", + "owner": { + "id": 1000, + "firstname": "Jaya", + "lastname": "Norris" + }, + "objective": { + "id": 1000, + "state": "ongoing-icon.svg", + "keyResultQuarterDto": null + }, + "lastCheckIn": null, + "createdOn": null, + "modifiedOn": null, + "writeable": false, + "actionList": [] + } + """; + + JsonParser jsonParser = objectMapper.getFactory() + .createParser(jsonMetric); DeserializationContext ctxt = mock(DeserializationContext.class); // act @@ -109,35 +112,36 @@ private static void assertObjective(KeyResultObjectiveDto objective) { void deserializeShouldReturnKeyResultOrdinalDtoForOrdinalJson() throws Exception { // arrange String jsonMetric = """ - { - "id": 43, - "version": 0, - "keyResultType": "ordinal", - "title": "TITLE_ORDINAL", - "description": "BESCHREIBUNG", - "commitZone": "1", - "targetZone": "3", - "stretchZone": "5", - "owner": { - "id": 1000, - "firstname": "Jaya", - "lastname": "Norris" - }, - "objective": { - "id": 1000, - "state": "ongoing-icon.svg", - "keyResultQuarterDto": null - }, - "lastCheckIn": null, - "createdOn": null, - "modifiedOn": null, - "writeable": false, - "actionList": [] - } - - """; - - JsonParser jsonParser = objectMapper.getFactory().createParser(jsonMetric); + { + "id": 43, + "version": 0, + "keyResultType": "ordinal", + "title": "TITLE_ORDINAL", + "description": "BESCHREIBUNG", + "commitZone": "1", + "targetZone": "3", + "stretchZone": "5", + "owner": { + "id": 1000, + "firstname": "Jaya", + "lastname": "Norris" + }, + "objective": { + "id": 1000, + "state": "ongoing-icon.svg", + "keyResultQuarterDto": null + }, + "lastCheckIn": null, + "createdOn": null, + "modifiedOn": null, + "writeable": false, + "actionList": [] + } + + """; + + JsonParser jsonParser = objectMapper.getFactory() + .createParser(jsonMetric); DeserializationContext ctxt = mock(DeserializationContext.class); // act @@ -172,16 +176,17 @@ private void assertKeyResultOrdinalDto(KeyResultOrdinalDto keyResultOrdinalDto) void deserializeShouldThrowResponseStatusExceptionIfKeyResultIsUnsupportedType() throws Exception { // arrange String jsonMetric = """ - { - "id": 44, - "version": 0, - "keyResultType": "unsupported", - "title": "TITLE_UNSUPPORTED", - "description": "BESCHREIBUNG" - } - """; - - JsonParser jsonParser = objectMapper.getFactory().createParser(jsonMetric); + { + "id": 44, + "version": 0, + "keyResultType": "unsupported", + "title": "TITLE_UNSUPPORTED", + "description": "BESCHREIBUNG" + } + """; + + JsonParser jsonParser = objectMapper.getFactory() + .createParser(jsonMetric); DeserializationContext ctxt = mock(DeserializationContext.class); // act + assert @@ -197,15 +202,16 @@ void deserializeShouldThrowResponseStatusExceptionIfKeyResultIsUnsupportedType() void deserializeShouldThrowResponseStatusExceptionIfJsonHasNoKeyResultType() throws Exception { // arrange String jsonMetric = """ - { - "id": 45, - "version": 0, - "title": "NO_KEY_RESULT_TYPE", - "description": "BESCHREIBUNG" - } - """; - - JsonParser jsonParser = objectMapper.getFactory().createParser(jsonMetric); + { + "id": 45, + "version": 0, + "title": "NO_KEY_RESULT_TYPE", + "description": "BESCHREIBUNG" + } + """; + + JsonParser jsonParser = objectMapper.getFactory() + .createParser(jsonMetric); DeserializationContext ctxt = mock(DeserializationContext.class); // act + assert diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java index 9dc733ff5e..ab9fe120c1 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper; +import java.util.List; + import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResult; @@ -7,6 +9,7 @@ import ch.puzzle.okr.service.business.KeyResultBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,8 +17,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; @@ -29,7 +30,9 @@ public class ActionMapperTest { private static final boolean IS_CHECKED = true; private static final boolean IS_WRITEABLE = true; public static final long KEY_RESULT_ID = 10L; - private final KeyResult keyResult = KeyResultMetric.Builder.builder().withId(KEY_RESULT_ID).build(); + private final KeyResult keyResult = KeyResultMetric.Builder.builder() + .withId(KEY_RESULT_ID) + .build(); private ActionMapper actionMapper; @Mock @@ -49,13 +52,13 @@ void setup() { void toDtoShouldMapActionToDto() { // arrange Action action = Action.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withAction(ACTION) // - .withPriority(PRIORITY) // - .withIsChecked(IS_CHECKED) // - .withKeyResult(keyResult) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withAction(ACTION) // + .withPriority(PRIORITY) // + .withIsChecked(IS_CHECKED) // + .withKeyResult(keyResult) // + .build(); action.setWriteable(IS_WRITEABLE); // act @@ -72,7 +75,8 @@ private void assertActionDto(Action expected, ActionDto actual) { assertEquals(expected.getAction(), actual.action()); assertEquals(expected.getPriority(), actual.priority()); assertEquals(expected.isChecked(), actual.isChecked()); - assertEquals(expected.getKeyResult().getId(), actual.keyResultId()); + assertEquals(expected.getKeyResult() + .getId(), actual.keyResultId()); assertEquals(expected.isWriteable(), actual.writeable()); } @@ -105,14 +109,16 @@ void toActionsShouldMapListOfDtosWithKeyResltIdToListOfActions() { @Test void toActionsWithKeyResultParameterShouldMapListOfDtosToListOfActions() { // arrange - KeyResult keyResultParameter = KeyResultMetric.Builder.builder().withId(20L).build(); + KeyResult keyResultParameter = KeyResultMetric.Builder.builder() + .withId(20L) + .build(); ActionDto actionDtoWithKeyResultIdIsNull = new ActionDto(ID, // - VERSION, // - ACTION, // - PRIORITY, // - IS_CHECKED, // - null, // keyResultId - IS_WRITEABLE // + VERSION, // + ACTION, // + PRIORITY, // + IS_CHECKED, // + null, // keyResultId + IS_WRITEABLE // ); // act @@ -129,13 +135,19 @@ void toActionsWithKeyResultParameterShouldMapListOfDtosToListOfActions() { private void assertListOfActionsWithKeyResultId(List expectedDtoList, List actualList) { assertListsAndFirstAction(expectedDtoList, actualList); - assertEquals(expectedDtoList.get(0).keyResultId(), actualList.get(0).getKeyResult().getId()); + assertEquals(expectedDtoList.get(0) + .keyResultId(), + actualList.get(0) + .getKeyResult() + .getId()); } - private void assertListOfActionsAndKeyResultParameter(List expectedDtoList, List actualList, - Long keyResultId) { + private void assertListOfActionsAndKeyResultParameter(List expectedDtoList, List actualList, Long keyResultId) { assertListsAndFirstAction(expectedDtoList, actualList); - assertEquals(keyResultId, actualList.get(0).getKeyResult().getId()); + assertEquals(keyResultId, + actualList.get(0) + .getKeyResult() + .getId()); } private void assertListsAndFirstAction(List expectedDtoList, List actualList) { diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java index 84c1db2ff8..4e10c4ea7a 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java @@ -1,11 +1,12 @@ package ch.puzzle.okr.mapper; +import java.util.List; + import ch.puzzle.okr.dto.alignment.AlignmentObjectiveDto; import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; -import org.junit.jupiter.api.Test; -import java.util.List; +import org.junit.jupiter.api.Test; import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -25,68 +26,116 @@ void toDtoShouldReturnEmptyListWhenNoObjectiveFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveFound() { List alignmentSelections = List.of(AlignmentSelection.Builder.builder() - .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder().withObjectiveId(1L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").build()); + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(1, alignmentObjectiveDtos.size()); - assertEquals(0, alignmentObjectiveDtos.get(0).keyResults().size()); + assertEquals(0, + alignmentObjectiveDtos.get(0) + .keyResults() + .size()); } @Test void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultFound() { List alignmentSelections = List.of(AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(3L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 3").build()); + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(3L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 3") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(1, alignmentObjectiveDtos.size()); - assertEquals(1, alignmentObjectiveDtos.get(0).keyResults().size()); + assertEquals(1, + alignmentObjectiveDtos.get(0) + .keyResults() + .size()); } @Test void toDtoShouldReturnOneElementWhenObjectiveWithTwoKeyResultsFound() { - List alignmentSelections = List.of( - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(3L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 3").build(), - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(5L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 5").build()); + List alignmentSelections = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(3L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 3") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(5L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 5") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(1, alignmentObjectiveDtos.size()); - assertEquals(2, alignmentObjectiveDtos.get(0).keyResults().size()); + assertEquals(2, + alignmentObjectiveDtos.get(0) + .keyResults() + .size()); } @Test void toDtoShouldReturnOneElementWhenTwoObjectivesWithKeyResultsFound() { - List alignmentSelections = List.of( - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(3L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 3").build(), - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(5L).withKeyResultId(6L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 5") - .withKeyResultTitle("Key Result 6").build(), - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(9L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 9").build()); + List alignmentSelections = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(3L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 3") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(5L) + .withKeyResultId(6L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 6") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(9L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 9") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(2, alignmentObjectiveDtos.size()); - assertEquals(2, alignmentObjectiveDtos.get(0).keyResults().size()); - assertEquals(1, alignmentObjectiveDtos.get(1).keyResults().size()); + assertEquals(2, + alignmentObjectiveDtos.get(0) + .keyResults() + .size()); + assertEquals(1, + alignmentObjectiveDtos.get(1) + .keyResults() + .size()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java index 141bb9f789..58d1a68fe5 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java @@ -3,6 +3,7 @@ import ch.puzzle.okr.dto.CompletedDto; import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.Objective; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -25,13 +26,15 @@ public class CompletedMapperTest { @Test void toDtoShouldMapCompletedToDto() { // arrange - Objective objective = Objective.Builder.builder().withId(23L).build(); + Objective objective = Objective.Builder.builder() + .withId(23L) + .build(); Completed completed = Completed.Builder.builder() // - .withId(ID) // - .withComment(COMMENT) // - .withObjective(objective) // - .build(); + .withId(ID) // + .withComment(COMMENT) // + .withObjective(objective) // + .build(); // act CompletedDto completedDto = completedMapper.toDto(completed); @@ -44,14 +47,19 @@ void toDtoShouldMapCompletedToDto() { private void assertCompletedDto(Completed expected, CompletedDto actual) { assertEquals(expected.getId(), actual.id()); assertEquals(expected.getComment(), actual.comment()); - assertEquals(expected.getObjective().getId(), actual.objective().getId()); + assertEquals(expected.getObjective() + .getId(), + actual.objective() + .getId()); } @DisplayName("toCompleted() should map Dto to Completed") @Test void toCompletedShouldMapDtoToCompleted() { // arrange - Objective objective = Objective.Builder.builder().withId(23L).build(); + Objective objective = Objective.Builder.builder() + .withId(23L) + .build(); CompletedDto completedDto = new CompletedDto(ID, objective, COMMENT); // act @@ -65,7 +73,10 @@ void toCompletedShouldMapDtoToCompleted() { private void assertCompleted(CompletedDto expected, Completed actual) { assertEquals(expected.id(), actual.getId()); assertEquals(expected.comment(), actual.getComment()); - assertEquals(expected.objective().getId(), actual.getObjective().getId()); + assertEquals(expected.objective() + .getId(), + actual.getObjective() + .getId()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java index 35ce1d1cc7..e6c62d8274 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.mapper; +import java.time.LocalDateTime; +import java.time.Month; + import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Quarter; @@ -7,6 +10,7 @@ import ch.puzzle.okr.models.Team; import ch.puzzle.okr.service.business.QuarterBusinessService; import ch.puzzle.okr.service.business.TeamBusinessService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -16,9 +20,6 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import java.time.LocalDateTime; -import java.time.Month; - import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; @@ -38,11 +39,13 @@ public class ObjectiveMapperTest { private static final LocalDateTime CREATE_DATE_TIME = LocalDateTime.of(2024, Month.MAY, 20, 12, 35, 0); private static final LocalDateTime MODIFIED_DATE_TIME = LocalDateTime.of(2024, Month.MAY, 21, 8, 0, 0); - private final Team team = Team.Builder.builder().withId(TEAM_ID).build(); + private final Team team = Team.Builder.builder() + .withId(TEAM_ID) + .build(); private final Quarter quarter = Quarter.Builder.builder() // - .withId(QUARTER_ID) // - .withLabel(QUARTER_LABEL) // - .build(); + .withId(QUARTER_ID) // + .withLabel(QUARTER_LABEL) // + .build(); private ObjectiveMapper objectiveMapper; @@ -62,16 +65,16 @@ void setup() { void toDtoShouldMapObjectiveToDto() { // arrange Objective objective = Objective.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withTitle(TITLE) // - .withTeam(team) // - .withQuarter(quarter) // - .withDescription(DESCRIPTION) // - .withState(STATE) // - .withCreatedOn(CREATE_DATE_TIME) // - .withModifiedOn(MODIFIED_DATE_TIME) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withTitle(TITLE) // + .withTeam(team) // + .withQuarter(quarter) // + .withDescription(DESCRIPTION) // + .withState(STATE) // + .withCreatedOn(CREATE_DATE_TIME) // + .withModifiedOn(MODIFIED_DATE_TIME) // + .build(); objective.setWriteable(IS_WRITEABLE); // act @@ -86,9 +89,12 @@ private void assertObjectiveDto(Objective expected, ObjectiveDto actual) { assertEquals(expected.getId(), actual.id()); assertEquals(expected.getVersion(), actual.version()); assertEquals(expected.getTitle(), actual.title()); - assertEquals(expected.getTeam().getId(), actual.teamId()); - assertEquals(expected.getQuarter().getId(), actual.quarterId()); - assertEquals(expected.getQuarter().getLabel(), actual.quarterLabel()); + assertEquals(expected.getTeam() + .getId(), actual.teamId()); + assertEquals(expected.getQuarter() + .getId(), actual.quarterId()); + assertEquals(expected.getQuarter() + .getLabel(), actual.quarterLabel()); assertEquals(expected.getDescription(), actual.description()); assertEquals(expected.getState(), actual.state()); assertEquals(expected.getCreatedOn(), actual.createdOn()); @@ -133,9 +139,15 @@ private void assertObjective(ObjectiveDto expected, Objective actual) { assertEquals(expected.id(), actual.getId()); assertEquals(expected.version(), actual.getVersion()); assertEquals(expected.title(), actual.getTitle()); - assertEquals(expected.teamId(), actual.getTeam().getId()); - assertEquals(expected.quarterId(), actual.getQuarter().getId()); - assertEquals(expected.quarterLabel(), actual.getQuarter().getLabel()); + assertEquals(expected.teamId(), + actual.getTeam() + .getId()); + assertEquals(expected.quarterId(), + actual.getQuarter() + .getId()); + assertEquals(expected.quarterLabel(), + actual.getQuarter() + .getLabel()); assertEquals(expected.description(), actual.getDescription()); assertEquals(expected.state(), actual.getState()); assertEquals(expected.createdOn(), actual.getCreatedOn()); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java index 374057e987..309e328dd6 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.dto.overview.OverviewDto; import ch.puzzle.okr.dto.overview.OverviewKeyResultDto; @@ -9,13 +11,12 @@ import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; @@ -40,148 +41,308 @@ void toDtoShouldReturnEmptyListWhenNoTeamFound() { @Test void toDtoShouldReturnEmptyListWhenTeamFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withTeamId(2L).build()).withTeamName(TEAM_PUZZLE).build()); + .withOverviewId(OverviewId.Builder.builder() + .withTeamId(2L) + .build()) + .withTeamName(TEAM_PUZZLE) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); - assertEquals(0, overviewDtos.get(0).objectives().size()); + assertEquals(0, + overviewDtos.get(0) + .objectives() + .size()); } @Test void toDtoShouldReturnOneElementWhenObjectiveFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); - assertEquals(1, overviewDtos.get(0).objectives().size()); - assertEquals(0, overviewDtos.get(0).objectives().get(0).keyResults().size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .size()); + assertEquals(0, + overviewDtos.get(0) + .objectives() + .get(0) + .keyResults() + .size()); } @Test void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId( - OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).withKeyResultId(3L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); - assertEquals(1, overviewDtos.get(0).objectives().size()); - assertEquals(1, overviewDtos.get(0).objectives().get(0).keyResults().size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .get(0) + .keyResults() + .size()); } @Test void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultAndCheckInsFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).withKeyResultId(3L) - .withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withCheckInValue(27.5).withConfidence(5).build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withCheckInValue(27.5) + .withConfidence(5) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); - assertEquals(1, overviewDtos.get(0).objectives().size()); - assertEquals(1, overviewDtos.get(0).objectives().get(0).keyResults().size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .get(0) + .keyResults() + .size()); } @Test void toDtoShouldReturnOneElementWhenObjectiveWithTwoKeyResultAndCheckInFound() { - List overviews = List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(3L).withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).withCheckInZone("COMMIT").build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(5L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 5") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).build()); + List overviews = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .withCheckInZone("COMMIT") + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(5L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 5") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); - assertEquals(1, overviewDtos.get(0).objectives().size()); - assertEquals(2, overviewDtos.get(0).objectives().get(0).keyResults().size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .size()); + assertEquals(2, + overviewDtos.get(0) + .objectives() + .get(0) + .keyResults() + .size()); } @Test void toDtoShouldReturnOneElementWhenTwoObjectivesWithKeyResultAndCheckInFound() { - List overviews = List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(3L).withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withBaseline(20.0).withStretchGoal(37.0) - .withUnit("TCHF").withCheckInValue(27.5).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(5L).withTeamId(2L) - .withKeyResultId(6L).withCheckInId(7L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 5").withKeyResultTitle("Key Result 6") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).withCommitZone("commit").withTargetZone("target") - .withStretchZone("stretch").withCheckInZone("checkIn").build()); + List overviews = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withBaseline(20.0) + .withStretchGoal(37.0) + .withUnit("TCHF") + .withCheckInValue(27.5) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(5L) + .withTeamId(2L) + .withKeyResultId(6L) + .withCheckInId(7L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 6") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .withCommitZone("commit") + .withTargetZone("target") + .withStretchZone("stretch") + .withCheckInZone("checkIn") + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); - assertEquals(2, overviewDtos.get(0).objectives().size()); - assertEquals(1, overviewDtos.get(0).objectives().get(0).keyResults().size()); - assertEquals(1, overviewDtos.get(0).objectives().get(1).keyResults().size()); + assertEquals(2, + overviewDtos.get(0) + .objectives() + .size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .get(0) + .keyResults() + .size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .get(1) + .keyResults() + .size()); - OverviewKeyResultDto keyResultDto = overviewDtos.get(0).objectives().get(0).keyResults().get(0); + OverviewKeyResultDto keyResultDto = overviewDtos.get(0) + .objectives() + .get(0) + .keyResults() + .get(0); assertTrue(keyResultDto instanceof OverviewKeyResultMetricDto); assertEquals(KEY_RESULT_TYPE_METRIC, keyResultDto.keyResultType()); assertEquals(20.0, ((OverviewKeyResultMetricDto) keyResultDto).baseline(), 0.1); assertEquals(37.0, ((OverviewKeyResultMetricDto) keyResultDto).stretchGoal(), 0.1); - assertEquals(27.5, ((OverviewKeyResultMetricDto) keyResultDto).lastCheckIn().value(), 0.1); + assertEquals(27.5, + ((OverviewKeyResultMetricDto) keyResultDto).lastCheckIn() + .value(), + 0.1); - keyResultDto = overviewDtos.get(0).objectives().get(1).keyResults().get(0); + keyResultDto = overviewDtos.get(0) + .objectives() + .get(1) + .keyResults() + .get(0); assertTrue(keyResultDto instanceof OverviewKeyResultOrdinalDto); assertEquals(KEY_RESULT_TYPE_ORDINAL, keyResultDto.keyResultType()); assertEquals("commit", ((OverviewKeyResultOrdinalDto) keyResultDto).commitZone()); assertEquals("target", ((OverviewKeyResultOrdinalDto) keyResultDto).targetZone()); assertEquals("stretch", ((OverviewKeyResultOrdinalDto) keyResultDto).stretchZone()); - assertEquals("checkIn", ((OverviewKeyResultOrdinalDto) keyResultDto).lastCheckIn().value()); + assertEquals("checkIn", + ((OverviewKeyResultOrdinalDto) keyResultDto).lastCheckIn() + .value()); } @Test void toDtoShouldReturnOneElementWhenTwoTeamsWithObjectivesAndKeyResultsFound() { - List overviews = List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(3L).withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).withCheckInZone("TARGET").build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(5L).withTeamId(4L) - .withKeyResultId(6L).build()) - .withTeamName("/BBT").withObjectiveTitle("Objective 5").withKeyResultTitle("Key Result 6") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(5L).withTeamId(4L) - .withKeyResultId(8L).build()) - .withTeamName("/BBT").withObjectiveTitle("Objective 5").withKeyResultTitle("Key Result 8") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).build()); + List overviews = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .withCheckInZone("TARGET") + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(5L) + .withTeamId(4L) + .withKeyResultId(6L) + .build()) + .withTeamName("/BBT") + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 6") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(5L) + .withTeamId(4L) + .withKeyResultId(8L) + .build()) + .withTeamName("/BBT") + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 8") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(2, overviewDtos.size()); - assertEquals(1, overviewDtos.get(0).objectives().size()); - assertEquals(1, overviewDtos.get(0).objectives().get(0).keyResults().size()); - assertEquals(1, overviewDtos.get(1).objectives().size()); - assertEquals(2, overviewDtos.get(1).objectives().get(0).keyResults().size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .size()); + assertEquals(1, + overviewDtos.get(0) + .objectives() + .get(0) + .keyResults() + .size()); + assertEquals(1, + overviewDtos.get(1) + .objectives() + .size()); + assertEquals(2, + overviewDtos.get(1) + .objectives() + .get(0) + .keyResults() + .size()); } @Test void toDtoShouldThrowExceptionWhenKeyResultTypeNotSupported() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).withKeyResultId(3L) - .withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType("unknown").withCheckInZone("TARGET").build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType("unknown") + .withCheckInZone("TARGET") + .build()); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> overviewMapper.toDto(overviews)); + () -> overviewMapper.toDto(overviews)); assertEquals(BAD_REQUEST, exception.getStatusCode()); @@ -189,6 +350,7 @@ void toDtoShouldThrowExceptionWhenKeyResultTypeNotSupported() { assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java index a885626375..f6a1f9a645 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java @@ -2,6 +2,7 @@ import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.models.Team; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -26,10 +27,10 @@ public class TeamMapperTest { void toDtoShouldMapTeamToDto() { // arrange Team team = Team.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withName(NAME) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withName(NAME) // + .build(); team.setWriteable(IS_WRITEABLE); // act diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java index 3677e06a18..901203b39a 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java @@ -1,10 +1,13 @@ package ch.puzzle.okr.mapper; +import java.util.List; + import ch.puzzle.okr.dto.NewUserDto; import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.UserTeam; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -12,8 +15,6 @@ import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static org.junit.jupiter.api.Assertions.*; @ExtendWith(MockitoExtension.class) @@ -33,17 +34,18 @@ public class UserMapperTest { private TeamMapper teamMapper; private final User user = User.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withFirstname(FIRSTNAME) // - .withLastname(LASTNAME) // - .withEmail(EMAIL) // - .withUserTeamList(List.of(UserTeam.Builder.builder() // - .withId(USER_TEAM_ID) // - .withTeam(Team.Builder.builder().build()) // - .build())) // - .withOkrChampion(IS_OKR_CHAMPION) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withFirstname(FIRSTNAME) // + .withLastname(LASTNAME) // + .withEmail(EMAIL) // + .withUserTeamList(List.of(UserTeam.Builder.builder() // + .withId(USER_TEAM_ID) // + .withTeam(Team.Builder.builder() + .build()) // + .build())) // + .withOkrChampion(IS_OKR_CHAMPION) // + .build(); private final NewUserDto userDto = new NewUserDto(FIRSTNAME, LASTNAME, EMAIL); @@ -57,13 +59,13 @@ void setup() { void toDtoWithoutTeamListThrowsException() { // arrange User user = User.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withFirstname(FIRSTNAME) // - .withLastname(LASTNAME) // - .withEmail(EMAIL) // - .withOkrChampion(IS_OKR_CHAMPION) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withFirstname(FIRSTNAME) // + .withLastname(LASTNAME) // + .withEmail(EMAIL) // + .withOkrChampion(IS_OKR_CHAMPION) // + .build(); // act + assert assertThrows(NullPointerException.class, () -> userMapper.toDto(user)); @@ -98,8 +100,15 @@ private void assertUserDto(User expected, UserDto actual) { assertEquals(expected.isOkrChampion(), actual.isOkrChampion()); assertEquals(expected.getEmail(), actual.email()); - assertEquals(1, actual.userTeamList().size()); - assertEquals(expected.getUserTeamList().get(0).getId(), actual.userTeamList().get(0).id()); + assertEquals(1, + actual.userTeamList() + .size()); + assertEquals(expected.getUserTeamList() + .get(0) + .getId(), + actual.userTeamList() + .get(0) + .id()); } @DisplayName("toUser() should map UserDto to User") diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java index 514d838491..4b4be344c7 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java @@ -12,6 +12,7 @@ import ch.puzzle.okr.service.business.KeyResultBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -110,8 +111,8 @@ void toDtoShouldThrowExceptionIfCheckInIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> checkInMapper.toDto(checkIn)); + ResponseStatusException.class, // + () -> checkInMapper.toDto(checkIn)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } @@ -124,8 +125,8 @@ void toCheckInShouldThrowExceptionIfCheckInIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> checkInMapper.toCheckIn(checkInDto)); + ResponseStatusException.class, // + () -> checkInMapper.toCheckIn(checkInDto)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java index 138391aa35..3a35c94736 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java @@ -8,6 +8,7 @@ import ch.puzzle.okr.service.business.KeyResultBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java index 76a7900bcf..f5eb3d9bfe 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java @@ -8,6 +8,7 @@ import ch.puzzle.okr.service.business.KeyResultBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java index f05c16717b..41ff440248 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java @@ -16,7 +16,8 @@ public static void assertCheckInMetricDto(CheckInMetric expected, CheckInMetricD assertEquals(expected.getChangeInfo(), actual.changeInfo()); assertEquals(expected.getInitiatives(), actual.initiatives()); assertEquals(expected.getConfidence(), actual.confidence()); - assertEquals(expected.getKeyResult().getId(), actual.keyResultId()); + assertEquals(expected.getKeyResult() + .getId(), actual.keyResultId()); assertEquals(expected.getCreatedOn(), actual.createdOn()); assertEquals(expected.getModifiedOn(), actual.modifiedOn()); assertEquals(expected.getValue(), actual.value()); @@ -29,7 +30,9 @@ public static void assertCheckInMetric(CheckInMetricDto expected, CheckInMetric assertEquals(expected.changeInfo(), actual.getChangeInfo()); assertEquals(expected.initiatives(), actual.getInitiatives()); assertEquals(expected.confidence(), actual.getConfidence()); - assertEquals(expected.keyResultId(), actual.getKeyResult().getId()); + assertEquals(expected.keyResultId(), + actual.getKeyResult() + .getId()); assertEquals(expected.createdOn(), actual.getCreatedOn()); assertEquals(expected.modifiedOn(), actual.getModifiedOn()); assertEquals(expected.value(), actual.getValue()); @@ -42,7 +45,8 @@ public static void assertCheckInOrdinalDto(CheckInOrdinal expected, CheckInOrdin assertEquals(expected.getChangeInfo(), actual.changeInfo()); assertEquals(expected.getInitiatives(), actual.initiatives()); assertEquals(expected.getConfidence(), actual.confidence()); - assertEquals(expected.getKeyResult().getId(), actual.keyResultId()); + assertEquals(expected.getKeyResult() + .getId(), actual.keyResultId()); assertEquals(expected.getCreatedOn(), actual.createdOn()); assertEquals(expected.getModifiedOn(), actual.modifiedOn()); assertEquals(expected.getZone(), actual.value()); @@ -55,7 +59,9 @@ public static void assertCheckInOrdinal(CheckInOrdinalDto checkInOrdinalDto, Che assertEquals(checkInOrdinalDto.changeInfo(), checkInOrdinal.getChangeInfo()); assertEquals(checkInOrdinalDto.initiatives(), checkInOrdinal.getInitiatives()); assertEquals(checkInOrdinalDto.confidence(), checkInOrdinal.getConfidence()); - assertEquals(checkInOrdinalDto.keyResultId(), checkInOrdinal.getKeyResult().getId()); + assertEquals(checkInOrdinalDto.keyResultId(), + checkInOrdinal.getKeyResult() + .getId()); assertEquals(checkInOrdinalDto.createdOn(), checkInOrdinal.getCreatedOn()); assertEquals(checkInOrdinalDto.modifiedOn(), checkInOrdinal.getModifiedOn()); assertEquals(checkInOrdinalDto.value(), checkInOrdinal.getZone()); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java index a060a43c11..7b2786f9fd 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java @@ -1,10 +1,10 @@ package ch.puzzle.okr.mapper.checkin.helper; -import ch.puzzle.okr.models.checkin.Zone; - import java.time.LocalDateTime; import java.time.Month; +import ch.puzzle.okr.models.checkin.Zone; + public class TestDataConstants { public static final boolean CHECK_IN_IS_WRITEABLE = true; public static final long CHECK_IN_ID = 0L; diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java index f7c7f2ff14..c3dc952988 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java @@ -16,26 +16,26 @@ public static CheckInOrdinalDto checkInOrdinalDto() { } private static final CheckInMetricDto checkInMetricDto = new CheckInMetricDto(CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES, // - CHECK_IN_CONFIDENCE, // - KEY_RESULT_ID, // - CHECK_IN_CREATE_DATE_TIME, // - CHECK_IN_MODIFIED_DATE_TIME, // - CHECK_IN_METRIC_VALUE, // - CHECK_IN_IS_WRITEABLE // + CHECK_IN_VERSION, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES, // + CHECK_IN_CONFIDENCE, // + KEY_RESULT_ID, // + CHECK_IN_CREATE_DATE_TIME, // + CHECK_IN_MODIFIED_DATE_TIME, // + CHECK_IN_METRIC_VALUE, // + CHECK_IN_IS_WRITEABLE // ); private static final CheckInOrdinalDto checkInOrdinalDto = new CheckInOrdinalDto(CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES, // - CHECK_IN_CONFIDENCE, // - KEY_RESULT_ID, // - CHECK_IN_CREATE_DATE_TIME, // - CHECK_IN_MODIFIED_DATE_TIME, // - CHECK_IN_ORDINAL_ZONE, // - CHECK_IN_IS_WRITEABLE // + CHECK_IN_VERSION, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES, // + CHECK_IN_CONFIDENCE, // + KEY_RESULT_ID, // + CHECK_IN_CREATE_DATE_TIME, // + CHECK_IN_MODIFIED_DATE_TIME, // + CHECK_IN_ORDINAL_ZONE, // + CHECK_IN_IS_WRITEABLE // ); } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java index dc2d43b9c8..aff4643a41 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java @@ -25,29 +25,30 @@ public static CheckInOrdinal checkInOrdinal() { } private static final KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withId(KEY_RESULT_ID) // - .build(); + .withId(KEY_RESULT_ID) // + .build(); private static final CheckIn checkInMetric = CheckInMetric.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withKeyResult(keyResult) // - .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // - .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // - .withValue(CHECK_IN_METRIC_VALUE) // - .build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withKeyResult(keyResult) // + .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // + .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // + .withValue(CHECK_IN_METRIC_VALUE) // + .build(); private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withKeyResult(keyResult) // - .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // - .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // - .withZone(CHECK_IN_ORDINAL_ZONE).build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withKeyResult(keyResult) // + .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // + .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // + .withZone(CHECK_IN_ORDINAL_ZONE) + .build(); } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java index 8ba2235adc..7a8913d12c 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult; +import java.util.List; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; @@ -11,6 +13,7 @@ import ch.puzzle.okr.service.business.CheckInBusinessService; import ch.puzzle.okr.service.business.ObjectiveBusinessService; import ch.puzzle.okr.service.business.UserBusinessService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -21,8 +24,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.keyResultMetricDto; import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.keyResultOrdinalDto; import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.keyResultMetric; @@ -46,16 +47,16 @@ public class KeyResultMapperTest { @BeforeEach void setup() { KeyResultMetricMapper keyResultMetricMapper = new KeyResultMetricMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); KeyResultOrdinalMapper keyResultOrdinalMapper = new KeyResultOrdinalMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); keyResultMapper = new KeyResultMapper(keyResultOrdinalMapper, keyResultMetricMapper); } @@ -124,8 +125,8 @@ void toDtoShouldThrowExceptionIfKeyResultIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> keyResultMapper.toDto(keyResult, actions)); + ResponseStatusException.class, // + () -> keyResultMapper.toDto(keyResult, actions)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } @@ -137,8 +138,8 @@ void toKeyResultShouldThrowExceptionIfKeyResultDtoIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> keyResultMapper.toKeyResult(keyResultDto)); + ResponseStatusException.class, // + () -> keyResultMapper.toKeyResult(keyResultDto)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java index e6efdb524e..9c8e707167 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult; +import java.util.List; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.mapper.ActionMapper; @@ -15,6 +17,7 @@ import ch.puzzle.okr.service.business.UserBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -23,8 +26,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static ch.puzzle.okr.mapper.keyresult.helper.AssertHelper.*; import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.*; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -54,10 +55,10 @@ public class KeyResultMetricMapperTest { void setup() { actionMapper = new ActionMapper(keyResultBusinessService); keyResultMetricMapper = new KeyResultMetricMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); } @DisplayName("toDto() should map a KeyResultMetric to a Dto") diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java index dbc631e1d5..e2eabcef8a 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult; +import java.util.List; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; import ch.puzzle.okr.mapper.ActionMapper; @@ -15,6 +17,7 @@ import ch.puzzle.okr.service.business.UserBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -23,8 +26,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static ch.puzzle.okr.mapper.keyresult.helper.AssertHelper.*; import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.*; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -55,10 +56,10 @@ public class KeyResultOrdinalMapperTest { void setup() { actionMapper = new ActionMapper(keyResultBusinessService); keyResultOrdinalMapper = new KeyResultOrdinalMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); } @DisplayName("toDto() should map a KeyResultOrdinal with CheckIn to a Dto") diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java index fe66213e59..4b002fd1ec 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult.helper; +import java.util.List; + import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.dto.keyresult.*; import ch.puzzle.okr.models.Action; @@ -9,8 +11,6 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; -import java.util.List; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.lastCheckInMetricDto; @@ -18,8 +18,7 @@ public class AssertHelper { - public static void assertKeyResultMetricDtoWithCheckIn(KeyResultMetric expected, KeyResultMetricDto actual, - List actions) { + public static void assertKeyResultMetricDtoWithCheckIn(KeyResultMetric expected, KeyResultMetricDto actual, List actions) { assertKeyResultMetricDto(expected, actual, actions); // checkIn is only available on KeyResultMetricDto (and not on KeyResultMetric). // So check actual against the checkInMetricDto from TestDataDtoHelper @@ -27,14 +26,12 @@ public static void assertKeyResultMetricDtoWithCheckIn(KeyResultMetric expected, assertCheckInMetricDto(lastCheckInMetricDto(), actual.lastCheckIn()); } - public static void assertKeyResultMetricDtoWithoutCheckIn(KeyResultMetric expected, KeyResultMetricDto actual, - List actions) { + public static void assertKeyResultMetricDtoWithoutCheckIn(KeyResultMetric expected, KeyResultMetricDto actual, List actions) { assertKeyResultMetricDto(expected, actual, actions); assertNull(actual.lastCheckIn()); } - private static void assertKeyResultMetricDto(KeyResultMetric expected, KeyResultMetricDto actual, - List actions) { + private static void assertKeyResultMetricDto(KeyResultMetric expected, KeyResultMetricDto actual, List actions) { assertEquals(KEY_RESULT_TYPE_METRIC, actual.keyResultType()); assertEquals(expected.getKeyResultType(), actual.keyResultType()); @@ -50,8 +47,12 @@ private static void assertKeyResultMetricDto(KeyResultMetric expected, KeyResult assertEquals(expected.getCreatedOn(), actual.createdOn()); assertEquals(expected.getModifiedOn(), actual.modifiedOn()); - assertEquals(1, actual.getActionList().size()); - assertActionDto(actions.get(0), actual.getActionList().get(0)); + assertEquals(1, + actual.getActionList() + .size()); + assertActionDto(actions.get(0), + actual.getActionList() + .get(0)); } public static void assertKeyResultMetric(KeyResultMetricDto expected, KeyResultMetric actual) { @@ -70,23 +71,20 @@ public static void assertKeyResultMetric(KeyResultMetricDto expected, KeyResultM assertEquals(expected.modifiedOn(), actual.getModifiedOn()); } - public static void assertKeyResultOrdinalDtoWithCheckIn(KeyResultOrdinal expected, KeyResultOrdinalDto actual, - List actions) { + public static void assertKeyResultOrdinalDtoWithCheckIn(KeyResultOrdinal expected, KeyResultOrdinalDto actual, List actions) { assertKeyResultOrdinalDto(expected, actual, actions); assertNotNull(actual.lastCheckIn()); assertCheckInOrdinalDto(TestDataDtoHelper.lastCheckInOrdinalDto(), actual.lastCheckIn()); } - public static void assertKeyResultOrdinalDtoWithoutCheckIn(KeyResultOrdinal expected, KeyResultOrdinalDto actual, - List actions) { + public static void assertKeyResultOrdinalDtoWithoutCheckIn(KeyResultOrdinal expected, KeyResultOrdinalDto actual, List actions) { assertKeyResultOrdinalDto(expected, actual, actions); // checkIn is only available on KeyResultOrdinalDto (and not on KeyResultOrdinal). // So check actual against the KeyResultOrdinalDto from TestDataDtoHelper assertNull(actual.lastCheckIn()); } - private static void assertKeyResultOrdinalDto(KeyResultOrdinal expected, KeyResultOrdinalDto actual, - List actions) { + private static void assertKeyResultOrdinalDto(KeyResultOrdinal expected, KeyResultOrdinalDto actual, List actions) { assertEquals(KEY_RESULT_TYPE_ORDINAL, actual.keyResultType()); assertEquals(expected.getKeyResultType(), actual.keyResultType()); @@ -102,8 +100,12 @@ private static void assertKeyResultOrdinalDto(KeyResultOrdinal expected, KeyResu assertEquals(expected.getCreatedOn(), actual.createdOn()); assertEquals(expected.getModifiedOn(), actual.modifiedOn()); - assertEquals(1, actual.getActionList().size()); - assertActionDto(actions.get(0), actual.getActionList().get(0)); + assertEquals(1, + actual.getActionList() + .size()); + assertActionDto(actions.get(0), + actual.getActionList() + .get(0)); } public static void assertKeyResultOrdinal(KeyResultOrdinalDto expected, KeyResultOrdinal actual) { @@ -128,12 +130,14 @@ private static void assertActionDto(Action expected, ActionDto actual) { assertEquals(expected.getAction(), actual.action()); assertEquals(expected.getPriority(), actual.priority()); assertEquals(expected.isChecked(), actual.isChecked()); - assertEquals(expected.getKeyResult().getId(), actual.keyResultId()); + assertEquals(expected.getKeyResult() + .getId(), actual.keyResultId()); } private static void assertObjectiveDto(Objective expected, KeyResultObjectiveDto actual) { assertEquals(expected.getId(), actual.id()); - assertEquals(expected.getState().name(), actual.state()); + assertEquals(expected.getState() + .name(), actual.state()); assertQuarterDto(expected.getQuarter(), actual.keyResultQuarterDto()); } @@ -146,7 +150,9 @@ private static void assertQuarterDto(Quarter expected, KeyResultQuarterDto actua private static void assertObjective(KeyResultObjectiveDto expected, Objective actual) { assertEquals(expected.id(), actual.getId()); - assertEquals(expected.state(), actual.getState().name()); + assertEquals(expected.state(), + actual.getState() + .name()); assertQuarter(expected.keyResultQuarterDto(), actual.getQuarter()); } @@ -169,8 +175,7 @@ private static void assertOwner(KeyResultUserDto expected, User actual) { assertEquals(expected.lastname(), actual.getLastname()); } - private static void assertCheckInMetricDto(KeyResultLastCheckInMetricDto expected, - KeyResultLastCheckInMetricDto actual) { + private static void assertCheckInMetricDto(KeyResultLastCheckInMetricDto expected, KeyResultLastCheckInMetricDto actual) { assertEquals(expected.id(), actual.id()); assertEquals(expected.version(), actual.version()); assertEquals(expected.value(), actual.value()); @@ -180,8 +185,7 @@ private static void assertCheckInMetricDto(KeyResultLastCheckInMetricDto expecte assertEquals(expected.initiatives(), actual.initiatives()); } - private static void assertCheckInOrdinalDto(KeyResultLastCheckInOrdinalDto expected, - KeyResultLastCheckInOrdinalDto actual) { + private static void assertCheckInOrdinalDto(KeyResultLastCheckInOrdinalDto expected, KeyResultLastCheckInOrdinalDto actual) { assertEquals(expected.id(), actual.id()); assertEquals(expected.version(), actual.version()); assertEquals(expected.value(), actual.value()); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java index eff5381a5a..121df39b6d 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.mapper.keyresult.helper; -import ch.puzzle.okr.models.State; -import ch.puzzle.okr.models.Unit; -import ch.puzzle.okr.models.checkin.Zone; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; +import ch.puzzle.okr.models.State; +import ch.puzzle.okr.models.Unit; +import ch.puzzle.okr.models.checkin.Zone; + public class TestDataConstants { public static final long CHECK_IN_ID = 100L; diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java index ed836d442b..ea701e4277 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java @@ -24,78 +24,78 @@ public static KeyResultLastCheckInOrdinalDto lastCheckInOrdinalDto() { } private static final KeyResultUserDto ownerDto = new KeyResultUserDto( // - USER_ID, // - USER_FIRSTNAME, // - USER_LASTNAME // + USER_ID, // + USER_FIRSTNAME, // + USER_LASTNAME // ); private static final KeyResultQuarterDto quarterDto = new KeyResultQuarterDto( // - QUARTER_ID, // - QUARTER_LABEL, // - QUARTER_START_DATE, // - QUARTER_END_DATE // + QUARTER_ID, // + QUARTER_LABEL, // + QUARTER_START_DATE, // + QUARTER_END_DATE // ); private static final KeyResultObjectiveDto objectiveDto = new KeyResultObjectiveDto( // - OBJECTIVE_ID, // - OBJECTIVE_STATE.name(), // - quarterDto // + OBJECTIVE_ID, // + OBJECTIVE_STATE.name(), // + quarterDto // ); private static final KeyResultLastCheckInMetricDto lastCheckInMetricDto = new KeyResultLastCheckInMetricDto( // - CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_METRIC_VALUE, // - CHECK_IN_CONFIDENCE, // - CHECK_IN_CREATED_ON, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES // + CHECK_IN_ID, // + CHECK_IN_VERSION, // + CHECK_IN_METRIC_VALUE, // + CHECK_IN_CONFIDENCE, // + CHECK_IN_CREATED_ON, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES // ); private static final KeyResultLastCheckInOrdinalDto lastCheckInOrdinalDto = new KeyResultLastCheckInOrdinalDto( // - CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_ORDINAL_ZONE, // - CHECK_IN_CONFIDENCE, // - CHECK_IN_CREATED_ON, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES // + CHECK_IN_ID, // + CHECK_IN_VERSION, // + CHECK_IN_ORDINAL_ZONE, // + CHECK_IN_CONFIDENCE, // + CHECK_IN_CREATED_ON, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES // ); private static final KeyResultMetricDto keyResultMetricDto = new KeyResultMetricDto( // - KEY_RESULT_ID, // - KEY_RESULT_VERSION, // - KEY_RESULT_TYPE_METRIC, // - KEY_RESULT_TITLE, // - KEY_RESULT_DESCRIPTION, // - KEY_RESULT_BASELINE, // - KEY_RESULT_STRETCH_GOAL, // - KEY_RESULT_UNIT, // - ownerDto, // - objectiveDto, // - lastCheckInMetricDto, // - CHECK_IN_CREATED_ON, // - CHECK_IN_MODIFIED_ON, // - CHECK_IN_IS_WRITABLE, // - null // actionList; ony used for keyResultMetric + action -> dto BUT NOT FOR dto -> keyResultMetric + KEY_RESULT_ID, // + KEY_RESULT_VERSION, // + KEY_RESULT_TYPE_METRIC, // + KEY_RESULT_TITLE, // + KEY_RESULT_DESCRIPTION, // + KEY_RESULT_BASELINE, // + KEY_RESULT_STRETCH_GOAL, // + KEY_RESULT_UNIT, // + ownerDto, // + objectiveDto, // + lastCheckInMetricDto, // + CHECK_IN_CREATED_ON, // + CHECK_IN_MODIFIED_ON, // + CHECK_IN_IS_WRITABLE, // + null // actionList; ony used for keyResultMetric + action -> dto BUT NOT FOR dto -> keyResultMetric ); private static final KeyResultOrdinalDto keyResultOrdinalDto = new KeyResultOrdinalDto( // - KEY_RESULT_ID, // - KEY_RESULT_VERSION, // - KEY_RESULT_TYPE_ORDINAL, // - KEY_RESULT_TITLE, // - KEY_RESULT_DESCRIPTION, // - KEY_RESULT_COMMIT_ZONE, // - KEY_RESULT_TARGET_ZONE, // - KEY_RESULT_STRETCH_ZONE, // - ownerDto, // - objectiveDto, // - lastCheckInOrdinalDto, // - CHECK_IN_CREATED_ON, // - CHECK_IN_MODIFIED_ON, // - CHECK_IN_IS_WRITABLE, // - null // actionList; ony used for keyResultOrdinal + action -> dto BUT NOT FOR dto -> keyResultOrdinal + KEY_RESULT_ID, // + KEY_RESULT_VERSION, // + KEY_RESULT_TYPE_ORDINAL, // + KEY_RESULT_TITLE, // + KEY_RESULT_DESCRIPTION, // + KEY_RESULT_COMMIT_ZONE, // + KEY_RESULT_TARGET_ZONE, // + KEY_RESULT_STRETCH_ZONE, // + ownerDto, // + objectiveDto, // + lastCheckInOrdinalDto, // + CHECK_IN_CREATED_ON, // + CHECK_IN_MODIFIED_ON, // + CHECK_IN_IS_WRITABLE, // + null // actionList; ony used for keyResultOrdinal + action -> dto BUT NOT FOR dto -> keyResultOrdinal ); } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java index 365999229f..4d323f0c17 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java @@ -52,86 +52,88 @@ public static Objective objective() { } private static final CheckIn checkInMetric = CheckInMetric.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withValue(CHECK_IN_METRIC_VALUE) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withValue(CHECK_IN_METRIC_VALUE) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .build(); private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withZone(CHECK_IN_ORDINAL_ZONE) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withZone(CHECK_IN_ORDINAL_ZONE) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .build(); private static final User owner = User.Builder.builder() // - .withId(USER_ID) // - .withFirstname(USER_FIRSTNAME) // - .withLastname(USER_LASTNAME) // - .build(); + .withId(USER_ID) // + .withFirstname(USER_FIRSTNAME) // + .withLastname(USER_LASTNAME) // + .build(); private static final Quarter quarter = Quarter.Builder.builder() // - .withId(QUARTER_ID) // - .withLabel(QUARTER_LABEL) // - .withStartDate(QUARTER_START_DATE) // - .withEndDate(QUARTER_END_DATE) // - .build(); + .withId(QUARTER_ID) // + .withLabel(QUARTER_LABEL) // + .withStartDate(QUARTER_START_DATE) // + .withEndDate(QUARTER_END_DATE) // + .build(); private static final Objective objective = Objective.Builder.builder() // - .withId(OBJECTIVE_ID) // - .withQuarter(quarter) // - .withState(OBJECTIVE_STATE) // - .build(); + .withId(OBJECTIVE_ID) // + .withQuarter(quarter) // + .withState(OBJECTIVE_STATE) // + .build(); private static final KeyResult keyResultMetric = KeyResultMetric.Builder.builder() // - .withId(KEY_RESULT_ID) // - .withVersion(KEY_RESULT_VERSION) // - .withTitle(KEY_RESULT_TITLE) // - .withDescription(KEY_RESULT_DESCRIPTION) // - .withBaseline(KEY_RESULT_BASELINE) // - .withStretchGoal(KEY_RESULT_STRETCH_GOAL) // - .withUnit(KEY_RESULT_UNIT) // - .withOwner(owner) // - .withObjective(objective) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withModifiedOn(CHECK_IN_MODIFIED_ON) // - .build(); + .withId(KEY_RESULT_ID) // + .withVersion(KEY_RESULT_VERSION) // + .withTitle(KEY_RESULT_TITLE) // + .withDescription(KEY_RESULT_DESCRIPTION) // + .withBaseline(KEY_RESULT_BASELINE) // + .withStretchGoal(KEY_RESULT_STRETCH_GOAL) // + .withUnit(KEY_RESULT_UNIT) // + .withOwner(owner) // + .withObjective(objective) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withModifiedOn(CHECK_IN_MODIFIED_ON) // + .build(); private static final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() // - .withId(KEY_RESULT_ID) // - .withVersion(KEY_RESULT_VERSION) // - .withTitle(KEY_RESULT_TITLE) // - .withDescription(KEY_RESULT_DESCRIPTION) // - .withCommitZone(KEY_RESULT_COMMIT_ZONE).withTargetZone(KEY_RESULT_TARGET_ZONE) - .withStretchZone(KEY_RESULT_STRETCH_ZONE).withOwner(owner) // - .withObjective(objective) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withModifiedOn(CHECK_IN_MODIFIED_ON) // - .build(); + .withId(KEY_RESULT_ID) // + .withVersion(KEY_RESULT_VERSION) // + .withTitle(KEY_RESULT_TITLE) // + .withDescription(KEY_RESULT_DESCRIPTION) // + .withCommitZone(KEY_RESULT_COMMIT_ZONE) + .withTargetZone(KEY_RESULT_TARGET_ZONE) + .withStretchZone(KEY_RESULT_STRETCH_ZONE) + .withOwner(owner) // + .withObjective(objective) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withModifiedOn(CHECK_IN_MODIFIED_ON) // + .build(); private static final Action actionForKeyResultMetric = Action.Builder.builder() // - .withId(ACTION_ID) // - .withVersion(ACTION_VERSION) // - .withAction(ACTION_ACTION) // - .withPriority(ACTION_PRIORITY) // - .withIsChecked(ACTION_IS_CHECKED) // - .withKeyResult(keyResultMetric) // - .build(); + .withId(ACTION_ID) // + .withVersion(ACTION_VERSION) // + .withAction(ACTION_ACTION) // + .withPriority(ACTION_PRIORITY) // + .withIsChecked(ACTION_IS_CHECKED) // + .withKeyResult(keyResultMetric) // + .build(); private static final Action actionForKeyResultOrdinal = Action.Builder.builder() // - .withId(ACTION_ID) // - .withVersion(ACTION_VERSION) // - .withAction(ACTION_ACTION) // - .withPriority(ACTION_PRIORITY) // - .withIsChecked(ACTION_IS_CHECKED) // - .withKeyResult(keyResultOrdinal) // - .build(); + .withId(ACTION_ID) // + .withVersion(ACTION_VERSION) // + .withAction(ACTION_ACTION) // + .withPriority(ACTION_PRIORITY) // + .withIsChecked(ACTION_IS_CHECKED) // + .withKeyResult(keyResultOrdinal) // + .build(); } diff --git a/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java b/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java index 2b74f3dc69..8ae51e9975 100644 --- a/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java +++ b/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java @@ -1,23 +1,40 @@ package ch.puzzle.okr.models.authorization; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.UserTeam; -import org.junit.jupiter.api.Test; +import ch.puzzle.okr.test.TestHelper; -import java.util.List; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class AuthorizationUserTest { - private final List userTeamList = List.of( - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(1L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(2L)).withTeamAdmin(false).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(3L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(4L)).withTeamAdmin(false).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(5L)).withTeamAdmin(false).build()); - private final User user = User.Builder.builder().withUserTeamList(userTeamList).build(); + private final List userTeamList = List.of(UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(1L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(2L)) + .withTeamAdmin(false) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(3L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(4L)) + .withTeamAdmin(false) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(5L)) + .withTeamAdmin(false) + .build()); + private final User user = User.Builder.builder() + .withUserTeamList(userTeamList) + .build(); private final AuthorizationUser authorizationUser = new AuthorizationUser(user); @Test diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java index 3ab1cb4eb4..21d67b744d 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.multitenancy; +import java.util.List; +import java.util.Optional; + import org.flywaydb.core.Flyway; import org.flywaydb.core.api.configuration.FluentConfiguration; import org.junit.jupiter.api.DisplayName; @@ -7,9 +10,6 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.util.List; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; @@ -68,11 +68,18 @@ public String getLog() { private final TenantConfigProviderInterface providerInterfaceMock = new TenantConfigProviderInterface() { - private final TenantConfigProvider.DataSourceConfig dataSourceConfig = new TenantConfigProvider.DataSourceConfig( - NOT_USED, URL, NAME, PASSWORD, SCHEMA); + private final TenantConfigProvider.DataSourceConfig dataSourceConfig = new TenantConfigProvider.DataSourceConfig(NOT_USED, + URL, + NAME, + PASSWORD, + SCHEMA); private final TenantConfigProvider.TenantConfig tenantConfig = new TenantConfigProvider.TenantConfig(NOT_USED, - new String[] { NOT_USED }, NOT_USED, NOT_USED, NOT_USED, dataSourceConfig); + new String[]{NOT_USED}, + NOT_USED, + NOT_USED, + NOT_USED, + dataSourceConfig); @Override public List getTenantConfigs() { @@ -96,10 +103,11 @@ void flywayConfigureShouldReturnFluentConfigurationWhichWeCanAssert() { try (MockedStatic mockedStatic = Mockito.mockStatic(Flyway.class)) { // arrange FluentConfigurationSpy fluentConfiguration = new FluentConfigurationSpy(); - mockedStatic.when(Flyway::configure).thenReturn(fluentConfiguration); + mockedStatic.when(Flyway::configure) + .thenReturn(fluentConfiguration); - FlywayMultitenantMigrationInitializer migrationInitializer = new FlywayMultitenantMigrationInitializer( - providerInterfaceMock, new String[] { SCRIPT_LOCATION }); + FlywayMultitenantMigrationInitializer migrationInitializer = new FlywayMultitenantMigrationInitializer(providerInterfaceMock, + new String[]{SCRIPT_LOCATION}); // act migrationInitializer.migrateFlyway(); diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java index 7dbc3a5b16..adfe8fca94 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.multitenancy; +import java.util.Properties; +import java.util.stream.Stream; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,9 +11,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.core.env.ConfigurableEnvironment; -import java.util.Properties; -import java.util.stream.Stream; - import static ch.puzzle.okr.multitenancy.HibernateContext.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; @@ -37,27 +37,27 @@ void setHibernateConfigShouldThrowExceptionIfDbConfigIsNull() { @DisplayName("setHibernateConfig() should throw exception if db config has null or empty values") @ParameterizedTest @MethodSource("invalidDbConfig") - void setHibernateConfigShouldThrowExceptionIfDbConfigHasNullOrEmptyValues(String url, String username, - String password, String tenant) { + void setHibernateConfigShouldThrowExceptionIfDbConfigHasNullOrEmptyValues(String url, String username, String password, String tenant) { // arrange DbConfig dbConfig = new DbConfig(url, username, password, tenant); // act + assert RuntimeException exception = assertThrows(RuntimeException.class, () -> setHibernateConfig(dbConfig)); - assertTrue(exception.getMessage().startsWith("Invalid hibernate configuration")); + assertTrue(exception.getMessage() + .startsWith("Invalid hibernate configuration")); } private static Stream invalidDbConfig() { return Stream.of( // - Arguments.of(null, "username", "password", "multiTenancy"), // - Arguments.of("", "username", "password", "multiTenancy"), // - Arguments.of("url", null, "password", "multiTenancy"), // - Arguments.of("url", "", "password", "multiTenancy"), // - Arguments.of("url", "username", null, "multiTenancy"), // - Arguments.of("url", "username", "", "multiTenancy"), // - Arguments.of("url", "username", "password", null), // - Arguments.of("url", "username", "password", "")); + Arguments.of(null, "username", "password", "multiTenancy"), // + Arguments.of("", "username", "password", "multiTenancy"), // + Arguments.of("url", null, "password", "multiTenancy"), // + Arguments.of("url", "", "password", "multiTenancy"), // + Arguments.of("url", "username", null, "multiTenancy"), // + Arguments.of("url", "username", "", "multiTenancy"), // + Arguments.of("url", "username", "password", null), // + Arguments.of("url", "username", "password", "")); } @DisplayName("extractAndSetHibernateConfig() should extract hibernate properties from environment and set it") @@ -107,8 +107,7 @@ void getHibernateConfigShouldReturnHibernateConfigAsPropertiesIfDbConfigIsValid( assertProperties(url, username, password, multiTenancy, hibernateProperties); } - private void assertProperties(String url, String username, String password, String multiTenancy, - Properties properties) { + private void assertProperties(String url, String username, String password, String multiTenancy, Properties properties) { assertEquals(url, properties.get(HIBERNATE_CONNECTION_URL)); assertEquals(username, properties.get(HIBERNATE_CONNECTION_USERNAME)); diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java index e8bc0dc7b0..a36a83a87c 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java @@ -1,13 +1,14 @@ package ch.puzzle.okr.multitenancy; +import java.util.Properties; + import ch.puzzle.okr.exception.ConnectionProviderException; + import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Properties; - import static org.mockito.Mockito.mock; public class SchemaMultiTenantConnectionProviderInternalsTest { diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java index e9a97a6d14..bb2ecf0b4b 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java @@ -1,14 +1,15 @@ package ch.puzzle.okr.multitenancy; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + import ch.puzzle.okr.test.SpringIntegrationTest; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java index 940473d020..ba4934feea 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java @@ -1,6 +1,11 @@ package ch.puzzle.okr.multitenancy; +import java.text.MessageFormat; +import java.util.List; +import java.util.Optional; + import ch.puzzle.okr.test.SpringIntegrationTest; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,10 +15,6 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.core.env.Environment; -import java.text.MessageFormat; -import java.util.List; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; @@ -32,7 +33,7 @@ public class TenantConfigProviderTestIT { private static final String CHAMPION_EMAILS_2 = "b@pitc.ch"; private static final String CHAMPION_EMAILS = CHAMPION_EMAILS_1 + "," + CHAMPION_EMAILS_2; - private final String[] tenantIds = { "pitc", "acme" }; + private final String[] tenantIds = {"pitc", "acme"}; @Mock private Environment env; @@ -87,7 +88,7 @@ public void testGetTenantConfigs() { @DisplayName("getTenantConfigById returns for an existing TenantId the TenantConfig as Optional") @ParameterizedTest - @CsvSource({ "pitc, acme" }) + @CsvSource({"pitc, acme"}) void testGetTenantConfigByIdForExistingTenantId(String tenantId) { TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); Optional config = configProvider.getTenantConfigById(tenantId); @@ -97,7 +98,7 @@ void testGetTenantConfigByIdForExistingTenantId(String tenantId) { @DisplayName("getTenantConfigById returns for a non existing TenantId an empty Optional") @ParameterizedTest - @CsvSource({ "PITC-London" }) + @CsvSource({"PITC-London"}) void testGetTenantConfigByIdForNonExistingTenantId(String nonExistingTenantId) { TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); Optional config = configProvider.getTenantConfigById(nonExistingTenantId); @@ -106,7 +107,7 @@ void testGetTenantConfigByIdForNonExistingTenantId(String nonExistingTenantId) { @DisplayName("getJwkSetUri returns for an existing TenantId the JwkSetUri as Optional") @ParameterizedTest - @CsvSource({ "pitc", "acme" }) + @CsvSource({"pitc", "acme"}) void testGetJwkSetUriForExistingTenantId(String tenantId) { // arrange TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); @@ -121,7 +122,7 @@ void testGetJwkSetUriForExistingTenantId(String tenantId) { @DisplayName("getJwkSetUri returns for a non existing TenantId an empty Optional") @ParameterizedTest - @CsvSource({ "PITC-London" }) + @CsvSource({"PITC-London"}) void testGetJwkSetUriForNonExistingTenantId(String nonExistingTenantId) { TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); Optional jwkSetUri = configProvider.getJwkSetUri(nonExistingTenantId); @@ -134,13 +135,23 @@ private void assertTenantConfigProvider(TenantConfigProvider.TenantConfig tenant assertEquals(prefix(tenantId) + JWK_SET_URI, tenantConfig.jwkSetUri()); assertEquals(prefix(tenantId) + FRONTEND_CLIENT_ISSUER_URL, tenantConfig.issuerUrl()); assertEquals(prefix(tenantId) + FRONTEND_CLIENT_ID, tenantConfig.clientId()); - assertEquals(prefix(tenantId) + DATASOURCE_URL, tenantConfig.dataSourceConfig().url()); - assertEquals(prefix(tenantId) + DATASOURCE_NAME, tenantConfig.dataSourceConfig().name()); - assertEquals(prefix(tenantId) + DATASOURCE_PASSWORD, tenantConfig.dataSourceConfig().password()); - assertEquals(prefix(tenantId) + DATASOURCE_SCHEMA, tenantConfig.dataSourceConfig().schema()); - - assertArrayEquals(new String[] { CHAMPION_EMAILS_1, CHAMPION_EMAILS_2 }, tenantConfig.okrChampionEmails()); - assertEquals(DRIVER_CLASS_NAME, tenantConfig.dataSourceConfig().driverClassName()); + assertEquals(prefix(tenantId) + DATASOURCE_URL, + tenantConfig.dataSourceConfig() + .url()); + assertEquals(prefix(tenantId) + DATASOURCE_NAME, + tenantConfig.dataSourceConfig() + .name()); + assertEquals(prefix(tenantId) + DATASOURCE_PASSWORD, + tenantConfig.dataSourceConfig() + .password()); + assertEquals(prefix(tenantId) + DATASOURCE_SCHEMA, + tenantConfig.dataSourceConfig() + .schema()); + + assertArrayEquals(new String[]{CHAMPION_EMAILS_1, CHAMPION_EMAILS_2}, tenantConfig.okrChampionEmails()); + assertEquals(DRIVER_CLASS_NAME, + tenantConfig.dataSourceConfig() + .driverClassName()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java index 9d5a393af0..8d6ffb9dcd 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java @@ -12,12 +12,11 @@ public class TenantClientCustomizationProviderTest { @DisplayName("extractCssNameFromPropertyName() should return css name for valid property name") @ParameterizedTest - @CsvSource({ "pitc", "acme" }) + @CsvSource({"pitc", "acme"}) void extractCssNameFromPropertyNameShouldReturnCssNameForValidPropertyName(String tenantId) { // arrange - String propertyNameWithTenant = "okr.tenants." + tenantId - + ".clientcustomization.customstyles.my-css-property-name"; - TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[] {}, null); + String propertyNameWithTenant = "okr.tenants." + tenantId + ".clientcustomization.customstyles.my-css-property-name"; + TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[]{}, null); // act String cssName = provider.extractCssNameFromPropertyName(propertyNameWithTenant, tenantId); @@ -31,10 +30,10 @@ void extractCssNameFromPropertyNameShouldReturnCssNameForValidPropertyName(Strin void extractCssNameFromPropertyNameShouldThrowIllegalArgumentExceptionForInvalidPropertyName() { // arrange String propertyNameWithoutTenant = "okr.tenants.clientcustomization.customstyles.my-css-property-name"; - TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[] {}, null); + TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[]{}, null); // act + assert assertThrows(IllegalArgumentException.class, - () -> provider.extractCssNameFromPropertyName(propertyNameWithoutTenant, "pitc")); + () -> provider.extractCssNameFromPropertyName(propertyNameWithoutTenant, "pitc")); } } diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java index fe41e7e636..b3e10dfda6 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java @@ -1,6 +1,10 @@ package ch.puzzle.okr.multitenancy.customization; +import java.text.MessageFormat; +import java.util.Optional; + import ch.puzzle.okr.test.SpringIntegrationTest; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; @@ -8,9 +12,6 @@ import org.mockito.Mock; import org.springframework.core.env.Environment; -import java.text.MessageFormat; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; @@ -25,7 +26,7 @@ public class TenantClientCustomizationProviderTestIT { private static final String CUSTOM_STYLE_NAME = "okr-topbar-background-color"; private static final String CUSTOM_STYLE_VALUE = "css-custom-value"; - private final String[] tenantIds = { "pitc", "acme" }; + private final String[] tenantIds = {"pitc", "acme"}; @Mock private Environment env; @@ -43,8 +44,9 @@ private void setupPropertiesForTenantWithId(String id) { mockProperty("okr.tenants.{0}.clientcustomization.background-logo", BACKGROUND_LOGO, id); mockProperty("okr.tenants.{0}.clientcustomization.favicon", FAVICON, id); mockProperty("okr.tenants.{0}.clientcustomization.title", TITLE, id); - mockProperty("okr.tenants.{0}.clientcustomization.customstyles.okr-topbar-background-color", CUSTOM_STYLE_VALUE, - id); + mockProperty("okr.tenants.{0}.clientcustomization.customstyles.okr-topbar-background-color", + CUSTOM_STYLE_VALUE, + id); } private void mockProperty(String propertyName, String propertyValue, String tenantId) { @@ -58,7 +60,7 @@ private String prefix(String tenantId) { @DisplayName("getTenantClientCustomizationsById() should return TenantClientCustomization") @ParameterizedTest - @CsvSource({ "pitc", "acme" }) + @CsvSource({"pitc", "acme"}) void getTenantClientCustomizationsByIdShouldReturnTenantClientCustomization(String tenantId) { // arrange TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(tenantIds, env); @@ -82,9 +84,11 @@ private void assertTenantClientCustomization(TenantClientCustomization customiza private void assertCustomStyles(TenantClientCustomization customization, String tenantId) { assertNotNull(customization.customStyles()); - assertFalse(customization.customStyles().isEmpty()); + assertFalse(customization.customStyles() + .isEmpty()); - String customStyleValue = customization.customStyles().get(CUSTOM_STYLE_NAME); + String customStyleValue = customization.customStyles() + .get(CUSTOM_STYLE_NAME); assertEquals(prefix(tenantId) + CUSTOM_STYLE_VALUE, customStyleValue); } } diff --git a/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java b/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java index f73c3ecf83..8d88fb806b 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.security; import ch.puzzle.okr.multitenancy.TenantContext; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -28,7 +29,8 @@ void onSuccessPutsTokenFromAuthenticationSuccessEventInTenantContext() { Jwt tokenMock = mock(Jwt.class); AuthenticationSuccessEvent successEvent = new AuthenticationSuccessEvent(mock(Authentication.class)); - when(successEvent.getAuthentication().getPrincipal()).thenReturn(tokenMock); + when(successEvent.getAuthentication() + .getPrincipal()).thenReturn(tokenMock); JwtHelper jwtHelperMock = mock(JwtHelper.class); when(jwtHelperMock.getTenantFromToken(tokenMock)).thenReturn(TENANT_FROM_TOKEN); @@ -53,8 +55,7 @@ private void assertTenantFromTokenIsInTenantContext() { assertEquals(TENANT_FROM_TOKEN, TenantContext.getCurrentTenant()); } - private void verifyGetTenantFromTokenIsCalledWithTokenFromAuthenticationSuccessEvent(JwtHelper jwtHelper, - Jwt token) { + private void verifyGetTenantFromTokenIsCalledWithTokenFromAuthenticationSuccessEvent(JwtHelper jwtHelper, Jwt token) { verify(jwtHelper).getTenantFromToken(token); } diff --git a/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java index 35f0367478..d0550923d8 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java @@ -1,17 +1,20 @@ package ch.puzzle.okr.security; +import java.text.ParseException; +import java.util.Map; +import java.util.Optional; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantConfigProvider; -import com.nimbusds.jwt.JWTClaimsSet; -import jakarta.persistence.EntityNotFoundException; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.jwt.Jwt; -import java.text.ParseException; -import java.util.Map; -import java.util.Optional; +import com.nimbusds.jwt.JWTClaimsSet; + +import jakarta.persistence.EntityNotFoundException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -38,13 +41,18 @@ void getUserFromJwtExtractsUserDataFromToken() { // arrange Jwt tokenWithUserDataMock = mock(Jwt.class); when(tokenWithUserDataMock.getClaims()).thenReturn(Map.of( // - TOKEN_CLAIMS_KEY_FIRSTNAME, HANS, // - TOKEN_CLAIMS_KEY_LASTNAME, MUSTER, // - TOKEN_CLAIMS_KEY_EMAIL, EMAIL // + TOKEN_CLAIMS_KEY_FIRSTNAME, + HANS, // + TOKEN_CLAIMS_KEY_LASTNAME, + MUSTER, // + TOKEN_CLAIMS_KEY_EMAIL, + EMAIL // )); JwtHelper jwtHelper = new JwtHelper(null, // - TOKEN_CLAIMS_KEY_FIRSTNAME, TOKEN_CLAIMS_KEY_LASTNAME, TOKEN_CLAIMS_KEY_EMAIL); + TOKEN_CLAIMS_KEY_FIRSTNAME, + TOKEN_CLAIMS_KEY_LASTNAME, + TOKEN_CLAIMS_KEY_EMAIL); // act User userFromToken = jwtHelper.getUserFromJwt(tokenWithUserDataMock); @@ -63,7 +71,9 @@ void getUserFromJwtThrowsExceptionIfTokenNotContainsUserData() { Jwt tokenWithNoUserDataMock = mock(Jwt.class); JwtHelper jwtHelper = new JwtHelper(null, // - TOKEN_CLAIMS_KEY_FIRSTNAME, TOKEN_CLAIMS_KEY_LASTNAME, TOKEN_CLAIMS_KEY_EMAIL); + TOKEN_CLAIMS_KEY_FIRSTNAME, + TOKEN_CLAIMS_KEY_LASTNAME, + TOKEN_CLAIMS_KEY_EMAIL); // act + assert OkrResponseStatusException okrResponseStatusException = // @@ -82,9 +92,12 @@ void getTenantFromTokenReturnsTenantIfTenantFoundInTenantConfigProvider() { TenantConfigProvider tenantConfigProviderMock = mock(TenantConfigProvider.class); when(tenantConfigProviderMock.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig(PITC, // - new String[] {}, "jwkSetUri", "issuerUrl", // - "clientId", null) // + new TenantConfigProvider.TenantConfig(PITC, // + new String[]{}, + "jwkSetUri", + "issuerUrl", // + "clientId", + null) // )); JwtHelper jwtHelper = new JwtHelper(tenantConfigProviderMock, null, null, null); @@ -120,9 +133,12 @@ void getTenantFromJWTClaimsSetReturnsTenantIfTenantFoundInTenantConfigProvider() TenantConfigProvider tenantConfigProviderWithDataMock = mock(TenantConfigProvider.class); when(tenantConfigProviderWithDataMock.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig(PITC, // - new String[] {}, "jwkSetUri", "issuerUrl", // - "clientId", null) // + new TenantConfigProvider.TenantConfig(PITC, // + new String[]{}, + "jwkSetUri", + "issuerUrl", // + "clientId", + null) // )); JwtHelper jwtHelper = new JwtHelper(tenantConfigProviderWithDataMock, null, null, null); diff --git a/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java b/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java index f02c34d5c1..d7d641e75f 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java @@ -1,17 +1,19 @@ package ch.puzzle.okr.security; +import java.security.Key; +import java.util.List; +import java.util.Optional; + import ch.puzzle.okr.multitenancy.TenantConfigProvider; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.KeySourceException; import com.nimbusds.jose.proc.JWSKeySelector; import com.nimbusds.jose.proc.SecurityContext; import com.nimbusds.jwt.JWTClaimsSet; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.security.Key; -import java.util.List; -import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; @@ -40,7 +42,9 @@ void selectKeysThrowsExceptionIfTenantConfigIsNotFound() { // act + assert TenantJWSKeySelector selector = new TenantJWSKeySelector(emptyTenantConfigProviderMock, jwtHelperMock); IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class, // - () -> selector.selectKeys(jwsHeaderMock, jwtClaimsSetMock, securityContext)); + () -> selector.selectKeys(jwsHeaderMock, + jwtClaimsSetMock, + securityContext)); assertEquals(UNKNOWN_TENANT, illegalArgumentException.getLocalizedMessage()); } diff --git a/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java b/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java index 7c675c4204..f82188708d 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java @@ -1,14 +1,15 @@ package ch.puzzle.okr.security; +import java.util.Optional; + import ch.puzzle.okr.multitenancy.TenantConfigProvider; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtIssuerValidator; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -49,12 +50,16 @@ void validateReturnOAuth2TokenValidatorResultIfTenantConfigWithIssuerUrlIsFound( TenantConfigProvider tenantConfigProviderWithPitcConfig = mock(TenantConfigProvider.class); when(tenantConfigProviderWithPitcConfig.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig( // - PITC, new String[] {}, "jwkSetUri", // - ISSUER_URL, "clientId", null))); - - TenantJwtIssuerValidator tenantJwtIssuerValidator = new TenantJwtIssuerValidator( - tenantConfigProviderWithPitcConfig, jwtHelper) { + new TenantConfigProvider.TenantConfig( // + PITC, + new String[]{}, + "jwkSetUri", // + ISSUER_URL, + "clientId", + null))); + + TenantJwtIssuerValidator tenantJwtIssuerValidator = new TenantJwtIssuerValidator(tenantConfigProviderWithPitcConfig, + jwtHelper) { @Override JwtIssuerValidator createValidator(String issuer) { diff --git a/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java index 0a3850bf1f..1480eaadfe 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java @@ -1,14 +1,15 @@ package ch.puzzle.okr.security.helper; -import com.nimbusds.jwt.JWTClaimsSet; +import java.text.ParseException; +import java.util.Optional; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.text.ParseException; -import java.util.Optional; +import com.nimbusds.jwt.JWTClaimsSet; import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; @@ -85,7 +86,7 @@ void getTenantFromClaimsSetUsingClaimTenantReturnEmptyIfParsingOfClaimFailed() t @DisplayName("getTenantFromClaimsSetUsingClaimIss() return tenant if claim iss is found") @ParameterizedTest - @ValueSource(strings = { "https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc" }) + @ValueSource(strings = {"https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc"}) void getTenantFromClaimsSetUsingClaimIssReturnTenantIfClaimIssFound(String issUrl) throws ParseException { // arrange JWTClaimsSet claimsSetMock = mock(JWTClaimsSet.class); diff --git a/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java index 0b9c2215ce..cb8bf9b71a 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.security.helper; +import java.util.Optional; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,8 +9,6 @@ import org.junit.jupiter.params.provider.ValueSource; import org.springframework.security.oauth2.jwt.Jwt; -import java.util.Optional; - import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -70,7 +70,7 @@ void getTenantFromTokenUsingClaimTenantReturnEmptyIfClaimTenantFoundButValueIsNu @DisplayName("getTenantFromTokenUsingClaimIss() return tenant if claim iss is found") @ParameterizedTest - @ValueSource(strings = { "https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc" }) + @ValueSource(strings = {"https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc"}) void getTenantFromTokenUsingClaimIssReturnTenantIfClaimIssFound(String issUrl) { // arrange Jwt tokenMock = mock(Jwt.class); diff --git a/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java index 76f71a918e..e550fe5381 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java @@ -1,12 +1,12 @@ package ch.puzzle.okr.security.helper; +import java.util.Optional; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.*; public class UrlHelperTest { @@ -15,7 +15,7 @@ public class UrlHelperTest { @DisplayName("extractTenantFromIssUrl() return tenant if Url contains slash") @ParameterizedTest - @ValueSource(strings = { "https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc" }) + @ValueSource(strings = {"https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc"}) void extractTenantFromIssUrlReturnTenantIfUrlContainSlash(String issUrl) { // arrange diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java index 7e113dea5d..9d4cb341b7 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java @@ -1,10 +1,13 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.business.ActionBusinessService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -15,8 +18,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -34,15 +35,28 @@ class ActionAuthorizationServiceTest { AuthorizationService authorizationService; private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); - private final KeyResult keyResult = KeyResultMetric.Builder.builder().withId(10L).withTitle("KR Title").build(); - private final Action action1 = Action.Builder.builder().withId(1L).withAction("Neue Katze").withIsChecked(false) - .withPriority(0).withKeyResult(keyResult).build(); - private final Action action2 = Action.Builder.builder().withId(2L).withAction("Neues Lama").withIsChecked(true) - .withPriority(1).withKeyResult(keyResult).build(); + private final KeyResult keyResult = KeyResultMetric.Builder.builder() + .withId(10L) + .withTitle("KR Title") + .build(); + private final Action action1 = Action.Builder.builder() + .withId(1L) + .withAction("Neue Katze") + .withIsChecked(false) + .withPriority(0) + .withKeyResult(keyResult) + .build(); + private final Action action2 = Action.Builder.builder() + .withId(2L) + .withAction("Neues Lama") + .withIsChecked(true) + .withPriority(1) + .withKeyResult(keyResult) + .build(); private final List actionList = List.of(action1, action2); @ParameterizedTest - @ValueSource(booleans = { true, false }) + @ValueSource(booleans = {true, false}) void getActionsByKeyResultShouldReturnListOfActions(boolean isWriteable) { keyResult.setWriteable(isWriteable); when(actionBusinessService.getActionsByKeyResultId(anyLong())).thenReturn(actionList); @@ -72,10 +86,12 @@ void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(actionList.get(0).getKeyResult(), authorizationUser); + .hasRoleCreateOrUpdate(actionList.get(0) + .getKeyResult(), + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> actionAuthorizationService.createEntities(actionList)); + () -> actionAuthorizationService.createEntities(actionList)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -94,10 +110,12 @@ void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(actionList.get(0).getKeyResult(), authorizationUser); + .hasRoleCreateOrUpdate(actionList.get(0) + .getKeyResult(), + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> actionAuthorizationService.updateEntities(actionList)); + () -> actionAuthorizationService.updateEntities(actionList)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -118,10 +136,11 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByActionId(id, authorizationUser); + .hasRoleDeleteByActionId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> actionAuthorizationService.deleteActionByActionId(id)); + () -> actionAuthorizationService.deleteActionByActionId(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java index 4f0e3c77e4..ce340dc2fc 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java @@ -1,18 +1,19 @@ package ch.puzzle.okr.service.authorization; -import ch.puzzle.okr.test.TestHelper; +import java.util.Optional; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; -import java.util.Optional; - import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; import static ch.puzzle.okr.test.TestHelper.defaultUser; import static org.junit.jupiter.api.Assertions.*; @@ -49,9 +50,11 @@ private void resetOkrChampionStatus() { Optional userFromDb = userPersistenceService.findByEmail(EMAIL_WUNDERLAND); assertTrue(userFromDb.isPresent()); - userFromDb.get().setOkrChampion(false); + userFromDb.get() + .setOkrChampion(false); userPersistenceService.save(userFromDb.get()); - assertOkrChampionStatusInDb(userFromDb.get().getEmail(), false); + assertOkrChampionStatusInDb(userFromDb.get() + .getEmail(), false); } private void clearCache() { @@ -63,7 +66,9 @@ private void clearCache() { private void assertOkrChampionStatusInDb(String email, boolean expectedOkrChampionStatus) { var userInDb = userPersistenceService.findByEmail(email); assertTrue(userInDb.isPresent()); - assertEquals(expectedOkrChampionStatus, userInDb.get().isOkrChampion()); + assertEquals(expectedOkrChampionStatus, + userInDb.get() + .isOkrChampion()); } @Test @@ -87,10 +92,10 @@ void registerAuthorizationUserShouldAddAuthorizationUserToCache() { void registerAuthorizationUser_shouldSetOkrChampionsToFalse() { // arrange User user = User.Builder.builder() // - .withFirstname("Richard") // - .withLastname("Eberhard") // - .withEmail("richard.eberhard@puzzle.ch") // email not found in application-integration-test.properties - .build(); + .withFirstname("Richard") // + .withLastname("Eberhard") // + .withEmail("richard.eberhard@puzzle.ch") // email not found in application-integration-test.properties + .build(); userPersistenceService.getOrCreateUser(user); // updates input user with id from DB !!! @@ -98,14 +103,17 @@ void registerAuthorizationUser_shouldSetOkrChampionsToFalse() { AuthorizationUser processedUser = authorizationRegistrationService.updateOrAddAuthorizationUser(user); // assert - assertFalse(processedUser.user().isOkrChampion()); + assertFalse(processedUser.user() + .isOkrChampion()); Optional userFromDB = userPersistenceService.findByEmail(user.getEmail()); assertTrue(userFromDB.isPresent()); - assertFalse(userFromDB.get().isOkrChampion()); + assertFalse(userFromDB.get() + .isOkrChampion()); // cleanup - userPersistenceService.deleteById(userFromDB.get().getId()); + userPersistenceService.deleteById(userFromDB.get() + .getId()); } /* @@ -124,36 +132,37 @@ void registerAuthorizationUserShouldSetOkrChampionsToTrue() { // act // load user from db (by email) and set OkrChampion status based on property // "okr.tenants.pitc.user.champion.emails" from application-integration-test.properties file - AuthorizationUser processedUser = authorizationRegistrationService - .updateOrAddAuthorizationUser(User.Builder.builder() // - .withFirstname("Alice") // - .withLastname("Wunderland") // - .withEmail(EMAIL_WUNDERLAND) // user.champion.emails from - // application-integration-test.properties - .build()); + AuthorizationUser processedUser = authorizationRegistrationService.updateOrAddAuthorizationUser(User.Builder.builder() // + .withFirstname("Alice") // + .withLastname("Wunderland") // + .withEmail(EMAIL_WUNDERLAND) // user.champion.emails from + // application-integration-test.properties + .build()); // assert - assertTrue(processedUser.user().isOkrChampion()); - assertOkrChampionStatusInDb(processedUser.user().getEmail(), true); + assertTrue(processedUser.user() + .isOkrChampion()); + assertOkrChampionStatusInDb(processedUser.user() + .getEmail(), true); } @Test void registerAuthorizationUser_shouldSetFirstnameAndLastnameFromToken() { // arrange User user = User.Builder.builder() // - .withFirstname("Richard") // - .withLastname("Eberhard") // - .withEmail("richard.eberhard@puzzle.ch") // - .build(); + .withFirstname("Richard") // + .withLastname("Eberhard") // + .withEmail("richard.eberhard@puzzle.ch") // + .build(); userPersistenceService.save(user); String firstNameFromToken = "Richu"; String lastNameFromToken = "von Gunten"; User userFromToken = User.Builder.builder() // - .withFirstname(firstNameFromToken) // - .withLastname(lastNameFromToken) // - .withEmail("richard.eberhard@puzzle.ch") // - .build(); + .withFirstname(firstNameFromToken) // + .withLastname(lastNameFromToken) // + .withEmail("richard.eberhard@puzzle.ch") // + .build(); // act authorizationRegistrationService.updateOrAddAuthorizationUser(userFromToken); @@ -161,10 +170,13 @@ void registerAuthorizationUser_shouldSetFirstnameAndLastnameFromToken() { // assert Optional userFromDB = userPersistenceService.findByEmail(user.getEmail()); assertTrue(userFromDB.isPresent()); - assertEquals(userFromDB.get().getFirstname(), firstNameFromToken); - assertEquals(userFromDB.get().getLastname(), lastNameFromToken); + assertEquals(userFromDB.get() + .getFirstname(), firstNameFromToken); + assertEquals(userFromDB.get() + .getLastname(), lastNameFromToken); // cleanup - userPersistenceService.deleteById(userFromDB.get().getId()); + userPersistenceService.deleteById(userFromDB.get() + .getId()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java index 957b27540f..8bcaaafafb 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.authorization; +import java.util.Collection; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -13,6 +16,7 @@ import ch.puzzle.okr.security.JwtHelper; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -24,9 +28,6 @@ import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.oauth2.jwt.Jwt; -import java.util.Collection; -import java.util.List; - import static ch.puzzle.okr.ErrorKey.*; import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteForTeam; @@ -49,12 +50,30 @@ class AuthorizationServiceTest { @Mock JwtHelper jwtHelper; - private final List adminTeams = List.of(Team.Builder.builder().withName("Team 1").withId(1L).build(), - Team.Builder.builder().withName("Team 2").withId(2L).build()); - private final List memberTeams = List.of(Team.Builder.builder().withName("Team 3").withId(3L).build(), - Team.Builder.builder().withName("Team 4").withId(4L).build()); - private final List otherTeams = List.of(Team.Builder.builder().withName("Team 5").withId(5L).build(), - Team.Builder.builder().withName("Team 6").withId(6L).build()); + private final List adminTeams = List.of(Team.Builder.builder() + .withName("Team 1") + .withId(1L) + .build(), + Team.Builder.builder() + .withName("Team 2") + .withId(2L) + .build()); + private final List memberTeams = List.of(Team.Builder.builder() + .withName("Team 3") + .withId(3L) + .build(), + Team.Builder.builder() + .withName("Team 4") + .withId(4L) + .build()); + private final List otherTeams = List.of(Team.Builder.builder() + .withName("Team 5") + .withId(5L) + .build(), + Team.Builder.builder() + .withName("Team 6") + .withId(6L) + .build()); private final User user = defaultUserWithTeams(1L, adminTeams, memberTeams); private final User okrUser = defaultOkrChampion(1L); @@ -106,8 +125,8 @@ void getAuthorizationUserShouldReturnAuthorizationUser() { void hasRoleReadByObjectiveIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())) - .thenReturn(new Objective()); + when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())).thenReturn( + new Objective()); authorizationService.hasRoleReadByObjectiveId(id, authorizationUser); } @@ -117,19 +136,21 @@ void hasRoleReadByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "KeyResult"); + "KeyResult"); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())) - .thenThrow(expectedException); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())).thenThrow( + expectedException); OkrResponseStatusException actualException = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleReadByKeyResultId(id, authorizationUser)); + () -> authorizationService.hasRoleReadByKeyResultId(id, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_READ, "KeyResult")); assertEquals(UNAUTHORIZED, actualException.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(actualException.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(actualException.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(actualException.getReason())); } @Test @@ -137,9 +158,9 @@ void hasRoleReadByKeyResultIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "KeyResult"); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())) - .thenReturn(new Objective()); + "KeyResult"); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())).thenReturn( + new Objective()); authorizationService.hasRoleReadByKeyResultId(id, authorizationUser); } @@ -150,18 +171,20 @@ void hasRoleReadByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "Check-in"); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenThrow(expectedException); + "Check-in"); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())).thenThrow( + expectedException); OkrResponseStatusException actualException = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleReadByCheckInId(id, authorizationUser)); + () -> authorizationService.hasRoleReadByCheckInId(id, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_READ, "Check-in")); assertEquals(UNAUTHORIZED, actualException.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(actualException.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(actualException.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(actualException.getReason())); } @Test @@ -169,17 +192,21 @@ void hasRoleReadByCheckInIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "Check-in"); + "Check-in"); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenReturn(new Objective()); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())).thenReturn( + new Objective()); authorizationService.hasRoleReadByCheckInId(id, authorizationUser); } @Test void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedForAllObjectives() { - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(5L).build()).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(5L) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); authorizationService.hasRoleCreateOrUpdate(objective, authorizationUser); @@ -187,104 +214,164 @@ void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedForAllObjectives() { @Test void hasRoleCreateOrUpdateShouldThrowExceptionWhenMember() { - var id = memberTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); + var id = memberTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdate(objective, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdate(objective, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "Objective")); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedForKeyResults() { - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(1L).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(1L) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(keyResult, authorizationUser); } @Test void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedAsAdminForKeyResults() { - var id = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); + var id = adminTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(keyResult, authorizationUser); } @Test void hasRoleCreateOrUpdateShouldThorwExceptionWhenNotAuthorizedForKeyResults() { - var id = otherTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); + var id = otherTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdate(keyResult, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdate(keyResult, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "KeyResult")); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedAsAdminForTeamCheckIns() { - var id = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); - CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); + var id = adminTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withKeyResult(keyResult) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult() + .getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(checkIn, authorizationUser); } @Test void hasRoleCreateOrUpdateShouldThrowExceptionWhenMemberForTeamCheckIns() { - var id = memberTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); - CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); + var id = memberTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withKeyResult(keyResult) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult() + .getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdate(checkIn, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdate(checkIn, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "Check-in")); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void hasRoleCreateOrUpdateByObjectiveIdShouldPassThroughWhenAuthorizedForAllObjectives() { Long id = 13L; - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(5L).build()).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(5L) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())).thenReturn(objective); @@ -294,8 +381,13 @@ void hasRoleCreateOrUpdateByObjectiveIdShouldPassThroughWhenAuthorizedForAllObje @Test void hasRoleCreateOrUpdateByObjectiveIdShouldPassThroughWhenAuthorizedAsAdmin() { - var id = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); + var id = adminTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())).thenReturn(objective); @@ -305,26 +397,37 @@ void hasRoleCreateOrUpdateByObjectiveIdShouldPassThroughWhenAuthorizedAsAdmin() @Test void hasRoleCreateOrUpdateByObjectiveIdShouldThrowExceptionWhenAuthorizedAsMember() { - var id = memberTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); + var id = memberTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdateByObjectiveId(id, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdateByObjectiveId(id, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "Objective")); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedToWriteAllObjectives() { - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(5L).build()).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(5L) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); assertTrue(authorizationService.hasRoleWriteForTeam(objective, authorizationUser)); @@ -332,8 +435,13 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedToWriteAllObjectives() { @Test void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedAsAdmin() { - var id = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); + var id = adminTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); assertTrue(authorizationService.hasRoleWriteForTeam(objective, authorizationUser)); @@ -341,8 +449,13 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedAsAdmin() { @Test void hasRoleWriteForTeamShouldReturnFalseWhenAuthorizedAsMember() { - var id = memberTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); + var id = memberTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); assertFalse(authorizationService.hasRoleWriteForTeam(objective, authorizationUser)); @@ -350,77 +463,127 @@ void hasRoleWriteForTeamShouldReturnFalseWhenAuthorizedAsMember() { @Test void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedToWriteAllKeyResults() { - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(4L).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(4L) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(keyResult, authorizationUser)); } @Test void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedAsAdminForKeyResults() { - var id = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); + var id = adminTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(keyResult, authorizationUser)); } @Test void hasRoleWriteForTeamShouldReturnFalseWhenNotAuthorizedToWriteKeyResults() { - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(5L).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(5L) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); AuthorizationUser authorizationUser = mockAuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertFalse(authorizationService.hasRoleWriteForTeam(keyResult, authorizationUser)); } @Test void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedToWriteAllCheckIns() { - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(5L).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); - CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(5L) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withKeyResult(keyResult) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @Test void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedAsAdminForCheckIns() { - var id = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(id).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); - CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); + var id = adminTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(id) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withKeyResult(keyResult) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @Test void hasRoleWriteForTeamShouldReturnFalseWhenNotAuthorizedToWriteCheckIns() { - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(5L).build()).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); - CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(5L) + .build()) + .build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withObjective(objective) + .build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withKeyResult(keyResult) + .build(); AuthorizationUser authorizationUser = mockAuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult() + .getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertFalse(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @@ -428,7 +591,11 @@ void hasRoleWriteForTeamShouldReturnFalseWhenNotAuthorizedToWriteCheckIns() { @Test void hasRoleDeleteByObjectiveIdShouldPassThroughWhenAuthorizedForAllObjectives() { Long id = 13L; - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(5L).build()).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(5L) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())).thenReturn(objective); @@ -439,57 +606,78 @@ void hasRoleDeleteByObjectiveIdShouldPassThroughWhenAuthorizedForAllObjectives() @Test void hasRoleDeleteByKeyResultIdShouldPassThroughWhenAuthorizedForAllTeamsKeyResults() { Long id = 13L; - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(1L).build()).build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(1L) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrUser); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())).thenReturn( + objective); authorizationService.hasRoleDeleteByKeyResultId(id, authorizationUser); } @Test void hasRoleDeleteByCheckInIdShouldPassThroughWhenAuthorizedAsAdminForTeamCheckIns() { - var id = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(1L).build()).build(); + var id = adminTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(1L) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())).thenReturn( + objective); authorizationService.hasRoleDeleteByCheckInId(id, authorizationUser); } @Test void hasRoleDeleteByCheckInIdShouldPassThroughWhenAuthorizedAsMemberForTeamCheckIns() { - var id = memberTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(1L).build()).build(); + var id = memberTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(1L) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())).thenReturn( + objective); authorizationService.hasRoleDeleteByCheckInId(id, authorizationUser); } @Test void hasRoleDeleteByKeyResultIdShouldThrowExceptionWhenNotAuthorized() { - var memeberId = memberTeams.get(0).getId(); - var otherId = otherTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(memeberId).build()) - .build(); + var memeberId = memberTeams.get(0) + .getId(); + var otherId = otherTeams.get(0) + .getId(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder() + .withId(memeberId) + .build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(otherId), eq(authorizationUser), any())) - .thenReturn(objective); + .thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleDeleteByKeyResultId(otherId, authorizationUser)); + () -> authorizationService.hasRoleDeleteByKeyResultId(otherId, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_DELETE, "KeyResult")); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } private void setSecurityContext(Jwt token) { diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java index c2cf02731e..ddc6812260 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java @@ -3,6 +3,7 @@ import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.service.business.CheckInBusinessService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -56,10 +57,11 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleReadByCheckInId(id, authorizationUser); + .hasRoleReadByCheckInId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.getEntityById(id)); + () -> checkInAuthorizationService.getEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -78,10 +80,11 @@ void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(checkInMetric, authorizationUser); + .hasRoleCreateOrUpdate(checkInMetric, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.createEntity(checkInMetric)); + () -> checkInAuthorizationService.createEntity(checkInMetric)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -102,10 +105,12 @@ void updateEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(checkInMetric, authorizationUser); + .hasRoleCreateOrUpdate(checkInMetric, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.updateEntity(id, checkInMetric)); + () -> checkInAuthorizationService.updateEntity(id, + checkInMetric)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -124,10 +129,11 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByCheckInId(id, authorizationUser); + .hasRoleDeleteByCheckInId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.deleteEntityById(id)); + () -> checkInAuthorizationService.deleteEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java index 2358188144..8b43ae479a 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java @@ -4,6 +4,7 @@ import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.CompletedBusinessService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -30,8 +31,13 @@ class CompletedAuthorizationServiceTest { private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); private final Long objectiveId = 12L; - private final Completed newCompleted = Completed.Builder.builder().withId(5L) - .withObjective(Objective.Builder.builder().withId(objectiveId).withTitle("Completed 1").build()).build(); + private final Completed newCompleted = Completed.Builder.builder() + .withId(5L) + .withObjective(Objective.Builder.builder() + .withId(objectiveId) + .withTitle("Completed 1") + .build()) + .build(); @Test void createCompletedShouldReturnObjectiveWhenAuthorized() { @@ -47,10 +53,11 @@ void createCompletedShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdateByObjectiveId(objectiveId, authorizationUser); + .hasRoleCreateOrUpdateByObjectiveId(objectiveId, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> completedAuthorizationService.createCompleted(newCompleted)); + () -> completedAuthorizationService.createCompleted(newCompleted)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -67,10 +74,11 @@ void deleteCompletedByObjectiveIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByObjectiveId(objectiveId, authorizationUser); + .hasRoleDeleteByObjectiveId(objectiveId, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> completedAuthorizationService.deleteCompletedByObjectiveId(objectiveId)); + () -> completedAuthorizationService.deleteCompletedByObjectiveId(objectiveId)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java index 2888e08a8a..69898f4b0d 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java @@ -1,10 +1,13 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultWithActionList; import ch.puzzle.okr.service.business.KeyResultBusinessService; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,8 +17,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static ch.puzzle.okr.test.KeyResultTestHelpers.checkIn1; import static ch.puzzle.okr.test.KeyResultTestHelpers.metricKeyResult; import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; @@ -50,10 +51,11 @@ void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(metricKeyResult, authorizationUser); + .hasRoleCreateOrUpdate(metricKeyResult, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.createEntity(metricKeyResult)); + () -> keyResultAuthorizationService.createEntity(metricKeyResult)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -85,10 +87,11 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleReadByKeyResultId(id, authorizationUser); + .hasRoleReadByKeyResultId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.getEntityById(id)); + () -> keyResultAuthorizationService.getEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -97,11 +100,13 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { void updateEntitiesShouldReturnUpdatedKeyResultWhenAuthorized() { Long id = 13L; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(keyResultBusinessService.updateEntities(id, metricKeyResult, List.of())) - .thenReturn(new KeyResultWithActionList(metricKeyResult, List.of())); + when(keyResultBusinessService.updateEntities(id, metricKeyResult, List.of())).thenReturn( + new KeyResultWithActionList(metricKeyResult, + List.of())); - KeyResultWithActionList KeyResult = keyResultAuthorizationService.updateEntities(id, metricKeyResult, - List.of()); + KeyResultWithActionList KeyResult = keyResultAuthorizationService.updateEntities(id, + metricKeyResult, + List.of()); assertEquals(metricKeyResult, KeyResult.keyResult()); } @@ -111,10 +116,13 @@ void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(metricKeyResult, authorizationUser); + .hasRoleCreateOrUpdate(metricKeyResult, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.updateEntities(id, metricKeyResult, List.of())); + () -> keyResultAuthorizationService.updateEntities(id, + metricKeyResult, + List.of())); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -122,10 +130,11 @@ void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { @Test void updateEntityShouldThrowException() { ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.updateEntity(1L, metricKeyResult)); + () -> keyResultAuthorizationService.updateEntity(1L, + metricKeyResult)); assertEquals(BAD_REQUEST, exception.getStatusCode()); - assertEquals("unsupported method in class " + KeyResultAuthorizationService.class.getSimpleName() - + ", use updateEntities() instead", exception.getReason()); + assertEquals("unsupported method in class " + KeyResultAuthorizationService.class.getSimpleName() + ", use updateEntities() instead", + exception.getReason()); } @Test @@ -142,10 +151,11 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByKeyResultId(id, authorizationUser); + .hasRoleDeleteByKeyResultId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.deleteEntityById(id)); + () -> keyResultAuthorizationService.deleteEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java index 04b72412f9..aff1ae7cc4 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java @@ -3,6 +3,7 @@ import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.ObjectiveBusinessService; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -28,7 +29,10 @@ class ObjectiveAuthorizationServiceTest { AuthorizationService authorizationService; private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); - private final Objective newObjective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").build(); + private final Objective newObjective = Objective.Builder.builder() + .withId(5L) + .withTitle("Objective 1") + .build(); @Test void createEntityShouldReturnObjectiveWhenAuthorized() { @@ -44,10 +48,11 @@ void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(newObjective, authorizationUser); + .hasRoleCreateOrUpdate(newObjective, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.createEntity(newObjective)); + () -> objectiveAuthorizationService.createEntity(newObjective)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -79,10 +84,11 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleReadByObjectiveId(id, authorizationUser); + .hasRoleReadByObjectiveId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.getEntityById(id)); + () -> objectiveAuthorizationService.getEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -103,10 +109,12 @@ void updateEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(newObjective, authorizationUser); + .hasRoleCreateOrUpdate(newObjective, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.updateEntity(id, newObjective)); + () -> objectiveAuthorizationService.updateEntity(id, + newObjective)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -132,10 +140,11 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByObjectiveId(id, authorizationUser); + .hasRoleDeleteByObjectiveId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.deleteEntityById(id)); + () -> objectiveAuthorizationService.deleteEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -146,15 +155,18 @@ void duplicateEntityShouldThrowExceptionWhenNotAuthorized() { // arrange Long idExistingObjective = 13L; String reason = "junit test reason"; - Objective objective = Objective.Builder.builder().build(); + Objective objective = Objective.Builder.builder() + .build(); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(objective, authorizationUser); + .hasRoleCreateOrUpdate(objective, + authorizationUser); // act ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.duplicateEntity(idExistingObjective, objective)); + () -> objectiveAuthorizationService.duplicateEntity(idExistingObjective, + objective)); // assert assertEquals(UNAUTHORIZED, exception.getStatusCode()); @@ -168,18 +180,22 @@ void duplicateEntityShouldReturnDuplicatedObjectiveWhenAuthorized() { Long idExistingObjective = 13L; Objective newObjectiveWithoutKeyResults = Objective.Builder.builder() // - .withTitle("Objective without KeyResults").build(); + .withTitle("Objective without KeyResults") + .build(); Objective newObjectiveWithKeyResults = Objective.Builder.builder() // - .withId(42L).withTitle("Objective with Id and KeyResults").build(); + .withId(42L) + .withTitle("Objective with Id and KeyResults") + .build(); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(objectiveBusinessService.duplicateObjective(idExistingObjective, newObjectiveWithoutKeyResults, - authorizationUser)).thenReturn(newObjectiveWithKeyResults); + when(objectiveBusinessService.duplicateObjective(idExistingObjective, + newObjectiveWithoutKeyResults, + authorizationUser)).thenReturn(newObjectiveWithKeyResults); // act Objective objective = objectiveAuthorizationService.duplicateEntity(idExistingObjective, - newObjectiveWithoutKeyResults); + newObjectiveWithoutKeyResults); // assert assertEquals(newObjectiveWithKeyResults, objective); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java index e2ced700f8..baa1107707 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java @@ -1,9 +1,12 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.service.business.OverviewBusinessService; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -13,8 +16,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.*; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -35,12 +36,17 @@ class OverviewAuthorizationServiceTest { private final long adminTeamId = 5L; private final long memberTeamId = 6L; - private final AuthorizationUser authorizationUser = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(defaultTeam(adminTeamId)), List.of(defaultTeam(memberTeamId)))); + private final AuthorizationUser authorizationUser = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(defaultTeam(adminTeamId)), + List.of(defaultTeam(memberTeamId)))); private final AuthorizationUser okrChampionUser = new AuthorizationUser(defaultOkrChampion(2L)); private final Overview overview = Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(adminTeamId).build()) - .withObjectiveTitle("Objective 1").build(); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(adminTeamId) + .build()) + .withObjectiveTitle("Objective 1") + .build(); @DisplayName("getFilteredOverview() should do nothing when OverviewId is null") @Test @@ -50,8 +56,8 @@ void getFilteredOverviewShouldDoNothingWhenOverviewIdIsNull() { when(overviewWithoutOverviewId.getOverviewId()).thenReturn(null); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))) - .thenReturn(List.of(overviewWithoutOverviewId)); + when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))).thenReturn(List + .of(overviewWithoutOverviewId)); // act overviewAuthorizationService.getFilteredOverview(1L, List.of(5L), ""); @@ -70,8 +76,8 @@ void getFilteredOverviewShouldDoNothingWhenTeamIdIsNull() { when(overviewWithoutTeamId.getOverviewId()).thenReturn(overviewId); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))) - .thenReturn(List.of(overviewWithoutTeamId)); + when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))).thenReturn(List + .of(overviewWithoutTeamId)); // act overviewAuthorizationService.getFilteredOverview(1L, List.of(5L), ""); @@ -90,8 +96,8 @@ void getFilteredOverviewShouldDoNothingWhenObjectiveIdIsNull() { when(overviewWithoutObjectiveId.getOverviewId()).thenReturn(overviewId); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))) - .thenReturn(List.of(overviewWithoutObjectiveId)); + when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))).thenReturn(List + .of(overviewWithoutObjectiveId)); // act overviewAuthorizationService.getFilteredOverview(1L, List.of(5L), ""); @@ -144,13 +150,12 @@ void getFilteredOverviewShouldReturnEmptyListWhenNotAuthorized() { } @ParameterizedTest - @ValueSource(booleans = { true, false }) + @ValueSource(booleans = {true, false}) void hasWriteAllAccessShouldReturnHasRoleWriteAll(boolean hasRoleWriteAll) { if (hasRoleWriteAll) { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(okrChampionUser); } else { - when(authorizationService.updateOrAddAuthorizationUser()) - .thenReturn(mockAuthorizationUser(defaultUser(adminTeamId))); + when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(mockAuthorizationUser(defaultUser(adminTeamId))); } assertEquals(hasRoleWriteAll, overviewAuthorizationService.hasWriteAllAccess()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java index 6fb9ec4f34..b20f3466bf 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java @@ -1,9 +1,12 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.TeamBusinessService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -13,8 +16,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -33,13 +34,19 @@ class TeamAuthorizationServiceTest { private TeamAuthorizationService teamAuthorizationService; private final AuthorizationUser okrChampionUser = new AuthorizationUser(defaultOkrChampion(1L)); - private final Team teamUnderTest = Team.Builder.builder().withId(5L).withName("Team").build(); - private final AuthorizationUser adminUser = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(teamUnderTest), List.of())); - private final AuthorizationUser memberUser = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(), List.of(teamUnderTest))); - private final AuthorizationUser userWithNoTeams = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(), List.of())); + private final Team teamUnderTest = Team.Builder.builder() + .withId(5L) + .withName("Team") + .build(); + private final AuthorizationUser adminUser = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(teamUnderTest), + List.of())); + private final AuthorizationUser memberUser = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(), + List.of(teamUnderTest))); + private final AuthorizationUser userWithNoTeams = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(), + List.of())); @Test void createEntityShouldReturnTeam() { @@ -75,7 +82,8 @@ void updateEntityShouldThrowExceptionWhenAuthorizedAsMemberUser() { Long id = 13L; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(memberUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> teamAuthorizationService.updateEntity(teamUnderTest, id)); + () -> teamAuthorizationService.updateEntity(teamUnderTest, + id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals("NOT_AUTHORIZED_TO_WRITE", exception.getReason()); } @@ -85,7 +93,8 @@ void updateEntityShouldThrowExceptionWhenAuthorizedAsUserWithNoTeams() { Long id = 13L; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(userWithNoTeams); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> teamAuthorizationService.updateEntity(teamUnderTest, id)); + () -> teamAuthorizationService.updateEntity(teamUnderTest, + id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals("NOT_AUTHORIZED_TO_WRITE", exception.getReason()); } @@ -118,13 +127,13 @@ void deleteEntityByIdShouldThrowExceptionWhenAuthorizedAsUserWithNoTeams() { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(userWithNoTeams); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> teamAuthorizationService.deleteEntity(id)); + () -> teamAuthorizationService.deleteEntity(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals("NOT_AUTHORIZED_TO_DELETE", exception.getReason()); } @ParameterizedTest - @ValueSource(booleans = { true, false }) + @ValueSource(booleans = {true, false}) void getAllTeamsShouldReturnAllTeams(boolean isWriteable) { List teamList = List.of(teamUnderTest, teamUnderTest); if (isWriteable) { @@ -151,8 +160,9 @@ void addUsersToTeam_shouldCallTeamBusinessService() { var adminTeamId = 1L; var adminTeam = defaultTeam(adminTeamId); var usersList = List.of(1L, 2L); - when(authorizationService.updateOrAddAuthorizationUser()) - .thenReturn(new AuthorizationUser(defaultUserWithTeams(1L, List.of(adminTeam), List.of()))); + when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(new AuthorizationUser(defaultUserWithTeams(1L, + List.of(adminTeam), + List.of()))); teamAuthorizationService.addUsersToTeam(adminTeamId, usersList); verify(teamBusinessService, times(1)).addUsersToTeam(adminTeamId, usersList); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java index 8575cdd561..45b8e1a377 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java @@ -1,17 +1,18 @@ package ch.puzzle.okr.service.authorization; +import java.util.List; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.UserBusinessService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -51,10 +52,26 @@ void getAllUsers_shouldSetTeamWritableCorrectly() { when(teamAuthorizationService.isUserWriteAllowed(memberTeamId)).thenReturn(false); List users = userAuthorizationService.getAllUsers(); - assertTrue(users.get(0).getUserTeamList().get(0).getTeam().isWriteable()); - assertFalse(users.get(0).getUserTeamList().get(1).getTeam().isWriteable()); - assertTrue(users.get(1).getUserTeamList().get(0).getTeam().isWriteable()); - assertFalse(users.get(1).getUserTeamList().get(1).getTeam().isWriteable()); + assertTrue(users.get(0) + .getUserTeamList() + .get(0) + .getTeam() + .isWriteable()); + assertFalse(users.get(0) + .getUserTeamList() + .get(1) + .getTeam() + .isWriteable()); + assertTrue(users.get(1) + .getUserTeamList() + .get(0) + .getTeam() + .isWriteable()); + assertFalse(users.get(1) + .getUserTeamList() + .get(1) + .getTeam() + .isWriteable()); } @Test @@ -79,7 +96,7 @@ void setOkrChampion_shouldThrowErrorIfLoggedInUserIsNotOkrChampion() { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(new AuthorizationUser(loggedInUser)); assertThrows(OkrResponseStatusException.class, - () -> userAuthorizationService.setIsOkrChampion(user.getId(), true)); + () -> userAuthorizationService.setIsOkrChampion(user.getId(), true)); } @Test @@ -104,6 +121,6 @@ void createUsers_shouldThrowErrorIfLoggedInUserIsNotOkrChampion() { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(new AuthorizationUser(loggedInUser)); assertThrows(OkrResponseStatusException.class, - () -> userAuthorizationService.createUsers(List.of(user, user2))); + () -> userAuthorizationService.createUsers(List.of(user, user2))); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java index 958eaac311..1b8cd5ea86 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java @@ -2,6 +2,7 @@ import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantConfigProvider; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -21,16 +22,16 @@ void setup() { void updateUserFromWithTokenData() { // arrange User userFromDB = User.Builder.builder() // - .withId(23L) // - .withFirstname("firstname_from_db") // - .withLastname("lastname_from_db") // - .withEmail("a@b.ch") // - .build(); + .withId(23L) // + .withFirstname("firstname_from_db") // + .withLastname("lastname_from_db") // + .withEmail("a@b.ch") // + .build(); User userFromToken = User.Builder.builder() // - .withFirstname("firstname_from_token") // - .withLastname("lastname_from_token") // - .build(); + .withFirstname("firstname_from_token") // + .withLastname("lastname_from_token") // + .build(); // act User updatedUser = helper.setFirstLastNameFromToken(userFromDB, userFromToken); @@ -45,9 +46,15 @@ void updateUserFromWithTokenData() { @Test void updateUserAsNoChampion() { // arrange - User noChampionUser = User.Builder.builder().withEmail("no@champions.ch").build(); + User noChampionUser = User.Builder.builder() + .withEmail("no@champions.ch") + .build(); TenantConfigProvider.TenantConfig tenantConfig = new TenantConfigProvider.TenantConfig(null, // - new String[] { "yes@champions.ch" }, null, null, null, null); + new String[]{"yes@champions.ch"}, + null, + null, + null, + null); // act User updatedUser = helper.setOkrChampionFromProperties(noChampionUser, tenantConfig); @@ -59,9 +66,15 @@ void updateUserAsNoChampion() { @Test void updateUserAsChampion() { // arrange - User championUser = User.Builder.builder().withEmail("yes@champions.ch").build(); + User championUser = User.Builder.builder() + .withEmail("yes@champions.ch") + .build(); TenantConfigProvider.TenantConfig tenantConfig = new TenantConfigProvider.TenantConfig(null, // - new String[] { "yes@champions.ch" }, null, null, null, null); + new String[]{"yes@champions.ch"}, + null, + null, + null, + null); // act User updatedUser = helper.setOkrChampionFromProperties(championUser, tenantConfig); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java index 41e8151e4c..cec5ec3462 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.service.business; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Unit; import ch.puzzle.okr.models.authorization.AuthorizationUser; @@ -7,14 +9,13 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.persistence.ActionPersistenceService; import ch.puzzle.okr.service.validation.ActionValidationService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertIterableEquals; @@ -32,12 +33,27 @@ class ActionBusinessServiceTest { @InjectMocks private ActionBusinessService actionBusinessService; - private KeyResult metricKeyResult = KeyResultMetric.Builder.builder().withBaseline(10D).withStretchGoal(50D) - .withUnit(Unit.CHF).withId(8L).withTitle("Keyresult Metric").build(); - private Action action1 = Action.Builder.builder().withId(1L).withAction("Neue Katze").withIsChecked(false) - .withPriority(0).withKeyResult(metricKeyResult).build(); - private Action action2 = Action.Builder.builder().withId(2L).withAction("Neues Lama").withIsChecked(true) - .withPriority(1).withKeyResult(metricKeyResult).build(); + private KeyResult metricKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(10D) + .withStretchGoal(50D) + .withUnit(Unit.CHF) + .withId(8L) + .withTitle("Keyresult Metric") + .build(); + private Action action1 = Action.Builder.builder() + .withId(1L) + .withAction("Neue Katze") + .withIsChecked(false) + .withPriority(0) + .withKeyResult(metricKeyResult) + .build(); + private Action action2 = Action.Builder.builder() + .withId(2L) + .withAction("Neues Lama") + .withIsChecked(true) + .withPriority(1) + .withKeyResult(metricKeyResult) + .build(); private List actionList = List.of(action1, action2); @Test @@ -78,8 +94,12 @@ void shouldUpdateMultipleActionsNoKeyResult() { @Test void shouldCreateActionWhenUpdateWithNoId() { - Action action = Action.Builder.builder().withAction("Neue Katze").withPriority(0).withIsChecked(false) - .withKeyResult(metricKeyResult).build(); + Action action = Action.Builder.builder() + .withAction("Neue Katze") + .withPriority(0) + .withIsChecked(false) + .withKeyResult(metricKeyResult) + .build(); actionBusinessService.updateEntities(List.of(action)); verify(actionPersistenceService, times(1)).save(action); @@ -95,10 +115,18 @@ void shouldUpdateMultipleActionsNormal() { @Test void shouldCreateMultipleActions() { - Action newAction1 = Action.Builder.builder().withAction("Neuer Drucker").withKeyResult(metricKeyResult) - .withPriority(0).withIsChecked(false).build(); - Action newAction2 = Action.Builder.builder().withAction("Neues Papier").withKeyResult(metricKeyResult) - .withPriority(1).withIsChecked(false).build(); + Action newAction1 = Action.Builder.builder() + .withAction("Neuer Drucker") + .withKeyResult(metricKeyResult) + .withPriority(0) + .withIsChecked(false) + .build(); + Action newAction2 = Action.Builder.builder() + .withAction("Neues Papier") + .withKeyResult(metricKeyResult) + .withPriority(1) + .withIsChecked(false) + .build(); when(actionPersistenceService.save(newAction1)).thenReturn(action1); when(actionPersistenceService.save(newAction2)).thenReturn(action2); @@ -112,8 +140,12 @@ void shouldCreateMultipleActions() { @Test void shouldCreateOneAction() { - Action newAction1 = Action.Builder.builder().withAction("Neuer Drucker").withKeyResult(metricKeyResult) - .withPriority(0).withIsChecked(false).build(); + Action newAction1 = Action.Builder.builder() + .withAction("Neuer Drucker") + .withKeyResult(metricKeyResult) + .withPriority(0) + .withIsChecked(false) + .build(); when(actionPersistenceService.save(newAction1)).thenReturn(action1); List createdActions = actionBusinessService.createEntities(List.of(newAction1)); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java index 29b57b5aed..9ced1e23f9 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java @@ -1,16 +1,17 @@ package ch.puzzle.okr.service.business; +import java.util.List; + import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; import ch.puzzle.okr.service.persistence.AlignmentSelectionPersistenceService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; @@ -24,9 +25,15 @@ class AlignmentSelectionBusinessServiceTest { AlignmentSelectionPersistenceService alignmentSelectionPersistenceService; private static AlignmentSelection createAlignmentSelection() { - return AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(9L, 15L)) - .withTeamId(5L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 9").withQuarterId(2L) - .withQuarterLabel("GJ 23/24-Q1").withKeyResultTitle("Key Result 15").build(); + return AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(9L, 15L)) + .withTeamId(5L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 9") + .withQuarterId(2L) + .withQuarterLabel("GJ 23/24-Q1") + .withKeyResultTitle("Key Result 15") + .build(); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java index 9a6d397863..b20c5a0640 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java @@ -12,6 +12,7 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.CheckInPersistenceService; import ch.puzzle.okr.service.validation.CheckInValidationService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -36,18 +37,41 @@ class CheckInBusinessServiceTest { @InjectMocks private CheckInBusinessService checkInBusinessService; - private User user = User.Builder.builder().withEmail("Email").withFirstname("Firstname").withLastname("Lastname") - .build(); - private KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder().withCommitZone("Baum") - .withStretchZone("Wald").withId(7L).withTitle("Keyresult Ordinal").build(); - private KeyResult metricKeyResult = KeyResultMetric.Builder.builder().withBaseline(10D).withStretchGoal(50D) - .withUnit(Unit.CHF).withId(8L).withTitle("Keyresult Metric").build(); - private CheckIn checkInMetric = CheckInMetric.Builder.builder().withValue(30D).withId(1L).withConfidence(5) - .withChangeInfo("ChangeInfo1").withInitiatives("Initiatives1").withCreatedBy(user) - .withKeyResult(metricKeyResult).build(); - private CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder().withZone(Zone.COMMIT).withConfidence(5) - .withChangeInfo("ChangeInfo2").withInitiatives("Initiatives2").withCreatedBy(user) - .withKeyResult(ordinalKeyResult).build(); + private User user = User.Builder.builder() + .withEmail("Email") + .withFirstname("Firstname") + .withLastname("Lastname") + .build(); + private KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withStretchZone("Wald") + .withId(7L) + .withTitle("Keyresult Ordinal") + .build(); + private KeyResult metricKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(10D) + .withStretchGoal(50D) + .withUnit(Unit.CHF) + .withId(8L) + .withTitle("Keyresult Metric") + .build(); + private CheckIn checkInMetric = CheckInMetric.Builder.builder() + .withValue(30D) + .withId(1L) + .withConfidence(5) + .withChangeInfo("ChangeInfo1") + .withInitiatives("Initiatives1") + .withCreatedBy(user) + .withKeyResult(metricKeyResult) + .build(); + private CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() + .withZone(Zone.COMMIT) + .withConfidence(5) + .withChangeInfo("ChangeInfo2") + .withInitiatives("Initiatives2") + .withCreatedBy(user) + .withKeyResult(ordinalKeyResult) + .build(); @Test void shouldGetMetricCheckIn() { @@ -132,8 +156,8 @@ void shouldDeleteCheckIn() { @Test void shouldGetCheckInsByKeyResultId() { checkInBusinessService.getCheckInsByKeyResultId(this.metricKeyResult.getId()); - verify(checkInPersistenceService, times(1)) - .getCheckInsByKeyResultIdOrderByCheckInDateDesc(this.metricKeyResult.getId()); + verify(checkInPersistenceService, times(1)).getCheckInsByKeyResultIdOrderByCheckInDateDesc(this.metricKeyResult + .getId()); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java index 0302b92e97..c772525a7f 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java @@ -4,6 +4,7 @@ import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.service.persistence.CompletedPersistenceService; import ch.puzzle.okr.service.validation.CompletedValidationService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -23,22 +24,30 @@ class CompletedBusinessServiceTest { @Mock CompletedValidationService validator; - Completed successfulCompleted = Completed.Builder.builder().withId(1L) - .withObjective(Objective.Builder.builder().withId(3L).withTitle("Gute Lernende").build()) - .withComment("Wir haben es gut geschafft").build(); + Completed successfulCompleted = Completed.Builder.builder() + .withId(1L) + .withObjective(Objective.Builder.builder() + .withId(3L) + .withTitle("Gute Lernende") + .build()) + .withComment("Wir haben es gut geschafft") + .build(); - @InjectMocks - @Spy + @InjectMocks @Spy private CompletedBusinessService completedBusinessService; @Test void saveSuccessFulCompleted() { - Mockito.when(completedPersistenceService.save(any())).thenReturn(successfulCompleted); + Mockito.when(completedPersistenceService.save(any())) + .thenReturn(successfulCompleted); Completed completed = Completed.Builder.builder() - .withObjective(Objective.Builder.builder().withId(4L) - .withTitle("Build a company culture that kills the competition.").build()) - .withComment("Das ist gut").build(); + .withObjective(Objective.Builder.builder() + .withId(4L) + .withTitle("Build a company culture that kills the competition.") + .build()) + .withComment("Das ist gut") + .build(); Completed savedCompleted = completedBusinessService.createCompleted(completed); verify(completedPersistenceService, times(1)).save(completed); @@ -47,10 +56,15 @@ void saveSuccessFulCompleted() { @Test void shouldBePossibleToSaveCompletedWithoutComment() { - Completed completed = Completed.Builder.builder().withObjective(Objective.Builder.builder().withId(4L) - .withTitle("Build a company culture that kills the competition.").build()).build(); - - Mockito.when(completedPersistenceService.save(any())).thenReturn(successfulCompleted); + Completed completed = Completed.Builder.builder() + .withObjective(Objective.Builder.builder() + .withId(4L) + .withTitle("Build a company culture that kills the competition.") + .build()) + .build(); + + Mockito.when(completedPersistenceService.save(any())) + .thenReturn(successfulCompleted); Completed savedCompleted = completedBusinessService.createCompleted(completed); verify(completedPersistenceService, times(1)).save(completed); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java index 13e46094a9..0e03278abd 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java @@ -1,6 +1,8 @@ package ch.puzzle.okr.service.business; -import ch.puzzle.okr.test.TestHelper; +import java.time.LocalDateTime; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Unit; @@ -17,6 +19,8 @@ import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.service.authorization.AuthorizationService; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,9 +28,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; @@ -56,39 +57,77 @@ class KeyResultBusinessServiceIT { private AuthorizationService authorizationService; private static KeyResult createKeyResultMetric(Long id) { - return KeyResultMetric.Builder.builder().withBaseline(3.0).withStretchGoal(5.0).withUnit(Unit.FTE).withId(id) - .withTitle("Title").withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultMetric.Builder.builder() + .withBaseline(3.0) + .withStretchGoal(5.0) + .withUnit(Unit.FTE) + .withId(id) + .withTitle("Title") + .withCreatedBy(User.Builder.builder() + .withId(1L) + .build()) + .withOwner(User.Builder.builder() + .withId(1L) + .build()) + .withObjective(Objective.Builder.builder() + .withId(4L) + .build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static KeyResult createKeyResultOrdinal(Long id) { - return KeyResultOrdinal.Builder.builder().withCommitZone("Hamster").withTargetZone("Katze").withId(id) - .withTitle("Ordinal KeyResult").withStretchZone("ZOO") - .withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultOrdinal.Builder.builder() + .withCommitZone("Hamster") + .withTargetZone("Katze") + .withId(id) + .withTitle("Ordinal KeyResult") + .withStretchZone("ZOO") + .withCreatedBy(User.Builder.builder() + .withId(1L) + .build()) + .withOwner(User.Builder.builder() + .withId(1L) + .build()) + .withObjective(Objective.Builder.builder() + .withId(4L) + .build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static CheckIn createCheckInMetric(KeyResult keyResult) { - return CheckInMetric.Builder.builder().withKeyResult(keyResult).withConfidence(5).withValue(7.5).build(); + return CheckInMetric.Builder.builder() + .withKeyResult(keyResult) + .withConfidence(5) + .withValue(7.5) + .build(); } private static CheckIn createCheckInOrdinal(KeyResult keyResult) { - return CheckInOrdinal.Builder.builder().withKeyResult(keyResult).withConfidence(5).withZone(Zone.COMMIT) - .build(); + return CheckInOrdinal.Builder.builder() + .withKeyResult(keyResult) + .withConfidence(5) + .withZone(Zone.COMMIT) + .build(); } private static Action createAction1(KeyResult keyResult) { - return Action.Builder.builder().withIsChecked(false).withAction("Neuer Drucker").withPriority(0) - .withKeyResult(keyResult).build(); + return Action.Builder.builder() + .withIsChecked(false) + .withAction("Neuer Drucker") + .withPriority(0) + .withKeyResult(keyResult) + .build(); } private static Action createAction2(KeyResult keyResult) { - return Action.Builder.builder().withIsChecked(false).withAction("Neues Papier").withPriority(0) - .withKeyResult(keyResult).build(); + return Action.Builder.builder() + .withIsChecked(false) + .withAction("Neues Papier") + .withPriority(0) + .withKeyResult(keyResult) + .build(); } @BeforeEach @@ -135,7 +174,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeMetric() { createdKeyResult.setTitle(KEY_RESULT_UPDATED); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of()); + createdKeyResult, + List.of()); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); } @@ -148,7 +188,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeMetricWithActionList() { action2 = actionBusinessService.createEntity(createAction2(createdKeyResult)); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of(action1, action2)); + createdKeyResult, + List.of(action1, action2)); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); assertSameActions(List.of(action1, action2), updatedKeyResult); @@ -160,7 +201,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeOrdinal() { createdKeyResult.setTitle(KEY_RESULT_UPDATED); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of()); + createdKeyResult, + List.of()); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); } @@ -168,12 +210,13 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeOrdinal() { @Test void updateEntitiesShouldRecreateKeyResultMetric() { KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultOrdinal(null), - authorizationUser); + authorizationUser); Long createdKeyResultId = savedKeyResult.getId(); KeyResult changedKeyResult = createKeyResultMetric(savedKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -182,14 +225,15 @@ void updateEntitiesShouldRecreateKeyResultMetric() { @Test void updateEntitiesShouldRecreateKeyResultMetricWithActionList() { KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultOrdinal(null), - authorizationUser); + authorizationUser); action1 = actionBusinessService.createEntity(createAction1(savedKeyResult)); action2 = actionBusinessService.createEntity(createAction2(savedKeyResult)); KeyResult changedKeyResult = createKeyResultMetric(savedKeyResult.getId()); Long createdKeyResultId = changedKeyResult.getId(); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of(action1, action2)); + changedKeyResult, + List.of(action1, action2)); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -199,12 +243,13 @@ void updateEntitiesShouldRecreateKeyResultMetricWithActionList() { @Test void updateEntitiesShouldRecreateKeyResultOrdinal() { KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultMetric(null), - authorizationUser); + authorizationUser); Long createdKeyResultId = savedKeyResult.getId(); KeyResult changedKeyResult = createKeyResultOrdinal(savedKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -218,7 +263,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInMetric() { KeyResult changedKeyResult = createKeyResultMetric(createdKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); } @@ -235,7 +281,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInMetricWithAct action2.setChecked(true); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of(action1, action2)); + changedKeyResult, + List.of(action1, action2)); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); assertUpdatedActions(List.of(action1, action2), updatedKeyResult); @@ -249,7 +296,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInOrdinal() { KeyResult changedKeyResult = createKeyResultOrdinal(createdKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); } @@ -299,7 +347,8 @@ private static void assertKeyResult(KeyResult expected, KeyResult actual) { private void assertSameActions(List expected, KeyResultWithActionList actual) { assertSameKeyResultIds(expected, actual); expected.forEach(this::removeKeyResult); - actual.actionList().forEach(this::removeKeyResult); + actual.actionList() + .forEach(this::removeKeyResult); assertThat(expected).hasSameElementsAs(actual.actionList()); } @@ -310,20 +359,37 @@ private void assertUpdatedActions(List expected, KeyResultWithActionList } private void assertSameKeyResultIds(List expected, KeyResultWithActionList actual) { - List expectedIds = expected.stream().map(action -> action.getKeyResult().getId()).toList(); - List updatedIds = actual.actionList().stream().map(action -> action.getKeyResult().getId()).toList(); + List expectedIds = expected.stream() + .map(action -> action.getKeyResult() + .getId()) + .toList(); + List updatedIds = actual.actionList() + .stream() + .map(action -> action.getKeyResult() + .getId()) + .toList(); assertThat(expectedIds).hasSameElementsAs(updatedIds); } private void assertSameActionIds(List expected, KeyResultWithActionList actual) { - List expectedIds = expected.stream().map(Action::getId).toList(); - List updatedIds = actual.actionList().stream().map(Action::getId).toList(); + List expectedIds = expected.stream() + .map(Action::getId) + .toList(); + List updatedIds = actual.actionList() + .stream() + .map(Action::getId) + .toList(); assertThat(expectedIds).hasSameElementsAs(updatedIds); } private void assertUpdateVersions(List expected, KeyResultWithActionList actual) { - List expectedVersions = expected.stream().map(action -> action.getVersion() + 1).toList(); - List updatedVerisons = actual.actionList().stream().map(Action::getVersion).toList(); + List expectedVersions = expected.stream() + .map(action -> action.getVersion() + 1) + .toList(); + List updatedVerisons = actual.actionList() + .stream() + .map(Action::getVersion) + .toList(); assertThat(expectedVersions).hasSameElementsAs(updatedVerisons); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java index d23d3b61d8..baf5219e67 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.business; +import java.util.Collections; +import java.util.List; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; @@ -12,6 +15,7 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,9 +26,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.Collections; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; @@ -57,25 +58,59 @@ class KeyResultBusinessServiceTest { @BeforeEach void setup() { - user = User.Builder.builder().withId(1L).withEmail("newMail@tese.com").build(); - - objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").build(); - - metricKeyResult = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0).withId(5L) - .withTitle("Keyresult Metric").withObjective(objective).withOwner(user).withCreatedBy(user).build(); - ordinalKeyResult = KeyResultOrdinal.Builder.builder().withCommitZone("Baum").withStretchZone("Wald").withId(7L) - .withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user).withCreatedBy(user).build(); - - checkIn1 = CheckInMetric.Builder.builder().withId(1L).withKeyResult(metricKeyResult).withCreatedBy(user) - .build(); - checkIn2 = CheckInOrdinal.Builder.builder().withId(2L).withKeyResult(ordinalKeyResult).withCreatedBy(user) - .build(); - checkIn3 = CheckInOrdinal.Builder.builder().withId(3L).withKeyResult(ordinalKeyResult).withCreatedBy(user) - .build(); + user = User.Builder.builder() + .withId(1L) + .withEmail("newMail@tese.com") + .build(); + + objective = Objective.Builder.builder() + .withId(5L) + .withTitle("Objective 1") + .build(); + + metricKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withId(5L) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .withCreatedBy(user) + .build(); + ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withStretchZone("Wald") + .withId(7L) + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .withOwner(user) + .withCreatedBy(user) + .build(); + + checkIn1 = CheckInMetric.Builder.builder() + .withId(1L) + .withKeyResult(metricKeyResult) + .withCreatedBy(user) + .build(); + checkIn2 = CheckInOrdinal.Builder.builder() + .withId(2L) + .withKeyResult(ordinalKeyResult) + .withCreatedBy(user) + .build(); + checkIn3 = CheckInOrdinal.Builder.builder() + .withId(3L) + .withKeyResult(ordinalKeyResult) + .withCreatedBy(user) + .build(); keyResults = List.of(metricKeyResult, ordinalKeyResult); checkIns = List.of(checkIn1, checkIn2, checkIn3); - Action action = Action.Builder.builder().withId(3L).withAction("Neues Haus").withPriority(1).withIsChecked(true) - .withKeyResult(metricKeyResult).build(); + Action action = Action.Builder.builder() + .withId(3L) + .withAction("Neues Haus") + .withPriority(1) + .withIsChecked(true) + .withKeyResult(metricKeyResult) + .build(); actions = List.of(action, action); } @@ -99,8 +134,10 @@ void shouldGetOrdinalKeyResultById() { @Test void shouldThrowExceptionWhenDefaultMethodUsed() { - IllegalCallerException exception = assertThrows(IllegalCallerException.class, () -> keyResultBusinessService - .updateEntity(metricKeyResult.getId(), metricKeyResult, authorizationUser)); + IllegalCallerException exception = assertThrows(IllegalCallerException.class, + () -> keyResultBusinessService.updateEntity(metricKeyResult.getId(), + metricKeyResult, + authorizationUser)); assertEquals("unsupported method 'updateEntity' use updateEntities() instead", exception.getMessage()); } @@ -108,11 +145,16 @@ void shouldThrowExceptionWhenDefaultMethodUsed() { @Test void shouldEditMetricKeyResultWhenNoTypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultMetric.Builder.builder().withId(1L).withTitle("Keyresult Metric update").build()); - Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(metricKeyResult); - Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); - doNothing().when(newKeyresult).setModifiedOn(any()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withId(1L) + .withTitle("Keyresult Metric update") + .build()); + Mockito.when(keyResultPersistenceService.findById(1L)) + .thenReturn(metricKeyResult); + Mockito.when(keyResultPersistenceService.updateEntity(any())) + .thenReturn(newKeyresult); + doNothing().when(newKeyresult) + .setModifiedOn(any()); keyResultBusinessService.updateEntities(newKeyresult.getId(), newKeyresult, List.of()); verify(keyResultPersistenceService, times(1)).updateEntity(newKeyresult); @@ -125,11 +167,16 @@ void shouldEditMetricKeyResultWhenNoTypeChange() { @Test void shouldEditOrdinalKeyResultWhenNoTypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withId(1L).withTitle("Keyresult Ordinal update").build()); - Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(ordinalKeyResult); - Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); - doNothing().when(newKeyresult).setModifiedOn(any()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withId(1L) + .withTitle("Keyresult Ordinal update") + .build()); + Mockito.when(keyResultPersistenceService.findById(1L)) + .thenReturn(ordinalKeyResult); + Mockito.when(keyResultPersistenceService.updateEntity(any())) + .thenReturn(newKeyresult); + doNothing().when(newKeyresult) + .setModifiedOn(any()); keyResultBusinessService.updateEntities(newKeyresult.getId(), newKeyresult, List.of()); verify(keyResultPersistenceService, times(1)).updateEntity(newKeyresult); @@ -142,12 +189,18 @@ void shouldEditOrdinalKeyResultWhenNoTypeChange() { @Test void shouldEditMetricKeyResultWhenATypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultMetric.Builder.builder().withId(1L).withTitle("Keyresult Metric update").build()); - Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(ordinalKeyResult); - Mockito.when(keyResultPersistenceService.recreateEntity(any(), any())).thenReturn(newKeyresult); - Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); - doNothing().when(newKeyresult).setModifiedOn(any()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withId(1L) + .withTitle("Keyresult Metric update") + .build()); + Mockito.when(keyResultPersistenceService.findById(1L)) + .thenReturn(ordinalKeyResult); + Mockito.when(keyResultPersistenceService.recreateEntity(any(), any())) + .thenReturn(newKeyresult); + Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())) + .thenReturn(emptyList); + doNothing().when(newKeyresult) + .setModifiedOn(any()); keyResultBusinessService.updateEntities(newKeyresult.getId(), newKeyresult, actions); verify(keyResultPersistenceService, times(1)).recreateEntity(1L, newKeyresult); @@ -161,11 +214,16 @@ void shouldEditMetricKeyResultWhenATypeChange() { @Test void shouldEditOrdinalKeyResultWhenATypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withId(1L).withTitle("Keyresult Ordinal update").build()); - Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(metricKeyResult); - Mockito.when(keyResultPersistenceService.recreateEntity(any(), any())).thenReturn(newKeyresult); - Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withId(1L) + .withTitle("Keyresult Ordinal update") + .build()); + Mockito.when(keyResultPersistenceService.findById(1L)) + .thenReturn(metricKeyResult); + Mockito.when(keyResultPersistenceService.recreateEntity(any(), any())) + .thenReturn(newKeyresult); + Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())) + .thenReturn(emptyList); keyResultBusinessService.updateEntities(newKeyresult.getId(), newKeyresult, actions); verify(keyResultPersistenceService, times(1)).recreateEntity(1L, newKeyresult); @@ -179,11 +237,16 @@ void shouldEditOrdinalKeyResultWhenATypeChange() { @Test void shouldOnlyEditCoupleOfAttributesFromMetricKeyResultWhenATypeChangeAndCheckIns() { List emptyList = checkIns; - KeyResult newKeyresult = spy( - KeyResultMetric.Builder.builder().withId(1L).withTitle("Keyresult Metric update").build()); - Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(ordinalKeyResult); - Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); - Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withId(1L) + .withTitle("Keyresult Metric update") + .build()); + Mockito.when(keyResultPersistenceService.findById(1L)) + .thenReturn(ordinalKeyResult); + Mockito.when(keyResultPersistenceService.updateEntity(any())) + .thenReturn(newKeyresult); + Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())) + .thenReturn(emptyList); keyResultBusinessService.updateEntities(newKeyresult.getId(), newKeyresult, List.of()); verify(keyResultPersistenceService, times(1)).updateEntity(ordinalKeyResult); @@ -197,12 +260,18 @@ void shouldOnlyEditCoupleOfAttributesFromMetricKeyResultWhenATypeChangeAndCheckI @Test void shouldOnlyEditCoupleOfAttributesFromOrdinalKeyResultWhenATypeChangeAndCheckIns() { List emptyList = checkIns; - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withId(1L).withTitle("Keyresult Ordinal update").build()); - Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(metricKeyResult); - Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); - Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); - doNothing().when(newKeyresult).setModifiedOn(any()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withId(1L) + .withTitle("Keyresult Ordinal update") + .build()); + Mockito.when(keyResultPersistenceService.findById(1L)) + .thenReturn(metricKeyResult); + Mockito.when(keyResultPersistenceService.updateEntity(any())) + .thenReturn(newKeyresult); + Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())) + .thenReturn(emptyList); + doNothing().when(newKeyresult) + .setModifiedOn(any()); keyResultBusinessService.updateEntities(newKeyresult.getId(), newKeyresult, List.of()); verify(keyResultPersistenceService, times(1)).updateEntity(metricKeyResult); @@ -214,10 +283,17 @@ void shouldOnlyEditCoupleOfAttributesFromOrdinalKeyResultWhenATypeChangeAndCheck @Test void saveMetricKeyResult() { - KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(8.0).withId(1L) - .withTitle("Keyresult Metric save").withDescription("The description").build()); - Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); - doNothing().when(newKeyresult).setCreatedOn(any()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(8.0) + .withId(1L) + .withTitle("Keyresult Metric save") + .withDescription("The description") + .build()); + Mockito.when(keyResultPersistenceService.save(any())) + .thenReturn(newKeyresult); + doNothing().when(newKeyresult) + .setCreatedOn(any()); KeyResult savedKeyResult = keyResultBusinessService.createEntity(newKeyresult, authorizationUser); verify(keyResultPersistenceService, times(1)).save(newKeyresult); @@ -226,11 +302,17 @@ void saveMetricKeyResult() { @Test void saveOrdinalKeyResult() { - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withCommitZone("Eine Pflanze").withTargetZone("Ein Baum").withId(1L) - .withTitle("Keyresult ordinal save").withDescription("The description").build()); - Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); - doNothing().when(newKeyresult).setCreatedOn(any()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withCommitZone("Eine Pflanze") + .withTargetZone("Ein Baum") + .withId(1L) + .withTitle("Keyresult ordinal save") + .withDescription("The description") + .build()); + Mockito.when(keyResultPersistenceService.save(any())) + .thenReturn(newKeyresult); + doNothing().when(newKeyresult) + .setCreatedOn(any()); KeyResult savedKeyResult = keyResultBusinessService.createEntity(newKeyresult, authorizationUser); verify(keyResultPersistenceService, times(1)).save(newKeyresult); @@ -239,10 +321,16 @@ void saveOrdinalKeyResult() { @Test void shouldBePossibleToSaveMetricKeyResultWithoutDescription() { - KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(8.0).withId(1L) - .withTitle("Keyresult Metric save").build()); - Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); - doNothing().when(newKeyresult).setCreatedOn(any()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(8.0) + .withId(1L) + .withTitle("Keyresult Metric save") + .build()); + Mockito.when(keyResultPersistenceService.save(any())) + .thenReturn(newKeyresult); + doNothing().when(newKeyresult) + .setCreatedOn(any()); KeyResult keyResult = keyResultBusinessService.createEntity(newKeyresult, authorizationUser); verify(keyResultPersistenceService, times(1)).save(newKeyresult); @@ -251,10 +339,16 @@ void shouldBePossibleToSaveMetricKeyResultWithoutDescription() { @Test void shouldBePossibleToSaveOrdinalKeyResultWithoutDescription() { - KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder().withCommitZone("Eine Pflanze") - .withTargetZone("Ein Baum").withId(1L).withTitle("Keyresult ordinal save").build()); - Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); - doNothing().when(newKeyresult).setCreatedOn(any()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withCommitZone("Eine Pflanze") + .withTargetZone("Ein Baum") + .withId(1L) + .withTitle("Keyresult ordinal save") + .build()); + Mockito.when(keyResultPersistenceService.save(any())) + .thenReturn(newKeyresult); + doNothing().when(newKeyresult) + .setCreatedOn(any()); KeyResult keyResult = keyResultBusinessService.createEntity(newKeyresult, authorizationUser); verify(keyResultPersistenceService, times(1)).save(newKeyresult); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java index ce4db63f9c..5639092755 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.business; +import java.time.LocalDateTime; +import java.util.List; + import ch.puzzle.okr.models.*; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; @@ -7,6 +10,7 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.validation.ObjectiveValidationService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -18,11 +22,8 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static ch.puzzle.okr.models.State.DRAFT; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; @@ -32,8 +33,7 @@ @ExtendWith(MockitoExtension.class) class ObjectiveBusinessServiceTest { private static final AuthorizationUser authorizationUser = defaultAuthorizationUser(); - @InjectMocks - @Spy + @InjectMocks @Spy ObjectiveBusinessService objectiveBusinessService; @Mock ObjectivePersistenceService objectivePersistenceService; @@ -44,16 +44,39 @@ class ObjectiveBusinessServiceTest { @Mock ObjectiveValidationService validator = Mockito.mock(ObjectiveValidationService.class); - private final Team team1 = Team.Builder.builder().withId(1L).withName("Team1").build(); - private final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - private final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - private final Objective objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").build(); - private final Objective fullObjective = Objective.Builder.builder().withTitle("FullObjective1").withCreatedBy(user) - .withTeam(team1).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).build(); - private final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder().withCommitZone("Baum") - .withStretchZone("Wald").withId(5L).withTitle("Keyresult Ordinal").withObjective(objective).build(); + private final Team team1 = Team.Builder.builder() + .withId(1L) + .withName("Team1") + .build(); + private final Quarter quarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .build(); + private final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + private final Objective objective = Objective.Builder.builder() + .withId(5L) + .withTitle("Objective 1") + .build(); + private final Objective fullObjective = Objective.Builder.builder() + .withTitle("FullObjective1") + .withCreatedBy(user) + .withTeam(team1) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .build(); + private final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withStretchZone("Wald") + .withId(5L) + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .build(); private final List keyResultList = List.of(ordinalKeyResult, ordinalKeyResult, ordinalKeyResult); @Test @@ -87,11 +110,18 @@ void shouldNotFindTheObjective() { @Test void shouldSaveANewObjective() { - Objective objective = spy(Objective.Builder.builder().withTitle("Received Objective").withTeam(team1) - .withQuarter(quarter).withDescription("The description").withModifiedOn(null).withModifiedBy(null) - .withState(DRAFT).build()); - - doNothing().when(objective).setCreatedOn(any()); + Objective objective = spy(Objective.Builder.builder() + .withTitle("Received Objective") + .withTeam(team1) + .withQuarter(quarter) + .withDescription("The description") + .withModifiedOn(null) + .withModifiedBy(null) + .withState(DRAFT) + .build()); + + doNothing().when(objective) + .setCreatedOn(any()); objectiveBusinessService.createEntity(objective, authorizationUser); @@ -103,31 +133,59 @@ void shouldSaveANewObjective() { @Test void shouldNotThrowResponseStatusExceptionWhenPuttingNullId() { - Objective objective1 = Objective.Builder.builder().withId(null).withTitle("Title") - .withDescription("Description").withModifiedOn(LocalDateTime.now()).build(); + Objective objective1 = Objective.Builder.builder() + .withId(null) + .withTitle("Title") + .withDescription("Description") + .withModifiedOn(LocalDateTime.now()) + .build(); when(objectiveBusinessService.createEntity(objective1, authorizationUser)).thenReturn(fullObjective); Objective savedObjective = objectiveBusinessService.createEntity(objective1, authorizationUser); assertNull(savedObjective.getId()); assertEquals("FullObjective1", savedObjective.getTitle()); - assertEquals("Bob", savedObjective.getCreatedBy().getFirstname()); + assertEquals("Bob", + savedObjective.getCreatedBy() + .getFirstname()); } @ParameterizedTest - @ValueSource(booleans = { false, true }) + @ValueSource(booleans = {false, true}) void updateEntityShouldHandleQuarterCorrectly(boolean hasKeyResultAnyCheckIns) { Long id = 27L; String title = "Received Objective"; String description = "The description"; - Quarter changedQuarter = Quarter.Builder.builder().withId(2L).withLabel("another quarter").build(); - Objective savedObjective = Objective.Builder.builder().withId(id).withTitle(title).withTeam(team1) - .withQuarter(quarter).withDescription(null).withModifiedOn(null).withModifiedBy(null).build(); - Objective changedObjective = Objective.Builder.builder().withId(id).withTitle(title).withTeam(team1) - .withQuarter(changedQuarter).withDescription(description).withModifiedOn(null).withModifiedBy(null) - .build(); - Objective updatedObjective = Objective.Builder.builder().withId(id).withTitle(title).withTeam(team1) - .withQuarter(hasKeyResultAnyCheckIns ? quarter : changedQuarter).withDescription(description) - .withModifiedOn(null).withModifiedBy(null).build(); + Quarter changedQuarter = Quarter.Builder.builder() + .withId(2L) + .withLabel("another quarter") + .build(); + Objective savedObjective = Objective.Builder.builder() + .withId(id) + .withTitle(title) + .withTeam(team1) + .withQuarter(quarter) + .withDescription(null) + .withModifiedOn(null) + .withModifiedBy(null) + .build(); + Objective changedObjective = Objective.Builder.builder() + .withId(id) + .withTitle(title) + .withTeam(team1) + .withQuarter(changedQuarter) + .withDescription(description) + .withModifiedOn(null) + .withModifiedBy(null) + .build(); + Objective updatedObjective = Objective.Builder.builder() + .withId(id) + .withTitle(title) + .withTeam(team1) + .withQuarter(hasKeyResultAnyCheckIns ? quarter : changedQuarter) + .withDescription(description) + .withModifiedOn(null) + .withModifiedBy(null) + .build(); when(objectivePersistenceService.findById(any())).thenReturn(savedObjective); when(keyResultBusinessService.getAllKeyResultsByObjective(savedObjective.getId())).thenReturn(keyResultList); @@ -135,12 +193,13 @@ void updateEntityShouldHandleQuarterCorrectly(boolean hasKeyResultAnyCheckIns) { when(objectivePersistenceService.save(changedObjective)).thenReturn(updatedObjective); boolean isImUsed = objectiveBusinessService.isImUsed(changedObjective); - Objective updatedEntity = objectiveBusinessService.updateEntity(changedObjective.getId(), changedObjective, - authorizationUser); + Objective updatedEntity = objectiveBusinessService.updateEntity(changedObjective.getId(), + changedObjective, + authorizationUser); assertEquals(hasKeyResultAnyCheckIns, isImUsed); assertEquals(hasKeyResultAnyCheckIns ? savedObjective.getQuarter() : changedObjective.getQuarter(), - updatedEntity.getQuarter()); + updatedEntity.getQuarter()); assertEquals(changedObjective.getDescription(), updatedEntity.getDescription()); assertEquals(changedObjective.getTitle(), updatedEntity.getTitle()); } @@ -159,32 +218,33 @@ void shouldDeleteObjectiveAndAssociatedKeyResults() { void shouldDuplicateObjective() { // arrange Objective sourceObjective = Objective.Builder.builder() // - .withId(23L) // - .withTitle("Objective 1") // - .build(); + .withId(23L) // + .withTitle("Objective 1") // + .build(); KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() // - .withTitle("Ordinal 1") // - .withObjective(sourceObjective) // - .build(); + .withTitle("Ordinal 1") // + .withObjective(sourceObjective) // + .build(); KeyResult keyResultMetric = KeyResultMetric.Builder.builder() // - .withTitle("Metric 1") // - .withObjective(sourceObjective) // - .withUnit(Unit.FTE) // - .build(); + .withTitle("Metric 1") // + .withObjective(sourceObjective) // + .withUnit(Unit.FTE) // + .build(); // new Objective with no KeyResults Objective newObjective = Objective.Builder.builder() // - .withId(42L) // - .withTitle("Objective 2") // - .build(); + .withId(42L) // + .withTitle("Objective 2") // + .build(); when(objectivePersistenceService.save(any())).thenReturn(newObjective); - when(keyResultBusinessService.getAllKeyResultsByObjective(anyLong())) - .thenReturn(List.of(keyResultOrdinal, keyResultMetric)); + when(keyResultBusinessService.getAllKeyResultsByObjective(anyLong())).thenReturn(List.of(keyResultOrdinal, + keyResultMetric)); // act Objective duplicatedObjective = objectiveBusinessService.duplicateObjective(sourceObjective.getId(), - newObjective, authorizationUser); + newObjective, + authorizationUser); // assert assertNotEquals(sourceObjective.getId(), duplicatedObjective.getId()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java index 546a65df47..69bef57564 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java @@ -1,11 +1,16 @@ package ch.puzzle.okr.service.business; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.service.persistence.OverviewPersistenceService; import ch.puzzle.okr.service.validation.OverviewValidationService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -14,10 +19,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - import static ch.puzzle.okr.test.OverviewTestHelper.QUARTER_ID; import static ch.puzzle.okr.test.OverviewTestHelper.teamIds; import static ch.puzzle.okr.test.TestHelper.*; @@ -49,34 +50,61 @@ private static List createOverviews() { private static List createOverviews(AuthorizationUser authorizationUser) { long index = 1L; - List overviews = new ArrayList<>(List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++).withTeamId(111L).build()) - .withObjectiveTitle("Another Team Objective A").withTeamName("team-111") - .withObjectiveCreatedOn(LocalDateTime.of(2023, 10, 21, 18, 33)).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++).withTeamId(222L).build()) - .withObjectiveTitle("Another Team Objective B").withTeamName("team-222") - .withObjectiveCreatedOn(LocalDateTime.of(2023, 10, 1, 8, 53)).build())); + List overviews = new ArrayList<>(List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(111L) + .build()) + .withObjectiveTitle("Another Team Objective A") + .withTeamName("team-111") + .withObjectiveCreatedOn(LocalDateTime.of(2023, + 10, + 21, + 18, + 33)) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(222L) + .build()) + .withObjectiveTitle("Another Team Objective B") + .withTeamName("team-222") + .withObjectiveCreatedOn(LocalDateTime.of(2023, + 10, + 1, + 8, + 53)) + .build())); for (Long teamId : authorizationUser.extractTeamIds()) { - overviews - .addAll((List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++) - .withTeamId(teamId).build()) - .withObjectiveTitle("ZZZ Objective").withTeamName("firstLevelTeam-" + teamId) - .withObjectiveCreatedOn(LocalDateTime.of(2023, 12, 10, 18, 33)).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++) - .withTeamId(teamId).build()) - .withObjectiveTitle("AAA Objective").withTeamName("firstLevelTeam-" + teamId) - .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++) - .withTeamId(teamId).build()) - .withObjectiveTitle("AAA Objective").withTeamName("firstLevelTeam-" + teamId) - .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)).build()))); + overviews.addAll((List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(teamId) + .build()) + .withObjectiveTitle("ZZZ Objective") + .withTeamName("firstLevelTeam-" + teamId) + .withObjectiveCreatedOn(LocalDateTime.of(2023, 12, 10, 18, 33)) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(teamId) + .build()) + .withObjectiveTitle("AAA Objective") + .withTeamName("firstLevelTeam-" + teamId) + .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(teamId) + .build()) + .withObjectiveTitle("AAA Objective") + .withTeamName("firstLevelTeam-" + teamId) + .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)) + .build()))); } return overviews; } @@ -123,67 +151,79 @@ void getFilteredOverviewShouldReturnEmptyListOfOverviewsWhenTeamIdsAreNull() { verify(overviewValidationService, times(1)).validateOnGet(QUARTER_ID, List.of()); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewPersistenceService, never()).getFilteredOverview(QUARTER_ID, List.of(), "", authorizationUser); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), anyString(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + anyString(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldReturnExceptionWhenQuarterIdIsNonExistent() { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(overviewValidationService) - .validateOnGet(eq(QUARTER_ID), anyList()); + .validateOnGet(eq(QUARTER_ID), anyList()); assertThrows(ResponseStatusException.class, - () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, List.of(), "", authorizationUser)); + () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, List.of(), "", authorizationUser)); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewValidationService, never()).validateOnGet(QUARTER_ID, teamIds); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), anyString(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + anyString(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldReturnExceptionWhenTeamIdIsNonExistent() { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(overviewValidationService) - .validateOnGet(QUARTER_ID, teamIds); + .validateOnGet(QUARTER_ID, teamIds); assertThrows(ResponseStatusException.class, - () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); + () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewValidationService, never()).validateQuarter(QUARTER_ID); verify(overviewValidationService, times(1)).validateOnGet(QUARTER_ID, teamIds); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), any(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + any(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldThrowExceptionWhenTeamIdIsNonExistent() { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(overviewValidationService) - .validateOnGet(QUARTER_ID, teamIds); + .validateOnGet(QUARTER_ID, teamIds); assertThrows(ResponseStatusException.class, - () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); + () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewValidationService, times(1)).validateOnGet(QUARTER_ID, teamIds); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), anyString(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + anyString(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldReturnSortedListUserTeamsFirst() { Long firstLevelTeamId = 5L; AuthorizationUser user = mockAuthorizationUser(defaultUser(13L)); - when(overviewPersistenceService.getFilteredOverview(QUARTER_ID, teamIds, null, user)) - .thenReturn(createOverviews(user)); + when(overviewPersistenceService.getFilteredOverview(QUARTER_ID, teamIds, null, user)).thenReturn( + createOverviews(user)); List overviews = overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, null, user); - assertThat(List.of(OverviewId.of(1L, 4L, null, null), OverviewId.of(1L, 5L, null, null), - OverviewId.of(1L, 3L, null, null), OverviewId.of(111L, 1L, null, null), - OverviewId.of(222L, 2L, null, null))).hasSameElementsAs(getOverviewIds(overviews)); + assertThat(List.of(OverviewId.of(1L, 4L, null, null), + OverviewId.of(1L, 5L, null, null), + OverviewId.of(1L, 3L, null, null), + OverviewId.of(111L, 1L, null, null), + OverviewId.of(222L, 2L, null, null))).hasSameElementsAs(getOverviewIds(overviews)); } private List getOverviewIds(List overviews) { - return overviews.stream().map(Overview::getOverviewId).toList(); + return overviews.stream() + .map(Overview::getOverviewId) + .toList(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java index 479620ad3d..f3a853e5d9 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java @@ -1,8 +1,17 @@ package ch.puzzle.okr.service.business; +import java.time.LocalDate; +import java.time.YearMonth; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; import ch.puzzle.okr.service.validation.QuarterValidationService; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -16,14 +25,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; -import java.time.LocalDate; -import java.time.YearMonth; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -38,8 +39,7 @@ class QuarterBusinessServiceTest { @Mock QuarterValidationService quarterValidationService; - @InjectMocks - @Spy + @InjectMocks @Spy private QuarterBusinessService quarterBusinessService; private static Stream shouldGetFirstMonthFromQuarter() { @@ -74,70 +74,92 @@ void shouldCallGetQuarters() { @Test void shouldGetBacklogQuarter() { - Quarter realQuarter1 = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withStartDate(LocalDate.of(2022, 4, 1)).withEndDate(LocalDate.of(2022, 7, 31)).build(); - Quarter realQuarter2 = Quarter.Builder.builder().withId(2L).withLabel("GJ-22/23-Q4") - .withStartDate(LocalDate.of(2022, 8, 1)).withEndDate(LocalDate.of(2022, 11, 30)).build(); + Quarter realQuarter1 = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withStartDate(LocalDate.of(2022, 4, 1)) + .withEndDate(LocalDate.of(2022, 7, 31)) + .build(); + Quarter realQuarter2 = Quarter.Builder.builder() + .withId(2L) + .withLabel("GJ-22/23-Q4") + .withStartDate(LocalDate.of(2022, 8, 1)) + .withEndDate(LocalDate.of(2022, 11, 30)) + .build(); List quarterList = new ArrayList<>(Arrays.asList(realQuarter1, realQuarter2)); - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .build(); when(quarterPersistenceService.getMostCurrentQuarters()).thenReturn(quarterList); when(quarterPersistenceService.findByLabel(BACK_LOG_QUARTER_LABEL)).thenReturn(backlogQuarter); quarterList = quarterBusinessService.getQuarters(); assertEquals(3, quarterList.size()); - assertEquals(BACK_LOG_QUARTER_LABEL, quarterList.get(0).getLabel()); - assertNull(quarterList.get(0).getStartDate()); - assertNull(quarterList.get(0).getEndDate()); + assertEquals(BACK_LOG_QUARTER_LABEL, + quarterList.get(0) + .getLabel()); + assertNull(quarterList.get(0) + .getStartDate()); + assertNull(quarterList.get(0) + .getEndDate()); } @ParameterizedTest - @ValueSource(ints = { 1, 2, 4, 5, 7, 8, 10, 11 }) + @ValueSource(ints = {1, 2, 4, 5, 7, 8, 10, 11}) void shouldNotGenerateQuarterIfNotLastMonth(int month) { ReflectionTestUtils.setField(quarterBusinessService, "quarterStart", 7); - Mockito.when(quarterBusinessService.getCurrentYearMonth()).thenReturn(YearMonth.of(2030, month)); + Mockito.when(quarterBusinessService.getCurrentYearMonth()) + .thenReturn(YearMonth.of(2030, month)); quarterBusinessService.scheduledGenerationQuarters(); verify(quarterPersistenceService, never()).save(any()); } @ParameterizedTest - @ValueSource(ints = { 3, 6, 9, 12 }) + @ValueSource(ints = {3, 6, 9, 12}) void shouldGenerateQuarterIfLastMonth(int month) { ReflectionTestUtils.setField(quarterBusinessService, "quarterStart", 7); - Mockito.when(quarterBusinessService.getCurrentYearMonth()).thenReturn(YearMonth.of(2030, month)); + Mockito.when(quarterBusinessService.getCurrentYearMonth()) + .thenReturn(YearMonth.of(2030, month)); quarterBusinessService.scheduledGenerationQuarters(); verify(quarterPersistenceService, times(1)).save(any()); } private static Stream generateQuarterParams() { return Stream.of(Arguments.of(7, "GJ xx/yy-Qzz", YearMonth.of(2030, 3), "GJ 30/31-Q1"), - Arguments.of(7, "GJ xx/yy-Qzz", YearMonth.of(2030, 9), "GJ 30/31-Q3"), - Arguments.of(5, "GJ xx/yy-Qzz", YearMonth.of(2030, 4), "GJ 30/31-Q2"), - Arguments.of(1, "GJ xx-Qzz", YearMonth.of(2030, 9), "GJ 31-Q1"), - Arguments.of(1, "GJ xxxx-Qzz", YearMonth.of(2030, 6), "GJ 2030-Q4"), - Arguments.of(2, "xx-yy-xxxx-yyyy-Qzz", YearMonth.of(2030, 1), "30-31-2030-2031-Q2")); + Arguments.of(7, "GJ xx/yy-Qzz", YearMonth.of(2030, 9), "GJ 30/31-Q3"), + Arguments.of(5, "GJ xx/yy-Qzz", YearMonth.of(2030, 4), "GJ 30/31-Q2"), + Arguments.of(1, "GJ xx-Qzz", YearMonth.of(2030, 9), "GJ 31-Q1"), + Arguments.of(1, "GJ xxxx-Qzz", YearMonth.of(2030, 6), "GJ 2030-Q4"), + Arguments.of(2, "xx-yy-xxxx-yyyy-Qzz", YearMonth.of(2030, 1), "30-31-2030-2031-Q2")); } @ParameterizedTest @MethodSource("generateQuarterParams") - void shouldGenerateCorrectQuarter(int quarterStart, String quarterFormat, YearMonth currentYearMonth, - String expectedLabel) { + void shouldGenerateCorrectQuarter(int quarterStart, String quarterFormat, YearMonth currentYearMonth, String expectedLabel) { ReflectionTestUtils.setField(quarterBusinessService, "quarterStart", quarterStart); ReflectionTestUtils.setField(quarterBusinessService, "quarterFormat", quarterFormat); int monthsToNextQuarterStart = 4; - LocalDate expectedStart = currentYearMonth.plusMonths(monthsToNextQuarterStart).atDay(1); + LocalDate expectedStart = currentYearMonth.plusMonths(monthsToNextQuarterStart) + .atDay(1); int monthsToNextQuarterEnd = 6; - LocalDate expectedEnd = currentYearMonth.plusMonths(monthsToNextQuarterEnd).atEndOfMonth(); + LocalDate expectedEnd = currentYearMonth.plusMonths(monthsToNextQuarterEnd) + .atEndOfMonth(); - Quarter expectedQuarter = Quarter.Builder.builder().withId(null).withLabel(expectedLabel) - .withStartDate(expectedStart).withEndDate(expectedEnd).build(); + Quarter expectedQuarter = Quarter.Builder.builder() + .withId(null) + .withLabel(expectedLabel) + .withStartDate(expectedStart) + .withEndDate(expectedEnd) + .build(); - Mockito.when(quarterBusinessService.getCurrentYearMonth()).thenReturn(currentYearMonth); + Mockito.when(quarterBusinessService.getCurrentYearMonth()) + .thenReturn(currentYearMonth); quarterBusinessService.scheduledGenerationQuarters(); @@ -145,12 +167,30 @@ void shouldGenerateCorrectQuarter(int quarterStart, String quarterFormat, YearMo } private static Stream getQuartersParams() { - return Stream.of(Arguments.of(5, 1, 3), Arguments.of(5, 2, 4), Arguments.of(5, 3, 4), Arguments.of(5, 4, 4), - Arguments.of(5, 5, 1), Arguments.of(5, 6, 1), Arguments.of(5, 7, 1), Arguments.of(5, 8, 2), - Arguments.of(5, 9, 2), Arguments.of(5, 10, 2), Arguments.of(5, 11, 3), Arguments.of(5, 12, 3), - Arguments.of(10, 1, 2), Arguments.of(10, 2, 2), Arguments.of(10, 3, 2), Arguments.of(10, 4, 3), - Arguments.of(10, 5, 3), Arguments.of(10, 6, 3), Arguments.of(10, 7, 4), Arguments.of(10, 8, 4), - Arguments.of(10, 9, 4), Arguments.of(10, 10, 1), Arguments.of(10, 11, 1), Arguments.of(10, 12, 1)); + return Stream.of(Arguments.of(5, 1, 3), + Arguments.of(5, 2, 4), + Arguments.of(5, 3, 4), + Arguments.of(5, 4, 4), + Arguments.of(5, 5, 1), + Arguments.of(5, 6, 1), + Arguments.of(5, 7, 1), + Arguments.of(5, 8, 2), + Arguments.of(5, 9, 2), + Arguments.of(5, 10, 2), + Arguments.of(5, 11, 3), + Arguments.of(5, 12, 3), + Arguments.of(10, 1, 2), + Arguments.of(10, 2, 2), + Arguments.of(10, 3, 2), + Arguments.of(10, 4, 3), + Arguments.of(10, 5, 3), + Arguments.of(10, 6, 3), + Arguments.of(10, 7, 4), + Arguments.of(10, 8, 4), + Arguments.of(10, 9, 4), + Arguments.of(10, 10, 1), + Arguments.of(10, 11, 1), + Arguments.of(10, 12, 1)); } @ParameterizedTest(name = "Start month={0}, current month={1} => quarter={2}") @@ -163,7 +203,8 @@ void shouldGetQuartersBasedOnStart(int start, int month, int quarter) { @Test void shouldReturnNullWhenNoQuarterGenerationNeeded() { - Mockito.when(quarterBusinessService.getCurrentYearMonth()).thenReturn(YearMonth.of(2030, 4)); + Mockito.when(quarterBusinessService.getCurrentYearMonth()) + .thenReturn(YearMonth.of(2030, 4)); quarterBusinessService.scheduledGenerationQuarters(); verify(quarterPersistenceService, times(0)).save(any()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java index e5586543ec..53841b4150 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.business; +import java.util.ArrayList; +import java.util.List; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -12,6 +15,7 @@ import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.service.persistence.UserTeamPersistenceService; import ch.puzzle.okr.service.validation.TeamValidationService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,12 +25,9 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.util.ArrayList; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.*; import static ch.puzzle.okr.models.State.DRAFT; import static ch.puzzle.okr.models.State.SUCCESSFUL; +import static ch.puzzle.okr.test.TestHelper.*; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -64,27 +65,60 @@ class TeamBusinessServiceTest { @BeforeEach void setUp() { - this.team1 = Team.Builder.builder().withId(1L).withName("Team 1").build(); - this.team1.setUserTeamList(List.of( - UserTeam.Builder.builder().withTeam(team1).withUser(defaultUser(2L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(team1).withUser(defaultUser(3L)).withTeamAdmin(false).build())); - this.team2 = Team.Builder.builder().withId(2L).withName("Team 2").build(); - this.team2.setUserTeamList(List.of( - UserTeam.Builder.builder().withTeam(team2).withUser(defaultUser(4L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(team2).withUser(defaultUser(5L)).withTeamAdmin(true).build())); - this.team3 = Team.Builder.builder().withId(3L).withName("Team 3").build(); + this.team1 = Team.Builder.builder() + .withId(1L) + .withName("Team 1") + .build(); + this.team1.setUserTeamList(List.of(UserTeam.Builder.builder() + .withTeam(team1) + .withUser(defaultUser(2L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(team1) + .withUser(defaultUser(3L)) + .withTeamAdmin(false) + .build())); + this.team2 = Team.Builder.builder() + .withId(2L) + .withName("Team 2") + .build(); + this.team2.setUserTeamList(List.of(UserTeam.Builder.builder() + .withTeam(team2) + .withUser(defaultUser(4L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(team2) + .withUser(defaultUser(5L)) + .withTeamAdmin(true) + .build())); + this.team3 = Team.Builder.builder() + .withId(3L) + .withName("Team 3") + .build(); this.team3.setUserTeamList(List.of()); - this.teamWithIdNull = Team.Builder.builder().withName("Team with id null").build(); - this.objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").withState(DRAFT).build(); - this.objectiveCompleted = Objective.Builder.builder().withId(6L).withTitle("Objective 1").withState(SUCCESSFUL) - .build(); + this.teamWithIdNull = Team.Builder.builder() + .withName("Team with id null") + .build(); + this.objective = Objective.Builder.builder() + .withId(5L) + .withTitle("Objective 1") + .withState(DRAFT) + .build(); + this.objectiveCompleted = Objective.Builder.builder() + .withId(6L) + .withTitle("Objective 1") + .withState(SUCCESSFUL) + .build(); this.objectiveList = List.of(objective, objective, objective, objectiveCompleted); } @Test void getTeamByIdShouldBeSuccessful() { Long id = team1.getId(); - Mockito.when(teamPersistenceService.findById(id)).thenReturn(team1); + Mockito.when(teamPersistenceService.findById(id)) + .thenReturn(team1); Team team = teamBusinessService.getTeamById(id); @@ -93,7 +127,8 @@ void getTeamByIdShouldBeSuccessful() { @Test void getAllTeamsShouldBeSuccessful() { - Mockito.when(teamPersistenceService.findAll()).thenReturn(List.of(team1, team2)); + Mockito.when(teamPersistenceService.findAll()) + .thenReturn(List.of(team1, team2)); List teams = teamBusinessService.getAllTeams(defaultAuthorizationUser()); @@ -102,16 +137,35 @@ void getAllTeamsShouldBeSuccessful() { @Test void getAllTeamsSortedShouldReturnSortedListUserTeamsFirst() { - Team userTeam = Team.Builder.builder().withId(1L).withName("UserTeam").withVersion(1).build(); - Team notUserTeam = Team.Builder.builder().withId(2L).withName("NOTUserTeam").withVersion(1).build(); - Team notUserTeam2 = Team.Builder.builder().withId(3L).withName("NOTUserTeam2").withVersion(1).build(); + Team userTeam = Team.Builder.builder() + .withId(1L) + .withName("UserTeam") + .withVersion(1) + .build(); + Team notUserTeam = Team.Builder.builder() + .withId(2L) + .withName("NOTUserTeam") + .withVersion(1) + .build(); + Team notUserTeam2 = Team.Builder.builder() + .withId(3L) + .withName("NOTUserTeam2") + .withVersion(1) + .build(); List teams = List.of(notUserTeam, userTeam, notUserTeam2); User user = defaultUser(13L); - List userTeamList = List - .of(UserTeam.Builder.builder().withUser(user).withTeam(userTeam).withId(1L).build()); - AuthorizationUser authUser = new AuthorizationUser(User.Builder.builder().withId(user.getId()) - .withFirstname(user.getFirstname()).withLastname(user.getLastname()).withEmail(user.getEmail()) - .withUserTeamList(userTeamList).build()); + List userTeamList = List.of(UserTeam.Builder.builder() + .withUser(user) + .withTeam(userTeam) + .withId(1L) + .build()); + AuthorizationUser authUser = new AuthorizationUser(User.Builder.builder() + .withId(user.getId()) + .withFirstname(user.getFirstname()) + .withLastname(user.getLastname()) + .withEmail(user.getEmail()) + .withUserTeamList(userTeamList) + .build()); when(teamPersistenceService.findAll()).thenReturn(teams); List sortedList = teamBusinessService.getAllTeams(authUser); @@ -120,7 +174,10 @@ void getAllTeamsSortedShouldReturnSortedListUserTeamsFirst() { @Test void shouldSaveANewTeam_shouldSetCurrentUserAsAdmin() { - Team team = Team.Builder.builder().withName("OKR-TEAM").withId(2L).build(); + Team team = Team.Builder.builder() + .withName("OKR-TEAM") + .withId(2L) + .build(); var user = defaultUserWithTeams(1L, List.of(), List.of()); when(teamPersistenceService.save(team)).thenReturn(team); @@ -130,14 +187,23 @@ void shouldSaveANewTeam_shouldSetCurrentUserAsAdmin() { verify(teamPersistenceService, times(1)).save(team); verify(cacheService, times(1)).emptyAuthorizationUsersCache(); - assertEquals(user.getUserTeamList().size(), 1); - assertEquals(user.getUserTeamList().get(0).getTeam().getId(), team.getId()); - assertTrue(user.getUserTeamList().get(0).isTeamAdmin()); + assertEquals(user.getUserTeamList() + .size(), 1); + assertEquals(user.getUserTeamList() + .get(0) + .getTeam() + .getId(), team.getId()); + assertTrue(user.getUserTeamList() + .get(0) + .isTeamAdmin()); } @Test void shouldUpdateTeam() { - Team team = Team.Builder.builder().withId(1L).withName("OKR-TEAM").build(); + Team team = Team.Builder.builder() + .withId(1L) + .withName("OKR-TEAM") + .build(); teamBusinessService.updateTeam(team, team.getId()); verify(teamPersistenceService, times(1)).save(team); verify(cacheService, times(1)).emptyAuthorizationUsersCache(); @@ -146,8 +212,11 @@ void shouldUpdateTeam() { @Test void shouldDeleteTeamAndItsObjectives() { var team = defaultTeam(1L); - team.setUserTeamList( - List.of(UserTeam.Builder.builder().withTeam(team).withUser(new User()).withId(1L).build())); + team.setUserTeamList(List.of(UserTeam.Builder.builder() + .withTeam(team) + .withUser(new User()) + .withId(1L) + .build())); when(objectiveBusinessService.getEntitiesByTeamId(team.getId())).thenReturn(objectiveList); when(teamPersistenceService.findById(team.getId())).thenReturn(team); @@ -172,10 +241,18 @@ void addUsersToTeam_shouldAddUsersCorrectly() { teamBusinessService.addUsersToTeam(teamId, userIds); - var user1Teamids = user1.getUserTeamList().stream().map(ut -> ut.getTeam().getId()).toList(); + var user1Teamids = user1.getUserTeamList() + .stream() + .map(ut -> ut.getTeam() + .getId()) + .toList(); assertTrue(user1Teamids.contains(teamId)); - var user2Teamids = user2.getUserTeamList().stream().map(ut -> ut.getTeam().getId()).toList(); + var user2Teamids = user2.getUserTeamList() + .stream() + .map(ut -> ut.getTeam() + .getId()) + .toList(); assertTrue(user2Teamids.contains(teamId)); assertFalse(user1Teamids.contains(3L)); @@ -190,9 +267,14 @@ void removeUserFromTeam_shouldRemoveUser() { team2.setUserTeamList(new ArrayList<>(team2.getUserTeamList())); teamBusinessService.removeUserFromTeam(team2.getId(), user.getId()); - assertEquals(2, user.getUserTeamList().size()); - assertEquals(user.getUserTeamList().stream().map(ut -> ut.getTeam().getId()).toList(), - List.of(team1.getId(), team3.getId())); + assertEquals(2, + user.getUserTeamList() + .size()); + assertEquals(user.getUserTeamList() + .stream() + .map(ut -> ut.getTeam() + .getId()) + .toList(), List.of(team1.getId(), team3.getId())); verify(cacheService, times(1)).emptyAuthorizationUsersCache(); } @@ -212,8 +294,8 @@ void removeUserFromTeam_shouldThrowExceptionWhenLastAdminShouldBeRemoved() { when(teamPersistenceService.findById(team1.getId())).thenReturn(team1); assertThrows(OkrResponseStatusException.class, - () -> teamBusinessService.removeUserFromTeam(team1.getId(), user.getId()), - ErrorKey.TRIED_TO_DELETE_LAST_ADMIN.toString()); + () -> teamBusinessService.removeUserFromTeam(team1.getId(), user.getId()), + ErrorKey.TRIED_TO_DELETE_LAST_ADMIN.toString()); } @Test @@ -221,9 +303,15 @@ void updateOrAddTeamMembership_shouldUpdateIfTeamFound() { var user = defaultUserWithTeams(1L, List.of(team1), List.of(team2, team3)); when(userPersistenceService.findById(user.getId())).thenReturn(user); teamBusinessService.updateOrAddTeamMembership(team2.getId(), user.getId(), true); - assertTrue(user.getUserTeamList().get(0).isTeamAdmin()); - assertTrue(user.getUserTeamList().get(1).isTeamAdmin()); - assertFalse(user.getUserTeamList().get(2).isTeamAdmin()); + assertTrue(user.getUserTeamList() + .get(0) + .isTeamAdmin()); + assertTrue(user.getUserTeamList() + .get(1) + .isTeamAdmin()); + assertFalse(user.getUserTeamList() + .get(2) + .isTeamAdmin()); verify(cacheService, times(1)).emptyAuthorizationUsersCache(); } @@ -235,7 +323,7 @@ void updateOrAddTeamMembership_shouldThrowExceptionIfLastAdminShouldBeRemoved() when(userPersistenceService.findById(user.getId())).thenReturn(user); assertThrows(OkrResponseStatusException.class, - () -> teamBusinessService.updateOrAddTeamMembership(team1.getId(), user.getId(), false)); + () -> teamBusinessService.updateOrAddTeamMembership(team1.getId(), user.getId(), false)); } @Test @@ -248,16 +336,32 @@ void updateOrAddTeamMembership_shouldAddTeamIfNoTeamFound() { teamBusinessService.updateOrAddTeamMembership(team1.getId(), user.getId(), true); teamBusinessService.updateOrAddTeamMembership(team3.getId(), user.getId(), false); - assertFalse(user.getUserTeamList().get(0).isTeamAdmin()); - assertEquals(user.getUserTeamList().get(0).getTeam().getId(), team2.getId()); - - assertTrue(user.getUserTeamList().get(1).isTeamAdmin()); - assertEquals(user.getUserTeamList().get(1).getTeam().getId(), team1.getId()); - - assertFalse(user.getUserTeamList().get(2).isTeamAdmin()); - assertEquals(user.getUserTeamList().get(2).getTeam().getId(), team3.getId()); - - assertEquals(user.getUserTeamList().size(), 3); + assertFalse(user.getUserTeamList() + .get(0) + .isTeamAdmin()); + assertEquals(user.getUserTeamList() + .get(0) + .getTeam() + .getId(), team2.getId()); + + assertTrue(user.getUserTeamList() + .get(1) + .isTeamAdmin()); + assertEquals(user.getUserTeamList() + .get(1) + .getTeam() + .getId(), team1.getId()); + + assertFalse(user.getUserTeamList() + .get(2) + .isTeamAdmin()); + assertEquals(user.getUserTeamList() + .get(2) + .getTeam() + .getId(), team3.getId()); + + assertEquals(user.getUserTeamList() + .size(), 3); verify(cacheService, times(2)).emptyAuthorizationUsersCache(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java index 29eb1f74af..12a274f58b 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java @@ -1,11 +1,15 @@ package ch.puzzle.okr.service.business; -import ch.puzzle.okr.test.TestHelper; +import java.util.Arrays; +import java.util.List; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.service.CacheService; import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.service.validation.UserValidationService; +import ch.puzzle.okr.test.TestHelper; + import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,9 +21,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.Arrays; -import java.util.List; - import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -38,44 +39,76 @@ class UserBusinessServiceTest { @BeforeEach void setUp() { - User userAlice = User.Builder.builder().withId(2L).withFirstname("Alice").withLastname("Wunderland") - .withEmail("wunderland@puzzle.ch").build(); - - User userBob = User.Builder.builder().withId(9L).withFirstname("Bob").withLastname("Baumeister") - .withEmail("baumeister@puzzle.ch").build(); + User userAlice = User.Builder.builder() + .withId(2L) + .withFirstname("Alice") + .withLastname("Wunderland") + .withEmail("wunderland@puzzle.ch") + .build(); + + User userBob = User.Builder.builder() + .withId(9L) + .withFirstname("Bob") + .withLastname("Baumeister") + .withEmail("baumeister@puzzle.ch") + .build(); userList = Arrays.asList(userAlice, userBob); } @Test void shouldReturnAllUsersCorrect() throws ResponseStatusException { - Mockito.when(userPersistenceService.findAll()).thenReturn(userList); + Mockito.when(userPersistenceService.findAll()) + .thenReturn(userList); List userList = userBusinessService.getAllUsers(); - Assertions.assertThat(userList.size()).isEqualTo(2); - Assertions.assertThat(userList.get(0).getId()).isEqualTo(2); - Assertions.assertThat(userList.get(0).getFirstname()).isEqualTo("Alice"); - Assertions.assertThat(userList.get(0).getLastname()).isEqualTo("Wunderland"); - Assertions.assertThat(userList.get(0).getEmail()).isEqualTo("wunderland@puzzle.ch"); - Assertions.assertThat(userList.get(1).getId()).isEqualTo(9); - Assertions.assertThat(userList.get(1).getFirstname()).isEqualTo("Bob"); - Assertions.assertThat(userList.get(1).getLastname()).isEqualTo("Baumeister"); - Assertions.assertThat(userList.get(1).getEmail()).isEqualTo("baumeister@puzzle.ch"); + Assertions.assertThat(userList.size()) + .isEqualTo(2); + Assertions.assertThat(userList.get(0) + .getId()) + .isEqualTo(2); + Assertions.assertThat(userList.get(0) + .getFirstname()) + .isEqualTo("Alice"); + Assertions.assertThat(userList.get(0) + .getLastname()) + .isEqualTo("Wunderland"); + Assertions.assertThat(userList.get(0) + .getEmail()) + .isEqualTo("wunderland@puzzle.ch"); + Assertions.assertThat(userList.get(1) + .getId()) + .isEqualTo(9); + Assertions.assertThat(userList.get(1) + .getFirstname()) + .isEqualTo("Bob"); + Assertions.assertThat(userList.get(1) + .getLastname()) + .isEqualTo("Baumeister"); + Assertions.assertThat(userList.get(1) + .getEmail()) + .isEqualTo("baumeister@puzzle.ch"); } @Test void shouldReturnEmptyUsers() throws ResponseStatusException { List userList = userBusinessService.getAllUsers(); - Assertions.assertThat(userList.size()).isEqualTo(0); + Assertions.assertThat(userList.size()) + .isEqualTo(0); } @Test void shouldReturnSingleUserWhenFindingOwnerByValidId() { - User owner = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - Mockito.when(userPersistenceService.findById(any())).thenReturn(owner); + User owner = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + Mockito.when(userPersistenceService.findById(any())) + .thenReturn(owner); User returnedUser = userBusinessService.getUserById(1L); @@ -87,9 +120,14 @@ void shouldReturnSingleUserWhenFindingOwnerByValidId() { @Test void getOrCreateUserShouldReturnSingleUserWhenUserFound() { - User newUser = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - Mockito.when(userPersistenceService.getOrCreateUser(any())).thenReturn(newUser); + User newUser = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + Mockito.when(userPersistenceService.getOrCreateUser(any())) + .thenReturn(newUser); User returnedUser = userBusinessService.getOrCreateUser(newUser); @@ -101,9 +139,14 @@ void getOrCreateUserShouldReturnSingleUserWhenUserFound() { @Test void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { - User newUser = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - Mockito.when(userPersistenceService.getOrCreateUser(newUser)).thenReturn(newUser); + User newUser = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + Mockito.when(userPersistenceService.getOrCreateUser(newUser)) + .thenReturn(newUser); User returnedUser = userBusinessService.getOrCreateUser(newUser); @@ -115,10 +158,15 @@ void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { @Test void getOrCreateUserShouldThrowResponseStatusExceptionWhenInvalidUser() { - User newUser = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + User newUser = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); Mockito.doThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Not allowed to give an id")) - .when(validationService).validateOnGetOrCreate(newUser); + .when(validationService) + .validateOnGetOrCreate(newUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, () -> { userBusinessService.getOrCreateUser(newUser); diff --git a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java index e0ba905289..f402cf5140 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java @@ -1,8 +1,10 @@ package ch.puzzle.okr.service.clientconfig; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.test.SpringIntegrationTest; -import jakarta.persistence.EntityNotFoundException; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -10,7 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.util.stream.Stream; +import jakarta.persistence.EntityNotFoundException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrowsExactly; @@ -24,8 +26,7 @@ class ClientConfigServiceIT { @ParameterizedTest @MethodSource("tenantConfigs") - void getConfigBasedOnActiveEnv_validSubdomain_returnsCorrectTenantConfig(String hostname, String activeProfile, - String issuer, String clientId) { + void getConfigBasedOnActiveEnv_validSubdomain_returnsCorrectTenantConfig(String hostname, String activeProfile, String issuer, String clientId) { // arrange + act ClientConfigDto clientConfig = clientConfigService.getConfigBasedOnActiveEnv(hostname); @@ -37,15 +38,20 @@ void getConfigBasedOnActiveEnv_validSubdomain_returnsCorrectTenantConfig(String } private static Stream tenantConfigs() { - return Stream.of( - Arguments.of("pitc.okr.puzzle.ch", "prod", "http://localhost:8544/realms/pitc", "pitc_okr_staging"), - Arguments.of("acme.okr.puzzle.ch", "prod", "http://localhost:8544/realms/pitc", "acme_okr_staging")); + return Stream.of(Arguments.of("pitc.okr.puzzle.ch", + "prod", + "http://localhost:8544/realms/pitc", + "pitc_okr_staging"), + Arguments.of("acme.okr.puzzle.ch", + "prod", + "http://localhost:8544/realms/pitc", + "acme_okr_staging")); } @Test void getConfigBasedOnActiveEnv_invalidSubdomain_throwsException() { assertThrowsExactly(EntityNotFoundException.class, - () -> clientConfigService.getConfigBasedOnActiveEnv("foobar.okr.puzzle.ch")); + () -> clientConfigService.getConfigBasedOnActiveEnv("foobar.okr.puzzle.ch")); } @Test @@ -61,7 +67,9 @@ void getClientConfig_withOtherValues_returnsRightValues() { assertEquals("assets/images/triangles-okr-header.svg", clientConfig.triangles()); assertEquals("assets/images/puzzle-p.svg", clientConfig.backgroundLogo()); assertEquals("Puzzle OKR", clientConfig.title()); - assertEquals("#1e5a96", clientConfig.customStyles().get("okr-topbar-background-color")); + assertEquals("#1e5a96", + clientConfig.customStyles() + .get("okr-topbar-background-color")); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java index aced05adae..941db48ff0 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java @@ -1,16 +1,18 @@ package ch.puzzle.okr.service.clientconfig; +import java.util.HashMap; +import java.util.Optional; + import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.multitenancy.TenantConfigProvider; import ch.puzzle.okr.multitenancy.customization.TenantClientCustomization; import ch.puzzle.okr.multitenancy.customization.TenantClientCustomizationProvider; -import jakarta.persistence.EntityNotFoundException; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import java.util.HashMap; -import java.util.Optional; +import jakarta.persistence.EntityNotFoundException; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; @@ -20,7 +22,7 @@ public class ClientConfigServiceTest { @DisplayName("getConfigBasedOnActiveEnv() should be successful when tenant is configured properly") @ParameterizedTest - @CsvSource({ "pitc,pitc.ork.ch", "acme,acme-ork.ch" }) + @CsvSource({"pitc,pitc.ork.ch", "acme,acme-ork.ch"}) void getConfigBasedOnActiveEnvShouldBeSuccessfulWhenTenantIsConfiguredProperly(String tenant, String hostname) { // arrange TenantConfigProvider.TenantConfig tenantConfig = getTenantConfig(tenant); @@ -36,9 +38,8 @@ void getConfigBasedOnActiveEnvShouldBeSuccessfulWhenTenantIsConfiguredProperly(S @DisplayName("getConfigBasedOnActiveEnv() should throw exception if client customization is not found") @ParameterizedTest - @CsvSource({ "pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr" }) - void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientCustomizationIsNotFound(String tenant, String hostname, - String subdomain) { + @CsvSource({"pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr"}) + void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientCustomizationIsNotFound(String tenant, String hostname, String subdomain) { // arrange TenantConfigProvider.TenantConfig tenantConfig = getTenantConfig(tenant); ClientConfigService service = getClientConfig(tenantConfig, tenant); @@ -53,9 +54,8 @@ void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientCustomizationIsNotFoun @DisplayName("getConfigBasedOnActiveEnv() should throw exception if client config is not found") @ParameterizedTest - @CsvSource({ "pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr" }) - void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientConfigIsNotFound(String tenant, String hostname, - String subdomain) { + @CsvSource({"pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr"}) + void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientConfigIsNotFound(String tenant, String hostname, String subdomain) { // arrange TenantClientCustomization tenantCustomization = getTenantClientCustomization(tenant); ClientConfigService service = getClientConfig(tenantCustomization, tenant); @@ -68,8 +68,7 @@ void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientConfigIsNotFound(Strin assertEquals(expectedErrorMessage, entityNotFoundException.getMessage()); } - private ClientConfigService getClientConfig(TenantConfigProvider.TenantConfig tenantConfig, - TenantClientCustomization tenantClientCustomization, String tenantId) { + private ClientConfigService getClientConfig(TenantConfigProvider.TenantConfig tenantConfig, TenantClientCustomization tenantClientCustomization, String tenantId) { return mockClientConfigService(tenantConfig, tenantClientCustomization, tenantId); } @@ -81,38 +80,37 @@ private ClientConfigService getClientConfig(TenantConfigProvider.TenantConfig te return mockClientConfigService(tenantConfig, null, tenantId); } - private ClientConfigService mockClientConfigService(TenantConfigProvider.TenantConfig tenantConfig, - TenantClientCustomization tenantCustomization, String tenantId) { + private ClientConfigService mockClientConfigService(TenantConfigProvider.TenantConfig tenantConfig, TenantClientCustomization tenantCustomization, String tenantId) { TenantClientCustomizationProvider tenantCustomizationProvider = mock(TenantClientCustomizationProvider.class); when(tenantCustomizationProvider.getTenantClientCustomizationsById(tenantId)) // - .thenReturn(Optional.ofNullable(tenantCustomization)); + .thenReturn(Optional.ofNullable(tenantCustomization)); TenantConfigProvider tenantConfigProvider = mock(TenantConfigProvider.class); when(tenantConfigProvider.getTenantConfigById(tenantId)) // - .thenReturn(Optional.ofNullable(tenantConfig)); + .thenReturn(Optional.ofNullable(tenantConfig)); return new ClientConfigService(tenantCustomizationProvider, tenantConfigProvider); } private TenantConfigProvider.TenantConfig getTenantConfig(String tenantId) { return new TenantConfigProvider.TenantConfig( // - prefix(tenantId) + "tenantId", // - new String[] {}, // - prefix(tenantId) + "jwkSetUri", // - prefix(tenantId) + "issuerUrl", // - prefix(tenantId) + "clientId", // - null); + prefix(tenantId) + "tenantId", // + new String[]{}, // + prefix(tenantId) + "jwkSetUri", // + prefix(tenantId) + "issuerUrl", // + prefix(tenantId) + "clientId", // + null); } private TenantClientCustomization getTenantClientCustomization(String tenantId) { return new TenantClientCustomization( // - prefix(tenantId) + "favicon", // - prefix(tenantId) + "logo", // - prefix(tenantId) + "triangles", // - prefix(tenantId) + "backgroundLogo", // - prefix(tenantId) + "title", // - new HashMap<>()); + prefix(tenantId) + "favicon", // + prefix(tenantId) + "logo", // + prefix(tenantId) + "triangles", // + prefix(tenantId) + "backgroundLogo", // + prefix(tenantId) + "title", // + new HashMap<>()); } private void assertClientConfigDto(ClientConfigDto clientConfigDto, String tenant) { diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java index b8e62b6a63..e53e5f8f5c 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Action; @@ -8,14 +9,14 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; @@ -31,11 +32,21 @@ private static Action createAction(Long id) { } private static Action createAction(Long id, int version) { - return Action.Builder.builder().withId(id).withVersion(version).withAction("Neue Katze").withPriority(0) - .withIsChecked(false) - .withKeyResult(KeyResultMetric.Builder.builder().withBaseline(1.0).withStretchGoal(13.0).withId(8L) - .withObjective(Objective.Builder.builder().withId(1L).build()).build()) - .build(); + return Action.Builder.builder() + .withId(id) + .withVersion(version) + .withAction("Neue Katze") + .withPriority(0) + .withIsChecked(false) + .withKeyResult(KeyResultMetric.Builder.builder() + .withBaseline(1.0) + .withStretchGoal(13.0) + .withId(8L) + .withObjective(Objective.Builder.builder() + .withId(1L) + .build()) + .build()) + .build(); } private static final String UPDATED_ACTION = "Updated Action"; @@ -94,12 +105,13 @@ void updateActionShouldThrowExceptionWhenAlreadyUpdated() { changedAction.setAction(UPDATED_ACTION); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> actionPersistenceService.save(changedAction)); + () -> actionPersistenceService.save(changedAction)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of("Action"))); assertEquals(UNPROCESSABLE_ENTITY, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -114,9 +126,15 @@ void getAllActionsByKeyResultIdShouldReturnListOfAllActionsFromThisKeyResultOrde List actions = actionPersistenceService.getActionsByKeyResultIdOrderByPriorityAsc(6L); assertEquals(3, actions.size()); - assertEquals(1, actions.get(0).getPriority()); - assertEquals(2, actions.get(1).getPriority()); - assertEquals(3, actions.get(2).getPriority()); + assertEquals(1, + actions.get(0) + .getPriority()); + assertEquals(2, + actions.get(1) + .getPriority()); + assertEquals(3, + actions.get(2) + .getPriority()); } @Test @@ -127,7 +145,9 @@ void getActionByIdShouldReturnActionProperly() { assertEquals("Neues Haus", action.getAction()); assertEquals(1, action.getPriority()); assertTrue(action.isChecked()); - assertEquals(8L, action.getKeyResult().getId()); + assertEquals(8L, + action.getKeyResult() + .getId()); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java index de38eed3a5..299d01e54e 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -10,14 +11,14 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; @@ -29,9 +30,15 @@ class AlignmentPersistenceServiceIT { private Alignment createdAlignment; private static ObjectiveAlignment createObjectiveAlignment(Long id) { - return ObjectiveAlignment.Builder.builder().withId(id) - .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) - .withTargetObjective(Objective.Builder.builder().withId(4L).build()).build(); + return ObjectiveAlignment.Builder.builder() + .withId(id) + .withAlignedObjective(Objective.Builder.builder() + .withId(5L) + .build()) + .withTargetObjective(Objective.Builder.builder() + .withId(4L) + .build()) + .build(); } private static KeyResultAlignment createKeyResultAlignment(Long id) { @@ -39,9 +46,16 @@ private static KeyResultAlignment createKeyResultAlignment(Long id) { } private static KeyResultAlignment createKeyResultAlignment(Long id, int version) { - return KeyResultAlignment.Builder.builder().withId(id).withVersion(version) - .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) - .withTargetKeyResult(KeyResultMetric.Builder.builder().withId(8L).build()).build(); + return KeyResultAlignment.Builder.builder() + .withId(id) + .withVersion(version) + .withAlignedObjective(Objective.Builder.builder() + .withId(5L) + .build()) + .withTargetKeyResult(KeyResultMetric.Builder.builder() + .withId(8L) + .build()) + .build(); } @BeforeEach @@ -71,8 +85,12 @@ void saveAlignmentShouldSaveNewObjectiveAlignment() { createdAlignment = alignmentPersistenceService.save(alignment); assertNotNull(createdAlignment.getId()); - assertEquals(5L, createdAlignment.getAlignedObjective().getId()); - assertEquals(4L, ((ObjectiveAlignment) createdAlignment).getAlignmentTarget().getId()); + assertEquals(5L, + createdAlignment.getAlignedObjective() + .getId()); + assertEquals(4L, + ((ObjectiveAlignment) createdAlignment).getAlignmentTarget() + .getId()); } @Test @@ -82,15 +100,21 @@ void saveAlignmentShouldSaveNewKeyResultAlignment() { createdAlignment = alignmentPersistenceService.save(alignment); assertNotNull(createdAlignment.getId()); - assertEquals(5L, createdAlignment.getAlignedObjective().getId()); - assertEquals(8L, ((KeyResultAlignment) createdAlignment).getAlignmentTarget().getId()); + assertEquals(5L, + createdAlignment.getAlignedObjective() + .getId()); + assertEquals(8L, + ((KeyResultAlignment) createdAlignment).getAlignmentTarget() + .getId()); } @Test void updateAlignmentShouldSaveKeyResultAlignment() { createdAlignment = alignmentPersistenceService.save(createKeyResultAlignment(null)); Alignment updateAlignment = createKeyResultAlignment(createdAlignment.getId(), createdAlignment.getVersion()); - updateAlignment.setAlignedObjective(Objective.Builder.builder().withId(8L).build()); + updateAlignment.setAlignedObjective(Objective.Builder.builder() + .withId(8L) + .build()); Alignment updatedAlignment = alignmentPersistenceService.save(updateAlignment); @@ -102,16 +126,19 @@ void updateAlignmentShouldSaveKeyResultAlignment() { void updateAlignmentShouldThrowExceptionWhenAlreadyUpdated() { createdAlignment = alignmentPersistenceService.save(createKeyResultAlignment(null)); Alignment updateAlignment = createKeyResultAlignment(createdAlignment.getId(), 0); - updateAlignment.setAlignedObjective(Objective.Builder.builder().withId(8L).build()); + updateAlignment.setAlignedObjective(Objective.Builder.builder() + .withId(8L) + .build()); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> alignmentPersistenceService.save(updateAlignment)); + () -> alignmentPersistenceService.save(updateAlignment)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of("Alignment"))); assertEquals(UNPROCESSABLE_ENTITY, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -150,13 +177,21 @@ private void assertAlignment(Alignment alignment) { private void assertAlignment(ObjectiveAlignment objectiveAlignment) { assertEquals(1L, objectiveAlignment.getId()); - assertEquals(3L, objectiveAlignment.getAlignmentTarget().getId()); - assertEquals(4L, objectiveAlignment.getAlignedObjective().getId()); + assertEquals(3L, + objectiveAlignment.getAlignmentTarget() + .getId()); + assertEquals(4L, + objectiveAlignment.getAlignedObjective() + .getId()); } private void assertAlignment(KeyResultAlignment keyResultAlignment) { assertEquals(2L, keyResultAlignment.getId()); - assertEquals(8L, keyResultAlignment.getAlignmentTarget().getId()); - assertEquals(4L, keyResultAlignment.getAlignedObjective().getId()); + assertEquals(8L, + keyResultAlignment.getAlignmentTarget() + .getId()); + assertEquals(4L, + keyResultAlignment.getAlignedObjective() + .getId()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java index 60ab85c7d9..27aae6518f 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java @@ -1,18 +1,19 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; -import java.util.stream.Stream; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -33,12 +34,11 @@ void tearDown() { @Test void getAlignmentSelectionByQuarterIdAndTeamIdNotShouldReturnAlignmentSelections() { - List alignmentSelections = alignmentSelectionPersistenceService - .getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L); + List alignmentSelections = alignmentSelectionPersistenceService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, + 4L); assertEquals(12, alignmentSelections.size()); - alignmentSelections.forEach(alignmentSelection -> assertTrue( - matchAlignmentSelectionId(alignmentSelection.getAlignmentSelectionId()))); + alignmentSelections.forEach(alignmentSelection -> assertTrue(matchAlignmentSelectionId(alignmentSelection.getAlignmentSelectionId()))); } private boolean matchAlignmentSelectionId(AlignmentSelectionId alignmentSelectionId) { @@ -47,16 +47,16 @@ private boolean matchAlignmentSelectionId(AlignmentSelectionId alignmentSelectio private static Stream getExpectedAlignmentSelectionIds() { return Stream.of(AlignmentSelectionId.of(9L, 15L), // - AlignmentSelectionId.of(9L, 16L), // - AlignmentSelectionId.of(9L, 17L), // - AlignmentSelectionId.of(4L, 6L), // - AlignmentSelectionId.of(4L, 7L), // - AlignmentSelectionId.of(4L, 8L), // - AlignmentSelectionId.of(3L, 3L), // - AlignmentSelectionId.of(3L, 4L), // - AlignmentSelectionId.of(3L, 5L), // - AlignmentSelectionId.of(8L, 18L), // - AlignmentSelectionId.of(8L, 19L), // - AlignmentSelectionId.of(10L, -1L)); + AlignmentSelectionId.of(9L, 16L), // + AlignmentSelectionId.of(9L, 17L), // + AlignmentSelectionId.of(4L, 6L), // + AlignmentSelectionId.of(4L, 7L), // + AlignmentSelectionId.of(4L, 8L), // + AlignmentSelectionId.of(3L, 3L), // + AlignmentSelectionId.of(3L, 4L), // + AlignmentSelectionId.of(3L, 5L), // + AlignmentSelectionId.of(8L, 18L), // + AlignmentSelectionId.of(8L, 19L), // + AlignmentSelectionId.of(10L, -1L)); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java index 7d1e4450ce..a44e2a237d 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java @@ -1,18 +1,19 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -65,8 +66,10 @@ void appendObjectiveShouldReturnObjectiveWhenMemberRole() { void appendOverviewShouldReturnObjectiveWhenFirstLevelRoleAndTeamIdsEmpty() { Long quarterId = 2L; AuthorizationUser authorizationUser = defaultAuthorizationUser(); - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, List.of(), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + List.of(), + "", + authorizationUser); assertEquals(18L, overviews.size()); } @@ -75,8 +78,10 @@ void appendOverviewShouldReturnObjectiveWhenFirstLevelRoleAndTeamIdsEmpty() { void appendOverviewShouldReturnObjectiveWhenSecondLevelRole() { Long quarterId = 2L; AuthorizationUser authorizationUser = mockAuthorizationUser(defaultUser(null)); - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, List.of(5L), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + List.of(5L), + "", + authorizationUser); assertEquals(6L, overviews.size()); } @@ -85,8 +90,10 @@ void appendOverviewShouldReturnObjectiveWhenSecondLevelRole() { void appendOverviewShouldReturnObjectiveWhenMemberRole() { Long quarterId = 2L; AuthorizationUser authorizationUser = mockAuthorizationUser(defaultUser(null)); - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, List.of(5L), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + List.of(5L), + "", + authorizationUser); assertEquals(6L, overviews.size()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java index 7cff83afd8..d6c44750bc 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java @@ -1,8 +1,11 @@ package ch.puzzle.okr.service.persistence; +import java.util.*; +import java.util.stream.Stream; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; -import jakarta.persistence.*; + import org.apache.commons.lang3.NotImplementedException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,8 +13,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.*; -import java.util.stream.Stream; +import jakarta.persistence.*; import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static ch.puzzle.okr.test.TestHelper.mockAuthorizationUser; @@ -31,10 +33,10 @@ void setParametersShouldBeSuccessfulWithDefaultAuthorizationUser() { // assert var expected = """ - teamDraftState, State=DRAFT - userTeamIds, ListN=[1] - publishedStates, ListN=[ONGOING, SUCCESSFUL, NOTSUCCESSFUL] - """; + teamDraftState, State=DRAFT + userTeamIds, ListN=[1] + publishedStates, ListN=[ONGOING, SUCCESSFUL, NOTSUCCESSFUL] + """; assertEquals(expected, typedQueryMock.getLog()); } @@ -44,12 +46,12 @@ void setParametersShouldBeSuccessfulWithDefaultAuthorizationUser() { void setParametersShouldBeSuccessfulWhenUserIsOkrChampion() { // arrange var user = User.Builder.builder() // - .withId(23L) // - .withFirstname("Hanna") // - .withLastname("muster") // - .withEmail("hanna.muster@example.com") // - .withOkrChampion(true) // - .build(); + .withId(23L) // + .withFirstname("Hanna") // + .withLastname("muster") // + .withEmail("hanna.muster@example.com") // + .withOkrChampion(true) // + .build(); var criteria = new AuthorizationCriteria(); TypedQueryMock typedQueryMock = new TypedQueryMock<>(); @@ -58,9 +60,9 @@ void setParametersShouldBeSuccessfulWhenUserIsOkrChampion() { // assert var expected = """ - allDraftState, State=DRAFT - publishedStates, ListN=[ONGOING, SUCCESSFUL, NOTSUCCESSFUL] - """; + allDraftState, State=DRAFT + publishedStates, ListN=[ONGOING, SUCCESSFUL, NOTSUCCESSFUL] + """; assertEquals(expected, typedQueryMock.getLog()); } @@ -78,20 +80,20 @@ void setParametersShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List provideListAndString() { return Stream.of( // - Arguments.of(List.of(), null), // - Arguments.of(List.of(), ""), // - Arguments.of(null, null), // - Arguments.of(null, "")); + Arguments.of(List.of(), null), // + Arguments.of(List.of(), ""), // + Arguments.of(null, null), // + Arguments.of(null, "")); } @DisplayName("setParameters() should be successful when team ids and objective query are not empty") @@ -108,12 +110,12 @@ void setParametersShouldBeSuccessfulWhenTeamIdsAndObjectiveQueryAreNotEmpty() { // assert var expected = """ - teamIds, List12=[99] - objectiveQuery, String=OBJECTIVEQUERY - teamDraftState, State=DRAFT - userTeamIds, ListN=[1] - publishedStates, ListN=[ONGOING, SUCCESSFUL, NOTSUCCESSFUL] - """; + teamIds, List12=[99] + objectiveQuery, String=OBJECTIVEQUERY + teamDraftState, State=DRAFT + userTeamIds, ListN=[1] + publishedStates, ListN=[ONGOING, SUCCESSFUL, NOTSUCCESSFUL] + """; assertEquals(expected, typedQueryMock.getLog()); } @@ -131,80 +133,103 @@ public String getLog() { @Override public TypedQuery setParameter(Parameter parameter, T t) { - log.append(parameter.getName()).append(", ") // - .append(t.getClass().getSimpleName()).append("=").append(t) // - .append("\n"); + log.append(parameter.getName()) + .append(", ") // + .append(t.getClass() + .getSimpleName()) + .append("=") + .append(t) // + .append("\n"); return null; } @Override - public TypedQuery setParameter(Parameter parameter, Calendar calendar, - TemporalType temporalType) { - log.append(parameter.getName()).append(", ") // - .append(calendar.getTime()).append(", ") // - .append(temporalType.name()) // - .append("\n"); + public TypedQuery setParameter(Parameter parameter, Calendar calendar, TemporalType temporalType) { + log.append(parameter.getName()) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(Parameter parameter, Date date, TemporalType temporalType) { - log.append(parameter.getName()).append(", ") // - .append(date).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(parameter.getName()) + .append(", ") // + .append(date) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(String s, Object o) { - log.append(s).append(", ") // - .append(o.getClass().getSimpleName()).append("=").append(o) // - .append("\n"); + log.append(s) + .append(", ") // + .append(o.getClass() + .getSimpleName()) + .append("=") + .append(o) // + .append("\n"); return null; } @Override public TypedQuery setParameter(String s, Calendar calendar, TemporalType temporalType) { - log.append(s).append(", ") // - .append(calendar.getTime()).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(s) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(String s, Date date, TemporalType temporalType) { - log.append(s).append(", ") // - .append(date).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(s) + .append(", ") // + .append(date) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(int i, Object o) { - log.append(i).append(", ") // - .append(o.getClass().getSimpleName()).append("=").append(o) // - .append("\n"); + log.append(i) + .append(", ") // + .append(o.getClass() + .getSimpleName()) + .append("=") + .append(o) // + .append("\n"); return null; } @Override public TypedQuery setParameter(int i, Calendar calendar, TemporalType temporalType) { - log.append(i).append(", ") // - .append(calendar.getTime()).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(i) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(int i, Date date, TemporalType temporalType) { - log.append(i).append(", ") // - .append(date).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(i) + .append(", ") // + .append(date) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java index bdb382edaf..33a932cbfe 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java @@ -1,16 +1,17 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.List; -import java.util.stream.Stream; - import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static ch.puzzle.okr.test.TestHelper.mockAuthorizationUser; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,12 +38,12 @@ void appendObjectiveShouldBeSuccessfulWithDefaultAuthorizationUser() { void appendObjectiveShouldBeSuccessfulWhenUserIsOkrChampion() { // arrange var user = User.Builder.builder() // - .withId(23L) // - .withFirstname("Hanna") // - .withLastname("muster") // - .withEmail("hanna.muster@example.com") // - .withOkrChampion(true) // - .build(); + .withId(23L) // + .withFirstname("Hanna") // + .withLastname("muster") // + .withEmail("hanna.muster@example.com") // + .withOkrChampion(true) // + .build(); var criteria = new AuthorizationCriteria(); // act @@ -56,8 +57,7 @@ void appendObjectiveShouldBeSuccessfulWhenUserIsOkrChampion() { @DisplayName("appendOverview() should be successful when team ids or objective query are empty") @ParameterizedTest @MethodSource("provideListAndString") - void appendOverviewShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List teamIds, - String objectiveQuery) { + void appendOverviewShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List teamIds, String objectiveQuery) { // arrange var criteria = new AuthorizationCriteria(); @@ -71,10 +71,10 @@ void appendOverviewShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List provideListAndString() { return Stream.of( // - Arguments.of(List.of(), null), // - Arguments.of(List.of(), ""), // - Arguments.of(null, null), // - Arguments.of(null, "")); + Arguments.of(List.of(), null), // + Arguments.of(List.of(), ""), // + Arguments.of(null, null), // + Arguments.of(null, "")); } @DisplayName("appendOverview() should be successful when team ids and objective query are not empty") @@ -91,11 +91,10 @@ void appendOverviewShouldBeSuccessfulWhenTeamIdsAndObjectiveQueryAreNotEmpty() { var current = criteria.appendOverview(anyTeamIds, anyNonEmptyString, defaultAuthorizationUser()); // assert - var expected = startingNewLine + singleSpace - + """ - and o.overviewId.teamId in (:teamIds) - and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:objectiveQuery,'%')) - and ((o.objectiveState=:teamDraftState and o.overviewId.teamId IN (:userTeamIds)) or o.objectiveState IN (:publishedStates) or o.overviewId.objectiveId = -1)"""; + var expected = startingNewLine + singleSpace + """ + and o.overviewId.teamId in (:teamIds) + and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:objectiveQuery,'%')) + and ((o.objectiveState=:teamDraftState and o.overviewId.teamId IN (:userTeamIds)) or o.objectiveState IN (:publishedStates) or o.overviewId.objectiveId = -1)"""; assertEquals(expected, current); assertFalse(current.contains(anyNonEmptyString)); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java index 0837b5f996..b603a3349e 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java @@ -1,18 +1,19 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; +import java.util.Objects; + import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; -import java.util.Objects; - import static ch.puzzle.okr.Constants.CHECK_IN; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; @@ -42,8 +43,7 @@ void tearDown() { @Test void getCheckInsByKeyResultIdOrderByCheckInDateShouldGetCheckInsByKeyResultIdAndOrderThemByDateDesc() { // act - List checkIns = checkInPersistenceService - .getCheckInsByKeyResultIdOrderByCheckInDateDesc(KEY_RESULT_ID); + List checkIns = checkInPersistenceService.getCheckInsByKeyResultIdOrderByCheckInDateDesc(KEY_RESULT_ID); // assert assertThat(2, greaterThanOrEqualTo(checkIns.size())); @@ -53,7 +53,8 @@ void getCheckInsByKeyResultIdOrderByCheckInDateShouldGetCheckInsByKeyResultIdAnd } private void assertFirstIsCreatedAfterSecond(CheckIn first, CheckIn second) { - assertTrue(first.getCreatedOn().isAfter(second.getCreatedOn())); + assertTrue(first.getCreatedOn() + .isAfter(second.getCreatedOn())); } // uses data from V100_0_0__TestData.sql @@ -72,7 +73,8 @@ void getLastCheckInOfKeyResultShouldGetLastCheckInOfKeyResult() { private void assertLastIsCreatedAfterAllOtherCheckIns(CheckIn last, List allCheckIns) { for (CheckIn checkInLoop : allCheckIns) { if (!Objects.equals(checkInLoop.getId(), last.getId())) { - assertTrue(last.getCreatedOn().isAfter(checkInLoop.getCreatedOn())); + assertTrue(last.getCreatedOn() + .isAfter(checkInLoop.getCreatedOn())); } } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java index 651cfa0b88..492d8b8714 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java @@ -1,20 +1,21 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.http.HttpStatus.NOT_FOUND; @@ -34,9 +35,15 @@ private static Completed createCompleted(Long id) { } private static Completed createCompleted(Long id, int version) { - return Completed.Builder.builder().withId(id).withVersion(version) - .withObjective(Objective.Builder.builder().withId(OBJECTIVE_ID).withTitle(GUTE_LERNENDE).build()) - .withComment(WIR_HABEN_ES_GUT_GESCHAFFT).build(); + return Completed.Builder.builder() + .withId(id) + .withVersion(version) + .withObjective(Objective.Builder.builder() + .withId(OBJECTIVE_ID) + .withTitle(GUTE_LERNENDE) + .build()) + .withComment(WIR_HABEN_ES_GUT_GESCHAFFT) + .build(); } private static final String COMPLETED = "Completed"; @@ -67,8 +74,12 @@ void saveCompletedShouldSaveCompleted() { assertNotNull(createdCompleted.getId()); assertEquals(WIR_HABEN_ES_GUT_GESCHAFFT, createdCompleted.getComment()); - assertEquals(OBJECTIVE_ID, createdCompleted.getObjective().getId()); - assertEquals(GUTE_LERNENDE, createdCompleted.getObjective().getTitle()); + assertEquals(OBJECTIVE_ID, + createdCompleted.getObjective() + .getId()); + assertEquals(GUTE_LERNENDE, + createdCompleted.getObjective() + .getTitle()); } @Test @@ -91,13 +102,14 @@ void updateCompletedShouldThrowExceptionWhenAlreadyUpdated() { updateCompleted.setComment("Updated completed"); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> completedPersistenceService.save(updateCompleted)); + () -> completedPersistenceService.save(updateCompleted)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of(COMPLETED))); assertEquals(UNPROCESSABLE_ENTITY, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -107,7 +119,8 @@ void getCompletedShouldGetCompletedByObjectiveId() { assertNotNull(savedCompleted.getId()); assertEquals("War leider nicht moeglich", savedCompleted.getComment()); assertEquals("Als BBT wollen wir den Arbeitsalltag der Members von Puzzle ITC erleichtern.", - savedCompleted.getObjective().getTitle()); + savedCompleted.getObjective() + .getTitle()); } @Test @@ -116,13 +129,14 @@ void deleteCompletedIdShouldDeleteExistingCompletedByObjectiveId() { completedPersistenceService.deleteById(3L); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> completedPersistenceService.findById(3L)); + () -> completedPersistenceService.findById(3L)); List expectedErrors = List.of(new ErrorDto("MODEL_WITH_ID_NOT_FOUND", List.of(COMPLETED, "3"))); assertEquals(NOT_FOUND, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -132,12 +146,13 @@ void deleteCompletedShouldThrowExceptionWhenCompletedNotFound() { Long completedId = createdCompleted.getId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> completedPersistenceService.findById(completedId)); + () -> completedPersistenceService.findById(completedId)); List expectedErrors = List.of(new ErrorDto("MODEL_WITH_ID_NOT_FOUND", List.of(COMPLETED, "200"))); assertEquals(NOT_FOUND, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java index 75e33aea68..441d7f6edd 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java @@ -1,6 +1,8 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import java.time.LocalDateTime; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -11,14 +13,13 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.time.LocalDateTime; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.http.HttpStatus.*; @@ -30,11 +31,23 @@ class KeyResultPersistenceServiceIT { private KeyResultPersistenceService keyResultPersistenceService; private static KeyResult createKeyResultMetric(Long id) { - return KeyResultMetric.Builder.builder().withBaseline(3.0).withStretchGoal(5.0).withUnit(Unit.FTE).withId(id) - .withTitle("Title").withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultMetric.Builder.builder() + .withBaseline(3.0) + .withStretchGoal(5.0) + .withUnit(Unit.FTE) + .withId(id) + .withTitle("Title") + .withCreatedBy(User.Builder.builder() + .withId(1L) + .build()) + .withOwner(User.Builder.builder() + .withId(1L) + .build()) + .withObjective(Objective.Builder.builder() + .withId(4L) + .build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static KeyResult createKeyResultOrdinal(Long id) { @@ -42,12 +55,24 @@ private static KeyResult createKeyResultOrdinal(Long id) { } private static KeyResult createKeyResultOrdinal(Long id, int version) { - return KeyResultOrdinal.Builder.builder().withCommitZone("Hamster").withTargetZone("Katze") - .withStretchZone("ZOO").withId(id).withVersion(version).withTitle("Ordinal KeyResult") - .withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultOrdinal.Builder.builder() + .withCommitZone("Hamster") + .withTargetZone("Katze") + .withStretchZone("ZOO") + .withId(id) + .withVersion(version) + .withTitle("Ordinal KeyResult") + .withCreatedBy(User.Builder.builder() + .withId(1L) + .build()) + .withOwner(User.Builder.builder() + .withId(1L) + .build()) + .withObjective(Objective.Builder.builder() + .withId(4L) + .build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static final String KEY_RESULT_UPDATED = "Updated Key Result"; @@ -100,25 +125,27 @@ void getKeyResultByIdShouldReturnKeyResultProperly() { @Test void getKeyResultByIdShouldThrowExceptionWhenKeyResultNotFound() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(321L)); + () -> keyResultPersistenceService.findById(321L)); List expectedErrors = List.of(new ErrorDto(MODEL_NOT_FOUND, List.of(KEYRESULT, "321"))); assertEquals(NOT_FOUND, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void getKeyResultByIdShouldThrowExceptionWhenKeyResultIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(null)); + () -> keyResultPersistenceService.findById(null)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", KEYRESULT))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -129,22 +156,29 @@ void recreateEntityShouldUpdateKeyResultNoTypeChange() { Long keyResultId = createdKeyResult.getId(); KeyResult recreatedKeyResult = keyResultPersistenceService.recreateEntity(createdKeyResult.getId(), - createdKeyResult); + createdKeyResult); assertNotNull(createdKeyResult.getId()); assertEquals(KEY_RESULT_UPDATED, recreatedKeyResult.getTitle()); - assertEquals(createdKeyResult.getOwner().getId(), recreatedKeyResult.getOwner().getId()); - assertEquals(createdKeyResult.getObjective().getId(), recreatedKeyResult.getObjective().getId()); + assertEquals(createdKeyResult.getOwner() + .getId(), + recreatedKeyResult.getOwner() + .getId()); + assertEquals(createdKeyResult.getObjective() + .getId(), + recreatedKeyResult.getObjective() + .getId()); // Should delete the old KeyResult OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); assertEquals(NOT_FOUND, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); // delete re-created key result in tearDown() createdKeyResult = recreatedKeyResult; @@ -155,30 +189,43 @@ void recreateEntityShouldUpdateKeyResultWithTypeChange() { KeyResult keyResult = createKeyResultMetric(null); createdKeyResult = keyResultPersistenceService.save(keyResult); - KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Hund") - .withTargetZone("Hund + Katze").withStretchZone("Zoo").withId(createdKeyResult.getId()) - .withTitle(KEY_RESULT_UPDATED).withObjective(createdKeyResult.getObjective()) - .withOwner(createdKeyResult.getOwner()).withCreatedBy(createdKeyResult.getCreatedBy()) - .withCreatedOn(createdKeyResult.getCreatedOn()).build(); + KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() + .withCommitZone("Hund") + .withTargetZone("Hund + Katze") + .withStretchZone("Zoo") + .withId(createdKeyResult.getId()) + .withTitle(KEY_RESULT_UPDATED) + .withObjective(createdKeyResult.getObjective()) + .withOwner(createdKeyResult.getOwner()) + .withCreatedBy(createdKeyResult.getCreatedBy()) + .withCreatedOn(createdKeyResult.getCreatedOn()) + .build(); KeyResult recreatedKeyResult = keyResultPersistenceService.recreateEntity(keyResultOrdinal.getId(), - keyResultOrdinal); + keyResultOrdinal); assertNotNull(createdKeyResult.getId()); - assertEquals(createdKeyResult.getObjective().getId(), recreatedKeyResult.getObjective().getId()); + assertEquals(createdKeyResult.getObjective() + .getId(), + recreatedKeyResult.getObjective() + .getId()); assertEquals(KEY_RESULT_UPDATED, recreatedKeyResult.getTitle()); - assertEquals(createdKeyResult.getOwner().getId(), recreatedKeyResult.getOwner().getId()); + assertEquals(createdKeyResult.getOwner() + .getId(), + recreatedKeyResult.getOwner() + .getId()); Long keyResultId = createdKeyResult.getId(); // Should delete the old KeyResult OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); assertEquals(NOT_FOUND, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); // delete re-created key result in tearDown() createdKeyResult = recreatedKeyResult; @@ -198,8 +245,14 @@ void updateEntityShouldUpdateKeyResult() { assertEquals(createdKeyResult.getVersion() + 1, updatedKeyResult.getVersion()); assertEquals(KEY_RESULT_UPDATED, updatedKeyResult.getTitle()); assertEquals(THIS_IS_DESCRIPTION, updatedKeyResult.getDescription()); - assertEquals(createdKeyResult.getOwner().getId(), updatedKeyResult.getOwner().getId()); - assertEquals(createdKeyResult.getObjective().getId(), updatedKeyResult.getObjective().getId()); + assertEquals(createdKeyResult.getOwner() + .getId(), + updatedKeyResult.getOwner() + .getId()); + assertEquals(createdKeyResult.getObjective() + .getId(), + updatedKeyResult.getObjective() + .getId()); assertEquals(createdKeyResult.getModifiedOn(), updatedKeyResult.getModifiedOn()); } @@ -212,12 +265,13 @@ void updateEntityShouldThrowExceptionWhenAlreadyUpdated() { updateKeyResult.setDescription(THIS_IS_DESCRIPTION); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.updateEntity(updateKeyResult)); + () -> keyResultPersistenceService.updateEntity(updateKeyResult)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of(KEYRESULT))); assertEquals(UNPROCESSABLE_ENTITY, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -235,13 +289,14 @@ void deleteKeyResultByIdShouldDeleteExistingKeyResult() { Long keyResultId = createdKeyResult.getId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); assertEquals(NOT_FOUND, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -252,13 +307,14 @@ void deleteKeyResultShouldThrowExceptionWhenKeyResultNotFound() { Long keyResultId = newKeyResult.getId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); assertEquals(NOT_FOUND, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } private void execute() { diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java index 9708e9d779..046938648f 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -9,6 +12,7 @@ import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -19,9 +23,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import java.util.List; -import java.util.stream.Stream; - import static ch.puzzle.okr.exception.OkrResponseStatusException.of; import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static org.assertj.core.api.Assertions.assertThat; @@ -79,8 +80,9 @@ void tearDown() { @Test void findObjectiveByIdShouldReturnObjectiveProperly() { // act - var objective = objectivePersistenceService.findObjectiveById(ID_OF_OBJECTIVE_3, authorizationUser, - NO_RESULT_EXCEPTION); + var objective = objectivePersistenceService.findObjectiveById(ID_OF_OBJECTIVE_3, + authorizationUser, + NO_RESULT_EXCEPTION); // assert assertObjective(ID_OF_OBJECTIVE_3, TITLE_OF_OBJECTIVE_3, objective); @@ -90,8 +92,10 @@ void findObjectiveByIdShouldReturnObjectiveProperly() { @Test void findObjectiveByIdShouldThrowExceptionWhenObjectiveNotFound() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveById(INVALID_OBJECTIVE_ID, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveById(INVALID_OBJECTIVE_ID, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(REASON_UNAUTHORIZED, List.of())); @@ -103,7 +107,9 @@ void findObjectiveByIdShouldThrowExceptionWhenObjectiveNotFound() { void findObjectiveByIdShouldThrowExceptionWhenObjectiveIdIsNull() { // act var exception = assertThrows(OkrResponseStatusException.class, - () -> objectivePersistenceService.findObjectiveById(null, authorizationUser, NO_RESULT_EXCEPTION)); + () -> objectivePersistenceService.findObjectiveById(null, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(ATTRIBUTE_NULL, List.of("ID", OBJECTIVE))); @@ -114,8 +120,9 @@ void findObjectiveByIdShouldThrowExceptionWhenObjectiveIdIsNull() { @Test void findObjectiveByKeyResultIdShouldReturnObjectiveProperly() { // act - var objective = objectivePersistenceService.findObjectiveByKeyResultId(ID_OF_KEY_RESULT_5, authorizationUser, - NO_RESULT_EXCEPTION); + var objective = objectivePersistenceService.findObjectiveByKeyResultId(ID_OF_KEY_RESULT_5, + authorizationUser, + NO_RESULT_EXCEPTION); // assert assertObjective(ID_OF_OBJECTIVE_3, TITLE_OF_OBJECTIVE_3, objective); @@ -125,8 +132,10 @@ void findObjectiveByKeyResultIdShouldReturnObjectiveProperly() { @Test void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByKeyResultId(INVALID_KEY_RESULT_ID, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByKeyResultId(INVALID_KEY_RESULT_ID, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(REASON_UNAUTHORIZED, List.of())); @@ -137,8 +146,10 @@ void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { @Test void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveIdIsNull() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByKeyResultId(null, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByKeyResultId(null, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(ATTRIBUTE_NULL, List.of("ID", OBJECTIVE))); @@ -149,8 +160,9 @@ void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveIdIsNull() { @Test void findObjectiveByCheckInIdShouldReturnObjectiveProperly() { // act - var objective = objectivePersistenceService.findObjectiveByCheckInId(ID_OF_CHECK_IN_7, authorizationUser, - NO_RESULT_EXCEPTION); + var objective = objectivePersistenceService.findObjectiveByCheckInId(ID_OF_CHECK_IN_7, + authorizationUser, + NO_RESULT_EXCEPTION); // assert assertObjective(ID_OF_OBJECTIVE_3, TITLE_OF_OBJECTIVE_3, objective); @@ -160,8 +172,10 @@ void findObjectiveByCheckInIdShouldReturnObjectiveProperly() { @Test void findObjectiveByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByCheckInId(INVALID_CHECK_IN_ID, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByCheckInId(INVALID_CHECK_IN_ID, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(REASON_UNAUTHORIZED, List.of())); @@ -172,8 +186,10 @@ void findObjectiveByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { @Test void findObjectiveByCheckInIdShouldThrowExceptionWhenObjectiveIdIsNull() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByCheckInId(null, authorizationUser, ObjectivePersistenceServiceIT.NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByCheckInId(null, + authorizationUser, + ObjectivePersistenceServiceIT.NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(ATTRIBUTE_NULL, List.of("ID", OBJECTIVE))); @@ -217,8 +233,12 @@ void findObjectiveByTeamIdShouldReturnEmptyListWhenObjectiveIdIsNull() { @Test void countByTeamAndQuarterShouldReturnNumberOfObjectivesForCurrentQuarter() { // arrange: there are 3 objectives for the current quarter (id 2) for team with id 6 - var team = Team.Builder.builder().withId(ID_OF_TEAM_6).build(); - var quarter = Quarter.Builder.builder().withId(CURRENT_QUARTER_ID).build(); + var team = Team.Builder.builder() + .withId(ID_OF_TEAM_6) + .build(); + var quarter = Quarter.Builder.builder() + .withId(CURRENT_QUARTER_ID) + .build(); // act var count = objectivePersistenceService.countByTeamAndQuarter(team, quarter); @@ -239,24 +259,32 @@ void countByTeamAndQuarterShouldReturnZeroWhenTeamOrQuarterIsNotValidOrNull(Team } private static Stream invalidTeamsAndQuarters() { - var validTeam = Team.Builder.builder().withId(ID_OF_TEAM_6).build(); - var invalidTeam = Team.Builder.builder().withId(INVALID_TEAM_ID).build(); - var validQuarter = Quarter.Builder.builder().withId(CURRENT_QUARTER_ID).build(); - var invalidQuarter = Quarter.Builder.builder().withId(INVALID_QUARTER_ID).build(); + var validTeam = Team.Builder.builder() + .withId(ID_OF_TEAM_6) + .build(); + var invalidTeam = Team.Builder.builder() + .withId(INVALID_TEAM_ID) + .build(); + var validQuarter = Quarter.Builder.builder() + .withId(CURRENT_QUARTER_ID) + .build(); + var invalidQuarter = Quarter.Builder.builder() + .withId(INVALID_QUARTER_ID) + .build(); return Stream.of( - // valid team + invalid quarter - arguments(validTeam, invalidQuarter), - // valid team + null quarter - arguments(validTeam, null), - // invalid team + valid quarter - arguments(invalidTeam, validQuarter), - // invalid team + null quarter - arguments(null, validQuarter), - // invalid team + invalid quarter - arguments(invalidTeam, invalidQuarter), - // null team + null quarter - arguments(null, null)); + // valid team + invalid quarter + arguments(validTeam, invalidQuarter), + // valid team + null quarter + arguments(validTeam, null), + // invalid team + valid quarter + arguments(invalidTeam, validQuarter), + // invalid team + null quarter + arguments(null, validQuarter), + // invalid team + invalid quarter + arguments(invalidTeam, invalidQuarter), + // null team + null quarter + arguments(null, null)); } @DisplayName("getModelName() should return Objective") @@ -265,11 +293,11 @@ void getModelNameShouldReturnObjective() { assertEquals(OBJECTIVE, objectivePersistenceService.getModelName()); } - private void assertResponseStatusException(HttpStatus expectedStatus, List expectedErrors, - OkrResponseStatusException currentException) { + private void assertResponseStatusException(HttpStatus expectedStatus, List expectedErrors, OkrResponseStatusException currentException) { assertEquals(expectedStatus, currentException.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(currentException.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(currentException.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(currentException.getReason())); } private void assertObjective(Long expectedId, String expectedTitle, Objective currentObjective) { diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java index fb74abd66e..58b413b028 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java @@ -1,18 +1,19 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -20,27 +21,27 @@ @SpringIntegrationTest class OverviewPersistenceServiceIT { private static final List expectedOverviewIds = List.of( // index: - OverviewId.of(4L, 5L, 9L, 15L), // 0 - OverviewId.of(4L, 5L, 10L, 14L), // 1 - OverviewId.of(4L, 6L, 12L, 12L), // 2 - OverviewId.of(4L, 6L, 13L, 11L), // 3 - OverviewId.of(4L, 6L, 14L, 10L), // 4 - OverviewId.of(5L, 3L, 3L, 9L), // 5 - OverviewId.of(5L, 3L, 4L, 8L), // 6 - OverviewId.of(5L, 3L, 5L, 7L), // 7 - OverviewId.of(5L, 4L, 6L, 5L), // 8 - OverviewId.of(5L, 4L, 7L, 4L), // 9 - OverviewId.of(5L, 4L, 8L, 2L), // 10 - OverviewId.of(6L, 8L, 18L, 20L), // 11 - OverviewId.of(6L, 8L, 19L, 19L), // 12 - OverviewId.of(6L, 9L, 15L, 18L), // 13 - OverviewId.of(6L, 9L, 16L, 17L), // 14 - OverviewId.of(6L, 9L, 17L, 16L), // 15 - OverviewId.of(6L, 10L, -1L, -1L), // 16 - OverviewId.of(8L, -1L, -1L, -1L), // 17 - OverviewId.of(5L, -1L, -1L, -1L), // 18 - OverviewId.of(6L, -1L, -1L, -1L), // 19 - OverviewId.of(4L, -1L, -1L, -1L)); // 20 + OverviewId.of(4L, 5L, 9L, 15L), // 0 + OverviewId.of(4L, 5L, 10L, 14L), // 1 + OverviewId.of(4L, 6L, 12L, 12L), // 2 + OverviewId.of(4L, 6L, 13L, 11L), // 3 + OverviewId.of(4L, 6L, 14L, 10L), // 4 + OverviewId.of(5L, 3L, 3L, 9L), // 5 + OverviewId.of(5L, 3L, 4L, 8L), // 6 + OverviewId.of(5L, 3L, 5L, 7L), // 7 + OverviewId.of(5L, 4L, 6L, 5L), // 8 + OverviewId.of(5L, 4L, 7L, 4L), // 9 + OverviewId.of(5L, 4L, 8L, 2L), // 10 + OverviewId.of(6L, 8L, 18L, 20L), // 11 + OverviewId.of(6L, 8L, 19L, 19L), // 12 + OverviewId.of(6L, 9L, 15L, 18L), // 13 + OverviewId.of(6L, 9L, 16L, 17L), // 14 + OverviewId.of(6L, 9L, 17L, 16L), // 15 + OverviewId.of(6L, 10L, -1L, -1L), // 16 + OverviewId.of(8L, -1L, -1L, -1L), // 17 + OverviewId.of(5L, -1L, -1L, -1L), // 18 + OverviewId.of(6L, -1L, -1L, -1L), // 19 + OverviewId.of(4L, -1L, -1L, -1L)); // 20 private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); @Autowired @@ -58,8 +59,10 @@ void tearDown() { @Test void getFilteredOverviewShouldReturnOverviewsWhenTeamIdsSet() { - List overviews = overviewPersistenceService.getFilteredOverview(2L, List.of(5L, 6L, 8L), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(2L, + List.of(5L, 6L, 8L), + "", + authorizationUser); assertThat(expectedOverviewIds.subList(5, 18)).hasSameElementsAs(getOverviewIds(overviews)); } @@ -73,29 +76,37 @@ void getFilteredOverviewShouldReturnOverviewsWhenTeamIdsEmpty() { @Test void getFilteredOverviewShouldReturnOverviewsWhenObjectiveQuery() { - List overviews = overviewPersistenceService.getFilteredOverview(2L, List.of(5L, 6L, 8L), - "kundenzufriedenheit", authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(2L, + List.of(5L, 6L, 8L), + "kundenzufriedenheit", + authorizationUser); assertThat(expectedOverviewIds.subList(5, 8)).hasSameElementsAs(getOverviewIds(overviews)); } @Test void getFilteredOverviewShouldReturnOverviewsWhenQuarterWithoutObjectives() { - List overviews = overviewPersistenceService.getFilteredOverview(3L, List.of(5L, 6L, 8L), null, - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(3L, + List.of(5L, 6L, 8L), + null, + authorizationUser); assertThat(expectedOverviewIds.subList(17, 20)).hasSameElementsAs(getOverviewIds(overviews)); } @Test void getFilteredOverviewShouldReturnOverviewsWhenQuarterWithoutObjectivesAndObjectiveQuery() { - List overviews = overviewPersistenceService.getFilteredOverview(3L, List.of(5L, 6L, 8L), - "kundenzufriedenheit", authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(3L, + List.of(5L, 6L, 8L), + "kundenzufriedenheit", + authorizationUser); assertTrue(overviews.isEmpty()); } private List getOverviewIds(List overviewList) { - return overviewList.stream().map(Overview::getOverviewId).toList(); + return overviewList.stream() + .map(Overview::getOverviewId) + .toList(); } } \ No newline at end of file diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java index 7f5a60a5e5..1321a6cce0 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java @@ -1,10 +1,13 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.repository.UserRepository; import ch.puzzle.okr.test.SpringIntegrationTest; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -13,8 +16,6 @@ import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static ch.puzzle.okr.test.TestHelper.getAllErrorKeys; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; @@ -37,10 +38,10 @@ public class PersistenceBaseTestIT { private static final long NON_EXISTING_USER_ID = 321L; private static final long USER_PACO_ID = 1L; private static final User USER_WITHOUT_CONSTRAINTS = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("hans.muster@puzzle.ch") // - .build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("hans.muster@puzzle.ch") // + .build(); @Autowired private PersistenceBase persistenceBase; @@ -72,7 +73,7 @@ void findByIdShouldReturnSingleEntityIfEntityWithIdExists() { @Test void findByIdShouldThrowExceptionIfEntityWithIdDoesNotExist() { var exception = assertThrows(ResponseStatusException.class, - () -> persistenceBase.findById(NON_EXISTING_USER_ID)); + () -> persistenceBase.findById(NON_EXISTING_USER_ID)); assertEquals(NOT_FOUND, exception.getStatusCode()); assertErrorKey("MODEL_WITH_ID_NOT_FOUND", exception); @@ -162,8 +163,7 @@ void deleteByIdShouldDeleteEntity() throws ResponseStatusException { assertEntityNotFound(createdUserId); } - private static void assertUser(String expectedFirstName, String expectedLastName, String expectedEmail, - User currentUser) { + private static void assertUser(String expectedFirstName, String expectedLastName, String expectedEmail, User currentUser) { assertEquals(expectedFirstName, currentUser.getFirstname()); assertEquals(expectedLastName, currentUser.getLastname()); assertEquals(expectedEmail, currentUser.getEmail()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java index 1eee877cc1..c42df54e09 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java @@ -1,19 +1,20 @@ package ch.puzzle.okr.service.persistence; +import java.time.LocalDate; +import java.util.List; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; import ch.puzzle.okr.util.quarter.check.QuarterRangeChecker; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.time.LocalDate; -import java.util.List; - import static ch.puzzle.okr.Constants.QUARTER; import static ch.puzzle.okr.test.TestConstants.GJ_FOR_TESTS_QUARTER_ID; import static ch.puzzle.okr.test.TestConstants.GJ_FOR_TEST_QUARTER_LABEL; @@ -47,13 +48,17 @@ void getMostCurrentQuartersShouldReturnCurrentQuarterAndFutureQuarterAndGJForTes private void assertGJForTestsQuarterIsFoundOnce(List quarters) { long foundGJForTestsQuartersCount = quarters.stream() - .filter(quarter -> quarter.getLabel().equals(GJ_FOR_TEST_QUARTER_LABEL)).count(); + .filter(quarter -> quarter.getLabel() + .equals(GJ_FOR_TEST_QUARTER_LABEL)) + .count(); assertEquals(1, foundGJForTestsQuartersCount); } private void assertCurrentQuarterIsFoundOnce(List quarters) { long foundCurrentQuartersCount = quarters.stream() - .filter(quarter -> QuarterRangeChecker.nowIsInQuarter(LocalDate.now(), quarter)).count(); + .filter(quarter -> QuarterRangeChecker.nowIsInQuarter(LocalDate.now(), + quarter)) + .count(); assertEquals(1, foundCurrentQuartersCount); } @@ -61,11 +66,15 @@ private void assertCurrentQuarterIsFoundOnce(List quarters) { void shouldReturnCurrentQuarter() { Quarter quarter = quarterPersistenceService.getCurrentQuarter(); - assertTrue(LocalDate.now().isEqual(quarter.getStartDate()) || // - LocalDate.now().isAfter(quarter.getStartDate())); + assertTrue(LocalDate.now() + .isEqual(quarter.getStartDate()) || // + LocalDate.now() + .isAfter(quarter.getStartDate())); - assertTrue(LocalDate.now().isEqual(quarter.getEndDate()) || // - LocalDate.now().isBefore(quarter.getEndDate())); + assertTrue(LocalDate.now() + .isEqual(quarter.getEndDate()) || // + LocalDate.now() + .isBefore(quarter.getEndDate())); assertNotNull(quarter.getId()); assertNotNull(quarter.getLabel()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java index f37812cb21..f27d977a23 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java @@ -1,16 +1,17 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.models.Team; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; - import static ch.puzzle.okr.Constants.TEAM; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -32,8 +33,12 @@ void findTeamsByNameShouldReturnTeamsWithMatchingName() { List teams = teamPersistenceService.findTeamsByName("LoremIpsum"); assertEquals(1, teams.size()); - assertEquals(6, teams.get(0).getId()); - assertEquals("LoremIpsum", teams.get(0).getName()); + assertEquals(6, + teams.get(0) + .getId()); + assertEquals("LoremIpsum", + teams.get(0) + .getName()); } @DisplayName("getModelName() should return Team") diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java index 0104060b48..9f7c89d469 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java @@ -1,17 +1,18 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; +import java.util.Optional; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; -import java.util.Optional; - import static ch.puzzle.okr.Constants.USER; import static ch.puzzle.okr.util.CollectionUtils.iterableToList; import static org.junit.jupiter.api.Assertions.*; @@ -43,10 +44,11 @@ void tearDown() { void saveShouldSaveUserWithEmptyUserTeamList() { // arrange var newUser = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("muster@puzzle.ch") // - .withUserTeamList(List.of()).build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("muster@puzzle.ch") // + .withUserTeamList(List.of()) + .build(); // act createdUser = userPersistenceService.save(newUser); @@ -61,10 +63,11 @@ void saveShouldSaveUserWithEmptyUserTeamList() { void saveShouldSaveUserWithNullUserTeamList() { // arrange var newUser = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("muster@puzzle.ch") // - .withUserTeamList(null).build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("muster@puzzle.ch") // + .withUserTeamList(null) + .build(); // act createdUser = userPersistenceService.save(newUser); @@ -79,10 +82,10 @@ void saveShouldSaveUserWithNullUserTeamList() { void saveAllShouldSaveAllUsersInTheInputList() { // arrange var newUser = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("muster@puzzle.ch") // - .build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("muster@puzzle.ch") // + .build(); // act var createdUsers = iterableToList(userPersistenceService.saveAll(List.of(newUser))); @@ -99,7 +102,9 @@ void saveAllShouldSaveAllUsersInTheInputList() { @Test void getOrCreateUserShouldReturnSingleUserWhenUserFound() { // arrange - var existingUser = User.Builder.builder().withEmail("wunderland@puzzle.ch").build(); + var existingUser = User.Builder.builder() + .withEmail("wunderland@puzzle.ch") + .build(); // act var returnedUser = userPersistenceService.getOrCreateUser(existingUser); @@ -113,11 +118,11 @@ void getOrCreateUserShouldReturnSingleUserWhenUserFound() { void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { // arrange var newUser = User.Builder.builder() // - .withId(null) // - .withFirstname("firstname") // - .withLastname("lastname") // - .withEmail("lastname@puzzle.ch") // - .build(); + .withId(null) // + .withFirstname("firstname") // + .withLastname("lastname") // + .withEmail("lastname@puzzle.ch") // + .build(); // act createdUser = userPersistenceService.getOrCreateUser(newUser); @@ -134,20 +139,26 @@ void findByEmailShouldReturnUserIfEmailIsFound() { Optional user = userPersistenceService.findByEmail("gl@gl.com"); assertTrue(user.isPresent()); - assertEquals("Jaya", user.get().getFirstname()); - assertEquals("Norris", user.get().getLastname()); + assertEquals("Jaya", + user.get() + .getFirstname()); + assertEquals("Norris", + user.get() + .getLastname()); } @DisplayName("findByEmail() should return empty optional if email is not found") @Test void findByEmailShouldReturnEmptyOptionalIfEmailIsNotFound() { - assertTrue(userPersistenceService.findByEmail("not_valid@gl.com").isEmpty()); + assertTrue(userPersistenceService.findByEmail("not_valid@gl.com") + .isEmpty()); } @DisplayName("findByEmail() should return empty optional if email is null") @Test void findByEmailShouldReturnEmptyOptionalIfEmailIsNull() { - assertTrue(userPersistenceService.findByEmail(null).isEmpty()); + assertTrue(userPersistenceService.findByEmail(null) + .isEmpty()); } // uses data from V100_0_0__TestData.sql diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java index cc2dfe71b8..575ab70866 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java @@ -1,16 +1,17 @@ package ch.puzzle.okr.service.persistence; +import java.util.List; + import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; -import java.util.List; - // uses test date from V100_0_0__TestData.sql @SpringIntegrationTest public class UserTeamPersistenceServiceIT { @@ -45,11 +46,14 @@ void deleteShouldRemoveSingleUserFromTeam() { assertUserIsInTeam(ID_OF_USER_ALICE, ID_OF_TEAM_LOREM, 3); // arrange - var userTeamToRemove = user.getUserTeamList().get(0); // Alice is only in Team Lorem + var userTeamToRemove = user.getUserTeamList() + .get(0); // Alice is only in Team Lorem // act - user.getUserTeamList().remove(userTeamToRemove); - team.getUserTeamList().remove(userTeamToRemove); + user.getUserTeamList() + .remove(userTeamToRemove); + team.getUserTeamList() + .remove(userTeamToRemove); userTeamPersistenceService.delete(userTeamToRemove); // assert: user Alice is no longer in team Lorem and team Lorem has 2 users @@ -68,11 +72,14 @@ void deleteAllShouldRemoveListOfUsersFromTeam() { assertUserIsInTeam(ID_OF_USER_BOB, ID_OF_TEAM_CUBE, 2); // arrange - var userTeamToRemove = user.getUserTeamList().get(0); // Bos is only in Team Cube + var userTeamToRemove = user.getUserTeamList() + .get(0); // Bos is only in Team Cube // act - user.getUserTeamList().remove(userTeamToRemove); - team.getUserTeamList().remove(userTeamToRemove); + user.getUserTeamList() + .remove(userTeamToRemove); + team.getUserTeamList() + .remove(userTeamToRemove); userTeamPersistenceService.deleteAll(List.of(userTeamToRemove)); // assert: user Bob is no longer in team Cube and team Cube has 1 user @@ -81,18 +88,26 @@ void deleteAllShouldRemoveListOfUsersFromTeam() { private void assertUserIsInTeam(Long userId, Long teamId, int expectedUsersInTeam) { var user = userPersistenceService.findById(userId); - Assertions.assertEquals(1, user.getUserTeamList().size()); + Assertions.assertEquals(1, + user.getUserTeamList() + .size()); var team = this.teamPersistenceService.findById(teamId); - Assertions.assertEquals(expectedUsersInTeam, team.getUserTeamList().size()); + Assertions.assertEquals(expectedUsersInTeam, + team.getUserTeamList() + .size()); } private void assertUserIsRemovedFromTeam(Long userId, Long teamId, int expectedUsersInTeam) { var reloadedUser = userPersistenceService.findById(userId); - Assertions.assertEquals(0, reloadedUser.getUserTeamList().size()); + Assertions.assertEquals(0, + reloadedUser.getUserTeamList() + .size()); var reloadedTeam = this.teamPersistenceService.findById(teamId); - Assertions.assertEquals(expectedUsersInTeam, reloadedTeam.getUserTeamList().size()); + Assertions.assertEquals(expectedUsersInTeam, + reloadedTeam.getUserTeamList() + .size()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java index 1521f05a33..1ef6b84ce5 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java @@ -1,11 +1,15 @@ package ch.puzzle.okr.service.validation; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.persistence.ActionPersistenceService; + import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -20,9 +24,6 @@ import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; -import java.util.stream.Stream; - import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.params.provider.Arguments.arguments; @@ -33,21 +34,25 @@ @ExtendWith(MockitoExtension.class) class ActionValidationServiceTest { private final KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withId(10L) // - .withTitle("KR Title").build(); // + .withId(10L) // + .withTitle("KR Title") + .build(); // private final Action action1 = Action.Builder.builder() // - .withId(null) // - .withAction("Neue Katze") // - .withIsChecked(false) // - .withPriority(0) // - .withKeyResult(keyResult).build(); + .withId(null) // + .withAction("Neue Katze") // + .withIsChecked(false) // + .withPriority(0) // + .withKeyResult(keyResult) + .build(); private final Action action2 = Action.Builder.builder() // - .withId(2L) // - .withAction("Neues Lama") // - .withIsChecked(true) // // - .withPriority(1).withKeyResult(keyResult).build(); + .withId(2L) // + .withAction("Neues Lama") // + .withIsChecked(true) // // + .withPriority(1) + .withKeyResult(keyResult) + .build(); @Mock ActionPersistenceService actionPersistenceService; @@ -55,15 +60,14 @@ class ActionValidationServiceTest { @Mock KeyResultValidationService keyResultValidationService; - @Spy - @InjectMocks + @Spy @InjectMocks private ActionValidationService validator; private static Stream actionValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 5000), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("action", "Action", "0", "4096")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))))); + return Stream.of(arguments(StringUtils.repeat('1', 5000), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("action", "Action", "0", "4096")))), + arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))))); } private record ActionPair(Action action, Action saveAction) { @@ -72,40 +76,69 @@ private record ActionPair(Action action, Action saveAction) { // generate Pairs of Actions with and without KeyResults private static Stream actionPairArgument() { Long id = 3L; - KeyResult keyResult = KeyResultMetric.Builder.builder().withId(10L).withTitle("KR Title").build(); // + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withId(10L) + .withTitle("KR Title") + .build(); // return Stream.of( // - Arguments.of(new ActionPair( // - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build(), - - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build())), - - Arguments.of(new ActionPair( // - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(keyResult).build(), - - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build())), - - Arguments.of(new ActionPair( // - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build(), - - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) - .withKeyResult(keyResult).build()))); + Arguments.of(new ActionPair( // + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build(), + + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build())), + + Arguments.of(new ActionPair( // + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(keyResult) + .build(), + + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build())), + + Arguments.of(new ActionPair( // + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build(), + + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) + .withKeyResult(keyResult) + .build()))); } @BeforeEach void setUp() { - Mockito.lenient().when(actionPersistenceService.getModelName()).thenReturn("Action"); + Mockito.lenient() + .when(actionPersistenceService.getModelName()) + .thenReturn("Action"); } @Test @@ -120,11 +153,11 @@ void validateOnCreateShouldBeSuccessfulWhenActionIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // arrange OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); // act + assert List expectedErrors = List.of( // - new ErrorDto("MODEL_NULL", List.of("Action"))); + new ErrorDto("MODEL_NULL", List.of("Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -132,11 +165,11 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // arrange OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(action2)); + () -> validator.validateOnCreate(action2)); // act + assert List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -144,12 +177,17 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @MethodSource("actionValidationArguments") void validateOnCreateShouldThrowExceptionWhenActionIsInvalid(String actionText, List errors) { // arrange - Action action = Action.Builder.builder().withId(null).withAction(actionText).withIsChecked(false) - .withPriority(1).withKeyResult(keyResult).build(); + Action action = Action.Builder.builder() + .withId(null) + .withAction(actionText) + .withIsChecked(false) + .withPriority(1) + .withKeyResult(keyResult) + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(action)); + () -> validator.validateOnCreate(action)); assertOkrResponseStatusException(exception, errors); } @@ -157,15 +195,17 @@ void validateOnCreateShouldThrowExceptionWhenActionIsInvalid(String actionText, @Test void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange - Action actionInvalid = Action.Builder.builder().withIsChecked(true).build(); + Action actionInvalid = Action.Builder.builder() + .withIsChecked(true) + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(actionInvalid)); + () -> validator.validateOnCreate(actionInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -190,11 +230,11 @@ void validateOnUpdateShouldBeSuccessfulWhenActionIsValid() { void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { // arrange OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); // act + assert List expectedErrors = List.of( // - new ErrorDto("MODEL_NULL", List.of("Action"))); + new ErrorDto("MODEL_NULL", List.of("Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -202,13 +242,13 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, action1)); + () -> validator.validateOnUpdate(null, action1)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action1); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Action"))); + new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -216,14 +256,14 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, action2)); + () -> validator.validateOnUpdate(1L, action2)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action2); verify(validator, times(1)).throwExceptionWhenIdIsNull(action2.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(1L, action2.getId()); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_CHANGED", List.of("ID", "1", "2"))); + new ErrorDto("ATTRIBUTE_CHANGED", List.of("ID", "1", "2"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -231,12 +271,12 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { void validateOnUpdateShouldThrowExceptionWhenEntityDoesNotExist() { // arrange String reason = "MODEL_WITH_ID_NOT_FOUND"; - when(actionPersistenceService.findById(anyLong())) - .thenThrow(new OkrResponseStatusException(BAD_REQUEST, reason)); + when(actionPersistenceService.findById(anyLong())).thenThrow(new OkrResponseStatusException(BAD_REQUEST, + reason)); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(action2.getId(), action2)); + () -> validator.validateOnUpdate(action2.getId(), action2)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action2); verify(validator, times(1)).throwExceptionWhenIdIsNull(action2.getId()); @@ -259,35 +299,43 @@ void validateOnUpdateShouldThrowExceptionWhenKeyResultNotSet(ActionPair actionPa // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, action)); + () -> validator.validateOnUpdate(id, action)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action); verify(validator, times(1)).throwExceptionWhenIdIsNull(action.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(id, action.getId()); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @Test void validateOnUpdateShouldThrowExceptionWhenKeyResultIdHasChanged() { // arrange - Action action = Action.Builder.builder().withId(action2.getId()).withAction("Action").withIsChecked(false) - .withPriority(1) - .withKeyResult(KeyResultMetric.Builder.builder().withId(11L).withTitle("KR Title").build()).build(); + Action action = Action.Builder.builder() + .withId(action2.getId()) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(11L) + .withTitle("KR Title") + .build()) + .build(); when(actionPersistenceService.findById(anyLong())).thenReturn(action2); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(action.getId(), action)); + () -> validator.validateOnUpdate(action.getId(), action)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action); verify(validator, times(1)).throwExceptionWhenIdIsNull(action.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(action.getId(), action2.getId()); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of("KeyResult", "Action"))); + new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", + List.of("KeyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -295,44 +343,55 @@ void validateOnUpdateShouldThrowExceptionWhenKeyResultIdHasChanged() { @MethodSource("actionValidationArguments") void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String actionText, List errors) { // arrange - Action action = Action.Builder.builder().withId(3L).withAction(actionText).withIsChecked(false).withPriority(1) - .withKeyResult(keyResult).build(); + Action action = Action.Builder.builder() + .withId(3L) + .withAction(actionText) + .withIsChecked(false) + .withPriority(1) + .withKeyResult(keyResult) + .build(); when(actionPersistenceService.findById(anyLong())).thenReturn(action); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, action)); + () -> validator.validateOnUpdate(3L, action)); assertOkrResponseStatusException(exception, errors); } @Test void validateOnUpdateShouldThrowExceptionWhenKeyResultIsMissing() { // arrange - Action actionInvalid = Action.Builder.builder().withId(11L).withIsChecked(true).build(); + Action actionInvalid = Action.Builder.builder() + .withId(11L) + .withIsChecked(true) + .build(); when(actionPersistenceService.findById(anyLong())).thenReturn(actionInvalid); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(11L, actionInvalid)); + () -> validator.validateOnUpdate(11L, actionInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @Test void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // arrange - Action actionInvalid = Action.Builder.builder().withId(11L).withIsChecked(true).withKeyResult(keyResult) - .build(); + Action actionInvalid = Action.Builder.builder() + .withId(11L) + .withIsChecked(true) + .withKeyResult(keyResult) + .build(); when(actionPersistenceService.findById(anyLong())).thenReturn(actionInvalid); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(11L, actionInvalid)); + () -> validator.validateOnUpdate(11L, actionInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -341,7 +400,8 @@ void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { void validateOnGetByKeyResultIdShouldBeSuccessfulWhenIdIsNotNull() { // arrange Long id = 1L; - doNothing().when(keyResultValidationService).validateOnGet(id); + doNothing().when(keyResultValidationService) + .validateOnGet(id); // act + assert assertDoesNotThrow(() -> validator.validateOnGetByKeyResultId(id)); @@ -353,7 +413,8 @@ void validateOnGetByKeyResultIdShouldBeSuccessfulWhenIdIsNotNull() { void validateOnGetByKeyResultIdShouldThrowExceptionWhenIdIsNull() { // arrange Long id = null; - doThrow(OkrResponseStatusException.class).when(keyResultValidationService).validateOnGet(id); + doThrow(OkrResponseStatusException.class).when(keyResultValidationService) + .validateOnGet(id); // act + assert assertThrows(OkrResponseStatusException.class, () -> validator.validateOnGetByKeyResultId(id)); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java index b4a1801da5..e512866cac 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.service.validation; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; @@ -11,6 +15,7 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.CheckInPersistenceService; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -23,10 +28,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; @@ -37,40 +38,91 @@ class CheckInValidationServiceTest { @MockBean CheckInPersistenceService checkInPersistenceService = Mockito.mock(CheckInPersistenceService.class); - private final User user = User.Builder.builder().withId(1L).withFirstname("Ruedi").withLastname("Grochde") - .withEmail("grochde@puzzle.ch").build(); - private final Team team = Team.Builder.builder().withId(1L).withName("Team4").build(); - private final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - private final Objective objective = Objective.Builder.builder().withId(1L).withTitle("Objective 1") - .withCreatedBy(user).withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder().withBaseline(13D).withStretchGoal(25D) - .withUnit(Unit.NUMBER).withId(8L).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .build(); - private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Commit Zone") - .withTargetZone("Target Zone").withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user) - .build(); - private final CheckIn checkInMetric = CheckInMetric.Builder.builder().withValue(45D).withChangeInfo("ChangeInfo") - .withInitiatives("Initiatives").withConfidence(10).withKeyResult(keyResultMetric) - .withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX).withCreatedBy(user).build(); - private final CheckIn checkInOrdinal = CheckInMetric.Builder.builder().withValue(27D).withId(1L) - .withChangeInfo("ChangeInfoMetric").withInitiatives("InitiativesMetric").withConfidence(8) - .withKeyResult(keyResultOrdinal).withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX) - .withCreatedBy(user).build(); - private final CheckIn fullCheckIn = CheckInOrdinal.Builder.builder().withZone(Zone.STRETCH).withId(1L) - .withChangeInfo("ChangeInfoMetric").withInitiatives("InitiativesMetric").withConfidence(8) - .withKeyResult(keyResultMetric).withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX) - .withCreatedBy(user).build(); - @Spy - @InjectMocks + private final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Ruedi") + .withLastname("Grochde") + .withEmail("grochde@puzzle.ch") + .build(); + private final Team team = Team.Builder.builder() + .withId(1L) + .withName("Team4") + .build(); + private final Quarter quarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .build(); + private final Objective objective = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder() + .withBaseline(13D) + .withStretchGoal(25D) + .withUnit(Unit.NUMBER) + .withId(8L) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .build(); + private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() + .withCommitZone("Commit Zone") + .withTargetZone("Target Zone") + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .withOwner(user) + .build(); + private final CheckIn checkInMetric = CheckInMetric.Builder.builder() + .withValue(45D) + .withChangeInfo("ChangeInfo") + .withInitiatives("Initiatives") + .withConfidence(10) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .withCreatedBy(user) + .build(); + private final CheckIn checkInOrdinal = CheckInMetric.Builder.builder() + .withValue(27D) + .withId(1L) + .withChangeInfo("ChangeInfoMetric") + .withInitiatives("InitiativesMetric") + .withConfidence(8) + .withKeyResult(keyResultOrdinal) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .withCreatedBy(user) + .build(); + private final CheckIn fullCheckIn = CheckInOrdinal.Builder.builder() + .withZone(Zone.STRETCH) + .withId(1L) + .withChangeInfo("ChangeInfoMetric") + .withInitiatives("InitiativesMetric") + .withConfidence(8) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .withCreatedBy(user) + .build(); + @Spy @InjectMocks private CheckInValidationService validator; private static Stream confidenceValidationArguments() { - return Stream.of( - arguments(-1, List.of(new ErrorDto("ATTRIBUTE_MIN_VALUE", List.of("confidence", "CheckIn", "0")))), - arguments(11, List.of(new ErrorDto("ATTRIBUTE_MAX_VALUE", List.of("confidence", "CheckIn", "10")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn"))))); + return Stream.of(arguments(-1, + List.of(new ErrorDto("ATTRIBUTE_MIN_VALUE", List.of("confidence", "CheckIn", "0")))), + arguments(11, + List.of(new ErrorDto("ATTRIBUTE_MAX_VALUE", + List.of("confidence", "CheckIn", "10")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn"))))); } @BeforeEach @@ -88,7 +140,7 @@ void validateOnGetShouldBeSuccessfulWhenValidCheckInId() { void validateOnGetShouldThrowExceptionIfCheckInIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -111,7 +163,7 @@ void validateOnCreateShouldBeSuccessfulWhenCheckInIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -121,7 +173,7 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(fullCheckIn)); + () -> validator.validateOnCreate(fullCheckIn)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -129,24 +181,23 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @ParameterizedTest @MethodSource("confidenceValidationArguments") - void validateOnCreateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confidence, - List expectedErrors) { + void validateOnCreateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confidence, List expectedErrors) { // arrange CheckIn checkIn = CheckInMetric.Builder.builder() // - .withValue(40.9) // - .withChangeInfo("ChangeInfo") // - .withInitiatives("Initiatives") // - .withConfidence(confidence) // - .withCreatedBy(user) // - .withKeyResult(keyResultMetric) // - .withCreatedOn(LocalDateTime.MAX) // - .withModifiedOn(LocalDateTime.MAX) // - .build(); + .withValue(40.9) // + .withChangeInfo("ChangeInfo") // + .withInitiatives("Initiatives") // + .withConfidence(confidence) // + .withCreatedBy(user) // + .withKeyResult(keyResultMetric) // + .withCreatedOn(LocalDateTime.MAX) // + .withModifiedOn(LocalDateTime.MAX) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(checkIn)); + () -> validator.validateOnCreate(checkIn)); assertOkrResponseStatusException(exception, expectedErrors); } @@ -154,19 +205,20 @@ void validateOnCreateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confide void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange CheckIn checkInInvalid = CheckInMetric.Builder.builder() // - .withId(null) // - .withChangeInfo("ChangeInfo").build(); + .withId(null) // + .withChangeInfo("ChangeInfo") + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(checkInInvalid)); + () -> validator.validateOnCreate(checkInInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -186,7 +238,7 @@ void validateOnUpdateShouldBeSuccessfulWhenCheckInIsValid() { void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -196,7 +248,7 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, checkInOrdinal)); + () -> validator.validateOnUpdate(null, checkInOrdinal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(checkInOrdinal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -209,7 +261,7 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsHasChanged() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(2L, checkInOrdinal)); + () -> validator.validateOnUpdate(2L, checkInOrdinal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(checkInOrdinal); verify(validator, times(1)).throwExceptionWhenIdIsNull(2L); @@ -221,20 +273,26 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsHasChanged() { @ParameterizedTest @MethodSource("confidenceValidationArguments") - void validateOnUpdateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confidence, - List expectedErrors) { + void validateOnUpdateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confidence, List expectedErrors) { // arrange Long id = 2L; - CheckIn checkIn = CheckInMetric.Builder.builder().withValue(40.9).withId(id).withChangeInfo("ChangeInfo") - .withInitiatives("Initiatives").withConfidence(confidence).withCreatedBy(user) - .withKeyResult(keyResultMetric).withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX) - .build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withValue(40.9) + .withId(id) + .withChangeInfo("ChangeInfo") + .withInitiatives("Initiatives") + .withConfidence(confidence) + .withCreatedBy(user) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .build(); when(checkInPersistenceService.findById(id)).thenReturn(checkIn); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, checkIn)); + () -> validator.validateOnUpdate(id, checkIn)); assertOkrResponseStatusException(exception, expectedErrors); } @@ -242,24 +300,38 @@ void validateOnUpdateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confide void validateOnUpdateShouldThrowExceptionWhenCheckInsOfKeyResultIsEmpty() { // arrange Long id = 2L; - CheckIn checkIn = CheckInMetric.Builder.builder().withValue(40.9).withId(id).withChangeInfo("ChangeInfo") - .withInitiatives("Initiatives").withConfidence(2).withCreatedBy(user).withKeyResult(keyResultMetric) - .withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX).build(); - CheckIn savedCheckIn = CheckInMetric.Builder.builder().withId(id).withChangeInfo("") - .withInitiatives("Initiatives").withCreatedBy(user) - .withKeyResult(KeyResultMetric.Builder.builder().withId(13L).build()).build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withValue(40.9) + .withId(id) + .withChangeInfo("ChangeInfo") + .withInitiatives("Initiatives") + .withConfidence(2) + .withCreatedBy(user) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .build(); + CheckIn savedCheckIn = CheckInMetric.Builder.builder() + .withId(id) + .withChangeInfo("") + .withInitiatives("Initiatives") + .withCreatedBy(user) + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(13L) + .build()) + .build(); when(checkInPersistenceService.findById(id)).thenReturn(savedCheckIn); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, checkIn)); + () -> validator.validateOnUpdate(id, checkIn)); verify(validator, times(1)).throwExceptionWhenModelIsNull(checkIn); verify(validator, times(1)).throwExceptionWhenIdIsNull(checkIn.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(checkIn.getId(), checkIn.getId()); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of("KeyResult", "Check-in"))); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", + List.of("KeyResult", "Check-in"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -268,21 +340,23 @@ void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // arrange Long id = 11L; CheckIn checkInInvalid = CheckInMetric.Builder.builder() // - .withId(id) // - .withChangeInfo("ChangeInfo") // - .withKeyResult(KeyResultMetric.Builder.builder().withId(13L).build()) // - .build(); + .withId(id) // + .withChangeInfo("ChangeInfo") // + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(13L) + .build()) // + .build(); when(checkInPersistenceService.findById(id)).thenReturn(checkInInvalid); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, checkInInvalid)); + () -> validator.validateOnUpdate(id, checkInInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -297,7 +371,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidKeyResultId() { void validateOnDeleteShouldThrowExceptionIfKeyResultIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnDelete(null)); + () -> validator.validateOnDelete(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java index 3fbe650e14..b107cae07c 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java @@ -1,9 +1,14 @@ package ch.puzzle.okr.service.validation; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; import ch.puzzle.okr.service.persistence.CompletedPersistenceService; + import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -20,10 +25,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; @@ -43,33 +44,55 @@ class CompletedValidationServiceTest { @BeforeEach void setUp() { - this.user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - this.team = Team.Builder.builder().withId(1L).withName("Team1").build(); - this.quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - - this.objective = Objective.Builder.builder().withId(1L).withTitle("Objective 1").withCreatedBy(user) - .withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - - this.validCompleted = Completed.Builder.builder().withObjective(this.objective).withComment("Valid Comment") - .build(); + this.user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + this.team = Team.Builder.builder() + .withId(1L) + .withName("Team1") + .build(); + this.quarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .build(); + + this.objective = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + + this.validCompleted = Completed.Builder.builder() + .withObjective(this.objective) + .withComment("Valid Comment") + .build(); when(completedPersistenceService.getCompletedByObjectiveId(1L)).thenReturn(this.validCompleted); when(completedPersistenceService.getModelName()).thenReturn("Completed"); doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", completedPersistenceService.getModelName(), 2L))) - .when(completedPersistenceService).getCompletedByObjectiveId(2L); + String.format("%s with id %s not found", + completedPersistenceService.getModelName(), + 2L))).when(completedPersistenceService) + .getCompletedByObjectiveId(2L); } - @Spy - @InjectMocks + @Spy @InjectMocks private CompletedValidationService validator; private static Stream nameValidationArguments() { return Stream.of(arguments(StringUtils.repeat('1', 5000), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("comment", "Completed", "0", "4096"))))); + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("comment", "Completed", "0", "4096"))))); } @Test @@ -84,7 +107,7 @@ void validateOnCreateShouldBeSuccessfulWhenCompletedIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Completed"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -94,14 +117,14 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // arrange Completed completed = Completed.Builder.builder() // - .withId(300L) // - .withObjective(this.objective) // - .withComment("Not valid") // - .build(); + .withId(300L) // + .withObjective(this.objective) // + .withComment("Not valid") // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(completed)); + () -> validator.validateOnCreate(completed)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Completed"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -112,13 +135,13 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { void validateOnCreateShouldThrowExceptionWhenCommentIsInvalid(String comment, List expectedErrors) { // arrange Completed completed = Completed.Builder.builder() // - .withObjective(this.objective) // - .withComment(comment) // - .build(); + .withObjective(this.objective) // + .withComment(comment) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(completed)); + () -> validator.validateOnCreate(completed)); assertOkrResponseStatusException(exception, expectedErrors); } @@ -127,14 +150,14 @@ void validateOnCreateShouldThrowExceptionWhenCommentIsInvalid(String comment, Li void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange Completed completedInvalid = Completed.Builder.builder() // - .withId(null) // - .withComment("Valid comment") // - .withObjective(null) // - .build(); + .withId(null) // + .withComment("Valid comment") // + .withObjective(null) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(completedInvalid)); + () -> validator.validateOnCreate(completedInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("objective", "Completed"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -145,7 +168,8 @@ void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { void validateOnUpdateShouldThrowException() { // arrange Long id = 1L; - Completed completed = Completed.Builder.builder().build(); + Completed completed = Completed.Builder.builder() + .build(); // act + assert assertThrows(IllegalCallerException.class, () -> validator.validateOnUpdate(id, completed)); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java index 5eaa2aa827..956885d048 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.service.validation; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; @@ -7,6 +11,7 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; + import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -23,13 +28,9 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; import static ch.puzzle.okr.Constants.KEY_RESULT; import static ch.puzzle.okr.Constants.OBJECTIVE; +import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.Mockito.*; @@ -39,24 +40,61 @@ class KeyResultValidationServiceTest { @MockBean KeyResultPersistenceService keyResultPersistenceService = Mockito.mock(KeyResultPersistenceService.class); - private final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - private final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - private final Team team = Team.Builder.builder().withId(1L).withName("Team1").build(); - private final Objective objective = Objective.Builder.builder().withId(1L).withTitle("Objective 1") - .withCreatedBy(user).withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0) - .withUnit(Unit.NUMBER).withId(5L).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .build(); - private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Ein Baum") - .withTargetZone("Zwei Bäume").withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user) - .build(); - private final KeyResult fullKeyResult = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0) - .withUnit(Unit.FTE).withId(null).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .withCreatedOn(LocalDateTime.MIN).withModifiedOn(LocalDateTime.MAX).withDescription("Description") - .withCreatedBy(user).build(); + private final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + private final Quarter quarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .build(); + private final Team team = Team.Builder.builder() + .withId(1L) + .withName("Team1") + .build(); + private final Objective objective = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withUnit(Unit.NUMBER) + .withId(5L) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .build(); + private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() + .withCommitZone("Ein Baum") + .withTargetZone("Zwei Bäume") + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .withOwner(user) + .build(); + private final KeyResult fullKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withUnit(Unit.FTE) + .withId(null) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .withCreatedOn(LocalDateTime.MIN) + .withModifiedOn(LocalDateTime.MAX) + .withDescription("Description") + .withCreatedBy(user) + .build(); @BeforeEach void setUp() { @@ -67,25 +105,29 @@ void setUp() { .when(keyResultPersistenceService).findById(2L); } - @Spy - @InjectMocks + @Spy @InjectMocks private KeyResultValidationService validator; private static Stream nameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 251), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")))), - arguments("", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "KeyResult")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult"))))); + return Stream.of(arguments(StringUtils.repeat('1', 251), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")))), + arguments("", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "KeyResult")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult"))))); } @Test @@ -100,7 +142,7 @@ void validateOnGetShouldBeSuccessfulWhenValidKeyResultId() { void validateOnGetShouldThrowExceptionIfKeyResultIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -120,7 +162,7 @@ void validateOnCreateShouldBeSuccessfulWhenKeyResultIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -130,7 +172,7 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(keyResultMetric)); + () -> validator.validateOnCreate(keyResultMetric)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -141,20 +183,20 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List errors) { // arrange KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withBaseline(3.0) // - .withStretchGoal(5.0) // - .withUnit(Unit.EUR) // - .withId(null) // - .withTitle(title) // - .withOwner(user) // - .withObjective(objective) // - .withCreatedBy(user) // - .withCreatedOn(LocalDateTime.MIN) // - .build(); + .withBaseline(3.0) // + .withStretchGoal(5.0) // + .withUnit(Unit.EUR) // + .withId(null) // + .withTitle(title) // + .withOwner(user) // + .withObjective(objective) // + .withCreatedBy(user) // + .withCreatedOn(LocalDateTime.MIN) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(keyResult)); + () -> validator.validateOnCreate(keyResult)); assertOkrResponseStatusException(exception, errors); } @@ -162,22 +204,22 @@ void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnCreate(keyResultInvalid)); + () -> validator.validateOnCreate(keyResultInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("objective", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("objective", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -185,10 +227,19 @@ void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { void validateOnUpdateShouldBeSuccessfulWhenKeyResultIsValid() { // arrange Long id = 5L; - KeyResult keyResult = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0) - .withUnit(Unit.EUR).withId(id).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .withCreatedOn(LocalDateTime.MIN).withModifiedOn(LocalDateTime.MAX).withDescription("Description") - .withCreatedBy(user).build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withUnit(Unit.EUR) + .withId(id) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .withCreatedOn(LocalDateTime.MIN) + .withModifiedOn(LocalDateTime.MAX) + .withDescription("Description") + .withCreatedBy(user) + .build(); when(keyResultPersistenceService.findById(id)).thenReturn(keyResult); // act @@ -205,7 +256,7 @@ void validateOnUpdateShouldBeSuccessfulWhenKeyResultIsValid() { void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -215,7 +266,7 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, keyResultOrdinal)); + () -> validator.validateOnUpdate(null, keyResultOrdinal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(keyResultOrdinal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -228,7 +279,7 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, keyResultMetric)); + () -> validator.validateOnUpdate(1L, keyResultMetric)); verify(validator, times(1)).throwExceptionWhenModelIsNull(keyResultMetric); verify(validator, times(1)).throwExceptionWhenIdIsNull(keyResultMetric.getId()); @@ -244,21 +295,21 @@ void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnUpdate(id, keyResult)); + () -> validator.validateOnUpdate(id, keyResult)); assertOkrResponseStatusException(exception, errors); } @@ -268,23 +319,23 @@ void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // arrange Long id = 11L; KeyResult keyResultInvalid = KeyResultMetric.Builder.builder() // - .withId(id) // - .withTitle("Title") // - .withObjective(objective) // - .build(); + .withId(id) // + .withTitle("Title") // + .withObjective(objective) // + .build(); when(keyResultPersistenceService.findById(id)).thenReturn(keyResultInvalid); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, keyResultInvalid)); + () -> validator.validateOnUpdate(id, keyResultInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -300,7 +351,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidKeyResultId() { void validateOnDeleteShouldThrowExceptionIfKeyResultIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -314,25 +365,31 @@ void validateOnUpdateShouldThrowExceptionWhenObjectiveIdOfKeyResultHasChanged() // arrange Long keyResultId = 1L; Long objectiveId = 2L; - Objective objective = Objective.Builder.builder().withId(objectiveId).build(); + Objective objective = Objective.Builder.builder() + .withId(objectiveId) + .build(); KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withId(keyResultId) // - .withObjective(objective).build(); + .withId(keyResultId) // + .withObjective(objective) + .build(); Long savedObjectiveId = 3L; - Objective savedObjective = Objective.Builder.builder().withId(savedObjectiveId).build(); + Objective savedObjective = Objective.Builder.builder() + .withId(savedObjectiveId) + .build(); KeyResult savedKeyResultWithDifferentObjectiveId = KeyResultMetric.Builder.builder() // - .withId(keyResultId) // - .withObjective(savedObjective).build(); + .withId(keyResultId) // + .withObjective(savedObjective) + .build(); when(keyResultPersistenceService.findById(keyResultId)).thenReturn(savedKeyResultWithDifferentObjectiveId); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(keyResultId, keyResult)); + () -> validator.validateOnUpdate(keyResultId, keyResult)); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of(OBJECTIVE, KEY_RESULT))); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", + List.of(OBJECTIVE, KEY_RESULT))); assertOkrResponseStatusException(exception, expectedErrors); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java index cc52bad997..1f16277121 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java @@ -1,10 +1,16 @@ package ch.puzzle.okr.service.validation; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.test.TestHelper; + import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,11 +26,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; import static org.assertj.core.api.Assertions.assertThat; @@ -44,51 +45,83 @@ class ObjectiveValidationServiceTest { User user; Quarter quarter; Team team; - @Spy - @InjectMocks + @Spy @InjectMocks private ObjectiveValidationService validator; private static Stream nameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 251), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")))), - - arguments("", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), - - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), - - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "Objective"))))); + return Stream.of(arguments(StringUtils.repeat('1', 251), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")))), + + arguments("", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), + + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), + + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "Objective"))))); } @BeforeEach void setUp() { - this.user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - this.team = Team.Builder.builder().withId(1L).withName("Team1").build(); - this.quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2") - .withStartDate(LocalDate.of(2022, 1, 1)).withEndDate(LocalDate.of(2022, 3, 31)).build(); - - this.objective1 = Objective.Builder.builder().withId(1L).withTitle("Objective 1").withCreatedBy(user) - .withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - - this.objectiveMinimal = Objective.Builder.builder().withId(null).withTitle("Objective 2").withCreatedBy(user) - .withTeam(team).withQuarter(quarter).withState(State.DRAFT).withCreatedOn(LocalDateTime.MAX).build(); + this.user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + this.team = Team.Builder.builder() + .withId(1L) + .withName("Team1") + .build(); + this.quarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .withStartDate(LocalDate.of(2022, 1, 1)) + .withEndDate(LocalDate.of(2022, 3, 31)) + .build(); + + this.objective1 = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + + this.objectiveMinimal = Objective.Builder.builder() + .withId(null) + .withTitle("Objective 2") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withState(State.DRAFT) + .withCreatedOn(LocalDateTime.MAX) + .build(); when(objectivePersistenceService.findById(1L)).thenReturn(objective1); when(objectivePersistenceService.getModelName()).thenReturn("Objective"); doThrow(new OkrResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", objectivePersistenceService.getModelName(), 2L))) - .when(objectivePersistenceService).findById(2L); + String.format("%s with id %s not found", + objectivePersistenceService.getModelName(), + 2L))).when(objectivePersistenceService) + .findById(2L); } @Test @@ -102,14 +135,15 @@ void validateOnGetShouldBeSuccessfulWhenValidObjectiveId() { @Test void validateOnGetShouldThrowExceptionIfObjectiveIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -123,107 +157,151 @@ void validateOnCreateShouldBeSuccessfulWhenTeamIsValid() { @Test void validateOnCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objective1)); + () -> validator.validateOnCreate(objective1)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("nameValidationArguments") void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List expectedErrors) { - Objective objective = Objective.Builder.builder().withId(null).withTitle(title).withCreatedBy(this.user) - .withTeam(this.team).withQuarter(this.quarter).withDescription("This is our description 2") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withCreatedOn(LocalDateTime.MAX).build(); + Objective objective = Objective.Builder.builder() + .withId(null) + .withTitle(title) + .withCreatedBy(this.user) + .withTeam(this.team) + .withQuarter(this.quarter) + .withDescription("This is our description 2") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withCreatedOn(LocalDateTime.MAX) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objective)); + () -> validator.validateOnCreate(objective)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { - Objective objectiveInvalid = Objective.Builder.builder().withId(null).withTitle("Title").withQuarter(quarter) - .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(null) + .withTitle("Title") + .withQuarter(quarter) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objectiveInvalid)); + () -> validator.validateOnCreate(objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenAttrModifiedByIsSet() { - Objective objectiveInvalid = Objective.Builder.builder().withId(null) - .withTitle("ModifiedBy is not null on create").withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withState(State.DRAFT).withTeam(team).withQuarter(quarter).withModifiedBy(user).build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(null) + .withTitle("ModifiedBy is not null on create") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(quarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objectiveInvalid)); - List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_SET_FORBIDDEN", List.of("ModifiedBy", - "User{id=1, version=0, firstname='Bob', lastname='Kaufmann', email='kaufmann@puzzle.ch', isOkrChampion='false'}"))); + () -> validator.validateOnCreate(objectiveInvalid)); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_SET_FORBIDDEN", + List.of("ModifiedBy", + "User{id=1, version=0, firstname='Bob', lastname='Kaufmann', email='kaufmann@puzzle.ch', isOkrChampion='false'}"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenStartDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withEndDate(LocalDate.of(2022, 7, 31)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(null).withTitle("Start date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withEndDate(LocalDate.of(2022, 7, 31)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(null) + .withTitle("Start date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objectiveInvalid)); + () -> validator.validateOnCreate(objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenEndDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withStartDate(LocalDate.of(2022, 4, 1)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(null).withTitle("End date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withStartDate(LocalDate.of(2022, 4, 1)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(null) + .withTitle("End date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objectiveInvalid)); + () -> validator.validateOnCreate(objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -239,19 +317,20 @@ void validateOnUpdateShouldBeSuccessfulWhenObjectiveIsValid() { @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, objectiveMinimal)); + () -> validator.validateOnUpdate(null, objectiveMinimal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(objectiveMinimal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -259,13 +338,14 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(7L, objective1)); + () -> validator.validateOnUpdate(7L, objective1)); verify(validator, times(1)).throwExceptionWhenModelIsNull(objective1); verify(validator, times(1)).throwExceptionWhenIdIsNull(objective1.getId()); @@ -274,161 +354,257 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("nameValidationArguments") void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List expectedErrors) { - Objective objective = Objective.Builder.builder().withId(3L).withTitle(title).withCreatedBy(this.user) - .withTeam(this.team).withQuarter(this.quarter).withDescription("This is our description 2") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(this.user) - .withCreatedOn(LocalDateTime.MAX).build(); + Objective objective = Objective.Builder.builder() + .withId(3L) + .withTitle(title) + .withCreatedBy(this.user) + .withTeam(this.team) + .withQuarter(this.quarter) + .withDescription("This is our description 2") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(this.user) + .withCreatedOn(LocalDateTime.MAX) + .build(); when(objectivePersistenceService.findById(objective.getId())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, objective)); + () -> validator.validateOnUpdate(3L, objective)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { - Objective objective = Objective.Builder.builder().withId(5L).withTitle("Title").withQuarter(quarter) - .withModifiedBy(user).build(); + Objective objective = Objective.Builder.builder() + .withId(5L) + .withTitle("Title") + .withQuarter(quarter) + .withModifiedBy(user) + .build(); when(objectivePersistenceService.findById(objective.getId())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(5L, objective)); + () -> validator.validateOnUpdate(5L, objective)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenAttrModifiedByIsNotSet() { - Objective objectiveInvalid = Objective.Builder.builder().withId(1L) - .withTitle("ModifiedBy is not null on create").withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withState(State.DRAFT).withTeam(team).withQuarter(quarter).withModifiedBy(null).build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(1L) + .withTitle("ModifiedBy is not null on create") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(quarter) + .withModifiedBy(null) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, objectiveInvalid)); + () -> validator.validateOnUpdate(1L, objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_SET", List.of("modifiedBy"))); assertEquals(INTERNAL_SERVER_ERROR, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenStartDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withEndDate(LocalDate.of(2022, 7, 31)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(1L).withTitle("Start date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).withModifiedBy(user).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withEndDate(LocalDate.of(2022, 7, 31)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(1L) + .withTitle("Start date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, objectiveInvalid)); + () -> validator.validateOnUpdate(1L, objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenEndDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withStartDate(LocalDate.of(2022, 4, 1)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(1L).withTitle("End date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).withModifiedBy(user).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withStartDate(LocalDate.of(2022, 4, 1)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(1L) + .withTitle("End date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, objectiveInvalid)); + () -> validator.validateOnUpdate(1L, objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWheTeamHasChanged() { - Objective savedObjective = Objective.Builder.builder().withId(1L).withTitle("Team has changed") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(quarter).withModifiedBy(null).build(); - Objective updatedObjective = Objective.Builder.builder().withId(1L).withTitle("Team has changed") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT) - .withTeam(Team.Builder.builder().withId(2L).withName("other team").build()).withQuarter(quarter) - .withModifiedBy(user).build(); + Objective savedObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Team has changed") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(quarter) + .withModifiedBy(null) + .build(); + Objective updatedObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Team has changed") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(Team.Builder.builder() + .withId(2L) + .withName("other team") + .build()) + .withQuarter(quarter) + .withModifiedBy(user) + .build(); when(objectivePersistenceService.findById(savedObjective.getId())).thenReturn(savedObjective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, updatedObjective)); + () -> validator.validateOnUpdate(1L, updatedObjective)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of("Team", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @ParameterizedTest - @EnumSource(value = State.class, names = { "DRAFT" }, mode = EnumSource.Mode.EXCLUDE) + @EnumSource(value = State.class, names = {"DRAFT"}, mode = EnumSource.Mode.EXCLUDE) void validateOnCreateShouldThrowExceptionWhenQuarterIsBacklogAndStateIsNotDraft(State state) { - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .withStartDate(null).withEndDate(null).build(); - - Objective invalidObjective = Objective.Builder.builder().withTitle("Invalid Objective").withCreatedBy(user) - .withCreatedOn(LocalDateTime.MAX).withState(state).withTeam(team).withQuarter(backlogQuarter).build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); + + Objective invalidObjective = Objective.Builder.builder() + .withTitle("Invalid Objective") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(state) + .withTeam(team) + .withQuarter(backlogQuarter) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(invalidObjective)); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", List.of("Objective", "Draft", state.toString()))); + () -> validator.validateOnCreate(invalidObjective)); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", + List.of("Objective", "Draft", state.toString()))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @ParameterizedTest - @EnumSource(value = State.class, names = { "DRAFT" }, mode = EnumSource.Mode.EXCLUDE) + @EnumSource(value = State.class, names = {"DRAFT"}, mode = EnumSource.Mode.EXCLUDE) void validateOnUpdateShouldThrowExceptionWhenQuarterIsBacklogAndStateIsNotDraft(State state) { - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .withStartDate(null).withEndDate(null).build(); - - Objective invalidObjective = Objective.Builder.builder().withId(1L).withTitle("Invalid Objective") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(state).withTeam(team) - .withQuarter(backlogQuarter).withModifiedBy(user).build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); + + Objective invalidObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Invalid Objective") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(state) + .withTeam(team) + .withQuarter(backlogQuarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, invalidObjective)); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", List.of("Objective", "Draft", state.toString()))); + () -> validator.validateOnUpdate(1L, invalidObjective)); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", + List.of("Objective", "Draft", state.toString()))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldPassWhenQuarterIsBacklogAndStateIsDraft() { - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .withStartDate(null).withEndDate(null).build(); - - Objective validObjective = Objective.Builder.builder().withId(1L).withTitle("Invalid Objective") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(backlogQuarter).withModifiedBy(user).build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); + + Objective validObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Invalid Objective") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(backlogQuarter) + .withModifiedBy(user) + .build(); assertDoesNotThrow(() -> validator.validateOnUpdate(1L, validObjective)); } @@ -444,13 +620,14 @@ void validateOnDeleteShouldBeSuccessfulWhenValidObjectiveId() { @Test void validateOnDeleteShouldThrowExceptionIfObjectiveIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java index d47a98e53c..fdb046ae0d 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java @@ -1,10 +1,14 @@ package ch.puzzle.okr.service.validation; +import java.time.LocalDate; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,9 +18,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.time.LocalDate; -import java.util.List; - import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; @@ -28,8 +29,7 @@ class QuarterValidationServiceTest { @MockBean QuarterPersistenceService quarterPersistenceService = Mockito.mock(QuarterPersistenceService.class); - @Spy - @InjectMocks + @Spy @InjectMocks private QuarterValidationService validator; @DisplayName("throwExceptionWhenStartEndDateQuarterIsNull() should do nothing when Quarter Label is Backlog") @@ -57,7 +57,7 @@ void throwExceptionWhenStartEndDateQuarterIsNullShouldThrowExceptionWhenStartDat // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); + () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); assertEquals(BAD_REQUEST, okrResponseStatusException.getStatusCode()); } @@ -72,7 +72,7 @@ void throwExceptionWhenStartEndDateQuarterIsNullShouldThrowExceptionWhenEndDateI // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); + () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); assertEquals(BAD_REQUEST, okrResponseStatusException.getStatusCode()); } @@ -100,7 +100,7 @@ void validateOnCreateShouldThrowException() { @Test void validateOnUpdateShouldThrowException() { Exception exception = assertThrows(IllegalCallerException.class, - () -> validator.validateOnUpdate(anyLong(), any())); + () -> validator.validateOnUpdate(anyLong(), any())); assertEquals("This method must not be called because there is no update of quarters", exception.getMessage()); } @@ -114,11 +114,11 @@ void validateOnGenerationShouldThrowExceptionWhenStartDateIsNull() { // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGeneration(quarter)); + () -> validator.validateOnGeneration(quarter)); assertOkrResponseStatusException( // - okrResponseStatusException, // - List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "Any Label")))); + okrResponseStatusException, // + List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "Any Label")))); } @DisplayName("validateOnGeneration() should throw exception when EndDate is null") @@ -132,11 +132,11 @@ void validateOnGenerationShouldThrowExceptionWhenEndDateIsNull() { // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGeneration(quarter)); + () -> validator.validateOnGeneration(quarter)); assertOkrResponseStatusException( // - okrResponseStatusException, // - List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "Any Label")))); + okrResponseStatusException, // + List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "Any Label")))); } @DisplayName("validateOnGeneration() should do nothing when both dates are not null") @@ -156,7 +156,8 @@ void validateOnGenerationShouldDoNothingWhenBothDatesAreNotNull() { private void assertOkrResponseStatusException(OkrResponseStatusException exception, List expectedErrors) { assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java index 044a7b9a5c..ef41634d33 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java @@ -1,10 +1,13 @@ package ch.puzzle.okr.service.validation; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.service.persistence.TeamPersistenceService; +import ch.puzzle.okr.test.TestHelper; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -17,8 +20,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -37,21 +38,34 @@ class TeamValidationServiceTest { @BeforeEach void setUp() { - team1 = Team.Builder.builder().withId(1L).withName("Team 1").build(); - team2 = Team.Builder.builder().withId(2L).withName("Team 2").build(); - teamWithIdNull = Team.Builder.builder().withId(null).withName("Team null").build(); - teamWithoutName = Team.Builder.builder().build(); - teamWithoutNameWithId = Team.Builder.builder().withId(1L).build(); + team1 = Team.Builder.builder() + .withId(1L) + .withName("Team 1") + .build(); + team2 = Team.Builder.builder() + .withId(2L) + .withName("Team 2") + .build(); + teamWithIdNull = Team.Builder.builder() + .withId(null) + .withName("Team null") + .build(); + teamWithoutName = Team.Builder.builder() + .build(); + teamWithoutNameWithId = Team.Builder.builder() + .withId(1L) + .build(); when(teamPersistenceService.findById(1L)).thenReturn(team1); when(teamPersistenceService.getModelName()).thenReturn("Team"); doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", teamPersistenceService.getModelName(), 2L))) - .when(teamPersistenceService).findById(2L); + String.format("%s with id %s not found", + teamPersistenceService.getModelName(), + 2L))).when(teamPersistenceService) + .findById(2L); } - @Spy - @InjectMocks + @Spy @InjectMocks private TeamValidationService validator; @Test @@ -65,14 +79,15 @@ void validateOnGetShouldBeSuccessfulWhenValidTeamId() { @Test void validateOnGetShouldThrowExceptionIfTeamIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -86,105 +101,116 @@ void validateOnDeleteShouldBeSuccessfulWhenValidTeamId() { @Test void validateOnDeleteShouldThrowExceptionIfTeamIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(team1)); + () -> validator.validateOnCreate(team1)); verify(validator, times(1)).throwExceptionWhenIdIsNotNull(team1.getId()); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenTeamAlreadyExists() { - BDDMockito.given(teamPersistenceService.findTeamsByName(anyString())).willReturn(List.of(team1)); + BDDMockito.given(teamPersistenceService.findTeamsByName(anyString())) + .willReturn(List.of(team1)); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(teamWithIdNull)); + () -> validator.validateOnCreate(teamWithIdNull)); List expectedErrors = List.of(new ErrorDto("ALREADY_EXISTS_SAME_NAME", List.of("Team", "Team null"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); verify(validator, times(1)).throwExceptionWhenModelIsNull(null); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenModelIsNameIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(teamWithoutName)); + () -> validator.validateOnCreate(teamWithoutName)); verify(validator, times(1)).throwExceptionWhenModelIsNull(teamWithoutName); verify(validator, times(1)).throwExceptionWhenIdIsNotNull(teamWithoutName.getId()); verify(validator, times(1)).validate(teamWithoutName); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("name", "Team")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenModelIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(teamWithIdNull.getId(), teamWithIdNull)); + () -> validator.validateOnUpdate(teamWithIdNull.getId(), + teamWithIdNull)); verify(validator, times(1)).throwExceptionWhenModelIsNull(teamWithIdNull); verify(validator, times(1)).throwExceptionWhenIdIsNull(teamWithIdNull.getId()); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, null)); + () -> validator.validateOnUpdate(null, null)); verify(validator, times(1)).throwExceptionWhenModelIsNull(null); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNameIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(teamWithoutNameWithId.getId(), teamWithoutNameWithId)); + () -> validator.validateOnUpdate(teamWithoutNameWithId.getId(), + teamWithoutNameWithId)); verify(validator, times(1)).throwExceptionWhenModelIsNull(teamWithoutNameWithId); verify(validator, times(1)).throwExceptionWhenIdIsNull(teamWithoutNameWithId.getId()); verify(validator, times(1)).validate(teamWithoutNameWithId); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("name", "Team")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java index fbf55cb798..85dc4a7aaf 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java @@ -1,10 +1,14 @@ package ch.puzzle.okr.service.validation; -import ch.puzzle.okr.test.TestHelper; +import java.util.List; +import java.util.stream.Stream; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.service.persistence.UserPersistenceService; +import ch.puzzle.okr.test.TestHelper; + import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,9 +25,6 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.server.ResponseStatusException; -import java.util.List; -import java.util.stream.Stream; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.params.provider.Arguments.arguments; @@ -43,77 +44,97 @@ class UserValidationServiceTest { @BeforeEach void setUp() { - user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - - userMinimal = User.Builder.builder().withFirstname("Max").withLastname("Mustermann") - .withEmail("max@mustermann.com").build(); + user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + + userMinimal = User.Builder.builder() + .withFirstname("Max") + .withLastname("Mustermann") + .withEmail("max@mustermann.com") + .build(); when(userPersistenceService.findById(1L)).thenReturn(user); when(userPersistenceService.getModelName()).thenReturn("User"); doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", userPersistenceService.getModelName(), 2L))) - .when(userPersistenceService).findById(2L); + String.format("%s with id %s not found", + userPersistenceService.getModelName(), + 2L))).when(userPersistenceService) + .findById(2L); } - @Spy - @InjectMocks + @Spy @InjectMocks private UserValidationService validator; private static Stream firstNameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 51), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments("", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("firstname", "User"))))); + return Stream.of(arguments(StringUtils.repeat('1', 51), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments("", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("firstname", "User"))))); } private static Stream lastNameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 51), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments("", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("lastname", "User"))))); + return Stream.of(arguments(StringUtils.repeat('1', 51), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments("", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("lastname", "User"))))); } private static Stream emailValidationArguments() { - return Stream.of( - arguments(("1".repeat(251)), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), - arguments(("1"), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), - arguments((""), - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")))), - arguments((" "), - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")))), - arguments((" "), - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User"))))); + return Stream.of(arguments(("1".repeat(251)), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), + arguments(("1"), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), + arguments((""), + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("email", "User", "2", "250")))), + arguments((" "), + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("email", "User", "2", "250")))), + arguments((" "), + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User"))))); } @Test @@ -127,13 +148,14 @@ void validateOnGetShouldBeSuccessfulWhenValidUserId() { @Test void validateOnGetShouldThrowExceptionIfUserIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -147,14 +169,15 @@ void validateOnGetOrCreateShouldBeSuccessful() { @Test void validateOnGetOrCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGetOrCreate(null)); + () -> validator.validateOnGetOrCreate(null)); verify(validator, times(1)).throwExceptionWhenModelIsNull(null); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -168,81 +191,100 @@ void validateOnCreateShouldBeSuccessfulWhenUserIsValid() { @Test void validateOnCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user)); + () -> validator.validateOnCreate(user)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("firstNameValidationArguments") void validateOnCreateShouldThrowExceptionWhenFirstnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withEmail("max@mail.com").withFirstname(name).withLastname("lastname") - .build(); + User user2 = User.Builder.builder() + .withEmail("max@mail.com") + .withFirstname(name) + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user2)); + () -> validator.validateOnCreate(user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(errors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(errors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("lastNameValidationArguments") void validateOnCreateShouldThrowExceptionWhenLastnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withEmail("max@mail.com").withFirstname("firstname").withLastname(name) - .build(); + User user2 = User.Builder.builder() + .withEmail("max@mail.com") + .withFirstname("firstname") + .withLastname(name) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user2)); + () -> validator.validateOnCreate(user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(errors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(errors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("emailValidationArguments") void validateOnCreateShouldThrowExceptionWhenEmailIsInvalid(String email, List errors) { - User user2 = User.Builder.builder().withEmail(email).withFirstname("firstname").withLastname("lastname") - .build(); + User user2 = User.Builder.builder() + .withEmail(email) + .withFirstname("firstname") + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user2)); + () -> validator.validateOnCreate(user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(errors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(errors) + .contains(exception.getReason())); } @Test void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { - User userInvalid = User.Builder.builder().withId(null).withLastname("Lastname").withFirstname("firstname") - .withEmail("falseemail").build(); + User userInvalid = User.Builder.builder() + .withId(null) + .withLastname("Lastname") + .withFirstname("firstname") + .withEmail("falseemail") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(userInvalid)); + () -> validator.validateOnCreate(userInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -258,19 +300,20 @@ void validateOnUpdateShouldBeSuccessfulWhenUserIsValid() { @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, userMinimal)); + () -> validator.validateOnUpdate(null, userMinimal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(userMinimal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -279,13 +322,14 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(7L, user)); + () -> validator.validateOnUpdate(7L, user)); verify(validator, times(1)).throwExceptionWhenModelIsNull(user); verify(validator, times(1)).throwExceptionWhenIdIsNull(user.getId()); @@ -295,63 +339,84 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("firstNameValidationArguments") void validateOnUpdateShouldThrowExceptionWhenFirstnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withId(3L).withEmail("max@mail.com").withFirstname(name) - .withLastname("lastname").build(); + User user2 = User.Builder.builder() + .withId(3L) + .withEmail("max@mail.com") + .withFirstname(name) + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, user2)); + () -> validator.validateOnUpdate(3L, user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(errors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(errors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("lastNameValidationArguments") void validateOnUpdateShouldThrowExceptionWhenLastnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withId(3L).withEmail("max@mail.com").withFirstname("firstname") - .withLastname(name).build(); + User user2 = User.Builder.builder() + .withId(3L) + .withEmail("max@mail.com") + .withFirstname("firstname") + .withLastname(name) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, user2)); + () -> validator.validateOnUpdate(3L, user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(errors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(errors) + .contains(exception.getReason())); } @ParameterizedTest @MethodSource("emailValidationArguments") void validateOnUpdateShouldThrowExceptionWhenEmailIsInvalid(String email, List errors) { - User user2 = User.Builder.builder().withId(3L).withEmail(email).withFirstname("firstname") - .withLastname("lastname").build(); + User user2 = User.Builder.builder() + .withId(3L) + .withEmail(email) + .withFirstname("firstname") + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, user2)); + () -> validator.validateOnUpdate(3L, user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(errors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(errors) + .contains(exception.getReason())); } @Test void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { - User userInvalid = User.Builder.builder().withId(3L).withLastname("Lastname").withFirstname("firstname") - .withEmail("falseemail").build(); + User userInvalid = User.Builder.builder() + .withId(3L) + .withLastname("Lastname") + .withFirstname("firstname") + .withEmail("falseemail") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, userInvalid)); + () -> validator.validateOnUpdate(3L, userInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -364,13 +429,14 @@ void validateAuthorisationTokenShouldNotThrowError() { @Test void validateAuthorisationTokenShouldThrowErrorWhenNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateAuthorisationToken(null)); + () -> validator.validateAuthorisationToken(null)); List expectedErrors = List.of(new ErrorDto("TOKEN_NULL", List.of())); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } @Test @@ -384,14 +450,15 @@ void validateOnDeleteShouldBeSuccessfulWhenValidObjectiveId() { @Test void validateOnDeleteShouldThrowExceptionIfObjectiveIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "User"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java index c91cfddc1b..fa8c313a5b 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.service.validation; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -8,6 +10,7 @@ import ch.puzzle.okr.repository.QuarterRepository; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -17,8 +20,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.util.List; - import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -31,8 +32,7 @@ class ValidationBaseTest { @MockBean ObjectivePersistenceService objectivePersistenceService = Mockito.mock(ObjectivePersistenceService.class); - @Spy - @InjectMocks + @Spy @InjectMocks private DummyValidationService validator; @InjectMocks @@ -58,11 +58,12 @@ void validateOnGetShouldBeSuccessfulWhenIdIsValid() { void validateOnGetShouldThrowExceptionWhenIdIsNull() { // arrange Long id = null; - Mockito.when(quarterPersistenceService.getModelName()).thenReturn("Quarter"); + Mockito.when(quarterPersistenceService.getModelName()) + .thenReturn("Quarter"); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(id)); + () -> validator.validateOnGet(id)); // assert List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Quarter"))); @@ -74,7 +75,10 @@ void validateOnGetShouldThrowExceptionWhenIdIsNull() { void validateOnDeleteShouldBeSuccessfulWhenIdIsValid() { // arrange Long id = 1L; - Quarter quarter = Quarter.Builder.builder().withId(id).withLabel("Quarter").build(); + Quarter quarter = Quarter.Builder.builder() + .withId(id) + .withLabel("Quarter") + .build(); when(quarterPersistenceService.findById(id)).thenReturn(quarter); // act @@ -89,11 +93,12 @@ void validateOnDeleteShouldBeSuccessfulWhenIdIsValid() { void validateOnDeleteShouldThrowExceptionWhenIdIsNull() { // arrange Long id = null; - Mockito.when(quarterPersistenceService.getModelName()).thenReturn("Quarter"); + Mockito.when(quarterPersistenceService.getModelName()) + .thenReturn("Quarter"); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnDelete(id)); + () -> validator.validateOnDelete(id)); // assert List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Quarter"))); @@ -105,7 +110,10 @@ void validateOnDeleteShouldThrowExceptionWhenIdIsNull() { void throwExceptionWhenModelIsNullShouldBeSuccessfulWhenModelIsValid() { // act Long id = 1L; - Quarter model = Quarter.Builder.builder().withId(id).withLabel("Quarter").build(); + Quarter model = Quarter.Builder.builder() + .withId(id) + .withLabel("Quarter") + .build(); // act + assert assertDoesNotThrow(() -> validator.throwExceptionWhenModelIsNull(model)); @@ -117,11 +125,12 @@ void throwExceptionWhenModelIsNullShouldBeSuccessfulWhenModelIsValid() { void throwExceptionWhenModelIsNullShouldThrowExceptionWhenModelIsNull() { // arrange Quarter model = null; - Mockito.when(quarterPersistenceService.getModelName()).thenReturn("Quarter"); + Mockito.when(quarterPersistenceService.getModelName()) + .thenReturn("Quarter"); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.throwExceptionWhenModelIsNull(model)); + () -> validator.throwExceptionWhenModelIsNull(model)); // assert List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Quarter"))); @@ -141,11 +150,12 @@ void throwExceptionWhenIdIsNotNullShouldBeSuccessfulWhenIdIsNull() { void throwExceptionWhenIdIsNotNullShouldThrowExceptionWhenIdIsNotNull() { // arrange long id = 1L; - Mockito.when(quarterPersistenceService.getModelName()).thenReturn("Quarter"); + Mockito.when(quarterPersistenceService.getModelName()) + .thenReturn("Quarter"); // act OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.throwExceptionWhenIdIsNotNull(id)); + () -> validator.throwExceptionWhenIdIsNotNull(id)); // assert List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Quarter"))); @@ -167,15 +177,17 @@ void throwExceptionWhenIdHasChangedShouldThrowExceptionWhenIdsAreNotEqual() { // arrange Long id = 1L; Long modelId = 2L; - Mockito.when(quarterPersistenceService.getModelName()).thenReturn("Quarter"); + Mockito.when(quarterPersistenceService.getModelName()) + .thenReturn("Quarter"); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.throwExceptionWhenIdHasChanged(id, modelId)); + () -> validator.throwExceptionWhenIdHasChanged(id, + modelId)); // assert - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_CHANGED", List.of("ID", id.toString(), modelId.toString()))); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CHANGED", + List.of("ID", id.toString(), modelId.toString()))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -183,8 +195,11 @@ void throwExceptionWhenIdHasChangedShouldThrowExceptionWhenIdsAreNotEqual() { @Test void validateShouldBeSuccessfulWhenConstraintInModelClassIsNotViolated() { // arrange - Quarter quarterWithValidLabel = Quarter.Builder.builder().withLabel("Quarter").build(); - Mockito.when(objectivePersistenceService.getModelName()).thenReturn("Quarter"); + Quarter quarterWithValidLabel = Quarter.Builder.builder() + .withLabel("Quarter") + .build(); + Mockito.when(objectivePersistenceService.getModelName()) + .thenReturn("Quarter"); // act + assert assertDoesNotThrow(() -> validator.validate(quarterWithValidLabel)); @@ -196,12 +211,15 @@ void validateShouldBeSuccessfulWhenConstraintInModelClassIsNotViolated() { void validateShouldThrowExceptionWhenWhenConstraintInModelClassIsViolated() { // arrange // Quarter which violates the NotNull constraint in Quarter model class - Quarter quarterWithNullLabel = Quarter.Builder.builder().withLabel(null).build(); - Mockito.when(quarterPersistenceService.getModelName()).thenReturn("Quarter"); + Quarter quarterWithNullLabel = Quarter.Builder.builder() + .withLabel(null) + .build(); + Mockito.when(quarterPersistenceService.getModelName()) + .thenReturn("Quarter"); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validate(quarterWithNullLabel)); + () -> validator.validate(quarterWithNullLabel)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("label", "Quarter"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -212,26 +230,29 @@ void validateShouldThrowExceptionWhenWhenConstraintInModelClassIsViolated() { void validateShouldThrowExceptionWhenOneOfSeveralConstraintsInModelClassIsViolated() { // arrange // Objective which violates several constraints in Objective model class - Objective objective = Objective.Builder.builder().withTitle("X").build(); - Mockito.when(objectivePersistenceService.getModelName()).thenReturn("Objective"); + Objective objective = Objective.Builder.builder() + .withTitle("X") + .build(); + Mockito.when(objectivePersistenceService.getModelName()) + .thenReturn("Objective"); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validatorWithSeveralConstraints.validate(objective)); + () -> validatorWithSeveralConstraints.validate(objective)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("quarter", "Objective")), // - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")) // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("quarter", "Objective")), // + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")) // ); assertOkrResponseStatusException(exception, expectedErrors); } - static class DummyValidationService - extends ValidationBase { + static class DummyValidationService extends ValidationBase { public DummyValidationService(QuarterPersistenceService quarterPersistenceService) { super(quarterPersistenceService); @@ -246,8 +267,7 @@ public void validateOnUpdate(Long aLong, Quarter model) { } } - static class DummyValidationServiceWithSeveralConstraints - extends ValidationBase { + static class DummyValidationServiceWithSeveralConstraints extends ValidationBase { public DummyValidationServiceWithSeveralConstraints(ObjectivePersistenceService objectivePersistenceService) { super(objectivePersistenceService); diff --git a/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java b/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java index cb5e4e2322..6b8c191659 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java @@ -1,31 +1,30 @@ package ch.puzzle.okr.test; +import java.util.List; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; + import org.junit.jupiter.api.Assertions; import org.springframework.http.HttpStatus; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.http.HttpStatus.BAD_REQUEST; public class AssertionHelper { - public static void assertOkrResponseStatusException(OkrResponseStatusException exception, - List expectedErrors) { + public static void assertOkrResponseStatusException(OkrResponseStatusException exception, List expectedErrors) { assertOkrResponseStatusException(BAD_REQUEST, exception, expectedErrors); } - public static void assertOkrResponseStatusException(HttpStatus statusCode, OkrResponseStatusException exception, - List expectedErrors) { + public static void assertOkrResponseStatusException(HttpStatus statusCode, OkrResponseStatusException exception, List expectedErrors) { assertEquals(statusCode, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); - Assertions.assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(exception.getReason())); + Assertions.assertTrue(TestHelper.getAllErrorKeys(expectedErrors) + .contains(exception.getReason())); } } diff --git a/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java b/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java index 78c98b659e..c5a771cf2d 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java +++ b/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.test; +import java.time.LocalDateTime; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; @@ -12,8 +14,6 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; -import java.time.LocalDateTime; - public class CheckInTestHelpers { public static final String CHANGE_INFO = "ChangeInfo"; public static final String CHANGE_INFO_1 = "ChangeInfo1"; @@ -28,10 +28,8 @@ public class CheckInTestHelpers { public static final String JSON_CHANGE_INFO = "changeinfo"; public static final String JSON_INITIATIVES = "initiatives"; - public static final String JSON = "{\"" + JSON_CHANGE_INFO + "\":" + "\"" + CHANGE_INFO_1 + "\"" - + ", \"keyResultId\": 1}"; - public static final String JSON_WITHOUT_KEY_RESULT_ID = "{\"" + JSON_CHANGE_INFO + "\":" + "\"" + CHANGE_INFO_1 - + "\"}"; + public static final String JSON = "{\"" + JSON_CHANGE_INFO + "\":" + "\"" + CHANGE_INFO_1 + "\"" + ", \"keyResultId\": 1}"; + public static final String JSON_WITHOUT_KEY_RESULT_ID = "{\"" + JSON_CHANGE_INFO + "\":" + "\"" + CHANGE_INFO_1 + "\"}"; public static final String JSON_PATH_ID = "$.id"; public static final String JSON_PATH_CHANGE_INFO = "$.changeInfo"; @@ -45,25 +43,63 @@ public class CheckInTestHelpers { public static final String JSON_PATH_ZONE = "$.value"; /* Test entities */ - static final Objective objective = Objective.Builder.builder().withId(1L).build(); - public static final CheckIn checkInMetric = CheckInMetric.Builder.builder().withValue(30D).withConfidence(5) - .withChangeInfo(CHANGE_INFO).withInitiatives(INITIATIVES) - .withCreatedBy(User.Builder.builder().withId(1L).withFirstname("Frank").build()) - .withKeyResult(KeyResultMetric.Builder.builder().withBaseline(3.0).withStretchGoal(6.0).withId(8L) - .withObjective(objective).build()) - .build(); - public static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder().withZone(Zone.COMMIT).withId(4L) - .withCreatedBy(User.Builder.builder().withId(2L).withFirstname("Robert").build()) - .withCreatedOn(LocalDateTime.MAX).withChangeInfo(CHANGE_INFO).withInitiatives(INITIATIVES) - .withKeyResult( - KeyResultOrdinal.Builder.builder().withCommitZone("Baum").withTargetZone("Wald").withId(9L).build()) - .build(); + static final Objective objective = Objective.Builder.builder() + .withId(1L) + .build(); + public static final CheckIn checkInMetric = CheckInMetric.Builder.builder() + .withValue(30D) + .withConfidence(5) + .withChangeInfo(CHANGE_INFO) + .withInitiatives(INITIATIVES) + .withCreatedBy(User.Builder.builder() + .withId(1L) + .withFirstname("Frank") + .build()) + .withKeyResult(KeyResultMetric.Builder.builder() + .withBaseline(3.0) + .withStretchGoal(6.0) + .withId(8L) + .withObjective(objective) + .build()) + .build(); + public static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() + .withZone(Zone.COMMIT) + .withId(4L) + .withCreatedBy(User.Builder.builder() + .withId(2L) + .withFirstname("Robert") + .build()) + .withCreatedOn(LocalDateTime.MAX) + .withChangeInfo(CHANGE_INFO) + .withInitiatives(INITIATIVES) + .withKeyResult(KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withTargetZone("Wald") + .withId(9L) + .build()) + .build(); /* Test DTOs */ - public static final CheckInDto checkInMetricDto = new CheckInMetricDto(5L, 1, CHANGE_INFO_1, INITIATIVES_1, 6, 1L, - LocalDateTime.MAX, LocalDateTime.MAX, 46D, true); - public static final CheckInDto checkInOrdinalDto = new CheckInOrdinalDto(4L, 1, CHANGE_INFO_2, INITIATIVES_2, 5, 2L, - LocalDateTime.MAX, LocalDateTime.MAX, Zone.COMMIT, true); + public static final CheckInDto checkInMetricDto = new CheckInMetricDto(5L, + 1, + CHANGE_INFO_1, + INITIATIVES_1, + 6, + 1L, + LocalDateTime.MAX, + LocalDateTime.MAX, + 46D, + true); + public static final CheckInDto checkInOrdinalDto = new CheckInOrdinalDto(4L, + 1, + CHANGE_INFO_2, + INITIATIVES_2, + 5, + 2L, + LocalDateTime.MAX, + LocalDateTime.MAX, + Zone.COMMIT, + true); private CheckInTestHelpers() { } diff --git a/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java b/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java index 27f175ccb1..0450cf98ec 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java +++ b/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.test; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.keyresult.*; @@ -13,10 +17,6 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; @@ -61,11 +61,11 @@ public class KeyResultTestHelpers { public static final String JSON_PATH_QUARTER_LABEL = "$.objective.keyResultQuarterDto.label"; public static final String JSON_PATH_QUARTER_START_DATE = "$.objective.keyResultQuarterDto.startDate"; public static final String JSON = """ - {"title": "Keyresult 1", - "keyResultType": "metric", - "actionList": [] - }"; - """; + {"title": "Keyresult 1", + "keyResultType": "metric", + "actionList": [] + }"; + """; public static final String URL_BASE = "/api/v2/keyresults"; public static final String URL_TO_KEY_RESULT_1 = "/api/v2/keyresults/1"; public static final String URL_TO_KEY_RESULT_10 = "/api/v2/keyresults/10"; @@ -78,189 +78,266 @@ public class KeyResultTestHelpers { static final String INITIATIVES_2 = "Initiatives2"; static final String CHANGE_INFO_1 = "Changeinfo1"; static final String CHANGE_INFO_2 = "Changeinfo2"; - public static final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - public static final KeyResult metricKeyResult = KeyResultMetric.Builder.builder().withId(5L).withTitle(TITLE) - .build(); - public static final CheckIn checkIn1 = CheckInMetric.Builder.builder().withValue(23D).withId(1L) - .withKeyResult(metricKeyResult).withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withChangeInfo(CHANGE_INFO_1).withInitiatives(INITIATIVES_1).build(); - public static final CheckIn checkIn2 = CheckInMetric.Builder.builder().withValue(12D).withId(4L) - .withKeyResult(metricKeyResult).withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withChangeInfo(CHANGE_INFO_2).withInitiatives(INITIATIVES_2).build(); - public static final CheckInDto checkInDto1 = new CheckInMetricDto(1L, 1, CHANGE_INFO_1, INITIATIVES_1, 6, - metricKeyResult.getId(), LocalDateTime.MAX, LocalDateTime.MAX, 23D, true); - public static final CheckInDto checkInDto2 = new CheckInMetricDto(4L, 1, CHANGE_INFO_2, INITIATIVES_2, 5, - metricKeyResult.getId(), LocalDateTime.MAX, LocalDateTime.MAX, 12D, true); + public static final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + public static final KeyResult metricKeyResult = KeyResultMetric.Builder.builder() + .withId(5L) + .withTitle(TITLE) + .build(); + public static final CheckIn checkIn1 = CheckInMetric.Builder.builder() + .withValue(23D) + .withId(1L) + .withKeyResult(metricKeyResult) + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withChangeInfo(CHANGE_INFO_1) + .withInitiatives(INITIATIVES_1) + .build(); + public static final CheckIn checkIn2 = CheckInMetric.Builder.builder() + .withValue(12D) + .withId(4L) + .withKeyResult(metricKeyResult) + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withChangeInfo(CHANGE_INFO_2) + .withInitiatives(INITIATIVES_2) + .build(); + public static final CheckInDto checkInDto1 = new CheckInMetricDto(1L, + 1, + CHANGE_INFO_1, + INITIATIVES_1, + 6, + metricKeyResult.getId(), + LocalDateTime.MAX, + LocalDateTime.MAX, + 23D, + true); + public static final CheckInDto checkInDto2 = new CheckInMetricDto(4L, + 1, + CHANGE_INFO_2, + INITIATIVES_2, + 5, + metricKeyResult.getId(), + LocalDateTime.MAX, + LocalDateTime.MAX, + 12D, + true); public static final KeyResultUserDto keyResultUserDto = new KeyResultUserDto(1L, FIRSTNAME, LASTNAME); - public static final KeyResultQuarterDto keyResultQuarterDto = new KeyResultQuarterDto(1L, QUARTER_LABEL, - LocalDate.MIN, LocalDate.MAX); - public static final KeyResultLastCheckInMetricDto keyResultLastCheckInDto = new KeyResultLastCheckInMetricDto(1L, 1, - 4.0, 6, LocalDateTime.MIN, CHANGE_INFO_1, INITIATIVES_1); - public static final KeyResultLastCheckInOrdinalDto keyResultLastCheckInOrdinalDto = new KeyResultLastCheckInOrdinalDto( - 1L, 1, LAST_CHECK_IN_ZONE, 6, LocalDateTime.MIN, CHANGE_INFO_2, INITIATIVES_2); + public static final KeyResultQuarterDto keyResultQuarterDto = new KeyResultQuarterDto(1L, + QUARTER_LABEL, + LocalDate.MIN, + LocalDate.MAX); + public static final KeyResultLastCheckInMetricDto keyResultLastCheckInDto = new KeyResultLastCheckInMetricDto(1L, + 1, + 4.0, + 6, + LocalDateTime.MIN, + CHANGE_INFO_1, + INITIATIVES_1); + public static final KeyResultLastCheckInOrdinalDto keyResultLastCheckInOrdinalDto = new KeyResultLastCheckInOrdinalDto(1L, + 1, + LAST_CHECK_IN_ZONE, + 6, + LocalDateTime.MIN, + CHANGE_INFO_2, + INITIATIVES_2); public static final KeyResultObjectiveDto keyResultObjectiveDto = new KeyResultObjectiveDto(1L, - OBJECTIVE_STATE_ONGOING, keyResultQuarterDto); + OBJECTIVE_STATE_ONGOING, + keyResultQuarterDto); - public static final KeyResultMetricDto keyResultMetricDto = new KeyResultMetricDto(5L, 1, KEY_RESULT_TYPE_METRIC, - TITLE, DESCRIPTION, 1.0, 5.0, KEY_RESULT_UNIT, keyResultUserDto, keyResultObjectiveDto, - keyResultLastCheckInDto, LocalDateTime.MIN, LocalDateTime.MAX, true, List.of()); - public static final KeyResultOrdinalDto keyResultOrdinalDto = new KeyResultOrdinalDto(5L, 1, - KEY_RESULT_TYPE_ORDINAL, TITLE, DESCRIPTION, COMMIT_ZONE, TARGET_ZONE, STRETCH_ZONE, keyResultUserDto, - keyResultObjectiveDto, keyResultLastCheckInOrdinalDto, LocalDateTime.MIN, LocalDateTime.MAX, true, - List.of()); - public static final Objective objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").build(); - public static final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder().withId(3L) - .withTitle("Keyresult 2").withOwner(user).withObjective(objective).build(); + public static final KeyResultMetricDto keyResultMetricDto = new KeyResultMetricDto(5L, + 1, + KEY_RESULT_TYPE_METRIC, + TITLE, + DESCRIPTION, + 1.0, + 5.0, + KEY_RESULT_UNIT, + keyResultUserDto, + keyResultObjectiveDto, + keyResultLastCheckInDto, + LocalDateTime.MIN, + LocalDateTime.MAX, + true, + List.of()); + public static final KeyResultOrdinalDto keyResultOrdinalDto = new KeyResultOrdinalDto(5L, + 1, + KEY_RESULT_TYPE_ORDINAL, + TITLE, + DESCRIPTION, + COMMIT_ZONE, + TARGET_ZONE, + STRETCH_ZONE, + keyResultUserDto, + keyResultObjectiveDto, + keyResultLastCheckInOrdinalDto, + LocalDateTime.MIN, + LocalDateTime.MAX, + true, + List.of()); + public static final Objective objective = Objective.Builder.builder() + .withId(5L) + .withTitle("Objective 1") + .build(); + public static final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withId(3L) + .withTitle("Keyresult 2") + .withOwner(user) + .withObjective(objective) + .build(); public static final String CREATE_BODY_METRIC = """ - { - "id":null, - "objectiveId":5, - "title":"", - "description":"", - "ownerId":5, - "keyResultType":"metric", - "createdById":5, - "createdOn":null, - "modifiedOn":null, - "baseline":2.0, - "stretchGoal":5.0, - "unit":"FTE", - "actionList":[] - } - """; + { + "id":null, + "objectiveId":5, + "title":"", + "description":"", + "ownerId":5, + "keyResultType":"metric", + "createdById":5, + "createdOn":null, + "modifiedOn":null, + "baseline":2.0, + "stretchGoal":5.0, + "unit":"FTE", + "actionList":[] + } + """; public static final String CREATE_BODY_ORDINAL = """ - { - "id":null, - "objectiveId":5, - "title":"", - "description":"", - "ownerId":5, - "keyResultType":"ordinal", - "createdById":5, - "createdOn":null, - "modifiedOn":null, - "commitZone":"Eine Pflanze", - "targetZone":"Ein Baum", - "stretchZone":"Ein Wald", - "actionList":[] - } - """; + { + "id":null, + "objectiveId":5, + "title":"", + "description":"", + "ownerId":5, + "keyResultType":"ordinal", + "createdById":5, + "createdOn":null, + "modifiedOn":null, + "commitZone":"Eine Pflanze", + "targetZone":"Ein Baum", + "stretchZone":"Ein Wald", + "actionList":[] + } + """; public static final String CREATE_BODY_ORDINAL_ACTION_LIST = """ - { - "id":null, - "objectiveId":5, - "title":"", - "description":"", - "ownerId":5, - "keyResultType":"ordinal", - "createdById":5, - "createdOn":null, - "modifiedOn":null, - "commitZone":"Eine Pflanze", - "targetZone":"Ein Baum", - "stretchZone":"Ein Wald", - "actionList":[ - { - "id":null, - "version":1, - "action":"Neue Katze", - "priority":0, - "isChecked":true, - "keyResultId":null - }, - { - "id":null, - "version":1, - "action":"Neuer Hund", - "priority":1, - "isChecked":false, - "keyResultId":null - } - ] - } - """; + { + "id":null, + "objectiveId":5, + "title":"", + "description":"", + "ownerId":5, + "keyResultType":"ordinal", + "createdById":5, + "createdOn":null, + "modifiedOn":null, + "commitZone":"Eine Pflanze", + "targetZone":"Ein Baum", + "stretchZone":"Ein Wald", + "actionList":[ + { + "id":null, + "version":1, + "action":"Neue Katze", + "priority":0, + "isChecked":true, + "keyResultId":null + }, + { + "id":null, + "version":1, + "action":"Neuer Hund", + "priority":1, + "isChecked":false, + "keyResultId":null + } + ] + } + """; public static final String CREATE_BODY_KEY_RESULT_TYPE_MISSING = """ - { - "objectiveId":5, - "ownerId":5, - "createdById":5, - "commitZone":"Eine Pflanze", - "targetZone":"Ein Baum", - "stretchZone":"Ein Wald" - } - """; + { + "objectiveId":5, + "ownerId":5, + "createdById":5, + "commitZone":"Eine Pflanze", + "targetZone":"Ein Baum", + "stretchZone":"Ein Wald" + } + """; public static final String CREATE_BODY_KEY_RESULT_TYPE_UNKNOWN = """ - { - "objectiveId":5, - "ownerId":5, - "keyResultType":"unknown", - "createdById":5, - "commitZone":"Eine Pflanze", - "targetZone":"Ein Baum", - "stretchZone":"Ein Wald" - } - """; + { + "objectiveId":5, + "ownerId":5, + "keyResultType":"unknown", + "createdById":5, + "commitZone":"Eine Pflanze", + "targetZone":"Ein Baum", + "stretchZone":"Ein Wald" + } + """; public static final String CREATE_BODY_WITH_ENUM_KEYS = """ - { - "id":null, - "keyResultType":"metric", - "objectiveId":5, - "title":"", - "description":"", - "ownerId":5, - "ownerFirstname":"", - "ownerLastname":"", - "createdById":5, - "createdByFirstname":"", - "createdByLastname":"", - "createdOn":null, - "modifiedOn":null, - "baseline":2.0, - "stretchGoal":5.0, - "unit":"PERCENT", - "actionList":[] - } - """; + { + "id":null, + "keyResultType":"metric", + "objectiveId":5, + "title":"", + "description":"", + "ownerId":5, + "ownerFirstname":"", + "ownerLastname":"", + "createdById":5, + "createdByFirstname":"", + "createdByLastname":"", + "createdOn":null, + "modifiedOn":null, + "baseline":2.0, + "stretchGoal":5.0, + "unit":"PERCENT", + "actionList":[] + } + """; public static final String PUT_BODY_METRIC = """ - { - "id":1, - "keyResultType":"metric", - "title":"Updated Keyresult", - "description":"", - "baseline":2.0, - "stretchGoal":5.0, - "unit":"NUMBER", - "ownerId":5, - "ownerFirstname":"", - "ownerLastname":"", - "objectiveId":5, - "objectiveState":"INPROGRESS", - "objectiveQuarterId":1, - "objectiveQuarterLabel":"GJ 22/23-Q3", - "objectiveQuarterStartDate":null, - "objectiveQuarterEndDate":null, - "lastCheckInId":1, - "lastCheckInValue":4.0, - "lastCheckInConfidence":6, - "lastCheckInCreatedOn":null, - "lastCheckInComment":"", - "createdById":5, - "createdByFirstname":"", - "createdByLastname":"", - "createdOn":null, - "modifiedOn":null, - "actionList":[] - } - """; + { + "id":1, + "keyResultType":"metric", + "title":"Updated Keyresult", + "description":"", + "baseline":2.0, + "stretchGoal":5.0, + "unit":"NUMBER", + "ownerId":5, + "ownerFirstname":"", + "ownerLastname":"", + "objectiveId":5, + "objectiveState":"INPROGRESS", + "objectiveQuarterId":1, + "objectiveQuarterLabel":"GJ 22/23-Q3", + "objectiveQuarterStartDate":null, + "objectiveQuarterEndDate":null, + "lastCheckInId":1, + "lastCheckInValue":4.0, + "lastCheckInConfidence":6, + "lastCheckInCreatedOn":null, + "lastCheckInComment":"", + "createdById":5, + "createdByFirstname":"", + "createdByLastname":"", + "createdOn":null, + "modifiedOn":null, + "actionList":[] + } + """; private KeyResultTestHelpers() { } diff --git a/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java b/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java index 2fe500d842..bff33b7fcd 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java +++ b/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java @@ -1,12 +1,12 @@ package ch.puzzle.okr.test; +import java.lang.annotation.*; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; -import java.lang.annotation.*; - -@Target({ ElementType.TYPE }) +@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited diff --git a/backend/src/test/java/ch/puzzle/okr/test/TestContextInitializer.java b/backend/src/test/java/ch/puzzle/okr/test/TestContextInitializer.java index 80829562cd..9afef1ff2f 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/TestContextInitializer.java +++ b/backend/src/test/java/ch/puzzle/okr/test/TestContextInitializer.java @@ -1,6 +1,7 @@ package ch.puzzle.okr.test; import ch.puzzle.okr.multitenancy.HibernateContext; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContextInitializer; diff --git a/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java b/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java index 86bb30b3f7..450aa52394 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java @@ -1,12 +1,5 @@ package ch.puzzle.okr.test; -import ch.puzzle.okr.dto.ErrorDto; -import ch.puzzle.okr.models.Team; -import ch.puzzle.okr.models.User; -import ch.puzzle.okr.models.UserTeam; -import ch.puzzle.okr.models.authorization.AuthorizationUser; -import org.springframework.security.oauth2.jwt.Jwt; - import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -15,6 +8,14 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import ch.puzzle.okr.dto.ErrorDto; +import ch.puzzle.okr.models.Team; +import ch.puzzle.okr.models.User; +import ch.puzzle.okr.models.UserTeam; +import ch.puzzle.okr.models.authorization.AuthorizationUser; + +import org.springframework.security.oauth2.jwt.Jwt; + public class TestHelper { private TestHelper() { } @@ -26,8 +27,12 @@ private TestHelper() { private static final String EMAIL = "kaufmann@puzzle.ch"; public static User defaultUser(Long id) { - return User.Builder.builder().withId(id).withFirstname(FIRSTNAME).withLastname(LASTNAME).withEmail(EMAIL) - .build(); + return User.Builder.builder() + .withId(id) + .withFirstname(FIRSTNAME) + .withLastname(LASTNAME) + .withEmail(EMAIL) + .build(); } public static User defaultOkrChampion(Long id) { @@ -39,20 +44,34 @@ public static User defaultOkrChampion(Long id) { public static User defaultUserWithTeams(Long userId, List adminTeams, List memberTeams) { var user = defaultUser(userId); var adminUserTeams = adminTeams.stream() - .map(t -> UserTeam.Builder.builder().withTeamAdmin(true).withTeam(t).withUser(user).build()); + .map(t -> UserTeam.Builder.builder() + .withTeamAdmin(true) + .withTeam(t) + .withUser(user) + .build()); var memberUserTeams = memberTeams.stream() - .map(t -> UserTeam.Builder.builder().withTeam(t).withUser(user).build()); - user.setUserTeamList( - Stream.concat(adminUserTeams, memberUserTeams).collect(Collectors.toCollection(ArrayList::new))); + .map(t -> UserTeam.Builder.builder() + .withTeam(t) + .withUser(user) + .build()); + user.setUserTeamList(Stream.concat(adminUserTeams, memberUserTeams) + .collect(Collectors.toCollection(ArrayList::new))); return user; } public static Team defaultTeam(Long id) { - return Team.Builder.builder().withId(id).withName("Test Team").build(); + return Team.Builder.builder() + .withId(id) + .withName("Test Team") + .build(); } public static UserTeam defaultUserTeam(Long id, User user) { - return UserTeam.Builder.builder().withId(id).withTeam(defaultTeam(1L)).withUser(user).build(); + return UserTeam.Builder.builder() + .withId(id) + .withTeam(defaultTeam(1L)) + .withUser(user) + .build(); } public static AuthorizationUser defaultAuthorizationUser() { @@ -60,19 +79,21 @@ public static AuthorizationUser defaultAuthorizationUser() { } public static AuthorizationUser mockAuthorizationUser(User user) { - return mockAuthorizationUser(user.getId(), user.getFirstname(), user.getLastname(), user.getEmail(), - user.isOkrChampion()); + return mockAuthorizationUser(user.getId(), + user.getFirstname(), + user.getLastname(), + user.getEmail(), + user.isOkrChampion()); } - public static AuthorizationUser mockAuthorizationUser(Long id, String firstname, String lastname, String email, - boolean isOkrChampion) { + public static AuthorizationUser mockAuthorizationUser(Long id, String firstname, String lastname, String email, boolean isOkrChampion) { User user = User.Builder.builder() // - .withId(id) // - .withFirstname(firstname) // - .withLastname(lastname) // - .withEmail(email) // - .withOkrChampion(isOkrChampion) // - .build(); + .withId(id) // + .withFirstname(firstname) // + .withLastname(lastname) // + .withEmail(email) // + .withOkrChampion(isOkrChampion) // + .build(); user.setUserTeamList(List.of(defaultUserTeam(1L, user))); return new AuthorizationUser(user); } @@ -96,12 +117,22 @@ public static Jwt mockJwtToken(String firstname, String lastname, String email) claims.put("given_name", firstname); claims.put("family_name", lastname); claims.put("email", email); - claims.put("exp", Instant.now().plusSeconds(3600).getEpochSecond()); // Expires in 1 hour - - return new Jwt(exampleToken, Instant.now(), Instant.now().plusSeconds(3600), headers, claims); + claims.put("exp", + Instant.now() + .plusSeconds(3600) + .getEpochSecond()); // Expires in 1 hour + + return new Jwt(exampleToken, + Instant.now(), + Instant.now() + .plusSeconds(3600), + headers, + claims); } public static List getAllErrorKeys(List errors) { - return errors.stream().map(ErrorDto::errorKey).toList(); + return errors.stream() + .map(ErrorDto::errorKey) + .toList(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java index d7ec5e387a..1ee09f2898 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java @@ -1,9 +1,9 @@ package ch.puzzle.okr.util.quarter.check; -import ch.puzzle.okr.models.Quarter; - import java.time.LocalDate; +import ch.puzzle.okr.models.Quarter; + public class QuarterRangeChecker { public static boolean nowIsInQuarter(LocalDate now, Quarter quarter) { diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java index 8dbf76d0a1..9c6b99df32 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java @@ -1,11 +1,12 @@ package ch.puzzle.okr.util.quarter.check; +import java.time.LocalDate; + import ch.puzzle.okr.models.Quarter; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.time.LocalDate; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -26,7 +27,8 @@ void nowIsInQuarterShouldReturnFalseIfQuarterIsNull() { @Test void nowIsInQuarterShouldReturnFalseIfNowIsNull() { // arrange - Quarter quarter = Quarter.Builder.builder().build(); + Quarter quarter = Quarter.Builder.builder() + .build(); LocalDate now = null; // act + assert @@ -104,8 +106,8 @@ void nowIsInQuarterShouldReturnFalseIfNowIsAfterQuarterEndDate() { private Quarter quarter(LocalDate startDate, LocalDate endDate) { return Quarter.Builder.builder() // - .withStartDate(startDate) // - .withEndDate(endDate) // - .build(); + .withStartDate(startDate) // + .withEndDate(endDate) // + .build(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java index 8d3d466546..ebe4aecc74 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.util.quarter.generate; +import java.time.LocalDate; +import java.util.stream.Stream; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.time.LocalDate; -import java.util.stream.Stream; - import static org.junit.jupiter.api.Assertions.*; public class QuarterLabelTest { @@ -22,33 +22,33 @@ void labelShouldReturnLabelWithYearAndQuarterInfo(LocalDate date, String expecte private static Stream datesAndLabels() { return Stream.of( // - Arguments.of(LocalDate.of(2024, 7, 1), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 7, 2), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 7, 15), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 9, 15), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 9, 29), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 9, 30), "GJ 24/25-Q1"), - - Arguments.of(LocalDate.of(2024, 10, 1), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 10, 2), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 10, 15), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 12, 15), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 12, 30), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 12, 31), "GJ 24/25-Q2"), - - Arguments.of(LocalDate.of(2024, 1, 1), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 1, 2), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 1, 15), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 3, 15), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 3, 30), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 3, 31), "GJ 23/24-Q3"), - - Arguments.of(LocalDate.of(2024, 4, 1), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 4, 2), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 4, 15), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 6, 15), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 6, 29), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 6, 30), "GJ 23/24-Q4")); + Arguments.of(LocalDate.of(2024, 7, 1), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 7, 2), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 7, 15), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 9, 15), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 9, 29), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 9, 30), "GJ 24/25-Q1"), + + Arguments.of(LocalDate.of(2024, 10, 1), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 10, 2), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 10, 15), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 12, 15), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 12, 30), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 12, 31), "GJ 24/25-Q2"), + + Arguments.of(LocalDate.of(2024, 1, 1), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 1, 2), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 1, 15), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 3, 15), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 3, 30), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 3, 31), "GJ 23/24-Q3"), + + Arguments.of(LocalDate.of(2024, 4, 1), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 4, 2), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 4, 15), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 6, 15), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 6, 29), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 6, 30), "GJ 23/24-Q4")); } } diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java index 43d7aca711..0dc5d804f7 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java @@ -1,14 +1,14 @@ package ch.puzzle.okr.util.quarter.generate; +import java.time.LocalDate; +import java.util.stream.Stream; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.time.LocalDate; -import java.util.stream.Stream; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -17,8 +17,7 @@ public class QuartersTest { @DisplayName("currentQuarter() should find current quarter for now and 12 months in future") @ParameterizedTest @MethodSource("futureDatesAndLabels") - void currentQuarterShouldFindCurrentQuarterForNowAnd12MonthsInFuture(LocalDate date, String expectedLabelFirstYear, - String expectedLabelSecondYear) { + void currentQuarterShouldFindCurrentQuarterForNowAnd12MonthsInFuture(LocalDate date, String expectedLabelFirstYear, String expectedLabelSecondYear) { // arrange Quarters nowQuarters = new Quarters(date.getYear()); @@ -37,65 +36,64 @@ void currentQuarterShouldFindCurrentQuarterForNowAnd12MonthsInFuture(LocalDate d private static Stream futureDatesAndLabels() { return Stream.of( // - Arguments.of( // - LocalDate.of(2024, 7, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), - Arguments.of( // - LocalDate.of(2024, 8, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), - Arguments.of( // - LocalDate.of(2024, 9, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), - Arguments.of( // - LocalDate.of(2024, 10, 15), // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), - Arguments.of( // - LocalDate.of(2024, 11, 15), // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), - Arguments.of( // - LocalDate.of(2024, 12, 15), // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), - Arguments.of( // - LocalDate.of(2025, 1, 15), // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), - Arguments.of( // - LocalDate.of(2025, 2, 15), // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), - Arguments.of( // - LocalDate.of(2025, 3, 15), // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), - Arguments.of( // - LocalDate.of(2025, 4, 15), // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), - Arguments.of( // - LocalDate.of(2025, 5, 15), // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), - Arguments.of( // - LocalDate.of(2025, 6, 15), // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), - Arguments.of( // - LocalDate.of(2025, 7, 15), // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')", // - "('GJ 25/26-Q2', '2025-10-01', '2025-12-31')")); + Arguments.of( // + LocalDate.of(2024, 7, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), + Arguments.of( // + LocalDate.of(2024, 8, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), + Arguments.of( // + LocalDate.of(2024, 9, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), + Arguments.of( // + LocalDate.of(2024, 10, 15), // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), + Arguments.of( // + LocalDate.of(2024, 11, 15), // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), + Arguments.of( // + LocalDate.of(2024, 12, 15), // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), + Arguments.of( // + LocalDate.of(2025, 1, 15), // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), + Arguments.of( // + LocalDate.of(2025, 2, 15), // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), + Arguments.of( // + LocalDate.of(2025, 3, 15), // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), + Arguments.of( // + LocalDate.of(2025, 4, 15), // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), + Arguments.of( // + LocalDate.of(2025, 5, 15), // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), + Arguments.of( // + LocalDate.of(2025, 6, 15), // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), + Arguments.of( // + LocalDate.of(2025, 7, 15), // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')", // + "('GJ 25/26-Q2', '2025-10-01', '2025-12-31')")); } @DisplayName("currentQuarter() should find current quarter for now and 7 months in past") @ParameterizedTest @MethodSource("pastDatesAndLabels") - void currentQuarterShouldFindCurrentQuarterForNowAnd7MonthsInPast(LocalDate date, String expectedLabelFirstYear, - String expectedLabelSecondYear) { + void currentQuarterShouldFindCurrentQuarterForNowAnd7MonthsInPast(LocalDate date, String expectedLabelFirstYear, String expectedLabelSecondYear) { // arrange Quarters nowQuarters = new Quarters(date.getYear()); @@ -114,38 +112,38 @@ void currentQuarterShouldFindCurrentQuarterForNowAnd7MonthsInPast(LocalDate date private static Stream pastDatesAndLabels() { return Stream.of( // - Arguments.of( // - LocalDate.of(2023, 12, 15), // - "('GJ 23/24-Q2', '2023-10-01', '2023-12-31')", // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')"), - Arguments.of( // - LocalDate.of(2024, 1, 15), // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), - Arguments.of( // - LocalDate.of(2024, 2, 15), // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), - Arguments.of( // - LocalDate.of(2024, 3, 15), // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), - Arguments.of( // - LocalDate.of(2024, 4, 15), // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), - Arguments.of( // - LocalDate.of(2024, 5, 15), // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), - Arguments.of( // - LocalDate.of(2024, 6, 15), // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), - Arguments.of( // - LocalDate.of(2024, 7, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')")); + Arguments.of( // + LocalDate.of(2023, 12, 15), // + "('GJ 23/24-Q2', '2023-10-01', '2023-12-31')", // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')"), + Arguments.of( // + LocalDate.of(2024, 1, 15), // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), + Arguments.of( // + LocalDate.of(2024, 2, 15), // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), + Arguments.of( // + LocalDate.of(2024, 3, 15), // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), + Arguments.of( // + LocalDate.of(2024, 4, 15), // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), + Arguments.of( // + LocalDate.of(2024, 5, 15), // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), + Arguments.of( // + LocalDate.of(2024, 6, 15), // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), + Arguments.of( // + LocalDate.of(2024, 7, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')")); } @DisplayName("currentQuarter() should throw exception if no matching quarter is found for now") @@ -159,7 +157,7 @@ void currentQuarterShouldThrowExceptionIfNoMatchingQuarterIsFoundForNow() { // act RuntimeException exception = assertThrows(RuntimeException.class, - () -> allQuartersOfCurrentYear.currentQuarter(in2Years)); + () -> allQuartersOfCurrentYear.currentQuarter(in2Years)); // assert assertEquals(RuntimeException.class, exception.getClass()); @@ -182,12 +180,12 @@ void currentQuarterShouldFindCurrentQuarterForBoundaryDates(LocalDate date, Stri private static Stream boundaryDatesAndLabels() { return Stream.of( // - Arguments.of( // - LocalDate.of(2024, 7, 1), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), // - Arguments.of( // - LocalDate.of(2024, 9, 30), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')") // + Arguments.of( // + LocalDate.of(2024, 7, 1), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), // + Arguments.of( // + LocalDate.of(2024, 9, 30), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')") // ); } } diff --git a/frontend/cypress/e2e/checkIn.cy.ts b/frontend/cypress/e2e/checkIn.cy.ts index 6024396ae2..61c2b7c8ba 100644 --- a/frontend/cypress/e2e/checkIn.cy.ts +++ b/frontend/cypress/e2e/checkIn.cy.ts @@ -411,8 +411,8 @@ function checkForDialogTextOrdinal() { function getCurrentDate() { const today = new Date(); const yyyy = today.getFullYear(); - let mm = today.getMonth() + 1; // Months start at 0! - let dd = today.getDate(); + const mm = today.getMonth() + 1; // Months start at 0! + const dd = today.getDate(); let dd_str = '' + dd; let mm_str = '' + mm; diff --git a/frontend/cypress/e2e/duplicated-scoring.cy.ts b/frontend/cypress/e2e/duplicated-scoring.cy.ts index 6a87dbd243..b4dc29e337 100644 --- a/frontend/cypress/e2e/duplicated-scoring.cy.ts +++ b/frontend/cypress/e2e/duplicated-scoring.cy.ts @@ -28,7 +28,7 @@ describe('e2e test for scoring adjustment on objective duplicate', () => { cy.fillOutObjective('A duplicated Objective for this tool', 'safe', '3'); cy.visit('/?quarter=3'); - let scoringBlock1 = cy + const scoringBlock1 = cy .get('.objective:contains("A duplicated Objective for this tool")') .first() .getByTestId('key-result') @@ -41,7 +41,7 @@ describe('e2e test for scoring adjustment on objective duplicate', () => { scoringBlock1.getByTestId('fail').first().should('not.have.css', 'score-green'); scoringBlock1.getByTestId('fail').first().should('not.have.css', 'score-stretch'); - let scoringBlock2 = cy + const scoringBlock2 = cy .getByTestId('objective') .first() .getByTestId('key-result') diff --git a/frontend/cypress/e2e/teammanagement.cy.ts b/frontend/cypress/e2e/teammanagement.cy.ts index 6f595384cd..659bf05c71 100644 --- a/frontend/cypress/e2e/teammanagement.cy.ts +++ b/frontend/cypress/e2e/teammanagement.cy.ts @@ -263,11 +263,11 @@ describe('Team management tests', () => { let foundEsha = false; cy.get('app-member-list tbody tr') .each(($row) => { - let usernameCell = $row.find('td:nth-child(2)'); + const usernameCell = $row.find('td:nth-child(2)'); if (usernameCell.text().trim() === nameEsha) { foundEsha = true; - let roleCell = $row.find('td:nth-child(3)'); - let teamsCell = $row.find('td:nth-child(4)'); + const roleCell = $row.find('td:nth-child(3)'); + const teamsCell = $row.find('td:nth-child(4)'); expect(roleCell.text().trim()).to.equal('Team-Admin, Team-Member'); expect(teamsCell.text().trim()).to.equal('/BBT, LoremIpsum'); return false; @@ -373,7 +373,7 @@ describe('Team management tests', () => { cy.get('app-member-list tbody tr') .each(($row) => { - let usernameCell = $row.find('td:nth-child(2)'); + const usernameCell = $row.find('td:nth-child(2)'); if (usernameCell.text().trim() !== 'Findus Peterson') { return; } diff --git a/frontend/cypress/support/scoringSupport.ts b/frontend/cypress/support/scoringSupport.ts index e79bdad5ca..2e825ee42f 100644 --- a/frontend/cypress/support/scoringSupport.ts +++ b/frontend/cypress/support/scoringSupport.ts @@ -7,8 +7,8 @@ interface ScoringValue { } export function validateScoring(isOverview: boolean, percentage: number) { - let rgbCode = colorFromPercentage(percentage); - let scoringValue = scoringValueFromPercentage(percentage); + const rgbCode = colorFromPercentage(percentage); + const scoringValue = scoringValueFromPercentage(percentage); if (percentage >= 100) { cy.getZone('stretch', isOverview).should('have.attr', 'src').should('include', 'star-filled-icon.svg'); @@ -81,12 +81,12 @@ function scoringValueFromPercentage(percentage: number): ScoringValue { if (percentage >= 100) { return { failPercent: 0, commitPercent: 0, targetPercent: 0 }; } else if (percentage > 70) { - let targetPercent = (percentage - 70) * (100 / 30); + const targetPercent = (percentage - 70) * (100 / 30); return { failPercent: 100, commitPercent: 100, targetPercent: targetPercent }; } else if (percentage > 30) { - let commitPercent = (percentage - 30) * (100 / 40); + const commitPercent = (percentage - 30) * (100 / 40); return { failPercent: 100, commitPercent: commitPercent, targetPercent: -1 }; } - let failPercent = percentage * (100 / 30); + const failPercent = percentage * (100 / 30); return { failPercent: failPercent, commitPercent: -1, targetPercent: -1 }; } diff --git a/frontend/src/app/components/action-plan/action-plan.component.ts b/frontend/src/app/components/action-plan/action-plan.component.ts index e08f5da787..e46acdd1d0 100644 --- a/frontend/src/app/components/action-plan/action-plan.component.ts +++ b/frontend/src/app/components/action-plan/action-plan.component.ts @@ -41,7 +41,7 @@ export class ActionPlanComponent { changeItemPosition(newIndex: number, currentIndex: number) { this.activeItem = newIndex; - let currentActionPlan: Action[] = this.control.getValue()!; + const currentActionPlan: Action[] = this.control.getValue()!; this.updateActionTexts(currentActionPlan); moveItemInArray(currentActionPlan, currentIndex, newIndex); currentActionPlan.forEach((action: Action, index: number) => (action.priority = index)); @@ -49,7 +49,7 @@ export class ActionPlanComponent { } updateActionTexts(currentActionPlan: Action[]) { - let texts = Array.from(this.listItems).map((input: any) => input.nativeElement.value); + const texts = Array.from(this.listItems).map((input: any) => input.nativeElement.value); currentActionPlan.forEach((action: Action, index: number) => (action.action = texts[index])); } @@ -66,7 +66,7 @@ export class ActionPlanComponent { } drop(event: CdkDragDrop) { - let value: string = (( + const value: string = (( event.container.element.nativeElement.children[event.previousIndex].children[1] )).value; const actions: Action[] = this.control.getValue()!; @@ -92,7 +92,7 @@ export class ActionPlanComponent { } removeAction(index: number) { - let actions: Action[] = this.control.getValue()!; + const actions: Action[] = this.control.getValue()!; if (this.activeItem == index && this.activeItem > 0) { this.activeItem--; } diff --git a/frontend/src/app/components/application-banner/application-banner.component.spec.ts b/frontend/src/app/components/application-banner/application-banner.component.spec.ts index 86e542750c..0975757428 100644 --- a/frontend/src/app/components/application-banner/application-banner.component.spec.ts +++ b/frontend/src/app/components/application-banner/application-banner.component.spec.ts @@ -81,9 +81,9 @@ describe('ApplicationBannerComponent', () => { it('should should hide banner if scrolled down', fakeAsync(() => { //Set bannerHeight to default - let bannerHeight: number = 160; + const bannerHeight: number = 160; //Scroll more than the height of the banner - let scrollTop: number = 180; + const scrollTop: number = 180; //Set lastScrollPosition to smaller than scrollTop => user scrolls down component.lastScrollPosition = 160; component.bannerHeight = bannerHeight; @@ -101,7 +101,7 @@ describe('ApplicationBannerComponent', () => { it('should show banner if scrolled up', fakeAsync(() => { //Scroll more than the height of the banner - let scrollTop: number = 180; + const scrollTop: number = 180; //Set lastScrollPosition to bigger than scrollTop => user scrolls up component.lastScrollPosition = 200; diff --git a/frontend/src/app/components/application-banner/application-banner.component.ts b/frontend/src/app/components/application-banner/application-banner.component.ts index d9a064f348..a2a620c770 100644 --- a/frontend/src/app/components/application-banner/application-banner.component.ts +++ b/frontend/src/app/components/application-banner/application-banner.component.ts @@ -41,7 +41,7 @@ export class ApplicationBannerComponent implements AfterViewInit, OnDestroy { } changeHeaderAppearance() { - let scrollTop: number = window.scrollY || document.documentElement.scrollTop; + const scrollTop: number = window.scrollY || document.documentElement.scrollTop; this.refreshBanner(scrollTop); this.lastScrollPosition = scrollTop; } diff --git a/frontend/src/app/components/application-top-bar/application-top-bar.component.ts b/frontend/src/app/components/application-top-bar/application-top-bar.component.ts index cecc531c29..e030c6a9bd 100644 --- a/frontend/src/app/components/application-top-bar/application-top-bar.component.ts +++ b/frontend/src/app/components/application-top-bar/application-top-bar.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { OAuthService } from 'angular-oauth2-oidc'; -import { BehaviorSubject, filter, Observable, of, Subscription, switchMap } from 'rxjs'; +import { BehaviorSubject, Subscription } from 'rxjs'; import { ConfigService } from '../../services/config.service'; import { NavigationEnd, Router } from '@angular/router'; import { UserService } from '../../services/user.service'; @@ -15,7 +15,7 @@ import { getFullNameFromUser } from '../../shared/types/model/User'; export class ApplicationTopBarComponent implements OnInit, OnDestroy { userFullName: string = ''; menuIsOpen = false; - logoSrc$ = new BehaviorSubject('assets/images/empty.svg'); + logoSrc$ = new BehaviorSubject('assets/images/empty.svg'); private subscription?: Subscription; constructor( diff --git a/frontend/src/app/components/key-result-form/key-result-form.component.spec.ts b/frontend/src/app/components/key-result-form/key-result-form.component.spec.ts index 3e29d0ee5a..63c0ac2b2a 100644 --- a/frontend/src/app/components/key-result-form/key-result-form.component.spec.ts +++ b/frontend/src/app/components/key-result-form/key-result-form.component.spec.ts @@ -173,12 +173,12 @@ describe('KeyResultFormComponent', () => { }); it('should return label from user', () => { - let userName: string = component.getUserNameFromUser(testUser); + const userName: string = component.getUserNameFromUser(testUser); expect(userName).toEqual('Bob Baumeister'); }); it('should set metric values', () => { - let fullKeyResultMetric: KeyResultMetric = { + const fullKeyResultMetric: KeyResultMetric = { id: 3, version: 2, title: 'Der Titel ist hier', @@ -203,7 +203,7 @@ describe('KeyResultFormComponent', () => { }); it('should set ordinal values', () => { - let fullKeyResultOrdinal: KeyResultOrdinal = { + const fullKeyResultOrdinal: KeyResultOrdinal = { id: 3, version: 2, title: 'Der Titel ist hier', @@ -234,7 +234,7 @@ describe('KeyResultFormComponent', () => { }); it('should get username from user right', () => { - let user = users[0]; + const user = users[0]; expect(component.getUserNameFromUser(user)).toEqual('Bob Baumeister'); expect(component.getUserNameFromUser(null!)).toEqual(''); }); diff --git a/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.spec.ts b/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.spec.ts index e13b93a55d..08d4134fdb 100644 --- a/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.spec.ts +++ b/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.spec.ts @@ -47,7 +47,7 @@ describe('KeyresultDialogComponent', () => { getCurrentUser: jest.fn(), }; - let fullObjective = { + const fullObjective = { id: 1, title: 'Das ist ein Objective', description: 'Das ist die Beschreibung', @@ -56,13 +56,13 @@ describe('KeyresultDialogComponent', () => { quarter: { id: 1, label: 'GJ 22/23-Q2' }, }; - let keyResultObjective: KeyResultObjective = { + const keyResultObjective: KeyResultObjective = { id: 2, state: State.ONGOING, quarter: new Quarter(1, 'GJ 22/23-Q2', new Date(), new Date()), }; - let fullKeyResultMetric = { + const fullKeyResultMetric = { id: 3, version: 2, actionList: [ @@ -98,7 +98,7 @@ describe('KeyresultDialogComponent', () => { unit: 'CHF', }; - let receivedKeyResultMetric = { + const receivedKeyResultMetric = { id: 3, version: 2, actionList: [ @@ -137,7 +137,7 @@ describe('KeyresultDialogComponent', () => { stretchZone: null, }; - let fullKeyResultOrdinal = { + const fullKeyResultOrdinal = { id: 6, version: 2, actionList: [ @@ -173,7 +173,7 @@ describe('KeyresultDialogComponent', () => { stretchZone: 'Stretch goal', }; - let receivedKeyResultOrdinal = { + const receivedKeyResultOrdinal = { id: 6, version: 2, actionList: [ @@ -212,7 +212,7 @@ describe('KeyresultDialogComponent', () => { unit: null, }; - let initKeyResult = { + const initKeyResult = { id: undefined, title: '', description: '', @@ -228,7 +228,7 @@ describe('KeyresultDialogComponent', () => { actionList: [], }; - let savedKeyResult = { + const savedKeyResult = { id: undefined, version: undefined, title: 'Neuer Titel', diff --git a/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.ts b/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.ts index 9526b25676..8e55009152 100644 --- a/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.ts +++ b/frontend/src/app/components/keyresult-dialog/keyresult-dialog.component.ts @@ -44,7 +44,7 @@ export class KeyresultDialogComponent { saveKeyResult(openNewDialog = false) { const value = this.keyResultForm.value; - let keyResult = this.isMetricKeyResult() + const keyResult = this.isMetricKeyResult() ? ({ ...value, objective: this.data.objective } as KeyResultMetricDTO) : ({ ...value, objective: this.data.objective, id: this.data.keyResult?.id } as KeyResultOrdinalDTO); keyResult.id = this.data.keyResult?.id; diff --git a/frontend/src/app/components/keyresult-type/keyresult-type.component.spec.ts b/frontend/src/app/components/keyresult-type/keyresult-type.component.spec.ts index 5e2e5dcfe6..cf81571b3f 100644 --- a/frontend/src/app/components/keyresult-type/keyresult-type.component.spec.ts +++ b/frontend/src/app/components/keyresult-type/keyresult-type.component.spec.ts @@ -13,10 +13,10 @@ describe('KeyresultTypeComponent', () => { let component: KeyresultTypeComponent; let fixture: ComponentFixture; - let metricKeyResult: KeyResult = keyResultMetric; - let ordinalKeyResult: KeyResult = keyResultOrdinal; + const metricKeyResult: KeyResult = keyResultMetric; + const ordinalKeyResult: KeyResult = keyResultOrdinal; - let metricKeyResultForm = new FormGroup({ + const metricKeyResultForm = new FormGroup({ title: new FormControl('100% aller Schweizer Kunden betreuen', [ Validators.required, Validators.minLength(2), @@ -35,7 +35,7 @@ describe('KeyresultTypeComponent', () => { keyResultType: new FormControl('metric'), }); - let ordinalKeyResultForm = new FormGroup({ + const ordinalKeyResultForm = new FormGroup({ title: new FormControl('100% aller Schweizer Kunden betreuen', [ Validators.required, Validators.minLength(2), @@ -54,7 +54,7 @@ describe('KeyresultTypeComponent', () => { keyResultType: new FormControl('metric'), }); - let emptyKeyResultForm = new FormGroup({ + const emptyKeyResultForm = new FormGroup({ title: new FormControl('100% aller Schweizer Kunden betreuen', [ Validators.required, Validators.minLength(2), @@ -124,7 +124,7 @@ describe('KeyresultTypeComponent', () => { it('should select metric tab', () => { component.isMetric = true; - let activeTab = document.getElementsByClassName('active')[0]; + const activeTab = document.getElementsByClassName('active')[0]; expect(activeTab.innerHTML).toContain('Metrisch'); }); @@ -189,7 +189,7 @@ describe('KeyresultTypeComponent', () => { component.isMetric = false; fixture.detectChanges(); - let activeTab = document.getElementsByClassName('active')[0]; + const activeTab = document.getElementsByClassName('active')[0]; expect(activeTab.innerHTML).toContain('Ordinal'); }); @@ -253,7 +253,7 @@ describe('KeyresultTypeComponent', () => { it('should select metric tab', () => { component.isMetric = true; - let activeTab = document.getElementsByClassName('active')[0]; + const activeTab = document.getElementsByClassName('active')[0]; expect(activeTab.innerHTML).toContain('Metrisch'); }); diff --git a/frontend/src/app/components/keyresult-type/keyresult-type.component.ts b/frontend/src/app/components/keyresult-type/keyresult-type.component.ts index 0be35b7ced..3c6cdec431 100644 --- a/frontend/src/app/components/keyresult-type/keyresult-type.component.ts +++ b/frontend/src/app/components/keyresult-type/keyresult-type.component.ts @@ -94,7 +94,7 @@ export class KeyresultTypeComponent implements OnInit { switchKeyResultType(type: string) { if (((type == 'metric' && !this.isMetric) || (type == 'ordinal' && this.isMetric)) && this.typeChangeAllowed) { this.isMetric = !this.isMetric; - let keyResultType = this.isMetric ? 'metric' : 'ordinal'; + const keyResultType = this.isMetric ? 'metric' : 'ordinal'; this.keyResultForm.controls['keyResultType'].setValue(keyResultType); this.switchValidators(); } diff --git a/frontend/src/app/components/objective-detail/objective-detail.component.spec.ts b/frontend/src/app/components/objective-detail/objective-detail.component.spec.ts index 8a397f7582..425c38ac44 100644 --- a/frontend/src/app/components/objective-detail/objective-detail.component.spec.ts +++ b/frontend/src/app/components/objective-detail/objective-detail.component.spec.ts @@ -11,7 +11,7 @@ import { ActivatedRoute } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { TranslateModule } from '@ngx-translate/core'; -let objectiveService = { +const objectiveService = { getFullObjective: jest.fn(), }; diff --git a/frontend/src/app/components/objective/objective.component.spec.ts b/frontend/src/app/components/objective/objective.component.spec.ts index 79385ab23c..754996bc56 100644 --- a/frontend/src/app/components/objective/objective.component.spec.ts +++ b/frontend/src/app/components/objective/objective.component.spec.ts @@ -89,7 +89,7 @@ describe('ObjectiveColumnComponent', () => { component.objective = { ...objectiveMin, state: state }; fixture.detectChanges(); const image = fixture.debugElement.query(By.css('[data-testid="objective-state"]')); - let statusIndicatorSrc = image.attributes['src']; + const statusIndicatorSrc = image.attributes['src']; expect(statusIndicatorSrc).toBe(path); }); diff --git a/frontend/src/app/components/objective/objective.component.ts b/frontend/src/app/components/objective/objective.component.ts index d67984a57b..74cdefd935 100644 --- a/frontend/src/app/components/objective/objective.component.ts +++ b/frontend/src/app/components/objective/objective.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnInit, ViewChild } from '@angular/core'; +import { Component, Input, ViewChild } from '@angular/core'; import { ObjectiveMin } from '../../shared/types/model/ObjectiveMin'; import { Router } from '@angular/router'; import { map, ReplaySubject, take } from 'rxjs'; diff --git a/frontend/src/app/components/overview/overview.component.ts b/frontend/src/app/components/overview/overview.component.ts index b5c2b9158d..46f9093478 100644 --- a/frontend/src/app/components/overview/overview.component.ts +++ b/frontend/src/app/components/overview/overview.component.ts @@ -7,7 +7,6 @@ import { EMPTY, ReplaySubject, Subject, - Subscription, take, takeUntil, } from 'rxjs'; @@ -29,7 +28,7 @@ export class OverviewComponent implements OnInit, OnDestroy { private destroyed$: ReplaySubject = new ReplaySubject(1); overviewPadding: Subject = new Subject(); - backgroundLogoSrc$ = new BehaviorSubject('assets/images/empty.svg'); + backgroundLogoSrc$ = new BehaviorSubject('assets/images/empty.svg'); constructor( private overviewService: OverviewService, diff --git a/frontend/src/app/guards/auth.guard.ts b/frontend/src/app/guards/auth.guard.ts index 21a018e322..896f54f48c 100644 --- a/frontend/src/app/guards/auth.guard.ts +++ b/frontend/src/app/guards/auth.guard.ts @@ -7,14 +7,14 @@ export const authGuard: CanActivateFn = (route, state) => { const router = inject(Router); return oauthService.loadDiscoveryDocumentAndTryLogin().then(async () => { // if the login failed initialize code flow - let validToken = oauthService.hasValidIdToken(); + const validToken = oauthService.hasValidIdToken(); if (!validToken) { oauthService.initCodeFlow(); return false; } oauthService.setupAutomaticSilentRefresh(); // redirect route to remove state query param. do it only, if this param exist to avoid infinite loop - if (!!route.queryParamMap.get('state')) { + if (route.queryParamMap.get('state')) { await router.navigateByUrl(''); return false; } diff --git a/frontend/src/app/interceptors/error-interceptor.service.ts b/frontend/src/app/interceptors/error-interceptor.service.ts index c5841d0990..e91464e392 100644 --- a/frontend/src/app/interceptors/error-interceptor.service.ts +++ b/frontend/src/app/interceptors/error-interceptor.service.ts @@ -60,7 +60,7 @@ export class ErrorInterceptor implements HttpInterceptor { if (!successMessageObj) return; let messageKey = successMessageObj.key; - let isBacklogQuarter = !GJ_REGEX_PATTERN.test(response.body?.quarterLabel); + const isBacklogQuarter = !GJ_REGEX_PATTERN.test(response.body?.quarterLabel); if (messageKey == 'OBJECTIVE.POST' && isBacklogQuarter) { messageKey += '_BACKLOG'; } @@ -75,7 +75,7 @@ export class ErrorInterceptor implements HttpInterceptor { for (const toasterMessage of value.methods) { if (toasterMessage.method == method) { - for (let codeKey of toasterMessage.keysForCode || []) { + for (const codeKey of toasterMessage.keysForCode || []) { if (codeKey.code == statusCode) { const messageKey = value.KEY + '.' + codeKey.key; return { key: messageKey, toasterType: codeKey.toaster }; diff --git a/frontend/src/app/interceptors/error.interceptor.spec.ts b/frontend/src/app/interceptors/error.interceptor.spec.ts index 14477ec29b..bd395a8675 100644 --- a/frontend/src/app/interceptors/error.interceptor.spec.ts +++ b/frontend/src/app/interceptors/error.interceptor.spec.ts @@ -159,7 +159,7 @@ describe('ErrorInterceptor', () => { jest.spyOn(toaster, 'showCustomToaster'); jest.spyOn(interceptor, 'getSuccessMessageKey').mockReturnValue({ key: 'OBJECTIVE.POST', toasterType: undefined }); - let mockHttpResponse = { + const mockHttpResponse = { url: '"http://localhost:4200/api/v2/objectives"', status: 201, statusText: 'Created', diff --git a/frontend/src/app/interceptors/oauth.interceptor.spec.ts b/frontend/src/app/interceptors/oauth.interceptor.spec.ts index 8650d459c9..ef7da9d42e 100644 --- a/frontend/src/app/interceptors/oauth.interceptor.spec.ts +++ b/frontend/src/app/interceptors/oauth.interceptor.spec.ts @@ -2,7 +2,7 @@ import { TestBed } from '@angular/core/testing'; import { OauthInterceptor } from './oauth.interceptor'; import { HttpClientTestingModule } from '@angular/common/http/testing'; -import { DateTimeProvider, OAuthLogger, OAuthModule, OAuthService, UrlHelperService } from 'angular-oauth2-oidc'; +import { DateTimeProvider, OAuthLogger, OAuthService, UrlHelperService } from 'angular-oauth2-oidc'; describe('OauthInterceptor', () => { beforeEach(() => diff --git a/frontend/src/app/services/customization.service.spec.ts b/frontend/src/app/services/customization.service.spec.ts index 9dae942dfa..6a2e3f2875 100644 --- a/frontend/src/app/services/customization.service.spec.ts +++ b/frontend/src/app/services/customization.service.spec.ts @@ -42,7 +42,7 @@ describe('CustomizationService', () => { let service: CustomizationService; let configServiceMock: ConfigService; let documentMock: Document; - let callRecorder = new CallRecorder(); + const callRecorder = new CallRecorder(); let configSubject: BehaviorSubject; beforeEach(() => { diff --git a/frontend/src/app/services/dialog.service.ts b/frontend/src/app/services/dialog.service.ts index 964ce85571..cac62be5cc 100644 --- a/frontend/src/app/services/dialog.service.ts +++ b/frontend/src/app/services/dialog.service.ts @@ -35,7 +35,7 @@ export class DialogService { }); } - openConfirmDialog(translationKey: string, i18nData?: Object): MatDialogRef { + openConfirmDialog(translationKey: string, i18nData?: object): MatDialogRef { const title = this.translationService.instant(`${translationKey}.TITLE`, i18nData); const text = this.translationService.instant(`${translationKey}.TEXT`, i18nData); return this.open(ConfirmDialogComponent, { diff --git a/frontend/src/app/services/objective-menu-actions.service.spec.ts b/frontend/src/app/services/objective-menu-actions.service.spec.ts index 75124354cc..638159feb6 100644 --- a/frontend/src/app/services/objective-menu-actions.service.spec.ts +++ b/frontend/src/app/services/objective-menu-actions.service.spec.ts @@ -29,36 +29,36 @@ describe('ObjectiveMenuActionsService', () => { describe('getMenu', () => { it('should return default and specific menu entries for an ongoing objective', () => { - let spyOn = jest.spyOn(service as any, 'getOngoingMenuActions'); + const spyOn = jest.spyOn(service as any, 'getOngoingMenuActions'); - let objectiveMinLocal: ObjectiveMin = objectiveMin; + const objectiveMinLocal: ObjectiveMin = objectiveMin; objectiveMinLocal.state = State.ONGOING; service.getMenu(objectiveMinLocal); expect(spyOn).toHaveBeenCalledTimes(1); }); it('should return draft menu entries for a draft objective', () => { - let spyOn = jest.spyOn(service as any, 'getDraftMenuActions'); + const spyOn = jest.spyOn(service as any, 'getDraftMenuActions'); - let objectiveMinLocal: ObjectiveMin = objectiveMin; + const objectiveMinLocal: ObjectiveMin = objectiveMin; objectiveMinLocal.state = State.DRAFT; service.getMenu(objectiveMinLocal); expect(spyOn).toHaveBeenCalledTimes(1); }); it('should return completed menu entries for a successful objective', () => { - let spyOn = jest.spyOn(service as any, 'getCompletedMenuActions'); + const spyOn = jest.spyOn(service as any, 'getCompletedMenuActions'); - let objectiveMinLocal: ObjectiveMin = objectiveMin; + const objectiveMinLocal: ObjectiveMin = objectiveMin; objectiveMinLocal.state = State.SUCCESSFUL; service.getMenu(objectiveMinLocal); expect(spyOn).toHaveBeenCalledTimes(1); }); it('should return completed menu entries for a non-successful objective', () => { - let spyOn = jest.spyOn(service as any, 'getCompletedMenuActions'); + const spyOn = jest.spyOn(service as any, 'getCompletedMenuActions'); - let objectiveMinLocal: ObjectiveMin = objectiveMin; + const objectiveMinLocal: ObjectiveMin = objectiveMin; objectiveMinLocal.state = State.NOTSUCCESSFUL; service.getMenu(objectiveMinLocal); expect(spyOn).toHaveBeenCalledTimes(1); @@ -71,14 +71,14 @@ describe('ObjectiveMenuActionsService', () => { describe('getReleaseAction', () => { it('should return release from backlog action for an objective in backlog quarter', () => { jest.spyOn(service as any, 'isInBacklogQuarter').mockReturnValue(true); - let spyOn = jest.spyOn(service as any, 'isInBacklogQuarter').mockReturnValue(true); + const spyOn = jest.spyOn(service as any, 'isInBacklogQuarter').mockReturnValue(true); // @ts-expect-error service.getReleaseAction(objectiveMin); expect(spyOn).toHaveBeenCalledTimes(1); }); it('should return release from quarter action for an objective in non-backlog quarter', () => { - let spyOn = jest.spyOn(service as any, 'isInBacklogQuarter').mockReturnValue(false); + const spyOn = jest.spyOn(service as any, 'isInBacklogQuarter').mockReturnValue(false); // @ts-expect-error service.getReleaseAction(objectiveMin); expect(spyOn).toHaveBeenCalledTimes(1); diff --git a/frontend/src/app/shared/common.spec.ts b/frontend/src/app/shared/common.spec.ts index c17d78d0c4..1552603ae9 100644 --- a/frontend/src/app/shared/common.spec.ts +++ b/frontend/src/app/shared/common.spec.ts @@ -10,7 +10,6 @@ import { sanitize, } from './common'; import { FormControl, FormGroup, Validators } from '@angular/forms'; -import { User } from './types/model/User'; import { keyResultMetricMinScoring, keyResultOrdinalMinScoring } from './testData'; import { KeyResultMetricMin } from './types/model/KeyResultMetricMin'; @@ -139,7 +138,7 @@ describe('test common functions', () => { stretchGoal: stretchGoal, lastCheckIn: { ...keyResultOrdinalMinScoring.lastCheckIn, value: value }, } as KeyResultMetricMin; - let percentage = calculateCurrentPercentage(keyResult); + const percentage = calculateCurrentPercentage(keyResult); expect(percentage).toBe(filledPercentage); }, ); @@ -176,7 +175,7 @@ describe('test common functions', () => { ); test('should return correct class', () => { - let testForm = new FormGroup({ + const testForm = new FormGroup({ title: new FormControl(undefined, [ Validators.required, Validators.minLength(2), diff --git a/frontend/src/app/shared/common.ts b/frontend/src/app/shared/common.ts index 57f70b2c0e..7eb6f3a0b8 100644 --- a/frontend/src/app/shared/common.ts +++ b/frontend/src/app/shared/common.ts @@ -39,9 +39,9 @@ export function isLastCheckInNegative(baseline: number, stretchGoal: number, val } export function calculateCurrentPercentage(keyResultMetric: KeyResultMetricMin): number { - let value: number = +keyResultMetric.lastCheckIn?.value!; - let baseline: number = +keyResultMetric.baseline; - let stretchGoal: number = +keyResultMetric.stretchGoal; + const value: number = +keyResultMetric.lastCheckIn?.value!; + const baseline: number = +keyResultMetric.baseline; + const stretchGoal: number = +keyResultMetric.stretchGoal; if (isLastCheckInNegative(baseline, stretchGoal, value)) return 0; if (value == stretchGoal) return 100; diff --git a/frontend/src/app/shared/custom/scoring/scoring.component.spec.ts b/frontend/src/app/shared/custom/scoring/scoring.component.spec.ts index 43f00d5e31..9e3b7b8d06 100644 --- a/frontend/src/app/shared/custom/scoring/scoring.component.spec.ts +++ b/frontend/src/app/shared/custom/scoring/scoring.component.spec.ts @@ -3,7 +3,6 @@ import { ScoringComponent } from './scoring.component'; import { keyResultMetricMinScoring, keyResultOrdinalMinScoring } from '../../testData'; import { Router } from '@angular/router'; import { HttpClientTestingModule } from '@angular/common/http/testing'; -import { By } from '@angular/platform-browser'; import { Zone } from '../../types/enums/Zone'; describe('ScoringComponent', () => { @@ -55,7 +54,7 @@ describe('ScoringComponent', () => { component.commitPercent = object.commit; component.failPercent = object.fail; - let color: string | null = component.getScoringColorClassAndSetBorder(); + const color: string | null = component.getScoringColorClassAndSetBorder(); expect(color).toBe(object.className); }); }); diff --git a/frontend/src/app/shared/custom/scoring/scoring.component.ts b/frontend/src/app/shared/custom/scoring/scoring.component.ts index bdf7bf89f4..5f09b40ca7 100644 --- a/frontend/src/app/shared/custom/scoring/scoring.component.ts +++ b/frontend/src/app/shared/custom/scoring/scoring.component.ts @@ -71,7 +71,7 @@ export class ScoringComponent implements OnInit, AfterViewInit, OnChanges { } // Set color of scoring component - let scoringClass = this.getScoringColorClassAndSetBorder(); + const scoringClass = this.getScoringColorClassAndSetBorder(); if (scoringClass !== null) { this.targetElement!.nativeElement.classList.add(scoringClass); this.commitElement!.nativeElement.classList.add(scoringClass); @@ -110,9 +110,9 @@ export class ScoringComponent implements OnInit, AfterViewInit, OnChanges { calculatePercentageMetric() { if (this.keyResult.lastCheckIn !== null) { - let keyResultMetric: KeyResultMetricMin = this.castToMetric(); + const keyResultMetric: KeyResultMetricMin = this.castToMetric(); - let percentage = calculateCurrentPercentage(keyResultMetric); + const percentage = calculateCurrentPercentage(keyResultMetric); this.labelPercentage = of(percentage); if (percentage < 30) { this.stretched = false; @@ -166,8 +166,8 @@ export class ScoringComponent implements OnInit, AfterViewInit, OnChanges { } removeStyleClass() { - let classArray: string[] = ['score-red', 'score-green', 'score-yellow', 'score-stretch', 'border-right']; - for (let classToRemove of classArray) { + const classArray: string[] = ['score-red', 'score-green', 'score-yellow', 'score-stretch', 'border-right']; + for (const classToRemove of classArray) { this.commitElement?.nativeElement.classList.remove(classToRemove); this.targetElement?.nativeElement.classList.remove(classToRemove); this.failElement?.nativeElement.classList.remove(classToRemove); diff --git a/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.spec.ts b/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.spec.ts index 885b3850f6..d3640ae38f 100644 --- a/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.spec.ts +++ b/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.spec.ts @@ -15,7 +15,7 @@ const dialogMock = { close: jest.fn(), }; -let matDataMock: { objective: { objectiveId: number | undefined; teamId: number | undefined } } = { +const matDataMock: { objective: { objectiveId: number | undefined; teamId: number | undefined } } = { objective: { objectiveId: undefined, teamId: 1, @@ -51,10 +51,10 @@ describe('CompleteDialogComponent', () => { }); it('should set right classes on init', () => { - let elements = document.querySelectorAll('.valuation-card'); - let successful = document.querySelectorAll('.card-hover-successful'); - let notSuccessful = document.querySelectorAll('.card-hover-not-successful'); - let submitButton = debugElement.querySelector('[data-testid="submit"]'); + const elements = document.querySelectorAll('.valuation-card'); + const successful = document.querySelectorAll('.card-hover-successful'); + const notSuccessful = document.querySelectorAll('.card-hover-not-successful'); + const submitButton = debugElement.querySelector('[data-testid="submit"]'); expect(elements.length).toEqual(2); expect(successful.length).toEqual(1); @@ -68,7 +68,7 @@ describe('CompleteDialogComponent', () => { it('should change isSuccessful value on card click and remove class card-hover', () => { component.switchSuccessState('successful'); let elements = document.querySelectorAll('.card-hover'); - let submitButton = debugElement.querySelector('[data-testid="submit"]'); + const submitButton = debugElement.querySelector('[data-testid="submit"]'); expect(component.completeForm.value.isSuccessful).toBeTruthy(); expect(component.completeForm.invalid).toBeFalsy(); diff --git a/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.ts b/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.ts index ab8623bac5..e40ac75ef0 100644 --- a/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.ts +++ b/frontend/src/app/shared/dialog/complete-dialog/complete-dialog.component.ts @@ -44,7 +44,7 @@ export class CompleteDialogComponent { } removeStandardHover() { - let elements = document.querySelectorAll('.card-hover'); + const elements = document.querySelectorAll('.card-hover'); elements.forEach((el) => { el.classList.remove('card-hover'); }); diff --git a/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.spec.ts b/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.spec.ts index 22c02998c8..6631e26824 100644 --- a/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.spec.ts +++ b/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.spec.ts @@ -56,7 +56,7 @@ describe('ConfirmDialogComponent', () => { }); it('should call close method with parameter: true if clicked to submit button', async () => { - let buttons = await loader.getAllHarnesses(MatButtonHarness); + const buttons = await loader.getAllHarnesses(MatButtonHarness); const submitButton = buttons[1]; await submitButton.click(); @@ -64,7 +64,7 @@ describe('ConfirmDialogComponent', () => { }); it('should call close method with parameter: "" if clicked to cancel button', async () => { - let buttons = await loader.getAllHarnesses(MatButtonHarness); + const buttons = await loader.getAllHarnesses(MatButtonHarness); const cancelButton = buttons[0]; await cancelButton.click(); diff --git a/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.ts b/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.ts index dbb86d6cd5..b4dc16ac65 100644 --- a/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.ts +++ b/frontend/src/app/shared/dialog/confirm-dialog/confirm-dialog.component.ts @@ -1,6 +1,5 @@ -import { Component, Inject, InjectionToken, OnInit } from '@angular/core'; -import { MAT_DIALOG_DATA, MatDialogConfig, MatDialogRef } from '@angular/material/dialog'; -import { TranslateService } from '@ngx-translate/core'; +import { Component, Inject, OnInit } from '@angular/core'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { ConfirmDialogData } from '../../../services/dialog.service'; @Component({ diff --git a/frontend/src/app/shared/dialog/example-dialog/example-dialog.component.spec.ts b/frontend/src/app/shared/dialog/example-dialog/example-dialog.component.spec.ts index c70ce01531..f29b121880 100644 --- a/frontend/src/app/shared/dialog/example-dialog/example-dialog.component.spec.ts +++ b/frontend/src/app/shared/dialog/example-dialog/example-dialog.component.spec.ts @@ -22,7 +22,7 @@ describe('ExampleDialogComponent', () => { let fixture: ComponentFixture; let loader: HarnessLoader; - let errors = errorData; + const errors = errorData; beforeEach(() => { TestBed.configureTestingModule({ @@ -146,7 +146,7 @@ describe('ExampleDialogComponent', () => { const radioButtons = loader.getAllHarnesses(MatRadioButtonHarness); //Verify that the submit button is disabled because the radio button is not checked yet - let submitButton = fixture.debugElement.query(By.css('[data-testId="submit"]')); + const submitButton = fixture.debugElement.query(By.css('[data-testId="submit"]')); expect(submitButton.nativeElement.disabled).toBeTruthy(); await Promise.all([nameInput, matSelect, radioButtons]).then( diff --git a/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.spec.ts b/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.spec.ts index 8e683e9a4e..53ce1b2ada 100644 --- a/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.spec.ts +++ b/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.spec.ts @@ -23,7 +23,7 @@ import { By } from '@angular/platform-browser'; import { MatCheckboxHarness } from '@angular/material/checkbox/testing'; import { RouterTestingHarness } from '@angular/router/testing'; import { TranslateTestingModule } from 'ngx-translate-testing'; -// @ts-ignore +// @ts-expect-error import * as de from '../../../../assets/i18n/de.json'; import { ActivatedRoute, provideRouter } from '@angular/router'; import { provideHttpClient } from '@angular/common/http'; @@ -31,7 +31,7 @@ import { provideHttpClientTesting } from '@angular/common/http/testing'; import { DialogTemplateCoreComponent } from '../../custom/dialog-template-core/dialog-template-core.component'; import { MatDividerModule } from '@angular/material/divider'; -let objectiveService = { +const objectiveService = { getFullObjective: jest.fn(), createObjective: jest.fn(), updateObjective: jest.fn(), @@ -68,7 +68,7 @@ const dialogMock = { close: jest.fn(), }; -let matDataMock: MatDialogDataInterface = { +const matDataMock: MatDialogDataInterface = { objective: { objectiveId: undefined, teamId: 1, @@ -131,9 +131,9 @@ describe('ObjectiveDialogComponent', () => { 'onSubmit create', fakeAsync((state: string) => { //Prepare data - let title: string = 'title'; - let description: string = 'description'; - let createKeyresults: boolean = true; + const title: string = 'title'; + const description: string = 'description'; + const createKeyresults: boolean = true; let quarter: number = 0; let team: number = 0; teamService.getAllTeams().subscribe((teams) => { @@ -308,9 +308,9 @@ describe('ObjectiveDialogComponent', () => { }); it('should return if option is allowed for quarter select', async () => { - let quarter: Quarter = new Quarter(1, 'Backlog', null, null); + const quarter: Quarter = new Quarter(1, 'Backlog', null, null); - let data = { + const data = { action: 'duplicate', objective: { objectiveId: 22, diff --git a/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.ts b/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.ts index 8bb93a22bd..adac559295 100644 --- a/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.ts +++ b/frontend/src/app/shared/dialog/objective-dialog/objective-form.component.ts @@ -10,8 +10,7 @@ import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { State } from '../../types/enums/State'; import { ObjectiveMin } from '../../types/model/ObjectiveMin'; import { Objective } from '../../types/model/Objective'; -import { ConfirmDialogComponent } from '../confirm-dialog/confirm-dialog.component'; -import { formInputCheck, getValueFromQuery, hasFormFieldErrors, isMobileDevice } from '../../common'; +import { formInputCheck, getValueFromQuery, hasFormFieldErrors } from '../../common'; import { ActivatedRoute } from '@angular/router'; import { GJ_REGEX_PATTERN } from '../../constantLibary'; import { TranslateService } from '@ngx-translate/core'; @@ -64,7 +63,7 @@ export class ObjectiveFormComponent implements OnInit, OnDestroy { onSubmit(submitType: any): void { const value = this.objectiveForm.getRawValue(); const state = this.data.objective.objectiveId == null ? submitType : this.state; - let objectiveDTO: Objective = { + const objectiveDTO: Objective = { id: this.data.objective.objectiveId, version: this.version, quarterId: value.quarter, @@ -137,7 +136,7 @@ export class ObjectiveFormComponent implements OnInit, OnDestroy { if (result) { this.objectiveService.deleteObjective(this.data.objective.objectiveId!).subscribe({ next: () => { - let objectiveDTO: Objective = { id: this.data.objective.objectiveId! } as unknown as Objective; + const objectiveDTO: Objective = { id: this.data.objective.objectiveId! } as unknown as Objective; this.closeDialog(objectiveDTO, true); }, error: () => { @@ -182,11 +181,11 @@ export class ObjectiveFormComponent implements OnInit, OnDestroy { } allowedToSaveBacklog() { - let currentQuarter: Quarter | undefined = this.quarters.find( + const currentQuarter: Quarter | undefined = this.quarters.find( (quarter) => quarter.id == this.objectiveForm.value.quarter, ); if (currentQuarter) { - let isBacklogCurrent: boolean = !this.isBacklogQuarter(currentQuarter.label); + const isBacklogCurrent: boolean = !this.isBacklogQuarter(currentQuarter.label); if (this.data.action == 'duplicate') return true; if (this.data.objective.objectiveId) { return isBacklogCurrent ? this.state == 'DRAFT' : true; diff --git a/frontend/src/app/shared/pipes/unit-value-transformation/unit-value-transformation.pipe.ts b/frontend/src/app/shared/pipes/unit-value-transformation/unit-value-transformation.pipe.ts index ca8d95c7f9..858557c515 100644 --- a/frontend/src/app/shared/pipes/unit-value-transformation/unit-value-transformation.pipe.ts +++ b/frontend/src/app/shared/pipes/unit-value-transformation/unit-value-transformation.pipe.ts @@ -1,5 +1,4 @@ import { Pipe, PipeTransform } from '@angular/core'; -import { Unit } from '../../types/enums/Unit'; @Pipe({ name: 'unitValueTransformation', diff --git a/frontend/src/app/shared/testData.ts b/frontend/src/app/shared/testData.ts index 48ba98a0de..57ee020302 100644 --- a/frontend/src/app/shared/testData.ts +++ b/frontend/src/app/shared/testData.ts @@ -228,41 +228,41 @@ export const objectiveMin: ObjectiveMin = { keyResults: [keyResultMetricMin, keyResultOrdinalMin] as KeyresultMin[], } as ObjectiveMin; -export const objectiveResponse1: any = { +export const objectiveResponse1: ObjectiveMin = { id: 101, version: 1, title: 'Increase Environment Engagement', state: 'ONGOING', quarter: quarterMin, keyResults: [keyResultMetricMin, keyResultOrdinalMin] as KeyresultMin[], -}; +} as ObjectiveMin; -export const objectiveResponse2: any = { +export const objectiveResponse2: ObjectiveMin = { id: 102, version: 1, title: 'Increase Social Engagement', state: 'DRAFT', quarter: quarterMin, keyResults: [keyResultMetricMin, keyResultOrdinalMin] as KeyresultMin[], -}; +} as ObjectiveMin; -export const objectiveResponse3: any = { +export const objectiveResponse3: ObjectiveMin = { id: 103, version: 1, title: 'Increase Member Engagement', state: 'NOTSUCCESSFUL', quarter: quarterMin, keyResults: [keyResultMetricMin, keyResultOrdinalMin] as KeyresultMin[], -}; +} as ObjectiveMin; -export const objectiveResponse4: any = { +export const objectiveResponse4: ObjectiveMin = { id: 104, version: 1, title: 'Increase Company Engagement', state: 'SUCCESSFUL', quarter: quarterMin, keyResults: [keyResultMetricMin, keyResultOrdinalMin] as KeyresultMin[], -}; +} as ObjectiveMin; export const overViewEntity1: OverviewEntity = { team: marketingTeamWriteable, @@ -276,16 +276,16 @@ export const overViewEntity2: OverviewEntity = { writeable: true, }; -export const overViewEntityResponse1: any = { +export const overViewEntityResponse1: OverviewEntity = { team: team1, objectives: [objectiveResponse1, objectiveResponse2], - writable: true, + writeable: true, }; -export const overViewEntityResponse2: any = { +export const overViewEntityResponse2: OverviewEntity = { team: team2, objectives: [objectiveResponse3, objectiveResponse4], - writable: false, + writeable: false, }; export const overviews: OverviewEntity[] = [overViewEntityResponse1, overViewEntityResponse2]; diff --git a/frontend/src/app/shared/types/menu-entry.ts b/frontend/src/app/shared/types/menu-entry.ts deleted file mode 100644 index 83339960c9..0000000000 --- a/frontend/src/app/shared/types/menu-entry.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ComponentType } from '@angular/cdk/overlay'; - -export interface MenuEntry { - displayName: string; - dialog?: { - dialog: ComponentType; - data: any; - }; - route?: string; - action?: string; -} diff --git a/frontend/src/app/shared/validators.ts b/frontend/src/app/shared/validators.ts index dbfbc6c0f4..b5a163f10d 100644 --- a/frontend/src/app/shared/validators.ts +++ b/frontend/src/app/shared/validators.ts @@ -16,7 +16,7 @@ export class UnitValueValidator implements Validator { @Input('unitValueValidator') unit: string | null = ''; validate(control: AbstractControl): ValidationErrors | null { - let value: string = control.value; + const value: string = control.value; switch (this.unit) { case 'PERCENT': { return this.proceedRegex(value, PERCENT_REGEX); diff --git a/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.spec.ts b/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.spec.ts index 767eb28010..3920d2d549 100644 --- a/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.spec.ts +++ b/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.spec.ts @@ -1,6 +1,5 @@ import { AddEditTeamDialog } from './add-edit-team-dialog.component'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { HarnessLoader } from '@angular/cdk/testing'; import { provideHttpClientTesting } from '@angular/common/http/testing'; import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; @@ -10,7 +9,6 @@ import { ReactiveFormsModule } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { MatCheckboxModule } from '@angular/material/checkbox'; -import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TeamService } from '../../services/team.service'; import { of } from 'rxjs'; import { marketingTeamWriteable, teamFormObject } from '../../shared/testData'; @@ -39,7 +37,6 @@ const teamServiceMock = { describe('TeamManagementComponent', () => { let component: AddEditTeamDialog; let fixture: ComponentFixture; - let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ @@ -81,7 +78,6 @@ describe('TeamManagementComponent', () => { fixture = TestBed.createComponent(AddEditTeamDialog); component = fixture.componentInstance; fixture.detectChanges(); - loader = TestbedHarnessEnvironment.loader(fixture); }); it('should create', () => { diff --git a/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.ts b/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.ts index 98aa5de9f0..a6337bfd0e 100644 --- a/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.ts +++ b/frontend/src/app/team-management/add-edit-team-dialog/add-edit-team-dialog.component.ts @@ -51,7 +51,7 @@ export class AddEditTeamDialog implements OnInit { } private createNewTeam() { - let newTeam: Team = this.teamForm.value as Team; + const newTeam: Team = this.teamForm.value as Team; this.teamService.createTeam(newTeam).subscribe((result) => { this.userService.reloadUsers(); this.userService.reloadCurrentUser().subscribe(); @@ -61,7 +61,7 @@ export class AddEditTeamDialog implements OnInit { } private updateTeam() { - let updatedTeam: Team = { + const updatedTeam: Team = { ...this.teamForm.value, id: this.data!.team.id, version: this.data!.team.version, diff --git a/frontend/src/app/team-management/add-user-team/add-user-team.component.spec.ts b/frontend/src/app/team-management/add-user-team/add-user-team.component.spec.ts index 3fd1a309fb..c0c2a67c29 100644 --- a/frontend/src/app/team-management/add-user-team/add-user-team.component.spec.ts +++ b/frontend/src/app/team-management/add-user-team/add-user-team.component.spec.ts @@ -7,7 +7,6 @@ import { of } from 'rxjs'; describe('AddUserTeamComponent', () => { let component: AddUserTeamComponent; let fixture: ComponentFixture; - let teamService: TeamService; const team1Copy = { ...team1 }; const team2Copy = { ...team2 }; @@ -27,7 +26,6 @@ describe('AddUserTeamComponent', () => { beforeEach(() => { fixture = TestBed.createComponent(AddUserTeamComponent); component = fixture.componentInstance; - teamService = TestBed.inject(TeamService); teamServiceMock.getAllTeams.mockReturnValue(of([team1Copy, team2Copy, team3Copy])); component.currentTeams$ = of(testUser.userTeamList); diff --git a/frontend/src/app/team-management/member-list/member-list-table/member-list-table.component.ts b/frontend/src/app/team-management/member-list/member-list-table/member-list-table.component.ts index 1c1f587343..fa6c0f42d3 100644 --- a/frontend/src/app/team-management/member-list/member-list-table/member-list-table.component.ts +++ b/frontend/src/app/team-management/member-list/member-list-table/member-list-table.component.ts @@ -1,7 +1,7 @@ import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; import { UserTableEntry } from '../../../shared/types/model/UserTableEntry'; -import { getFullNameFromUser, User } from '../../../shared/types/model/User'; +import { User } from '../../../shared/types/model/User'; import { Team } from '../../../shared/types/model/Team'; import { TeamService } from '../../../services/team.service'; import { UserService } from '../../../services/user.service'; @@ -33,7 +33,8 @@ export class MemberListTableComponent implements OnInit, OnDestroy { ngOnInit() { this.selectedTeam$.pipe(takeUntil(this.unsubscribe$)).subscribe((team) => { - team ? this.setColumnForTeam(team) : this.setColumnsForAllTeams(); + if (team) this.setColumnForTeam(team) + else this.setColumnsForAllTeams(); }); } diff --git a/frontend/src/app/team-management/member-list/member-list.component.spec.ts b/frontend/src/app/team-management/member-list/member-list.component.spec.ts index b54e9ee180..f330ac8b46 100644 --- a/frontend/src/app/team-management/member-list/member-list.component.spec.ts +++ b/frontend/src/app/team-management/member-list/member-list.component.spec.ts @@ -149,7 +149,7 @@ describe('MemberListComponent', () => { }, ); - let userTableEntries = convertFromUsers(usersCopy, null); + const userTableEntries = convertFromUsers(usersCopy, null); expect(userTableEntries.length).toBe(4); // test that it makes a deep copy expect(userTableEntries).not.toBe(usersCopy); diff --git a/frontend/src/app/team-management/new-user/new-user.component.ts b/frontend/src/app/team-management/new-user/new-user.component.ts index 2ef11f8b3c..e4bd59c3bf 100644 --- a/frontend/src/app/team-management/new-user/new-user.component.ts +++ b/frontend/src/app/team-management/new-user/new-user.component.ts @@ -1,7 +1,7 @@ import { AfterViewInit, ChangeDetectionStrategy, - Component, + Component, ElementRef, EventEmitter, Input, Output, @@ -30,7 +30,7 @@ export class NewUserComponent implements AfterViewInit { @Output() removeUser: EventEmitter = new EventEmitter(); - @ViewChild('firstInput') firstInput: any; + @ViewChild('firstInput') firstInput: ElementRef; ngAfterViewInit(): void { this.firstInput.nativeElement.focus(); diff --git a/frontend/src/app/team-management/search-team-management/search-team-management.component.spec.ts b/frontend/src/app/team-management/search-team-management/search-team-management.component.spec.ts index aaa1f893e4..853bd5180f 100644 --- a/frontend/src/app/team-management/search-team-management/search-team-management.component.spec.ts +++ b/frontend/src/app/team-management/search-team-management/search-team-management.component.spec.ts @@ -152,8 +152,8 @@ describe('SearchTeamManagementComponent', () => { fixture.detectChanges(); jest.advanceTimersByTime(250); - let filteredUsers = component.filteredUsers$.getValue(); - let filteredTeams = component.filteredTeams$.getValue(); + const filteredUsers = component.filteredUsers$.getValue(); + const filteredTeams = component.filteredTeams$.getValue(); expect(filteredUsers.map(getDisplayValues)).toEqual([ 'Pete Parrot (parrot@puzzle.ch)', 'Martin Käser (kaeser@puzzle.ch)', @@ -171,8 +171,8 @@ describe('SearchTeamManagementComponent', () => { fixture.detectChanges(); jest.advanceTimersByTime(250); - let filteredUsers = component.filteredUsers$.getValue(); - let filteredTeams = component.filteredTeams$.getValue(); + const filteredUsers = component.filteredUsers$.getValue(); + const filteredTeams = component.filteredTeams$.getValue(); expect(filteredUsers.map(getHTMLValues)).toEqual(['Ruedi Peters (rpeter@gmail.com)']); diff --git a/frontend/src/app/team-management/team-list/team-list.component.spec.ts b/frontend/src/app/team-management/team-list/team-list.component.spec.ts index b547fe18c8..78d9fd05c1 100644 --- a/frontend/src/app/team-management/team-list/team-list.component.spec.ts +++ b/frontend/src/app/team-management/team-list/team-list.component.spec.ts @@ -7,8 +7,6 @@ import { TeamListComponent } from './team-list.component'; describe('TeamListComponent', () => { let component: TeamListComponent; let fixture: ComponentFixture; - let teamService: TeamService; - let route: ActivatedRoute; const paramTeamId = 1; const teamServiceMock = { @@ -34,8 +32,6 @@ describe('TeamListComponent', () => { beforeEach(() => { fixture = TestBed.createComponent(TeamListComponent); component = fixture.componentInstance; - teamService = TestBed.inject(TeamService); - route = TestBed.inject(ActivatedRoute); fixture.detectChanges(); }); diff --git a/frontend/src/app/team-management/team-management-mobile-filter/team-management-mobile-filter.component.ts b/frontend/src/app/team-management/team-management-mobile-filter/team-management-mobile-filter.component.ts index 18d346bd45..1f7521bc34 100644 --- a/frontend/src/app/team-management/team-management-mobile-filter/team-management-mobile-filter.component.ts +++ b/frontend/src/app/team-management/team-management-mobile-filter/team-management-mobile-filter.component.ts @@ -27,7 +27,8 @@ export class TeamManagementMobileFilterComponent { } navigate(team: Team | 'alle') { - team == this.ALL_TEAMS ? this.navigateToAllTeams() : this.navigateToTeam(team); + if (team == this.ALL_TEAMS) this.navigateToAllTeams() + else this.navigateToTeam(team); } private navigateToTeam(team: Team) { diff --git a/frontend/src/global.ts b/frontend/src/global.ts index a9a8df6207..11709a5916 100644 --- a/frontend/src/global.ts +++ b/frontend/src/global.ts @@ -5,9 +5,9 @@ declare global { } } -String.prototype.format = function () { - const args = Array.from(arguments).flat(); +String.prototype.format = function (...args) { + const allArgs = Array.from(args).flat(); return this.replace(/{(\d+)}/g, function (match, index) { - return typeof args[index] == 'undefined' ? match : args[index]; + return typeof allArgs[index] == 'undefined' ? match : allArgs[index]; }); };