From d934f6dccc109ec5ad593a464b07d4071abd39b4 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 15 Sep 2023 11:42:20 +0300 Subject: [PATCH 01/51] Added ACHIEVEMENTS category --- .../enums/AchievementsCalculationEnum.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java diff --git a/service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java b/service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java new file mode 100644 index 0000000000..e0928bb21b --- /dev/null +++ b/service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java @@ -0,0 +1,78 @@ +package greencity.enums; + +import lombok.Getter; + +@Getter +public enum AchievementsCalculationEnum { + // Habit Achievements + ACQUIRED_HABIT_14_DAYS(20), + ACQUIRED_HABIT_21_DAYS(30), + ACQUIRED_HABIT_30_DAYS(40), + UNDO_ACQUIRED_HABIT_14_DAYS(-20), + UNDO_ACQUIRED_HABIT_21_DAYS(-30), + UNDO_ACQUIRED_HABIT_30_DAYS(-40), + + // News Creation Achievements + CREATED_5_NEWS(5), + CREATED_10_NEWS(10), + CREATED_25_NEWS(25), + CREATED_50_NEWS(50), + CREATED_100_NEWS(100), + DELETE_5_NEWS(-5), + DELETE_10_NEWS(-10), + DELETE_25_NEWS(-25), + DELETE_50_NEWS(-50), + DELETE_100_NEWS(-100), + + // Comment or Reply Achievements + COMMENT_OR_REPLY_5_TIMES(10), + COMMENT_OR_REPLY_10_TIMES(20), + COMMENT_OR_REPLY_25_TIMES(50), + COMMENT_OR_REPLY_50_TIMES(100), + COMMENT_OR_REPLY_100_TIMES(200), + DELETE_COMMENT_OR_REPLY_5_TIMES(-10), + DELETE_COMMENT_OR_REPLY_10_TIMES(-20), + DELETE_COMMENT_OR_REPLY_25_TIMES(-50), + DELETE_COMMENT_OR_REPLY_50_TIMES(-100), + DELETE_COMMENT_OR_REPLY_100_TIMES(-200), + + // Like Achievements + LIKE_COMMENT_OR_REPLY_1_TIMES(10), + LIKE_COMMENT_OR_REPLY_5_TIMES(20), + LIKE_COMMENT_OR_REPLY_10_TIMES(30), + LIKE_COMMENT_OR_REPLY_25_TIMES(40), + LIKE_COMMENT_OR_REPLY_50_TIMES(50), + LIKE_COMMENT_OR_REPLY_100_TIMES(60), + UNLIKE_COMMENT_OR_REPLY_1_TIMES(-10), + UNLIKE_COMMENT_OR_REPLY_5_TIMES(-20), + UNLIKE_COMMENT_OR_REPLY_10_TIMES(-30), + UNLIKE_COMMENT_OR_REPLY_25_TIMES(-40), + UNLIKE_COMMENT_OR_REPLY_50_TIMES(-50), + UNLIKE_COMMENT_OR_REPLY_100_TIMES(-60), + + // Share Achievements + SHARE_NEWS_1_TIMES(20), + SHARE_NEWS_5_TIMES(40), + SHARE_NEWS_10_TIMES(60), + SHARE_NEWS_25_TIMES(80), + SHARE_NEWS_50_TIMES(100), + SHARE_NEWS_100_TIMES(120), + UNDO_SHARE_NEWS_1_TIMES(-20), + UNDO_SHARE_NEWS_5_TIMES(-40), + UNDO_SHARE_NEWS_10_TIMES(-60), + UNDO_SHARE_NEWS_25_TIMES(-80), + UNDO_SHARE_NEWS_50_TIMES(-100), + UNDO_SHARE_NEWS_100_TIMES(-120), + + // First Achievements + FIRST_5_ACHIEVEMENTS(20), + FIRST_10_ACHIEVEMENTS(40), + FIRST_15_ACHIEVEMENTS(60), + FIRST_20_ACHIEVEMENTS(80); + + private final long ratingPoints; + + AchievementsCalculationEnum(long ratingPoints) { + this.ratingPoints = ratingPoints; + } +} From c75ee8a34935143b5f295f8dfb18ee3880b80fed Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 15 Sep 2023 15:21:19 +0300 Subject: [PATCH 02/51] Changed naming of category type --- .../controller/AchievementControllerTest.java | 4 +- .../db/changelog/db.changelog-master.xml | 1 + ...values-achievement_categories-Spodaryk.xml | 45 +++++++++++ .../enums/AchievementCategoryType.java | 19 ++--- .../enums/AchievementsCalculationEnum.java | 78 ------------------- .../achievement/AchievementCalculation.java | 4 +- .../service/EcoNewsCommentServiceImpl.java | 2 +- .../greencity/service/EcoNewsServiceImpl.java | 6 +- .../service/HabitAssignServiceImpl.java | 4 +- .../AchievementCalculationTest.java | 6 +- .../service/AchievementServiceImplTest.java | 2 +- 11 files changed, 66 insertions(+), 105 deletions(-) create mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml delete mode 100644 service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java diff --git a/core/src/test/java/greencity/controller/AchievementControllerTest.java b/core/src/test/java/greencity/controller/AchievementControllerTest.java index 1f85607936..a44204c850 100644 --- a/core/src/test/java/greencity/controller/AchievementControllerTest.java +++ b/core/src/test/java/greencity/controller/AchievementControllerTest.java @@ -50,10 +50,10 @@ void calculateAchievements() throws Exception { mockMvc.perform(post(achievementLink + "/calculate-achievement" + "?id=" + 1L + "&setter=" + AchievementType.INCREMENT - + "&socialNetwork=" + AchievementCategoryType.ECO_NEWS + + "&socialNetwork=" + AchievementCategoryType.CREATE_NEWS + "&size=" + 1)).andExpect(status().isOk()); verify(achievementService).calculateAchievements(1L, AchievementType.INCREMENT, - AchievementCategoryType.ECO_NEWS, 1); + AchievementCategoryType.CREATE_NEWS, 1); } @Test diff --git a/dao/src/main/resources/db/changelog/db.changelog-master.xml b/dao/src/main/resources/db/changelog/db.changelog-master.xml index e4f4945917..7d8a23118d 100644 --- a/dao/src/main/resources/db/changelog/db.changelog-master.xml +++ b/dao/src/main/resources/db/changelog/db.changelog-master.xml @@ -172,5 +172,6 @@ + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml new file mode 100644 index 0000000000..3895f38215 --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/service-api/src/main/java/greencity/enums/AchievementCategoryType.java b/service-api/src/main/java/greencity/enums/AchievementCategoryType.java index a57a02a364..bc5a5a5bc0 100644 --- a/service-api/src/main/java/greencity/enums/AchievementCategoryType.java +++ b/service-api/src/main/java/greencity/enums/AchievementCategoryType.java @@ -4,17 +4,10 @@ @Getter public enum AchievementCategoryType { - ECO_NEWS("EcoNews"), - ECO_NEWS_COMMENT("EcoNewsComments"), - ECO_NEWS_LIKE("EcoNewsLikes"), - ACHIEVEMENTS("Achievements"), - HABIT_STREAK("HabitStreak"), - ACQUIRED_HABIT("AcquiredHabits"), - SOCIAL_NETWORK("SocialNetworks"); - - private final String category; - - AchievementCategoryType(String category) { - this.category = category; - } + CREATE_NEWS, + COMMENT_OR_REPLY, + LIKE_COMMENT_OR_REPLY, + SHARE_NEWS, + HABIT, + ACHIEVEMENT } diff --git a/service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java b/service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java deleted file mode 100644 index e0928bb21b..0000000000 --- a/service-api/src/main/java/greencity/enums/AchievementsCalculationEnum.java +++ /dev/null @@ -1,78 +0,0 @@ -package greencity.enums; - -import lombok.Getter; - -@Getter -public enum AchievementsCalculationEnum { - // Habit Achievements - ACQUIRED_HABIT_14_DAYS(20), - ACQUIRED_HABIT_21_DAYS(30), - ACQUIRED_HABIT_30_DAYS(40), - UNDO_ACQUIRED_HABIT_14_DAYS(-20), - UNDO_ACQUIRED_HABIT_21_DAYS(-30), - UNDO_ACQUIRED_HABIT_30_DAYS(-40), - - // News Creation Achievements - CREATED_5_NEWS(5), - CREATED_10_NEWS(10), - CREATED_25_NEWS(25), - CREATED_50_NEWS(50), - CREATED_100_NEWS(100), - DELETE_5_NEWS(-5), - DELETE_10_NEWS(-10), - DELETE_25_NEWS(-25), - DELETE_50_NEWS(-50), - DELETE_100_NEWS(-100), - - // Comment or Reply Achievements - COMMENT_OR_REPLY_5_TIMES(10), - COMMENT_OR_REPLY_10_TIMES(20), - COMMENT_OR_REPLY_25_TIMES(50), - COMMENT_OR_REPLY_50_TIMES(100), - COMMENT_OR_REPLY_100_TIMES(200), - DELETE_COMMENT_OR_REPLY_5_TIMES(-10), - DELETE_COMMENT_OR_REPLY_10_TIMES(-20), - DELETE_COMMENT_OR_REPLY_25_TIMES(-50), - DELETE_COMMENT_OR_REPLY_50_TIMES(-100), - DELETE_COMMENT_OR_REPLY_100_TIMES(-200), - - // Like Achievements - LIKE_COMMENT_OR_REPLY_1_TIMES(10), - LIKE_COMMENT_OR_REPLY_5_TIMES(20), - LIKE_COMMENT_OR_REPLY_10_TIMES(30), - LIKE_COMMENT_OR_REPLY_25_TIMES(40), - LIKE_COMMENT_OR_REPLY_50_TIMES(50), - LIKE_COMMENT_OR_REPLY_100_TIMES(60), - UNLIKE_COMMENT_OR_REPLY_1_TIMES(-10), - UNLIKE_COMMENT_OR_REPLY_5_TIMES(-20), - UNLIKE_COMMENT_OR_REPLY_10_TIMES(-30), - UNLIKE_COMMENT_OR_REPLY_25_TIMES(-40), - UNLIKE_COMMENT_OR_REPLY_50_TIMES(-50), - UNLIKE_COMMENT_OR_REPLY_100_TIMES(-60), - - // Share Achievements - SHARE_NEWS_1_TIMES(20), - SHARE_NEWS_5_TIMES(40), - SHARE_NEWS_10_TIMES(60), - SHARE_NEWS_25_TIMES(80), - SHARE_NEWS_50_TIMES(100), - SHARE_NEWS_100_TIMES(120), - UNDO_SHARE_NEWS_1_TIMES(-20), - UNDO_SHARE_NEWS_5_TIMES(-40), - UNDO_SHARE_NEWS_10_TIMES(-60), - UNDO_SHARE_NEWS_25_TIMES(-80), - UNDO_SHARE_NEWS_50_TIMES(-100), - UNDO_SHARE_NEWS_100_TIMES(-120), - - // First Achievements - FIRST_5_ACHIEVEMENTS(20), - FIRST_10_ACHIEVEMENTS(40), - FIRST_15_ACHIEVEMENTS(60), - FIRST_20_ACHIEVEMENTS(80); - - private final long ratingPoints; - - AchievementsCalculationEnum(long ratingPoints) { - this.ratingPoints = ratingPoints; - } -} diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index df141f9de5..afa308d9d7 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -65,7 +65,7 @@ public AchievementCalculation(RestClient restClient, */ public void calculateAchievement(Long userId, AchievementType type, AchievementCategoryType category, Integer count) { - AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.getCategory()); + AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategoryVO.getId()); count = checkType(type, userActionVO, count); @@ -104,7 +104,7 @@ private void changeAchievementStatus(User user, AchievementVO achievementVO) { UserAchievement achievement = userAchievement.get(); achievement.setAchievementStatus(ACTIVE); userAchievementRepo.save(achievement); - calculateAchievement(user.getId(), INCREMENT, AchievementCategoryType.ACHIEVEMENTS, 0); + calculateAchievement(user.getId(), INCREMENT, AchievementCategoryType.ACHIEVEMENT, 0); } } diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index cec2b20510..74cb66e6f0 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -81,7 +81,7 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq } CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(userVO.getId(), AchievementType.INCREMENT, - AchievementCategoryType.ECO_NEWS_COMMENT, 0)); + AchievementCategoryType.COMMENT_OR_REPLY, 0)); String accessToken = httpServletRequest.getHeader(AUTHORIZATION); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.ADD_COMMENT, userVO, accessToken)); diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 582cb812d9..5e1b276cff 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -82,7 +82,7 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(toSave.getAuthor().getId(), AchievementType.INCREMENT, - AchievementCategoryType.ECO_NEWS, 0)); + AchievementCategoryType.CREATE_NEWS, 0)); return addEcoNewsDtoResponse; } @@ -100,7 +100,7 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, sendEmailDto(ecoNewsDto, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(toSave.getAuthor().getId(), AchievementType.INCREMENT, - AchievementCategoryType.ECO_NEWS, 0)); + AchievementCategoryType.CREATE_NEWS, 0)); return ecoNewsDto; } @@ -428,7 +428,7 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { CompletableFuture .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT, user, accessToken)); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementType.INCREMENT, AchievementCategoryType.ECO_NEWS_LIKE, 0)); + .calculateAchievement(user.getId(), AchievementType.INCREMENT, AchievementCategoryType.LIKE_COMMENT_OR_REPLY, 0)); } /** diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index a5255e4b1a..da05760062 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -748,12 +748,12 @@ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, habitAssign.setHabitStreak(habitStreak); CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(userId, AchievementType.COMPARISON, - AchievementCategoryType.HABIT_STREAK, habitStreak)); + AchievementCategoryType.HABIT, habitStreak)); if (isHabitAcquired(habitAssign)) { habitAssign.setStatus(HabitAssignStatus.ACQUIRED); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(userId, AchievementType.INCREMENT, AchievementCategoryType.HABIT_STREAK, 0)); + .calculateAchievement(userId, AchievementType.INCREMENT, AchievementCategoryType.HABIT, 0)); } habitAssignRepo.save(habitAssign); } diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index afae38437d..d8479f85e6 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -56,7 +56,7 @@ void calculateAchievement(AchievementType type) { AchievementVO achievementVO = ModelUtils.getAchievementVO(); UserAchievement userAchievement = ModelUtils.getUserAchievement(); user.setUserAchievements(Collections.singletonList(userAchievement)); - when(achievementCategoryService.findByName(AchievementCategoryType.ECO_NEWS.getCategory())) + when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) .thenReturn(achievementCategoryVO); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)).thenReturn(userActionVO); when(userActionService.updateUserActions(userActionVO)).thenReturn(userActionVO); @@ -64,9 +64,9 @@ void calculateAchievement(AchievementType type) { when(achievementService.findByCategoryIdAndCondition(1L, 1)).thenReturn(achievementVO); when(modelMapper.map(userVOAchievement, User.class)).thenReturn(user); when(userAchievementRepo.save(userAchievement)).thenReturn(userAchievement); - when(achievementCategoryService.findByName("Achievements")).thenReturn(achievementCategoryVO2); + when(achievementCategoryService.findByName("ACHIEVEMENT")).thenReturn(achievementCategoryVO2); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 2L)).thenReturn(userActionVO2); - achievementCalculation.calculateAchievement(1L, type, AchievementCategoryType.ECO_NEWS, 1); + achievementCalculation.calculateAchievement(1L, type, AchievementCategoryType.CREATE_NEWS, 1); verify(userAchievementRepo).save(userAchievement); } } diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index d83a6d8c8c..5364c9108c 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -249,7 +249,7 @@ void findAchievementsWithStatusActive() { @Test void calculateAchievement() { - achievementService.calculateAchievements(1L, AchievementType.INCREMENT, AchievementCategoryType.ECO_NEWS, 1); + achievementService.calculateAchievements(1L, AchievementType.INCREMENT, AchievementCategoryType. CREATE_NEWS, 1); verify(achievementCalculation).calculateAchievement( anyLong(), any(AchievementType.class), From 92894bdc75c849a549698710b616edeaf13895f8 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 15 Sep 2023 15:53:35 +0300 Subject: [PATCH 03/51] Added values for achievements --- .../db/changelog/db.changelog-master.xml | 6 +- .../ch-add-column-achievements-Spodaryk.xml | 26 ++ .../ch-add-value-achievements-Spodaryk.xml | 222 ++++++++++++++++++ ...values-achievement_categories-Spodaryk.xml | 2 +- .../ch-drop-column-achievement-Spodaryk.xml | 11 + 5 files changed, 265 insertions(+), 2 deletions(-) create mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml create mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml create mode 100644 dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml diff --git a/dao/src/main/resources/db/changelog/db.changelog-master.xml b/dao/src/main/resources/db/changelog/db.changelog-master.xml index 7d8a23118d..d03d23d8f7 100644 --- a/dao/src/main/resources/db/changelog/db.changelog-master.xml +++ b/dao/src/main/resources/db/changelog/db.changelog-master.xml @@ -172,6 +172,10 @@ - + + + + + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml new file mode 100644 index 0000000000..a9a35edc07 --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml new file mode 100644 index 0000000000..23d0ceabf9 --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml @@ -0,0 +1,222 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml index 3895f38215..46c0fb2972 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> - + diff --git a/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml new file mode 100644 index 0000000000..495b9c2350 --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml @@ -0,0 +1,11 @@ + + + + + + + + + From 79ee1068029c5567397521e182ac52fec931c21e Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 18 Sep 2023 11:08:45 +0300 Subject: [PATCH 04/51] added code to reorganise achievements structure --- .../ch-add-value-achievements-Spodaryk.xml | 215 +----------------- .../functions/insert-values-achievements.sql | 68 ++++++ 2 files changed, 69 insertions(+), 214 deletions(-) create mode 100644 dao/src/main/resources/db/functions/insert-values-achievements.sql diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml index 23d0ceabf9..51b0274543 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml @@ -3,220 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/dao/src/main/resources/db/functions/insert-values-achievements.sql b/dao/src/main/resources/db/functions/insert-values-achievements.sql new file mode 100644 index 0000000000..60ec286e41 --- /dev/null +++ b/dao/src/main/resources/db/functions/insert-values-achievements.sql @@ -0,0 +1,68 @@ +DO $$ +DECLARE +habit_id INTEGER; + create_news_id INTEGER; + comment_or_reply_id INTEGER; + like_comment_or_reply_id INTEGER; + share_news_id INTEGER; + achievement_id INTEGER; +BEGIN + -- Acquire IDs from achievement_categories +SELECT id INTO habit_id FROM achievement_categories WHERE name = 'HABIT'; +SELECT id INTO create_news_id FROM achievement_categories WHERE name = 'CREATE_NEWS'; +SELECT id INTO comment_or_reply_id FROM achievement_categories WHERE name = 'COMMENT_OR_REPLY'; +SELECT id INTO like_comment_or_reply_id FROM achievement_categories WHERE name = 'LIKE_COMMENT_OR_REPLY'; +SELECT id INTO share_news_id FROM achievement_categories WHERE name = 'SHARE_NEWS'; +SELECT id INTO achievement_id FROM achievement_categories WHERE name = 'ACHIEVEMENT'; + +-- Insert statements for each category +INSERT INTO achievements(name, achievement_category_id, score) +VALUES + ('ACQUIRED_HABIT_14_DAYS', habit_id, 10), + ('ACQUIRED_HABIT_21_DAYS', habit_id, 10), + ('ACQUIRED_HABIT_30_DAYS', habit_id, 10); + +INSERT INTO achievements(name, achievement_category_id, score) +VALUES + ('CREATED_5_NEWS', create_news_id, 10), + ('CREATED_10_NEWS', create_news_id, 10), + ('CREATED_25_NEWS', create_news_id, 10), + ('CREATED_50_NEWS', create_news_id, 10), + ('CREATED_100_NEWS', create_news_id, 10); + +INSERT INTO achievements(name, achievement_category_id, score) +VALUES + ('COMMENT_OR_REPLY_1_TIMES', comment_or_reply_id, 10), + ('COMMENT_OR_REPLY_5_TIMES', comment_or_reply_id, 10), + ('COMMENT_OR_REPLY_10_TIMES', comment_or_reply_id, 10), + ('COMMENT_OR_REPLY_25_TIMES', comment_or_reply_id, 10), + ('COMMENT_OR_REPLY_50_TIMES', comment_or_reply_id, 10), + ('COMMENT_OR_REPLY_100_TIMES', comment_or_reply_id, 10); + +INSERT INTO achievements(name, achievement_category_id, score) +VALUES + ('LIKE_COMMENT_OR_REPLY_1_TIMES', like_comment_or_reply_id, 10), + ('LIKE_COMMENT_OR_REPLY_5_TIMES', like_comment_or_reply_id, 10), + ('LIKE_COMMENT_OR_REPLY_10_TIMES', like_comment_or_reply_id, 10), + ('LIKE_COMMENT_OR_REPLY_25_TIMES', like_comment_or_reply_id, 10), + ('LIKE_COMMENT_OR_REPLY_50_TIMES', like_comment_or_reply_id, 10), + ('LIKE_COMMENT_OR_REPLY_100_TIMES', like_comment_or_reply_id, 10); + +INSERT INTO achievements(name, achievement_category_id, score) +VALUES + ('SHARE_NEWS_1_TIMES', share_news_id, 10), + ('SHARE_NEWS_5_TIMES', share_news_id, 10), + ('SHARE_NEWS_10_TIMES', share_news_id, 10), + ('SHARE_NEWS_25_TIMES', share_news_id, 10), + ('SHARE_NEWS_50_TIMES', share_news_id, 10), + ('SHARE_NEWS_100_TIMES', share_news_id, 10); + +INSERT INTO achievements(name, achievement_category_id, score) +VALUES + ('FIRST_5_ACHIEVEMENTS', achievement_id, 10), + ('FIRST_10_ACHIEVEMENTS', achievement_id, 10), + ('FIRST_25_ACHIEVEMENTS', achievement_id, 10), + ('FIRST_50_ACHIEVEMENTS', achievement_id, 10), + ('FIRST_100_ACHIEVEMENTS', achievement_id, 10); + +END $$; From cf4601750ed11f1d6df72a82b7fa4827270fefa0 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 18 Sep 2023 11:13:43 +0300 Subject: [PATCH 05/51] deleted condition from Achievement --- core/src/test/java/greencity/ModelUtils.java | 2 +- dao/src/main/java/greencity/entity/Achievement.java | 2 -- .../main/java/greencity/dto/achievement/AchievementVO.java | 3 --- .../java/greencity/mapping/AchievementCategoryVOMapper.java | 1 - .../src/main/java/greencity/mapping/AchievementVOMapper.java | 1 - .../main/java/greencity/service/AchievementServiceImpl.java | 1 - service/src/test/java/greencity/ModelUtils.java | 4 ++-- .../greencity/mapping/AchievementCategoryVOMapperTest.java | 1 - .../test/java/greencity/mapping/AchievementVOMapperTest.java | 1 - 9 files changed, 3 insertions(+), 13 deletions(-) diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index 81a69498e7..7e8bcbb6d9 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -599,7 +599,7 @@ public static AchievementPostDto getAchievementPostDto() { public static AchievementVO getAchievementVO() { return new AchievementVO(1L, getAchievementTranslationVOS(), Collections.singletonList(new UserAchievementVO()), - new AchievementCategoryVO(1L, "name", null, null), 1); + new AchievementCategoryVO(1L, "name", null, null) ); } public static UserShoppingListItem getUserShoppingListItem() { diff --git a/dao/src/main/java/greencity/entity/Achievement.java b/dao/src/main/java/greencity/entity/Achievement.java index a050bea47f..2187dacf3c 100644 --- a/dao/src/main/java/greencity/entity/Achievement.java +++ b/dao/src/main/java/greencity/entity/Achievement.java @@ -41,6 +41,4 @@ public class Achievement { @ManyToOne private AchievementCategory achievementCategory; - @Column(nullable = false) - private Integer condition; } diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java index 2141a20f96..52d72da51f 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java @@ -22,7 +22,4 @@ public class AchievementVO { @NotEmpty private AchievementCategoryVO achievementCategory; - - @NotEmpty - private Integer condition; } diff --git a/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java b/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java index ce04ce962c..0053f009b7 100644 --- a/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java @@ -19,7 +19,6 @@ protected AchievementCategoryVO convert(AchievementCategory achievementCategory) .achievementList(achievementCategory.getAchievementList().stream() .map(achievement -> AchievementVO.builder() .id(achievement.getId()) - .condition(achievement.getCondition()) .build()) .collect(Collectors.toList())) .userActions(achievementCategory.getUserActions().stream().map(userAction -> UserActionVO.builder() diff --git a/service/src/main/java/greencity/mapping/AchievementVOMapper.java b/service/src/main/java/greencity/mapping/AchievementVOMapper.java index ba1479931b..eeb8267e05 100644 --- a/service/src/main/java/greencity/mapping/AchievementVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementVOMapper.java @@ -32,7 +32,6 @@ protected AchievementVO convert(Achievement achievement) { .id(achievement.getAchievementCategory().getId()) .name(achievement.getAchievementCategory().getName()) .build()) - .condition(achievement.getCondition()) .build(); } } diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index bcddfb748c..f894203d3b 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -189,7 +189,6 @@ public AchievementPostDto update(AchievementManagementDto achievementManagementD .orElseThrow(() -> new NotUpdatedException(ErrorMessage.ACHIEVEMENT_NOT_FOUND_BY_ID + achievementManagementDto.getId())); setTranslations(achievement, achievementManagementDto); - achievement.setCondition(achievementManagementDto.getCondition()); Achievement updated = achievementRepo.save(achievement); return modelMapper.map(updated, AchievementPostDto.class); } diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 73e07a94e6..4a6544fbd7 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1379,7 +1379,7 @@ public static AdvicePostDto getAdvicePostDto() { public static Achievement getAchievement() { return new Achievement(1L, Collections.singletonList(getAchievementTranslation()), Collections.emptyList(), - new AchievementCategory(), 1); + new AchievementCategory()); } public static AchievementCategory getAchievementCategory() { @@ -1387,7 +1387,7 @@ public static AchievementCategory getAchievementCategory() { } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, Collections.emptyList(), Collections.emptyList(), new AchievementCategoryVO(), 1); + return new AchievementVO(1L, Collections.emptyList(), Collections.emptyList(), new AchievementCategoryVO()); } public static AchievementPostDto getAchievementPostDto() { diff --git a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java index 6bb19a0287..6883e3ad23 100644 --- a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java @@ -31,7 +31,6 @@ void convert() { .achievementList(achievementCategory.getAchievementList().stream() .map(achievement -> AchievementVO.builder() .id(achievement.getId()) - .condition(achievement.getCondition()) .build()) .collect(Collectors.toList())) .userActions(achievementCategory.getUserActions().stream().map(userAction -> UserActionVO.builder() diff --git a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java index f46d0db5da..3231f2c901 100644 --- a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java @@ -44,7 +44,6 @@ void convert() { .id(achievement.getAchievementCategory().getId()) .name(achievement.getAchievementCategory().getName()) .build()) - .condition(achievement.getCondition()) .build(); assertEquals(expected, achievementVOMapper.convert(achievement)); From 738f38742008e6d073632e8b019891bbdb59b364 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 19 Sep 2023 10:28:22 +0300 Subject: [PATCH 06/51] Returned column condition --- .../resources/db/changelog/db.changelog-master.xml | 1 - .../logs/ch-drop-column-achievement-Spodaryk.xml | 11 ----------- 2 files changed, 12 deletions(-) delete mode 100644 dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml diff --git a/dao/src/main/resources/db/changelog/db.changelog-master.xml b/dao/src/main/resources/db/changelog/db.changelog-master.xml index d03d23d8f7..653a43b60b 100644 --- a/dao/src/main/resources/db/changelog/db.changelog-master.xml +++ b/dao/src/main/resources/db/changelog/db.changelog-master.xml @@ -174,7 +174,6 @@ - diff --git a/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml deleted file mode 100644 index 495b9c2350..0000000000 --- a/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement-Spodaryk.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - From 035b7789ff6480402b1a370c970b626153a08f94 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 19 Sep 2023 12:04:56 +0300 Subject: [PATCH 07/51] Working version when user gets achievements --- .../java/greencity/entity/Achievement.java | 2 + .../repository/UserAchievementRepo.java | 4 + .../ch-add-value-achievements-Spodaryk.xml | 2 +- .../functions/insert-values-achievements.sql | 88 +++++++++---------- .../AchievementCategoryVO.java | 7 +- .../achievement/AchievementCalculation.java | 49 +++++++---- .../service/UserActionServiceImpl.java | 13 +++ 7 files changed, 99 insertions(+), 66 deletions(-) diff --git a/dao/src/main/java/greencity/entity/Achievement.java b/dao/src/main/java/greencity/entity/Achievement.java index 2187dacf3c..a050bea47f 100644 --- a/dao/src/main/java/greencity/entity/Achievement.java +++ b/dao/src/main/java/greencity/entity/Achievement.java @@ -41,4 +41,6 @@ public class Achievement { @ManyToOne private AchievementCategory achievementCategory; + @Column(nullable = false) + private Integer condition; } diff --git a/dao/src/main/java/greencity/repository/UserAchievementRepo.java b/dao/src/main/java/greencity/repository/UserAchievementRepo.java index 9a865d7f8c..78368e25cb 100644 --- a/dao/src/main/java/greencity/repository/UserAchievementRepo.java +++ b/dao/src/main/java/greencity/repository/UserAchievementRepo.java @@ -4,6 +4,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; +import java.util.List; @Repository public interface UserAchievementRepo extends JpaRepository { @@ -16,4 +17,7 @@ public interface UserAchievementRepo extends JpaRepository getUserAchievementByUserId(Long userId); + } diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml index 51b0274543..f36fa1e003 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd"> - + diff --git a/dao/src/main/resources/db/functions/insert-values-achievements.sql b/dao/src/main/resources/db/functions/insert-values-achievements.sql index 60ec286e41..997316910b 100644 --- a/dao/src/main/resources/db/functions/insert-values-achievements.sql +++ b/dao/src/main/resources/db/functions/insert-values-achievements.sql @@ -1,13 +1,13 @@ DO $$ DECLARE habit_id INTEGER; - create_news_id INTEGER; - comment_or_reply_id INTEGER; - like_comment_or_reply_id INTEGER; - share_news_id INTEGER; - achievement_id INTEGER; + create_news_id INTEGER; + comment_or_reply_id INTEGER; + like_comment_or_reply_id INTEGER; + share_news_id INTEGER; + achievement_id INTEGER; BEGIN - -- Acquire IDs from achievement_categories + -- Acquire IDs from achievement_categories SELECT id INTO habit_id FROM achievement_categories WHERE name = 'HABIT'; SELECT id INTO create_news_id FROM achievement_categories WHERE name = 'CREATE_NEWS'; SELECT id INTO comment_or_reply_id FROM achievement_categories WHERE name = 'COMMENT_OR_REPLY'; @@ -15,54 +15,54 @@ SELECT id INTO like_comment_or_reply_id FROM achievement_categories WHERE name = SELECT id INTO share_news_id FROM achievement_categories WHERE name = 'SHARE_NEWS'; SELECT id INTO achievement_id FROM achievement_categories WHERE name = 'ACHIEVEMENT'; --- Insert statements for each category -INSERT INTO achievements(name, achievement_category_id, score) +-- Insert statements for each category with condition +INSERT INTO achievements(name, achievement_category_id, score, condition) VALUES - ('ACQUIRED_HABIT_14_DAYS', habit_id, 10), - ('ACQUIRED_HABIT_21_DAYS', habit_id, 10), - ('ACQUIRED_HABIT_30_DAYS', habit_id, 10); + ('ACQUIRED_HABIT_14_DAYS', habit_id, 10, 14), + ('ACQUIRED_HABIT_21_DAYS', habit_id, 10, 21), + ('ACQUIRED_HABIT_30_DAYS', habit_id, 10, 30); -INSERT INTO achievements(name, achievement_category_id, score) +INSERT INTO achievements(name, achievement_category_id, score, condition) VALUES - ('CREATED_5_NEWS', create_news_id, 10), - ('CREATED_10_NEWS', create_news_id, 10), - ('CREATED_25_NEWS', create_news_id, 10), - ('CREATED_50_NEWS', create_news_id, 10), - ('CREATED_100_NEWS', create_news_id, 10); + ('CREATED_5_NEWS', create_news_id, 10, 5), + ('CREATED_10_NEWS', create_news_id, 10, 10), + ('CREATED_25_NEWS', create_news_id, 10, 25), + ('CREATED_50_NEWS', create_news_id, 10, 50), + ('CREATED_100_NEWS', create_news_id, 10, 100); -INSERT INTO achievements(name, achievement_category_id, score) +INSERT INTO achievements(name, achievement_category_id, score, condition) VALUES - ('COMMENT_OR_REPLY_1_TIMES', comment_or_reply_id, 10), - ('COMMENT_OR_REPLY_5_TIMES', comment_or_reply_id, 10), - ('COMMENT_OR_REPLY_10_TIMES', comment_or_reply_id, 10), - ('COMMENT_OR_REPLY_25_TIMES', comment_or_reply_id, 10), - ('COMMENT_OR_REPLY_50_TIMES', comment_or_reply_id, 10), - ('COMMENT_OR_REPLY_100_TIMES', comment_or_reply_id, 10); + ('COMMENT_OR_REPLY_1_TIMES', comment_or_reply_id, 10, 1), + ('COMMENT_OR_REPLY_5_TIMES', comment_or_reply_id, 10, 5), + ('COMMENT_OR_REPLY_10_TIMES', comment_or_reply_id, 10, 10), + ('COMMENT_OR_REPLY_25_TIMES', comment_or_reply_id, 10, 25), + ('COMMENT_OR_REPLY_50_TIMES', comment_or_reply_id, 10, 50), + ('COMMENT_OR_REPLY_100_TIMES', comment_or_reply_id, 10, 100); -INSERT INTO achievements(name, achievement_category_id, score) +INSERT INTO achievements(name, achievement_category_id, score, condition) VALUES - ('LIKE_COMMENT_OR_REPLY_1_TIMES', like_comment_or_reply_id, 10), - ('LIKE_COMMENT_OR_REPLY_5_TIMES', like_comment_or_reply_id, 10), - ('LIKE_COMMENT_OR_REPLY_10_TIMES', like_comment_or_reply_id, 10), - ('LIKE_COMMENT_OR_REPLY_25_TIMES', like_comment_or_reply_id, 10), - ('LIKE_COMMENT_OR_REPLY_50_TIMES', like_comment_or_reply_id, 10), - ('LIKE_COMMENT_OR_REPLY_100_TIMES', like_comment_or_reply_id, 10); + ('LIKE_COMMENT_OR_REPLY_1_TIMES', like_comment_or_reply_id, 10, 1), + ('LIKE_COMMENT_OR_REPLY_5_TIMES', like_comment_or_reply_id, 10, 5), + ('LIKE_COMMENT_OR_REPLY_10_TIMES', like_comment_or_reply_id, 10, 10), + ('LIKE_COMMENT_OR_REPLY_25_TIMES', like_comment_or_reply_id, 10, 25), + ('LIKE_COMMENT_OR_REPLY_50_TIMES', like_comment_or_reply_id, 10, 50), + ('LIKE_COMMENT_OR_REPLY_100_TIMES', like_comment_or_reply_id, 10, 100); -INSERT INTO achievements(name, achievement_category_id, score) +INSERT INTO achievements(name, achievement_category_id, score, condition) VALUES - ('SHARE_NEWS_1_TIMES', share_news_id, 10), - ('SHARE_NEWS_5_TIMES', share_news_id, 10), - ('SHARE_NEWS_10_TIMES', share_news_id, 10), - ('SHARE_NEWS_25_TIMES', share_news_id, 10), - ('SHARE_NEWS_50_TIMES', share_news_id, 10), - ('SHARE_NEWS_100_TIMES', share_news_id, 10); + ('SHARE_NEWS_1_TIMES', share_news_id, 10, 1), + ('SHARE_NEWS_5_TIMES', share_news_id, 10, 5), + ('SHARE_NEWS_10_TIMES', share_news_id, 10, 10), + ('SHARE_NEWS_25_TIMES', share_news_id, 10, 25), + ('SHARE_NEWS_50_TIMES', share_news_id, 10, 50), + ('SHARE_NEWS_100_TIMES', share_news_id, 10, 100); -INSERT INTO achievements(name, achievement_category_id, score) +INSERT INTO achievements(name, achievement_category_id, score, condition) VALUES - ('FIRST_5_ACHIEVEMENTS', achievement_id, 10), - ('FIRST_10_ACHIEVEMENTS', achievement_id, 10), - ('FIRST_25_ACHIEVEMENTS', achievement_id, 10), - ('FIRST_50_ACHIEVEMENTS', achievement_id, 10), - ('FIRST_100_ACHIEVEMENTS', achievement_id, 10); + ('FIRST_5_ACHIEVEMENTS', achievement_id, 10, 5), + ('FIRST_10_ACHIEVEMENTS', achievement_id, 10, 10), + ('FIRST_25_ACHIEVEMENTS', achievement_id, 10, 25), + ('FIRST_50_ACHIEVEMENTS', achievement_id, 10, 50), + ('FIRST_100_ACHIEVEMENTS', achievement_id, 10, 100); END $$; diff --git a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java index 915c118f71..0bc46a0e59 100644 --- a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java +++ b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java @@ -14,13 +14,8 @@ @Builder @EqualsAndHashCode public class AchievementCategoryVO { - @NotEmpty - private Long id; + @NotEmpty private String name; - - private List achievementList; - - private List userActions; } diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index afa308d9d7..caab973451 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -2,14 +2,20 @@ import greencity.client.RestClient; import greencity.dto.achievement.AchievementVO; +import greencity.dto.achievement.UserAchievementVO; import greencity.dto.achievement.UserVOAchievement; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.useraction.UserActionVO; +import greencity.entity.Achievement; +import greencity.entity.AchievementCategory; import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; import greencity.enums.AchievementType; +import greencity.repository.AchievementCategoryRepo; +import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; +import greencity.repository.UserRepo; import greencity.service.AchievementCategoryService; import greencity.service.AchievementService; import greencity.service.UserActionService; @@ -18,6 +24,8 @@ import org.springframework.stereotype.Component; import java.util.Optional; +import java.util.List; +import java.util.stream.Collectors; import static greencity.enums.AchievementStatus.ACTIVE; import static greencity.enums.AchievementType.INCREMENT; @@ -30,6 +38,9 @@ public class AchievementCalculation { private AchievementCategoryService achievementCategoryService; private final ModelMapper modelMapper; private UserAchievementRepo userAchievementRepo; + private final UserRepo userRepo; + private final AchievementRepo achievementRepo; + private final AchievementCategoryRepo achievementCategoryRepo; /** * Constructor for {@link AchievementCalculation}. @@ -45,13 +56,19 @@ public AchievementCalculation(RestClient restClient, @Lazy AchievementService achievementService, AchievementCategoryService achievementCategoryService, ModelMapper modelMapper, - UserAchievementRepo userAchievementRepo) { + UserAchievementRepo userAchievementRepo, + UserRepo userRepo, + AchievementRepo achievementRepo, + AchievementCategoryRepo achievementCategoryRepo) { this.restClient = restClient; this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; this.modelMapper = modelMapper; this.userAchievementRepo = userAchievementRepo; + this.userRepo = userRepo; + this.achievementRepo = achievementRepo; + this.achievementCategoryRepo = achievementCategoryRepo; } /** @@ -82,30 +99,32 @@ public void calculateAchievement(Long userId, AchievementType type, * @author Orest Mamchuk */ private void checkAchievements(Long achievementCategoryId, Integer count, Long userId) { - UserVOAchievement userForAchievement = restClient.findUserForAchievement(userId); AchievementVO achievementVO = achievementService.findByCategoryIdAndCondition(achievementCategoryId, count); if (achievementVO != null) { - changeAchievementStatus(modelMapper.map(userForAchievement, User.class), achievementVO); + changeAchievementStatus(userId, achievementCategoryId,count); } } /** * Method that changing achievement status. * - * @param user {@link User} - * @param achievementVO {@link AchievementVO} + * @param userId {@link User} * @author Orest Mamchuk */ - private void changeAchievementStatus(User user, AchievementVO achievementVO) { - Optional userAchievement = user.getUserAchievements().stream() - .filter(userAchievement1 -> userAchievement1.getAchievement().getId().equals(achievementVO.getId())) - .findFirst(); - if (userAchievement.isPresent()) { - UserAchievement achievement = userAchievement.get(); - achievement.setAchievementStatus(ACTIVE); - userAchievementRepo.save(achievement); - calculateAchievement(user.getId(), INCREMENT, AchievementCategoryType.ACHIEVEMENT, 0); - } + private void changeAchievementStatus(Long userId, Long achievementCategoryId,int count) { + Achievement achievement=achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId,count).get(); + UserAchievement userAchievement =UserAchievement.builder() + .achievement(achievement) + .user(userRepo.findById(userId).get()) + .achievementStatus(ACTIVE) + .build(); + userAchievementRepo.save(userAchievement); + AchievementCategory achievementCategory=achievementCategoryRepo.findByName(AchievementCategoryType.ACHIEVEMENT.toString()); + UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( + userId, achievementCategory.getId()); + int countAchievement = checkType(INCREMENT, userActionVO, count); + calculateAchievement(userId, INCREMENT, AchievementCategoryType.ACHIEVEMENT, countAchievement); + } /** diff --git a/service/src/main/java/greencity/service/UserActionServiceImpl.java b/service/src/main/java/greencity/service/UserActionServiceImpl.java index f12d911e8d..0f89c72152 100644 --- a/service/src/main/java/greencity/service/UserActionServiceImpl.java +++ b/service/src/main/java/greencity/service/UserActionServiceImpl.java @@ -1,8 +1,11 @@ package greencity.service; +import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.UserAction; +import greencity.repository.AchievementCategoryRepo; import greencity.repository.UserActionRepo; +import greencity.repository.UserRepo; import lombok.AllArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Service; @@ -15,6 +18,8 @@ public class UserActionServiceImpl implements UserActionService { private UserActionRepo userActionRepo; private final ModelMapper modelMapper; + private final UserRepo userRepo; + private final AchievementCategoryRepo achievementCategoryRepo; /** * {@inheritDoc} @@ -42,6 +47,14 @@ public UserActionVO updateUserActions(UserActionVO userActionVO) { @Override public UserActionVO findUserActionByUserIdAndAchievementCategory(Long userId, Long categoryId) { UserAction userAction = userActionRepo.findByUserIdAndAchievementCategoryId(userId, categoryId); + if(userAction==null){ + userAction=UserAction.builder() + .user(userRepo.findById(userId).get()) + .count(0) + .achievementCategory(achievementCategoryRepo.findById(categoryId).get()) + .build(); + userActionRepo.save(userAction); + } return userAction != null ? modelMapper.map(userAction, UserActionVO.class) : null; } From 565482d2bd3d1c50e33f6ad832a43cb779703067 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 19 Sep 2023 13:16:53 +0300 Subject: [PATCH 08/51] Updated achievement_translations:deleted unused lines --- core/src/test/java/greencity/ModelUtils.java | 2 +- .../localization/AchievementTranslation.java | 10 ++-------- .../greencity/repository/AchievementRepo.java | 6 +++--- .../db/changelog/db.changelog-master.xml | 4 +++- .../greencity/dto/achievement/AchievementVO.java | 3 +++ .../AchievementCategoryVO.java | 7 ++++++- .../greencity/mapping/AchievementVOMapper.java | 14 +++++++------- .../service/AchievementServiceImpl.java | 16 ++++++++-------- service/src/test/java/greencity/ModelUtils.java | 6 +++--- .../mapping/AchievementVOMapperTest.java | 14 +++++++------- .../service/AchievementServiceImplTest.java | 14 +++++++------- 11 files changed, 50 insertions(+), 46 deletions(-) diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index 7e8bcbb6d9..4999b24357 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -599,7 +599,7 @@ public static AchievementPostDto getAchievementPostDto() { public static AchievementVO getAchievementVO() { return new AchievementVO(1L, getAchievementTranslationVOS(), Collections.singletonList(new UserAchievementVO()), - new AchievementCategoryVO(1L, "name", null, null) ); + new AchievementCategoryVO(1L, "name", null, null),1 ); } public static UserShoppingListItem getUserShoppingListItem() { diff --git a/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java b/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java index 17f981c27e..a94c5251e7 100644 --- a/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java +++ b/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java @@ -20,17 +20,11 @@ public class AchievementTranslation { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @ManyToOne - private Language language; - - @Column(nullable = false, length = 300) - private String title; @Column(nullable = false, length = 300) - private String description; - + private String name; @Column(nullable = false, length = 300) - private String message; + private String nameEng; @ManyToOne private Achievement achievement; diff --git a/dao/src/main/java/greencity/repository/AchievementRepo.java b/dao/src/main/java/greencity/repository/AchievementRepo.java index 4815a473dd..1f781f9442 100644 --- a/dao/src/main/java/greencity/repository/AchievementRepo.java +++ b/dao/src/main/java/greencity/repository/AchievementRepo.java @@ -22,9 +22,9 @@ public interface AchievementRepo extends JpaRepository { @Query("SELECT DISTINCT a FROM Achievement a " + "JOIN AchievementTranslation at on at.achievement.id = a.id " + "WHERE CONCAT(a.id,'') LIKE LOWER(CONCAT('%', :query, '%')) " - + "OR LOWER(at.title) LIKE LOWER(CONCAT('%', :query, '%'))" - + "OR LOWER(at.description) LIKE LOWER(CONCAT('%', :query, '%'))" - + "OR LOWER(at.message) LIKE LOWER(CONCAT('%', :query, '%'))" +// + "OR LOWER(at.title) LIKE LOWER(CONCAT('%', :query, '%'))" +// + "OR LOWER(at.description) LIKE LOWER(CONCAT('%', :query, '%'))" +// + "OR LOWER(at.message) LIKE LOWER(CONCAT('%', :query, '%'))" + "OR LOWER(a.achievementCategory.name) LIKE LOWER(CONCAT('%', :query, '%'))" + "OR CONCAT(a.condition, ' ') LIKE LOWER(CONCAT('%', :query, '%'))") Page searchAchievementsBy(Pageable paging, String query); diff --git a/dao/src/main/resources/db/changelog/db.changelog-master.xml b/dao/src/main/resources/db/changelog/db.changelog-master.xml index 653a43b60b..de1ebd683a 100644 --- a/dao/src/main/resources/db/changelog/db.changelog-master.xml +++ b/dao/src/main/resources/db/changelog/db.changelog-master.xml @@ -175,6 +175,8 @@ - + + + diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java index 52d72da51f..2141a20f96 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java @@ -22,4 +22,7 @@ public class AchievementVO { @NotEmpty private AchievementCategoryVO achievementCategory; + + @NotEmpty + private Integer condition; } diff --git a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java index 0bc46a0e59..915c118f71 100644 --- a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java +++ b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java @@ -14,8 +14,13 @@ @Builder @EqualsAndHashCode public class AchievementCategoryVO { - + @NotEmpty + private Long id; @NotEmpty private String name; + + private List achievementList; + + private List userActions; } diff --git a/service/src/main/java/greencity/mapping/AchievementVOMapper.java b/service/src/main/java/greencity/mapping/AchievementVOMapper.java index eeb8267e05..adcf7c42d2 100644 --- a/service/src/main/java/greencity/mapping/AchievementVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementVOMapper.java @@ -17,13 +17,13 @@ protected AchievementVO convert(Achievement achievement) { List list = new ArrayList<>(); achievement.getTranslations().forEach(achievementTranslation -> list.add(AchievementTranslationVO.builder() .id(achievementTranslation.getId()) - .title(achievementTranslation.getTitle()) - .description(achievementTranslation.getDescription()) - .message(achievementTranslation.getMessage()) - .language(LanguageVO.builder() - .id(achievementTranslation.getLanguage().getId()) - .code(achievementTranslation.getLanguage().getCode()) - .build()) +// .title(achievementTranslation.getTitle()) +// .description(achievementTranslation.getDescription()) +// .message(achievementTranslation.getMessage()) +// .language(LanguageVO.builder() +// .id(achievementTranslation.getLanguage().getId()) +// .code(achievementTranslation.getLanguage().getCode()) +// .build()) .build())); return AchievementVO.builder() .id(achievement.getId()) diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index f894203d3b..63613619a3 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -232,9 +232,9 @@ private List setAchievementNotifications( translationList.forEach(translation -> { achievementNotifications.add(AchievementNotification.builder() .id(translation.getId()) - .title(translation.getTitle()) - .description(translation.getDescription()) - .message(translation.getMessage()) +// .title(translation.getTitle()) +// .description(translation.getDescription()) +// .message(translation.getMessage()) .build()); UserAchievement userAchievement = userAchievementRepo .getUserAchievementByIdAndAchievementId(userId, translation.getAchievement().getId()); @@ -249,12 +249,12 @@ private void setTranslations(Achievement achievement, AchievementManagementDto a .forEach(achievementTranslation -> { AchievementTranslationVO achievementTranslationVO = achievementManagementDto .getTranslations().stream() - .filter(newTranslation -> newTranslation.getLanguage().getCode() - .equals(achievementTranslation.getLanguage().getCode())) +// .filter(newTranslation -> newTranslation.getLanguage().getCode() +// .equals(achievementTranslation.getLanguage().getCode())) .findFirst().get(); - achievementTranslation.setTitle(achievementTranslationVO.getTitle()); - achievementTranslation.setDescription(achievementTranslationVO.getDescription()); - achievementTranslation.setMessage(achievementTranslationVO.getMessage()); +// achievementTranslation.setTitle(achievementTranslationVO.getTitle()); +// achievementTranslation.setDescription(achievementTranslationVO.getDescription()); +// achievementTranslation.setMessage(achievementTranslationVO.getMessage()); }); } } diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 4a6544fbd7..80be6380bc 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1379,7 +1379,7 @@ public static AdvicePostDto getAdvicePostDto() { public static Achievement getAchievement() { return new Achievement(1L, Collections.singletonList(getAchievementTranslation()), Collections.emptyList(), - new AchievementCategory()); + new AchievementCategory(),1); } public static AchievementCategory getAchievementCategory() { @@ -1387,7 +1387,7 @@ public static AchievementCategory getAchievementCategory() { } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, Collections.emptyList(), Collections.emptyList(), new AchievementCategoryVO()); + return new AchievementVO(1L, Collections.emptyList(), Collections.emptyList(), new AchievementCategoryVO(),1); } public static AchievementPostDto getAchievementPostDto() { @@ -1411,7 +1411,7 @@ public static AchievementManagementDto getAchievementManagementDto() { } public static AchievementTranslation getAchievementTranslation() { - return new AchievementTranslation(1L, getLanguage(), "Title", "Description", "Message", null); + return new AchievementTranslation(1L, "Title", "Description",getAchievement()); } public static UserAchievementVO getUserAchievementVO() { diff --git a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java index 3231f2c901..bf961bd2dc 100644 --- a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java @@ -28,13 +28,13 @@ void convert() { achievement.getTranslations().forEach(achievementTranslation -> list.add(AchievementTranslationVO.builder() .id(achievementTranslation.getId()) - .title(achievementTranslation.getTitle()) - .description(achievementTranslation.getDescription()) - .message(achievementTranslation.getMessage()) - .language(LanguageVO.builder() - .id(achievementTranslation.getLanguage().getId()) - .code(achievementTranslation.getLanguage().getCode()) - .build()) +// .title(achievementTranslation.getTitle()) +// .description(achievementTranslation.getDescription()) +// .message(achievementTranslation.getMessage()) +// .language(LanguageVO.builder() +// .id(achievementTranslation.getLanguage().getId()) +// .code(achievementTranslation.getLanguage().getCode()) +// .build()) .build())); AchievementVO expected = AchievementVO.builder() diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 5364c9108c..428314bdfb 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -229,13 +229,13 @@ void findAchievementsWithStatusActive() { .singletonList(AchievementTranslation.builder() .id(1L) .achievement(achievement) - .message("test") - .description("test") - .title("test") - .language(Language.builder() - .id(1L) - .code("ua") - .build()) +// .message("test") +// .description("test") +// .title("test") +// .language(Language.builder() +// .id(1L) +// .code("ua") +// .build()) .build()); UserAchievement userAchievement = ModelUtils.getUserAchievement(); when(restClient.findById(1L)).thenReturn(userVO); From e3ac1e0e7ceca66f819b82d40607d30efec6055e Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 19 Sep 2023 13:17:51 +0300 Subject: [PATCH 09/51] Updated achievement_translations:deleted unused lines+Formatted --- core/src/test/java/greencity/ModelUtils.java | 2 +- .../localization/AchievementTranslation.java | 1 - ...lumn-achievement_translations-Spodaryk.xml | 17 ++ ...lues-achievement_translations-Spodaryk.xml | 169 ++++++++++++++++++ ...lumn-achievement_translations-Spodaryk.xml | 11 ++ .../achievement/AchievementCalculation.java | 30 ++-- .../greencity/service/EcoNewsServiceImpl.java | 3 +- .../service/UserActionServiceImpl.java | 12 +- .../src/test/java/greencity/ModelUtils.java | 6 +- .../service/AchievementServiceImplTest.java | 2 +- 10 files changed, 226 insertions(+), 27 deletions(-) create mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml create mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml create mode 100644 dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index 4999b24357..81a69498e7 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -599,7 +599,7 @@ public static AchievementPostDto getAchievementPostDto() { public static AchievementVO getAchievementVO() { return new AchievementVO(1L, getAchievementTranslationVOS(), Collections.singletonList(new UserAchievementVO()), - new AchievementCategoryVO(1L, "name", null, null),1 ); + new AchievementCategoryVO(1L, "name", null, null), 1); } public static UserShoppingListItem getUserShoppingListItem() { diff --git a/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java b/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java index a94c5251e7..f11b6e8a0d 100644 --- a/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java +++ b/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java @@ -20,7 +20,6 @@ public class AchievementTranslation { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @Column(nullable = false, length = 300) private String name; @Column(nullable = false, length = 300) diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml new file mode 100644 index 0000000000..ba0eea0c2a --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml new file mode 100644 index 0000000000..eddd6c0230 --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml @@ -0,0 +1,169 @@ + + + + + -- Acquired Habits + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Набуття звички протягом 14 днів', 'Acquired habit 14 days' + FROM achievements a + WHERE a.name = 'ACQUIRED_HABIT_14_DAYS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Набуття звички протягом 21 днів', 'Acquired habit 21 days' + FROM achievements a + WHERE a.name = 'ACQUIRED_HABIT_21_DAYS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Набуття звички протягом 30 днів', 'Acquired habit 30 days' + FROM achievements a + WHERE a.name = 'ACQUIRED_HABIT_30_DAYS'; + + -- Created News + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Створено 5 новин', 'Created 5 news' + FROM achievements a + WHERE a.name = 'CREATED_5_NEWS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Створено 10 новин', 'Created 10 news' + FROM achievements a + WHERE a.name = 'CREATED_10_NEWS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Створено 25 новин', 'Created 25 news' + FROM achievements a + WHERE a.name = 'CREATED_25_NEWS'; + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Створено 50 новин', 'Created 50 news' + FROM achievements a + WHERE a.name = 'CREATED_50_NEWS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Створено 100 новин', 'Created 100 news' + FROM achievements a + WHERE a.name = 'CREATED_100_NEWS'; + + -- Comment or Reply + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Залишено коментар або відповідь 1 раз', 'Comment or reply 1 time' + FROM achievements a + WHERE a.name = 'COMMENT_OR_REPLY_1_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Залишено коментар або відповідь 5 разів', 'Comment or reply 5 times' + FROM achievements a + WHERE a.name = 'COMMENT_OR_REPLY_5_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Залишено коментар або відповідь 10 разів', 'Comment or reply 10 times' + FROM achievements a + WHERE a.name = 'COMMENT_OR_REPLY_10_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Залишено коментар або відповідь 25 разів', 'Comment or reply 25 times' + FROM achievements a + WHERE a.name = 'COMMENT_OR_REPLY_25_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Залишено коментар або відповідь 50 разів', 'Comment or reply 50 times' + FROM achievements a + WHERE a.name = 'COMMENT_OR_REPLY_50_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Залишено коментар або відповідь 100 разів', 'Comment or reply 100 times' + FROM achievements a + WHERE a.name = 'COMMENT_OR_REPLY_100_TIMES'; + + -- Like Comment or Reply + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Лайк коментаря або відповіді 1 раз', 'Like comment or reply 1 time' + FROM achievements a + WHERE a.name = 'LIKE_COMMENT_OR_REPLY_1_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Лайк коментаря або відповіді 5 разів', 'Like comment or reply 5 times' + FROM achievements a + WHERE a.name = 'LIKE_COMMENT_OR_REPLY_5_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Лайк коментаря або відповіді 10 разів', 'Like comment or reply 10 times' + FROM achievements a + WHERE a.name = 'LIKE_COMMENT_OR_REPLY_10_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Лайк коментаря або відповіді 25 разів', 'Like comment or reply 25 times' + FROM achievements a + WHERE a.name = 'LIKE_COMMENT_OR_REPLY_25_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Лайк коментаря або відповіді 50 разів', 'Like comment or reply 50 times' + FROM achievements a + WHERE a.name = 'LIKE_COMMENT_OR_REPLY_50_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Лайк коментаря або відповіді 100 разів', 'Like comment or reply 100 times' + FROM achievements a + WHERE a.name = 'LIKE_COMMENT_OR_REPLY_100_TIMES'; + + -- Share News + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Поширено 1 новину', 'Shared 1 news' + FROM achievements a + WHERE a.name = 'SHARE_NEWS_1_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Поширено 5 новин', 'Shared 5 news' + FROM achievements a + WHERE a.name = 'SHARE_NEWS_5_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Поширено 10 новин', 'Shared 10 news' + FROM achievements a + WHERE a.name = 'SHARE_NEWS_10_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Поширено 25 новин', 'Shared 25 news' + FROM achievements a + WHERE a.name = 'SHARE_NEWS_25_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Поширено 50 новин', 'Shared 50 news' + FROM achievements a + WHERE a.name = 'SHARE_NEWS_50_TIMES'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Поширено 100 новин', 'Shared 100 news' + FROM achievements a + WHERE a.name = 'SHARE_NEWS_100_TIMES'; + + -- First Achievements + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Перші 5 досягнень', 'First 5 achievements' + FROM achievements a + WHERE a.name = 'FIRST_5_ACHIEVEMENTS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Перші 10 досягнень', 'First 10 achievements' + FROM achievements a + WHERE a.name = 'FIRST_10_ACHIEVEMENTS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Перші 25 досягнень', 'First 25 achievements' + FROM achievements a + WHERE a.name = 'FIRST_25_ACHIEVEMENTS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Перші 50 досягнень', 'First 50 achievements' + FROM achievements a + WHERE a.name = 'FIRST_50_ACHIEVEMENTS'; + + INSERT INTO achievement_translations (achievement_id, name, name_eng) + SELECT a.id, 'Перші 100 досягнень', 'First 100 achievements' + FROM achievements a + WHERE a.name = 'FIRST_100_ACHIEVEMENTS'; + + + diff --git a/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml new file mode 100644 index 0000000000..525b6f979f --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index caab973451..26b5a78702 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -57,9 +57,9 @@ public AchievementCalculation(RestClient restClient, AchievementCategoryService achievementCategoryService, ModelMapper modelMapper, UserAchievementRepo userAchievementRepo, - UserRepo userRepo, - AchievementRepo achievementRepo, - AchievementCategoryRepo achievementCategoryRepo) { + UserRepo userRepo, + AchievementRepo achievementRepo, + AchievementCategoryRepo achievementCategoryRepo) { this.restClient = restClient; this.userActionService = userActionService; this.achievementService = achievementService; @@ -101,27 +101,29 @@ public void calculateAchievement(Long userId, AchievementType type, private void checkAchievements(Long achievementCategoryId, Integer count, Long userId) { AchievementVO achievementVO = achievementService.findByCategoryIdAndCondition(achievementCategoryId, count); if (achievementVO != null) { - changeAchievementStatus(userId, achievementCategoryId,count); + changeAchievementStatus(userId, achievementCategoryId, count); } } /** * Method that changing achievement status. * - * @param userId {@link User} + * @param userId {@link User} * @author Orest Mamchuk */ - private void changeAchievementStatus(Long userId, Long achievementCategoryId,int count) { - Achievement achievement=achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId,count).get(); - UserAchievement userAchievement =UserAchievement.builder() - .achievement(achievement) - .user(userRepo.findById(userId).get()) - .achievementStatus(ACTIVE) - .build(); + private void changeAchievementStatus(Long userId, Long achievementCategoryId, int count) { + Achievement achievement = + achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count).get(); + UserAchievement userAchievement = UserAchievement.builder() + .achievement(achievement) + .user(userRepo.findById(userId).get()) + .achievementStatus(ACTIVE) + .build(); userAchievementRepo.save(userAchievement); - AchievementCategory achievementCategory=achievementCategoryRepo.findByName(AchievementCategoryType.ACHIEVEMENT.toString()); + AchievementCategory achievementCategory = + achievementCategoryRepo.findByName(AchievementCategoryType.ACHIEVEMENT.toString()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( - userId, achievementCategory.getId()); + userId, achievementCategory.getId()); int countAchievement = checkType(INCREMENT, userActionVO, count); calculateAchievement(userId, INCREMENT, AchievementCategoryType.ACHIEVEMENT, countAchievement); diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 5e1b276cff..73daa77d0c 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -428,7 +428,8 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { CompletableFuture .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT, user, accessToken)); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementType.INCREMENT, AchievementCategoryType.LIKE_COMMENT_OR_REPLY, 0)); + .calculateAchievement(user.getId(), AchievementType.INCREMENT, + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, 0)); } /** diff --git a/service/src/main/java/greencity/service/UserActionServiceImpl.java b/service/src/main/java/greencity/service/UserActionServiceImpl.java index 0f89c72152..c4b39579a7 100644 --- a/service/src/main/java/greencity/service/UserActionServiceImpl.java +++ b/service/src/main/java/greencity/service/UserActionServiceImpl.java @@ -47,12 +47,12 @@ public UserActionVO updateUserActions(UserActionVO userActionVO) { @Override public UserActionVO findUserActionByUserIdAndAchievementCategory(Long userId, Long categoryId) { UserAction userAction = userActionRepo.findByUserIdAndAchievementCategoryId(userId, categoryId); - if(userAction==null){ - userAction=UserAction.builder() - .user(userRepo.findById(userId).get()) - .count(0) - .achievementCategory(achievementCategoryRepo.findById(categoryId).get()) - .build(); + if (userAction == null) { + userAction = UserAction.builder() + .user(userRepo.findById(userId).get()) + .count(0) + .achievementCategory(achievementCategoryRepo.findById(categoryId).get()) + .build(); userActionRepo.save(userAction); } return userAction != null ? modelMapper.map(userAction, UserActionVO.class) : null; diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 80be6380bc..9062838ad4 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1379,7 +1379,7 @@ public static AdvicePostDto getAdvicePostDto() { public static Achievement getAchievement() { return new Achievement(1L, Collections.singletonList(getAchievementTranslation()), Collections.emptyList(), - new AchievementCategory(),1); + new AchievementCategory(), 1); } public static AchievementCategory getAchievementCategory() { @@ -1387,7 +1387,7 @@ public static AchievementCategory getAchievementCategory() { } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, Collections.emptyList(), Collections.emptyList(), new AchievementCategoryVO(),1); + return new AchievementVO(1L, Collections.emptyList(), Collections.emptyList(), new AchievementCategoryVO(), 1); } public static AchievementPostDto getAchievementPostDto() { @@ -1411,7 +1411,7 @@ public static AchievementManagementDto getAchievementManagementDto() { } public static AchievementTranslation getAchievementTranslation() { - return new AchievementTranslation(1L, "Title", "Description",getAchievement()); + return new AchievementTranslation(1L, "Title", "Description", getAchievement()); } public static UserAchievementVO getUserAchievementVO() { diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 428314bdfb..ed7098001c 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -249,7 +249,7 @@ void findAchievementsWithStatusActive() { @Test void calculateAchievement() { - achievementService.calculateAchievements(1L, AchievementType.INCREMENT, AchievementCategoryType. CREATE_NEWS, 1); + achievementService.calculateAchievements(1L, AchievementType.INCREMENT, AchievementCategoryType.CREATE_NEWS, 1); verify(achievementCalculation).calculateAchievement( anyLong(), any(AchievementType.class), From 02a2bf89fc19feb73141b8605fdc0e2e893220d4 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 19 Sep 2023 14:10:24 +0300 Subject: [PATCH 10/51] Deleted from achieveent category unused fields --- core/src/test/java/greencity/ModelUtils.java | 2 +- .../java/greencity/entity/AchievementCategory.java | 5 ----- .../achievementcategory/AchievementCategoryVO.java | 4 ---- .../mapping/AchievementCategoryVOMapper.java | 9 --------- service/src/test/java/greencity/ModelUtils.java | 4 ++-- .../mapping/AchievementCategoryVOMapperTest.java | 13 +------------ 6 files changed, 4 insertions(+), 33 deletions(-) diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index 81a69498e7..2097552545 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -599,7 +599,7 @@ public static AchievementPostDto getAchievementPostDto() { public static AchievementVO getAchievementVO() { return new AchievementVO(1L, getAchievementTranslationVOS(), Collections.singletonList(new UserAchievementVO()), - new AchievementCategoryVO(1L, "name", null, null), 1); + new AchievementCategoryVO(1L, "name"), 1); } public static UserShoppingListItem getUserShoppingListItem() { diff --git a/dao/src/main/java/greencity/entity/AchievementCategory.java b/dao/src/main/java/greencity/entity/AchievementCategory.java index 3dbf598390..0eeb2cc498 100644 --- a/dao/src/main/java/greencity/entity/AchievementCategory.java +++ b/dao/src/main/java/greencity/entity/AchievementCategory.java @@ -26,9 +26,4 @@ public class AchievementCategory { @Column(nullable = false, unique = true, length = 100) private String name; - @OneToMany(mappedBy = "achievementCategory") - private List achievementList; - - @OneToMany(mappedBy = "achievementCategory") - private List userActions; } diff --git a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java index 915c118f71..c11b9bc377 100644 --- a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java +++ b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java @@ -19,8 +19,4 @@ public class AchievementCategoryVO { @NotEmpty private String name; - - private List achievementList; - - private List userActions; } diff --git a/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java b/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java index 0053f009b7..f7389e3d65 100644 --- a/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java @@ -16,15 +16,6 @@ protected AchievementCategoryVO convert(AchievementCategory achievementCategory) return AchievementCategoryVO.builder() .id(achievementCategory.getId()) .name(achievementCategory.getName()) - .achievementList(achievementCategory.getAchievementList().stream() - .map(achievement -> AchievementVO.builder() - .id(achievement.getId()) - .build()) - .collect(Collectors.toList())) - .userActions(achievementCategory.getUserActions().stream().map(userAction -> UserActionVO.builder() - .id(userAction.getId()) - .build()) - .collect(Collectors.toList())) .build(); } } diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 9062838ad4..be5141d810 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1383,7 +1383,7 @@ public static Achievement getAchievement() { } public static AchievementCategory getAchievementCategory() { - return new AchievementCategory(1L, "Name", null, null); + return new AchievementCategory(1L, "Name"); } public static AchievementVO getAchievementVO() { @@ -1403,7 +1403,7 @@ public static AchievementTranslationVO getAchievementTranslationVO() { } public static AchievementCategoryVO getAchievementCategoryVO() { - return new AchievementCategoryVO(1L, "Category", null, null); + return new AchievementCategoryVO(1L, "Category"); } public static AchievementManagementDto getAchievementManagementDto() { diff --git a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java index 6883e3ad23..0597ccfd51 100644 --- a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java @@ -22,21 +22,10 @@ class AchievementCategoryVOMapperTest { @Test void convert() { - AchievementCategory achievementCategory = new AchievementCategory(1L, "Name", - Collections.singletonList(ModelUtils.getAchievement()), - Collections.singletonList(ModelUtils.getUserAction())); + AchievementCategory achievementCategory = new AchievementCategory(1L, "Name"); AchievementCategoryVO achievementCategoryVO = AchievementCategoryVO.builder() .id(achievementCategory.getId()) .name(achievementCategory.getName()) - .achievementList(achievementCategory.getAchievementList().stream() - .map(achievement -> AchievementVO.builder() - .id(achievement.getId()) - .build()) - .collect(Collectors.toList())) - .userActions(achievementCategory.getUserActions().stream().map(userAction -> UserActionVO.builder() - .id(userAction.getId()) - .build()) - .collect(Collectors.toList())) .build(); assertEquals(achievementCategoryVO, achievementCategoryVOMapper.convert(achievementCategory)); } From e44f2541d0eb7573d10883a531f44f1f558069a4 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 19 Sep 2023 14:22:17 +0300 Subject: [PATCH 11/51] Deleted separation by category in Achievements --- .../java/greencity/enums/AchievementType.java | 7 ---- .../greencity/service/AchievementService.java | 4 +-- .../achievement/AchievementCalculation.java | 33 +++++-------------- .../service/AchievementServiceImpl.java | 5 ++- .../service/EcoNewsCommentServiceImpl.java | 3 +- .../greencity/service/EcoNewsServiceImpl.java | 8 ++--- .../service/HabitAssignServiceImpl.java | 5 +-- .../AchievementCalculationTest.java | 9 +++-- .../service/AchievementServiceImplTest.java | 4 +-- 9 files changed, 21 insertions(+), 57 deletions(-) delete mode 100644 service-api/src/main/java/greencity/enums/AchievementType.java diff --git a/service-api/src/main/java/greencity/enums/AchievementType.java b/service-api/src/main/java/greencity/enums/AchievementType.java deleted file mode 100644 index 6e9f82265a..0000000000 --- a/service-api/src/main/java/greencity/enums/AchievementType.java +++ /dev/null @@ -1,7 +0,0 @@ -package greencity.enums; - -public enum AchievementType { - INCREMENT, - SETTER, - COMPARISON -} diff --git a/service-api/src/main/java/greencity/service/AchievementService.java b/service-api/src/main/java/greencity/service/AchievementService.java index aca3e83de6..84c9f5bc61 100644 --- a/service-api/src/main/java/greencity/service/AchievementService.java +++ b/service-api/src/main/java/greencity/service/AchievementService.java @@ -4,7 +4,6 @@ import greencity.dto.achievement.*; import greencity.dto.user.UserVO; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import org.springframework.data.domain.Pageable; import java.util.List; @@ -101,6 +100,5 @@ public interface AchievementService { /** * Method for achievement Calculation. */ - void calculateAchievements(Long id, AchievementType achievementType, - AchievementCategoryType achievementCategory, Integer size); + void calculateAchievements(Long id, AchievementCategoryType achievementCategory, Integer size); } diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 26b5a78702..da22c765ee 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -11,7 +11,6 @@ import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.repository.AchievementCategoryRepo; import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; @@ -28,7 +27,6 @@ import java.util.stream.Collectors; import static greencity.enums.AchievementStatus.ACTIVE; -import static greencity.enums.AchievementType.INCREMENT; @Component public class AchievementCalculation { @@ -75,17 +73,16 @@ public AchievementCalculation(RestClient restClient, * Method that changing user actions. {@link greencity.entity.UserAction} * * @param userId of {@link User} - * @param type of action * @param category {@link AchievementCategoryType} * @param count number of specific actions * @author Orest Mamchuk */ - public void calculateAchievement(Long userId, AchievementType type, + public void calculateAchievement(Long userId, AchievementCategoryType category, Integer count) { AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategoryVO.getId()); - count = checkType(type, userActionVO, count); + count = checkCount( userActionVO); userActionService.updateUserActions(userActionVO); checkAchievements(achievementCategoryVO.getId(), count, userId); } @@ -124,35 +121,21 @@ private void changeAchievementStatus(Long userId, Long achievementCategoryId, in achievementCategoryRepo.findByName(AchievementCategoryType.ACHIEVEMENT.toString()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategory.getId()); - int countAchievement = checkType(INCREMENT, userActionVO, count); - calculateAchievement(userId, INCREMENT, AchievementCategoryType.ACHIEVEMENT, countAchievement); + int countAchievement = checkCount( userActionVO); + calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, countAchievement); } /** * Method check achievement type. * - * @param type of action - * @param count number of specific actions * @return count action */ - private int checkType(AchievementType type, UserActionVO userActionVO, Integer count) { - switch (type) { - case INCREMENT: - count = userActionVO.getCount() + 1; - userActionVO.setCount(count); - break; - case SETTER: + private int checkCount( UserActionVO userActionVO) { + + int count = userActionVO.getCount() + 1; userActionVO.setCount(count); - break; - case COMPARISON: - if (userActionVO.getCount() < count) { - userActionVO.setCount(count); - } - break; - default: - throw new IllegalStateException("Unexpected value: " + type); - } + return count; } } diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index 63613619a3..d3af6650d0 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -14,7 +14,6 @@ import greencity.entity.UserAchievement; import greencity.entity.localization.AchievementTranslation; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.NotUpdatedException; @@ -221,9 +220,9 @@ public List findAchievementsWithStatusActive(Long userI * {@inheritDoc} */ @Override - public void calculateAchievements(Long id, AchievementType achievementType, + public void calculateAchievements(Long id, AchievementCategoryType achievementCategory, Integer size) { - achievementCalculation.calculateAchievement(id, achievementType, achievementCategory, size); + achievementCalculation.calculateAchievement(id, achievementCategory, size); } private List setAchievementNotifications( diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index 74cb66e6f0..07e2698a13 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -16,7 +16,6 @@ import greencity.entity.EcoNewsComment; import greencity.entity.User; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.enums.CommentStatus; import greencity.enums.Role; import greencity.exception.exceptions.BadRequestException; @@ -80,7 +79,7 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq } } CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(userVO.getId(), AchievementType.INCREMENT, + .calculateAchievement(userVO.getId(), AchievementCategoryType.COMMENT_OR_REPLY, 0)); String accessToken = httpServletRequest.getHeader(AUTHORIZATION); CompletableFuture.runAsync( diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 73daa77d0c..424517936d 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -18,7 +18,6 @@ import greencity.entity.*; import greencity.entity.localization.TagTranslation; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.enums.Role; import greencity.enums.CommentStatus; import greencity.enums.TagType; @@ -81,7 +80,7 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, AddEcoNewsDtoResponse addEcoNewsDtoResponse = modelMapper.map(toSave, AddEcoNewsDtoResponse.class); sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(toSave.getAuthor().getId(), AchievementType.INCREMENT, + .calculateAchievement(toSave.getAuthor().getId(), AchievementCategoryType.CREATE_NEWS, 0)); return addEcoNewsDtoResponse; } @@ -99,7 +98,7 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, EcoNewsGenericDto ecoNewsDto = getEcoNewsGenericDtoWithAllTags(toSave); sendEmailDto(ecoNewsDto, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(toSave.getAuthor().getId(), AchievementType.INCREMENT, + .calculateAchievement(toSave.getAuthor().getId(), AchievementCategoryType.CREATE_NEWS, 0)); return ecoNewsDto; } @@ -428,8 +427,7 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { CompletableFuture .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT, user, accessToken)); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementType.INCREMENT, - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, 0)); + .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, 0)); } /** diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index da05760062..625ccf7cd4 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -38,7 +38,6 @@ import greencity.entity.UserShoppingListItem; import greencity.entity.localization.ShoppingListItemTranslation; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.enums.HabitAssignStatus; import greencity.enums.ShoppingListItemStatus; @@ -747,13 +746,11 @@ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, int habitStreak = countNewHabitStreak(habitAssign.getHabitStatusCalendars()); habitAssign.setHabitStreak(habitStreak); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(userId, AchievementType.COMPARISON, + .calculateAchievement(userId, AchievementCategoryType.HABIT, habitStreak)); if (isHabitAcquired(habitAssign)) { habitAssign.setStatus(HabitAssignStatus.ACQUIRED); - CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(userId, AchievementType.INCREMENT, AchievementCategoryType.HABIT, 0)); } habitAssignRepo.save(habitAssign); } diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index d8479f85e6..9bdf3384f0 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -9,9 +9,9 @@ import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.repository.UserAchievementRepo; import greencity.service.*; +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.EnumSource; @@ -42,9 +42,8 @@ class AchievementCalculationTest { @InjectMocks private AchievementCalculation achievementCalculation; - @ParameterizedTest(name = "{index} => type=''{0}''") - @EnumSource(AchievementType.class) - void calculateAchievement(AchievementType type) { +@Test + void calculateAchievement() { AchievementCategoryVO achievementCategoryVO = ModelUtils.getAchievementCategoryVO(); AchievementCategoryVO achievementCategoryVO2 = ModelUtils.getAchievementCategoryVO(); achievementCategoryVO2.setId(2L); @@ -66,7 +65,7 @@ void calculateAchievement(AchievementType type) { when(userAchievementRepo.save(userAchievement)).thenReturn(userAchievement); when(achievementCategoryService.findByName("ACHIEVEMENT")).thenReturn(achievementCategoryVO2); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 2L)).thenReturn(userActionVO2); - achievementCalculation.calculateAchievement(1L, type, AchievementCategoryType.CREATE_NEWS, 1); + achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, 1); verify(userAchievementRepo).save(userAchievement); } } diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index ed7098001c..169962e268 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -16,7 +16,6 @@ import greencity.entity.UserAchievement; import greencity.entity.localization.AchievementTranslation; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotUpdatedException; import greencity.repository.AchievementRepo; @@ -249,10 +248,9 @@ void findAchievementsWithStatusActive() { @Test void calculateAchievement() { - achievementService.calculateAchievements(1L, AchievementType.INCREMENT, AchievementCategoryType.CREATE_NEWS, 1); + achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, 1); verify(achievementCalculation).calculateAchievement( anyLong(), - any(AchievementType.class), any(AchievementCategoryType.class), anyInt()); } From 68483ec8f86a89ed6a1f1be699138f3230609a2f Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Wed, 20 Sep 2023 10:34:34 +0300 Subject: [PATCH 12/51] Fixed Translation dto --- .../controller/AchievementController.java | 4 +--- core/src/test/java/greencity/ModelUtils.java | 15 +++++++------- .../controller/AchievementControllerTest.java | 4 +--- .../dto/achievement/AchievementPostDto.java | 2 +- ...VO.java => AchievementTranslationDto.java} | 9 +++------ .../dto/achievement/AchievementVO.java | 4 +--- .../AchievementCategoryVO.java | 3 --- .../achievement/AchievementCalculation.java | 10 +++++----- .../mapping/AchievementVOMapper.java | 20 ++++++++----------- .../service/AchievementServiceImpl.java | 8 ++++---- .../src/test/java/greencity/ModelUtils.java | 8 ++++---- .../AchievementCalculationTest.java | 2 +- .../mapping/AchievementVOMapperTest.java | 7 ++++--- .../service/AchievementServiceImplTest.java | 15 ++++---------- 14 files changed, 44 insertions(+), 67 deletions(-) rename service-api/src/main/java/greencity/dto/achievement/{AchievementTranslationVO.java => AchievementTranslationDto.java} (56%) diff --git a/core/src/main/java/greencity/controller/AchievementController.java b/core/src/main/java/greencity/controller/AchievementController.java index 6811de07fe..a1be828e3f 100644 --- a/core/src/main/java/greencity/controller/AchievementController.java +++ b/core/src/main/java/greencity/controller/AchievementController.java @@ -6,7 +6,6 @@ import greencity.dto.achievement.AchievementVO; import greencity.dto.user.UserVO; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.service.AchievementService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; @@ -76,10 +75,9 @@ public ResponseEntity> getNotification(@PathVariab }) @PostMapping("/calculate-achievement") public ResponseEntity calculateAchievements(@RequestParam Long id, - @RequestParam AchievementType setter, @RequestParam AchievementCategoryType socialNetwork, @RequestParam int size) { - achievementService.calculateAchievements(id, setter, socialNetwork, size); + achievementService.calculateAchievements(id, socialNetwork, size); return ResponseEntity.ok().build(); } } diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index 2097552545..be60441ad1 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -4,7 +4,7 @@ import greencity.constant.AppConstant; import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.AchievementPostDto; -import greencity.dto.achievement.AchievementTranslationVO; +import greencity.dto.achievement.AchievementTranslationDto; import greencity.dto.achievement.AchievementVO; import greencity.dto.achievement.UserAchievementVO; import greencity.dto.achievementcategory.AchievementCategoryDto; @@ -581,11 +581,11 @@ public static ShoppingListItemPostDto getShoppingListItemPostDto() { return new ShoppingListItemPostDto(getLanguageTranslationsDTOs(), new ShoppingListItemRequestDto(1L)); } - public static List getAchievementTranslationVOS() { + public static List getAchievementTranslationDtoS() { return Arrays.asList( - new AchievementTranslationVO(1L, getLanguageVO(), "title", "description", "message"), - new AchievementTranslationVO(2L, getLanguageVO(), "title", "description", "message"), - new AchievementTranslationVO(3L, getLanguageVO(), "title", "description", "message")); + new AchievementTranslationDto(1L, "title", "description"), + new AchievementTranslationDto(2L, "title", "description"), + new AchievementTranslationDto(3L, "title", "description")); } public static AchievementCategoryDto getAchievementCategoryDto() { @@ -593,12 +593,11 @@ public static AchievementCategoryDto getAchievementCategoryDto() { } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto(getAchievementTranslationVOS(), getAchievementCategoryDto(), 1); + return new AchievementPostDto(getAchievementTranslationDtoS(), getAchievementCategoryDto(), 1); } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, getAchievementTranslationVOS(), - Collections.singletonList(new UserAchievementVO()), + return new AchievementVO(1L, getAchievementTranslationDtoS(), new AchievementCategoryVO(1L, "name"), 1); } diff --git a/core/src/test/java/greencity/controller/AchievementControllerTest.java b/core/src/test/java/greencity/controller/AchievementControllerTest.java index a44204c850..2b7e2a36ff 100644 --- a/core/src/test/java/greencity/controller/AchievementControllerTest.java +++ b/core/src/test/java/greencity/controller/AchievementControllerTest.java @@ -1,7 +1,6 @@ package greencity.controller; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.service.AchievementService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,10 +48,9 @@ void findAllTest() throws Exception { void calculateAchievements() throws Exception { mockMvc.perform(post(achievementLink + "/calculate-achievement" + "?id=" + 1L - + "&setter=" + AchievementType.INCREMENT + "&socialNetwork=" + AchievementCategoryType.CREATE_NEWS + "&size=" + 1)).andExpect(status().isOk()); - verify(achievementService).calculateAchievements(1L, AchievementType.INCREMENT, + verify(achievementService).calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, 1); } diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java index 727c095b16..f1cc81abe6 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java @@ -11,7 +11,7 @@ @Setter @EqualsAndHashCode public class AchievementPostDto { - private List translations; + private List translations; private AchievementCategoryDto achievementCategory; diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationVO.java b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java similarity index 56% rename from service-api/src/main/java/greencity/dto/achievement/AchievementTranslationVO.java rename to service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java index 11dbdc2ca9..7cc546e263 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java @@ -9,14 +9,11 @@ @Setter @EqualsAndHashCode @Builder -public class AchievementTranslationVO { +public class AchievementTranslationDto { private Long id; - private LanguageVO language; + private String name; - private String title; + private String nameEng; - private String description; - - private String message; } diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java index 2141a20f96..cb25f0c167 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java @@ -16,9 +16,7 @@ public class AchievementVO { private Long id; - private List translations; - - private List userAchievements; + private List translations; @NotEmpty private AchievementCategoryVO achievementCategory; diff --git a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java index c11b9bc377..36f9c2cd84 100644 --- a/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java +++ b/service-api/src/main/java/greencity/dto/achievementcategory/AchievementCategoryVO.java @@ -1,11 +1,8 @@ package greencity.dto.achievementcategory; -import greencity.dto.achievement.AchievementVO; -import greencity.dto.useraction.UserActionVO; import lombok.*; import javax.validation.constraints.NotEmpty; -import java.util.List; @NoArgsConstructor @AllArgsConstructor diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index da22c765ee..d66d68480a 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -82,7 +82,7 @@ public void calculateAchievement(Long userId, AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategoryVO.getId()); - count = checkCount( userActionVO); + count = checkCount(userActionVO); userActionService.updateUserActions(userActionVO); checkAchievements(achievementCategoryVO.getId(), count, userId); } @@ -121,7 +121,7 @@ private void changeAchievementStatus(Long userId, Long achievementCategoryId, in achievementCategoryRepo.findByName(AchievementCategoryType.ACHIEVEMENT.toString()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategory.getId()); - int countAchievement = checkCount( userActionVO); + int countAchievement = checkCount(userActionVO); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, countAchievement); } @@ -131,10 +131,10 @@ private void changeAchievementStatus(Long userId, Long achievementCategoryId, in * * @return count action */ - private int checkCount( UserActionVO userActionVO) { + private int checkCount(UserActionVO userActionVO) { - int count = userActionVO.getCount() + 1; - userActionVO.setCount(count); + int count = userActionVO.getCount() + 1; + userActionVO.setCount(count); return count; } diff --git a/service/src/main/java/greencity/mapping/AchievementVOMapper.java b/service/src/main/java/greencity/mapping/AchievementVOMapper.java index adcf7c42d2..7674c53d5a 100644 --- a/service/src/main/java/greencity/mapping/AchievementVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementVOMapper.java @@ -1,6 +1,6 @@ package greencity.mapping; -import greencity.dto.achievement.AchievementTranslationVO; +import greencity.dto.achievement.AchievementTranslationDto; import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.language.LanguageVO; @@ -14,17 +14,13 @@ public class AchievementVOMapper extends AbstractConverter { @Override protected AchievementVO convert(Achievement achievement) { - List list = new ArrayList<>(); - achievement.getTranslations().forEach(achievementTranslation -> list.add(AchievementTranslationVO.builder() - .id(achievementTranslation.getId()) -// .title(achievementTranslation.getTitle()) -// .description(achievementTranslation.getDescription()) -// .message(achievementTranslation.getMessage()) -// .language(LanguageVO.builder() -// .id(achievementTranslation.getLanguage().getId()) -// .code(achievementTranslation.getLanguage().getCode()) -// .build()) - .build())); + List list = new ArrayList<>(); + achievement.getTranslations() + .forEach(achievementTranslation -> list.add(AchievementTranslationDto.builder() + .id(achievementTranslation.getId()) + .name(achievementTranslation.getName()) + .nameEng(achievementTranslation.getNameEng()) + .build())); return AchievementVO.builder() .id(achievement.getId()) .translations(list) diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index d3af6650d0..dc08451700 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -246,14 +246,14 @@ private List setAchievementNotifications( private void setTranslations(Achievement achievement, AchievementManagementDto achievementManagementDto) { achievement.getTranslations() .forEach(achievementTranslation -> { - AchievementTranslationVO achievementTranslationVO = achievementManagementDto + AchievementTranslationDto AchievementTranslationDto = achievementManagementDto .getTranslations().stream() // .filter(newTranslation -> newTranslation.getLanguage().getCode() // .equals(achievementTranslation.getLanguage().getCode())) .findFirst().get(); -// achievementTranslation.setTitle(achievementTranslationVO.getTitle()); -// achievementTranslation.setDescription(achievementTranslationVO.getDescription()); -// achievementTranslation.setMessage(achievementTranslationVO.getMessage()); +// achievementTranslation.setTitle(AchievementTranslationDto.getTitle()); +// achievementTranslation.setDescription(AchievementTranslationDto.getDescription()); +// achievementTranslation.setMessage(AchievementTranslationDto.getMessage()); }); } } diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index be5141d810..68398d4b40 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -9,7 +9,7 @@ import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.AchievementManagementDto; import greencity.dto.achievement.AchievementPostDto; -import greencity.dto.achievement.AchievementTranslationVO; +import greencity.dto.achievement.AchievementTranslationDto; import greencity.dto.achievement.AchievementVO; import greencity.dto.achievement.UserAchievementVO; import greencity.dto.achievement.UserVOAchievement; @@ -1387,7 +1387,7 @@ public static AchievementCategory getAchievementCategory() { } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, Collections.emptyList(), Collections.emptyList(), new AchievementCategoryVO(), 1); + return new AchievementVO(1L, Collections.emptyList(), new AchievementCategoryVO(), 1); } public static AchievementPostDto getAchievementPostDto() { @@ -1398,8 +1398,8 @@ public static AchievementCategoryDto getAchievementCategoryDto() { return new AchievementCategoryDto("Test"); } - public static AchievementTranslationVO getAchievementTranslationVO() { - return new AchievementTranslationVO(1L, getLanguageVO(), "Title", "Description", "Message"); + public static AchievementTranslationDto getAchievementTranslationDto() { + return new AchievementTranslationDto(1L, "Title", "Description"); } public static AchievementCategoryVO getAchievementCategoryVO() { diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index 9bdf3384f0..ae599e19e8 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -42,7 +42,7 @@ class AchievementCalculationTest { @InjectMocks private AchievementCalculation achievementCalculation; -@Test + @Test void calculateAchievement() { AchievementCategoryVO achievementCategoryVO = ModelUtils.getAchievementCategoryVO(); AchievementCategoryVO achievementCategoryVO2 = ModelUtils.getAchievementCategoryVO(); diff --git a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java index bf961bd2dc..a9d44c3f75 100644 --- a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java @@ -3,7 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import greencity.ModelUtils; -import greencity.dto.achievement.AchievementTranslationVO; +import greencity.dto.achievement.AchievementTranslationDto; import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.language.LanguageVO; @@ -23,11 +23,12 @@ class AchievementVOMapperTest { @Test void convert() { - List list = new ArrayList<>(); + List list = new ArrayList<>(); Achievement achievement = ModelUtils.getAchievement(); - achievement.getTranslations().forEach(achievementTranslation -> list.add(AchievementTranslationVO.builder() + achievement.getTranslations().forEach(achievementTranslation -> list.add(AchievementTranslationDto.builder() .id(achievementTranslation.getId()) + // .title(achievementTranslation.getTitle()) // .description(achievementTranslation.getDescription()) // .message(achievementTranslation.getMessage()) diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 169962e268..2f1c2328db 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -152,9 +152,9 @@ void updateTest() { achievement.setTranslations(Collections.singletonList(achievementTranslation)); AchievementPostDto achievementPostDto = ModelUtils.getAchievementPostDto(); AchievementManagementDto achievementManagementDto = ModelUtils.getAchievementManagementDto(); - AchievementTranslationVO achievementTranslationVO = ModelUtils.getAchievementTranslationVO(); - achievementManagementDto.setTranslations(Collections.singletonList(achievementTranslationVO)); - achievementPostDto.setTranslations(Collections.singletonList(ModelUtils.getAchievementTranslationVO())); + AchievementTranslationDto AchievementTranslationDto = ModelUtils.getAchievementTranslationDto(); + achievementManagementDto.setTranslations(Collections.singletonList(AchievementTranslationDto)); + achievementPostDto.setTranslations(Collections.singletonList(ModelUtils.getAchievementTranslationDto())); when(achievementRepo.findById(1L)).thenReturn(Optional.of(achievement)); when(achievementRepo.save(achievement)).thenReturn(achievement); when(modelMapper.map(achievement, AchievementPostDto.class)).thenReturn(achievementPostDto); @@ -228,13 +228,6 @@ void findAchievementsWithStatusActive() { .singletonList(AchievementTranslation.builder() .id(1L) .achievement(achievement) -// .message("test") -// .description("test") -// .title("test") -// .language(Language.builder() -// .id(1L) -// .code("ua") -// .build()) .build()); UserAchievement userAchievement = ModelUtils.getUserAchievement(); when(restClient.findById(1L)).thenReturn(userVO); @@ -248,7 +241,7 @@ void findAchievementsWithStatusActive() { @Test void calculateAchievement() { - achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, 1); + achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, 1); verify(achievementCalculation).calculateAchievement( anyLong(), any(AchievementCategoryType.class), From 9f4b6767c995d6697b9eed7626c69308bd22fe16 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Wed, 20 Sep 2023 10:53:08 +0300 Subject: [PATCH 13/51] Everything worked --- .../greencity/dto/achievement/AchievementTranslationDto.java | 1 + 1 file changed, 1 insertion(+) diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java index 7cc546e263..39f07fe6a3 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java @@ -15,5 +15,6 @@ public class AchievementTranslationDto { private String name; private String nameEng; + private Long achievement_id; } From 89e366d0a418c17c63b2b4816c47419334a48d65 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Wed, 20 Sep 2023 10:55:47 +0300 Subject: [PATCH 14/51] Fixed AchievementTranslationDto --- core/src/test/java/greencity/ModelUtils.java | 6 +++--- .../dto/achievement/AchievementTranslationDto.java | 3 --- service/src/test/java/greencity/ModelUtils.java | 2 +- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index be60441ad1..b7db16b762 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -583,9 +583,9 @@ public static ShoppingListItemPostDto getShoppingListItemPostDto() { public static List getAchievementTranslationDtoS() { return Arrays.asList( - new AchievementTranslationDto(1L, "title", "description"), - new AchievementTranslationDto(2L, "title", "description"), - new AchievementTranslationDto(3L, "title", "description")); + new AchievementTranslationDto(1L, "title", "description",1L), + new AchievementTranslationDto(2L, "title", "description",1L), + new AchievementTranslationDto(3L, "title", "description",1L)); } public static AchievementCategoryDto getAchievementCategoryDto() { diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java index 39f07fe6a3..5f3168fad0 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java @@ -11,10 +11,7 @@ @Builder public class AchievementTranslationDto { private Long id; - private String name; - private String nameEng; private Long achievement_id; - } diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 68398d4b40..403599868d 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1399,7 +1399,7 @@ public static AchievementCategoryDto getAchievementCategoryDto() { } public static AchievementTranslationDto getAchievementTranslationDto() { - return new AchievementTranslationDto(1L, "Title", "Description"); + return new AchievementTranslationDto(1L, "Title", "Description",1L); } public static AchievementCategoryVO getAchievementCategoryVO() { From 1908f99669f19a1daee12c80f0d4e033c612ce8b Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Wed, 20 Sep 2023 12:02:39 +0300 Subject: [PATCH 15/51] Fixed tests --- .../controller/AchievementController.java | 22 +--------- .../ManagementAchievementController.java | 16 -------- .../controller/AchievementControllerTest.java | 13 +----- .../AchievementTranslationRepo.java | 2 +- .../greencity/service/AchievementService.java | 10 +---- .../achievement/AchievementCalculation.java | 8 ++-- .../mapping/AchievementVOMapper.java | 1 + .../service/AchievementServiceImpl.java | 14 +------ .../service/EcoNewsCommentServiceImpl.java | 2 +- .../greencity/service/EcoNewsServiceImpl.java | 6 +-- .../service/HabitAssignServiceImpl.java | 3 +- .../src/test/java/greencity/ModelUtils.java | 4 +- .../AchievementCalculationTest.java | 27 ++++++++---- .../mapping/AchievementVOMapperTest.java | 41 ++++++++++--------- .../service/AchievementServiceImplTest.java | 36 +--------------- 15 files changed, 62 insertions(+), 143 deletions(-) diff --git a/core/src/main/java/greencity/controller/AchievementController.java b/core/src/main/java/greencity/controller/AchievementController.java index a1be828e3f..10bd55b8d3 100644 --- a/core/src/main/java/greencity/controller/AchievementController.java +++ b/core/src/main/java/greencity/controller/AchievementController.java @@ -47,23 +47,6 @@ public ResponseEntity> getAll() { return ResponseEntity.status(HttpStatus.OK).body(achievementService.findAll()); } - /** - * Method notifies of the achievement. - * - * @param userId of {@link UserVO} - * @return list {@link AchievementNotification} - */ - @ApiOperation(value = "Get all the achievements that need to notify.") - @ApiResponses(value = { - @ApiResponse(code = 200, message = HttpStatuses.OK), - @ApiResponse(code = 400, message = HttpStatuses.BAD_REQUEST), - @ApiResponse(code = 401, message = HttpStatuses.UNAUTHORIZED), - }) - @GetMapping("/notification/{userId}") - public ResponseEntity> getNotification(@PathVariable Long userId) { - return ResponseEntity.status(HttpStatus.OK).body(achievementService.findAchievementsWithStatusActive(userId)); - } - /** * Method for achievement calculation. */ @@ -75,9 +58,8 @@ public ResponseEntity> getNotification(@PathVariab }) @PostMapping("/calculate-achievement") public ResponseEntity calculateAchievements(@RequestParam Long id, - @RequestParam AchievementCategoryType socialNetwork, - @RequestParam int size) { - achievementService.calculateAchievements(id, socialNetwork, size); + @RequestParam AchievementCategoryType socialNetwork) { + achievementService.calculateAchievements(id, socialNetwork); return ResponseEntity.ok().build(); } } diff --git a/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java b/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java index 520cefca43..21ef11c2e3 100644 --- a/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java +++ b/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java @@ -53,22 +53,6 @@ public String getAllAchievement(@RequestParam(required = false, name = "query") return "core/management_achievement"; } - /** - * Method for creating {@link AchievementVO}. - * - * @param achievementPostDto dto for {@link AchievementVO} entity. - * @return {@link GenericResponseDto} with of operation and errors fields. - * @author Orest Mamchuk - */ - @PostMapping - @ResponseBody - public GenericResponseDto saveAchievement(@Valid @RequestBody AchievementPostDto achievementPostDto, - BindingResult bindingResult) { - if (!bindingResult.hasErrors()) { - achievementService.save(achievementPostDto); - } - return buildGenericResponseDto(bindingResult); - } /** * Method which deteles {@link AchievementVO} by given id. diff --git a/core/src/test/java/greencity/controller/AchievementControllerTest.java b/core/src/test/java/greencity/controller/AchievementControllerTest.java index 2b7e2a36ff..072bdff0b3 100644 --- a/core/src/test/java/greencity/controller/AchievementControllerTest.java +++ b/core/src/test/java/greencity/controller/AchievementControllerTest.java @@ -48,17 +48,8 @@ void findAllTest() throws Exception { void calculateAchievements() throws Exception { mockMvc.perform(post(achievementLink + "/calculate-achievement" + "?id=" + 1L - + "&socialNetwork=" + AchievementCategoryType.CREATE_NEWS - + "&size=" + 1)).andExpect(status().isOk()); + + "&socialNetwork=" + AchievementCategoryType.CREATE_NEWS)).andExpect(status().isOk()); verify(achievementService).calculateAchievements(1L, - AchievementCategoryType.CREATE_NEWS, 1); + AchievementCategoryType.CREATE_NEWS); } - - @Test - void getNotificationTest() throws Exception { - mockMvc.perform(get(achievementLink - + "/notification/{userId}", 1)).andExpect(status().isOk()); - verify(achievementService).findAchievementsWithStatusActive(1L); - } - } diff --git a/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java b/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java index 820665a05d..469046f92a 100644 --- a/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java +++ b/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java @@ -17,7 +17,7 @@ public interface AchievementTranslationRepo extends JpaRepository findAchievementsWithStatusActive(Long userId, Long langId); } diff --git a/service-api/src/main/java/greencity/service/AchievementService.java b/service-api/src/main/java/greencity/service/AchievementService.java index 84c9f5bc61..e0ad252201 100644 --- a/service-api/src/main/java/greencity/service/AchievementService.java +++ b/service-api/src/main/java/greencity/service/AchievementService.java @@ -89,16 +89,8 @@ public interface AchievementService { */ AchievementVO findByCategoryIdAndCondition(Long categoryId, Integer condition); - /** - * Method notifies of the achievement. - * - * @param userId of {@link UserVO} - * @return list {@link AchievementNotification} - */ - List findAchievementsWithStatusActive(Long userId); - /** * Method for achievement Calculation. */ - void calculateAchievements(Long id, AchievementCategoryType achievementCategory, Integer size); + void calculateAchievements(Long id, AchievementCategoryType achievementCategory); } diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index d66d68480a..7061f3231f 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -74,15 +74,14 @@ public AchievementCalculation(RestClient restClient, * * @param userId of {@link User} * @param category {@link AchievementCategoryType} - * @param count number of specific actions * @author Orest Mamchuk */ public void calculateAchievement(Long userId, - AchievementCategoryType category, Integer count) { + AchievementCategoryType category) { AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategoryVO.getId()); - count = checkCount(userActionVO); + Integer count = checkCount(userActionVO); userActionService.updateUserActions(userActionVO); checkAchievements(achievementCategoryVO.getId(), count, userId); } @@ -121,8 +120,7 @@ private void changeAchievementStatus(Long userId, Long achievementCategoryId, in achievementCategoryRepo.findByName(AchievementCategoryType.ACHIEVEMENT.toString()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategory.getId()); - int countAchievement = checkCount(userActionVO); - calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, countAchievement); + calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT); } diff --git a/service/src/main/java/greencity/mapping/AchievementVOMapper.java b/service/src/main/java/greencity/mapping/AchievementVOMapper.java index 7674c53d5a..0f1c290da8 100644 --- a/service/src/main/java/greencity/mapping/AchievementVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementVOMapper.java @@ -20,6 +20,7 @@ protected AchievementVO convert(Achievement achievement) { .id(achievementTranslation.getId()) .name(achievementTranslation.getName()) .nameEng(achievementTranslation.getNameEng()) + .achievement_id(achievementTranslation.getAchievement().getId()) .build())); return AchievementVO.builder() .id(achievement.getId()) diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index dc08451700..21ced13aa4 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -205,24 +205,14 @@ public AchievementVO findByCategoryIdAndCondition(Long categoryId, Integer condi return achievement != null ? modelMapper.map(achievement, AchievementVO.class) : null; } - /** - * {@inheritDoc} - */ - @Override - public List findAchievementsWithStatusActive(Long userId) { - UserVO user = restClient.findById(userId); - List translationList = achievementTranslationRepo - .findAchievementsWithStatusActive(userId, user.getLanguageVO().getId()); - return setAchievementNotifications(new ArrayList<>(), translationList, userId); - } /** * {@inheritDoc} */ @Override public void calculateAchievements(Long id, - AchievementCategoryType achievementCategory, Integer size) { - achievementCalculation.calculateAchievement(id, achievementCategory, size); + AchievementCategoryType achievementCategory) { + achievementCalculation.calculateAchievement(id, achievementCategory); } private List setAchievementNotifications( diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index 07e2698a13..7993bb6e48 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -80,7 +80,7 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq } CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, 0)); + AchievementCategoryType.COMMENT_OR_REPLY)); String accessToken = httpServletRequest.getHeader(AUTHORIZATION); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.ADD_COMMENT, userVO, accessToken)); diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 424517936d..7951a97177 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -81,7 +81,7 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, 0)); + AchievementCategoryType.CREATE_NEWS)); return addEcoNewsDtoResponse; } @@ -99,7 +99,7 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, sendEmailDto(ecoNewsDto, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, 0)); + AchievementCategoryType.CREATE_NEWS)); return ecoNewsDto; } @@ -427,7 +427,7 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { CompletableFuture .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT, user, accessToken)); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, 0)); + .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY)); } /** diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 625ccf7cd4..ff5835e3ab 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -746,8 +746,7 @@ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, int habitStreak = countNewHabitStreak(habitAssign.getHabitStatusCalendars()); habitAssign.setHabitStreak(habitStreak); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(userId, - AchievementCategoryType.HABIT, habitStreak)); + .calculateAchievement(userId, AchievementCategoryType.HABIT)); if (isHabitAcquired(habitAssign)) { habitAssign.setStatus(HabitAssignStatus.ACQUIRED); diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 403599868d..f70615bb8a 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1378,7 +1378,9 @@ public static AdvicePostDto getAdvicePostDto() { } public static Achievement getAchievement() { - return new Achievement(1L, Collections.singletonList(getAchievementTranslation()), Collections.emptyList(), + return new Achievement(1L, + null, + Collections.emptyList(), new AchievementCategory(), 1); } diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index ae599e19e8..9fdd3831a2 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -6,10 +6,14 @@ import greencity.dto.achievement.UserVOAchievement; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.useraction.UserActionVO; +import greencity.entity.AchievementCategory; import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; +import greencity.repository.AchievementCategoryRepo; +import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; +import greencity.repository.UserRepo; import greencity.service.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,7 +25,9 @@ import org.modelmapper.ModelMapper; import java.util.Collections; +import java.util.Optional; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -39,6 +45,12 @@ class AchievementCalculationTest { private ModelMapper modelMapper; @Mock private UserAchievementRepo userAchievementRepo; + @Mock + private AchievementRepo achievementRepo; + @Mock + private UserRepo userRepo; + @Mock + private AchievementCategoryRepo achievementCategoryRepo; @InjectMocks private AchievementCalculation achievementCalculation; @@ -58,14 +70,11 @@ void calculateAchievement() { when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) .thenReturn(achievementCategoryVO); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)).thenReturn(userActionVO); - when(userActionService.updateUserActions(userActionVO)).thenReturn(userActionVO); - when(restClient.findUserForAchievement(1L)).thenReturn(userVOAchievement); - when(achievementService.findByCategoryIdAndCondition(1L, 1)).thenReturn(achievementVO); - when(modelMapper.map(userVOAchievement, User.class)).thenReturn(user); - when(userAchievementRepo.save(userAchievement)).thenReturn(userAchievement); - when(achievementCategoryService.findByName("ACHIEVEMENT")).thenReturn(achievementCategoryVO2); - when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 2L)).thenReturn(userActionVO2); - achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, 1); - verify(userAchievementRepo).save(userAchievement); +//when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(),anyInt())).thenReturn(Optional.of(ModelUtils.getAchievement())); +// when(userRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getUser())); +// when(achievementCategoryRepo.findByName(anyString())).thenReturn(ModelUtils.getAchievementCategory()); + + + achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS); } } diff --git a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java index a9d44c3f75..77fe0b83ee 100644 --- a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java @@ -8,8 +8,13 @@ import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.language.LanguageVO; import greencity.entity.Achievement; + +import java.lang.reflect.Array; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; + +import greencity.entity.localization.AchievementTranslation; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -23,29 +28,27 @@ class AchievementVOMapperTest { @Test void convert() { + List list1 = Arrays.asList(ModelUtils.getAchievementTranslation()); List list = new ArrayList<>(); + list1 + .forEach(achievementTranslation -> list.add(AchievementTranslationDto.builder() + .id(achievementTranslation.getId()) + .name(achievementTranslation.getName()) + .nameEng(achievementTranslation.getNameEng()) + .achievement_id(achievementTranslation.getAchievement().getId()) + .build())); + ; Achievement achievement = ModelUtils.getAchievement(); - - achievement.getTranslations().forEach(achievementTranslation -> list.add(AchievementTranslationDto.builder() - .id(achievementTranslation.getId()) - -// .title(achievementTranslation.getTitle()) -// .description(achievementTranslation.getDescription()) -// .message(achievementTranslation.getMessage()) -// .language(LanguageVO.builder() -// .id(achievementTranslation.getLanguage().getId()) -// .code(achievementTranslation.getLanguage().getCode()) -// .build()) - .build())); + achievement.setTranslations(list1); AchievementVO expected = AchievementVO.builder() - .id(achievement.getId()) - .translations(list) - .achievementCategory(AchievementCategoryVO.builder() - .id(achievement.getAchievementCategory().getId()) - .name(achievement.getAchievementCategory().getName()) - .build()) - .build(); + .id(achievement.getId()) + .translations(list) + .achievementCategory(AchievementCategoryVO.builder() + .id(achievement.getAchievementCategory().getId()) + .name(achievement.getAchievementCategory().getName()) + .build()) + .build(); assertEquals(expected, achievementVOMapper.convert(achievement)); } diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 2f1c2328db..02a900dbb4 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -208,43 +208,11 @@ void findByCategoryIdAndCondition() { when(modelMapper.map(achievement, AchievementVO.class)).thenReturn(achievementVO); assertEquals(achievementVO, achievementService.findByCategoryIdAndCondition(1L, 1)); } - - @Test - void findAchievementsWithStatusActive() { - List achievementNotifications = - Collections.singletonList(AchievementNotification.builder() - .id(1L) - .message("test") - .description("test") - .title("test") - .build()); - UserVO userVO = ModelUtils.getUserVO(); - userVO.setLanguageVO(LanguageVO.builder() - .id(1L) - .code("ua") - .build()); - Achievement achievement = ModelUtils.getAchievement(); - List achievementTranslations = Collections - .singletonList(AchievementTranslation.builder() - .id(1L) - .achievement(achievement) - .build()); - UserAchievement userAchievement = ModelUtils.getUserAchievement(); - when(restClient.findById(1L)).thenReturn(userVO); - when(achievementTranslationRepo.findAchievementsWithStatusActive(1L, 1L)) - .thenReturn(achievementTranslations); - when(userAchievementRepo.getUserAchievementByIdAndAchievementId(1L, 1L)).thenReturn(userAchievement); - userAchievement.setNotified(true); - when(userAchievementRepo.save(userAchievement)).thenReturn(userAchievement); - assertEquals(achievementNotifications, achievementService.findAchievementsWithStatusActive(1L)); - } - @Test void calculateAchievement() { - achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, 1); + achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS); verify(achievementCalculation).calculateAchievement( anyLong(), - any(AchievementCategoryType.class), - anyInt()); + any(AchievementCategoryType.class)); } } From 42badac3343ff336efecfcc6acf16622a9c8f874 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Wed, 20 Sep 2023 23:01:33 +0300 Subject: [PATCH 16/51] Fixed translations table --- .../ManagementAchievementController.java | 16 +++++++++ .../greencity/entity/UserAchievement.java | 5 --- .../greencity/enums/AchievementStatus.java | 6 ---- .../AchievementTranslationRepo.java | 15 +-------- .../db/changelog/db.changelog-master.xml | 1 + ...drop-column-user_achievements-Spodaryk.xml | 11 +++++++ .../AchievementTranslationDto.java | 2 +- .../dto/achievement/UserAchievementVO.java | 3 -- .../greencity/enums/AchievementStatus.java | 6 ---- .../achievement/AchievementCalculation.java | 8 ----- .../mapping/AchievementPostDtoMapper.java | 33 +++++++++++++++++++ .../mapping/UserVOAchievementMapper.java | 1 - .../java/greencity/mapping/UserVOMapper.java | 1 - .../src/test/java/greencity/ModelUtils.java | 17 +++++----- .../mapping/UserVOAchievementMapperTest.java | 1 - .../greencity/mapping/UserVOMapperTest.java | 1 - .../service/AchievementServiceImplTest.java | 5 +++ 17 files changed, 76 insertions(+), 56 deletions(-) delete mode 100644 dao/src/main/java/greencity/enums/AchievementStatus.java create mode 100644 dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml delete mode 100644 service-api/src/main/java/greencity/enums/AchievementStatus.java create mode 100644 service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java diff --git a/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java b/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java index 21ef11c2e3..520cefca43 100644 --- a/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java +++ b/core/src/main/java/greencity/webcontroller/ManagementAchievementController.java @@ -53,6 +53,22 @@ public String getAllAchievement(@RequestParam(required = false, name = "query") return "core/management_achievement"; } + /** + * Method for creating {@link AchievementVO}. + * + * @param achievementPostDto dto for {@link AchievementVO} entity. + * @return {@link GenericResponseDto} with of operation and errors fields. + * @author Orest Mamchuk + */ + @PostMapping + @ResponseBody + public GenericResponseDto saveAchievement(@Valid @RequestBody AchievementPostDto achievementPostDto, + BindingResult bindingResult) { + if (!bindingResult.hasErrors()) { + achievementService.save(achievementPostDto); + } + return buildGenericResponseDto(bindingResult); + } /** * Method which deteles {@link AchievementVO} by given id. diff --git a/dao/src/main/java/greencity/entity/UserAchievement.java b/dao/src/main/java/greencity/entity/UserAchievement.java index 843de9b76c..5cfa530b8e 100644 --- a/dao/src/main/java/greencity/entity/UserAchievement.java +++ b/dao/src/main/java/greencity/entity/UserAchievement.java @@ -1,6 +1,5 @@ package greencity.entity; -import greencity.enums.AchievementStatus; import javax.persistence.*; import lombok.*; @@ -25,10 +24,6 @@ public class UserAchievement { @ManyToOne(fetch = FetchType.LAZY) private Achievement achievement; - @Column(nullable = false) - @Enumerated(value = EnumType.STRING) - private AchievementStatus achievementStatus = AchievementStatus.INACTIVE; - @Column private boolean notified; } diff --git a/dao/src/main/java/greencity/enums/AchievementStatus.java b/dao/src/main/java/greencity/enums/AchievementStatus.java deleted file mode 100644 index 01b8ea2984..0000000000 --- a/dao/src/main/java/greencity/enums/AchievementStatus.java +++ /dev/null @@ -1,6 +0,0 @@ -package greencity.enums; - -public enum AchievementStatus { - INACTIVE, - ACTIVE -} diff --git a/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java b/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java index 469046f92a..d93d324e77 100644 --- a/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java +++ b/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java @@ -7,17 +7,4 @@ import java.util.List; -public interface AchievementTranslationRepo extends JpaRepository { - /** - * Method finding achievements with status active and no notify. - * - * @param userId of {@link User} - * @param langId of {@link Long} - * @return list {@link AchievementTranslation} - */ - @Query(nativeQuery = true, value = "SELECT * FROM achievement_translations t inner join user_achievements u " - + "on t.achievement_id = u.achievement_id WHERE " - + "u.user_id =:userId AND u.achievement_status = 'ACTIVE' " - + "AND u.notified = FALSE ;") - List findAchievementsWithStatusActive(Long userId, Long langId); -} +public interface AchievementTranslationRepo extends JpaRepository { } diff --git a/dao/src/main/resources/db/changelog/db.changelog-master.xml b/dao/src/main/resources/db/changelog/db.changelog-master.xml index de1ebd683a..643ed36a37 100644 --- a/dao/src/main/resources/db/changelog/db.changelog-master.xml +++ b/dao/src/main/resources/db/changelog/db.changelog-master.xml @@ -178,5 +178,6 @@ + diff --git a/dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml new file mode 100644 index 0000000000..693c3b8232 --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java index 5f3168fad0..3890eb186d 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java @@ -13,5 +13,5 @@ public class AchievementTranslationDto { private Long id; private String name; private String nameEng; - private Long achievement_id; + private AchievementVO achievementVO; } diff --git a/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java index 113bd4f839..8b9fafce91 100644 --- a/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java @@ -1,7 +1,6 @@ package greencity.dto.achievement; import greencity.dto.user.UserVO; -import greencity.enums.AchievementStatus; import lombok.*; import javax.validation.constraints.NotEmpty; @@ -21,6 +20,4 @@ public class UserAchievementVO { @NotEmpty private AchievementVO achievement; - @NotEmpty - private AchievementStatus achievementStatus; } diff --git a/service-api/src/main/java/greencity/enums/AchievementStatus.java b/service-api/src/main/java/greencity/enums/AchievementStatus.java deleted file mode 100644 index 01b8ea2984..0000000000 --- a/service-api/src/main/java/greencity/enums/AchievementStatus.java +++ /dev/null @@ -1,6 +0,0 @@ -package greencity.enums; - -public enum AchievementStatus { - INACTIVE, - ACTIVE -} diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 7061f3231f..1d074db934 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -2,8 +2,6 @@ import greencity.client.RestClient; import greencity.dto.achievement.AchievementVO; -import greencity.dto.achievement.UserAchievementVO; -import greencity.dto.achievement.UserVOAchievement; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.Achievement; @@ -22,11 +20,6 @@ import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; -import java.util.Optional; -import java.util.List; -import java.util.stream.Collectors; - -import static greencity.enums.AchievementStatus.ACTIVE; @Component public class AchievementCalculation { @@ -113,7 +106,6 @@ private void changeAchievementStatus(Long userId, Long achievementCategoryId, in UserAchievement userAchievement = UserAchievement.builder() .achievement(achievement) .user(userRepo.findById(userId).get()) - .achievementStatus(ACTIVE) .build(); userAchievementRepo.save(userAchievement); AchievementCategory achievementCategory = diff --git a/service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java b/service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java new file mode 100644 index 0000000000..16b71c1c6f --- /dev/null +++ b/service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java @@ -0,0 +1,33 @@ +package greencity.mapping; + +import greencity.dto.achievement.AchievementPostDto; +import greencity.dto.achievement.AchievementTranslationDto; +import greencity.dto.achievement.AchievementVO; +import greencity.dto.achievementcategory.AchievementCategoryDto; +import greencity.dto.achievementcategory.AchievementCategoryVO; +import greencity.entity.Achievement; +import greencity.entity.AchievementCategory; +import greencity.entity.localization.AchievementTranslation; +import org.modelmapper.AbstractConverter; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class AchievementPostDtoMapper extends AbstractConverter { + @Override + protected Achievement convert(AchievementPostDto achievementPostDto) { + AchievementCategoryDto achievementCategoryDto=achievementPostDto.getAchievementCategory(); + List achievementTranslations=achievementPostDto + .getTranslations() + .stream() + .map(obj->AchievementTranslation.builder() + .achievement(Achievement) + .build()); + return Achievement.builder() + .achievementCategory(AchievementCategory.builder().name(achievementCategoryDto.getName()).build()) + .translations(achievementPostDto.getTranslations().) + .build(); + } +} diff --git a/service/src/main/java/greencity/mapping/UserVOAchievementMapper.java b/service/src/main/java/greencity/mapping/UserVOAchievementMapper.java index 453ba975be..f47603ef0c 100644 --- a/service/src/main/java/greencity/mapping/UserVOAchievementMapper.java +++ b/service/src/main/java/greencity/mapping/UserVOAchievementMapper.java @@ -20,7 +20,6 @@ protected UserVOAchievement convert(User user) { .userAchievements(user.getUserAchievements() != null ? user.getUserAchievements() .stream().map(userAchievement -> UserAchievementVO.builder() .id(userAchievement.getId()) - .achievementStatus(userAchievement.getAchievementStatus()) .user(UserVO.builder() .id(userAchievement.getUser().getId()) .build()) diff --git a/service/src/main/java/greencity/mapping/UserVOMapper.java b/service/src/main/java/greencity/mapping/UserVOMapper.java index 63f3b129f4..e81a73c369 100644 --- a/service/src/main/java/greencity/mapping/UserVOMapper.java +++ b/service/src/main/java/greencity/mapping/UserVOMapper.java @@ -79,7 +79,6 @@ protected UserVO convert(User user) { .userAchievements(user.getUserAchievements() != null ? user.getUserAchievements() .stream().map(userAchievement -> UserAchievementVO.builder() .id(userAchievement.getId()) - .achievementStatus(userAchievement.getAchievementStatus()) .user(UserVO.builder() .id(userAchievement.getUser().getId()) .build()) diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index f70615bb8a..7aca717bbd 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -166,7 +166,6 @@ import greencity.entity.localization.AdviceTranslation; import greencity.entity.localization.ShoppingListItemTranslation; import greencity.entity.localization.TagTranslation; -import greencity.enums.AchievementStatus; import greencity.enums.CommentStatus; import greencity.enums.EmailNotification; import greencity.enums.FactOfDayStatus; @@ -443,7 +442,7 @@ public static UserVO getUserVOWithData() { .userAchievements(List.of( UserAchievementVO.builder() .id(47L) - .achievementStatus(AchievementStatus.ACTIVE) + .user(UserVO.builder() .id(13L) .build()) @@ -453,7 +452,7 @@ public static UserVO getUserVOWithData() { .build(), UserAchievementVO.builder() .id(39L) - .achievementStatus(AchievementStatus.INACTIVE) + .user(UserVO.builder() .id(13L) .build()) @@ -1417,11 +1416,11 @@ public static AchievementTranslation getAchievementTranslation() { } public static UserAchievementVO getUserAchievementVO() { - return new UserAchievementVO(1L, getUserVO(), getAchievementVO(), AchievementStatus.ACTIVE); + return new UserAchievementVO(1L, getUserVO(), getAchievementVO() ); } public static UserAchievement getUserAchievement() { - return new UserAchievement(1L, getUser(), getAchievement(), AchievementStatus.ACTIVE, false); + return new UserAchievement(1L, getUser(), getAchievement(), false); } public static UserAction getUserAction() { @@ -1699,7 +1698,7 @@ public static UserVO createUserVO2() { .userAchievements(List.of( UserAchievementVO.builder() .id(47L) - .achievementStatus(AchievementStatus.ACTIVE) + .user(UserVO.builder() .id(1L) .build()) @@ -1709,7 +1708,7 @@ public static UserVO createUserVO2() { .build(), UserAchievementVO.builder() .id(39L) - .achievementStatus(AchievementStatus.INACTIVE) + .user(UserVO.builder() .id(1L) .build()) @@ -1777,7 +1776,7 @@ public static UserVO createUserVO2() { .userAchievements(List.of( UserAchievementVO.builder() .id(47L) - .achievementStatus(AchievementStatus.ACTIVE) + .user(UserVO.builder() .id(1L) .build()) @@ -1787,7 +1786,7 @@ public static UserVO createUserVO2() { .build(), UserAchievementVO.builder() .id(39L) - .achievementStatus(AchievementStatus.INACTIVE) + .user(UserVO.builder() .id(1L) .build()) diff --git a/service/src/test/java/greencity/mapping/UserVOAchievementMapperTest.java b/service/src/test/java/greencity/mapping/UserVOAchievementMapperTest.java index 7b5129367c..efe43fc422 100644 --- a/service/src/test/java/greencity/mapping/UserVOAchievementMapperTest.java +++ b/service/src/test/java/greencity/mapping/UserVOAchievementMapperTest.java @@ -33,7 +33,6 @@ void convert() { .userAchievements(user.getUserAchievements() != null ? user.getUserAchievements() .stream().map(userAchievement -> UserAchievementVO.builder() .id(userAchievement.getId()) - .achievementStatus(userAchievement.getAchievementStatus()) .user(UserVO.builder() .id(userAchievement.getUser().getId()) .build()) diff --git a/service/src/test/java/greencity/mapping/UserVOMapperTest.java b/service/src/test/java/greencity/mapping/UserVOMapperTest.java index 38bac291c5..5543cf3edd 100644 --- a/service/src/test/java/greencity/mapping/UserVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/UserVOMapperTest.java @@ -82,7 +82,6 @@ void convert() { .userAchievements(expected.getUserAchievements() != null ? expected.getUserAchievements() .stream().map(userAchievement -> UserAchievement.builder() .id(userAchievement.getId()) - .achievementStatus(userAchievement.getAchievementStatus()) .user(User.builder() .id(userAchievement.getUser().getId()) .build()) diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 02a900dbb4..afd293f401 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -25,6 +25,7 @@ import greencity.repository.AchievementTranslationRepo; import greencity.repository.UserAchievementRepo; +import greencity.repository.UserRepo; import org.junit.jupiter.api.Assertions; import static org.junit.jupiter.api.Assertions.*; @@ -64,6 +65,8 @@ class AchievementServiceImplTest { private AchievementServiceImpl achievementService; @Mock private AchievementTranslationRepo achievementTranslationRepo; + @Mock + private UserRepo userRepo; @Test void findAllWithEmptyListTest() { @@ -123,6 +126,8 @@ void saveTest() { List userActionVOS = new ArrayList<>(); userActionVOS.add(userActionVO); userVO.setUserActions(userActionVOS); + achievementVO.setTranslations(Arrays.asList(ModelUtils.getAchievementTranslationDto())); + achievementPostDto.setTranslations(Arrays.asList(ModelUtils.getAchievementTranslationDto())); when(modelMapper.map(achievementPostDto, Achievement.class)).thenReturn(achievement); when(achievementCategoryService.findByName("Test")).thenReturn(achievementCategoryVO); when(modelMapper.map(achievementCategoryVO, AchievementCategory.class)).thenReturn(achievementCategory); From 113f1c6bdb00ed7d9819b7757b7988b805faeaf6 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Wed, 20 Sep 2023 23:39:41 +0300 Subject: [PATCH 17/51] Deleted table achievement_translations --- core/src/test/java/greencity/ModelUtils.java | 13 +- .../java/greencity/entity/Achievement.java | 11 +- .../localization/AchievementTranslation.java | 30 --- .../AchievementTranslationRepo.java | 10 - .../db/changelog/db.changelog-master.xml | 4 +- ...lumn-achievement_translations-Spodaryk.xml | 17 -- .../ch-add-column-achievements-Spodaryk.xml | 16 +- .../ch-add-value-achievements-Spodaryk.xml | 209 +++++++++++++++++- ...lues-achievement_translations-Spodaryk.xml | 169 -------------- ...able-achievement_translations-Spodaryk.xml | 8 + ...lumn-achievement_translations-Spodaryk.xml | 11 - ...drop-column-user_achievements-Spodaryk.xml | 2 +- .../dto/achievement/AchievementPostDto.java | 1 - .../AchievementTranslationDto.java | 17 -- .../dto/achievement/AchievementVO.java | 4 +- .../mapping/AchievementPostDtoMapper.java | 33 --- .../mapping/AchievementVOMapper.java | 14 +- .../service/AchievementServiceImpl.java | 39 +--- .../src/test/java/greencity/ModelUtils.java | 16 +- .../mapping/AchievementVOMapperTest.java | 17 +- .../service/AchievementServiceImplTest.java | 17 +- 21 files changed, 263 insertions(+), 395 deletions(-) delete mode 100644 dao/src/main/java/greencity/entity/localization/AchievementTranslation.java delete mode 100644 dao/src/main/java/greencity/repository/AchievementTranslationRepo.java delete mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml delete mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml create mode 100644 dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml delete mode 100644 dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml delete mode 100644 service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java delete mode 100644 service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index b7db16b762..fca43453f3 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -4,7 +4,7 @@ import greencity.constant.AppConstant; import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.AchievementPostDto; -import greencity.dto.achievement.AchievementTranslationDto; + import greencity.dto.achievement.AchievementVO; import greencity.dto.achievement.UserAchievementVO; import greencity.dto.achievementcategory.AchievementCategoryDto; @@ -581,23 +581,16 @@ public static ShoppingListItemPostDto getShoppingListItemPostDto() { return new ShoppingListItemPostDto(getLanguageTranslationsDTOs(), new ShoppingListItemRequestDto(1L)); } - public static List getAchievementTranslationDtoS() { - return Arrays.asList( - new AchievementTranslationDto(1L, "title", "description",1L), - new AchievementTranslationDto(2L, "title", "description",1L), - new AchievementTranslationDto(3L, "title", "description",1L)); - } - public static AchievementCategoryDto getAchievementCategoryDto() { return new AchievementCategoryDto("name"); } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto(getAchievementTranslationDtoS(), getAchievementCategoryDto(), 1); + return new AchievementPostDto( getAchievementCategoryDto(), 1); } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, getAchievementTranslationDtoS(), + return new AchievementVO(1L, "Test","Test", new AchievementCategoryVO(1L, "name"), 1); } diff --git a/dao/src/main/java/greencity/entity/Achievement.java b/dao/src/main/java/greencity/entity/Achievement.java index a050bea47f..4bfbae35c0 100644 --- a/dao/src/main/java/greencity/entity/Achievement.java +++ b/dao/src/main/java/greencity/entity/Achievement.java @@ -1,6 +1,6 @@ package greencity.entity; -import greencity.entity.localization.AchievementTranslation; + import java.util.List; import javax.persistence.CascadeType; @@ -32,8 +32,13 @@ public class Achievement { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "achievement", fetch = FetchType.LAZY) - private List translations; + @Column(nullable = false, length = 300) + private String title; + + @Column(nullable = false, length = 300) + private String name; + @Column(nullable = false, length = 300) + private String nameEng; @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "achievement", fetch = FetchType.LAZY) private List userAchievements; diff --git a/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java b/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java deleted file mode 100644 index f11b6e8a0d..0000000000 --- a/dao/src/main/java/greencity/entity/localization/AchievementTranslation.java +++ /dev/null @@ -1,30 +0,0 @@ -package greencity.entity.localization; - -import greencity.entity.Achievement; -import greencity.entity.Language; -import lombok.*; -import lombok.experimental.SuperBuilder; - -import javax.persistence.*; - -@Entity -@Table(name = "achievement_translations") -@SuperBuilder -@EqualsAndHashCode(exclude = "achievement") -@NoArgsConstructor -@Getter -@Setter -@AllArgsConstructor -public class AchievementTranslation { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column(nullable = false, length = 300) - private String name; - @Column(nullable = false, length = 300) - private String nameEng; - - @ManyToOne - private Achievement achievement; -} diff --git a/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java b/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java deleted file mode 100644 index d93d324e77..0000000000 --- a/dao/src/main/java/greencity/repository/AchievementTranslationRepo.java +++ /dev/null @@ -1,10 +0,0 @@ -package greencity.repository; - -import greencity.entity.localization.AchievementTranslation; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import greencity.entity.User; - -import java.util.List; - -public interface AchievementTranslationRepo extends JpaRepository { } diff --git a/dao/src/main/resources/db/changelog/db.changelog-master.xml b/dao/src/main/resources/db/changelog/db.changelog-master.xml index 643ed36a37..25fcc3e888 100644 --- a/dao/src/main/resources/db/changelog/db.changelog-master.xml +++ b/dao/src/main/resources/db/changelog/db.changelog-master.xml @@ -175,9 +175,7 @@ - - - + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml deleted file mode 100644 index ba0eea0c2a..0000000000 --- a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievement_translations-Spodaryk.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml index a9a35edc07..3f08ac7903 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml @@ -15,7 +15,21 @@ - + + + + + + + + + + + + + + + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml index f36fa1e003..1fa9928565 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml @@ -4,6 +4,213 @@ xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd"> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml deleted file mode 100644 index eddd6c0230..0000000000 --- a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_translations-Spodaryk.xml +++ /dev/null @@ -1,169 +0,0 @@ - - - - - -- Acquired Habits - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Набуття звички протягом 14 днів', 'Acquired habit 14 days' - FROM achievements a - WHERE a.name = 'ACQUIRED_HABIT_14_DAYS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Набуття звички протягом 21 днів', 'Acquired habit 21 days' - FROM achievements a - WHERE a.name = 'ACQUIRED_HABIT_21_DAYS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Набуття звички протягом 30 днів', 'Acquired habit 30 days' - FROM achievements a - WHERE a.name = 'ACQUIRED_HABIT_30_DAYS'; - - -- Created News - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Створено 5 новин', 'Created 5 news' - FROM achievements a - WHERE a.name = 'CREATED_5_NEWS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Створено 10 новин', 'Created 10 news' - FROM achievements a - WHERE a.name = 'CREATED_10_NEWS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Створено 25 новин', 'Created 25 news' - FROM achievements a - WHERE a.name = 'CREATED_25_NEWS'; - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Створено 50 новин', 'Created 50 news' - FROM achievements a - WHERE a.name = 'CREATED_50_NEWS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Створено 100 новин', 'Created 100 news' - FROM achievements a - WHERE a.name = 'CREATED_100_NEWS'; - - -- Comment or Reply - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Залишено коментар або відповідь 1 раз', 'Comment or reply 1 time' - FROM achievements a - WHERE a.name = 'COMMENT_OR_REPLY_1_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Залишено коментар або відповідь 5 разів', 'Comment or reply 5 times' - FROM achievements a - WHERE a.name = 'COMMENT_OR_REPLY_5_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Залишено коментар або відповідь 10 разів', 'Comment or reply 10 times' - FROM achievements a - WHERE a.name = 'COMMENT_OR_REPLY_10_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Залишено коментар або відповідь 25 разів', 'Comment or reply 25 times' - FROM achievements a - WHERE a.name = 'COMMENT_OR_REPLY_25_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Залишено коментар або відповідь 50 разів', 'Comment or reply 50 times' - FROM achievements a - WHERE a.name = 'COMMENT_OR_REPLY_50_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Залишено коментар або відповідь 100 разів', 'Comment or reply 100 times' - FROM achievements a - WHERE a.name = 'COMMENT_OR_REPLY_100_TIMES'; - - -- Like Comment or Reply - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Лайк коментаря або відповіді 1 раз', 'Like comment or reply 1 time' - FROM achievements a - WHERE a.name = 'LIKE_COMMENT_OR_REPLY_1_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Лайк коментаря або відповіді 5 разів', 'Like comment or reply 5 times' - FROM achievements a - WHERE a.name = 'LIKE_COMMENT_OR_REPLY_5_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Лайк коментаря або відповіді 10 разів', 'Like comment or reply 10 times' - FROM achievements a - WHERE a.name = 'LIKE_COMMENT_OR_REPLY_10_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Лайк коментаря або відповіді 25 разів', 'Like comment or reply 25 times' - FROM achievements a - WHERE a.name = 'LIKE_COMMENT_OR_REPLY_25_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Лайк коментаря або відповіді 50 разів', 'Like comment or reply 50 times' - FROM achievements a - WHERE a.name = 'LIKE_COMMENT_OR_REPLY_50_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Лайк коментаря або відповіді 100 разів', 'Like comment or reply 100 times' - FROM achievements a - WHERE a.name = 'LIKE_COMMENT_OR_REPLY_100_TIMES'; - - -- Share News - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Поширено 1 новину', 'Shared 1 news' - FROM achievements a - WHERE a.name = 'SHARE_NEWS_1_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Поширено 5 новин', 'Shared 5 news' - FROM achievements a - WHERE a.name = 'SHARE_NEWS_5_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Поширено 10 новин', 'Shared 10 news' - FROM achievements a - WHERE a.name = 'SHARE_NEWS_10_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Поширено 25 новин', 'Shared 25 news' - FROM achievements a - WHERE a.name = 'SHARE_NEWS_25_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Поширено 50 новин', 'Shared 50 news' - FROM achievements a - WHERE a.name = 'SHARE_NEWS_50_TIMES'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Поширено 100 новин', 'Shared 100 news' - FROM achievements a - WHERE a.name = 'SHARE_NEWS_100_TIMES'; - - -- First Achievements - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Перші 5 досягнень', 'First 5 achievements' - FROM achievements a - WHERE a.name = 'FIRST_5_ACHIEVEMENTS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Перші 10 досягнень', 'First 10 achievements' - FROM achievements a - WHERE a.name = 'FIRST_10_ACHIEVEMENTS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Перші 25 досягнень', 'First 25 achievements' - FROM achievements a - WHERE a.name = 'FIRST_25_ACHIEVEMENTS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Перші 50 досягнень', 'First 50 achievements' - FROM achievements a - WHERE a.name = 'FIRST_50_ACHIEVEMENTS'; - - INSERT INTO achievement_translations (achievement_id, name, name_eng) - SELECT a.id, 'Перші 100 досягнень', 'First 100 achievements' - FROM achievements a - WHERE a.name = 'FIRST_100_ACHIEVEMENTS'; - - - diff --git a/dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml new file mode 100644 index 0000000000..aed248f722 --- /dev/null +++ b/dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml deleted file mode 100644 index 525b6f979f..0000000000 --- a/dao/src/main/resources/db/changelog/logs/ch-drop-column-achievement_translations-Spodaryk.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - diff --git a/dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml index 693c3b8232..63376677cf 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-drop-column-user_achievements-Spodaryk.xml @@ -2,7 +2,7 @@ - + diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java index f1cc81abe6..cc5ad94209 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java @@ -11,7 +11,6 @@ @Setter @EqualsAndHashCode public class AchievementPostDto { - private List translations; private AchievementCategoryDto achievementCategory; diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java deleted file mode 100644 index 3890eb186d..0000000000 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementTranslationDto.java +++ /dev/null @@ -1,17 +0,0 @@ -package greencity.dto.achievement; - -import greencity.dto.language.LanguageVO; -import lombok.*; - -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -@Builder -public class AchievementTranslationDto { - private Long id; - private String name; - private String nameEng; - private AchievementVO achievementVO; -} diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java index cb25f0c167..8cd60d6cdf 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java @@ -16,8 +16,8 @@ public class AchievementVO { private Long id; - private List translations; - + private String name; + private String nameEng; @NotEmpty private AchievementCategoryVO achievementCategory; diff --git a/service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java b/service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java deleted file mode 100644 index 16b71c1c6f..0000000000 --- a/service/src/main/java/greencity/mapping/AchievementPostDtoMapper.java +++ /dev/null @@ -1,33 +0,0 @@ -package greencity.mapping; - -import greencity.dto.achievement.AchievementPostDto; -import greencity.dto.achievement.AchievementTranslationDto; -import greencity.dto.achievement.AchievementVO; -import greencity.dto.achievementcategory.AchievementCategoryDto; -import greencity.dto.achievementcategory.AchievementCategoryVO; -import greencity.entity.Achievement; -import greencity.entity.AchievementCategory; -import greencity.entity.localization.AchievementTranslation; -import org.modelmapper.AbstractConverter; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.List; - -@Component -public class AchievementPostDtoMapper extends AbstractConverter { - @Override - protected Achievement convert(AchievementPostDto achievementPostDto) { - AchievementCategoryDto achievementCategoryDto=achievementPostDto.getAchievementCategory(); - List achievementTranslations=achievementPostDto - .getTranslations() - .stream() - .map(obj->AchievementTranslation.builder() - .achievement(Achievement) - .build()); - return Achievement.builder() - .achievementCategory(AchievementCategory.builder().name(achievementCategoryDto.getName()).build()) - .translations(achievementPostDto.getTranslations().) - .build(); - } -} diff --git a/service/src/main/java/greencity/mapping/AchievementVOMapper.java b/service/src/main/java/greencity/mapping/AchievementVOMapper.java index 0f1c290da8..2a3686dc37 100644 --- a/service/src/main/java/greencity/mapping/AchievementVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementVOMapper.java @@ -1,6 +1,6 @@ package greencity.mapping; -import greencity.dto.achievement.AchievementTranslationDto; + import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.language.LanguageVO; @@ -14,17 +14,11 @@ public class AchievementVOMapper extends AbstractConverter { @Override protected AchievementVO convert(Achievement achievement) { - List list = new ArrayList<>(); - achievement.getTranslations() - .forEach(achievementTranslation -> list.add(AchievementTranslationDto.builder() - .id(achievementTranslation.getId()) - .name(achievementTranslation.getName()) - .nameEng(achievementTranslation.getNameEng()) - .achievement_id(achievementTranslation.getAchievement().getId()) - .build())); return AchievementVO.builder() .id(achievement.getId()) - .translations(list) + .name(achievement.getName()) + .nameEng(achievement.getNameEng()) + .condition(achievement.getCondition()) .achievementCategory(AchievementCategoryVO.builder() .id(achievement.getAchievementCategory().getId()) .name(achievement.getAchievementCategory().getName()) diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index 21ced13aa4..94677b3bd2 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -12,13 +12,13 @@ import greencity.entity.Achievement; import greencity.entity.AchievementCategory; import greencity.entity.UserAchievement; -import greencity.entity.localization.AchievementTranslation; + import greencity.enums.AchievementCategoryType; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.NotUpdatedException; import greencity.repository.AchievementRepo; -import greencity.repository.AchievementTranslationRepo; + import greencity.repository.UserAchievementRepo; import java.util.ArrayList; @@ -46,7 +46,6 @@ public class AchievementServiceImpl implements AchievementService { private final UserActionService userActionService; private UserAchievementRepo userAchievementRepo; private AchievementCalculation achievementCalculation; - private final AchievementTranslationRepo achievementTranslationRepo; /** * {@inheritDoc} @@ -58,7 +57,6 @@ public AchievementVO save(AchievementPostDto achievementPostDto) { Achievement achievement = modelMapper.map(achievementPostDto, Achievement.class); AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(achievementPostDto.getAchievementCategory().getName()); - achievement.getTranslations().forEach(adviceTranslation -> adviceTranslation.setAchievement(achievement)); achievement.setAchievementCategory(modelMapper.map(achievementCategoryVO, AchievementCategory.class)); AchievementVO achievementVO = modelMapper.map(achievementRepo.save(achievement), AchievementVO.class); UserAchievementVO userAchievementVO = new UserAchievementVO(); @@ -187,7 +185,6 @@ public AchievementPostDto update(AchievementManagementDto achievementManagementD Achievement achievement = achievementRepo.findById(achievementManagementDto.getId()) .orElseThrow(() -> new NotUpdatedException(ErrorMessage.ACHIEVEMENT_NOT_FOUND_BY_ID + achievementManagementDto.getId())); - setTranslations(achievement, achievementManagementDto); Achievement updated = achievementRepo.save(achievement); return modelMapper.map(updated, AchievementPostDto.class); } @@ -214,36 +211,4 @@ public void calculateAchievements(Long id, AchievementCategoryType achievementCategory) { achievementCalculation.calculateAchievement(id, achievementCategory); } - - private List setAchievementNotifications( - List achievementNotifications, - List translationList, Long userId) { - translationList.forEach(translation -> { - achievementNotifications.add(AchievementNotification.builder() - .id(translation.getId()) -// .title(translation.getTitle()) -// .description(translation.getDescription()) -// .message(translation.getMessage()) - .build()); - UserAchievement userAchievement = userAchievementRepo - .getUserAchievementByIdAndAchievementId(userId, translation.getAchievement().getId()); - userAchievement.setNotified(true); - userAchievementRepo.save(userAchievement); - }); - return achievementNotifications; - } - - private void setTranslations(Achievement achievement, AchievementManagementDto achievementManagementDto) { - achievement.getTranslations() - .forEach(achievementTranslation -> { - AchievementTranslationDto AchievementTranslationDto = achievementManagementDto - .getTranslations().stream() -// .filter(newTranslation -> newTranslation.getLanguage().getCode() -// .equals(achievementTranslation.getLanguage().getCode())) - .findFirst().get(); -// achievementTranslation.setTitle(AchievementTranslationDto.getTitle()); -// achievementTranslation.setDescription(AchievementTranslationDto.getDescription()); -// achievementTranslation.setMessage(AchievementTranslationDto.getMessage()); - }); - } } diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 7aca717bbd..5a4ce96276 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -9,7 +9,7 @@ import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.AchievementManagementDto; import greencity.dto.achievement.AchievementPostDto; -import greencity.dto.achievement.AchievementTranslationDto; + import greencity.dto.achievement.AchievementVO; import greencity.dto.achievement.UserAchievementVO; import greencity.dto.achievement.UserVOAchievement; @@ -162,7 +162,7 @@ import greencity.entity.event.EventComment; import greencity.entity.event.EventDateLocation; import greencity.entity.event.EventGrade; -import greencity.entity.localization.AchievementTranslation; + import greencity.entity.localization.AdviceTranslation; import greencity.entity.localization.ShoppingListItemTranslation; import greencity.entity.localization.TagTranslation; @@ -1378,7 +1378,7 @@ public static AdvicePostDto getAdvicePostDto() { public static Achievement getAchievement() { return new Achievement(1L, - null, + "Test","Test", "Test", Collections.emptyList(), new AchievementCategory(), 1); } @@ -1388,20 +1388,17 @@ public static AchievementCategory getAchievementCategory() { } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, Collections.emptyList(), new AchievementCategoryVO(), 1); + return new AchievementVO(1L,"Test","Test",new AchievementCategoryVO(), 1); } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto(Collections.emptyList(), getAchievementCategoryDto(), 1); + return new AchievementPostDto(getAchievementCategoryDto(), 1); } public static AchievementCategoryDto getAchievementCategoryDto() { return new AchievementCategoryDto("Test"); } - public static AchievementTranslationDto getAchievementTranslationDto() { - return new AchievementTranslationDto(1L, "Title", "Description",1L); - } public static AchievementCategoryVO getAchievementCategoryVO() { return new AchievementCategoryVO(1L, "Category"); @@ -1411,9 +1408,6 @@ public static AchievementManagementDto getAchievementManagementDto() { return new AchievementManagementDto(1L); } - public static AchievementTranslation getAchievementTranslation() { - return new AchievementTranslation(1L, "Title", "Description", getAchievement()); - } public static UserAchievementVO getUserAchievementVO() { return new UserAchievementVO(1L, getUserVO(), getAchievementVO() ); diff --git a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java index 77fe0b83ee..fad0224450 100644 --- a/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementVOMapperTest.java @@ -3,7 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import greencity.ModelUtils; -import greencity.dto.achievement.AchievementTranslationDto; + import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.language.LanguageVO; @@ -14,7 +14,7 @@ import java.util.Arrays; import java.util.List; -import greencity.entity.localization.AchievementTranslation; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -28,22 +28,9 @@ class AchievementVOMapperTest { @Test void convert() { - List list1 = Arrays.asList(ModelUtils.getAchievementTranslation()); - List list = new ArrayList<>(); - list1 - .forEach(achievementTranslation -> list.add(AchievementTranslationDto.builder() - .id(achievementTranslation.getId()) - .name(achievementTranslation.getName()) - .nameEng(achievementTranslation.getNameEng()) - .achievement_id(achievementTranslation.getAchievement().getId()) - .build())); - ; Achievement achievement = ModelUtils.getAchievement(); - achievement.setTranslations(list1); - AchievementVO expected = AchievementVO.builder() .id(achievement.getId()) - .translations(list) .achievementCategory(AchievementCategoryVO.builder() .id(achievement.getAchievementCategory().getId()) .name(achievement.getAchievementCategory().getName()) diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index afd293f401..537df72fe0 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -14,7 +14,7 @@ import greencity.entity.AchievementCategory; import greencity.entity.Language; import greencity.entity.UserAchievement; -import greencity.entity.localization.AchievementTranslation; + import greencity.enums.AchievementCategoryType; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotUpdatedException; @@ -23,7 +23,7 @@ import java.util.*; import java.util.stream.Collectors; -import greencity.repository.AchievementTranslationRepo; + import greencity.repository.UserAchievementRepo; import greencity.repository.UserRepo; import org.junit.jupiter.api.Assertions; @@ -64,8 +64,6 @@ class AchievementServiceImplTest { @InjectMocks private AchievementServiceImpl achievementService; @Mock - private AchievementTranslationRepo achievementTranslationRepo; - @Mock private UserRepo userRepo; @Test @@ -126,8 +124,6 @@ void saveTest() { List userActionVOS = new ArrayList<>(); userActionVOS.add(userActionVO); userVO.setUserActions(userActionVOS); - achievementVO.setTranslations(Arrays.asList(ModelUtils.getAchievementTranslationDto())); - achievementPostDto.setTranslations(Arrays.asList(ModelUtils.getAchievementTranslationDto())); when(modelMapper.map(achievementPostDto, Achievement.class)).thenReturn(achievement); when(achievementCategoryService.findByName("Test")).thenReturn(achievementCategoryVO); when(modelMapper.map(achievementCategoryVO, AchievementCategory.class)).thenReturn(achievementCategory); @@ -153,14 +149,9 @@ void findByIdTest() { @Test void updateTest() { Achievement achievement = ModelUtils.getAchievement(); - AchievementTranslation achievementTranslation = ModelUtils.getAchievementTranslation(); - achievement.setTranslations(Collections.singletonList(achievementTranslation)); - AchievementPostDto achievementPostDto = ModelUtils.getAchievementPostDto(); + AchievementPostDto achievementPostDto = ModelUtils.getAchievementPostDto(); AchievementManagementDto achievementManagementDto = ModelUtils.getAchievementManagementDto(); - AchievementTranslationDto AchievementTranslationDto = ModelUtils.getAchievementTranslationDto(); - achievementManagementDto.setTranslations(Collections.singletonList(AchievementTranslationDto)); - achievementPostDto.setTranslations(Collections.singletonList(ModelUtils.getAchievementTranslationDto())); - when(achievementRepo.findById(1L)).thenReturn(Optional.of(achievement)); + when(achievementRepo.findById(1L)).thenReturn(Optional.of(achievement)); when(achievementRepo.save(achievement)).thenReturn(achievement); when(modelMapper.map(achievement, AchievementPostDto.class)).thenReturn(achievementPostDto); AchievementPostDto expected = achievementService.update(achievementManagementDto); From 73e69dec15ec66df89304bb08a23964b9784ade7 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Thu, 21 Sep 2023 10:34:14 +0300 Subject: [PATCH 18/51] Fixed tests and deleted translation table+ changed mapper --- core/src/test/java/greencity/ModelUtils.java | 4 +- .../ManagementAchievementControllerTest.java | 3 - .../greencity/repository/AchievementRepo.java | 17 +- .../ch-add-column-achievements-Spodaryk.xml | 13 +- .../ch-add-value-achievements-Spodaryk.xml | 201 +----------------- .../functions/insert-values-achievements.sql | 145 ++++++++----- .../dto/achievement/AchievementPostDto.java | 3 + .../dto/achievement/AchievementVO.java | 1 + .../mapping/AchievementVOMapper.java | 5 +- .../service/AchievementServiceImpl.java | 5 + .../src/test/java/greencity/ModelUtils.java | 4 +- .../mapping/AchievementVOMapperTest.java | 5 +- .../service/AchievementServiceImplTest.java | 12 +- 13 files changed, 111 insertions(+), 307 deletions(-) diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index fca43453f3..04ae7c46b7 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -586,11 +586,11 @@ public static AchievementCategoryDto getAchievementCategoryDto() { } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto( getAchievementCategoryDto(), 1); + return new AchievementPostDto( "Test","Test","Test",getAchievementCategoryDto(), 1); } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, "Test","Test", + return new AchievementVO(1L, "Test", "Test","Test", new AchievementCategoryVO(1L, "name"), 1); } diff --git a/core/src/test/java/greencity/webcontroller/ManagementAchievementControllerTest.java b/core/src/test/java/greencity/webcontroller/ManagementAchievementControllerTest.java index e46b67e7e3..cdae8f90f3 100644 --- a/core/src/test/java/greencity/webcontroller/ManagementAchievementControllerTest.java +++ b/core/src/test/java/greencity/webcontroller/ManagementAchievementControllerTest.java @@ -111,9 +111,6 @@ void getAllAchievementSearchByQueryTest() throws Exception { @Test void saveAchievementTest() throws Exception { -// String accessToken = "accessToken"; -// HttpHeaders headers = new HttpHeaders(); -// headers.set(AUTHORIZATION, accessToken); AchievementPostDto achievementPostDto = ModelUtils.getAchievementPostDto(); String content = objectMapper.writeValueAsString(achievementPostDto); this.mockMvc.perform(post(link) diff --git a/dao/src/main/java/greencity/repository/AchievementRepo.java b/dao/src/main/java/greencity/repository/AchievementRepo.java index 1f781f9442..6425fc32e3 100644 --- a/dao/src/main/java/greencity/repository/AchievementRepo.java +++ b/dao/src/main/java/greencity/repository/AchievementRepo.java @@ -11,22 +11,7 @@ @Repository public interface AchievementRepo extends JpaRepository { - /** - * Method returns {@link Achievement} by search query and page. - * - * @param paging {@link Pageable}. - * @param query query to search. - * @return list of {@link Achievement}. - * @author Orest Mamchuk - */ - @Query("SELECT DISTINCT a FROM Achievement a " - + "JOIN AchievementTranslation at on at.achievement.id = a.id " - + "WHERE CONCAT(a.id,'') LIKE LOWER(CONCAT('%', :query, '%')) " -// + "OR LOWER(at.title) LIKE LOWER(CONCAT('%', :query, '%'))" -// + "OR LOWER(at.description) LIKE LOWER(CONCAT('%', :query, '%'))" -// + "OR LOWER(at.message) LIKE LOWER(CONCAT('%', :query, '%'))" - + "OR LOWER(a.achievementCategory.name) LIKE LOWER(CONCAT('%', :query, '%'))" - + "OR CONCAT(a.condition, ' ') LIKE LOWER(CONCAT('%', :query, '%'))") + Page searchAchievementsBy(Pageable paging, String query); /** diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml index 3f08ac7903..609532902b 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml @@ -3,18 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd"> - - - - - - - - - - - - + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml index 1fa9928565..1012a0bb2c 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml @@ -10,207 +10,8 @@ - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dao/src/main/resources/db/functions/insert-values-achievements.sql b/dao/src/main/resources/db/functions/insert-values-achievements.sql index 997316910b..14a9505230 100644 --- a/dao/src/main/resources/db/functions/insert-values-achievements.sql +++ b/dao/src/main/resources/db/functions/insert-values-achievements.sql @@ -1,68 +1,99 @@ -DO $$ +DO +$$ DECLARE habit_id INTEGER; - create_news_id INTEGER; - comment_or_reply_id INTEGER; - like_comment_or_reply_id INTEGER; - share_news_id INTEGER; - achievement_id INTEGER; + create_news_id +INTEGER; + comment_or_reply_id +INTEGER; + like_comment_or_reply_id +INTEGER; + share_news_id +INTEGER; + achievement_id +INTEGER; BEGIN - -- Acquire IDs from achievement_categories -SELECT id INTO habit_id FROM achievement_categories WHERE name = 'HABIT'; -SELECT id INTO create_news_id FROM achievement_categories WHERE name = 'CREATE_NEWS'; -SELECT id INTO comment_or_reply_id FROM achievement_categories WHERE name = 'COMMENT_OR_REPLY'; -SELECT id INTO like_comment_or_reply_id FROM achievement_categories WHERE name = 'LIKE_COMMENT_OR_REPLY'; -SELECT id INTO share_news_id FROM achievement_categories WHERE name = 'SHARE_NEWS'; -SELECT id INTO achievement_id FROM achievement_categories WHERE name = 'ACHIEVEMENT'; +SELECT id +INTO habit_id +FROM achievement_categories +WHERE name = 'HABIT'; +SELECT id +INTO create_news_id +FROM achievement_categories +WHERE name = 'CREATE_NEWS'; +SELECT id +INTO comment_or_reply_id +FROM achievement_categories +WHERE name = 'COMMENT_OR_REPLY'; +SELECT id +INTO like_comment_or_reply_id +FROM achievement_categories +WHERE name = 'LIKE_COMMENT_OR_REPLY'; +SELECT id +INTO share_news_id +FROM achievement_categories +WHERE name = 'SHARE_NEWS'; +SELECT id +INTO achievement_id +FROM achievement_categories +WHERE name = 'ACHIEVEMENT'; --- Insert statements for each category with condition -INSERT INTO achievements(name, achievement_category_id, score, condition) -VALUES - ('ACQUIRED_HABIT_14_DAYS', habit_id, 10, 14), - ('ACQUIRED_HABIT_21_DAYS', habit_id, 10, 21), - ('ACQUIRED_HABIT_30_DAYS', habit_id, 10, 30); +DELETE +FROM achievements; -INSERT INTO achievements(name, achievement_category_id, score, condition) -VALUES - ('CREATED_5_NEWS', create_news_id, 10, 5), - ('CREATED_10_NEWS', create_news_id, 10, 10), - ('CREATED_25_NEWS', create_news_id, 10, 25), - ('CREATED_50_NEWS', create_news_id, 10, 50), - ('CREATED_100_NEWS', create_news_id, 10, 100); +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('ACQUIRED_HABIT_14_DAYS', 'Набуття звички протягом 14 днів', 'Acquired habit 14 days', 20, habit_id, 14), + ('ACQUIRED_HABIT_21_DAYS', 'Набуття звички протягом 21 днів', 'Acquired habit 21 days', 30, habit_id, 21), + ('ACQUIRED_HABIT_30_DAYS', 'Набуття звички протягом 30 днів', 'Acquired habit 30 days', 40, habit_id, 30); -INSERT INTO achievements(name, achievement_category_id, score, condition) -VALUES - ('COMMENT_OR_REPLY_1_TIMES', comment_or_reply_id, 10, 1), - ('COMMENT_OR_REPLY_5_TIMES', comment_or_reply_id, 10, 5), - ('COMMENT_OR_REPLY_10_TIMES', comment_or_reply_id, 10, 10), - ('COMMENT_OR_REPLY_25_TIMES', comment_or_reply_id, 10, 25), - ('COMMENT_OR_REPLY_50_TIMES', comment_or_reply_id, 10, 50), - ('COMMENT_OR_REPLY_100_TIMES', comment_or_reply_id, 10, 100); +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('CREATED_1_NEWS', 'Створено 1 новину', 'Created 1 newі', 10, create_news_id, 5), + ('CREATED_5_NEWS', 'Створено 5 новин', 'Created 5 news', 10, create_news_id, 5), + ('CREATED_10_NEWS', 'Створено 10 новин', 'Created 10 news', 10, create_news_id, 10), + ('CREATED_25_NEWS', 'Створено 25 новин', 'Created 25 news', 10, create_news_id, 25), + ('CREATED_50_NEWS', 'Створено 50 новин', 'Created 50 news', 10, create_news_id, 50), + ('CREATED_100_NEWS', 'Створено 100 новин', 'Created 100 news', 10, create_news_id, 100); -INSERT INTO achievements(name, achievement_category_id, score, condition) -VALUES - ('LIKE_COMMENT_OR_REPLY_1_TIMES', like_comment_or_reply_id, 10, 1), - ('LIKE_COMMENT_OR_REPLY_5_TIMES', like_comment_or_reply_id, 10, 5), - ('LIKE_COMMENT_OR_REPLY_10_TIMES', like_comment_or_reply_id, 10, 10), - ('LIKE_COMMENT_OR_REPLY_25_TIMES', like_comment_or_reply_id, 10, 25), - ('LIKE_COMMENT_OR_REPLY_50_TIMES', like_comment_or_reply_id, 10, 50), - ('LIKE_COMMENT_OR_REPLY_100_TIMES', like_comment_or_reply_id, 10, 100); +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('COMMENT_OR_REPLY_1_TIMES', 'Коментування або відповідь 1 раз', 'Comment or reply 1 time', 1, + comment_or_reply_id, 1), + ('COMMENT_OR_REPLY_5_TIMES', 'Коментування або відповідь 5 разів', 'Comment or reply 5 times', 5, + comment_or_reply_id, 5), + ('COMMENT_OR_REPLY_10_TIMES', 'Коментування або відповідь 10 разів', 'Comment or reply 10 times', 10, + comment_or_reply_id, 10), + ('COMMENT_OR_REPLY_25_TIMES', 'Коментування або відповідь 25 разів', 'Comment or reply 25 times', 25, + comment_or_reply_id, 25), + ('COMMENT_OR_REPLY_50_TIMES', 'Коментування або відповідь 50 разів', 'Comment or reply 50 times', 50, + comment_or_reply_id, 50), + ('COMMENT_OR_REPLY_100_TIMES', 'Коментування або відповідь 100 разів', 'Comment or reply 100 times', 100, + comment_or_reply_id, 100); -INSERT INTO achievements(name, achievement_category_id, score, condition) -VALUES - ('SHARE_NEWS_1_TIMES', share_news_id, 10, 1), - ('SHARE_NEWS_5_TIMES', share_news_id, 10, 5), - ('SHARE_NEWS_10_TIMES', share_news_id, 10, 10), - ('SHARE_NEWS_25_TIMES', share_news_id, 10, 25), - ('SHARE_NEWS_50_TIMES', share_news_id, 10, 50), - ('SHARE_NEWS_100_TIMES', share_news_id, 10, 100); +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('LIKE_COMMENT_OR_REPLY_1_TIMES', 'Лайкнуто коментар або відповідь 1 раз', 'Liked a comment or reply 1 time', 1, + like_comment_or_reply_id, 1), + ('LIKE_COMMENT_OR_REPLY_5_TIMES', 'Лайкнуто коментарі або відповіді 5 разів', + 'Liked comments or replies 5 times', 5, like_comment_or_reply_id, 5), + ('LIKE_COMMENT_OR_REPLY_10_TIMES', 'Лайкнуто коментарі або відповіді 10 разів', + 'Liked comments or replies 10 times', 10, like_comment_or_reply_id, 10), + ('LIKE_COMMENT_OR_REPLY_25_TIMES', 'Лайкнуто коментарі або відповіді 25 разів', + 'Liked comments or replies 25 times', 25, like_comment_or_reply_id, 25), + ('LIKE_COMMENT_OR_REPLY_50_TIMES', 'Лайкнуто коментарі або відповіді 50 разів', + 'Liked comments or replies 50 times', 50, like_comment_or_reply_id, 50), + ('LIKE_COMMENT_OR_REPLY_100_TIMES', 'Лайкнуто коментарі або відповіді 100 разів', + 'Liked comments or replies 100 times', 100, like_comment_or_reply_id, 100); -INSERT INTO achievements(name, achievement_category_id, score, condition) -VALUES - ('FIRST_5_ACHIEVEMENTS', achievement_id, 10, 5), - ('FIRST_10_ACHIEVEMENTS', achievement_id, 10, 10), - ('FIRST_25_ACHIEVEMENTS', achievement_id, 10, 25), - ('FIRST_50_ACHIEVEMENTS', achievement_id, 10, 50), - ('FIRST_100_ACHIEVEMENTS', achievement_id, 10, 100); +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('SHARE_NEWS_1_TIMES', 'Поділено новину 1 раз', 'Shared news 1 time', 1, share_news_id, 1), + ('SHARE_NEWS_5_TIMES', 'Поділено новини 5 разів', 'Shared news 5 times', 5, share_news_id, 5), + ('SHARE_NEWS_10_TIMES', 'Поділено новини 10 разів', 'Shared news 10 times', 10, share_news_id, 10), + ('SHARE_NEWS_25_TIMES', 'Поділено новини 25 разів', 'Shared news 25 times', 25, share_news_id, 25), + ('SHARE_NEWS_50_TIMES', 'Поділено новини 50 разів', 'Shared news 50 times', 50, share_news_id, 50), + ('SHARE_NEWS_100_TIMES', 'Поділено новини 100 разів', 'Shared news 100 times', 100, share_news_id, 100); +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('FIRST_5_ACHIEVEMENTS', 'Перші 5 досягнень', 'First 5 Achievements', 10, achievement_id, 5), + ('FIRST_10_ACHIEVEMENTS', 'Перші 10 досягнень', 'First 10 Achievements', 25, achievement_id, 10), + ('FIRST_25_ACHIEVEMENTS', 'Перші 25 досягнень', 'First 25 Achievements', 50, achievement_id, 25), + ('FIRST_50_ACHIEVEMENTS', 'Перші 50 досягнень', 'First 50 Achievements', 100, achievement_id, 50), + ('FIRST_100_ACHIEVEMENTS', 'Перші 100 досягнень', 'First 100 Achievements', 200, achievement_id, 100); END $$; diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java index cc5ad94209..398f85ebf6 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java @@ -11,6 +11,9 @@ @Setter @EqualsAndHashCode public class AchievementPostDto { +private String title; + private String name; + private String nameEng; private AchievementCategoryDto achievementCategory; diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java index 8cd60d6cdf..6e3b7a11db 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java @@ -15,6 +15,7 @@ @Builder public class AchievementVO { private Long id; + private String title; private String name; private String nameEng; diff --git a/service/src/main/java/greencity/mapping/AchievementVOMapper.java b/service/src/main/java/greencity/mapping/AchievementVOMapper.java index 2a3686dc37..779be06ae0 100644 --- a/service/src/main/java/greencity/mapping/AchievementVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementVOMapper.java @@ -3,10 +3,7 @@ import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; -import greencity.dto.language.LanguageVO; import greencity.entity.Achievement; -import java.util.ArrayList; -import java.util.List; import org.modelmapper.AbstractConverter; import org.springframework.stereotype.Component; @@ -16,6 +13,8 @@ public class AchievementVOMapper extends AbstractConverter page = new PageImpl<>(Collections.singletonList(achievement), pageable, 10); - AchievementVO achievementVO = ModelUtils.getAchievementVO(); - when(achievementRepo.searchAchievementsBy(pageable, "")).thenReturn(page); - when(modelMapper.map(achievement, AchievementVO.class)).thenReturn(achievementVO); - PageableAdvancedDto pageableAdvancedDto = achievementService.searchAchievementBy(pageable, ""); - assertEquals(10, pageableAdvancedDto.getTotalElements()); - } + @Test void saveTest() { From 6e1b8fcf7f7d6f433d05a1f3f796728879065254 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Thu, 21 Sep 2023 10:52:07 +0300 Subject: [PATCH 19/51] Formatted and fixed checkstyle --- .../controller/AchievementController.java | 2 -- core/src/test/java/greencity/ModelUtils.java | 7 ++--- .../java/greencity/entity/Achievement.java | 2 -- .../greencity/entity/AchievementCategory.java | 1 - .../greencity/repository/AchievementRepo.java | 11 ++++++-- .../repository/UserAchievementRepo.java | 8 +++++- .../dto/achievement/AchievementPostDto.java | 2 +- .../dto/achievement/UserAchievementVO.java | 1 - .../achievement/AchievementCalculation.java | 22 ++------------- .../mapping/AchievementVOMapper.java | 11 ++++---- .../service/AchievementServiceImpl.java | 6 ++-- .../src/test/java/greencity/ModelUtils.java | 28 +++++++++---------- .../AchievementCalculationTest.java | 1 - .../mapping/AchievementVOMapperTest.java | 23 ++++++++------- .../service/AchievementServiceImplTest.java | 10 +++---- 15 files changed, 57 insertions(+), 78 deletions(-) diff --git a/core/src/main/java/greencity/controller/AchievementController.java b/core/src/main/java/greencity/controller/AchievementController.java index 10bd55b8d3..d81654c23a 100644 --- a/core/src/main/java/greencity/controller/AchievementController.java +++ b/core/src/main/java/greencity/controller/AchievementController.java @@ -2,9 +2,7 @@ import greencity.constant.HttpStatuses; import greencity.dto.achievement.AchievementDTO; -import greencity.dto.achievement.AchievementNotification; import greencity.dto.achievement.AchievementVO; -import greencity.dto.user.UserVO; import greencity.enums.AchievementCategoryType; import greencity.service.AchievementService; import io.swagger.annotations.ApiOperation; diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index 04ae7c46b7..88cd35b084 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -4,9 +4,8 @@ import greencity.constant.AppConstant; import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.AchievementPostDto; - + import greencity.dto.achievement.AchievementVO; -import greencity.dto.achievement.UserAchievementVO; import greencity.dto.achievementcategory.AchievementCategoryDto; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.advice.AdvicePostDto; @@ -586,11 +585,11 @@ public static AchievementCategoryDto getAchievementCategoryDto() { } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto( "Test","Test","Test",getAchievementCategoryDto(), 1); + return new AchievementPostDto("Test", "Test", "Test", getAchievementCategoryDto(), 1); } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, "Test", "Test","Test", + return new AchievementVO(1L, "Test", "Test", "Test", new AchievementCategoryVO(1L, "name"), 1); } diff --git a/dao/src/main/java/greencity/entity/Achievement.java b/dao/src/main/java/greencity/entity/Achievement.java index 4bfbae35c0..b0d8a473c4 100644 --- a/dao/src/main/java/greencity/entity/Achievement.java +++ b/dao/src/main/java/greencity/entity/Achievement.java @@ -1,7 +1,5 @@ package greencity.entity; - - import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; diff --git a/dao/src/main/java/greencity/entity/AchievementCategory.java b/dao/src/main/java/greencity/entity/AchievementCategory.java index 0eeb2cc498..63611c9c49 100644 --- a/dao/src/main/java/greencity/entity/AchievementCategory.java +++ b/dao/src/main/java/greencity/entity/AchievementCategory.java @@ -25,5 +25,4 @@ public class AchievementCategory { @Column(nullable = false, unique = true, length = 100) private String name; - } diff --git a/dao/src/main/java/greencity/repository/AchievementRepo.java b/dao/src/main/java/greencity/repository/AchievementRepo.java index 6425fc32e3..7b1123613e 100644 --- a/dao/src/main/java/greencity/repository/AchievementRepo.java +++ b/dao/src/main/java/greencity/repository/AchievementRepo.java @@ -4,14 +4,21 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface AchievementRepo extends JpaRepository { - + /** + * Searches for achievements based on a query string and returns a paginated + * result. + * + * @param paging A Pageable object containing the pagination information (e.g., + * page number, size, sort order). + * @param query The search query string to filter achievements. + * @return A Page of Achievement objects that match the search query. + */ Page searchAchievementsBy(Pageable paging, String query); /** diff --git a/dao/src/main/java/greencity/repository/UserAchievementRepo.java b/dao/src/main/java/greencity/repository/UserAchievementRepo.java index 78368e25cb..993faa15c1 100644 --- a/dao/src/main/java/greencity/repository/UserAchievementRepo.java +++ b/dao/src/main/java/greencity/repository/UserAchievementRepo.java @@ -18,6 +18,12 @@ public interface UserAchievementRepo extends JpaRepository getUserAchievementByUserId(Long userId); - } diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java index 398f85ebf6..f383f7c5e4 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java @@ -11,7 +11,7 @@ @Setter @EqualsAndHashCode public class AchievementPostDto { -private String title; + private String title; private String name; private String nameEng; diff --git a/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java index 8b9fafce91..28db409920 100644 --- a/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java @@ -19,5 +19,4 @@ public class UserAchievementVO { @NotEmpty private AchievementVO achievement; - } diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 1d074db934..7d73c9d059 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -20,7 +20,6 @@ import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; - @Component public class AchievementCalculation { private RestClient restClient; @@ -74,7 +73,8 @@ public void calculateAchievement(Long userId, AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( userId, achievementCategoryVO.getId()); - Integer count = checkCount(userActionVO); + int count = userActionVO.getCount() + 1; + userActionVO.setCount(count); userActionService.updateUserActions(userActionVO); checkAchievements(achievementCategoryVO.getId(), count, userId); } @@ -108,24 +108,6 @@ private void changeAchievementStatus(Long userId, Long achievementCategoryId, in .user(userRepo.findById(userId).get()) .build(); userAchievementRepo.save(userAchievement); - AchievementCategory achievementCategory = - achievementCategoryRepo.findByName(AchievementCategoryType.ACHIEVEMENT.toString()); - UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( - userId, achievementCategory.getId()); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT); - - } - - /** - * Method check achievement type. - * - * @return count action - */ - private int checkCount(UserActionVO userActionVO) { - - int count = userActionVO.getCount() + 1; - userActionVO.setCount(count); - - return count; } } diff --git a/service/src/main/java/greencity/mapping/AchievementVOMapper.java b/service/src/main/java/greencity/mapping/AchievementVOMapper.java index 779be06ae0..ffad2ab689 100644 --- a/service/src/main/java/greencity/mapping/AchievementVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementVOMapper.java @@ -1,6 +1,5 @@ package greencity.mapping; - import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.entity.Achievement; @@ -13,11 +12,11 @@ public class AchievementVOMapper extends AbstractConverter Date: Thu, 21 Sep 2023 11:02:11 +0300 Subject: [PATCH 20/51] Fixed errors --- .../main/java/greencity/service/EcoNewsCommentServiceImpl.java | 1 - .../src/main/java/greencity/service/HabitAssignServiceImpl.java | 1 - 2 files changed, 2 deletions(-) diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index 7ff0249daa..fb32e0b4ef 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -80,7 +80,6 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(userVO.getId(), AchievementCategoryType.COMMENT_OR_REPLY)); - String accessToken = httpServletRequest.getHeader(AUTHORIZATION); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); ecoNewsComment.setStatus(CommentStatus.ORIGINAL); diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 40eaba5d43..5e240872d8 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -38,7 +38,6 @@ import greencity.entity.UserShoppingListItem; import greencity.entity.localization.ShoppingListItemTranslation; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementType; import greencity.enums.HabitAssignStatus; import greencity.enums.ShoppingListItemStatus; import greencity.enums.RatingCalculationEnum; From 47270ca4f531861192860e72e1c582c9ac5f57a9 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Thu, 21 Sep 2023 11:10:58 +0300 Subject: [PATCH 21/51] Fixed errors --- dao/src/main/java/greencity/repository/AchievementRepo.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dao/src/main/java/greencity/repository/AchievementRepo.java b/dao/src/main/java/greencity/repository/AchievementRepo.java index 7b1123613e..ef1c027eb4 100644 --- a/dao/src/main/java/greencity/repository/AchievementRepo.java +++ b/dao/src/main/java/greencity/repository/AchievementRepo.java @@ -4,6 +4,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @@ -19,6 +20,10 @@ public interface AchievementRepo extends JpaRepository { * @param query The search query string to filter achievements. * @return A Page of Achievement objects that match the search query. */ + @Query("SELECT DISTINCT a FROM Achievement a " + + "WHERE CONCAT(a.id,'') LIKE LOWER(CONCAT('%', :query, '%')) " + + "OR LOWER(a.achievementCategory.name) LIKE LOWER(CONCAT('%', :query, '%'))" + + "OR CONCAT(a.condition, ' ') LIKE LOWER(CONCAT('%', :query, '%'))") Page searchAchievementsBy(Pageable paging, String query); /** From 20cb60d3535db94fc5fa73eb73729768a2e7fb4d Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Thu, 21 Sep 2023 11:23:50 +0300 Subject: [PATCH 22/51] Fixed bugs --- .../src/main/java/greencity/constant/ErrorMessage.java | 4 +++- .../greencity/achievement/AchievementCalculation.java | 10 ++++++++-- .../java/greencity/service/UserActionServiceImpl.java | 8 ++++++-- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/service-api/src/main/java/greencity/constant/ErrorMessage.java b/service-api/src/main/java/greencity/constant/ErrorMessage.java index 941af0bd6b..b1a554277e 100644 --- a/service-api/src/main/java/greencity/constant/ErrorMessage.java +++ b/service-api/src/main/java/greencity/constant/ErrorMessage.java @@ -156,7 +156,9 @@ public final class ErrorMessage { "Count of tags should be at least one but not more three"; public static final String TOKEN_FOR_RESTORE_IS_INVALID = "Token is null or it doesn't exist."; public static final String ACHIEVEMENT_NOT_DELETED = "Achievement not deleted "; - public static final String ACHIEVEMENT_NOT_FOUND_BY_ID = "The name does not exist by this id: "; + public static final String ACHIEVEMENT_NOT_FOUND_BY_ID = "The achievement does not exist by this id: "; + public static final String ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID = + "The achievement category does not exist by this id: "; public static final String PAGE_INDEX_IS_MORE_THAN_TOTAL_PAGES = "Page index is more than total pages: "; public static final String MULTIPART_FILE_BAD_REQUEST = "Can`t convert To Multipart Image. Bad inputed image string : "; diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 7d73c9d059..a5c2fd476f 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -1,6 +1,7 @@ package greencity.achievement; import greencity.client.RestClient; +import greencity.constant.ErrorMessage; import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.useraction.UserActionVO; @@ -20,6 +21,8 @@ import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; +import java.util.NoSuchElementException; + @Component public class AchievementCalculation { private RestClient restClient; @@ -102,10 +105,13 @@ private void checkAchievements(Long achievementCategoryId, Integer count, Long u */ private void changeAchievementStatus(Long userId, Long achievementCategoryId, int count) { Achievement achievement = - achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count).get(); + achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) + .orElseThrow(() -> new NoSuchElementException( + ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); UserAchievement userAchievement = UserAchievement.builder() .achievement(achievement) - .user(userRepo.findById(userId).get()) + .user(userRepo.findById(userId) + .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) .build(); userAchievementRepo.save(userAchievement); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT); diff --git a/service/src/main/java/greencity/service/UserActionServiceImpl.java b/service/src/main/java/greencity/service/UserActionServiceImpl.java index c4b39579a7..a714b26892 100644 --- a/service/src/main/java/greencity/service/UserActionServiceImpl.java +++ b/service/src/main/java/greencity/service/UserActionServiceImpl.java @@ -1,5 +1,6 @@ package greencity.service; +import greencity.constant.ErrorMessage; import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.UserAction; @@ -11,6 +12,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.NoSuchElementException; import java.util.Optional; @Service @@ -49,9 +51,11 @@ public UserActionVO findUserActionByUserIdAndAchievementCategory(Long userId, Lo UserAction userAction = userActionRepo.findByUserIdAndAchievementCategoryId(userId, categoryId); if (userAction == null) { userAction = UserAction.builder() - .user(userRepo.findById(userId).get()) + .user(userRepo.findById(userId) + .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) .count(0) - .achievementCategory(achievementCategoryRepo.findById(categoryId).get()) + .achievementCategory(achievementCategoryRepo.findById(categoryId).orElseThrow( + () -> new NoSuchElementException(ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + categoryId))) .build(); userActionRepo.save(userAction); } From 4e0a2d22d8915a375f50137f696cf7abb1d5fa4d Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Thu, 21 Sep 2023 11:35:50 +0300 Subject: [PATCH 23/51] Fixed codesmells --- .../greencity/entity/AchievementCategory.java | 1 - .../dto/achievement/AchievementPostDto.java | 2 -- .../dto/achievement/AchievementVO.java | 1 - .../greencity/service/AchievementService.java | 1 - .../achievement/AchievementCalculation.java | 14 +------------- .../mapping/AchievementCategoryVOMapper.java | 4 ---- .../service/AchievementServiceImpl.java | 3 --- .../service/HabitAssignServiceImpl.java | 2 -- .../service/UserActionServiceImpl.java | 1 - .../achievement/AchievementCalculationTest.java | 17 +++++------------ 10 files changed, 6 insertions(+), 40 deletions(-) diff --git a/dao/src/main/java/greencity/entity/AchievementCategory.java b/dao/src/main/java/greencity/entity/AchievementCategory.java index 63611c9c49..78bb4d02f4 100644 --- a/dao/src/main/java/greencity/entity/AchievementCategory.java +++ b/dao/src/main/java/greencity/entity/AchievementCategory.java @@ -8,7 +8,6 @@ import lombok.Builder; import javax.persistence.*; -import java.util.List; @Entity @AllArgsConstructor diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java index f383f7c5e4..c71da7a31f 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementPostDto.java @@ -3,8 +3,6 @@ import greencity.dto.achievementcategory.AchievementCategoryDto; import lombok.*; -import java.util.List; - @NoArgsConstructor @AllArgsConstructor @Getter diff --git a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java index 6e3b7a11db..ff6a1320b7 100644 --- a/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/AchievementVO.java @@ -7,7 +7,6 @@ import lombok.NoArgsConstructor; import javax.validation.constraints.NotEmpty; -import java.util.List; @Data @NoArgsConstructor diff --git a/service-api/src/main/java/greencity/service/AchievementService.java b/service-api/src/main/java/greencity/service/AchievementService.java index e0ad252201..b7da6767ba 100644 --- a/service-api/src/main/java/greencity/service/AchievementService.java +++ b/service-api/src/main/java/greencity/service/AchievementService.java @@ -2,7 +2,6 @@ import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.*; -import greencity.dto.user.UserVO; import greencity.enums.AchievementCategoryType; import org.springframework.data.domain.Pageable; diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index a5c2fd476f..0316a95989 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -1,12 +1,10 @@ package greencity.achievement; -import greencity.client.RestClient; import greencity.constant.ErrorMessage; import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.Achievement; -import greencity.entity.AchievementCategory; import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; @@ -17,7 +15,6 @@ import greencity.service.AchievementCategoryService; import greencity.service.AchievementService; import greencity.service.UserActionService; -import org.modelmapper.ModelMapper; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @@ -25,43 +22,34 @@ @Component public class AchievementCalculation { - private RestClient restClient; private UserActionService userActionService; private AchievementService achievementService; private AchievementCategoryService achievementCategoryService; - private final ModelMapper modelMapper; private UserAchievementRepo userAchievementRepo; private final UserRepo userRepo; private final AchievementRepo achievementRepo; - private final AchievementCategoryRepo achievementCategoryRepo; /** * Constructor for {@link AchievementCalculation}. * - * @param restClient {@link RestClient} * @param userActionService {@link UserActionService} * @param achievementService {@link AchievementService} * @param achievementCategoryService {@link AchievementCategoryService} - * @param modelMapper {@link ModelMapper} */ - public AchievementCalculation(RestClient restClient, + public AchievementCalculation( UserActionService userActionService, @Lazy AchievementService achievementService, AchievementCategoryService achievementCategoryService, - ModelMapper modelMapper, UserAchievementRepo userAchievementRepo, UserRepo userRepo, AchievementRepo achievementRepo, AchievementCategoryRepo achievementCategoryRepo) { - this.restClient = restClient; this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; - this.modelMapper = modelMapper; this.userAchievementRepo = userAchievementRepo; this.userRepo = userRepo; this.achievementRepo = achievementRepo; - this.achievementCategoryRepo = achievementCategoryRepo; } /** diff --git a/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java b/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java index f7389e3d65..6a6da7781b 100644 --- a/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java +++ b/service/src/main/java/greencity/mapping/AchievementCategoryVOMapper.java @@ -1,14 +1,10 @@ package greencity.mapping; -import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; -import greencity.dto.useraction.UserActionVO; import greencity.entity.AchievementCategory; import org.modelmapper.AbstractConverter; import org.springframework.stereotype.Component; -import java.util.stream.Collectors; - @Component public class AchievementCategoryVOMapper extends AbstractConverter { @Override diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index d0a58c4e6c..6a8dfbee6a 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -11,7 +11,6 @@ import greencity.dto.useraction.UserActionVO; import greencity.entity.Achievement; import greencity.entity.AchievementCategory; -import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; import greencity.exception.exceptions.NotDeletedException; @@ -21,7 +20,6 @@ import greencity.repository.UserAchievementRepo; -import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -44,7 +42,6 @@ public class AchievementServiceImpl implements AchievementService { private final RestClient restClient; private final AchievementCategoryService achievementCategoryService; private final UserActionService userActionService; - private UserAchievementRepo userAchievementRepo; private AchievementCalculation achievementCalculation; /** diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 5e240872d8..3f535699f8 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -41,7 +41,6 @@ import greencity.enums.HabitAssignStatus; import greencity.enums.ShoppingListItemStatus; import greencity.enums.RatingCalculationEnum; -import greencity.enums.AchievementCategoryType; import java.time.LocalDate; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; @@ -100,7 +99,6 @@ public class HabitAssignServiceImpl implements HabitAssignService { private final HabitStatusCalendarService habitStatusCalendarService; private final AchievementCalculation achievementCalculation; private final ModelMapper modelMapper; - private final HttpServletRequest httpServletRequest; private final UserService userService; private final RatingCalculation ratingCalculation; diff --git a/service/src/main/java/greencity/service/UserActionServiceImpl.java b/service/src/main/java/greencity/service/UserActionServiceImpl.java index a714b26892..6844adcb64 100644 --- a/service/src/main/java/greencity/service/UserActionServiceImpl.java +++ b/service/src/main/java/greencity/service/UserActionServiceImpl.java @@ -1,7 +1,6 @@ package greencity.service; import greencity.constant.ErrorMessage; -import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.UserAction; import greencity.repository.AchievementCategoryRepo; diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index 18e3f2d41d..f801a59c18 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -6,7 +6,6 @@ import greencity.dto.achievement.UserVOAchievement; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.useraction.UserActionVO; -import greencity.entity.AchievementCategory; import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; @@ -17,8 +16,6 @@ import greencity.service.*; 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.EnumSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -27,9 +24,9 @@ import java.util.Collections; import java.util.Optional; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class AchievementCalculationTest { @@ -60,20 +57,16 @@ void calculateAchievement() { AchievementCategoryVO achievementCategoryVO2 = ModelUtils.getAchievementCategoryVO(); achievementCategoryVO2.setId(2L); UserActionVO userActionVO = ModelUtils.getUserActionVO(); + int count = userActionVO.getCount(); UserActionVO userActionVO2 = ModelUtils.getUserActionVO(); userActionVO2.setId(2L); - UserVOAchievement userVOAchievement = ModelUtils.getUserVOAchievement(); User user = ModelUtils.getUser(); - AchievementVO achievementVO = ModelUtils.getAchievementVO(); UserAchievement userAchievement = ModelUtils.getUserAchievement(); user.setUserAchievements(Collections.singletonList(userAchievement)); when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) .thenReturn(achievementCategoryVO); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)).thenReturn(userActionVO); -//when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(),anyInt())).thenReturn(Optional.of(ModelUtils.getAchievement())); -// when(userRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getUser())); -// when(achievementCategoryRepo.findByName(anyString())).thenReturn(ModelUtils.getAchievementCategory()); - achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS); + assertEquals(count + 1, userActionVO.getCount()); } } From 9bd6e290c156c14f9eade6feb33c5872dbcc8baa Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Thu, 21 Sep 2023 12:54:34 +0300 Subject: [PATCH 24/51] Fixed code --- .../greencity/entity/AchievementCategory.java | 3 +++ .../functions/insert-values-achievements.sql | 18 +++++++++--------- .../dto/achievement/UserAchievementVO.java | 3 +++ 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/dao/src/main/java/greencity/entity/AchievementCategory.java b/dao/src/main/java/greencity/entity/AchievementCategory.java index 78bb4d02f4..ca880b2bf8 100644 --- a/dao/src/main/java/greencity/entity/AchievementCategory.java +++ b/dao/src/main/java/greencity/entity/AchievementCategory.java @@ -8,6 +8,7 @@ import lombok.Builder; import javax.persistence.*; +import java.util.List; @Entity @AllArgsConstructor @@ -24,4 +25,6 @@ public class AchievementCategory { @Column(nullable = false, unique = true, length = 100) private String name; + @OneToMany(mappedBy = "achievementCategory") + private List achievementList; } diff --git a/dao/src/main/resources/db/functions/insert-values-achievements.sql b/dao/src/main/resources/db/functions/insert-values-achievements.sql index 14a9505230..b501381656 100644 --- a/dao/src/main/resources/db/functions/insert-values-achievements.sql +++ b/dao/src/main/resources/db/functions/insert-values-achievements.sql @@ -47,7 +47,7 @@ VALUES ('ACQUIRED_HABIT_14_DAYS', 'Набуття звички протягом ('ACQUIRED_HABIT_30_DAYS', 'Набуття звички протягом 30 днів', 'Acquired habit 30 days', 40, habit_id, 30); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('CREATED_1_NEWS', 'Створено 1 новину', 'Created 1 newі', 10, create_news_id, 5), +VALUES ('CREATED_1_NEWS', 'Створено перший новину', 'Created first news', 10, create_news_id, 1), ('CREATED_5_NEWS', 'Створено 5 новин', 'Created 5 news', 10, create_news_id, 5), ('CREATED_10_NEWS', 'Створено 10 новин', 'Created 10 news', 10, create_news_id, 10), ('CREATED_25_NEWS', 'Створено 25 новин', 'Created 25 news', 10, create_news_id, 25), @@ -55,7 +55,7 @@ VALUES ('CREATED_1_NEWS', 'Створено 1 новину', 'Created 1 newі', ('CREATED_100_NEWS', 'Створено 100 новин', 'Created 100 news', 10, create_news_id, 100); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('COMMENT_OR_REPLY_1_TIMES', 'Коментування або відповідь 1 раз', 'Comment or reply 1 time', 1, +VALUES ('COMMENT_OR_REPLY_1_TIMES', 'Коментування або відповідь перший раз', 'Comment or reply first time', 1, comment_or_reply_id, 1), ('COMMENT_OR_REPLY_5_TIMES', 'Коментування або відповідь 5 разів', 'Comment or reply 5 times', 5, comment_or_reply_id, 5), @@ -69,7 +69,7 @@ VALUES ('COMMENT_OR_REPLY_1_TIMES', 'Коментування або відпо comment_or_reply_id, 100); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('LIKE_COMMENT_OR_REPLY_1_TIMES', 'Лайкнуто коментар або відповідь 1 раз', 'Liked a comment or reply 1 time', 1, +VALUES ('LIKE_COMMENT_OR_REPLY_1_TIMES', 'Лайкнуто коментар або відповідь перший раз', 'Liked a comment or reply first time', 1, like_comment_or_reply_id, 1), ('LIKE_COMMENT_OR_REPLY_5_TIMES', 'Лайкнуто коментарі або відповіді 5 разів', 'Liked comments or replies 5 times', 5, like_comment_or_reply_id, 5), @@ -83,12 +83,12 @@ VALUES ('LIKE_COMMENT_OR_REPLY_1_TIMES', 'Лайкнуто коментар аб 'Liked comments or replies 100 times', 100, like_comment_or_reply_id, 100); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('SHARE_NEWS_1_TIMES', 'Поділено новину 1 раз', 'Shared news 1 time', 1, share_news_id, 1), - ('SHARE_NEWS_5_TIMES', 'Поділено новини 5 разів', 'Shared news 5 times', 5, share_news_id, 5), - ('SHARE_NEWS_10_TIMES', 'Поділено новини 10 разів', 'Shared news 10 times', 10, share_news_id, 10), - ('SHARE_NEWS_25_TIMES', 'Поділено новини 25 разів', 'Shared news 25 times', 25, share_news_id, 25), - ('SHARE_NEWS_50_TIMES', 'Поділено новини 50 разів', 'Shared news 50 times', 50, share_news_id, 50), - ('SHARE_NEWS_100_TIMES', 'Поділено новини 100 разів', 'Shared news 100 times', 100, share_news_id, 100); +VALUES ('SHARE_NEWS_1_TIMES', 'Поширено новину перший раз', 'Shared news first time', 1, share_news_id, 1), + ('SHARE_NEWS_5_TIMES', 'Поширено новини 5 разів', 'Shared news 5 times', 5, share_news_id, 5), + ('SHARE_NEWS_10_TIMES', 'Поширено новини 10 разів', 'Shared news 10 times', 10, share_news_id, 10), + ('SHARE_NEWS_25_TIMES', 'Поширено новини 25 разів', 'Shared news 25 times', 25, share_news_id, 25), + ('SHARE_NEWS_50_TIMES', 'Поширено новини 50 разів', 'Shared news 50 times', 50, share_news_id, 50), + ('SHARE_NEWS_100_TIMES', 'Поширено новини 100 разів', 'Shared news 100 times', 100, share_news_id, 100); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) VALUES ('FIRST_5_ACHIEVEMENTS', 'Перші 5 досягнень', 'First 5 Achievements', 10, achievement_id, 5), diff --git a/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java b/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java index 28db409920..a0cd9a41e2 100644 --- a/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java +++ b/service-api/src/main/java/greencity/dto/achievement/UserAchievementVO.java @@ -19,4 +19,7 @@ public class UserAchievementVO { @NotEmpty private AchievementVO achievement; + + @NotEmpty + private boolean notified; } From 6dd1c4808f043c9cb311a1ae1ace425e793e3310 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Thu, 21 Sep 2023 12:56:00 +0300 Subject: [PATCH 25/51] Fixed code --- .../greencity/mapping/AchievementCategoryVOMapperTest.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java index 0597ccfd51..8cdd8baea4 100644 --- a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java @@ -1,9 +1,6 @@ package greencity.mapping; -import greencity.ModelUtils; -import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; -import greencity.dto.useraction.UserActionVO; import greencity.entity.AchievementCategory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -11,7 +8,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; -import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; @@ -22,7 +18,7 @@ class AchievementCategoryVOMapperTest { @Test void convert() { - AchievementCategory achievementCategory = new AchievementCategory(1L, "Name"); + AchievementCategory achievementCategory = new AchievementCategory(1L, "Name",Collections.emptyList()); AchievementCategoryVO achievementCategoryVO = AchievementCategoryVO.builder() .id(achievementCategory.getId()) .name(achievementCategory.getName()) From 1ca59332a7ffed1c77fb35d85efd97f3956eef4d Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 10:19:17 +0300 Subject: [PATCH 26/51] Created AchievementAction to check if we have to add achievements or delete --- .../controller/AchievementController.java | 15 -- .../controller/AchievementControllerTest.java | 8 - .../greencity/enums/AchievementAction.java | 9 ++ .../enums/RatingCalculationEnum.java | 84 +++++++++-- .../greencity/service/AchievementService.java | 3 +- .../enums/RatingCalculationEnumTest.java | 23 --- .../achievement/AchievementCalculation.java | 138 ++++++++++++------ .../greencity/rating/RatingCalculation.java | 20 +++ .../service/AchievementServiceImpl.java | 7 +- .../service/EcoNewsCommentServiceImpl.java | 7 +- .../greencity/service/EcoNewsServiceImpl.java | 12 +- .../service/HabitAssignServiceImpl.java | 9 +- .../AchievementCalculationTest.java | 6 +- .../service/AchievementServiceImplTest.java | 11 +- 14 files changed, 220 insertions(+), 132 deletions(-) create mode 100644 service-api/src/main/java/greencity/enums/AchievementAction.java diff --git a/core/src/main/java/greencity/controller/AchievementController.java b/core/src/main/java/greencity/controller/AchievementController.java index d81654c23a..ee58d64b7e 100644 --- a/core/src/main/java/greencity/controller/AchievementController.java +++ b/core/src/main/java/greencity/controller/AchievementController.java @@ -45,19 +45,4 @@ public ResponseEntity> getAll() { return ResponseEntity.status(HttpStatus.OK).body(achievementService.findAll()); } - /** - * Method for achievement calculation. - */ - @ApiOperation(value = "Calculate achievements.") - @ApiResponses(value = { - @ApiResponse(code = 200, message = HttpStatuses.OK), - @ApiResponse(code = 400, message = HttpStatuses.BAD_REQUEST), - @ApiResponse(code = 401, message = HttpStatuses.UNAUTHORIZED), - }) - @PostMapping("/calculate-achievement") - public ResponseEntity calculateAchievements(@RequestParam Long id, - @RequestParam AchievementCategoryType socialNetwork) { - achievementService.calculateAchievements(id, socialNetwork); - return ResponseEntity.ok().build(); - } } diff --git a/core/src/test/java/greencity/controller/AchievementControllerTest.java b/core/src/test/java/greencity/controller/AchievementControllerTest.java index 072bdff0b3..f0dc6d5727 100644 --- a/core/src/test/java/greencity/controller/AchievementControllerTest.java +++ b/core/src/test/java/greencity/controller/AchievementControllerTest.java @@ -44,12 +44,4 @@ void findAllTest() throws Exception { verify(achievementService).findAll(); } - @Test - void calculateAchievements() throws Exception { - mockMvc.perform(post(achievementLink + "/calculate-achievement" - + "?id=" + 1L - + "&socialNetwork=" + AchievementCategoryType.CREATE_NEWS)).andExpect(status().isOk()); - verify(achievementService).calculateAchievements(1L, - AchievementCategoryType.CREATE_NEWS); - } } diff --git a/service-api/src/main/java/greencity/enums/AchievementAction.java b/service-api/src/main/java/greencity/enums/AchievementAction.java new file mode 100644 index 0000000000..c018db18d8 --- /dev/null +++ b/service-api/src/main/java/greencity/enums/AchievementAction.java @@ -0,0 +1,9 @@ +package greencity.enums; + +import lombok.Getter; + +@Getter +public enum AchievementAction { + ASSIGN, + DELETE +} diff --git a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java index 25f155130f..b7c69c7cbf 100644 --- a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java +++ b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java @@ -5,28 +5,94 @@ @Getter public enum RatingCalculationEnum { DAYS_OF_HABIT_IN_PROGRESS(1), - CREATE_NEWS(20), - COMMENT_OR_REPLY(2), - LIKE_COMMENT_OR_REPLY(10), - SHARE_NEWS(20), - UNDO_DAYS_OF_HABIT_IN_PROGRESS(-1), - DELETE_NEWS(-20), - DELETE_COMMENT_OR_REPLY(-2), - UNLIKE_COMMENT_OR_REPLY(-10), + UNDO_SHARE_NEWS(-20), + + ACQUIRED_HABIT_14_DAYS(20), + ACQUIRED_HABIT_21_DAYS(30), + ACQUIRED_HABIT_30_DAYS(40), + CREATED_1_NEWS(10), + CREATED_5_NEWS(10), + CREATED_10_NEWS(10), + CREATED_25_NEWS(10), + CREATED_50_NEWS(10), + CREATED_100_NEWS(10), + COMMENT_OR_REPLY_1_TIMES(1), + COMMENT_OR_REPLY_5_TIMES(5), + COMMENT_OR_REPLY_10_TIMES(10), + COMMENT_OR_REPLY_25_TIMES(25), + COMMENT_OR_REPLY_50_TIMES(50), + COMMENT_OR_REPLY_100_TIMES(100), + LIKE_COMMENT_OR_REPLY_1_TIMES(1), + LIKE_COMMENT_OR_REPLY_5_TIMES(5), + LIKE_COMMENT_OR_REPLY_10_TIMES(10), + LIKE_COMMENT_OR_REPLY_25_TIMES(25), + LIKE_COMMENT_OR_REPLY_50_TIMES(50), + LIKE_COMMENT_OR_REPLY_100_TIMES(100), + SHARE_NEWS_1_TIMES(1), + SHARE_NEWS_5_TIMES(5), + SHARE_NEWS_10_TIMES(10), + SHARE_NEWS_25_TIMES(25), + SHARE_NEWS_50_TIMES(50), + SHARE_NEWS_100_TIMES(100), + FIRST_5_ACHIEVEMENTS(10), + FIRST_10_ACHIEVEMENTS(25), + FIRST_25_ACHIEVEMENTS(50), + FIRST_50_ACHIEVEMENTS(100), + FIRST_100_ACHIEVEMENTS(200), + UNDO_ACQUIRED_HABIT_14_DAYS(-20), + UNDO_ACQUIRED_HABIT_21_DAYS(-30), + UNDO_ACQUIRED_HABIT_30_DAYS(-40), + UNDO_CREATED_1_NEWS(-10), + UNDO_CREATED_5_NEWS(-10), + UNDO_CREATED_10_NEWS(-10), + UNDO_CREATED_25_NEWS(-10), + UNDO_CREATED_50_NEWS(-10), + UNDO_CREATED_100_NEWS(-10), + UNDO_COMMENT_OR_REPLY_1_TIMES(-1), + UNDO_COMMENT_OR_REPLY_5_TIMES(-5), + UNDO_COMMENT_OR_REPLY_10_TIMES(-10), + UNDO_COMMENT_OR_REPLY_25_TIMES(-25), + UNDO_COMMENT_OR_REPLY_50_TIMES(-50), + UNDO_COMMENT_OR_REPLY_100_TIMES(-100), + UNDO_LIKE_COMMENT_OR_REPLY_1_TIMES(-1), + UNDO_LIKE_COMMENT_OR_REPLY_5_TIMES(-5), + UNDO_LIKE_COMMENT_OR_REPLY_10_TIMES(-10), + UNDO_LIKE_COMMENT_OR_REPLY_25_TIMES(-25), + UNDO_LIKE_COMMENT_OR_REPLY_50_TIMES(-50), + UNDO_LIKE_COMMENT_OR_REPLY_100_TIMES(-100), + UNDO_SHARE_NEWS_1_TIMES(-1), + UNDO_SHARE_NEWS_5_TIMES(-5), + UNDO_SHARE_NEWS_10_TIMES(-10), + UNDO_SHARE_NEWS_25_TIMES(-25), + UNDO_SHARE_NEWS_50_TIMES(-50), + UNDO_SHARE_NEWS_100_TIMES(-100), + UNDO_FIRST_5_ACHIEVEMENTS(-10), + UNDO_FIRST_10_ACHIEVEMENTS(-25), + UNDO_FIRST_25_ACHIEVEMENTS(-50), + UNDO_FIRST_50_ACHIEVEMENTS(-100), + UNDO_FIRST_100_ACHIEVEMENTS(-200); - UNDO_SHARE_NEWS(-20); private final int ratingPoints; RatingCalculationEnum(int ratingPoints) { this.ratingPoints = ratingPoints; } + + public static RatingCalculationEnum findEnumByName(String name) { + try { + return RatingCalculationEnum.valueOf(name); + } catch (IllegalArgumentException e) { + return null; // повертаємо null, якщо елемент не знайдений + } + } + } diff --git a/service-api/src/main/java/greencity/service/AchievementService.java b/service-api/src/main/java/greencity/service/AchievementService.java index b7da6767ba..99f7d9f14b 100644 --- a/service-api/src/main/java/greencity/service/AchievementService.java +++ b/service-api/src/main/java/greencity/service/AchievementService.java @@ -3,6 +3,7 @@ import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.*; import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementAction; import org.springframework.data.domain.Pageable; import java.util.List; @@ -91,5 +92,5 @@ public interface AchievementService { /** * Method for achievement Calculation. */ - void calculateAchievements(Long id, AchievementCategoryType achievementCategory); + void calculateAchievements(Long id, AchievementCategoryType achievementCategory, AchievementAction achievementAction); } diff --git a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java index 99f50e35a7..b73c46d23a 100644 --- a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java +++ b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java @@ -5,29 +5,6 @@ class RatingCalculationEnumTest { - @Test - void testEnumValues() { - RatingCalculationEnum[] expected = { - RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, - RatingCalculationEnum.CREATE_NEWS, - RatingCalculationEnum.COMMENT_OR_REPLY, - RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, - RatingCalculationEnum.SHARE_NEWS, - RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, - RatingCalculationEnum.DELETE_NEWS, - RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, - RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, - RatingCalculationEnum.UNDO_SHARE_NEWS - }; - - RatingCalculationEnum[] actual = RatingCalculationEnum.values(); - assertEquals(expected.length, actual.length, "Enum length does not match expected length"); - - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], actual[i], "Enum value does not match at index " + i); - } - } - @Test void testEnumValueOf() { for (RatingCalculationEnum value : RatingCalculationEnum.values()) { diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 0316a95989..72b5473300 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -3,11 +3,14 @@ import greencity.constant.ErrorMessage; import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; +import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.Achievement; -import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementAction; +import greencity.enums.RatingCalculationEnum; +import greencity.rating.RatingCalculation; import greencity.repository.AchievementCategoryRepo; import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; @@ -15,93 +18,146 @@ import greencity.service.AchievementCategoryService; import greencity.service.AchievementService; import greencity.service.UserActionService; +import greencity.service.UserService; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import java.util.NoSuchElementException; +import java.util.concurrent.CompletableFuture; @Component public class AchievementCalculation { private UserActionService userActionService; private AchievementService achievementService; + private UserService userService; private AchievementCategoryService achievementCategoryService; private UserAchievementRepo userAchievementRepo; private final UserRepo userRepo; private final AchievementRepo achievementRepo; + private final RatingCalculation ratingCalculation; /** * Constructor for {@link AchievementCalculation}. - * + * * @param userActionService {@link UserActionService} * @param achievementService {@link AchievementService} * @param achievementCategoryService {@link AchievementCategoryService} */ public AchievementCalculation( - UserActionService userActionService, - @Lazy AchievementService achievementService, - AchievementCategoryService achievementCategoryService, - UserAchievementRepo userAchievementRepo, - UserRepo userRepo, - AchievementRepo achievementRepo, - AchievementCategoryRepo achievementCategoryRepo) { + UserActionService userActionService, + @Lazy AchievementService achievementService, + AchievementCategoryService achievementCategoryService, + UserAchievementRepo userAchievementRepo, + UserRepo userRepo, + AchievementRepo achievementRepo, + AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation) { this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; this.userAchievementRepo = userAchievementRepo; this.userRepo = userRepo; this.achievementRepo = achievementRepo; + this.ratingCalculation = ratingCalculation; } /** - * Method that changing user actions. {@link greencity.entity.UserAction} + * Calculate and handle achievements for a user based on specified category and status. * - * @param userId of {@link User} - * @param category {@link AchievementCategoryType} - * @author Orest Mamchuk + * @param userId The user ID for whom the achievement is to be calculated. + * @param category The category type of the achievement. + * @param achievementAction The status of the achievement (ASSIGN, DELETE, etc.). */ - public void calculateAchievement(Long userId, - AchievementCategoryType category) { + public void calculateAchievement(Long userId, AchievementCategoryType category, AchievementAction achievementAction) { AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); - UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( - userId, achievementCategoryVO.getId()); - int count = userActionVO.getCount() + 1; - userActionVO.setCount(count); + UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory(userId, achievementCategoryVO.getId()); + int count = updateCount(userActionVO, achievementAction); userActionService.updateUserActions(userActionVO); - checkAchievements(achievementCategoryVO.getId(), count, userId); + + checkAchievements(achievementCategoryVO.getId(), count, userId, achievementAction); + UserVO user = userService.findById(userId); + + String enumName = achievementAction.equals(AchievementAction.ASSIGN) ? achievementCategoryVO.getName() : "UNDO_" + achievementCategoryVO.getName(); + RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName(enumName); + + if (reason != null) { + CompletableFuture.runAsync(() -> ratingCalculation.ratingCalculation(reason, user)); + } + } + /** + * Update the count of user actions based on achievement status. + * + * @param userActionVO The user's action data object. + * @param achievementAction The status of the achievement. + * @return Updated count of user actions. + */ + private int updateCount(UserActionVO userActionVO, AchievementAction achievementAction) { + int count = achievementAction.equals(AchievementAction.ASSIGN)?userActionVO.getCount()+1:userActionVO.getCount()-1; + userActionVO.setCount(count); + return count; } /** - * Method for finding achievements. + * Check and handle achievements based on specified conditions. * - * @param achievementCategoryId of {@link AchievementCategoryType} - * @param count number of specific actions - * @param userId of {@link User} - * @author Orest Mamchuk + * @param achievementCategoryId The ID of the achievement category. + * @param count The count of user actions for the achievement. + * @param userId The user ID for whom the achievement is to be checked. + * @param achievementAction The status of the achievement. */ - private void checkAchievements(Long achievementCategoryId, Integer count, Long userId) { + private void checkAchievements(Long achievementCategoryId, Integer count, Long userId, AchievementAction achievementAction) { AchievementVO achievementVO = achievementService.findByCategoryIdAndCondition(achievementCategoryId, count); - if (achievementVO != null) { - changeAchievementStatus(userId, achievementCategoryId, count); + if (achievementVO != null) { + switch (achievementAction) { + case ASSIGN: + saveAchievementToUser(userId, achievementCategoryId, count); + break; + case DELETE: + deleteAchievementFromUser(userId, achievementCategoryId, count); + break; + } + } } - /** - * Method that changing achievement status. + * Save an achievement to a user's record. * - * @param userId {@link User} - * @author Orest Mamchuk + * @param userId The user ID. + * @param achievementCategoryId The achievement category ID. + * @param count The count of user actions for the achievement. */ - private void changeAchievementStatus(Long userId, Long achievementCategoryId, int count) { + + private void saveAchievementToUser(Long userId, Long achievementCategoryId, int count) { Achievement achievement = - achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) - .orElseThrow(() -> new NoSuchElementException( - ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); + achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) + .orElseThrow(() -> new NoSuchElementException( + ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); UserAchievement userAchievement = UserAchievement.builder() - .achievement(achievement) - .user(userRepo.findById(userId) - .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) - .build(); + .achievement(achievement) + .user(userRepo.findById(userId) + .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) + .build(); userAchievementRepo.save(userAchievement); - calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT); + calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.ASSIGN); + } + + /** + * Delete an achievement from a user's record. + * + * @param userId The user ID. + * @param achievementCategoryId The achievement category ID. + * @param count The count of user actions for the achievement. + */ + private void deleteAchievementFromUser(Long userId, Long achievementCategoryId, int count) { + Achievement achievement = + achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) + .orElseThrow(() -> new NoSuchElementException( + ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); + UserAchievement userAchievement = UserAchievement.builder() + .achievement(achievement) + .user(userRepo.findById(userId) + .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) + .build(); + userAchievementRepo.delete(userAchievement); + calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.DELETE); } } diff --git a/service/src/main/java/greencity/rating/RatingCalculation.java b/service/src/main/java/greencity/rating/RatingCalculation.java index 54a517eda8..a386010f86 100644 --- a/service/src/main/java/greencity/rating/RatingCalculation.java +++ b/service/src/main/java/greencity/rating/RatingCalculation.java @@ -43,4 +43,24 @@ public void ratingCalculation(RatingCalculationEnum rating, UserVO userVo) { .build(); ratingStatisticsService.save(modelMapper.map(ratingStatistics, RatingStatisticsVO.class)); } + /** + * Method that calculates the user rating. + * + * @param rating of {@link RatingCalculationEnum} + * @param userVo of {@link UserVO} + */ + public void ratingCalculation(RatingCalculationEnum rating, int points, UserVO userVo) { + String accessToken = httpServletRequest.getHeader(AUTHORIZATION); + User user = modelMapper.map(userVo, User.class); + userVo.setRating(userVo.getRating() +points); + restClient.save(userVo, accessToken); + RatingStatistics ratingStatistics = RatingStatistics + .builder() + .rating(userVo.getRating()) + .ratingCalculationEnum(rating) + .user(user) + .pointsChanged(rating.getRatingPoints()) + .build(); + ratingStatisticsService.save(modelMapper.map(ratingStatistics, RatingStatisticsVO.class)); + } } diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index 6a8dfbee6a..7dfeaaf721 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -13,13 +13,12 @@ import greencity.entity.AchievementCategory; import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementAction; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.NotUpdatedException; import greencity.repository.AchievementRepo; -import greencity.repository.UserAchievementRepo; - import java.util.List; import java.util.stream.Collectors; @@ -208,7 +207,7 @@ public AchievementVO findByCategoryIdAndCondition(Long categoryId, Integer condi */ @Override public void calculateAchievements(Long id, - AchievementCategoryType achievementCategory) { - achievementCalculation.calculateAchievement(id, achievementCategory); + AchievementCategoryType achievementCategory, AchievementAction achievementAction) { + achievementCalculation.calculateAchievement(id, achievementCategory, achievementAction); } } diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index fb32e0b4ef..af56a33c88 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -13,10 +13,7 @@ import greencity.entity.EcoNews; import greencity.entity.EcoNewsComment; import greencity.entity.User; -import greencity.enums.AchievementCategoryType; -import greencity.enums.CommentStatus; -import greencity.enums.Role; -import greencity.enums.RatingCalculationEnum; +import greencity.enums.*; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; @@ -79,7 +76,7 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq } CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY)); + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); ecoNewsComment.setStatus(CommentStatus.ORIGINAL); diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 55207243ff..86116e8a25 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -16,11 +16,7 @@ import greencity.dto.user.UserVO; import greencity.entity.*; import greencity.entity.localization.TagTranslation; -import greencity.enums.AchievementCategoryType; -import greencity.enums.Role; -import greencity.enums.CommentStatus; -import greencity.enums.TagType; -import greencity.enums.RatingCalculationEnum; +import greencity.enums.*; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.NotSavedException; @@ -82,7 +78,7 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS)); + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); return addEcoNewsDtoResponse; } @@ -100,7 +96,7 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, sendEmailDto(ecoNewsDto, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS)); + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); UserVO user = userService.findByEmail(email); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, user)); @@ -430,7 +426,7 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { CompletableFuture .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY)); + .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); } /** diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 3f535699f8..65d0d449d0 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -37,10 +37,8 @@ import greencity.entity.User; import greencity.entity.UserShoppingListItem; import greencity.entity.localization.ShoppingListItemTranslation; -import greencity.enums.AchievementCategoryType; -import greencity.enums.HabitAssignStatus; -import greencity.enums.ShoppingListItemStatus; -import greencity.enums.RatingCalculationEnum; +import greencity.enums.*; + import java.time.LocalDate; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; @@ -77,7 +75,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; -import javax.servlet.http.HttpServletRequest; /** * Implementation of {@link HabitAssignService}. @@ -753,7 +750,7 @@ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, int habitStreak = countNewHabitStreak(habitAssign.getHabitStatusCalendars()); habitAssign.setHabitStreak(habitStreak); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(userId, AchievementCategoryType.HABIT)); + .calculateAchievement(userId, AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); if (isHabitAcquired(habitAssign)) { habitAssign.setStatus(HabitAssignStatus.ACQUIRED); diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index f801a59c18..77e02c1c30 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -2,13 +2,12 @@ import greencity.ModelUtils; import greencity.client.RestClient; -import greencity.dto.achievement.AchievementVO; -import greencity.dto.achievement.UserVOAchievement; import greencity.dto.achievementcategory.AchievementCategoryVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementAction; import greencity.repository.AchievementCategoryRepo; import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; @@ -22,7 +21,6 @@ import org.modelmapper.ModelMapper; import java.util.Collections; -import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -66,7 +64,7 @@ void calculateAchievement() { when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) .thenReturn(achievementCategoryVO); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)).thenReturn(userActionVO); - achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS); + achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); assertEquals(count + 1, userActionVO.getCount()); } } diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index dd208ded0e..4bf04755a7 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -7,21 +7,18 @@ import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.*; import greencity.dto.achievementcategory.AchievementCategoryVO; -import greencity.dto.language.LanguageVO; import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.Achievement; import greencity.entity.AchievementCategory; -import greencity.entity.Language; -import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementAction; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotUpdatedException; import greencity.repository.AchievementRepo; import java.util.*; -import java.util.stream.Collectors; import greencity.repository.UserAchievementRepo; import greencity.repository.UserRepo; @@ -31,8 +28,6 @@ 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; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -203,9 +198,9 @@ void findByCategoryIdAndCondition() { @Test void calculateAchievement() { - achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS); + achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); verify(achievementCalculation).calculateAchievement( anyLong(), - any(AchievementCategoryType.class)); + any(AchievementCategoryType.class), AchievementAction.ASSIGN); } } From 2641893b6dd9778056bccdf32e604bb62653e2c5 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 10:32:19 +0300 Subject: [PATCH 27/51] Fixed test to work --- .../greencity/achievement/AchievementCalculation.java | 3 ++- service/src/test/java/greencity/ModelUtils.java | 4 ++-- .../greencity/achievement/AchievementCalculationTest.java | 8 +++++++- .../greencity/service/AchievementServiceImplTest.java | 3 ++- 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 72b5473300..ab54aeb7cd 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -50,7 +50,7 @@ public AchievementCalculation( UserAchievementRepo userAchievementRepo, UserRepo userRepo, AchievementRepo achievementRepo, - AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation) { + AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation,UserService userService) { this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; @@ -58,6 +58,7 @@ public AchievementCalculation( this.userRepo = userRepo; this.achievementRepo = achievementRepo; this.ratingCalculation = ratingCalculation; + this.userService = userService; } /** diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index f94c228375..a3b02fe3ec 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1384,7 +1384,7 @@ public static Achievement getAchievement() { } public static AchievementCategory getAchievementCategory() { - return new AchievementCategory(1L, "Name"); + return new AchievementCategory(1L, "Name",Collections.emptyList()); } public static AchievementVO getAchievementVO() { @@ -1408,7 +1408,7 @@ public static AchievementManagementDto getAchievementManagementDto() { } public static UserAchievementVO getUserAchievementVO() { - return new UserAchievementVO(1L, getUserVO(), getAchievementVO()); + return new UserAchievementVO(1L, getUserVO(), getAchievementVO(),true); } public static UserAchievement getUserAchievement() { diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index 77e02c1c30..394a57dc7e 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -8,6 +8,7 @@ import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; import greencity.enums.AchievementAction; +import greencity.enums.RatingCalculationEnum; import greencity.repository.AchievementCategoryRepo; import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; @@ -21,6 +22,7 @@ import org.modelmapper.ModelMapper; import java.util.Collections; +import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -46,9 +48,12 @@ class AchievementCalculationTest { private UserRepo userRepo; @Mock private AchievementCategoryRepo achievementCategoryRepo; + @Mock + private RatingCalculationEnum ratingCalculationEnum; @InjectMocks private AchievementCalculation achievementCalculation; - + @Mock + private UserService userService; @Test void calculateAchievement() { AchievementCategoryVO achievementCategoryVO = ModelUtils.getAchievementCategoryVO(); @@ -64,6 +69,7 @@ void calculateAchievement() { when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) .thenReturn(achievementCategoryVO); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)).thenReturn(userActionVO); + when(userService.findById(any())).thenReturn(ModelUtils.getUserVO()); achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); assertEquals(count + 1, userActionVO.getCount()); } diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 4bf04755a7..4e31cdef41 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -201,6 +201,7 @@ void calculateAchievement() { achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); verify(achievementCalculation).calculateAchievement( anyLong(), - any(AchievementCategoryType.class), AchievementAction.ASSIGN); + any(AchievementCategoryType.class), + eq( AchievementAction.ASSIGN)); } } From c4c05eccbccacccb2429c81784d1583b94563e0e Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 10:38:45 +0300 Subject: [PATCH 28/51] Added preconditions to changelog --- .../ch-add-column-achievements-Spodaryk.xml | 18 ++++++++++++++++++ .../ch-add-value-achievements-Spodaryk.xml | 7 +------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml index 609532902b..58a9afaba0 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-column-achievements-Spodaryk.xml @@ -3,6 +3,23 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd"> + + + + + + + + + + + + + + + + + @@ -26,4 +43,5 @@ + diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml index 1012a0bb2c..ac309d4688 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml @@ -2,16 +2,11 @@ - - - - - - + From 283d1fea8ea98a47e4487091b7dcfc139b30ea5e Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 10:41:58 +0300 Subject: [PATCH 29/51] Fixed error when enum not found --- .../src/main/java/greencity/constant/ErrorMessage.java | 2 ++ .../main/java/greencity/enums/RatingCalculationEnum.java | 7 +++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/service-api/src/main/java/greencity/constant/ErrorMessage.java b/service-api/src/main/java/greencity/constant/ErrorMessage.java index b1a554277e..e16883c6a4 100644 --- a/service-api/src/main/java/greencity/constant/ErrorMessage.java +++ b/service-api/src/main/java/greencity/constant/ErrorMessage.java @@ -1,6 +1,8 @@ package greencity.constant; public final class ErrorMessage { + public static final String RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME= + "RatingCalculationEnum with such name does not exist: "; public static final String CUSTOM_SHOPPING_LIST_ITEM_NOT_FOUND_BY_ID = "Custom shopping list item with such id does not exist."; public static final String DUPLICATED_CUSTOM_SHOPPING_LIST_ITEM = "CustomShoppingListItems should be unique"; diff --git a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java index b7c69c7cbf..d3a0e561c3 100644 --- a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java +++ b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java @@ -1,5 +1,7 @@ package greencity.enums; +import greencity.constant.ErrorMessage; +import greencity.exception.exceptions.NotUpdatedException; import lombok.Getter; @Getter @@ -14,7 +16,6 @@ public enum RatingCalculationEnum { DELETE_COMMENT_OR_REPLY(-2), UNLIKE_COMMENT_OR_REPLY(-10), UNDO_SHARE_NEWS(-20), - ACQUIRED_HABIT_14_DAYS(20), ACQUIRED_HABIT_21_DAYS(30), ACQUIRED_HABIT_30_DAYS(40), @@ -80,7 +81,6 @@ public enum RatingCalculationEnum { UNDO_FIRST_50_ACHIEVEMENTS(-100), UNDO_FIRST_100_ACHIEVEMENTS(-200); - private final int ratingPoints; RatingCalculationEnum(int ratingPoints) { @@ -91,8 +91,7 @@ public static RatingCalculationEnum findEnumByName(String name) { try { return RatingCalculationEnum.valueOf(name); } catch (IllegalArgumentException e) { - return null; // повертаємо null, якщо елемент не знайдений + throw new NotUpdatedException(ErrorMessage.RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME+name); } } - } From c2398955eb34ba7f76e873738d0d65ef2b080af3 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 10:57:37 +0300 Subject: [PATCH 30/51] Added preconditions to changelog --- .../logs/ch-delete-table-achievement_translations-Spodaryk.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml index aed248f722..014546a079 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-delete-table-achievement_translations-Spodaryk.xml @@ -3,6 +3,9 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd"> + + + \ No newline at end of file From da968f6539d53cc525f7f3b136615e54460e2da3 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 12:02:42 +0300 Subject: [PATCH 31/51] Fixed rating calculation and added counting of score --- .../java/greencity/service/UserService.java | 1 + .../achievement/AchievementCalculation.java | 46 +-- .../greencity/rating/RatingCalculation.java | 26 +- .../greencity/service/EcoNewsServiceImpl.java | 281 +++++++++--------- .../greencity/service/UserServiceImpl.java | 8 + 5 files changed, 178 insertions(+), 184 deletions(-) diff --git a/service-api/src/main/java/greencity/service/UserService.java b/service-api/src/main/java/greencity/service/UserService.java index 596d4f622a..b72a3ffa63 100644 --- a/service-api/src/main/java/greencity/service/UserService.java +++ b/service-api/src/main/java/greencity/service/UserService.java @@ -14,6 +14,7 @@ import java.util.Optional; public interface UserService { + void save(UserVO userVO); /** * Method that allow you to find not 'DEACTIVATED' {@link UserVO} by email. * diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index ab54aeb7cd..924624b7ac 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -50,7 +50,7 @@ public AchievementCalculation( UserAchievementRepo userAchievementRepo, UserRepo userRepo, AchievementRepo achievementRepo, - AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation,UserService userService) { + AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation, UserService userService) { this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; @@ -75,15 +75,8 @@ public void calculateAchievement(Long userId, AchievementCategoryType category, userActionService.updateUserActions(userActionVO); checkAchievements(achievementCategoryVO.getId(), count, userId, achievementAction); - UserVO user = userService.findById(userId); - - String enumName = achievementAction.equals(AchievementAction.ASSIGN) ? achievementCategoryVO.getName() : "UNDO_" + achievementCategoryVO.getName(); - RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName(enumName); - - if (reason != null) { - CompletableFuture.runAsync(() -> ratingCalculation.ratingCalculation(reason, user)); - } } + /** * Update the count of user actions based on achievement status. * @@ -92,7 +85,7 @@ public void calculateAchievement(Long userId, AchievementCategoryType category, * @return Updated count of user actions. */ private int updateCount(UserActionVO userActionVO, AchievementAction achievementAction) { - int count = achievementAction.equals(AchievementAction.ASSIGN)?userActionVO.getCount()+1:userActionVO.getCount()-1; + int count = achievementAction.equals(AchievementAction.ASSIGN) ? userActionVO.getCount() + 1 : userActionVO.getCount() - 1; userActionVO.setCount(count); return count; } @@ -107,18 +100,19 @@ private int updateCount(UserActionVO userActionVO, AchievementAction achievement */ private void checkAchievements(Long achievementCategoryId, Integer count, Long userId, AchievementAction achievementAction) { AchievementVO achievementVO = achievementService.findByCategoryIdAndCondition(achievementCategoryId, count); - if (achievementVO != null) { - switch (achievementAction) { - case ASSIGN: - saveAchievementToUser(userId, achievementCategoryId, count); - break; - case DELETE: - deleteAchievementFromUser(userId, achievementCategoryId, count); - break; - } + if (achievementVO != null) { + switch (achievementAction) { + case ASSIGN: + saveAchievementToUser(userId, achievementCategoryId, count); + break; + case DELETE: + deleteAchievementFromUser(userId, achievementCategoryId, count); + break; + } } } + /** * Save an achievement to a user's record. * @@ -137,6 +131,12 @@ private void saveAchievementToUser(Long userId, Long achievementCategoryId, int .user(userRepo.findById(userId) .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) .build(); + RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName(achievement.getTitle()); + UserVO user = userService.findById(userId); + + if (reason != null) { + ratingCalculation.ratingCalculation(reason, user); + } userAchievementRepo.save(userAchievement); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.ASSIGN); } @@ -153,11 +153,19 @@ private void deleteAchievementFromUser(Long userId, Long achievementCategoryId, achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) .orElseThrow(() -> new NoSuchElementException( ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); + UserAchievement userAchievement = UserAchievement.builder() .achievement(achievement) .user(userRepo.findById(userId) .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) .build(); + + RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName("UNDO_" + achievement.getTitle()); + UserVO user = userService.findById(userId); + + if (reason != null) { + ratingCalculation.ratingCalculation(reason, user); + } userAchievementRepo.delete(userAchievement); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.DELETE); } diff --git a/service/src/main/java/greencity/rating/RatingCalculation.java b/service/src/main/java/greencity/rating/RatingCalculation.java index a386010f86..e8a07e725b 100644 --- a/service/src/main/java/greencity/rating/RatingCalculation.java +++ b/service/src/main/java/greencity/rating/RatingCalculation.java @@ -7,6 +7,7 @@ import greencity.entity.User; import greencity.enums.RatingCalculationEnum; import greencity.service.RatingStatisticsService; +import greencity.service.UserService; import lombok.AllArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Component; @@ -22,6 +23,7 @@ public class RatingCalculation { private RatingStatisticsService ratingStatisticsService; private final ModelMapper modelMapper; private final HttpServletRequest httpServletRequest; + private UserService userService; /** * Method that calculates the user rating. @@ -30,10 +32,9 @@ public class RatingCalculation { * @param userVo of {@link UserVO} */ public void ratingCalculation(RatingCalculationEnum rating, UserVO userVo) { - String accessToken = httpServletRequest.getHeader(AUTHORIZATION); User user = modelMapper.map(userVo, User.class); userVo.setRating(userVo.getRating() + rating.getRatingPoints()); - restClient.save(userVo, accessToken); + userService.save(userVo); RatingStatistics ratingStatistics = RatingStatistics .builder() .rating(userVo.getRating()) @@ -43,24 +44,5 @@ public void ratingCalculation(RatingCalculationEnum rating, UserVO userVo) { .build(); ratingStatisticsService.save(modelMapper.map(ratingStatistics, RatingStatisticsVO.class)); } - /** - * Method that calculates the user rating. - * - * @param rating of {@link RatingCalculationEnum} - * @param userVo of {@link UserVO} - */ - public void ratingCalculation(RatingCalculationEnum rating, int points, UserVO userVo) { - String accessToken = httpServletRequest.getHeader(AUTHORIZATION); - User user = modelMapper.map(userVo, User.class); - userVo.setRating(userVo.getRating() +points); - restClient.save(userVo, accessToken); - RatingStatistics ratingStatistics = RatingStatistics - .builder() - .rating(userVo.getRating()) - .ratingCalculationEnum(rating) - .user(user) - .pointsChanged(rating.getRatingPoints()) - .build(); - ratingStatisticsService.save(modelMapper.map(ratingStatistics, RatingStatisticsVO.class)); - } + } diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 86116e8a25..398433ca9f 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -71,14 +71,14 @@ public class EcoNewsServiceImpl implements EcoNewsService { @CacheEvict(value = CacheConstants.NEWEST_ECO_NEWS_CACHE_NAME, allEntries = true) @Override public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, - MultipartFile image, String email) { + MultipartFile image, String email) { EcoNews toSave = genericSave(addEcoNewsDtoRequest, image, email); AddEcoNewsDtoResponse addEcoNewsDtoResponse = modelMapper.map(toSave, AddEcoNewsDtoResponse.class); sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); + .calculateAchievement(toSave.getAuthor().getId(), + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); return addEcoNewsDtoResponse; } @@ -87,20 +87,17 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, * * @author Danylo Hlynskyi. */ - @CacheEvict(value = CacheConstants.NEWEST_ECO_NEWS_CACHE_NAME, allEntries = true) +// @CacheEvict(value = CacheConstants.NEWEST_ECO_NEWS_CACHE_NAME, allEntries = true) @Override public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, MultipartFile image, String email) { EcoNews toSave = genericSave(addEcoNewsDtoRequest, image, email); EcoNewsGenericDto ecoNewsDto = getEcoNewsGenericDtoWithAllTags(toSave); sendEmailDto(ecoNewsDto, toSave.getAuthor()); - CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); UserVO user = userService.findByEmail(email); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, user)); - + ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, user); + achievementCalculation.calculateAchievement(toSave.getAuthor().getId(), + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); return ecoNewsDto; } @@ -110,18 +107,18 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, * @author Zakhar Veremchuk. */ public void sendEmailDto(AddEcoNewsDtoResponse addEcoNewsDtoResponse, - User user) { + User user) { String accessToken = httpServletRequest.getHeader(AUTHORIZATION); PlaceAuthorDto placeAuthorDto = modelMapper.map(user, PlaceAuthorDto.class); EcoNewsForSendEmailDto dto = EcoNewsForSendEmailDto.builder() - .author(placeAuthorDto) - .creationDate(addEcoNewsDtoResponse.getCreationDate()) - .unsubscribeToken(accessToken) - .text(addEcoNewsDtoResponse.getText()) - .title(addEcoNewsDtoResponse.getTitle()) - .source(addEcoNewsDtoResponse.getSource()) - .imagePath(addEcoNewsDtoResponse.getImagePath()) - .build(); + .author(placeAuthorDto) + .creationDate(addEcoNewsDtoResponse.getCreationDate()) + .unsubscribeToken(accessToken) + .text(addEcoNewsDtoResponse.getText()) + .title(addEcoNewsDtoResponse.getTitle()) + .source(addEcoNewsDtoResponse.getSource()) + .imagePath(addEcoNewsDtoResponse.getImagePath()) + .build(); restClient.addEcoNews(dto); } @@ -131,18 +128,18 @@ public void sendEmailDto(AddEcoNewsDtoResponse addEcoNewsDtoResponse, * @author Danylo Hlynskyi. */ public void sendEmailDto(EcoNewsGenericDto ecoNewsDto, - User user) { + User user) { String accessToken = httpServletRequest.getHeader(AUTHORIZATION); PlaceAuthorDto placeAuthorDto = modelMapper.map(user, PlaceAuthorDto.class); EcoNewsForSendEmailDto dto = EcoNewsForSendEmailDto.builder() - .author(placeAuthorDto) - .creationDate(ecoNewsDto.getCreationDate()) - .unsubscribeToken(accessToken) - .text(ecoNewsDto.getContent()) - .title(ecoNewsDto.getTitle()) - .imagePath(ecoNewsDto.getImagePath()) - .source(ecoNewsDto.getSource()) - .build(); + .author(placeAuthorDto) + .creationDate(ecoNewsDto.getCreationDate()) + .unsubscribeToken(accessToken) + .text(ecoNewsDto.getContent()) + .title(ecoNewsDto.getTitle()) + .imagePath(ecoNewsDto.getImagePath()) + .source(ecoNewsDto.getSource()) + .build(); restClient.addEcoNews(dto); } @@ -231,8 +228,8 @@ public PageableAdvancedDto findAllByUser(UserVO user, Pageabl /** * {@inheritDoc} * - * @author Kovaliv Taras. * @return + * @author Kovaliv Taras. */ @Override public PageableAdvancedDto find(Pageable page, List tags) { @@ -244,37 +241,37 @@ public PageableAdvancedDto find(Pageable page, List t private PageableAdvancedDto buildPageableAdvancedDto(Page ecoNewsPage) { List ecoNewsDtos = ecoNewsPage.stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .collect(Collectors.toList()); return new PageableAdvancedDto<>( - ecoNewsDtos, - ecoNewsPage.getTotalElements(), - ecoNewsPage.getPageable().getPageNumber(), - ecoNewsPage.getTotalPages(), - ecoNewsPage.getNumber(), - ecoNewsPage.hasPrevious(), - ecoNewsPage.hasNext(), - ecoNewsPage.isFirst(), - ecoNewsPage.isLast()); + ecoNewsDtos, + ecoNewsPage.getTotalElements(), + ecoNewsPage.getPageable().getPageNumber(), + ecoNewsPage.getTotalPages(), + ecoNewsPage.getNumber(), + ecoNewsPage.hasPrevious(), + ecoNewsPage.hasNext(), + ecoNewsPage.isFirst(), + ecoNewsPage.isLast()); } private PageableAdvancedDto buildPageableAdvancedGeneticDto(Page ecoNewsPage) { List ecoNewsDtos = ecoNewsPage.stream() - .map(this::getEcoNewsGenericDtoWithEnTags) - .collect(Collectors.toList()); + .map(this::getEcoNewsGenericDtoWithEnTags) + .collect(Collectors.toList()); return new PageableAdvancedDto<>( - ecoNewsDtos, - ecoNewsPage.getTotalElements(), - ecoNewsPage.getPageable().getPageNumber(), - ecoNewsPage.getTotalPages(), - ecoNewsPage.getNumber(), - ecoNewsPage.hasPrevious(), - ecoNewsPage.hasNext(), - ecoNewsPage.isFirst(), - ecoNewsPage.isLast()); + ecoNewsDtos, + ecoNewsPage.getTotalElements(), + ecoNewsPage.getPageable().getPageNumber(), + ecoNewsPage.getTotalPages(), + ecoNewsPage.getNumber(), + ecoNewsPage.hasPrevious(), + ecoNewsPage.hasNext(), + ecoNewsPage.isFirst(), + ecoNewsPage.isLast()); } /** @@ -285,8 +282,8 @@ private PageableAdvancedDto buildPageableAdvancedGeneticDto(P @Override public EcoNewsVO findById(Long id) { EcoNews ecoNews = ecoNewsRepo - .findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .findById(id) + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); return modelMapper.map(ecoNews, EcoNewsVO.class); } @@ -298,7 +295,7 @@ public EcoNewsVO findById(Long id) { @Override public EcoNewsDto getById(Long id) { EcoNews ecoNews = ecoNewsRepo.findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); return modelMapper.map(ecoNews, EcoNewsDto.class); } @@ -310,13 +307,13 @@ public EcoNewsDto getById(Long id) { @Override public EcoNewsDto findDtoByIdAndLanguage(Long id, String language) { var ecoNews = ecoNewsRepo.findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); List tags = new ArrayList<>(); for (String lang : languageCode) { tags.addAll(ecoNews.getTags().stream().flatMap(t -> t.getTagTranslations().stream()) - .filter(tagTranslation -> tagTranslation.getLanguage().getCode().equals(lang)) - .map(TagTranslation::getName) - .collect(Collectors.toList())); + .filter(tagTranslation -> tagTranslation.getLanguage().getCode().equals(lang)) + .map(TagTranslation::getName) + .collect(Collectors.toList())); } return getEcoNewsDto(ecoNews, tags); } @@ -334,7 +331,7 @@ public void delete(Long id, UserVO user) { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user)); + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user)); ecoNewsRepo.deleteById(ecoNewsVO.getId()); } @@ -365,14 +362,14 @@ public PageableDto search(Pageable pageable, String searchQuery, private PageableDto getSearchNewsDtoPageableDto(Page page) { List searchNewsDtos = page.stream() - .map(ecoNews -> modelMapper.map(ecoNews, SearchNewsDto.class)) - .collect(Collectors.toList()); + .map(ecoNews -> modelMapper.map(ecoNews, SearchNewsDto.class)) + .collect(Collectors.toList()); return new PageableDto<>( - searchNewsDtos, - page.getTotalElements(), - page.getPageable().getPageNumber(), - page.getTotalPages()); + searchNewsDtos, + page.getTotalElements(), + page.getPageable().getPageNumber(), + page.getTotalPages()); } /** @@ -384,8 +381,8 @@ private PageableDto getSearchNewsDtoPageableDto(Page pag @Override public List getAllPublishedNewsByUserId(Long userId) { return ecoNewsRepo.findAllByUserId(userId).stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .collect(Collectors.toList()); } /** @@ -398,8 +395,8 @@ public List getAllPublishedNewsByUserId(Long userId) { @Override public List getAllPublishedNewsByUser(UserVO user) { return ecoNewsRepo.findAllByUserId(user.getId()).stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .collect(Collectors.toList()); } /** @@ -424,9 +421,9 @@ public Long getAmountOfPublishedNewsByUserId(Long id) { public void likeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().add(user); CompletableFuture - .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); + .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); } /** @@ -439,7 +436,7 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { public void unlikeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().removeIf(u -> u.getId().equals(user.getId())); CompletableFuture - .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); + .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); } @Override @@ -449,28 +446,28 @@ public PageableAdvancedDto searchEcoNewsBy(Pageable paging, String q } private void enhanceWithNewManagementData(EcoNews toUpdate, EcoNewsDtoManagement ecoNewsDtoManagement, - MultipartFile image) { + MultipartFile image) { toUpdate.setTitle(ecoNewsDtoManagement.getTitle()); toUpdate.setText(ecoNewsDtoManagement.getText()); toUpdate.setTags(modelMapper - .map(tagService.findTagsByNamesAndType(ecoNewsDtoManagement.getTags(), TagType.ECO_NEWS), - new TypeToken>() { - }.getType())); + .map(tagService.findTagsByNamesAndType(ecoNewsDtoManagement.getTags(), TagType.ECO_NEWS), + new TypeToken>() { + }.getType())); if (image != null) { toUpdate.setImagePath(fileService.upload(image)); } } private void enhanceWithNewData(EcoNews toUpdate, UpdateEcoNewsDto updateEcoNewsDto, - MultipartFile image) { + MultipartFile image) { toUpdate.setTitle(updateEcoNewsDto.getTitle()); toUpdate.setText(updateEcoNewsDto.getContent()); toUpdate.setShortInfo(updateEcoNewsDto.getShortInfo()); toUpdate.setSource(updateEcoNewsDto.getSource()); toUpdate.setTags(modelMapper.map(tagService - .findTagsByNamesAndType(updateEcoNewsDto.getTags(), TagType.ECO_NEWS), - new TypeToken>() { - }.getType())); + .findTagsByNamesAndType(updateEcoNewsDto.getTags(), TagType.ECO_NEWS), + new TypeToken>() { + }.getType())); if (updateEcoNewsDto.getImage() != null) { image = fileService.convertToMultipartImage(updateEcoNewsDto.getImage()); } @@ -493,7 +490,7 @@ public void update(EcoNewsDtoManagement ecoNewsDtoManagement, MultipartFile imag /** * {@inheritDoc} - * + * * @return EcoNewsGenericDto */ @CacheEvict(value = CacheConstants.NEWEST_ECO_NEWS_CACHE_NAME, allEntries = true) @@ -510,7 +507,7 @@ public EcoNewsGenericDto update(UpdateEcoNewsDto updateEcoNewsDto, MultipartFile @Override public PageableAdvancedDto getFilteredDataForManagementByPage( - Pageable pageable, EcoNewsViewDto ecoNewsViewDto) { + Pageable pageable, EcoNewsViewDto ecoNewsViewDto) { Page page = ecoNewsRepo.findAll(getSpecification(ecoNewsViewDto), pageable); return buildPageableAdvancedDto(page); } @@ -647,10 +644,10 @@ public List buildSearchCriteria(EcoNewsViewDto ecoNewsViewDto) { if (!ecoNewsViewDto.getStartDate().isEmpty() && !ecoNewsViewDto.getEndDate().isEmpty()) { searchCriteria = SearchCriteria.builder() - .key(EcoNews_.CREATION_DATE) - .type("dateRange") - .value(new String[] {ecoNewsViewDto.getStartDate(), ecoNewsViewDto.getEndDate()}) - .build(); + .key(EcoNews_.CREATION_DATE) + .type("dateRange") + .value(new String[]{ecoNewsViewDto.getStartDate(), ecoNewsViewDto.getEndDate()}) + .build(); criteriaList.add(searchCriteria); } @@ -660,25 +657,25 @@ public List buildSearchCriteria(EcoNewsViewDto ecoNewsViewDto) { private void setValueIfNotEmpty(List searchCriteria, String key, String value) { if (!StringUtils.isEmpty(value)) { searchCriteria.add(SearchCriteria.builder() - .key(key) - .type(key) - .value(value) - .build()); + .key(key) + .type(key) + .value(value) + .build()); } } private List getEcoNewsList(List ecoNewsList) { return ecoNewsList - .stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .stream() + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .collect(Collectors.toList()); } private EcoNewsGenericDto getEcoNewsGenericDtoWithAllTags(EcoNews ecoNews) { List tags = ecoNews.getTags().stream() - .flatMap(t -> t.getTagTranslations().stream()) - .map(TagTranslation::getName) - .collect(Collectors.toList()); + .flatMap(t -> t.getTagTranslations().stream()) + .map(TagTranslation::getName) + .collect(Collectors.toList()); return buildEcoNewsGenericDto(ecoNews, tags); } @@ -687,10 +684,10 @@ private EcoNewsGenericDto getEcoNewsGenericDtoWithEnTags(EcoNews ecoNews) { List tags = new ArrayList<>(); for (String language : languageCode) { tags.addAll(ecoNews.getTags().stream() - .flatMap(t -> t.getTagTranslations().stream()) - .filter(t -> t.getLanguage().getCode().equals(language)) - .map(TagTranslation::getName) - .collect(Collectors.toList())); + .flatMap(t -> t.getTagTranslations().stream()) + .filter(t -> t.getLanguage().getCode().equals(language)) + .map(TagTranslation::getName) + .collect(Collectors.toList())); } return buildEcoNewsGenericDto(ecoNews, tags); @@ -700,44 +697,44 @@ private EcoNewsGenericDto buildEcoNewsGenericDto(EcoNews ecoNews, List t User author = ecoNews.getAuthor(); var ecoNewsAuthorDto = new EcoNewsAuthorDto(author.getId(), author.getName()); int countOfComments = ecoNews.getEcoNewsComments() != null - ? (int) ecoNews.getEcoNewsComments().stream() + ? (int) ecoNews.getEcoNewsComments().stream() .filter(ecoNewsComment -> !ecoNewsComment.getStatus().equals(CommentStatus.DELETED)).count() - : 0; + : 0; int countOfEcoNews = ecoNewsRepo.totalCountOfCreationNews(); return EcoNewsGenericDto.builder() - .id(ecoNews.getId()) - .imagePath(ecoNews.getImagePath()) - .author(ecoNewsAuthorDto) - .tagsEn(tags.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) - .tagsUa(tags.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) - .shortInfo(ecoNews.getShortInfo()) - .content(ecoNews.getText()) - .title(ecoNews.getTitle()) - .creationDate(ecoNews.getCreationDate()) - .source(ecoNews.getSource()) - .likes(ecoNews.getUsersLikedNews() != null ? ecoNews.getUsersLikedNews().size() : 0) - .countComments(countOfComments) - .countOfEcoNews(countOfEcoNews) - .build(); + .id(ecoNews.getId()) + .imagePath(ecoNews.getImagePath()) + .author(ecoNewsAuthorDto) + .tagsEn(tags.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) + .tagsUa(tags.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) + .shortInfo(ecoNews.getShortInfo()) + .content(ecoNews.getText()) + .title(ecoNews.getTitle()) + .creationDate(ecoNews.getCreationDate()) + .source(ecoNews.getSource()) + .likes(ecoNews.getUsersLikedNews() != null ? ecoNews.getUsersLikedNews().size() : 0) + .countComments(countOfComments) + .countOfEcoNews(countOfEcoNews) + .build(); } private EcoNewsDto getEcoNewsDto(EcoNews ecoNews, List list) { User author = ecoNews.getAuthor(); var ecoNewsAuthorDto = new EcoNewsAuthorDto(author.getId(), - author.getName()); + author.getName()); return EcoNewsDto.builder() - .id(ecoNews.getId()) - .imagePath(ecoNews.getImagePath()) - .author(ecoNewsAuthorDto) - .likes(ecoNews.getUsersLikedNews().size()) - .tags(list.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) - .tagsUa(list.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) - .shortInfo(ecoNews.getShortInfo()) - .content(ecoNews.getText()) - .title(ecoNews.getTitle()) - .creationDate(ecoNews.getCreationDate()) - .build(); + .id(ecoNews.getId()) + .imagePath(ecoNews.getImagePath()) + .author(ecoNewsAuthorDto) + .likes(ecoNews.getUsersLikedNews().size()) + .tags(list.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) + .tagsUa(list.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) + .shortInfo(ecoNews.getShortInfo()) + .content(ecoNews.getText()) + .title(ecoNews.getTitle()) + .creationDate(ecoNews.getCreationDate()) + .build(); } /** @@ -748,19 +745,19 @@ private EcoNewsDto getEcoNewsDto(EcoNews ecoNews, List list) { */ public EcoNewContentSourceDto getContentAndSourceForEcoNewsById(Long id) { EcoNews ecoNews = ecoNewsRepo.findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); return getContentSourceEcoNewsDto(ecoNews); } private EcoNewContentSourceDto getContentSourceEcoNewsDto(EcoNews ecoNews) { return EcoNewContentSourceDto.builder() - .content(ecoNews.getText()) - .source(ecoNews.getSource()) - .build(); + .content(ecoNews.getText()) + .source(ecoNews.getSource()) + .build(); } private EcoNews genericSave(AddEcoNewsDtoRequest addEcoNewsDtoRequest, - MultipartFile image, String email) { + MultipartFile image, String email) { EcoNews toSave = modelMapper.map(addEcoNewsDtoRequest, EcoNews.class); UserVO byEmail = restClient.findByEmail(email); User user = modelMapper.map(byEmail, User.class); @@ -779,16 +776,14 @@ private EcoNews genericSave(AddEcoNewsDtoRequest addEcoNewsDtoRequest, } List tagVOS = tagService.findTagsByNamesAndType( - addEcoNewsDtoRequest.getTags(), TagType.ECO_NEWS); + addEcoNewsDtoRequest.getTags(), TagType.ECO_NEWS); toSave.setTags(modelMapper.map(tagVOS, - new TypeToken>() { - }.getType())); + new TypeToken>() { + }.getType())); try { ecoNewsRepo.save(toSave); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, byEmail)); - } catch (DataIntegrityViolationException e) { + } catch (DataIntegrityViolationException e) { throw new NotSavedException(ErrorMessage.ECO_NEWS_NOT_SAVED); } return toSave; @@ -797,8 +792,8 @@ private EcoNews genericSave(AddEcoNewsDtoRequest addEcoNewsDtoRequest, @Override public Set findUsersWhoLikedPost(Long id) { EcoNews ecoNews = ecoNewsRepo - .findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .findById(id) + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); Set usersLikedNews = ecoNews.getUsersLikedNews(); return usersLikedNews.stream().map(u -> modelMapper.map(u, UserVO.class)).collect(Collectors.toSet()); } @@ -806,8 +801,8 @@ public Set findUsersWhoLikedPost(Long id) { @Override public Set findUsersWhoDislikedPost(Long id) { EcoNews ecoNews = ecoNewsRepo - .findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .findById(id) + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); Set usersDislikedNews = ecoNews.getUsersDislikedNews(); return usersDislikedNews.stream().map(u -> modelMapper.map(u, UserVO.class)).collect(Collectors.toSet()); } diff --git a/service/src/main/java/greencity/service/UserServiceImpl.java b/service/src/main/java/greencity/service/UserServiceImpl.java index 9416176050..aeb24ce425 100644 --- a/service/src/main/java/greencity/service/UserServiceImpl.java +++ b/service/src/main/java/greencity/service/UserServiceImpl.java @@ -41,6 +41,14 @@ public class UserServiceImpl implements UserService { private final ModelMapper modelMapper; @Value("300000") private long timeAfterLastActivity; + /** + * {@inheritDoc} + */ + @Override + public void save(UserVO userVO) { + User user=modelMapper.map(userVO, User.class); + userRepo.save(user); + } /** * {@inheritDoc} From f8d30658e1ad64887a3b8f011276d39200d1df1b Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 16:30:18 +0300 Subject: [PATCH 32/51] Fixed tests --- .../main/java/greencity/service/EcoNewsServiceImpl.java | 2 +- .../greencity/achievement/AchievementCalculationTest.java | 1 - .../test/java/greencity/rating/RatingCalculationTest.java | 6 +++++- .../java/greencity/service/EcoNewsServiceImplTest.java | 7 ++++++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 398433ca9f..97117c0bce 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -87,7 +87,7 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, * * @author Danylo Hlynskyi. */ -// @CacheEvict(value = CacheConstants.NEWEST_ECO_NEWS_CACHE_NAME, allEntries = true) + @CacheEvict(value = CacheConstants.NEWEST_ECO_NEWS_CACHE_NAME, allEntries = true) @Override public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, MultipartFile image, String email) { EcoNews toSave = genericSave(addEcoNewsDtoRequest, image, email); diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index 394a57dc7e..7fd9dcf3c0 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -69,7 +69,6 @@ void calculateAchievement() { when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) .thenReturn(achievementCategoryVO); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)).thenReturn(userActionVO); - when(userService.findById(any())).thenReturn(ModelUtils.getUserVO()); achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); assertEquals(count + 1, userActionVO.getCount()); } diff --git a/service/src/test/java/greencity/rating/RatingCalculationTest.java b/service/src/test/java/greencity/rating/RatingCalculationTest.java index 45c87d3d2c..9453677cdb 100644 --- a/service/src/test/java/greencity/rating/RatingCalculationTest.java +++ b/service/src/test/java/greencity/rating/RatingCalculationTest.java @@ -9,6 +9,8 @@ import greencity.entity.User; import greencity.service.RatingStatisticsService; import java.time.ZonedDateTime; + +import greencity.service.UserService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -30,6 +32,8 @@ class RatingCalculationTest { private ModelMapper modelMapper; @Mock private HttpServletRequest httpServletRequest; + @Mock + private UserService userService; @InjectMocks private RatingCalculation ratingCalculation; @@ -60,9 +64,9 @@ void ratingCalculation() { .pointsChanged(rating.getRatingPoints()) .build(); when(modelMapper.map(userVO, User.class)).thenReturn(user); - doNothing().when(restClient).save(userVO, null); when(modelMapper.map(ratingStatistics, RatingStatisticsVO.class)).thenReturn(ratingStatisticsVO); when(ratingStatisticsService.save(ratingStatisticsVO)).thenReturn(ratingStatisticsVO); + ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); verify(ratingStatisticsService).save(ratingStatisticsVO); diff --git a/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java b/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java index 8c47b44471..2c932d8114 100644 --- a/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java +++ b/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java @@ -6,6 +6,7 @@ import greencity.ModelUtils; import greencity.TestConst; +import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.constant.AppConstant; import greencity.dto.PageableAdvancedDto; @@ -84,6 +85,10 @@ class EcoNewsServiceImplTest { @Mock private RatingCalculation ratingCalculation; + @Mock + private AchievementService achievementService; + @Mock + private AchievementCalculation achievementCalculation; @InjectMocks private EcoNewsServiceImpl ecoNewsService; @@ -178,7 +183,7 @@ void saveEcoNews() { when(modelMapper.map(tagVOList, new TypeToken>() { }.getType())).thenReturn(tags); - + when(userService.findByEmail(anyString())).thenReturn(ModelUtils.getUserVO()); EcoNewsGenericDto actual = ecoNewsService.saveEcoNews(addEcoNewsDtoRequest, image, TestConst.EMAIL); assertEquals(ecoNewsGenericDto, actual); From e4a72ceee7b62daff7e7220a0e357d22b6d3a6c1 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 16:56:38 +0300 Subject: [PATCH 33/51] Added logic to achievements to all methods --- .../enums/RatingCalculationEnum.java | 1 + .../service/EcoNewsCommentServiceImpl.java | 14 ++++++++++++- .../greencity/service/EcoNewsServiceImpl.java | 9 +++++++- .../service/EventCommentServiceImpl.java | 21 +++++++++++++++---- .../service/HabitAssignServiceImpl.java | 15 +++++++++++++ .../service/PlaceCommentServiceImpl.java | 13 +++++++++++- 6 files changed, 66 insertions(+), 7 deletions(-) diff --git a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java index d3a0e561c3..9a73e96171 100644 --- a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java +++ b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java @@ -16,6 +16,7 @@ public enum RatingCalculationEnum { DELETE_COMMENT_OR_REPLY(-2), UNLIKE_COMMENT_OR_REPLY(-10), UNDO_SHARE_NEWS(-20), + ACQUIRED_HABIT_14_DAYS(20), ACQUIRED_HABIT_21_DAYS(30), ACQUIRED_HABIT_30_DAYS(40), diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index af56a33c88..fd0e4b5ed8 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -62,7 +62,8 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq UserVO userVO) { EcoNewsVO ecoNewsVO = ecoNewsService.findById(econewsId); EcoNewsComment ecoNewsComment = modelMapper.map(addEcoNewsCommentDtoRequest, EcoNewsComment.class); - ecoNewsComment.setUser(modelMapper.map(userVO, User.class)); + User user=modelMapper.map(userVO, User.class); + ecoNewsComment.setUser(user); ecoNewsComment.setEcoNews(modelMapper.map(ecoNewsVO, EcoNews.class)); if (addEcoNewsCommentDtoRequest.getParentCommentId() != 0) { EcoNewsComment parentComment = @@ -79,6 +80,7 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); + ecoNewsComment.setStatus(CommentStatus.ORIGINAL); return modelMapper.map(ecoNewsCommentRepo.save(ecoNewsComment), AddEcoNewsCommentDtoResponse.class); @@ -166,9 +168,13 @@ public void deleteById(Long id, UserVO userVO) { comment.getComments().forEach(c -> c.setStatus(CommentStatus.DELETED)); } comment.setStatus(CommentStatus.DELETED); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); ecoNewsCommentRepo.save(comment); + } /** @@ -206,11 +212,17 @@ public void like(Long id, UserVO userVO) { EcoNewsCommentVO ecoNewsCommentVO = modelMapper.map(comment, EcoNewsCommentVO.class); if (comment.getUsersLiked().stream() .anyMatch(user -> user.getId().equals(userVO.getId()))) { + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); ecoNewsService.unlikeComment(userVO, ecoNewsCommentVO); } else { ecoNewsService.likeComment(userVO, ecoNewsCommentVO); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); } diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 97117c0bce..b98b20f4b1 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -332,6 +332,10 @@ public void delete(Long id, UserVO user) { } CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE)); + ecoNewsRepo.deleteById(ecoNewsVO.getId()); } @@ -436,7 +440,10 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { public void unlikeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().removeIf(u -> u.getId().equals(user.getId())); CompletableFuture - .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); + .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, user)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); } @Override diff --git a/service/src/main/java/greencity/service/EventCommentServiceImpl.java b/service/src/main/java/greencity/service/EventCommentServiceImpl.java index 008b565a33..ff0b017f3e 100644 --- a/service/src/main/java/greencity/service/EventCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EventCommentServiceImpl.java @@ -1,5 +1,6 @@ package greencity.service; +import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.constant.ErrorMessage; import greencity.dto.PageableDto; @@ -15,9 +16,7 @@ import greencity.entity.User; import greencity.entity.event.Event; import greencity.entity.event.EventComment; -import greencity.enums.CommentStatus; -import greencity.enums.Role; -import greencity.enums.RatingCalculationEnum; +import greencity.enums.*; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; @@ -46,6 +45,7 @@ public class EventCommentServiceImpl implements EventCommentService { private final EventRepo eventRepo; private final RestClient restClient; private final RatingCalculation ratingCalculation; + private AchievementCalculation achievementCalculation; /** * Method to save {@link greencity.entity.event.EventComment}. @@ -93,7 +93,9 @@ public AddEventCommentDtoResponse save(Long eventId, AddEventCommentDtoRequest a CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); - + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); return addEventCommentDtoResponse; } @@ -241,6 +243,10 @@ public void delete(Long eventCommentId, UserVO user) { CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, user)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); + eventCommentRepo.save(eventComment); } @@ -304,8 +310,15 @@ public void like(Long commentId, UserVO userVO) { comment.getUsersLiked().removeIf(user -> user.getId().equals(userVO.getId())); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); + } else { comment.getUsersLiked().add(modelMapper.map(userVO, User.class)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); } diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 65d0d449d0..46cc913857 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -706,6 +706,10 @@ public HabitAssignDto enrollHabit(Long habitAssignId, Long userId, LocalDate dat UserVO userVO = userService.findById(userId); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); + return buildHabitAssignDto(habitAssign, language); } @@ -796,6 +800,9 @@ public HabitAssignDto unenrollHabit(Long habitAssignId, Long userId, LocalDate d UserVO userVO = userService.findById(userId); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE)); return modelMapper.map(habitAssign, HabitAssignDto.class); } @@ -987,6 +994,10 @@ public HabitAssignDto cancelHabitAssign(Long habitId, Long userId) { CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE)); + } habitAssignRepo.save(habitAssignToCancel); return buildHabitAssignDto(habitAssignToCancel, "en"); @@ -1011,6 +1022,10 @@ public void deleteHabitAssign(Long habitAssignId, Long userId) { CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE)); + } userShoppingListItemRepo.deleteShoppingListItemsByHabitAssignId(habitAssign.getId()); customShoppingListItemRepo.deleteCustomShoppingListItemsByHabitId(habitAssign.getHabit().getId()); diff --git a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java index 9c7843467c..663ef1271a 100644 --- a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java @@ -1,5 +1,8 @@ package greencity.service; +import greencity.achievement.AchievementCalculation; +import greencity.enums.AchievementAction; +import greencity.enums.AchievementCategoryType; import greencity.enums.RatingCalculationEnum; import greencity.client.RestClient; import greencity.constant.ErrorMessage; @@ -46,7 +49,7 @@ public class PlaceCommentServiceImpl implements PlaceCommentService { private ModelMapper modelMapper; private final greencity.rating.RatingCalculation ratingCalculation; private final HttpServletRequest httpServletRequest; - +private AchievementCalculation achievementCalculation; /** * {@inheritDoc} * @@ -88,6 +91,10 @@ public CommentReturnDto save(Long placeId, AddCommentDto addCommentDto, String e }); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + return modelMapper.map(placeCommentRepo.save(comment), CommentReturnDto.class); } @@ -104,6 +111,10 @@ public void deleteById(Long id) { UserVO userVO = restClient.findByEmail(authentication.getName()); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); + CompletableFuture.runAsync( + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); + } /** From d048b572287a0a592a8ab1cb6d78bdf45d8e87a4 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Fri, 22 Sep 2023 20:03:59 +0300 Subject: [PATCH 34/51] Formatted and fixed style --- .../controller/AchievementController.java | 1 - .../java/greencity/constant/ErrorMessage.java | 4 +- .../enums/RatingCalculationEnum.java | 10 +- .../greencity/service/AchievementService.java | 3 +- .../java/greencity/service/UserService.java | 11 +- .../achievement/AchievementCalculation.java | 78 ++--- .../greencity/rating/RatingCalculation.java | 1 - .../service/AchievementServiceImpl.java | 2 +- .../service/EcoNewsCommentServiceImpl.java | 15 +- .../greencity/service/EcoNewsServiceImpl.java | 277 +++++++++--------- .../service/EventCommentServiceImpl.java | 19 +- .../service/HabitAssignServiceImpl.java | 18 +- .../service/PlaceCommentServiceImpl.java | 12 +- .../greencity/service/UserServiceImpl.java | 5 +- .../src/test/java/greencity/ModelUtils.java | 4 +- .../AchievementCalculationTest.java | 1 + .../AchievementCategoryVOMapperTest.java | 2 +- .../service/AchievementServiceImplTest.java | 2 +- 18 files changed, 241 insertions(+), 224 deletions(-) diff --git a/core/src/main/java/greencity/controller/AchievementController.java b/core/src/main/java/greencity/controller/AchievementController.java index ee58d64b7e..8838250837 100644 --- a/core/src/main/java/greencity/controller/AchievementController.java +++ b/core/src/main/java/greencity/controller/AchievementController.java @@ -44,5 +44,4 @@ public AchievementController(AchievementService achievementService) { public ResponseEntity> getAll() { return ResponseEntity.status(HttpStatus.OK).body(achievementService.findAll()); } - } diff --git a/service-api/src/main/java/greencity/constant/ErrorMessage.java b/service-api/src/main/java/greencity/constant/ErrorMessage.java index e16883c6a4..eaebbb0d17 100644 --- a/service-api/src/main/java/greencity/constant/ErrorMessage.java +++ b/service-api/src/main/java/greencity/constant/ErrorMessage.java @@ -1,8 +1,8 @@ package greencity.constant; public final class ErrorMessage { - public static final String RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME= - "RatingCalculationEnum with such name does not exist: "; + public static final String RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME = + "RatingCalculationEnum with such name does not exist: "; public static final String CUSTOM_SHOPPING_LIST_ITEM_NOT_FOUND_BY_ID = "Custom shopping list item with such id does not exist."; public static final String DUPLICATED_CUSTOM_SHOPPING_LIST_ITEM = "CustomShoppingListItems should be unique"; diff --git a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java index 9a73e96171..92f7d1fadd 100644 --- a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java +++ b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java @@ -1,6 +1,7 @@ package greencity.enums; import greencity.constant.ErrorMessage; +import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.NotUpdatedException; import lombok.Getter; @@ -88,11 +89,18 @@ public enum RatingCalculationEnum { this.ratingPoints = ratingPoints; } + /** + * Finds the RatingCalculationEnum object corresponding to the given name. + * + * @param name The name of the enum to find. + * @return The found RatingCalculationEnum object. + * @throws NotFoundException if the enum by the given name does not exist. + */ public static RatingCalculationEnum findEnumByName(String name) { try { return RatingCalculationEnum.valueOf(name); } catch (IllegalArgumentException e) { - throw new NotUpdatedException(ErrorMessage.RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME+name); + throw new NotFoundException(ErrorMessage.RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME + name); } } } diff --git a/service-api/src/main/java/greencity/service/AchievementService.java b/service-api/src/main/java/greencity/service/AchievementService.java index 99f7d9f14b..37615be645 100644 --- a/service-api/src/main/java/greencity/service/AchievementService.java +++ b/service-api/src/main/java/greencity/service/AchievementService.java @@ -92,5 +92,6 @@ public interface AchievementService { /** * Method for achievement Calculation. */ - void calculateAchievements(Long id, AchievementCategoryType achievementCategory, AchievementAction achievementAction); + void calculateAchievements(Long id, AchievementCategoryType achievementCategory, + AchievementAction achievementAction); } diff --git a/service-api/src/main/java/greencity/service/UserService.java b/service-api/src/main/java/greencity/service/UserService.java index b72a3ffa63..a3c6edf040 100644 --- a/service-api/src/main/java/greencity/service/UserService.java +++ b/service-api/src/main/java/greencity/service/UserService.java @@ -14,7 +14,16 @@ import java.util.Optional; public interface UserService { - void save(UserVO userVO); + /** + * Saves the provided UserVO object into the repository after mapping it to a + * User entity. This method uses ModelMapper to convert the UserVO object into a + * User entity and then saves it using the User repository. + * + * @param userVO The user value object containing the user details to be saved. + * @see UserVO + */ + void save(UserVO userVO); + /** * Method that allow you to find not 'DEACTIVATED' {@link UserVO} by email. * diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 924624b7ac..3afadabdb1 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -44,13 +44,13 @@ public class AchievementCalculation { * @param achievementCategoryService {@link AchievementCategoryService} */ public AchievementCalculation( - UserActionService userActionService, - @Lazy AchievementService achievementService, - AchievementCategoryService achievementCategoryService, - UserAchievementRepo userAchievementRepo, - UserRepo userRepo, - AchievementRepo achievementRepo, - AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation, UserService userService) { + UserActionService userActionService, + @Lazy AchievementService achievementService, + AchievementCategoryService achievementCategoryService, + UserAchievementRepo userAchievementRepo, + UserRepo userRepo, + AchievementRepo achievementRepo, + AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation, UserService userService) { this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; @@ -62,15 +62,20 @@ public AchievementCalculation( } /** - * Calculate and handle achievements for a user based on specified category and status. + * Calculate and handle achievements for a user based on specified category and + * status. * - * @param userId The user ID for whom the achievement is to be calculated. + * @param userId The user ID for whom the achievement is to be + * calculated. * @param category The category type of the achievement. - * @param achievementAction The status of the achievement (ASSIGN, DELETE, etc.). + * @param achievementAction The status of the achievement (ASSIGN, DELETE, + * etc.). */ - public void calculateAchievement(Long userId, AchievementCategoryType category, AchievementAction achievementAction) { + public void calculateAchievement(Long userId, AchievementCategoryType category, + AchievementAction achievementAction) { AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); - UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory(userId, achievementCategoryVO.getId()); + UserActionVO userActionVO = + userActionService.findUserActionByUserIdAndAchievementCategory(userId, achievementCategoryVO.getId()); int count = updateCount(userActionVO, achievementAction); userActionService.updateUserActions(userActionVO); @@ -85,7 +90,8 @@ public void calculateAchievement(Long userId, AchievementCategoryType category, * @return Updated count of user actions. */ private int updateCount(UserActionVO userActionVO, AchievementAction achievementAction) { - int count = achievementAction.equals(AchievementAction.ASSIGN) ? userActionVO.getCount() + 1 : userActionVO.getCount() - 1; + int count = achievementAction.equals(AchievementAction.ASSIGN) ? userActionVO.getCount() + 1 + : userActionVO.getCount() - 1; userActionVO.setCount(count); return count; } @@ -95,21 +101,19 @@ private int updateCount(UserActionVO userActionVO, AchievementAction achievement * * @param achievementCategoryId The ID of the achievement category. * @param count The count of user actions for the achievement. - * @param userId The user ID for whom the achievement is to be checked. + * @param userId The user ID for whom the achievement is to be + * checked. * @param achievementAction The status of the achievement. */ - private void checkAchievements(Long achievementCategoryId, Integer count, Long userId, AchievementAction achievementAction) { + private void checkAchievements(Long achievementCategoryId, Integer count, Long userId, + AchievementAction achievementAction) { AchievementVO achievementVO = achievementService.findByCategoryIdAndCondition(achievementCategoryId, count); if (achievementVO != null) { - switch (achievementAction) { - case ASSIGN: - saveAchievementToUser(userId, achievementCategoryId, count); - break; - case DELETE: - deleteAchievementFromUser(userId, achievementCategoryId, count); - break; + if (achievementAction.equals(AchievementAction.ASSIGN)) { + saveAchievementToUser(userId, achievementCategoryId, count); + } else { + deleteAchievementFromUser(userId, achievementCategoryId, count); } - } } @@ -123,14 +127,14 @@ private void checkAchievements(Long achievementCategoryId, Integer count, Long u private void saveAchievementToUser(Long userId, Long achievementCategoryId, int count) { Achievement achievement = - achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) - .orElseThrow(() -> new NoSuchElementException( - ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); + achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) + .orElseThrow(() -> new NoSuchElementException( + ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); UserAchievement userAchievement = UserAchievement.builder() - .achievement(achievement) - .user(userRepo.findById(userId) - .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) - .build(); + .achievement(achievement) + .user(userRepo.findById(userId) + .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) + .build(); RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName(achievement.getTitle()); UserVO user = userService.findById(userId); @@ -150,15 +154,15 @@ private void saveAchievementToUser(Long userId, Long achievementCategoryId, int */ private void deleteAchievementFromUser(Long userId, Long achievementCategoryId, int count) { Achievement achievement = - achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) - .orElseThrow(() -> new NoSuchElementException( - ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); + achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) + .orElseThrow(() -> new NoSuchElementException( + ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); UserAchievement userAchievement = UserAchievement.builder() - .achievement(achievement) - .user(userRepo.findById(userId) - .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) - .build(); + .achievement(achievement) + .user(userRepo.findById(userId) + .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) + .build(); RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName("UNDO_" + achievement.getTitle()); UserVO user = userService.findById(userId); diff --git a/service/src/main/java/greencity/rating/RatingCalculation.java b/service/src/main/java/greencity/rating/RatingCalculation.java index e8a07e725b..080b0eb42a 100644 --- a/service/src/main/java/greencity/rating/RatingCalculation.java +++ b/service/src/main/java/greencity/rating/RatingCalculation.java @@ -44,5 +44,4 @@ public void ratingCalculation(RatingCalculationEnum rating, UserVO userVo) { .build(); ratingStatisticsService.save(modelMapper.map(ratingStatistics, RatingStatisticsVO.class)); } - } diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index 7dfeaaf721..16f2bf9bb2 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -207,7 +207,7 @@ public AchievementVO findByCategoryIdAndCondition(Long categoryId, Integer condi */ @Override public void calculateAchievements(Long id, - AchievementCategoryType achievementCategory, AchievementAction achievementAction) { + AchievementCategoryType achievementCategory, AchievementAction achievementAction) { achievementCalculation.calculateAchievement(id, achievementCategory, achievementAction); } } diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index fd0e4b5ed8..d21ae0828b 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -62,7 +62,7 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq UserVO userVO) { EcoNewsVO ecoNewsVO = ecoNewsService.findById(econewsId); EcoNewsComment ecoNewsComment = modelMapper.map(addEcoNewsCommentDtoRequest, EcoNewsComment.class); - User user=modelMapper.map(userVO, User.class); + User user = modelMapper.map(userVO, User.class); ecoNewsComment.setUser(user); ecoNewsComment.setEcoNews(modelMapper.map(ecoNewsVO, EcoNews.class)); if (addEcoNewsCommentDtoRequest.getParentCommentId() != 0) { @@ -169,12 +169,11 @@ public void deleteById(Long id, UserVO userVO) { } comment.setStatus(CommentStatus.DELETED); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); ecoNewsCommentRepo.save(comment); - } /** @@ -213,16 +212,16 @@ public void like(Long id, UserVO userVO) { if (comment.getUsersLiked().stream() .anyMatch(user -> user.getId().equals(userVO.getId()))) { CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); ecoNewsService.unlikeComment(userVO, ecoNewsCommentVO); } else { ecoNewsService.likeComment(userVO, ecoNewsCommentVO); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); } diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index b98b20f4b1..fbf69bbbec 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -71,14 +71,14 @@ public class EcoNewsServiceImpl implements EcoNewsService { @CacheEvict(value = CacheConstants.NEWEST_ECO_NEWS_CACHE_NAME, allEntries = true) @Override public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, - MultipartFile image, String email) { + MultipartFile image, String email) { EcoNews toSave = genericSave(addEcoNewsDtoRequest, image, email); AddEcoNewsDtoResponse addEcoNewsDtoResponse = modelMapper.map(toSave, AddEcoNewsDtoResponse.class); sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); + .calculateAchievement(toSave.getAuthor().getId(), + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); return addEcoNewsDtoResponse; } @@ -97,7 +97,7 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, UserVO user = userService.findByEmail(email); ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, user); achievementCalculation.calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); return ecoNewsDto; } @@ -107,18 +107,18 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, * @author Zakhar Veremchuk. */ public void sendEmailDto(AddEcoNewsDtoResponse addEcoNewsDtoResponse, - User user) { + User user) { String accessToken = httpServletRequest.getHeader(AUTHORIZATION); PlaceAuthorDto placeAuthorDto = modelMapper.map(user, PlaceAuthorDto.class); EcoNewsForSendEmailDto dto = EcoNewsForSendEmailDto.builder() - .author(placeAuthorDto) - .creationDate(addEcoNewsDtoResponse.getCreationDate()) - .unsubscribeToken(accessToken) - .text(addEcoNewsDtoResponse.getText()) - .title(addEcoNewsDtoResponse.getTitle()) - .source(addEcoNewsDtoResponse.getSource()) - .imagePath(addEcoNewsDtoResponse.getImagePath()) - .build(); + .author(placeAuthorDto) + .creationDate(addEcoNewsDtoResponse.getCreationDate()) + .unsubscribeToken(accessToken) + .text(addEcoNewsDtoResponse.getText()) + .title(addEcoNewsDtoResponse.getTitle()) + .source(addEcoNewsDtoResponse.getSource()) + .imagePath(addEcoNewsDtoResponse.getImagePath()) + .build(); restClient.addEcoNews(dto); } @@ -128,18 +128,18 @@ public void sendEmailDto(AddEcoNewsDtoResponse addEcoNewsDtoResponse, * @author Danylo Hlynskyi. */ public void sendEmailDto(EcoNewsGenericDto ecoNewsDto, - User user) { + User user) { String accessToken = httpServletRequest.getHeader(AUTHORIZATION); PlaceAuthorDto placeAuthorDto = modelMapper.map(user, PlaceAuthorDto.class); EcoNewsForSendEmailDto dto = EcoNewsForSendEmailDto.builder() - .author(placeAuthorDto) - .creationDate(ecoNewsDto.getCreationDate()) - .unsubscribeToken(accessToken) - .text(ecoNewsDto.getContent()) - .title(ecoNewsDto.getTitle()) - .imagePath(ecoNewsDto.getImagePath()) - .source(ecoNewsDto.getSource()) - .build(); + .author(placeAuthorDto) + .creationDate(ecoNewsDto.getCreationDate()) + .unsubscribeToken(accessToken) + .text(ecoNewsDto.getContent()) + .title(ecoNewsDto.getTitle()) + .imagePath(ecoNewsDto.getImagePath()) + .source(ecoNewsDto.getSource()) + .build(); restClient.addEcoNews(dto); } @@ -228,8 +228,6 @@ public PageableAdvancedDto findAllByUser(UserVO user, Pageabl /** * {@inheritDoc} * - * @return - * @author Kovaliv Taras. */ @Override public PageableAdvancedDto find(Pageable page, List tags) { @@ -241,37 +239,37 @@ public PageableAdvancedDto find(Pageable page, List t private PageableAdvancedDto buildPageableAdvancedDto(Page ecoNewsPage) { List ecoNewsDtos = ecoNewsPage.stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .collect(Collectors.toList()); return new PageableAdvancedDto<>( - ecoNewsDtos, - ecoNewsPage.getTotalElements(), - ecoNewsPage.getPageable().getPageNumber(), - ecoNewsPage.getTotalPages(), - ecoNewsPage.getNumber(), - ecoNewsPage.hasPrevious(), - ecoNewsPage.hasNext(), - ecoNewsPage.isFirst(), - ecoNewsPage.isLast()); + ecoNewsDtos, + ecoNewsPage.getTotalElements(), + ecoNewsPage.getPageable().getPageNumber(), + ecoNewsPage.getTotalPages(), + ecoNewsPage.getNumber(), + ecoNewsPage.hasPrevious(), + ecoNewsPage.hasNext(), + ecoNewsPage.isFirst(), + ecoNewsPage.isLast()); } private PageableAdvancedDto buildPageableAdvancedGeneticDto(Page ecoNewsPage) { List ecoNewsDtos = ecoNewsPage.stream() - .map(this::getEcoNewsGenericDtoWithEnTags) - .collect(Collectors.toList()); + .map(this::getEcoNewsGenericDtoWithEnTags) + .collect(Collectors.toList()); return new PageableAdvancedDto<>( - ecoNewsDtos, - ecoNewsPage.getTotalElements(), - ecoNewsPage.getPageable().getPageNumber(), - ecoNewsPage.getTotalPages(), - ecoNewsPage.getNumber(), - ecoNewsPage.hasPrevious(), - ecoNewsPage.hasNext(), - ecoNewsPage.isFirst(), - ecoNewsPage.isLast()); + ecoNewsDtos, + ecoNewsPage.getTotalElements(), + ecoNewsPage.getPageable().getPageNumber(), + ecoNewsPage.getTotalPages(), + ecoNewsPage.getNumber(), + ecoNewsPage.hasPrevious(), + ecoNewsPage.hasNext(), + ecoNewsPage.isFirst(), + ecoNewsPage.isLast()); } /** @@ -282,8 +280,8 @@ private PageableAdvancedDto buildPageableAdvancedGeneticDto(P @Override public EcoNewsVO findById(Long id) { EcoNews ecoNews = ecoNewsRepo - .findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .findById(id) + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); return modelMapper.map(ecoNews, EcoNewsVO.class); } @@ -295,7 +293,7 @@ public EcoNewsVO findById(Long id) { @Override public EcoNewsDto getById(Long id) { EcoNews ecoNews = ecoNewsRepo.findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); return modelMapper.map(ecoNews, EcoNewsDto.class); } @@ -307,13 +305,13 @@ public EcoNewsDto getById(Long id) { @Override public EcoNewsDto findDtoByIdAndLanguage(Long id, String language) { var ecoNews = ecoNewsRepo.findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); List tags = new ArrayList<>(); for (String lang : languageCode) { tags.addAll(ecoNews.getTags().stream().flatMap(t -> t.getTagTranslations().stream()) - .filter(tagTranslation -> tagTranslation.getLanguage().getCode().equals(lang)) - .map(TagTranslation::getName) - .collect(Collectors.toList())); + .filter(tagTranslation -> tagTranslation.getLanguage().getCode().equals(lang)) + .map(TagTranslation::getName) + .collect(Collectors.toList())); } return getEcoNewsDto(ecoNews, tags); } @@ -331,10 +329,10 @@ public void delete(Long id, UserVO user) { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user)); + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE)); + () -> achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE)); ecoNewsRepo.deleteById(ecoNewsVO.getId()); } @@ -366,14 +364,14 @@ public PageableDto search(Pageable pageable, String searchQuery, private PageableDto getSearchNewsDtoPageableDto(Page page) { List searchNewsDtos = page.stream() - .map(ecoNews -> modelMapper.map(ecoNews, SearchNewsDto.class)) - .collect(Collectors.toList()); + .map(ecoNews -> modelMapper.map(ecoNews, SearchNewsDto.class)) + .collect(Collectors.toList()); return new PageableDto<>( - searchNewsDtos, - page.getTotalElements(), - page.getPageable().getPageNumber(), - page.getTotalPages()); + searchNewsDtos, + page.getTotalElements(), + page.getPageable().getPageNumber(), + page.getTotalPages()); } /** @@ -385,8 +383,8 @@ private PageableDto getSearchNewsDtoPageableDto(Page pag @Override public List getAllPublishedNewsByUserId(Long userId) { return ecoNewsRepo.findAllByUserId(userId).stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .collect(Collectors.toList()); } /** @@ -399,8 +397,8 @@ public List getAllPublishedNewsByUserId(Long userId) { @Override public List getAllPublishedNewsByUser(UserVO user) { return ecoNewsRepo.findAllByUserId(user.getId()).stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .collect(Collectors.toList()); } /** @@ -425,9 +423,10 @@ public Long getAmountOfPublishedNewsByUserId(Long id) { public void likeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().add(user); CompletableFuture - .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); + .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, + AchievementAction.ASSIGN)); } /** @@ -440,10 +439,10 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { public void unlikeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().removeIf(u -> u.getId().equals(user.getId())); CompletableFuture - .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, user)); + .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, user)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); + () -> achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); } @Override @@ -453,28 +452,28 @@ public PageableAdvancedDto searchEcoNewsBy(Pageable paging, String q } private void enhanceWithNewManagementData(EcoNews toUpdate, EcoNewsDtoManagement ecoNewsDtoManagement, - MultipartFile image) { + MultipartFile image) { toUpdate.setTitle(ecoNewsDtoManagement.getTitle()); toUpdate.setText(ecoNewsDtoManagement.getText()); toUpdate.setTags(modelMapper - .map(tagService.findTagsByNamesAndType(ecoNewsDtoManagement.getTags(), TagType.ECO_NEWS), - new TypeToken>() { - }.getType())); + .map(tagService.findTagsByNamesAndType(ecoNewsDtoManagement.getTags(), TagType.ECO_NEWS), + new TypeToken>() { + }.getType())); if (image != null) { toUpdate.setImagePath(fileService.upload(image)); } } private void enhanceWithNewData(EcoNews toUpdate, UpdateEcoNewsDto updateEcoNewsDto, - MultipartFile image) { + MultipartFile image) { toUpdate.setTitle(updateEcoNewsDto.getTitle()); toUpdate.setText(updateEcoNewsDto.getContent()); toUpdate.setShortInfo(updateEcoNewsDto.getShortInfo()); toUpdate.setSource(updateEcoNewsDto.getSource()); toUpdate.setTags(modelMapper.map(tagService - .findTagsByNamesAndType(updateEcoNewsDto.getTags(), TagType.ECO_NEWS), - new TypeToken>() { - }.getType())); + .findTagsByNamesAndType(updateEcoNewsDto.getTags(), TagType.ECO_NEWS), + new TypeToken>() { + }.getType())); if (updateEcoNewsDto.getImage() != null) { image = fileService.convertToMultipartImage(updateEcoNewsDto.getImage()); } @@ -514,7 +513,7 @@ public EcoNewsGenericDto update(UpdateEcoNewsDto updateEcoNewsDto, MultipartFile @Override public PageableAdvancedDto getFilteredDataForManagementByPage( - Pageable pageable, EcoNewsViewDto ecoNewsViewDto) { + Pageable pageable, EcoNewsViewDto ecoNewsViewDto) { Page page = ecoNewsRepo.findAll(getSpecification(ecoNewsViewDto), pageable); return buildPageableAdvancedDto(page); } @@ -651,10 +650,10 @@ public List buildSearchCriteria(EcoNewsViewDto ecoNewsViewDto) { if (!ecoNewsViewDto.getStartDate().isEmpty() && !ecoNewsViewDto.getEndDate().isEmpty()) { searchCriteria = SearchCriteria.builder() - .key(EcoNews_.CREATION_DATE) - .type("dateRange") - .value(new String[]{ecoNewsViewDto.getStartDate(), ecoNewsViewDto.getEndDate()}) - .build(); + .key(EcoNews_.CREATION_DATE) + .type("dateRange") + .value(new String[] {ecoNewsViewDto.getStartDate(), ecoNewsViewDto.getEndDate()}) + .build(); criteriaList.add(searchCriteria); } @@ -664,25 +663,25 @@ public List buildSearchCriteria(EcoNewsViewDto ecoNewsViewDto) { private void setValueIfNotEmpty(List searchCriteria, String key, String value) { if (!StringUtils.isEmpty(value)) { searchCriteria.add(SearchCriteria.builder() - .key(key) - .type(key) - .value(value) - .build()); + .key(key) + .type(key) + .value(value) + .build()); } } private List getEcoNewsList(List ecoNewsList) { return ecoNewsList - .stream() - .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) - .collect(Collectors.toList()); + .stream() + .map(ecoNews -> modelMapper.map(ecoNews, EcoNewsDto.class)) + .collect(Collectors.toList()); } private EcoNewsGenericDto getEcoNewsGenericDtoWithAllTags(EcoNews ecoNews) { List tags = ecoNews.getTags().stream() - .flatMap(t -> t.getTagTranslations().stream()) - .map(TagTranslation::getName) - .collect(Collectors.toList()); + .flatMap(t -> t.getTagTranslations().stream()) + .map(TagTranslation::getName) + .collect(Collectors.toList()); return buildEcoNewsGenericDto(ecoNews, tags); } @@ -691,10 +690,10 @@ private EcoNewsGenericDto getEcoNewsGenericDtoWithEnTags(EcoNews ecoNews) { List tags = new ArrayList<>(); for (String language : languageCode) { tags.addAll(ecoNews.getTags().stream() - .flatMap(t -> t.getTagTranslations().stream()) - .filter(t -> t.getLanguage().getCode().equals(language)) - .map(TagTranslation::getName) - .collect(Collectors.toList())); + .flatMap(t -> t.getTagTranslations().stream()) + .filter(t -> t.getLanguage().getCode().equals(language)) + .map(TagTranslation::getName) + .collect(Collectors.toList())); } return buildEcoNewsGenericDto(ecoNews, tags); @@ -704,44 +703,44 @@ private EcoNewsGenericDto buildEcoNewsGenericDto(EcoNews ecoNews, List t User author = ecoNews.getAuthor(); var ecoNewsAuthorDto = new EcoNewsAuthorDto(author.getId(), author.getName()); int countOfComments = ecoNews.getEcoNewsComments() != null - ? (int) ecoNews.getEcoNewsComments().stream() + ? (int) ecoNews.getEcoNewsComments().stream() .filter(ecoNewsComment -> !ecoNewsComment.getStatus().equals(CommentStatus.DELETED)).count() - : 0; + : 0; int countOfEcoNews = ecoNewsRepo.totalCountOfCreationNews(); return EcoNewsGenericDto.builder() - .id(ecoNews.getId()) - .imagePath(ecoNews.getImagePath()) - .author(ecoNewsAuthorDto) - .tagsEn(tags.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) - .tagsUa(tags.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) - .shortInfo(ecoNews.getShortInfo()) - .content(ecoNews.getText()) - .title(ecoNews.getTitle()) - .creationDate(ecoNews.getCreationDate()) - .source(ecoNews.getSource()) - .likes(ecoNews.getUsersLikedNews() != null ? ecoNews.getUsersLikedNews().size() : 0) - .countComments(countOfComments) - .countOfEcoNews(countOfEcoNews) - .build(); + .id(ecoNews.getId()) + .imagePath(ecoNews.getImagePath()) + .author(ecoNewsAuthorDto) + .tagsEn(tags.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) + .tagsUa(tags.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) + .shortInfo(ecoNews.getShortInfo()) + .content(ecoNews.getText()) + .title(ecoNews.getTitle()) + .creationDate(ecoNews.getCreationDate()) + .source(ecoNews.getSource()) + .likes(ecoNews.getUsersLikedNews() != null ? ecoNews.getUsersLikedNews().size() : 0) + .countComments(countOfComments) + .countOfEcoNews(countOfEcoNews) + .build(); } private EcoNewsDto getEcoNewsDto(EcoNews ecoNews, List list) { User author = ecoNews.getAuthor(); var ecoNewsAuthorDto = new EcoNewsAuthorDto(author.getId(), - author.getName()); + author.getName()); return EcoNewsDto.builder() - .id(ecoNews.getId()) - .imagePath(ecoNews.getImagePath()) - .author(ecoNewsAuthorDto) - .likes(ecoNews.getUsersLikedNews().size()) - .tags(list.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) - .tagsUa(list.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) - .shortInfo(ecoNews.getShortInfo()) - .content(ecoNews.getText()) - .title(ecoNews.getTitle()) - .creationDate(ecoNews.getCreationDate()) - .build(); + .id(ecoNews.getId()) + .imagePath(ecoNews.getImagePath()) + .author(ecoNewsAuthorDto) + .likes(ecoNews.getUsersLikedNews().size()) + .tags(list.stream().filter(tag -> tag.matches("^([A-Za-z-])+$")).collect(Collectors.toList())) + .tagsUa(list.stream().filter(tag -> tag.matches("^([А-Яа-яієїґ'-])+$")).collect(Collectors.toList())) + .shortInfo(ecoNews.getShortInfo()) + .content(ecoNews.getText()) + .title(ecoNews.getTitle()) + .creationDate(ecoNews.getCreationDate()) + .build(); } /** @@ -752,19 +751,19 @@ private EcoNewsDto getEcoNewsDto(EcoNews ecoNews, List list) { */ public EcoNewContentSourceDto getContentAndSourceForEcoNewsById(Long id) { EcoNews ecoNews = ecoNewsRepo.findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); return getContentSourceEcoNewsDto(ecoNews); } private EcoNewContentSourceDto getContentSourceEcoNewsDto(EcoNews ecoNews) { return EcoNewContentSourceDto.builder() - .content(ecoNews.getText()) - .source(ecoNews.getSource()) - .build(); + .content(ecoNews.getText()) + .source(ecoNews.getSource()) + .build(); } private EcoNews genericSave(AddEcoNewsDtoRequest addEcoNewsDtoRequest, - MultipartFile image, String email) { + MultipartFile image, String email) { EcoNews toSave = modelMapper.map(addEcoNewsDtoRequest, EcoNews.class); UserVO byEmail = restClient.findByEmail(email); User user = modelMapper.map(byEmail, User.class); @@ -783,14 +782,14 @@ private EcoNews genericSave(AddEcoNewsDtoRequest addEcoNewsDtoRequest, } List tagVOS = tagService.findTagsByNamesAndType( - addEcoNewsDtoRequest.getTags(), TagType.ECO_NEWS); + addEcoNewsDtoRequest.getTags(), TagType.ECO_NEWS); toSave.setTags(modelMapper.map(tagVOS, - new TypeToken>() { - }.getType())); + new TypeToken>() { + }.getType())); try { ecoNewsRepo.save(toSave); - } catch (DataIntegrityViolationException e) { + } catch (DataIntegrityViolationException e) { throw new NotSavedException(ErrorMessage.ECO_NEWS_NOT_SAVED); } return toSave; @@ -799,8 +798,8 @@ private EcoNews genericSave(AddEcoNewsDtoRequest addEcoNewsDtoRequest, @Override public Set findUsersWhoLikedPost(Long id) { EcoNews ecoNews = ecoNewsRepo - .findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .findById(id) + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); Set usersLikedNews = ecoNews.getUsersLikedNews(); return usersLikedNews.stream().map(u -> modelMapper.map(u, UserVO.class)).collect(Collectors.toSet()); } @@ -808,8 +807,8 @@ public Set findUsersWhoLikedPost(Long id) { @Override public Set findUsersWhoDislikedPost(Long id) { EcoNews ecoNews = ecoNewsRepo - .findById(id) - .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); + .findById(id) + .orElseThrow(() -> new NotFoundException(ErrorMessage.ECO_NEWS_NOT_FOUND_BY_ID + id)); Set usersDislikedNews = ecoNews.getUsersDislikedNews(); return usersDislikedNews.stream().map(u -> modelMapper.map(u, UserVO.class)).collect(Collectors.toSet()); } diff --git a/service/src/main/java/greencity/service/EventCommentServiceImpl.java b/service/src/main/java/greencity/service/EventCommentServiceImpl.java index ff0b017f3e..6f3624501d 100644 --- a/service/src/main/java/greencity/service/EventCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EventCommentServiceImpl.java @@ -45,7 +45,7 @@ public class EventCommentServiceImpl implements EventCommentService { private final EventRepo eventRepo; private final RestClient restClient; private final RatingCalculation ratingCalculation; - private AchievementCalculation achievementCalculation; + private AchievementCalculation achievementCalculation; /** * Method to save {@link greencity.entity.event.EventComment}. @@ -94,8 +94,8 @@ public AddEventCommentDtoResponse save(Long eventId, AddEventCommentDtoRequest a CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); return addEventCommentDtoResponse; } @@ -244,8 +244,8 @@ public void delete(Long eventCommentId, UserVO user) { CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, user)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); + () -> achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); eventCommentRepo.save(eventComment); } @@ -311,14 +311,13 @@ public void like(Long commentId, UserVO userVO) { CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); - + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); } else { comment.getUsersLiked().add(modelMapper.map(userVO, User.class)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); } diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 46cc913857..7d3db7d982 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -707,8 +707,8 @@ public HabitAssignDto enrollHabit(Long habitAssignId, Long userId, LocalDate dat CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); return buildHabitAssignDto(habitAssign, language); } @@ -801,8 +801,8 @@ public HabitAssignDto unenrollHabit(Long habitAssignId, Long userId, LocalDate d CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE)); return modelMapper.map(habitAssign, HabitAssignDto.class); } @@ -995,9 +995,8 @@ public HabitAssignDto cancelHabitAssign(Long habitId, Long userId) { () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE)); - + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE)); } habitAssignRepo.save(habitAssignToCancel); return buildHabitAssignDto(habitAssignToCancel, "en"); @@ -1023,9 +1022,8 @@ public void deleteHabitAssign(Long habitAssignId, Long userId) { () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE)); - + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE)); } userShoppingListItemRepo.deleteShoppingListItemsByHabitAssignId(habitAssign.getId()); customShoppingListItemRepo.deleteCustomShoppingListItemsByHabitId(habitAssign.getHabit().getId()); diff --git a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java index 663ef1271a..897436fab3 100644 --- a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java @@ -49,7 +49,8 @@ public class PlaceCommentServiceImpl implements PlaceCommentService { private ModelMapper modelMapper; private final greencity.rating.RatingCalculation ratingCalculation; private final HttpServletRequest httpServletRequest; -private AchievementCalculation achievementCalculation; + private AchievementCalculation achievementCalculation; + /** * {@inheritDoc} * @@ -92,8 +93,8 @@ public CommentReturnDto save(Long placeId, AddCommentDto addCommentDto, String e CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); return modelMapper.map(placeCommentRepo.save(comment), CommentReturnDto.class); } @@ -112,9 +113,8 @@ public void deleteById(Long id) { CompletableFuture.runAsync( () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); - + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); } /** diff --git a/service/src/main/java/greencity/service/UserServiceImpl.java b/service/src/main/java/greencity/service/UserServiceImpl.java index aeb24ce425..4273791acf 100644 --- a/service/src/main/java/greencity/service/UserServiceImpl.java +++ b/service/src/main/java/greencity/service/UserServiceImpl.java @@ -41,13 +41,14 @@ public class UserServiceImpl implements UserService { private final ModelMapper modelMapper; @Value("300000") private long timeAfterLastActivity; + /** * {@inheritDoc} */ @Override public void save(UserVO userVO) { - User user=modelMapper.map(userVO, User.class); - userRepo.save(user); + User user = modelMapper.map(userVO, User.class); + userRepo.save(user); } /** diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index a3b02fe3ec..0c3091c35d 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1384,7 +1384,7 @@ public static Achievement getAchievement() { } public static AchievementCategory getAchievementCategory() { - return new AchievementCategory(1L, "Name",Collections.emptyList()); + return new AchievementCategory(1L, "Name", Collections.emptyList()); } public static AchievementVO getAchievementVO() { @@ -1408,7 +1408,7 @@ public static AchievementManagementDto getAchievementManagementDto() { } public static UserAchievementVO getUserAchievementVO() { - return new UserAchievementVO(1L, getUserVO(), getAchievementVO(),true); + return new UserAchievementVO(1L, getUserVO(), getAchievementVO(), true); } public static UserAchievement getUserAchievement() { diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index 7fd9dcf3c0..1abf2c372f 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -54,6 +54,7 @@ class AchievementCalculationTest { private AchievementCalculation achievementCalculation; @Mock private UserService userService; + @Test void calculateAchievement() { AchievementCategoryVO achievementCategoryVO = ModelUtils.getAchievementCategoryVO(); diff --git a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java index 8cdd8baea4..8d10b82d53 100644 --- a/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java +++ b/service/src/test/java/greencity/mapping/AchievementCategoryVOMapperTest.java @@ -18,7 +18,7 @@ class AchievementCategoryVOMapperTest { @Test void convert() { - AchievementCategory achievementCategory = new AchievementCategory(1L, "Name",Collections.emptyList()); + AchievementCategory achievementCategory = new AchievementCategory(1L, "Name", Collections.emptyList()); AchievementCategoryVO achievementCategoryVO = AchievementCategoryVO.builder() .id(achievementCategory.getId()) .name(achievementCategory.getName()) diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 4e31cdef41..2c23fbcaef 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -202,6 +202,6 @@ void calculateAchievement() { verify(achievementCalculation).calculateAchievement( anyLong(), any(AchievementCategoryType.class), - eq( AchievementAction.ASSIGN)); + eq(AchievementAction.ASSIGN)); } } From a57c1688fcae02bc32b6622ce9f59ec1a4052af6 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Sun, 24 Sep 2023 09:33:57 +0300 Subject: [PATCH 35/51] Formatted and added test to coverege --- .../enums/RatingCalculationEnum.java | 1 - .../enums/RatingCalculationEnumTest.java | 30 +++++++++---- .../service/UserActionServiceImplTest.java | 45 ++++++++++++++++++- .../service/UserServiceImplTest.java | 7 +++ 4 files changed, 73 insertions(+), 10 deletions(-) diff --git a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java index 92f7d1fadd..2e65e9299d 100644 --- a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java +++ b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java @@ -2,7 +2,6 @@ import greencity.constant.ErrorMessage; import greencity.exception.exceptions.NotFoundException; -import greencity.exception.exceptions.NotUpdatedException; import lombok.Getter; @Getter diff --git a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java index b73c46d23a..7b74deb64a 100644 --- a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java +++ b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java @@ -1,18 +1,13 @@ package greencity.enums; +import greencity.constant.ErrorMessage; +import greencity.exception.exceptions.NotFoundException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; class RatingCalculationEnumTest { - @Test - void testEnumValueOf() { - for (RatingCalculationEnum value : RatingCalculationEnum.values()) { - assertEquals(value, RatingCalculationEnum.valueOf(value.name()), - "Enum valueOf does not match for " + value.name()); - } - } - @Test void testRatingPoints() { assertEquals(1, RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS.getRatingPoints()); @@ -26,4 +21,23 @@ void testRatingPoints() { assertEquals(-10, RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY.getRatingPoints()); assertEquals(-20, RatingCalculationEnum.UNDO_SHARE_NEWS.getRatingPoints()); } + + @Test + public void testFindEnumByNameValidName() { + assertEquals(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, + RatingCalculationEnum.findEnumByName("DAYS_OF_HABIT_IN_PROGRESS")); + assertEquals(RatingCalculationEnum.CREATE_NEWS, RatingCalculationEnum.findEnumByName("CREATE_NEWS")); + } + + @Test + public void testFindEnumByNameInvalidName() { + assertThrows(NotFoundException.class, () -> RatingCalculationEnum.findEnumByName("INVALID_NAME")); + } + + @Test + public void testErrorMessageOnNotFound() { + NotFoundException exception = + assertThrows(NotFoundException.class, () -> RatingCalculationEnum.findEnumByName("INVALID_NAME")); + assertEquals(ErrorMessage.RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME + "INVALID_NAME", exception.getMessage()); + } } diff --git a/service/src/test/java/greencity/service/UserActionServiceImplTest.java b/service/src/test/java/greencity/service/UserActionServiceImplTest.java index e51dc52a9e..cba95c13d1 100644 --- a/service/src/test/java/greencity/service/UserActionServiceImplTest.java +++ b/service/src/test/java/greencity/service/UserActionServiceImplTest.java @@ -1,9 +1,15 @@ package greencity.service; import greencity.ModelUtils; +import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; +import greencity.entity.AchievementCategory; import greencity.entity.UserAction; +import greencity.exception.exceptions.BadCategoryRequestException; +import greencity.exception.exceptions.NotFoundException; +import greencity.repository.AchievementCategoryRepo; import greencity.repository.UserActionRepo; +import greencity.repository.UserRepo; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -11,10 +17,12 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; +import java.util.Collections; +import java.util.NoSuchElementException; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class UserActionServiceImplTest { @@ -23,7 +31,11 @@ class UserActionServiceImplTest { @Mock private UserActionRepo userActionRepo; @Mock + private UserRepo userRepo; + @Mock private ModelMapper modelMapper; + @Mock + private AchievementCategoryRepo achievementCategoryRepo; @Test void updateUserActions() { @@ -51,6 +63,37 @@ void findUserActionByUserId() { assertEquals(userActionVO, userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)); } + @Test + void findUserActionByUserId_NoSuchCategory() { + when(userActionRepo.findByUserIdAndAchievementCategoryId(1L, 1L)).thenReturn(null); + when(userRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getUser())); + assertThrows(NoSuchElementException.class, + () -> userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)); + } + + @Test + void findUserActionByUserIdNull() { + UserActionVO userActionVO = ModelUtils.getUserActionVO(); + when(userActionRepo.findByUserIdAndAchievementCategoryId(1L, 1L)).thenReturn(null); + when(userRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getUser())); + when(achievementCategoryRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getAchievementCategory())); + UserAction userAction = UserAction.builder() + .user(ModelUtils.getUser()) + .achievementCategory(AchievementCategory.builder() + .id(1L) + .name("Name") + .achievementList(Collections.emptyList()) + .build()) + .count(0) + .build(); + + when(modelMapper.map(userAction, UserActionVO.class)).thenReturn(userActionVO); + UserActionVO resultUserActionVO = userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L); + assertEquals(userActionVO, resultUserActionVO); + verify(userActionRepo, times(1)).save(any()); + + } + @Test void save() { UserAction userAction = ModelUtils.getUserAction(); diff --git a/service/src/test/java/greencity/service/UserServiceImplTest.java b/service/src/test/java/greencity/service/UserServiceImplTest.java index dc692eff27..101b65c721 100644 --- a/service/src/test/java/greencity/service/UserServiceImplTest.java +++ b/service/src/test/java/greencity/service/UserServiceImplTest.java @@ -77,6 +77,13 @@ void findByIdTest() { verify(userRepo, times(1)).findById(id); } + @Test + void saveTest() { + userService.save(userVO); + verify(modelMapper).map(userVO, User.class); + verify(userRepo, times(1)).save(any()); + } + @Test void checkIfTheUserIsOnlineExceptionTest() { assertThrows(WrongIdException.class, () -> userService.checkIfTheUserIsOnline(null)); From 64158fd1872c593f4dc74b9bed8c875e10448598 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Sun, 24 Sep 2023 10:44:21 +0300 Subject: [PATCH 36/51] Formatted and added test to coverege --- .../controller/AchievementController.java | 1 - .../enums/RatingCalculationEnumTest.java | 6 +- .../achievement/AchievementCalculation.java | 1 - .../greencity/rating/RatingCalculation.java | 2 - .../src/test/java/greencity/ModelUtils.java | 5 +- .../AchievementCalculationTest.java | 60 ++++++++++++++++++- 6 files changed, 63 insertions(+), 12 deletions(-) diff --git a/core/src/main/java/greencity/controller/AchievementController.java b/core/src/main/java/greencity/controller/AchievementController.java index 8838250837..fbe5af16e6 100644 --- a/core/src/main/java/greencity/controller/AchievementController.java +++ b/core/src/main/java/greencity/controller/AchievementController.java @@ -3,7 +3,6 @@ import greencity.constant.HttpStatuses; import greencity.dto.achievement.AchievementDTO; import greencity.dto.achievement.AchievementVO; -import greencity.enums.AchievementCategoryType; import greencity.service.AchievementService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; diff --git a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java index 7b74deb64a..94f131d250 100644 --- a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java +++ b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java @@ -23,19 +23,19 @@ void testRatingPoints() { } @Test - public void testFindEnumByNameValidName() { + void testFindEnumByNameValidName() { assertEquals(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, RatingCalculationEnum.findEnumByName("DAYS_OF_HABIT_IN_PROGRESS")); assertEquals(RatingCalculationEnum.CREATE_NEWS, RatingCalculationEnum.findEnumByName("CREATE_NEWS")); } @Test - public void testFindEnumByNameInvalidName() { + void testFindEnumByNameInvalidName() { assertThrows(NotFoundException.class, () -> RatingCalculationEnum.findEnumByName("INVALID_NAME")); } @Test - public void testErrorMessageOnNotFound() { + void testErrorMessageOnNotFound() { NotFoundException exception = assertThrows(NotFoundException.class, () -> RatingCalculationEnum.findEnumByName("INVALID_NAME")); assertEquals(ErrorMessage.RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME + "INVALID_NAME", exception.getMessage()); diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 3afadabdb1..7dabc89525 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -23,7 +23,6 @@ import org.springframework.stereotype.Component; import java.util.NoSuchElementException; -import java.util.concurrent.CompletableFuture; @Component public class AchievementCalculation { diff --git a/service/src/main/java/greencity/rating/RatingCalculation.java b/service/src/main/java/greencity/rating/RatingCalculation.java index 080b0eb42a..2b97da6d63 100644 --- a/service/src/main/java/greencity/rating/RatingCalculation.java +++ b/service/src/main/java/greencity/rating/RatingCalculation.java @@ -14,8 +14,6 @@ import javax.servlet.http.HttpServletRequest; -import static greencity.constant.AppConstant.AUTHORIZATION; - @Component @AllArgsConstructor public class RatingCalculation { diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 0c3091c35d..8843e59963 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1378,7 +1378,7 @@ public static AdvicePostDto getAdvicePostDto() { public static Achievement getAchievement() { return new Achievement(1L, - "Test", "Test", "Test", + "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", Collections.emptyList(), new AchievementCategory(), 1); } @@ -1388,7 +1388,8 @@ public static AchievementCategory getAchievementCategory() { } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, "Test", "Test", "Test", new AchievementCategoryVO(), 1); + return new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), + 1); } public static AchievementPostDto getAchievementPostDto() { diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index 1abf2c372f..a45dab8a06 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -2,13 +2,14 @@ import greencity.ModelUtils; import greencity.client.RestClient; +import greencity.dto.achievement.AchievementVO; import greencity.dto.achievementcategory.AchievementCategoryVO; +import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.User; import greencity.entity.UserAchievement; -import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementAction; -import greencity.enums.RatingCalculationEnum; +import greencity.enums.*; +import greencity.rating.RatingCalculation; import greencity.repository.AchievementCategoryRepo; import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; @@ -21,6 +22,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; +import greencity.entity.Achievement; import java.util.Collections; import java.util.Optional; @@ -54,9 +56,61 @@ class AchievementCalculationTest { private AchievementCalculation achievementCalculation; @Mock private UserService userService; + @Mock + private RatingCalculation ratingCalculation; @Test void calculateAchievement() { + AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); + AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); + UserVO userVO = ModelUtils.getUserVO(); + UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); + User user = ModelUtils.getUser(); + Achievement achievement = ModelUtils.getAchievement(); + UserAchievement userAchievement = ModelUtils.getUserAchievement(); + user.setUserAchievements(Collections.singletonList(userAchievement)); + AchievementVO achievementVO = + new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), 1); + when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) + .thenReturn(achievementCategoryVO); + when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); + when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) + .thenReturn(Optional.of(achievement)); + when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); + when(achievementCategoryService.findByName("ACHIEVEMENT")).thenReturn(achievementCategoryVO); + when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); + when(achievementService.findByCategoryIdAndCondition(2L, 1)).thenReturn(achievementVO); + achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); + assertEquals(2, userActionVO.getCount()); + } + + @Test + void calculateAchievement_UNDO() { + AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); + AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); + UserVO userVO = ModelUtils.getUserVO(); + UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); + User user = ModelUtils.getUser(); + Achievement achievement = ModelUtils.getAchievement(); + UserAchievement userAchievement = ModelUtils.getUserAchievement(); + user.setUserAchievements(Collections.singletonList(userAchievement)); + AchievementVO achievementVO = + new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), 1); + when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) + .thenReturn(achievementCategoryVO); + when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); + when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) + .thenReturn(Optional.of(achievement)); + when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); + when(achievementCategoryService.findByName("ACHIEVEMENT")).thenReturn(achievementCategoryVO); + when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); + when(achievementService.findByCategoryIdAndCondition(2L, -1)).thenReturn(achievementVO); + achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE); + assertEquals(-2, userActionVO.getCount()); + } + + @Test + void calculateAchievement_achievemmentNull() { AchievementCategoryVO achievementCategoryVO = ModelUtils.getAchievementCategoryVO(); AchievementCategoryVO achievementCategoryVO2 = ModelUtils.getAchievementCategoryVO(); achievementCategoryVO2.setId(2L); From 8e9ad2aaf3c84858ebdab4fd7bee854daed20354 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 25 Sep 2023 10:30:09 +0300 Subject: [PATCH 37/51] Formatted and added test to coverege --- .../achievement/AchievementCalculation.java | 8 +-- .../greencity/service/EcoNewsServiceImpl.java | 2 + .../AchievementCalculationTest.java | 55 +++++++++++++++++++ .../EcoNewsCommentServiceImplTest.java | 4 ++ .../service/EcoNewsServiceImplTest.java | 3 +- .../service/EventCommentServiceImplTest.java | 3 + .../service/PlaceCommentServiceImplTest.java | 3 + 7 files changed, 71 insertions(+), 7 deletions(-) diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 7dabc89525..0e08af8a1a 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -48,8 +48,7 @@ public AchievementCalculation( AchievementCategoryService achievementCategoryService, UserAchievementRepo userAchievementRepo, UserRepo userRepo, - AchievementRepo achievementRepo, - AchievementCategoryRepo achievementCategoryRepo, RatingCalculation ratingCalculation, UserService userService) { + AchievementRepo achievementRepo, RatingCalculation ratingCalculation, UserService userService) { this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; @@ -136,10 +135,7 @@ private void saveAchievementToUser(Long userId, Long achievementCategoryId, int .build(); RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName(achievement.getTitle()); UserVO user = userService.findById(userId); - - if (reason != null) { - ratingCalculation.ratingCalculation(reason, user); - } + ratingCalculation.ratingCalculation(reason, user); userAchievementRepo.save(userAchievement); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.ASSIGN); } diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index fbf69bbbec..1f4c014dc6 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -23,6 +23,7 @@ import greencity.exception.exceptions.UnsupportedSortException; import greencity.filters.EcoNewsSpecification; import greencity.filters.SearchCriteria; +import greencity.mapping.AddEcoNewsCommentDtoResponseMapper; import greencity.repository.EcoNewsRepo; import greencity.repository.EcoNewsSearchRepo; import lombok.RequiredArgsConstructor; @@ -37,6 +38,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index a45dab8a06..5e73a2a001 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -9,6 +9,7 @@ import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.*; +import greencity.exception.exceptions.NotFoundException; import greencity.rating.RatingCalculation; import greencity.repository.AchievementCategoryRepo; import greencity.repository.AchievementRepo; @@ -27,6 +28,7 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -59,6 +61,59 @@ class AchievementCalculationTest { @Mock private RatingCalculation ratingCalculation; + @Test + void calculateAchievement_reasonNull() { + AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); + AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); + UserVO userVO = ModelUtils.getUserVO(); + UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); + User user = ModelUtils.getUser(); + Achievement achievement = ModelUtils.getAchievement(); + achievement.setTitle("bla bla"); + UserAchievement userAchievement = ModelUtils.getUserAchievement(); + user.setUserAchievements(Collections.singletonList(userAchievement)); + AchievementVO achievementVO = + new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), 1); + when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) + .thenReturn(achievementCategoryVO); + when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); + when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) + .thenReturn(Optional.of(achievement)); + when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); + when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); + when(achievementService.findByCategoryIdAndCondition(2L, 1)).thenReturn(achievementVO); + + assertThrows(NotFoundException.class, () -> achievementCalculation.calculateAchievement(1L, + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); + } + + @Test + void calculateAchievement_UNDO_reasonNull() { + AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); + AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); + UserVO userVO = ModelUtils.getUserVO(); + UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); + User user = ModelUtils.getUser(); + Achievement achievement = ModelUtils.getAchievement(); + achievement.setTitle("Bla bla"); + UserAchievement userAchievement = ModelUtils.getUserAchievement(); + user.setUserAchievements(Collections.singletonList(userAchievement)); + AchievementVO achievementVO = + new AchievementVO(1L, "CREATED_5_NEWS___", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), + 1); + when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) + .thenReturn(achievementCategoryVO); + when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); + when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) + .thenReturn(Optional.of(achievement)); + when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); + when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); + when(achievementService.findByCategoryIdAndCondition(2L, -1)).thenReturn(achievementVO); + + assertThrows(NotFoundException.class, () -> achievementCalculation.calculateAchievement(1L, + AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE)); + } + @Test void calculateAchievement() { AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); diff --git a/service/src/test/java/greencity/service/EcoNewsCommentServiceImplTest.java b/service/src/test/java/greencity/service/EcoNewsCommentServiceImplTest.java index 01760bd84d..9155b3d277 100644 --- a/service/src/test/java/greencity/service/EcoNewsCommentServiceImplTest.java +++ b/service/src/test/java/greencity/service/EcoNewsCommentServiceImplTest.java @@ -3,6 +3,7 @@ import static greencity.ModelUtils.getUser; import static greencity.ModelUtils.getUserVO; +import greencity.achievement.AchievementCalculation; import greencity.enums.CommentStatus; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; import javax.servlet.http.HttpServletRequest; @@ -70,6 +71,9 @@ class EcoNewsCommentServiceImplTest { private UserService userService; @Mock private RatingCalculation ratingCalculation; + @Mock + private AchievementCalculation achievementCalculation; + private String token = "token"; @Test diff --git a/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java b/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java index 2c932d8114..7c37939184 100644 --- a/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java +++ b/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java @@ -127,14 +127,15 @@ void saveWithExistedImage() throws IOException { MultipartFile image = ModelUtils.getFile(); String imageToEncode = Base64.getEncoder().encodeToString(image.getBytes()); addEcoNewsDtoRequest.setImage(imageToEncode); - when(modelMapper.map(addEcoNewsDtoRequest, EcoNews.class)).thenReturn(ecoNews); when(restClient.findByEmail(TestConst.EMAIL)).thenReturn(ModelUtils.getUserVO()); when(fileService.upload(any(MultipartFile.class))).thenReturn(ModelUtils.getUrl().toString()); List tagVOList = Collections.singletonList(ModelUtils.getTagVO()); when(tagService.findTagsByNamesAndType(anyList(), eq(TagType.ECO_NEWS))).thenReturn(tagVOList); when(ecoNewsRepo.save(any(EcoNews.class))).thenReturn(ecoNews); + addEcoNewsDtoResponse.setEcoNewsAuthorDto(ModelUtils.getEcoNewsAuthorDto()); when(modelMapper.map(ecoNews, AddEcoNewsDtoResponse.class)).thenReturn(addEcoNewsDtoResponse); + when(modelMapper.map(ModelUtils.getUserVO(), User.class)).thenReturn(ModelUtils.getUser()); AddEcoNewsDtoResponse actual = ecoNewsService.save(addEcoNewsDtoRequest, image, TestConst.EMAIL); diff --git a/service/src/test/java/greencity/service/EventCommentServiceImplTest.java b/service/src/test/java/greencity/service/EventCommentServiceImplTest.java index eb45e335e6..1fb71dfe5d 100644 --- a/service/src/test/java/greencity/service/EventCommentServiceImplTest.java +++ b/service/src/test/java/greencity/service/EventCommentServiceImplTest.java @@ -1,6 +1,7 @@ package greencity.service; import greencity.ModelUtils; +import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.constant.ErrorMessage; import greencity.dto.PageableDto; @@ -73,6 +74,8 @@ class EventCommentServiceImplTest { HttpServletRequest httpServletRequest; @Mock private RatingCalculation ratingCalculation; + @Mock + private AchievementCalculation achievementCalculation; @Test void save() { diff --git a/service/src/test/java/greencity/service/PlaceCommentServiceImplTest.java b/service/src/test/java/greencity/service/PlaceCommentServiceImplTest.java index 38853f0b09..250fcd9a3d 100644 --- a/service/src/test/java/greencity/service/PlaceCommentServiceImplTest.java +++ b/service/src/test/java/greencity/service/PlaceCommentServiceImplTest.java @@ -1,6 +1,7 @@ package greencity.service; import greencity.ModelUtils; +import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.dto.PageableDto; import greencity.dto.comment.AddCommentDto; @@ -54,6 +55,8 @@ class PlaceCommentServiceImplTest { private UserService userService; @Mock private RatingCalculation ratingCalculation; + @Mock + private AchievementCalculation achievementCalculation; @Test void findByIdTest() { From c946ee1ef75b3899619c5239cd6973559e4959ac Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 25 Sep 2023 11:11:18 +0300 Subject: [PATCH 38/51] Formatted and added test to coverage --- .../java/greencity/achievement/AchievementCalculation.java | 3 --- .../main/java/greencity/service/HabitAssignServiceImpl.java | 6 +++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 0e08af8a1a..ea1b4e5012 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -161,10 +161,7 @@ private void deleteAchievementFromUser(Long userId, Long achievementCategoryId, RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName("UNDO_" + achievement.getTitle()); UserVO user = userService.findById(userId); - - if (reason != null) { ratingCalculation.ratingCalculation(reason, user); - } userAchievementRepo.delete(userAchievement); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.DELETE); } diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 7d3db7d982..38e28c31a3 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -705,10 +705,10 @@ public HabitAssignDto enrollHabit(Long habitAssignId, Long userId, LocalDate dat updateHabitAssignAfterEnroll(habitAssign, habitCalendar, userId); UserVO userVO = userService.findById(userId); CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO)); + () -> achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO)); return buildHabitAssignDto(habitAssign, language); } From 78c1687422f1c696c897799b26e7d167a214d68f Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 25 Sep 2023 11:18:48 +0300 Subject: [PATCH 39/51] Deleted running async --- .../achievement/AchievementCalculation.java | 2 +- .../service/EcoNewsCommentServiceImpl.java | 31 ++++++--------- .../greencity/service/EcoNewsServiceImpl.java | 29 ++++++-------- .../service/EventCommentServiceImpl.java | 34 ++++++---------- .../service/HabitAssignServiceImpl.java | 39 +++++++------------ .../service/PlaceCommentServiceImpl.java | 16 +++----- 6 files changed, 57 insertions(+), 94 deletions(-) diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index ea1b4e5012..1fc32072b2 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -161,7 +161,7 @@ private void deleteAchievementFromUser(Long userId, Long achievementCategoryId, RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName("UNDO_" + achievement.getTitle()); UserVO user = userService.findById(userId); - ratingCalculation.ratingCalculation(reason, user); + ratingCalculation.ratingCalculation(reason, user); userAchievementRepo.delete(userAchievement); calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.DELETE); } diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index d21ae0828b..b97e1d6c77 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -75,11 +75,10 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq throw new BadRequestException(ErrorMessage.CANNOT_REPLY_THE_REPLY); } } - CompletableFuture.runAsync(() -> achievementCalculation + achievementCalculation .calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN); + ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); ecoNewsComment.setStatus(CommentStatus.ORIGINAL); @@ -168,11 +167,9 @@ public void deleteById(Long id, UserVO userVO) { comment.getComments().forEach(c -> c.setStatus(CommentStatus.DELETED)); } comment.setStatus(CommentStatus.DELETED); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); + ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO); ecoNewsCommentRepo.save(comment); } @@ -211,19 +208,15 @@ public void like(Long id, UserVO userVO) { EcoNewsCommentVO ecoNewsCommentVO = modelMapper.map(comment, EcoNewsCommentVO.class); if (comment.getUsersLiked().stream() .anyMatch(user -> user.getId().equals(userVO.getId()))) { - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO); ecoNewsService.unlikeComment(userVO, ecoNewsCommentVO); } else { ecoNewsService.likeComment(userVO, ecoNewsCommentVO); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN); + ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO); } ecoNewsCommentRepo.save(modelMapper.map(ecoNewsCommentVO, EcoNewsComment.class)); } diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 1f4c014dc6..3ffa2e835d 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -78,9 +78,10 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, AddEcoNewsDtoResponse addEcoNewsDtoResponse = modelMapper.map(toSave, AddEcoNewsDtoResponse.class); sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); - CompletableFuture.runAsync(() -> achievementCalculation + achievementCalculation .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); + AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); + ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, modelMapper.map(toSave, UserVO.class)); return addEcoNewsDtoResponse; } @@ -330,11 +331,9 @@ public void delete(Long id, UserVO user) { if (user.getRole() != Role.ROLE_ADMIN && !user.getId().equals(ecoNewsVO.getAuthor().getId())) { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user); + achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE); ecoNewsRepo.deleteById(ecoNewsVO.getId()); } @@ -424,11 +423,9 @@ public Long getAmountOfPublishedNewsByUserId(Long id) { */ public void likeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().add(user); - CompletableFuture - .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); - CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, - AchievementAction.ASSIGN)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user); + achievementCalculation.calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, + AchievementAction.ASSIGN); } /** @@ -440,11 +437,9 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { */ public void unlikeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().removeIf(u -> u.getId().equals(user.getId())); - CompletableFuture - .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, user)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, user); + achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); } @Override diff --git a/service/src/main/java/greencity/service/EventCommentServiceImpl.java b/service/src/main/java/greencity/service/EventCommentServiceImpl.java index 6f3624501d..20c3f4fa5c 100644 --- a/service/src/main/java/greencity/service/EventCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EventCommentServiceImpl.java @@ -90,12 +90,9 @@ public AddEventCommentDtoResponse save(Long eventId, AddEventCommentDtoRequest a addEventCommentDtoResponse.setAuthor(modelMapper.map(userVO, EventCommentAuthorDto.class)); sendEmailDto(addEventCommentDtoResponse); - - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN); return addEventCommentDtoResponse; } @@ -240,12 +237,9 @@ public void delete(Long eventCommentId, UserVO user) { eventComment.getComments() .forEach(comment -> comment.setStatus(CommentStatus.DELETED)); } - - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, user)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, user); + achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); eventCommentRepo.save(eventComment); } @@ -308,18 +302,14 @@ public void like(Long commentId, UserVO userVO) { if (comment.getUsersLiked().stream().anyMatch(user -> user.getId().equals(userVO.getId()))) { comment.getUsersLiked().removeIf(user -> user.getId().equals(userVO.getId())); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); } else { comment.getUsersLiked().add(modelMapper.map(userVO, User.class)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN)); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN); + ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO); } eventCommentRepo.save(comment); } diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 38e28c31a3..0b8141b41b 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -704,11 +704,9 @@ public HabitAssignDto enrollHabit(Long habitAssignId, Long userId, LocalDate dat updateHabitAssignAfterEnroll(habitAssign, habitCalendar, userId); UserVO userVO = userService.findById(userId); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO)); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.ASSIGN); + ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO); return buildHabitAssignDto(habitAssign, language); } @@ -753,9 +751,6 @@ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, int habitStreak = countNewHabitStreak(habitAssign.getHabitStatusCalendars()); habitAssign.setHabitStreak(habitStreak); - CompletableFuture.runAsync(() -> achievementCalculation - .calculateAchievement(userId, AchievementCategoryType.HABIT, AchievementAction.ASSIGN)); - if (isHabitAcquired(habitAssign)) { habitAssign.setStatus(HabitAssignStatus.ACQUIRED); } @@ -798,11 +793,9 @@ public HabitAssignDto unenrollHabit(Long habitAssignId, Long userId, LocalDate d deleteHabitStatusCalendar(date, habitAssign); updateHabitAssignAfterUnenroll(habitAssign); UserVO userVO = userService.findById(userId); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE); return modelMapper.map(habitAssign, HabitAssignDto.class); } @@ -991,12 +984,10 @@ public HabitAssignDto cancelHabitAssign(Long habitId, Long userId) { UserVO userVO = userService.findById(userId); for (int i = 0; i < habitAssignToCancel.getWorkingDays(); i++) { - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, - userVO)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, + userVO); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE); } habitAssignRepo.save(habitAssignToCancel); return buildHabitAssignDto(habitAssignToCancel, "en"); @@ -1018,12 +1009,10 @@ public void deleteHabitAssign(Long habitAssignId, Long userId) { UserVO userVO = userService.findById(userId); for (int i = 0; i < habitAssign.getWorkingDays(); i++) { - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, - userVO)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, + userVO); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.HABIT, AchievementAction.DELETE); } userShoppingListItemRepo.deleteShoppingListItemsByHabitAssignId(habitAssign.getId()); customShoppingListItemRepo.deleteCustomShoppingListItemsByHabitId(habitAssign.getHabit().getId()); diff --git a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java index 897436fab3..f7638b33b0 100644 --- a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java @@ -90,11 +90,9 @@ public CommentReturnDto save(Long placeId, AddCommentDto addCommentDto, String e photo.setComment(comment); photo.setPlace(place); }); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN); return modelMapper.map(placeCommentRepo.save(comment), CommentReturnDto.class); } @@ -110,11 +108,9 @@ public void deleteById(Long id) { .orElseThrow(() -> new NotFoundException(ErrorMessage.COMMENT_NOT_FOUND_EXCEPTION))); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserVO userVO = restClient.findByEmail(authentication.getName()); - CompletableFuture.runAsync( - () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); - CompletableFuture.runAsync( - () -> achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE)); + ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO); + achievementCalculation.calculateAchievement(userVO.getId(), + AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); } /** From d2bb1a557fb32ed5b679a803638d51ec1cb4404c Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 25 Sep 2023 11:27:16 +0300 Subject: [PATCH 40/51] Formatted and added test to coverage --- .../java/greencity/service/HabitAssignServiceImplTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java b/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java index 2a7b94804a..08f535c9aa 100644 --- a/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java +++ b/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java @@ -1,6 +1,7 @@ package greencity.service; import greencity.ModelUtils; +import greencity.achievement.AchievementCalculation; import greencity.constant.AppConstant; import greencity.constant.ErrorMessage; import greencity.dto.habit.HabitAssignCustomPropertiesDto; @@ -132,6 +133,9 @@ class HabitAssignServiceImplTest { @Mock private RatingCalculation ratingCalculation; + @Mock + private AchievementCalculation achievementCalculation; + private static ZonedDateTime zonedDateTime = ZonedDateTime.now(); private HabitDto habitDto = HabitDto.builder().id(1L).build(); @@ -469,6 +473,7 @@ void unenrollHabit() { .thenReturn(Optional.of(habitAssign)); when(habitStatusCalendarRepo.findHabitStatusCalendarByEnrollDateAndHabitAssign(date, habitAssign)) .thenReturn(habitStatusCalendar); + when(userService.findById(any())).thenReturn(ModelUtils.getUserVO()); habitAssignService.unenrollHabit(habitAssignId, userId, date); assertEquals(0, habitAssign.getHabitStatusCalendars().size()); @@ -558,6 +563,7 @@ void deleteHabitAssign() { habitAssign.setWorkingDays(10); when(habitAssignRepo.findById(habitAssignId)).thenReturn(Optional.of(habitAssign)); + when(userService.findById(any())).thenReturn(ModelUtils.getUserVO()); habitAssignService.deleteHabitAssign(habitAssignId, userId); @@ -884,6 +890,7 @@ void enrollHabit() { .thenReturn(null); when(modelMapper.map(habitAssign, HabitAssignDto.class)).thenReturn(habitAssignDto); when(modelMapper.map(translation, HabitDto.class)).thenReturn(habitDto); + when(userService.findById(any())).thenReturn(ModelUtils.getUserVO()); HabitAssignDto actualDto = habitAssignService.enrollHabit(habitAssignId, userId, localDate, language); assertEquals(1, habitAssign.getWorkingDays()); From d51aa36648c0a2186e0bead44068064e83aa55bf Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 25 Sep 2023 11:59:18 +0300 Subject: [PATCH 41/51] Fixed codesmells --- .../java/greencity/achievement/AchievementCalculation.java | 1 - .../java/greencity/service/EcoNewsCommentServiceImpl.java | 1 - .../src/main/java/greencity/service/EcoNewsServiceImpl.java | 3 --- .../main/java/greencity/service/EventCommentServiceImpl.java | 1 - .../main/java/greencity/service/HabitAssignServiceImpl.java | 5 ++--- .../main/java/greencity/service/PlaceCommentServiceImpl.java | 1 - 6 files changed, 2 insertions(+), 10 deletions(-) diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 1fc32072b2..e90e104b74 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -11,7 +11,6 @@ import greencity.enums.AchievementAction; import greencity.enums.RatingCalculationEnum; import greencity.rating.RatingCalculation; -import greencity.repository.AchievementCategoryRepo; import greencity.repository.AchievementRepo; import greencity.repository.UserAchievementRepo; import greencity.repository.UserRepo; diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index b97e1d6c77..09e22328d6 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -30,7 +30,6 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; @Service diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 3ffa2e835d..906d44f9b4 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -23,7 +23,6 @@ import greencity.exception.exceptions.UnsupportedSortException; import greencity.filters.EcoNewsSpecification; import greencity.filters.SearchCriteria; -import greencity.mapping.AddEcoNewsCommentDtoResponseMapper; import greencity.repository.EcoNewsRepo; import greencity.repository.EcoNewsSearchRepo; import lombok.RequiredArgsConstructor; @@ -38,13 +37,11 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static greencity.constant.AppConstant.AUTHORIZATION; diff --git a/service/src/main/java/greencity/service/EventCommentServiceImpl.java b/service/src/main/java/greencity/service/EventCommentServiceImpl.java index 20c3f4fa5c..cbc9f45e0a 100644 --- a/service/src/main/java/greencity/service/EventCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EventCommentServiceImpl.java @@ -32,7 +32,6 @@ import java.util.List; import java.util.Optional; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; @Service diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 0b8141b41b..52a41f8d28 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -47,7 +47,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -702,7 +701,7 @@ public HabitAssignDto enrollHabit(Long habitAssignId, Long userId, LocalDate dat HabitStatusCalendar habitCalendar = HabitStatusCalendar.builder() .enrollDate(date).habitAssign(habitAssign).build(); - updateHabitAssignAfterEnroll(habitAssign, habitCalendar, userId); + updateHabitAssignAfterEnroll(habitAssign, habitCalendar); UserVO userVO = userService.findById(userId); achievementCalculation.calculateAchievement(userVO.getId(), AchievementCategoryType.HABIT, AchievementAction.ASSIGN); @@ -740,7 +739,7 @@ private void validateForEnroll(LocalDate date, HabitAssign habitAssign) { * @param habitAssign {@link HabitAssign} instance. */ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, - HabitStatusCalendar habitCalendar, Long userId) { + HabitStatusCalendar habitCalendar) { habitAssign.setWorkingDays(habitAssign.getWorkingDays() + 1); habitAssign.setLastEnrollmentDate(ZonedDateTime.now()); diff --git a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java index f7638b33b0..73656a6e2c 100644 --- a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java @@ -20,7 +20,6 @@ import greencity.exception.exceptions.UserBlockedException; import greencity.repository.PlaceCommentRepo; import java.util.List; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import lombok.AllArgsConstructor; From f01efd506546516136362ae9bf4a3ea048346991 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 25 Sep 2023 13:13:39 +0300 Subject: [PATCH 42/51] Added to table new values --- ...values-achievement_categories-Spodaryk.xml | 8 ++ .../functions/insert-values-achievements.sql | 97 +++++++++---------- 2 files changed, 55 insertions(+), 50 deletions(-) diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml index 46c0fb2972..c724ae541c 100644 --- a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml +++ b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml @@ -41,5 +41,13 @@ + + + + + + + + diff --git a/dao/src/main/resources/db/functions/insert-values-achievements.sql b/dao/src/main/resources/db/functions/insert-values-achievements.sql index b501381656..d7f87ff7b3 100644 --- a/dao/src/main/resources/db/functions/insert-values-achievements.sql +++ b/dao/src/main/resources/db/functions/insert-values-achievements.sql @@ -2,42 +2,23 @@ DO $$ DECLARE habit_id INTEGER; - create_news_id -INTEGER; - comment_or_reply_id -INTEGER; - like_comment_or_reply_id -INTEGER; - share_news_id -INTEGER; - achievement_id -INTEGER; -BEGIN -SELECT id -INTO habit_id -FROM achievement_categories -WHERE name = 'HABIT'; -SELECT id -INTO create_news_id -FROM achievement_categories -WHERE name = 'CREATE_NEWS'; -SELECT id -INTO comment_or_reply_id -FROM achievement_categories -WHERE name = 'COMMENT_OR_REPLY'; -SELECT id -INTO like_comment_or_reply_id -FROM achievement_categories -WHERE name = 'LIKE_COMMENT_OR_REPLY'; -SELECT id -INTO share_news_id -FROM achievement_categories -WHERE name = 'SHARE_NEWS'; -SELECT id -INTO achievement_id -FROM achievement_categories -WHERE name = 'ACHIEVEMENT'; +create_news_id INTEGER; +comment_or_reply_id INTEGER; +like_comment_or_reply_id INTEGER; +share_news_id INTEGER; +achievement_id INTEGER; +create_event_id INTEGER; +join_event_id INTEGER; +BEGIN +SELECT id INTO habit_id FROM achievement_categories WHERE name = 'HABIT'; +SELECT id INTO create_news_id FROM achievement_categories WHERE name = 'CREATE_NEWS'; +SELECT id INTO comment_or_reply_id FROM achievement_categories WHERE name = 'COMMENT_OR_REPLY'; +SELECT id INTO like_comment_or_reply_id FROM achievement_categories WHERE name = 'LIKE_COMMENT_OR_REPLY'; +SELECT id INTO share_news_id FROM achievement_categories WHERE name = 'SHARE_NEWS'; +SELECT id INTO achievement_id FROM achievement_categories WHERE name = 'ACHIEVEMENT'; +SELECT id INTO create_event_id FROM achievement_categories WHERE name = 'CREATE_EVENT'; +SELECT id INTO join_event_id FROM achievement_categories WHERE name = 'JOIN_EVENT'; DELETE FROM achievements; @@ -48,18 +29,18 @@ VALUES ('ACQUIRED_HABIT_14_DAYS', 'Набуття звички протягом INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) VALUES ('CREATED_1_NEWS', 'Створено перший новину', 'Created first news', 10, create_news_id, 1), - ('CREATED_5_NEWS', 'Створено 5 новин', 'Created 5 news', 10, create_news_id, 5), - ('CREATED_10_NEWS', 'Створено 10 новин', 'Created 10 news', 10, create_news_id, 10), - ('CREATED_25_NEWS', 'Створено 25 новин', 'Created 25 news', 10, create_news_id, 25), - ('CREATED_50_NEWS', 'Створено 50 новин', 'Created 50 news', 10, create_news_id, 50), - ('CREATED_100_NEWS', 'Створено 100 новин', 'Created 100 news', 10, create_news_id, 100); + ('CREATED_5_NEWS', 'Створено 5 новин', 'Created 5 news', 25, create_news_id, 5), + ('CREATED_10_NEWS', 'Створено 10 новин', 'Created 10 news', 50, create_news_id, 10), + ('CREATED_25_NEWS', 'Створено 25 новин', 'Created 25 news', 150, create_news_id, 25), + ('CREATED_50_NEWS', 'Створено 50 новин', 'Created 50 news', 250, create_news_id, 50), + ('CREATED_100_NEWS', 'Створено 100 новин', 'Created 100 news', 500, create_news_id, 100); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('COMMENT_OR_REPLY_1_TIMES', 'Коментування або відповідь перший раз', 'Comment or reply first time', 1, +VALUES ('COMMENT_OR_REPLY_1_TIMES', 'Коментування або відповідь перший раз', 'Comment or reply first time', 5, comment_or_reply_id, 1), - ('COMMENT_OR_REPLY_5_TIMES', 'Коментування або відповідь 5 разів', 'Comment or reply 5 times', 5, + ('COMMENT_OR_REPLY_5_TIMES', 'Коментування або відповідь 5 разів', 'Comment or reply 5 times', 10, comment_or_reply_id, 5), - ('COMMENT_OR_REPLY_10_TIMES', 'Коментування або відповідь 10 разів', 'Comment or reply 10 times', 10, + ('COMMENT_OR_REPLY_10_TIMES', 'Коментування або відповідь 10 разів', 'Comment or reply 10 times', 15, comment_or_reply_id, 10), ('COMMENT_OR_REPLY_25_TIMES', 'Коментування або відповідь 25 разів', 'Comment or reply 25 times', 25, comment_or_reply_id, 25), @@ -80,15 +61,15 @@ VALUES ('LIKE_COMMENT_OR_REPLY_1_TIMES', 'Лайкнуто коментар аб ('LIKE_COMMENT_OR_REPLY_50_TIMES', 'Лайкнуто коментарі або відповіді 50 разів', 'Liked comments or replies 50 times', 50, like_comment_or_reply_id, 50), ('LIKE_COMMENT_OR_REPLY_100_TIMES', 'Лайкнуто коментарі або відповіді 100 разів', - 'Liked comments or replies 100 times', 100, like_comment_or_reply_id, 100); + 'Liked comments or replies 100 times', 50, like_comment_or_reply_id, 100); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('SHARE_NEWS_1_TIMES', 'Поширено новину перший раз', 'Shared news first time', 1, share_news_id, 1), - ('SHARE_NEWS_5_TIMES', 'Поширено новини 5 разів', 'Shared news 5 times', 5, share_news_id, 5), - ('SHARE_NEWS_10_TIMES', 'Поширено новини 10 разів', 'Shared news 10 times', 10, share_news_id, 10), - ('SHARE_NEWS_25_TIMES', 'Поширено новини 25 разів', 'Shared news 25 times', 25, share_news_id, 25), - ('SHARE_NEWS_50_TIMES', 'Поширено новини 50 разів', 'Shared news 50 times', 50, share_news_id, 50), - ('SHARE_NEWS_100_TIMES', 'Поширено новини 100 разів', 'Shared news 100 times', 100, share_news_id, 100); +VALUES ('SHARE_NEWS_1_TIMES', 'Поширено новину перший раз', 'Shared news first time', 10, share_news_id, 1), + ('SHARE_NEWS_5_TIMES', 'Поширено новини 5 разів', 'Shared news 5 times', 25, share_news_id, 5), + ('SHARE_NEWS_10_TIMES', 'Поширено новини 10 разів', 'Shared news 10 times', 50, share_news_id, 10), + ('SHARE_NEWS_25_TIMES', 'Поширено новини 25 разів', 'Shared news 25 times', 150, share_news_id, 25), + ('SHARE_NEWS_50_TIMES', 'Поширено новини 50 разів', 'Shared news 50 times', 250, share_news_id, 50), + ('SHARE_NEWS_100_TIMES', 'Поширено новини 100 разів', 'Shared news 100 times', 500, share_news_id, 100); INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) VALUES ('FIRST_5_ACHIEVEMENTS', 'Перші 5 досягнень', 'First 5 Achievements', 10, achievement_id, 5), @@ -96,4 +77,20 @@ VALUES ('FIRST_5_ACHIEVEMENTS', 'Перші 5 досягнень', 'First 5 Achi ('FIRST_25_ACHIEVEMENTS', 'Перші 25 досягнень', 'First 25 Achievements', 50, achievement_id, 25), ('FIRST_50_ACHIEVEMENTS', 'Перші 50 досягнень', 'First 50 Achievements', 100, achievement_id, 50), ('FIRST_100_ACHIEVEMENTS', 'Перші 100 досягнень', 'First 100 Achievements', 200, achievement_id, 100); +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('CREATE_EVENT_1_TIMES', 'Створено подію 1 раз', 'Created event 1 time', 10, create_event_id, 1), + ('CREATE_EVENT_5_TIMES', 'Створено події 5 разів', 'Created events 5 times', 25, create_event_id, 5), + ('CREATE_EVENT_10_TIMES', 'Створено події 10 разів', 'Created events 10 times', 50, create_event_id, 10), + ('CREATE_EVENT_25_TIMES', 'Створено події 25 разів', 'Created events 25 times', 150, create_event_id, 25), + ('CREATE_EVENT_50_TIMES', 'Створено події 50 разів', 'Created events 50 times', 250, create_event_id, 50), + ('CREATE_EVENT_100_TIMES', 'Створено події 100 разів', 'Created events 100 times', 500, create_event_id, 100); + +INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) +VALUES ('JOIN_EVENT_1_TIMES', 'Приєднано до події 1 раз', 'Joined event 1 time', 5, join_event_id, 1), + ('JOIN_EVENT_5_TIMES', 'Приєднано до подій 5 разів', 'Joined events 5 times', 10, join_event_id, 5), + ('JOIN_EVENT_10_TIMES', 'Приєднано до подій 10 разів', 'Joined events 10 times', 25, join_event_id, 10), + ('JOIN_EVENT_25_TIMES', 'Приєднано до подій 25 разів', 'Joined events 25 times', 50, join_event_id, 25), + ('JOIN_EVENT_50_TIMES', 'Приєднано до подій 50 разів', 'Joined events 50 times', 100, join_event_id, 50), + ('JOIN_EVENT_100_TIMES', 'Приєднано до подій 100 разів', 'Joined events 100 times', 200, join_event_id, 100); + END $$; From a2558ba625542b8ea92fbfa94ec36961a1b3aa11 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Mon, 25 Sep 2023 14:00:08 +0300 Subject: [PATCH 43/51] Added methods to update score when we do action with events --- .../enums/AchievementCategoryType.java | 4 +- .../enums/RatingCalculationEnum.java | 121 +++++++++++------- .../enums/RatingCalculationEnumTest.java | 14 -- .../RatingStatisticsSpecification.java | 2 +- .../service/EcoNewsCommentServiceImpl.java | 4 +- .../greencity/service/EcoNewsServiceImpl.java | 4 +- .../service/EventCommentServiceImpl.java | 4 +- .../greencity/service/EventServiceImpl.java | 22 +++- .../service/PlaceCommentServiceImpl.java | 2 +- .../RatingStatisticsSpecificationTest.java | 12 +- .../service/EventServiceImplTest.java | 6 + 11 files changed, 120 insertions(+), 75 deletions(-) diff --git a/service-api/src/main/java/greencity/enums/AchievementCategoryType.java b/service-api/src/main/java/greencity/enums/AchievementCategoryType.java index bc5a5a5bc0..72faed4d92 100644 --- a/service-api/src/main/java/greencity/enums/AchievementCategoryType.java +++ b/service-api/src/main/java/greencity/enums/AchievementCategoryType.java @@ -9,5 +9,7 @@ public enum AchievementCategoryType { LIKE_COMMENT_OR_REPLY, SHARE_NEWS, HABIT, - ACHIEVEMENT + ACHIEVEMENT, + CREATE_EVENT, + JOIN_EVENT } diff --git a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java index 2e65e9299d..794d93021e 100644 --- a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java +++ b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java @@ -7,75 +7,104 @@ @Getter public enum RatingCalculationEnum { DAYS_OF_HABIT_IN_PROGRESS(1), - CREATE_NEWS(20), - COMMENT_OR_REPLY(2), - LIKE_COMMENT_OR_REPLY(10), + CREATE_NEWS(30), + COMMENT_OR_REPLY(5), + LIKE_COMMENT_OR_REPLY(1), SHARE_NEWS(20), + CREATE_EVENT(40), + JOIN_EVENT(20), UNDO_DAYS_OF_HABIT_IN_PROGRESS(-1), - DELETE_NEWS(-20), - DELETE_COMMENT_OR_REPLY(-2), - UNLIKE_COMMENT_OR_REPLY(-10), + UNDO_CREATE_NEWS(-30), + UNDO_COMMENT_OR_REPLY(-5), + UNDO_LIKE_COMMENT_OR_REPLY(-1), UNDO_SHARE_NEWS(-20), + UNDO_CREATE_EVENT(-40), + UNDO_JOIN_EVENT(-20), ACQUIRED_HABIT_14_DAYS(20), ACQUIRED_HABIT_21_DAYS(30), ACQUIRED_HABIT_30_DAYS(40), - CREATED_1_NEWS(10), - CREATED_5_NEWS(10), - CREATED_10_NEWS(10), - CREATED_25_NEWS(10), - CREATED_50_NEWS(10), - CREATED_100_NEWS(10), - COMMENT_OR_REPLY_1_TIMES(1), - COMMENT_OR_REPLY_5_TIMES(5), - COMMENT_OR_REPLY_10_TIMES(10), + COMMENT_OR_REPLY_1_TIMES(5), + COMMENT_OR_REPLY_5_TIMES(10), + COMMENT_OR_REPLY_10_TIMES(15), COMMENT_OR_REPLY_25_TIMES(25), COMMENT_OR_REPLY_50_TIMES(50), COMMENT_OR_REPLY_100_TIMES(100), - LIKE_COMMENT_OR_REPLY_1_TIMES(1), - LIKE_COMMENT_OR_REPLY_5_TIMES(5), - LIKE_COMMENT_OR_REPLY_10_TIMES(10), - LIKE_COMMENT_OR_REPLY_25_TIMES(25), - LIKE_COMMENT_OR_REPLY_50_TIMES(50), - LIKE_COMMENT_OR_REPLY_100_TIMES(100), - SHARE_NEWS_1_TIMES(1), - SHARE_NEWS_5_TIMES(5), - SHARE_NEWS_10_TIMES(10), - SHARE_NEWS_25_TIMES(25), - SHARE_NEWS_50_TIMES(50), - SHARE_NEWS_100_TIMES(100), + CREATE_EVENT_1_TIMES(10), + CREATE_EVENT_5_TIMES(25), + CREATE_EVENT_10_TIMES(50), + CREATE_EVENT_25_TIMES(150), + CREATE_EVENT_50_TIMES(250), + CREATE_EVENT_100_TIMES(500), + CREATED_1_NEWS(10), + CREATED_5_NEWS(25), + CREATED_10_NEWS(50), + CREATED_25_NEWS(150), + CREATED_50_NEWS(250), + CREATED_100_NEWS(500), FIRST_5_ACHIEVEMENTS(10), FIRST_10_ACHIEVEMENTS(25), FIRST_25_ACHIEVEMENTS(50), FIRST_50_ACHIEVEMENTS(100), FIRST_100_ACHIEVEMENTS(200), - UNDO_ACQUIRED_HABIT_14_DAYS(-20), - UNDO_ACQUIRED_HABIT_21_DAYS(-30), - UNDO_ACQUIRED_HABIT_30_DAYS(-40), - UNDO_CREATED_1_NEWS(-10), - UNDO_CREATED_5_NEWS(-10), - UNDO_CREATED_10_NEWS(-10), - UNDO_CREATED_25_NEWS(-10), - UNDO_CREATED_50_NEWS(-10), - UNDO_CREATED_100_NEWS(-10), - UNDO_COMMENT_OR_REPLY_1_TIMES(-1), - UNDO_COMMENT_OR_REPLY_5_TIMES(-5), - UNDO_COMMENT_OR_REPLY_10_TIMES(-10), + JOIN_EVENT_1_TIMES(5), + JOIN_EVENT_5_TIMES(10), + JOIN_EVENT_10_TIMES(25), + JOIN_EVENT_25_TIMES(50), + JOIN_EVENT_50_TIMES(100), + JOIN_EVENT_100_TIMES(200), + LIKE_COMMENT_OR_REPLY_1_TIMES(1), + LIKE_COMMENT_OR_REPLY_5_TIMES(5), + LIKE_COMMENT_OR_REPLY_10_TIMES(10), + LIKE_COMMENT_OR_REPLY_25_TIMES(25), + LIKE_COMMENT_OR_REPLY_50_TIMES(50), + LIKE_COMMENT_OR_REPLY_100_TIMES(50), + SHARE_NEWS_1_TIMES(10), + SHARE_NEWS_5_TIMES(25), + SHARE_NEWS_10_TIMES(50), + SHARE_NEWS_25_TIMES(150), + SHARE_NEWS_50_TIMES(250), + SHARE_NEWS_100_TIMES(500), + + UNDO_COMMENT_OR_REPLY_1_TIMES(-5), + UNDO_COMMENT_OR_REPLY_5_TIMES(-10), + UNDO_COMMENT_OR_REPLY_10_TIMES(-15), UNDO_COMMENT_OR_REPLY_25_TIMES(-25), UNDO_COMMENT_OR_REPLY_50_TIMES(-50), UNDO_COMMENT_OR_REPLY_100_TIMES(-100), + UNDO_CREATE_EVENT_1_TIMES(-10), + UNDO_CREATE_EVENT_5_TIMES(-25), + UNDO_CREATE_EVENT_10_TIMES(-50), + UNDO_CREATE_EVENT_25_TIMES(-150), + UNDO_CREATE_EVENT_50_TIMES(-250), + UNDO_CREATE_EVENT_100_TIMES(-500), + UNDO_CREATED_1_NEWS(-10), + UNDO_CREATED_5_NEWS(-25), + UNDO_CREATED_10_NEWS(-50), + UNDO_CREATED_25_NEWS(-150), + UNDO_CREATED_50_NEWS(-250), + UNDO_CREATED_100_NEWS(-500), + UNDO_JOIN_EVENT_1_TIMES(-5), + UNDO_JOIN_EVENT_5_TIMES(-10), + UNDO_JOIN_EVENT_10_TIMES(-25), + UNDO_JOIN_EVENT_25_TIMES(-50), + UNDO_JOIN_EVENT_50_TIMES(-100), + UNDO_JOIN_EVENT_100_TIMES(-200), UNDO_LIKE_COMMENT_OR_REPLY_1_TIMES(-1), UNDO_LIKE_COMMENT_OR_REPLY_5_TIMES(-5), UNDO_LIKE_COMMENT_OR_REPLY_10_TIMES(-10), UNDO_LIKE_COMMENT_OR_REPLY_25_TIMES(-25), UNDO_LIKE_COMMENT_OR_REPLY_50_TIMES(-50), - UNDO_LIKE_COMMENT_OR_REPLY_100_TIMES(-100), - UNDO_SHARE_NEWS_1_TIMES(-1), - UNDO_SHARE_NEWS_5_TIMES(-5), - UNDO_SHARE_NEWS_10_TIMES(-10), - UNDO_SHARE_NEWS_25_TIMES(-25), - UNDO_SHARE_NEWS_50_TIMES(-50), - UNDO_SHARE_NEWS_100_TIMES(-100), + UNDO_LIKE_COMMENT_OR_REPLY_100_TIMES(-50), + UNDO_SHARE_NEWS_1_TIMES(-10), + UNDO_SHARE_NEWS_5_TIMES(-25), + UNDO_SHARE_NEWS_10_TIMES(-50), + UNDO_SHARE_NEWS_25_TIMES(-150), + UNDO_SHARE_NEWS_50_TIMES(-250), + UNDO_SHARE_NEWS_100_TIMES(-500), + UNDO_ACQUIRED_HABIT_14_DAYS(-20), + UNDO_ACQUIRED_HABIT_21_DAYS(-30), + UNDO_ACQUIRED_HABIT_30_DAYS(-40), UNDO_FIRST_5_ACHIEVEMENTS(-10), UNDO_FIRST_10_ACHIEVEMENTS(-25), UNDO_FIRST_25_ACHIEVEMENTS(-50), diff --git a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java index 94f131d250..047e3570a3 100644 --- a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java +++ b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java @@ -8,20 +8,6 @@ class RatingCalculationEnumTest { - @Test - void testRatingPoints() { - assertEquals(1, RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS.getRatingPoints()); - assertEquals(20, RatingCalculationEnum.CREATE_NEWS.getRatingPoints()); - assertEquals(2, RatingCalculationEnum.COMMENT_OR_REPLY.getRatingPoints()); - assertEquals(10, RatingCalculationEnum.LIKE_COMMENT_OR_REPLY.getRatingPoints()); - assertEquals(20, RatingCalculationEnum.SHARE_NEWS.getRatingPoints()); - assertEquals(-1, RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS.getRatingPoints()); - assertEquals(-20, RatingCalculationEnum.DELETE_NEWS.getRatingPoints()); - assertEquals(-2, RatingCalculationEnum.DELETE_COMMENT_OR_REPLY.getRatingPoints()); - assertEquals(-10, RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY.getRatingPoints()); - assertEquals(-20, RatingCalculationEnum.UNDO_SHARE_NEWS.getRatingPoints()); - } - @Test void testFindEnumByNameValidName() { assertEquals(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, diff --git a/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java b/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java index 6162e2f701..66531f9969 100644 --- a/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java +++ b/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java @@ -63,7 +63,7 @@ private Predicate getEventNamePredicate(Root root, CriteriaBui SearchCriteria searchCriteria) { List enumValues = Arrays.asList(RatingCalculationEnum.values()); List selectedEnums = enumValues.stream() - .filter(x -> x.toString().toLowerCase().contains(((String) searchCriteria.getValue()).toLowerCase())) + .filter(x -> x.toString().toLowerCase().equals(((String) searchCriteria.getValue()).toLowerCase())) .collect(Collectors.toList()); Predicate predicate = criteriaBuilder.disjunction(); diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index 09e22328d6..7468c46ceb 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -168,7 +168,7 @@ public void deleteById(Long id, UserVO userVO) { comment.setStatus(CommentStatus.DELETED); achievementCalculation.calculateAchievement(userVO.getId(), AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); - ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_COMMENT_OR_REPLY, userVO); ecoNewsCommentRepo.save(comment); } @@ -209,7 +209,7 @@ public void like(Long id, UserVO userVO) { .anyMatch(user -> user.getId().equals(userVO.getId()))) { achievementCalculation.calculateAchievement(userVO.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_LIKE_COMMENT_OR_REPLY, userVO); ecoNewsService.unlikeComment(userVO, ecoNewsCommentVO); } else { ecoNewsService.likeComment(userVO, ecoNewsCommentVO); diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index 906d44f9b4..c43cb77461 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -328,7 +328,7 @@ public void delete(Long id, UserVO user) { if (user.getRole() != Role.ROLE_ADMIN && !user.getId().equals(ecoNewsVO.getAuthor().getId())) { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } - ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_CREATE_NEWS, user); achievementCalculation.calculateAchievement(user.getId(), AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE); @@ -434,7 +434,7 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { */ public void unlikeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().removeIf(u -> u.getId().equals(user.getId())); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, user); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_LIKE_COMMENT_OR_REPLY, user); achievementCalculation.calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); } diff --git a/service/src/main/java/greencity/service/EventCommentServiceImpl.java b/service/src/main/java/greencity/service/EventCommentServiceImpl.java index cbc9f45e0a..8717d2180f 100644 --- a/service/src/main/java/greencity/service/EventCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EventCommentServiceImpl.java @@ -236,7 +236,7 @@ public void delete(Long eventCommentId, UserVO user) { eventComment.getComments() .forEach(comment -> comment.setStatus(CommentStatus.DELETED)); } - ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, user); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_COMMENT_OR_REPLY, user); achievementCalculation.calculateAchievement(user.getId(), AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); @@ -301,7 +301,7 @@ public void like(Long commentId, UserVO userVO) { if (comment.getUsersLiked().stream().anyMatch(user -> user.getId().equals(userVO.getId()))) { comment.getUsersLiked().removeIf(user -> user.getId().equals(userVO.getId())); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_LIKE_COMMENT_OR_REPLY, userVO); achievementCalculation.calculateAchievement(userVO.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); } else { diff --git a/service/src/main/java/greencity/service/EventServiceImpl.java b/service/src/main/java/greencity/service/EventServiceImpl.java index 14c619292c..4961cb3b75 100644 --- a/service/src/main/java/greencity/service/EventServiceImpl.java +++ b/service/src/main/java/greencity/service/EventServiceImpl.java @@ -1,6 +1,7 @@ package greencity.service; import com.google.maps.model.LatLng; +import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.constant.AppConstant; import greencity.constant.ErrorMessage; @@ -15,6 +16,7 @@ import greencity.dto.filter.FilterEventDto; import greencity.dto.geocoding.AddressLatLngResponse; import greencity.dto.tag.TagVO; +import greencity.dto.user.UserVO; import greencity.entity.Tag; import greencity.entity.User; import greencity.entity.event.Event; @@ -22,12 +24,11 @@ import greencity.entity.event.EventGrade; import greencity.entity.event.EventImages; import greencity.entity.event.Address; -import greencity.enums.EventType; -import greencity.enums.Role; -import greencity.enums.TagType; +import greencity.enums.*; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; +import greencity.rating.RatingCalculation; import greencity.repository.EventRepo; import greencity.repository.UserRepo; import lombok.RequiredArgsConstructor; @@ -72,6 +73,8 @@ public class EventServiceImpl implements EventService { private final UserService userService; private static final String DEFAULT_TITLE_IMAGE_PATH = AppConstant.DEFAULT_EVENT_IMAGES; private final UserRepo userRepo; + private final RatingCalculation ratingCalculation; + private final AchievementCalculation achievementCalculation; @Override public EventDto save(AddEventDtoRequest addEventDtoRequest, String email, @@ -102,7 +105,10 @@ public EventDto save(AddEventDtoRequest addEventDtoRequest, String email, }.getType())); Event savedEvent = eventRepo.save(toSave); - + achievementCalculation.calculateAchievement(organizer.getId(), + AchievementCategoryType.CREATE_EVENT, AchievementAction.ASSIGN); + ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_EVENT, + modelMapper.map(organizer, UserVO.class)); return buildEventDto(savedEvent, organizer.getId()); } @@ -120,6 +126,10 @@ public void delete(Long eventId, String email) { if (toDelete.getOrganizer().getId().equals(user.getId()) || user.getRole() == Role.ROLE_ADMIN) { deleteImagesFromServer(eventImages); eventRepo.delete(toDelete); + achievementCalculation.calculateAchievement(user.getId(), + AchievementCategoryType.CREATE_EVENT, AchievementAction.DELETE); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_CREATE_EVENT, + modelMapper.map(user, UserVO.class)); } else { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } @@ -287,6 +297,10 @@ public void addAttender(Long eventId, String email) { User currentUser = modelMapper.map(restClient.findByEmail(email), User.class); checkAttenderToJoinTheEvent(event, currentUser); event.getAttenders().add(currentUser); + achievementCalculation.calculateAchievement(currentUser.getId(), + AchievementCategoryType.CREATE_EVENT, AchievementAction.ASSIGN); + ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_EVENT, + modelMapper.map(currentUser, UserVO.class)); eventRepo.save(event); } diff --git a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java index 73656a6e2c..790b0f0a0d 100644 --- a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java @@ -107,7 +107,7 @@ public void deleteById(Long id) { .orElseThrow(() -> new NotFoundException(ErrorMessage.COMMENT_NOT_FOUND_EXCEPTION))); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserVO userVO = restClient.findByEmail(authentication.getName()); - ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO); + ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_COMMENT_OR_REPLY, userVO); achievementCalculation.calculateAchievement(userVO.getId(), AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); } diff --git a/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java b/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java index 2fd1399a44..bc9a2a08ce 100644 --- a/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java +++ b/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java @@ -1,6 +1,8 @@ package greencity.filters; import static org.mockito.Mockito.*; + +import greencity.achievement.AchievementCalculation; import greencity.enums.RatingCalculationEnum; import greencity.dto.ratingstatistics.RatingStatisticsViewDto; import greencity.entity.RatingStatistics; @@ -12,6 +14,8 @@ import java.util.List; import javax.persistence.criteria.*; import javax.persistence.metamodel.SingularAttribute; + +import greencity.rating.RatingCalculation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -78,11 +82,15 @@ class RatingStatisticsSpecificationTest { private RatingStatisticsSpecification ratingStatisticsSpecification; private List criteriaList; + @Mock + RatingCalculation ratingCalculation; + @Mock + AchievementCalculation achievementCalculation; @BeforeEach void setUp() { RatingStatisticsViewDto ratingStatisticsViewDto = - new RatingStatisticsViewDto("2", "UNLIKE_COMMENT_OR_REPLY", "1", "", "2021-01-12", "2021-01-13", "", "50"); + new RatingStatisticsViewDto("2", "UNDO_COMMENT_OR_REPLY", "1", "", "2021-01-12", "2021-01-13", "", "50"); criteriaList = new ArrayList<>(); criteriaList.add( @@ -139,7 +147,7 @@ void toPredicate() { when(criteriaBuilderMock.disjunction()).thenReturn(predicateMock); - when(criteriaBuilderMock.equal(pathRatingStatisticsEnumMock, RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY)) + when(criteriaBuilderMock.equal(pathRatingStatisticsEnumMock, RatingCalculationEnum.UNDO_COMMENT_OR_REPLY)) .thenReturn(andEventNamePredicate); when(criteriaBuilderMock.or(predicateMock, andEventNamePredicate)).thenReturn(andEventNamePredicate); diff --git a/service/src/test/java/greencity/service/EventServiceImplTest.java b/service/src/test/java/greencity/service/EventServiceImplTest.java index 2a8a04a511..0b8a94898c 100644 --- a/service/src/test/java/greencity/service/EventServiceImplTest.java +++ b/service/src/test/java/greencity/service/EventServiceImplTest.java @@ -2,6 +2,7 @@ import greencity.ModelUtils; import greencity.TestConst; +import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.constant.AppConstant; import greencity.dto.PageableAdvancedDto; @@ -24,6 +25,7 @@ import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; +import greencity.rating.RatingCalculation; import greencity.repository.EventRepo; import greencity.repository.UserRepo; import lombok.SneakyThrows; @@ -100,6 +102,10 @@ class EventServiceImplTest { @InjectMocks EventServiceImpl eventService; + @Mock + RatingCalculation ratingCalculation; + @Mock + AchievementCalculation achievementCalculation; @Test void save() { From 68352113e5a64ff0ae7ccdb1f857ea3ddb9a3e6f Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 26 Sep 2023 18:55:50 +0300 Subject: [PATCH 44/51] Leaved only methods which are changing structure of achievement entity --- .../greencity/enums/AchievementAction.java | 9 - .../enums/AchievementCategoryType.java | 21 +- .../greencity/enums/AchievementStatus.java | 6 + .../java/greencity/enums/AchievementType.java | 7 + .../enums/RatingCalculationEnum.java | 130 ++----------- .../greencity/service/AchievementService.java | 7 +- .../java/greencity/service/UserService.java | 10 - .../enums/RatingCalculationEnumTest.java | 49 +++-- .../achievement/AchievementCalculation.java | 179 ++++++++---------- .../RatingStatisticsSpecification.java | 2 +- .../greencity/rating/RatingCalculation.java | 9 +- .../service/AchievementServiceImpl.java | 9 +- .../service/EcoNewsCommentServiceImpl.java | 35 ++-- .../greencity/service/EcoNewsServiceImpl.java | 46 +++-- .../service/EventCommentServiceImpl.java | 29 ++- .../greencity/service/EventServiceImpl.java | 21 +- .../service/HabitAssignServiceImpl.java | 45 +++-- .../service/PlaceCommentServiceImpl.java | 16 +- .../service/UserActionServiceImpl.java | 16 -- .../greencity/service/UserServiceImpl.java | 9 - .../AchievementCalculationTest.java | 157 +++------------ .../RatingStatisticsSpecificationTest.java | 12 +- .../service/AchievementServiceImplTest.java | 8 +- .../service/UserActionServiceImplTest.java | 45 +---- .../service/UserServiceImplTest.java | 7 - 25 files changed, 289 insertions(+), 595 deletions(-) delete mode 100644 service-api/src/main/java/greencity/enums/AchievementAction.java create mode 100644 service-api/src/main/java/greencity/enums/AchievementStatus.java create mode 100644 service-api/src/main/java/greencity/enums/AchievementType.java diff --git a/service-api/src/main/java/greencity/enums/AchievementAction.java b/service-api/src/main/java/greencity/enums/AchievementAction.java deleted file mode 100644 index c018db18d8..0000000000 --- a/service-api/src/main/java/greencity/enums/AchievementAction.java +++ /dev/null @@ -1,9 +0,0 @@ -package greencity.enums; - -import lombok.Getter; - -@Getter -public enum AchievementAction { - ASSIGN, - DELETE -} diff --git a/service-api/src/main/java/greencity/enums/AchievementCategoryType.java b/service-api/src/main/java/greencity/enums/AchievementCategoryType.java index 72faed4d92..a57a02a364 100644 --- a/service-api/src/main/java/greencity/enums/AchievementCategoryType.java +++ b/service-api/src/main/java/greencity/enums/AchievementCategoryType.java @@ -4,12 +4,17 @@ @Getter public enum AchievementCategoryType { - CREATE_NEWS, - COMMENT_OR_REPLY, - LIKE_COMMENT_OR_REPLY, - SHARE_NEWS, - HABIT, - ACHIEVEMENT, - CREATE_EVENT, - JOIN_EVENT + ECO_NEWS("EcoNews"), + ECO_NEWS_COMMENT("EcoNewsComments"), + ECO_NEWS_LIKE("EcoNewsLikes"), + ACHIEVEMENTS("Achievements"), + HABIT_STREAK("HabitStreak"), + ACQUIRED_HABIT("AcquiredHabits"), + SOCIAL_NETWORK("SocialNetworks"); + + private final String category; + + AchievementCategoryType(String category) { + this.category = category; + } } diff --git a/service-api/src/main/java/greencity/enums/AchievementStatus.java b/service-api/src/main/java/greencity/enums/AchievementStatus.java new file mode 100644 index 0000000000..01b8ea2984 --- /dev/null +++ b/service-api/src/main/java/greencity/enums/AchievementStatus.java @@ -0,0 +1,6 @@ +package greencity.enums; + +public enum AchievementStatus { + INACTIVE, + ACTIVE +} diff --git a/service-api/src/main/java/greencity/enums/AchievementType.java b/service-api/src/main/java/greencity/enums/AchievementType.java new file mode 100644 index 0000000000..6e9f82265a --- /dev/null +++ b/service-api/src/main/java/greencity/enums/AchievementType.java @@ -0,0 +1,7 @@ +package greencity.enums; + +public enum AchievementType { + INCREMENT, + SETTER, + COMPARISON +} diff --git a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java index 794d93021e..25f155130f 100644 --- a/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java +++ b/service-api/src/main/java/greencity/enums/RatingCalculationEnum.java @@ -1,134 +1,32 @@ package greencity.enums; -import greencity.constant.ErrorMessage; -import greencity.exception.exceptions.NotFoundException; import lombok.Getter; @Getter public enum RatingCalculationEnum { DAYS_OF_HABIT_IN_PROGRESS(1), - CREATE_NEWS(30), - COMMENT_OR_REPLY(5), - LIKE_COMMENT_OR_REPLY(1), + + CREATE_NEWS(20), + + COMMENT_OR_REPLY(2), + + LIKE_COMMENT_OR_REPLY(10), + SHARE_NEWS(20), - CREATE_EVENT(40), - JOIN_EVENT(20), + UNDO_DAYS_OF_HABIT_IN_PROGRESS(-1), - UNDO_CREATE_NEWS(-30), - UNDO_COMMENT_OR_REPLY(-5), - UNDO_LIKE_COMMENT_OR_REPLY(-1), - UNDO_SHARE_NEWS(-20), - UNDO_CREATE_EVENT(-40), - UNDO_JOIN_EVENT(-20), - ACQUIRED_HABIT_14_DAYS(20), - ACQUIRED_HABIT_21_DAYS(30), - ACQUIRED_HABIT_30_DAYS(40), - COMMENT_OR_REPLY_1_TIMES(5), - COMMENT_OR_REPLY_5_TIMES(10), - COMMENT_OR_REPLY_10_TIMES(15), - COMMENT_OR_REPLY_25_TIMES(25), - COMMENT_OR_REPLY_50_TIMES(50), - COMMENT_OR_REPLY_100_TIMES(100), - CREATE_EVENT_1_TIMES(10), - CREATE_EVENT_5_TIMES(25), - CREATE_EVENT_10_TIMES(50), - CREATE_EVENT_25_TIMES(150), - CREATE_EVENT_50_TIMES(250), - CREATE_EVENT_100_TIMES(500), - CREATED_1_NEWS(10), - CREATED_5_NEWS(25), - CREATED_10_NEWS(50), - CREATED_25_NEWS(150), - CREATED_50_NEWS(250), - CREATED_100_NEWS(500), - FIRST_5_ACHIEVEMENTS(10), - FIRST_10_ACHIEVEMENTS(25), - FIRST_25_ACHIEVEMENTS(50), - FIRST_50_ACHIEVEMENTS(100), - FIRST_100_ACHIEVEMENTS(200), - JOIN_EVENT_1_TIMES(5), - JOIN_EVENT_5_TIMES(10), - JOIN_EVENT_10_TIMES(25), - JOIN_EVENT_25_TIMES(50), - JOIN_EVENT_50_TIMES(100), - JOIN_EVENT_100_TIMES(200), - LIKE_COMMENT_OR_REPLY_1_TIMES(1), - LIKE_COMMENT_OR_REPLY_5_TIMES(5), - LIKE_COMMENT_OR_REPLY_10_TIMES(10), - LIKE_COMMENT_OR_REPLY_25_TIMES(25), - LIKE_COMMENT_OR_REPLY_50_TIMES(50), - LIKE_COMMENT_OR_REPLY_100_TIMES(50), - SHARE_NEWS_1_TIMES(10), - SHARE_NEWS_5_TIMES(25), - SHARE_NEWS_10_TIMES(50), - SHARE_NEWS_25_TIMES(150), - SHARE_NEWS_50_TIMES(250), - SHARE_NEWS_100_TIMES(500), + DELETE_NEWS(-20), - UNDO_COMMENT_OR_REPLY_1_TIMES(-5), - UNDO_COMMENT_OR_REPLY_5_TIMES(-10), - UNDO_COMMENT_OR_REPLY_10_TIMES(-15), - UNDO_COMMENT_OR_REPLY_25_TIMES(-25), - UNDO_COMMENT_OR_REPLY_50_TIMES(-50), - UNDO_COMMENT_OR_REPLY_100_TIMES(-100), - UNDO_CREATE_EVENT_1_TIMES(-10), - UNDO_CREATE_EVENT_5_TIMES(-25), - UNDO_CREATE_EVENT_10_TIMES(-50), - UNDO_CREATE_EVENT_25_TIMES(-150), - UNDO_CREATE_EVENT_50_TIMES(-250), - UNDO_CREATE_EVENT_100_TIMES(-500), - UNDO_CREATED_1_NEWS(-10), - UNDO_CREATED_5_NEWS(-25), - UNDO_CREATED_10_NEWS(-50), - UNDO_CREATED_25_NEWS(-150), - UNDO_CREATED_50_NEWS(-250), - UNDO_CREATED_100_NEWS(-500), - UNDO_JOIN_EVENT_1_TIMES(-5), - UNDO_JOIN_EVENT_5_TIMES(-10), - UNDO_JOIN_EVENT_10_TIMES(-25), - UNDO_JOIN_EVENT_25_TIMES(-50), - UNDO_JOIN_EVENT_50_TIMES(-100), - UNDO_JOIN_EVENT_100_TIMES(-200), - UNDO_LIKE_COMMENT_OR_REPLY_1_TIMES(-1), - UNDO_LIKE_COMMENT_OR_REPLY_5_TIMES(-5), - UNDO_LIKE_COMMENT_OR_REPLY_10_TIMES(-10), - UNDO_LIKE_COMMENT_OR_REPLY_25_TIMES(-25), - UNDO_LIKE_COMMENT_OR_REPLY_50_TIMES(-50), - UNDO_LIKE_COMMENT_OR_REPLY_100_TIMES(-50), - UNDO_SHARE_NEWS_1_TIMES(-10), - UNDO_SHARE_NEWS_5_TIMES(-25), - UNDO_SHARE_NEWS_10_TIMES(-50), - UNDO_SHARE_NEWS_25_TIMES(-150), - UNDO_SHARE_NEWS_50_TIMES(-250), - UNDO_SHARE_NEWS_100_TIMES(-500), - UNDO_ACQUIRED_HABIT_14_DAYS(-20), - UNDO_ACQUIRED_HABIT_21_DAYS(-30), - UNDO_ACQUIRED_HABIT_30_DAYS(-40), - UNDO_FIRST_5_ACHIEVEMENTS(-10), - UNDO_FIRST_10_ACHIEVEMENTS(-25), - UNDO_FIRST_25_ACHIEVEMENTS(-50), - UNDO_FIRST_50_ACHIEVEMENTS(-100), - UNDO_FIRST_100_ACHIEVEMENTS(-200); + DELETE_COMMENT_OR_REPLY(-2), + + UNLIKE_COMMENT_OR_REPLY(-10), + + UNDO_SHARE_NEWS(-20); private final int ratingPoints; RatingCalculationEnum(int ratingPoints) { this.ratingPoints = ratingPoints; } - - /** - * Finds the RatingCalculationEnum object corresponding to the given name. - * - * @param name The name of the enum to find. - * @return The found RatingCalculationEnum object. - * @throws NotFoundException if the enum by the given name does not exist. - */ - public static RatingCalculationEnum findEnumByName(String name) { - try { - return RatingCalculationEnum.valueOf(name); - } catch (IllegalArgumentException e) { - throw new NotFoundException(ErrorMessage.RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME + name); - } - } } diff --git a/service-api/src/main/java/greencity/service/AchievementService.java b/service-api/src/main/java/greencity/service/AchievementService.java index 37615be645..e74e416a43 100644 --- a/service-api/src/main/java/greencity/service/AchievementService.java +++ b/service-api/src/main/java/greencity/service/AchievementService.java @@ -3,7 +3,8 @@ import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.*; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementAction; + +import greencity.enums.AchievementType; import org.springframework.data.domain.Pageable; import java.util.List; @@ -92,6 +93,6 @@ public interface AchievementService { /** * Method for achievement Calculation. */ - void calculateAchievements(Long id, AchievementCategoryType achievementCategory, - AchievementAction achievementAction); + void calculateAchievements(Long id, AchievementType achievementType, + AchievementCategoryType achievementCategory, Integer size); } diff --git a/service-api/src/main/java/greencity/service/UserService.java b/service-api/src/main/java/greencity/service/UserService.java index a3c6edf040..596d4f622a 100644 --- a/service-api/src/main/java/greencity/service/UserService.java +++ b/service-api/src/main/java/greencity/service/UserService.java @@ -14,16 +14,6 @@ import java.util.Optional; public interface UserService { - /** - * Saves the provided UserVO object into the repository after mapping it to a - * User entity. This method uses ModelMapper to convert the UserVO object into a - * User entity and then saves it using the User repository. - * - * @param userVO The user value object containing the user details to be saved. - * @see UserVO - */ - void save(UserVO userVO); - /** * Method that allow you to find not 'DEACTIVATED' {@link UserVO} by email. * diff --git a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java index 047e3570a3..99f50e35a7 100644 --- a/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java +++ b/service-api/src/test/java/greencity/enums/RatingCalculationEnumTest.java @@ -1,29 +1,52 @@ package greencity.enums; -import greencity.constant.ErrorMessage; -import greencity.exception.exceptions.NotFoundException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; class RatingCalculationEnumTest { @Test - void testFindEnumByNameValidName() { - assertEquals(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, - RatingCalculationEnum.findEnumByName("DAYS_OF_HABIT_IN_PROGRESS")); - assertEquals(RatingCalculationEnum.CREATE_NEWS, RatingCalculationEnum.findEnumByName("CREATE_NEWS")); + void testEnumValues() { + RatingCalculationEnum[] expected = { + RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, + RatingCalculationEnum.CREATE_NEWS, + RatingCalculationEnum.COMMENT_OR_REPLY, + RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, + RatingCalculationEnum.SHARE_NEWS, + RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, + RatingCalculationEnum.DELETE_NEWS, + RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, + RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, + RatingCalculationEnum.UNDO_SHARE_NEWS + }; + + RatingCalculationEnum[] actual = RatingCalculationEnum.values(); + assertEquals(expected.length, actual.length, "Enum length does not match expected length"); + + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], actual[i], "Enum value does not match at index " + i); + } } @Test - void testFindEnumByNameInvalidName() { - assertThrows(NotFoundException.class, () -> RatingCalculationEnum.findEnumByName("INVALID_NAME")); + void testEnumValueOf() { + for (RatingCalculationEnum value : RatingCalculationEnum.values()) { + assertEquals(value, RatingCalculationEnum.valueOf(value.name()), + "Enum valueOf does not match for " + value.name()); + } } @Test - void testErrorMessageOnNotFound() { - NotFoundException exception = - assertThrows(NotFoundException.class, () -> RatingCalculationEnum.findEnumByName("INVALID_NAME")); - assertEquals(ErrorMessage.RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME + "INVALID_NAME", exception.getMessage()); + void testRatingPoints() { + assertEquals(1, RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS.getRatingPoints()); + assertEquals(20, RatingCalculationEnum.CREATE_NEWS.getRatingPoints()); + assertEquals(2, RatingCalculationEnum.COMMENT_OR_REPLY.getRatingPoints()); + assertEquals(10, RatingCalculationEnum.LIKE_COMMENT_OR_REPLY.getRatingPoints()); + assertEquals(20, RatingCalculationEnum.SHARE_NEWS.getRatingPoints()); + assertEquals(-1, RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS.getRatingPoints()); + assertEquals(-20, RatingCalculationEnum.DELETE_NEWS.getRatingPoints()); + assertEquals(-2, RatingCalculationEnum.DELETE_COMMENT_OR_REPLY.getRatingPoints()); + assertEquals(-10, RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY.getRatingPoints()); + assertEquals(-20, RatingCalculationEnum.UNDO_SHARE_NEWS.getRatingPoints()); } } diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index e90e104b74..7c1fd1d1df 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -1,167 +1,136 @@ package greencity.achievement; -import greencity.constant.ErrorMessage; +import greencity.client.RestClient; import greencity.dto.achievement.AchievementVO; +import greencity.dto.achievement.UserVOAchievement; import greencity.dto.achievementcategory.AchievementCategoryVO; -import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; -import greencity.entity.Achievement; +import greencity.entity.User; import greencity.entity.UserAchievement; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementAction; -import greencity.enums.RatingCalculationEnum; -import greencity.rating.RatingCalculation; -import greencity.repository.AchievementRepo; +import greencity.enums.AchievementType; import greencity.repository.UserAchievementRepo; -import greencity.repository.UserRepo; import greencity.service.AchievementCategoryService; import greencity.service.AchievementService; import greencity.service.UserActionService; -import greencity.service.UserService; +import org.modelmapper.ModelMapper; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; -import java.util.NoSuchElementException; +import java.util.Optional; + +import static greencity.enums.AchievementStatus.ACTIVE; +import static greencity.enums.AchievementType.INCREMENT; @Component public class AchievementCalculation { + private RestClient restClient; private UserActionService userActionService; private AchievementService achievementService; - private UserService userService; private AchievementCategoryService achievementCategoryService; + private final ModelMapper modelMapper; private UserAchievementRepo userAchievementRepo; - private final UserRepo userRepo; - private final AchievementRepo achievementRepo; - private final RatingCalculation ratingCalculation; /** * Constructor for {@link AchievementCalculation}. * + * @param restClient {@link RestClient} * @param userActionService {@link UserActionService} * @param achievementService {@link AchievementService} * @param achievementCategoryService {@link AchievementCategoryService} + * @param modelMapper {@link ModelMapper} */ - public AchievementCalculation( + public AchievementCalculation(RestClient restClient, UserActionService userActionService, @Lazy AchievementService achievementService, AchievementCategoryService achievementCategoryService, - UserAchievementRepo userAchievementRepo, - UserRepo userRepo, - AchievementRepo achievementRepo, RatingCalculation ratingCalculation, UserService userService) { + ModelMapper modelMapper, + UserAchievementRepo userAchievementRepo) { + this.restClient = restClient; this.userActionService = userActionService; this.achievementService = achievementService; this.achievementCategoryService = achievementCategoryService; + this.modelMapper = modelMapper; this.userAchievementRepo = userAchievementRepo; - this.userRepo = userRepo; - this.achievementRepo = achievementRepo; - this.ratingCalculation = ratingCalculation; - this.userService = userService; } /** - * Calculate and handle achievements for a user based on specified category and - * status. + * Method that changing user actions. {@link greencity.entity.UserAction} * - * @param userId The user ID for whom the achievement is to be - * calculated. - * @param category The category type of the achievement. - * @param achievementAction The status of the achievement (ASSIGN, DELETE, - * etc.). + * @param userId of {@link User} + * @param type of action + * @param category {@link AchievementCategoryType} + * @param count number of specific actions + * @author Orest Mamchuk */ - public void calculateAchievement(Long userId, AchievementCategoryType category, - AchievementAction achievementAction) { - AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.name()); - UserActionVO userActionVO = - userActionService.findUserActionByUserIdAndAchievementCategory(userId, achievementCategoryVO.getId()); - int count = updateCount(userActionVO, achievementAction); + public void calculateAchievement(Long userId, AchievementType type, + AchievementCategoryType category, Integer count) { + AchievementCategoryVO achievementCategoryVO = achievementCategoryService.findByName(category.getCategory()); + UserActionVO userActionVO = userActionService.findUserActionByUserIdAndAchievementCategory( + userId, achievementCategoryVO.getId()); + count = checkType(type, userActionVO, count); userActionService.updateUserActions(userActionVO); - - checkAchievements(achievementCategoryVO.getId(), count, userId, achievementAction); - } - - /** - * Update the count of user actions based on achievement status. - * - * @param userActionVO The user's action data object. - * @param achievementAction The status of the achievement. - * @return Updated count of user actions. - */ - private int updateCount(UserActionVO userActionVO, AchievementAction achievementAction) { - int count = achievementAction.equals(AchievementAction.ASSIGN) ? userActionVO.getCount() + 1 - : userActionVO.getCount() - 1; - userActionVO.setCount(count); - return count; + checkAchievements(achievementCategoryVO.getId(), count, userId); } /** - * Check and handle achievements based on specified conditions. + * Method for finding achievements. * - * @param achievementCategoryId The ID of the achievement category. - * @param count The count of user actions for the achievement. - * @param userId The user ID for whom the achievement is to be - * checked. - * @param achievementAction The status of the achievement. + * @param achievementCategoryId of {@link AchievementCategoryType} + * @param count number of specific actions + * @param userId of {@link User} + * @author Orest Mamchuk */ - private void checkAchievements(Long achievementCategoryId, Integer count, Long userId, - AchievementAction achievementAction) { + private void checkAchievements(Long achievementCategoryId, Integer count, Long userId) { + UserVOAchievement userForAchievement = restClient.findUserForAchievement(userId); AchievementVO achievementVO = achievementService.findByCategoryIdAndCondition(achievementCategoryId, count); if (achievementVO != null) { - if (achievementAction.equals(AchievementAction.ASSIGN)) { - saveAchievementToUser(userId, achievementCategoryId, count); - } else { - deleteAchievementFromUser(userId, achievementCategoryId, count); - } + changeAchievementStatus(modelMapper.map(userForAchievement, User.class), achievementVO); } } /** - * Save an achievement to a user's record. + * Method that changing achievement status. * - * @param userId The user ID. - * @param achievementCategoryId The achievement category ID. - * @param count The count of user actions for the achievement. + * @param user {@link User} + * @param achievementVO {@link AchievementVO} + * @author Orest Mamchuk */ - - private void saveAchievementToUser(Long userId, Long achievementCategoryId, int count) { - Achievement achievement = - achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) - .orElseThrow(() -> new NoSuchElementException( - ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); - UserAchievement userAchievement = UserAchievement.builder() - .achievement(achievement) - .user(userRepo.findById(userId) - .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) - .build(); - RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName(achievement.getTitle()); - UserVO user = userService.findById(userId); - ratingCalculation.ratingCalculation(reason, user); - userAchievementRepo.save(userAchievement); - calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.ASSIGN); + private void changeAchievementStatus(User user, AchievementVO achievementVO) { + Optional userAchievement = user.getUserAchievements().stream() + .filter(userAchievement1 -> userAchievement1.getAchievement().getId().equals(achievementVO.getId())) + .findFirst(); + if (userAchievement.isPresent()) { + UserAchievement achievement = userAchievement.get(); + userAchievementRepo.save(achievement); + calculateAchievement(user.getId(), INCREMENT, AchievementCategoryType.ACHIEVEMENTS, 0); + } } /** - * Delete an achievement from a user's record. + * Method check achievement type. * - * @param userId The user ID. - * @param achievementCategoryId The achievement category ID. - * @param count The count of user actions for the achievement. + * @param type of action + * @param count number of specific actions + * @return count action */ - private void deleteAchievementFromUser(Long userId, Long achievementCategoryId, int count) { - Achievement achievement = - achievementRepo.findByAchievementCategoryIdAndCondition(achievementCategoryId, count) - .orElseThrow(() -> new NoSuchElementException( - ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + achievementCategoryId)); - - UserAchievement userAchievement = UserAchievement.builder() - .achievement(achievement) - .user(userRepo.findById(userId) - .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) - .build(); - - RatingCalculationEnum reason = RatingCalculationEnum.findEnumByName("UNDO_" + achievement.getTitle()); - UserVO user = userService.findById(userId); - ratingCalculation.ratingCalculation(reason, user); - userAchievementRepo.delete(userAchievement); - calculateAchievement(userId, AchievementCategoryType.ACHIEVEMENT, AchievementAction.DELETE); + private int checkType(AchievementType type, UserActionVO userActionVO, Integer count) { + switch (type) { + case INCREMENT: + count = userActionVO.getCount() + 1; + userActionVO.setCount(count); + break; + case SETTER: + userActionVO.setCount(count); + break; + case COMPARISON: + if (userActionVO.getCount() < count) { + userActionVO.setCount(count); + } + break; + default: + throw new IllegalStateException("Unexpected value: " + type); + } + return count; } } diff --git a/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java b/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java index 66531f9969..6162e2f701 100644 --- a/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java +++ b/service/src/main/java/greencity/filters/RatingStatisticsSpecification.java @@ -63,7 +63,7 @@ private Predicate getEventNamePredicate(Root root, CriteriaBui SearchCriteria searchCriteria) { List enumValues = Arrays.asList(RatingCalculationEnum.values()); List selectedEnums = enumValues.stream() - .filter(x -> x.toString().toLowerCase().equals(((String) searchCriteria.getValue()).toLowerCase())) + .filter(x -> x.toString().toLowerCase().contains(((String) searchCriteria.getValue()).toLowerCase())) .collect(Collectors.toList()); Predicate predicate = criteriaBuilder.disjunction(); diff --git a/service/src/main/java/greencity/rating/RatingCalculation.java b/service/src/main/java/greencity/rating/RatingCalculation.java index 2b97da6d63..57b807f78f 100644 --- a/service/src/main/java/greencity/rating/RatingCalculation.java +++ b/service/src/main/java/greencity/rating/RatingCalculation.java @@ -7,13 +7,14 @@ import greencity.entity.User; import greencity.enums.RatingCalculationEnum; import greencity.service.RatingStatisticsService; -import greencity.service.UserService; import lombok.AllArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; +import static greencity.constant.AppConstant.AUTHORIZATION; + @Component @AllArgsConstructor public class RatingCalculation { @@ -21,18 +22,18 @@ public class RatingCalculation { private RatingStatisticsService ratingStatisticsService; private final ModelMapper modelMapper; private final HttpServletRequest httpServletRequest; - private UserService userService; /** * Method that calculates the user rating. - * + * * @param rating of {@link RatingCalculationEnum} * @param userVo of {@link UserVO} */ public void ratingCalculation(RatingCalculationEnum rating, UserVO userVo) { + String accessToken = httpServletRequest.getHeader(AUTHORIZATION); User user = modelMapper.map(userVo, User.class); userVo.setRating(userVo.getRating() + rating.getRatingPoints()); - userService.save(userVo); + restClient.save(userVo, accessToken); RatingStatistics ratingStatistics = RatingStatistics .builder() .rating(userVo.getRating()) diff --git a/service/src/main/java/greencity/service/AchievementServiceImpl.java b/service/src/main/java/greencity/service/AchievementServiceImpl.java index 16f2bf9bb2..f2014374b1 100644 --- a/service/src/main/java/greencity/service/AchievementServiceImpl.java +++ b/service/src/main/java/greencity/service/AchievementServiceImpl.java @@ -13,7 +13,8 @@ import greencity.entity.AchievementCategory; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementAction; + +import greencity.enums.AchievementType; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.NotUpdatedException; @@ -206,8 +207,8 @@ public AchievementVO findByCategoryIdAndCondition(Long categoryId, Integer condi * {@inheritDoc} */ @Override - public void calculateAchievements(Long id, - AchievementCategoryType achievementCategory, AchievementAction achievementAction) { - achievementCalculation.calculateAchievement(id, achievementCategory, achievementAction); + public void calculateAchievements(Long id, AchievementType achievementType, + AchievementCategoryType achievementCategory, Integer size) { + achievementCalculation.calculateAchievement(id, achievementType, achievementCategory, size); } } diff --git a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java index 7468c46ceb..aa21087d25 100644 --- a/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsCommentServiceImpl.java @@ -13,7 +13,11 @@ import greencity.entity.EcoNews; import greencity.entity.EcoNewsComment; import greencity.entity.User; -import greencity.enums.*; +import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementType; +import greencity.enums.CommentStatus; +import greencity.enums.Role; +import greencity.enums.RatingCalculationEnum; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; @@ -30,6 +34,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; @Service @@ -61,8 +66,7 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq UserVO userVO) { EcoNewsVO ecoNewsVO = ecoNewsService.findById(econewsId); EcoNewsComment ecoNewsComment = modelMapper.map(addEcoNewsCommentDtoRequest, EcoNewsComment.class); - User user = modelMapper.map(userVO, User.class); - ecoNewsComment.setUser(user); + ecoNewsComment.setUser(modelMapper.map(userVO, User.class)); ecoNewsComment.setEcoNews(modelMapper.map(ecoNewsVO, EcoNews.class)); if (addEcoNewsCommentDtoRequest.getParentCommentId() != 0) { EcoNewsComment parentComment = @@ -74,11 +78,11 @@ public AddEcoNewsCommentDtoResponse save(Long econewsId, AddEcoNewsCommentDtoReq throw new BadRequestException(ErrorMessage.CANNOT_REPLY_THE_REPLY); } } - achievementCalculation - .calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN); - ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); - + CompletableFuture.runAsync(() -> achievementCalculation + .calculateAchievement(userVO.getId(), AchievementType.INCREMENT, + AchievementCategoryType.ECO_NEWS_COMMENT, 0)); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); ecoNewsComment.setStatus(CommentStatus.ORIGINAL); return modelMapper.map(ecoNewsCommentRepo.save(ecoNewsComment), AddEcoNewsCommentDtoResponse.class); @@ -166,9 +170,8 @@ public void deleteById(Long id, UserVO userVO) { comment.getComments().forEach(c -> c.setStatus(CommentStatus.DELETED)); } comment.setStatus(CommentStatus.DELETED); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_COMMENT_OR_REPLY, userVO); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); ecoNewsCommentRepo.save(comment); } @@ -207,15 +210,13 @@ public void like(Long id, UserVO userVO) { EcoNewsCommentVO ecoNewsCommentVO = modelMapper.map(comment, EcoNewsCommentVO.class); if (comment.getUsersLiked().stream() .anyMatch(user -> user.getId().equals(userVO.getId()))) { - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_LIKE_COMMENT_OR_REPLY, userVO); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); ecoNewsService.unlikeComment(userVO, ecoNewsCommentVO); } else { ecoNewsService.likeComment(userVO, ecoNewsCommentVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN); - ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); } ecoNewsCommentRepo.save(modelMapper.map(ecoNewsCommentVO, EcoNewsComment.class)); } diff --git a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java index c43cb77461..79c0b90c7d 100644 --- a/service/src/main/java/greencity/service/EcoNewsServiceImpl.java +++ b/service/src/main/java/greencity/service/EcoNewsServiceImpl.java @@ -16,7 +16,12 @@ import greencity.dto.user.UserVO; import greencity.entity.*; import greencity.entity.localization.TagTranslation; -import greencity.enums.*; +import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementType; +import greencity.enums.Role; +import greencity.enums.CommentStatus; +import greencity.enums.TagType; +import greencity.enums.RatingCalculationEnum; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.NotSavedException; @@ -42,6 +47,7 @@ import javax.servlet.http.HttpServletRequest; import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static greencity.constant.AppConstant.AUTHORIZATION; @@ -75,10 +81,9 @@ public AddEcoNewsDtoResponse save(AddEcoNewsDtoRequest addEcoNewsDtoRequest, AddEcoNewsDtoResponse addEcoNewsDtoResponse = modelMapper.map(toSave, AddEcoNewsDtoResponse.class); sendEmailDto(addEcoNewsDtoResponse, toSave.getAuthor()); - achievementCalculation - .calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); - ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, modelMapper.map(toSave, UserVO.class)); + CompletableFuture.runAsync(() -> achievementCalculation + .calculateAchievement(toSave.getAuthor().getId(), AchievementType.INCREMENT, + AchievementCategoryType.ECO_NEWS, 0)); return addEcoNewsDtoResponse; } @@ -94,10 +99,13 @@ public EcoNewsGenericDto saveEcoNews(AddEcoNewsDtoRequest addEcoNewsDtoRequest, EcoNewsGenericDto ecoNewsDto = getEcoNewsGenericDtoWithAllTags(toSave); sendEmailDto(ecoNewsDto, toSave.getAuthor()); + CompletableFuture.runAsync(() -> achievementCalculation + .calculateAchievement(toSave.getAuthor().getId(), AchievementType.INCREMENT, + AchievementCategoryType.ECO_NEWS, 0)); UserVO user = userService.findByEmail(email); - ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, user); - achievementCalculation.calculateAchievement(toSave.getAuthor().getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, user)); + return ecoNewsDto; } @@ -228,6 +236,8 @@ public PageableAdvancedDto findAllByUser(UserVO user, Pageabl /** * {@inheritDoc} * + * @author Kovaliv Taras. + * @return */ @Override public PageableAdvancedDto find(Pageable page, List tags) { @@ -328,10 +338,8 @@ public void delete(Long id, UserVO user) { if (user.getRole() != Role.ROLE_ADMIN && !user.getId().equals(ecoNewsVO.getAuthor().getId())) { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_CREATE_NEWS, user); - achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE); - + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_NEWS, user)); ecoNewsRepo.deleteById(ecoNewsVO.getId()); } @@ -420,9 +428,10 @@ public Long getAmountOfPublishedNewsByUserId(Long id) { */ public void likeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().add(user); - ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user); - achievementCalculation.calculateAchievement(user.getId(), AchievementCategoryType.LIKE_COMMENT_OR_REPLY, - AchievementAction.ASSIGN); + CompletableFuture + .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); + CompletableFuture.runAsync(() -> achievementCalculation + .calculateAchievement(user.getId(), AchievementType.INCREMENT, AchievementCategoryType.ECO_NEWS_LIKE, 0)); } /** @@ -434,9 +443,8 @@ public void likeComment(UserVO user, EcoNewsCommentVO comment) { */ public void unlikeComment(UserVO user, EcoNewsCommentVO comment) { comment.getUsersLiked().removeIf(u -> u.getId().equals(user.getId())); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_LIKE_COMMENT_OR_REPLY, user); - achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); + CompletableFuture + .runAsync(() -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, user)); } @Override @@ -783,6 +791,8 @@ private EcoNews genericSave(AddEcoNewsDtoRequest addEcoNewsDtoRequest, }.getType())); try { ecoNewsRepo.save(toSave); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_NEWS, byEmail)); } catch (DataIntegrityViolationException e) { throw new NotSavedException(ErrorMessage.ECO_NEWS_NOT_SAVED); } diff --git a/service/src/main/java/greencity/service/EventCommentServiceImpl.java b/service/src/main/java/greencity/service/EventCommentServiceImpl.java index 8717d2180f..008b565a33 100644 --- a/service/src/main/java/greencity/service/EventCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/EventCommentServiceImpl.java @@ -1,6 +1,5 @@ package greencity.service; -import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.constant.ErrorMessage; import greencity.dto.PageableDto; @@ -16,7 +15,9 @@ import greencity.entity.User; import greencity.entity.event.Event; import greencity.entity.event.EventComment; -import greencity.enums.*; +import greencity.enums.CommentStatus; +import greencity.enums.Role; +import greencity.enums.RatingCalculationEnum; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; @@ -32,6 +33,7 @@ import java.util.List; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; @Service @@ -44,7 +46,6 @@ public class EventCommentServiceImpl implements EventCommentService { private final EventRepo eventRepo; private final RestClient restClient; private final RatingCalculation ratingCalculation; - private AchievementCalculation achievementCalculation; /** * Method to save {@link greencity.entity.event.EventComment}. @@ -89,9 +90,10 @@ public AddEventCommentDtoResponse save(Long eventId, AddEventCommentDtoRequest a addEventCommentDtoResponse.setAuthor(modelMapper.map(userVO, EventCommentAuthorDto.class)); sendEmailDto(addEventCommentDtoResponse); - ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN); + + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); + return addEventCommentDtoResponse; } @@ -236,10 +238,9 @@ public void delete(Long eventCommentId, UserVO user) { eventComment.getComments() .forEach(comment -> comment.setStatus(CommentStatus.DELETED)); } - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_COMMENT_OR_REPLY, user); - achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, user)); eventCommentRepo.save(eventComment); } @@ -301,14 +302,12 @@ public void like(Long commentId, UserVO userVO) { if (comment.getUsersLiked().stream().anyMatch(user -> user.getId().equals(userVO.getId()))) { comment.getUsersLiked().removeIf(user -> user.getId().equals(userVO.getId())); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_LIKE_COMMENT_OR_REPLY, userVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.DELETE); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY, userVO)); } else { comment.getUsersLiked().add(modelMapper.map(userVO, User.class)); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.LIKE_COMMENT_OR_REPLY, AchievementAction.ASSIGN); - ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.LIKE_COMMENT_OR_REPLY, userVO)); } eventCommentRepo.save(comment); } diff --git a/service/src/main/java/greencity/service/EventServiceImpl.java b/service/src/main/java/greencity/service/EventServiceImpl.java index a083089da7..4beef7dab1 100644 --- a/service/src/main/java/greencity/service/EventServiceImpl.java +++ b/service/src/main/java/greencity/service/EventServiceImpl.java @@ -1,7 +1,6 @@ package greencity.service; import com.google.maps.model.LatLng; -import greencity.achievement.AchievementCalculation; import greencity.client.RestClient; import greencity.constant.AppConstant; import greencity.constant.ErrorMessage; @@ -16,7 +15,6 @@ import greencity.dto.filter.FilterEventDto; import greencity.dto.geocoding.AddressLatLngResponse; import greencity.dto.tag.TagVO; -import greencity.dto.user.UserVO; import greencity.entity.Tag; import greencity.entity.User; import greencity.entity.event.Event; @@ -24,11 +22,12 @@ import greencity.entity.event.EventGrade; import greencity.entity.event.EventImages; import greencity.entity.event.Address; -import greencity.enums.*; +import greencity.enums.EventType; +import greencity.enums.Role; +import greencity.enums.TagType; import greencity.exception.exceptions.BadRequestException; import greencity.exception.exceptions.NotFoundException; import greencity.exception.exceptions.UserHasNoPermissionToAccessException; -import greencity.rating.RatingCalculation; import greencity.message.SendEventCreationNotification; import greencity.repository.EventRepo; import greencity.repository.UserRepo; @@ -74,8 +73,6 @@ public class EventServiceImpl implements EventService { private final UserService userService; private static final String DEFAULT_TITLE_IMAGE_PATH = AppConstant.DEFAULT_EVENT_IMAGES; private final UserRepo userRepo; - private final RatingCalculation ratingCalculation; - private final AchievementCalculation achievementCalculation; @Override public EventDto save(AddEventDtoRequest addEventDtoRequest, String email, @@ -106,10 +103,6 @@ public EventDto save(AddEventDtoRequest addEventDtoRequest, String email, }.getType())); Event savedEvent = eventRepo.save(toSave); - achievementCalculation.calculateAchievement(organizer.getId(), - AchievementCategoryType.CREATE_EVENT, AchievementAction.ASSIGN); - ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_EVENT, - modelMapper.map(organizer, UserVO.class)); sendEmailNotification(savedEvent.getTitle(), organizer.getFirstName(), organizer.getEmail()); return buildEventDto(savedEvent, organizer.getId()); } @@ -128,10 +121,6 @@ public void delete(Long eventId, String email) { if (toDelete.getOrganizer().getId().equals(user.getId()) || user.getRole() == Role.ROLE_ADMIN) { deleteImagesFromServer(eventImages); eventRepo.delete(toDelete); - achievementCalculation.calculateAchievement(user.getId(), - AchievementCategoryType.CREATE_EVENT, AchievementAction.DELETE); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_CREATE_EVENT, - modelMapper.map(user, UserVO.class)); } else { throw new BadRequestException(ErrorMessage.USER_HAS_NO_PERMISSION); } @@ -299,10 +288,6 @@ public void addAttender(Long eventId, String email) { User currentUser = modelMapper.map(restClient.findByEmail(email), User.class); checkAttenderToJoinTheEvent(event, currentUser); event.getAttenders().add(currentUser); - achievementCalculation.calculateAchievement(currentUser.getId(), - AchievementCategoryType.CREATE_EVENT, AchievementAction.ASSIGN); - ratingCalculation.ratingCalculation(RatingCalculationEnum.CREATE_EVENT, - modelMapper.map(currentUser, UserVO.class)); eventRepo.save(event); } diff --git a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java index 52a41f8d28..005d2cbdaa 100644 --- a/service/src/main/java/greencity/service/HabitAssignServiceImpl.java +++ b/service/src/main/java/greencity/service/HabitAssignServiceImpl.java @@ -37,8 +37,11 @@ import greencity.entity.User; import greencity.entity.UserShoppingListItem; import greencity.entity.localization.ShoppingListItemTranslation; -import greencity.enums.*; - +import greencity.enums.AchievementType; +import greencity.enums.HabitAssignStatus; +import greencity.enums.ShoppingListItemStatus; +import greencity.enums.RatingCalculationEnum; +import greencity.enums.AchievementCategoryType; import java.time.LocalDate; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; @@ -47,6 +50,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -74,6 +78,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; +import javax.servlet.http.HttpServletRequest; /** * Implementation of {@link HabitAssignService}. @@ -95,6 +100,7 @@ public class HabitAssignServiceImpl implements HabitAssignService { private final HabitStatusCalendarService habitStatusCalendarService; private final AchievementCalculation achievementCalculation; private final ModelMapper modelMapper; + private final HttpServletRequest httpServletRequest; private final UserService userService; private final RatingCalculation ratingCalculation; @@ -701,12 +707,10 @@ public HabitAssignDto enrollHabit(Long habitAssignId, Long userId, LocalDate dat HabitStatusCalendar habitCalendar = HabitStatusCalendar.builder() .enrollDate(date).habitAssign(habitAssign).build(); - updateHabitAssignAfterEnroll(habitAssign, habitCalendar); + updateHabitAssignAfterEnroll(habitAssign, habitCalendar, userId); UserVO userVO = userService.findById(userId); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.ASSIGN); - ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO); - + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DAYS_OF_HABIT_IN_PROGRESS, userVO)); return buildHabitAssignDto(habitAssign, language); } @@ -739,7 +743,7 @@ private void validateForEnroll(LocalDate date, HabitAssign habitAssign) { * @param habitAssign {@link HabitAssign} instance. */ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, - HabitStatusCalendar habitCalendar) { + HabitStatusCalendar habitCalendar, Long userId) { habitAssign.setWorkingDays(habitAssign.getWorkingDays() + 1); habitAssign.setLastEnrollmentDate(ZonedDateTime.now()); @@ -750,8 +754,14 @@ private void updateHabitAssignAfterEnroll(HabitAssign habitAssign, int habitStreak = countNewHabitStreak(habitAssign.getHabitStatusCalendars()); habitAssign.setHabitStreak(habitStreak); + CompletableFuture.runAsync(() -> achievementCalculation + .calculateAchievement(userId, AchievementType.COMPARISON, + AchievementCategoryType.HABIT_STREAK, habitStreak)); + if (isHabitAcquired(habitAssign)) { habitAssign.setStatus(HabitAssignStatus.ACQUIRED); + CompletableFuture.runAsync(() -> achievementCalculation + .calculateAchievement(userId, AchievementType.INCREMENT, AchievementCategoryType.HABIT_STREAK, 0)); } habitAssignRepo.save(habitAssign); } @@ -792,9 +802,8 @@ public HabitAssignDto unenrollHabit(Long habitAssignId, Long userId, LocalDate d deleteHabitStatusCalendar(date, habitAssign); updateHabitAssignAfterUnenroll(habitAssign); UserVO userVO = userService.findById(userId); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, userVO)); return modelMapper.map(habitAssign, HabitAssignDto.class); } @@ -983,10 +992,9 @@ public HabitAssignDto cancelHabitAssign(Long habitId, Long userId) { UserVO userVO = userService.findById(userId); for (int i = 0; i < habitAssignToCancel.getWorkingDays(); i++) { - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, - userVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, + userVO)); } habitAssignRepo.save(habitAssignToCancel); return buildHabitAssignDto(habitAssignToCancel, "en"); @@ -1008,10 +1016,9 @@ public void deleteHabitAssign(Long habitAssignId, Long userId) { UserVO userVO = userService.findById(userId); for (int i = 0; i < habitAssign.getWorkingDays(); i++) { - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, - userVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.HABIT, AchievementAction.DELETE); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_DAYS_OF_HABIT_IN_PROGRESS, + userVO)); } userShoppingListItemRepo.deleteShoppingListItemsByHabitAssignId(habitAssign.getId()); customShoppingListItemRepo.deleteCustomShoppingListItemsByHabitId(habitAssign.getHabit().getId()); diff --git a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java index 790b0f0a0d..9c7843467c 100644 --- a/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java +++ b/service/src/main/java/greencity/service/PlaceCommentServiceImpl.java @@ -1,8 +1,5 @@ package greencity.service; -import greencity.achievement.AchievementCalculation; -import greencity.enums.AchievementAction; -import greencity.enums.AchievementCategoryType; import greencity.enums.RatingCalculationEnum; import greencity.client.RestClient; import greencity.constant.ErrorMessage; @@ -20,6 +17,7 @@ import greencity.exception.exceptions.UserBlockedException; import greencity.repository.PlaceCommentRepo; import java.util.List; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import lombok.AllArgsConstructor; @@ -48,7 +46,6 @@ public class PlaceCommentServiceImpl implements PlaceCommentService { private ModelMapper modelMapper; private final greencity.rating.RatingCalculation ratingCalculation; private final HttpServletRequest httpServletRequest; - private AchievementCalculation achievementCalculation; /** * {@inheritDoc} @@ -89,10 +86,8 @@ public CommentReturnDto save(Long placeId, AddCommentDto addCommentDto, String e photo.setComment(comment); photo.setPlace(place); }); - ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.ASSIGN); - + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO)); return modelMapper.map(placeCommentRepo.save(comment), CommentReturnDto.class); } @@ -107,9 +102,8 @@ public void deleteById(Long id) { .orElseThrow(() -> new NotFoundException(ErrorMessage.COMMENT_NOT_FOUND_EXCEPTION))); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserVO userVO = restClient.findByEmail(authentication.getName()); - ratingCalculation.ratingCalculation(RatingCalculationEnum.UNDO_COMMENT_OR_REPLY, userVO); - achievementCalculation.calculateAchievement(userVO.getId(), - AchievementCategoryType.COMMENT_OR_REPLY, AchievementAction.DELETE); + CompletableFuture.runAsync( + () -> ratingCalculation.ratingCalculation(RatingCalculationEnum.DELETE_COMMENT_OR_REPLY, userVO)); } /** diff --git a/service/src/main/java/greencity/service/UserActionServiceImpl.java b/service/src/main/java/greencity/service/UserActionServiceImpl.java index 6844adcb64..f12d911e8d 100644 --- a/service/src/main/java/greencity/service/UserActionServiceImpl.java +++ b/service/src/main/java/greencity/service/UserActionServiceImpl.java @@ -1,17 +1,13 @@ package greencity.service; -import greencity.constant.ErrorMessage; import greencity.dto.useraction.UserActionVO; import greencity.entity.UserAction; -import greencity.repository.AchievementCategoryRepo; import greencity.repository.UserActionRepo; -import greencity.repository.UserRepo; import lombok.AllArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.NoSuchElementException; import java.util.Optional; @Service @@ -19,8 +15,6 @@ public class UserActionServiceImpl implements UserActionService { private UserActionRepo userActionRepo; private final ModelMapper modelMapper; - private final UserRepo userRepo; - private final AchievementCategoryRepo achievementCategoryRepo; /** * {@inheritDoc} @@ -48,16 +42,6 @@ public UserActionVO updateUserActions(UserActionVO userActionVO) { @Override public UserActionVO findUserActionByUserIdAndAchievementCategory(Long userId, Long categoryId) { UserAction userAction = userActionRepo.findByUserIdAndAchievementCategoryId(userId, categoryId); - if (userAction == null) { - userAction = UserAction.builder() - .user(userRepo.findById(userId) - .orElseThrow(() -> new NoSuchElementException(ErrorMessage.USER_NOT_FOUND_BY_ID + userId))) - .count(0) - .achievementCategory(achievementCategoryRepo.findById(categoryId).orElseThrow( - () -> new NoSuchElementException(ErrorMessage.ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID + categoryId))) - .build(); - userActionRepo.save(userAction); - } return userAction != null ? modelMapper.map(userAction, UserActionVO.class) : null; } diff --git a/service/src/main/java/greencity/service/UserServiceImpl.java b/service/src/main/java/greencity/service/UserServiceImpl.java index 4273791acf..9416176050 100644 --- a/service/src/main/java/greencity/service/UserServiceImpl.java +++ b/service/src/main/java/greencity/service/UserServiceImpl.java @@ -42,15 +42,6 @@ public class UserServiceImpl implements UserService { @Value("300000") private long timeAfterLastActivity; - /** - * {@inheritDoc} - */ - @Override - public void save(UserVO userVO) { - User user = modelMapper.map(userVO, User.class); - userRepo.save(user); - } - /** * {@inheritDoc} */ diff --git a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java index 5e73a2a001..afae38437d 100644 --- a/service/src/test/java/greencity/achievement/AchievementCalculationTest.java +++ b/service/src/test/java/greencity/achievement/AchievementCalculationTest.java @@ -3,34 +3,27 @@ import greencity.ModelUtils; import greencity.client.RestClient; import greencity.dto.achievement.AchievementVO; +import greencity.dto.achievement.UserVOAchievement; import greencity.dto.achievementcategory.AchievementCategoryVO; -import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; import greencity.entity.User; import greencity.entity.UserAchievement; -import greencity.enums.*; -import greencity.exception.exceptions.NotFoundException; -import greencity.rating.RatingCalculation; -import greencity.repository.AchievementCategoryRepo; -import greencity.repository.AchievementRepo; +import greencity.enums.AchievementCategoryType; +import greencity.enums.AchievementType; import greencity.repository.UserAchievementRepo; -import greencity.repository.UserRepo; import greencity.service.*; -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.EnumSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; -import greencity.entity.Achievement; import java.util.Collections; -import java.util.Optional; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class AchievementCalculationTest { @@ -46,140 +39,34 @@ class AchievementCalculationTest { private ModelMapper modelMapper; @Mock private UserAchievementRepo userAchievementRepo; - @Mock - private AchievementRepo achievementRepo; - @Mock - private UserRepo userRepo; - @Mock - private AchievementCategoryRepo achievementCategoryRepo; - @Mock - private RatingCalculationEnum ratingCalculationEnum; @InjectMocks private AchievementCalculation achievementCalculation; - @Mock - private UserService userService; - @Mock - private RatingCalculation ratingCalculation; - - @Test - void calculateAchievement_reasonNull() { - AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); - AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); - UserVO userVO = ModelUtils.getUserVO(); - UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); - User user = ModelUtils.getUser(); - Achievement achievement = ModelUtils.getAchievement(); - achievement.setTitle("bla bla"); - UserAchievement userAchievement = ModelUtils.getUserAchievement(); - user.setUserAchievements(Collections.singletonList(userAchievement)); - AchievementVO achievementVO = - new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), 1); - when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) - .thenReturn(achievementCategoryVO); - when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); - when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) - .thenReturn(Optional.of(achievement)); - when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); - when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); - when(achievementService.findByCategoryIdAndCondition(2L, 1)).thenReturn(achievementVO); - - assertThrows(NotFoundException.class, () -> achievementCalculation.calculateAchievement(1L, - AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN)); - } - - @Test - void calculateAchievement_UNDO_reasonNull() { - AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); - AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); - UserVO userVO = ModelUtils.getUserVO(); - UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); - User user = ModelUtils.getUser(); - Achievement achievement = ModelUtils.getAchievement(); - achievement.setTitle("Bla bla"); - UserAchievement userAchievement = ModelUtils.getUserAchievement(); - user.setUserAchievements(Collections.singletonList(userAchievement)); - AchievementVO achievementVO = - new AchievementVO(1L, "CREATED_5_NEWS___", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), - 1); - when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) - .thenReturn(achievementCategoryVO); - when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); - when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) - .thenReturn(Optional.of(achievement)); - when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); - when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); - when(achievementService.findByCategoryIdAndCondition(2L, -1)).thenReturn(achievementVO); - - assertThrows(NotFoundException.class, () -> achievementCalculation.calculateAchievement(1L, - AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE)); - } - - @Test - void calculateAchievement() { - AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); - AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); - UserVO userVO = ModelUtils.getUserVO(); - UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); - User user = ModelUtils.getUser(); - Achievement achievement = ModelUtils.getAchievement(); - UserAchievement userAchievement = ModelUtils.getUserAchievement(); - user.setUserAchievements(Collections.singletonList(userAchievement)); - AchievementVO achievementVO = - new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), 1); - when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) - .thenReturn(achievementCategoryVO); - when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); - when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) - .thenReturn(Optional.of(achievement)); - when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); - when(achievementCategoryService.findByName("ACHIEVEMENT")).thenReturn(achievementCategoryVO); - when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); - when(achievementService.findByCategoryIdAndCondition(2L, 1)).thenReturn(achievementVO); - achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); - assertEquals(2, userActionVO.getCount()); - } - - @Test - void calculateAchievement_UNDO() { - AchievementCategoryVO achievementCategoryVO = new AchievementCategoryVO(1L, "ACHIEVEMENT"); - AchievementCategoryVO achievementCategoryVO2 = new AchievementCategoryVO(2L, "CREATE_NEWS"); - UserVO userVO = ModelUtils.getUserVO(); - UserActionVO userActionVO = new UserActionVO(1L, userVO, achievementCategoryVO, 0); - User user = ModelUtils.getUser(); - Achievement achievement = ModelUtils.getAchievement(); - UserAchievement userAchievement = ModelUtils.getUserAchievement(); - user.setUserAchievements(Collections.singletonList(userAchievement)); - AchievementVO achievementVO = - new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), 1); - when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) - .thenReturn(achievementCategoryVO); - when(userActionService.findUserActionByUserIdAndAchievementCategory(any(), any())).thenReturn(userActionVO); - when(achievementRepo.findByAchievementCategoryIdAndCondition(anyLong(), any())) - .thenReturn(Optional.of(achievement)); - when(userRepo.findById(anyLong())).thenReturn(Optional.of(user)); - when(achievementCategoryService.findByName("ACHIEVEMENT")).thenReturn(achievementCategoryVO); - when(achievementCategoryService.findByName("CREATE_NEWS")).thenReturn(achievementCategoryVO2); - when(achievementService.findByCategoryIdAndCondition(2L, -1)).thenReturn(achievementVO); - achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.DELETE); - assertEquals(-2, userActionVO.getCount()); - } - @Test - void calculateAchievement_achievemmentNull() { + @ParameterizedTest(name = "{index} => type=''{0}''") + @EnumSource(AchievementType.class) + void calculateAchievement(AchievementType type) { AchievementCategoryVO achievementCategoryVO = ModelUtils.getAchievementCategoryVO(); AchievementCategoryVO achievementCategoryVO2 = ModelUtils.getAchievementCategoryVO(); achievementCategoryVO2.setId(2L); UserActionVO userActionVO = ModelUtils.getUserActionVO(); - int count = userActionVO.getCount(); UserActionVO userActionVO2 = ModelUtils.getUserActionVO(); userActionVO2.setId(2L); + UserVOAchievement userVOAchievement = ModelUtils.getUserVOAchievement(); User user = ModelUtils.getUser(); + AchievementVO achievementVO = ModelUtils.getAchievementVO(); UserAchievement userAchievement = ModelUtils.getUserAchievement(); user.setUserAchievements(Collections.singletonList(userAchievement)); - when(achievementCategoryService.findByName(AchievementCategoryType.CREATE_NEWS.name())) + when(achievementCategoryService.findByName(AchievementCategoryType.ECO_NEWS.getCategory())) .thenReturn(achievementCategoryVO); when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)).thenReturn(userActionVO); - achievementCalculation.calculateAchievement(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); - assertEquals(count + 1, userActionVO.getCount()); + when(userActionService.updateUserActions(userActionVO)).thenReturn(userActionVO); + when(restClient.findUserForAchievement(1L)).thenReturn(userVOAchievement); + when(achievementService.findByCategoryIdAndCondition(1L, 1)).thenReturn(achievementVO); + when(modelMapper.map(userVOAchievement, User.class)).thenReturn(user); + when(userAchievementRepo.save(userAchievement)).thenReturn(userAchievement); + when(achievementCategoryService.findByName("Achievements")).thenReturn(achievementCategoryVO2); + when(userActionService.findUserActionByUserIdAndAchievementCategory(1L, 2L)).thenReturn(userActionVO2); + achievementCalculation.calculateAchievement(1L, type, AchievementCategoryType.ECO_NEWS, 1); + verify(userAchievementRepo).save(userAchievement); } } diff --git a/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java b/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java index bc9a2a08ce..2fd1399a44 100644 --- a/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java +++ b/service/src/test/java/greencity/filters/RatingStatisticsSpecificationTest.java @@ -1,8 +1,6 @@ package greencity.filters; import static org.mockito.Mockito.*; - -import greencity.achievement.AchievementCalculation; import greencity.enums.RatingCalculationEnum; import greencity.dto.ratingstatistics.RatingStatisticsViewDto; import greencity.entity.RatingStatistics; @@ -14,8 +12,6 @@ import java.util.List; import javax.persistence.criteria.*; import javax.persistence.metamodel.SingularAttribute; - -import greencity.rating.RatingCalculation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -82,15 +78,11 @@ class RatingStatisticsSpecificationTest { private RatingStatisticsSpecification ratingStatisticsSpecification; private List criteriaList; - @Mock - RatingCalculation ratingCalculation; - @Mock - AchievementCalculation achievementCalculation; @BeforeEach void setUp() { RatingStatisticsViewDto ratingStatisticsViewDto = - new RatingStatisticsViewDto("2", "UNDO_COMMENT_OR_REPLY", "1", "", "2021-01-12", "2021-01-13", "", "50"); + new RatingStatisticsViewDto("2", "UNLIKE_COMMENT_OR_REPLY", "1", "", "2021-01-12", "2021-01-13", "", "50"); criteriaList = new ArrayList<>(); criteriaList.add( @@ -147,7 +139,7 @@ void toPredicate() { when(criteriaBuilderMock.disjunction()).thenReturn(predicateMock); - when(criteriaBuilderMock.equal(pathRatingStatisticsEnumMock, RatingCalculationEnum.UNDO_COMMENT_OR_REPLY)) + when(criteriaBuilderMock.equal(pathRatingStatisticsEnumMock, RatingCalculationEnum.UNLIKE_COMMENT_OR_REPLY)) .thenReturn(andEventNamePredicate); when(criteriaBuilderMock.or(predicateMock, andEventNamePredicate)).thenReturn(andEventNamePredicate); diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index 2c23fbcaef..defd7181ac 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -13,7 +13,8 @@ import greencity.entity.AchievementCategory; import greencity.enums.AchievementCategoryType; -import greencity.enums.AchievementAction; + +import greencity.enums.AchievementType; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotUpdatedException; import greencity.repository.AchievementRepo; @@ -198,10 +199,11 @@ void findByCategoryIdAndCondition() { @Test void calculateAchievement() { - achievementService.calculateAchievements(1L, AchievementCategoryType.CREATE_NEWS, AchievementAction.ASSIGN); + achievementService.calculateAchievements(1L, AchievementType.INCREMENT, AchievementCategoryType.ECO_NEWS, 1); verify(achievementCalculation).calculateAchievement( anyLong(), + any(AchievementType.class), any(AchievementCategoryType.class), - eq(AchievementAction.ASSIGN)); + anyInt()); } } diff --git a/service/src/test/java/greencity/service/UserActionServiceImplTest.java b/service/src/test/java/greencity/service/UserActionServiceImplTest.java index cba95c13d1..e51dc52a9e 100644 --- a/service/src/test/java/greencity/service/UserActionServiceImplTest.java +++ b/service/src/test/java/greencity/service/UserActionServiceImplTest.java @@ -1,15 +1,9 @@ package greencity.service; import greencity.ModelUtils; -import greencity.dto.user.UserVO; import greencity.dto.useraction.UserActionVO; -import greencity.entity.AchievementCategory; import greencity.entity.UserAction; -import greencity.exception.exceptions.BadCategoryRequestException; -import greencity.exception.exceptions.NotFoundException; -import greencity.repository.AchievementCategoryRepo; import greencity.repository.UserActionRepo; -import greencity.repository.UserRepo; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -17,12 +11,10 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; -import java.util.Collections; -import java.util.NoSuchElementException; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class UserActionServiceImplTest { @@ -31,11 +23,7 @@ class UserActionServiceImplTest { @Mock private UserActionRepo userActionRepo; @Mock - private UserRepo userRepo; - @Mock private ModelMapper modelMapper; - @Mock - private AchievementCategoryRepo achievementCategoryRepo; @Test void updateUserActions() { @@ -63,37 +51,6 @@ void findUserActionByUserId() { assertEquals(userActionVO, userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)); } - @Test - void findUserActionByUserId_NoSuchCategory() { - when(userActionRepo.findByUserIdAndAchievementCategoryId(1L, 1L)).thenReturn(null); - when(userRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getUser())); - assertThrows(NoSuchElementException.class, - () -> userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L)); - } - - @Test - void findUserActionByUserIdNull() { - UserActionVO userActionVO = ModelUtils.getUserActionVO(); - when(userActionRepo.findByUserIdAndAchievementCategoryId(1L, 1L)).thenReturn(null); - when(userRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getUser())); - when(achievementCategoryRepo.findById(anyLong())).thenReturn(Optional.of(ModelUtils.getAchievementCategory())); - UserAction userAction = UserAction.builder() - .user(ModelUtils.getUser()) - .achievementCategory(AchievementCategory.builder() - .id(1L) - .name("Name") - .achievementList(Collections.emptyList()) - .build()) - .count(0) - .build(); - - when(modelMapper.map(userAction, UserActionVO.class)).thenReturn(userActionVO); - UserActionVO resultUserActionVO = userActionService.findUserActionByUserIdAndAchievementCategory(1L, 1L); - assertEquals(userActionVO, resultUserActionVO); - verify(userActionRepo, times(1)).save(any()); - - } - @Test void save() { UserAction userAction = ModelUtils.getUserAction(); diff --git a/service/src/test/java/greencity/service/UserServiceImplTest.java b/service/src/test/java/greencity/service/UserServiceImplTest.java index 101b65c721..dc692eff27 100644 --- a/service/src/test/java/greencity/service/UserServiceImplTest.java +++ b/service/src/test/java/greencity/service/UserServiceImplTest.java @@ -77,13 +77,6 @@ void findByIdTest() { verify(userRepo, times(1)).findById(id); } - @Test - void saveTest() { - userService.save(userVO); - verify(modelMapper).map(userVO, User.class); - verify(userRepo, times(1)).save(any()); - } - @Test void checkIfTheUserIsOnlineExceptionTest() { assertThrows(WrongIdException.class, () -> userService.checkIfTheUserIsOnline(null)); From ab749fd0a63217838bcbc10b5a5ad3658a13c853 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 26 Sep 2023 19:41:38 +0300 Subject: [PATCH 45/51] Fixed modelUtils --- core/src/test/java/greencity/ModelUtils.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/src/test/java/greencity/ModelUtils.java b/core/src/test/java/greencity/ModelUtils.java index 88cd35b084..5b4898b804 100644 --- a/core/src/test/java/greencity/ModelUtils.java +++ b/core/src/test/java/greencity/ModelUtils.java @@ -585,11 +585,13 @@ public static AchievementCategoryDto getAchievementCategoryDto() { } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto("Test", "Test", "Test", getAchievementCategoryDto(), 1); + return new AchievementPostDto("ACQUIRED_HABIT_14_DAYS", "Набуття звички протягом 14 днів", + "Acquired habit 14 days", getAchievementCategoryDto(), 1); } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, "Test", "Test", "Test", + return new AchievementVO(1L, "ACQUIRED_HABIT_14_DAYS", "Набуття звички протягом 14 днів", + "Acquired habit 14 days", new AchievementCategoryVO(1L, "name"), 1); } From 97adca40bf5359f45887c3ddb8827c72a5900784 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 26 Sep 2023 19:53:09 +0300 Subject: [PATCH 46/51] Fixed code --- service/src/test/java/greencity/ModelUtils.java | 3 ++- .../test/java/greencity/rating/RatingCalculationTest.java | 6 +----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 8843e59963..8d7f46a136 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1393,7 +1393,8 @@ public static AchievementVO getAchievementVO() { } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto("Test", "Test", "Test", getAchievementCategoryDto(), 1); + return new AchievementPostDto("CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", getAchievementCategoryDto(), + 1); } public static AchievementCategoryDto getAchievementCategoryDto() { diff --git a/service/src/test/java/greencity/rating/RatingCalculationTest.java b/service/src/test/java/greencity/rating/RatingCalculationTest.java index 9453677cdb..45c87d3d2c 100644 --- a/service/src/test/java/greencity/rating/RatingCalculationTest.java +++ b/service/src/test/java/greencity/rating/RatingCalculationTest.java @@ -9,8 +9,6 @@ import greencity.entity.User; import greencity.service.RatingStatisticsService; import java.time.ZonedDateTime; - -import greencity.service.UserService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -32,8 +30,6 @@ class RatingCalculationTest { private ModelMapper modelMapper; @Mock private HttpServletRequest httpServletRequest; - @Mock - private UserService userService; @InjectMocks private RatingCalculation ratingCalculation; @@ -64,9 +60,9 @@ void ratingCalculation() { .pointsChanged(rating.getRatingPoints()) .build(); when(modelMapper.map(userVO, User.class)).thenReturn(user); + doNothing().when(restClient).save(userVO, null); when(modelMapper.map(ratingStatistics, RatingStatisticsVO.class)).thenReturn(ratingStatisticsVO); when(ratingStatisticsService.save(ratingStatisticsVO)).thenReturn(ratingStatisticsVO); - ratingCalculation.ratingCalculation(RatingCalculationEnum.COMMENT_OR_REPLY, userVO); verify(ratingStatisticsService).save(ratingStatisticsVO); From 9cd629713e14f8f4e18b5e89f5819cf154829208 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 26 Sep 2023 20:18:38 +0300 Subject: [PATCH 47/51] Deleted unused files --- .../db/changelog/db.changelog-master.xml | 2 - .../ch-add-value-achievements-Spodaryk.xml | 12 --- ...values-achievement_categories-Spodaryk.xml | 53 ---------- .../functions/insert-values-achievements.sql | 96 ------------------- 4 files changed, 163 deletions(-) delete mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml delete mode 100644 dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml delete mode 100644 dao/src/main/resources/db/functions/insert-values-achievements.sql diff --git a/dao/src/main/resources/db/changelog/db.changelog-master.xml b/dao/src/main/resources/db/changelog/db.changelog-master.xml index 25fcc3e888..c97af90b77 100644 --- a/dao/src/main/resources/db/changelog/db.changelog-master.xml +++ b/dao/src/main/resources/db/changelog/db.changelog-master.xml @@ -172,9 +172,7 @@ - - diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml deleted file mode 100644 index ac309d4688..0000000000 --- a/dao/src/main/resources/db/changelog/logs/ch-add-value-achievements-Spodaryk.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - diff --git a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml b/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml deleted file mode 100644 index c724ae541c..0000000000 --- a/dao/src/main/resources/db/changelog/logs/ch-add-values-achievement_categories-Spodaryk.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dao/src/main/resources/db/functions/insert-values-achievements.sql b/dao/src/main/resources/db/functions/insert-values-achievements.sql deleted file mode 100644 index d7f87ff7b3..0000000000 --- a/dao/src/main/resources/db/functions/insert-values-achievements.sql +++ /dev/null @@ -1,96 +0,0 @@ -DO -$$ -DECLARE -habit_id INTEGER; -create_news_id INTEGER; -comment_or_reply_id INTEGER; -like_comment_or_reply_id INTEGER; -share_news_id INTEGER; -achievement_id INTEGER; -create_event_id INTEGER; -join_event_id INTEGER; - -BEGIN -SELECT id INTO habit_id FROM achievement_categories WHERE name = 'HABIT'; -SELECT id INTO create_news_id FROM achievement_categories WHERE name = 'CREATE_NEWS'; -SELECT id INTO comment_or_reply_id FROM achievement_categories WHERE name = 'COMMENT_OR_REPLY'; -SELECT id INTO like_comment_or_reply_id FROM achievement_categories WHERE name = 'LIKE_COMMENT_OR_REPLY'; -SELECT id INTO share_news_id FROM achievement_categories WHERE name = 'SHARE_NEWS'; -SELECT id INTO achievement_id FROM achievement_categories WHERE name = 'ACHIEVEMENT'; -SELECT id INTO create_event_id FROM achievement_categories WHERE name = 'CREATE_EVENT'; -SELECT id INTO join_event_id FROM achievement_categories WHERE name = 'JOIN_EVENT'; -DELETE -FROM achievements; - -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('ACQUIRED_HABIT_14_DAYS', 'Набуття звички протягом 14 днів', 'Acquired habit 14 days', 20, habit_id, 14), - ('ACQUIRED_HABIT_21_DAYS', 'Набуття звички протягом 21 днів', 'Acquired habit 21 days', 30, habit_id, 21), - ('ACQUIRED_HABIT_30_DAYS', 'Набуття звички протягом 30 днів', 'Acquired habit 30 days', 40, habit_id, 30); - -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('CREATED_1_NEWS', 'Створено перший новину', 'Created first news', 10, create_news_id, 1), - ('CREATED_5_NEWS', 'Створено 5 новин', 'Created 5 news', 25, create_news_id, 5), - ('CREATED_10_NEWS', 'Створено 10 новин', 'Created 10 news', 50, create_news_id, 10), - ('CREATED_25_NEWS', 'Створено 25 новин', 'Created 25 news', 150, create_news_id, 25), - ('CREATED_50_NEWS', 'Створено 50 новин', 'Created 50 news', 250, create_news_id, 50), - ('CREATED_100_NEWS', 'Створено 100 новин', 'Created 100 news', 500, create_news_id, 100); - -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('COMMENT_OR_REPLY_1_TIMES', 'Коментування або відповідь перший раз', 'Comment or reply first time', 5, - comment_or_reply_id, 1), - ('COMMENT_OR_REPLY_5_TIMES', 'Коментування або відповідь 5 разів', 'Comment or reply 5 times', 10, - comment_or_reply_id, 5), - ('COMMENT_OR_REPLY_10_TIMES', 'Коментування або відповідь 10 разів', 'Comment or reply 10 times', 15, - comment_or_reply_id, 10), - ('COMMENT_OR_REPLY_25_TIMES', 'Коментування або відповідь 25 разів', 'Comment or reply 25 times', 25, - comment_or_reply_id, 25), - ('COMMENT_OR_REPLY_50_TIMES', 'Коментування або відповідь 50 разів', 'Comment or reply 50 times', 50, - comment_or_reply_id, 50), - ('COMMENT_OR_REPLY_100_TIMES', 'Коментування або відповідь 100 разів', 'Comment or reply 100 times', 100, - comment_or_reply_id, 100); - -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('LIKE_COMMENT_OR_REPLY_1_TIMES', 'Лайкнуто коментар або відповідь перший раз', 'Liked a comment or reply first time', 1, - like_comment_or_reply_id, 1), - ('LIKE_COMMENT_OR_REPLY_5_TIMES', 'Лайкнуто коментарі або відповіді 5 разів', - 'Liked comments or replies 5 times', 5, like_comment_or_reply_id, 5), - ('LIKE_COMMENT_OR_REPLY_10_TIMES', 'Лайкнуто коментарі або відповіді 10 разів', - 'Liked comments or replies 10 times', 10, like_comment_or_reply_id, 10), - ('LIKE_COMMENT_OR_REPLY_25_TIMES', 'Лайкнуто коментарі або відповіді 25 разів', - 'Liked comments or replies 25 times', 25, like_comment_or_reply_id, 25), - ('LIKE_COMMENT_OR_REPLY_50_TIMES', 'Лайкнуто коментарі або відповіді 50 разів', - 'Liked comments or replies 50 times', 50, like_comment_or_reply_id, 50), - ('LIKE_COMMENT_OR_REPLY_100_TIMES', 'Лайкнуто коментарі або відповіді 100 разів', - 'Liked comments or replies 100 times', 50, like_comment_or_reply_id, 100); - -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('SHARE_NEWS_1_TIMES', 'Поширено новину перший раз', 'Shared news first time', 10, share_news_id, 1), - ('SHARE_NEWS_5_TIMES', 'Поширено новини 5 разів', 'Shared news 5 times', 25, share_news_id, 5), - ('SHARE_NEWS_10_TIMES', 'Поширено новини 10 разів', 'Shared news 10 times', 50, share_news_id, 10), - ('SHARE_NEWS_25_TIMES', 'Поширено новини 25 разів', 'Shared news 25 times', 150, share_news_id, 25), - ('SHARE_NEWS_50_TIMES', 'Поширено новини 50 разів', 'Shared news 50 times', 250, share_news_id, 50), - ('SHARE_NEWS_100_TIMES', 'Поширено новини 100 разів', 'Shared news 100 times', 500, share_news_id, 100); - -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('FIRST_5_ACHIEVEMENTS', 'Перші 5 досягнень', 'First 5 Achievements', 10, achievement_id, 5), - ('FIRST_10_ACHIEVEMENTS', 'Перші 10 досягнень', 'First 10 Achievements', 25, achievement_id, 10), - ('FIRST_25_ACHIEVEMENTS', 'Перші 25 досягнень', 'First 25 Achievements', 50, achievement_id, 25), - ('FIRST_50_ACHIEVEMENTS', 'Перші 50 досягнень', 'First 50 Achievements', 100, achievement_id, 50), - ('FIRST_100_ACHIEVEMENTS', 'Перші 100 досягнень', 'First 100 Achievements', 200, achievement_id, 100); -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('CREATE_EVENT_1_TIMES', 'Створено подію 1 раз', 'Created event 1 time', 10, create_event_id, 1), - ('CREATE_EVENT_5_TIMES', 'Створено події 5 разів', 'Created events 5 times', 25, create_event_id, 5), - ('CREATE_EVENT_10_TIMES', 'Створено події 10 разів', 'Created events 10 times', 50, create_event_id, 10), - ('CREATE_EVENT_25_TIMES', 'Створено події 25 разів', 'Created events 25 times', 150, create_event_id, 25), - ('CREATE_EVENT_50_TIMES', 'Створено події 50 разів', 'Created events 50 times', 250, create_event_id, 50), - ('CREATE_EVENT_100_TIMES', 'Створено події 100 разів', 'Created events 100 times', 500, create_event_id, 100); - -INSERT INTO achievements(title, name, name_eng, score, achievement_category_id, condition) -VALUES ('JOIN_EVENT_1_TIMES', 'Приєднано до події 1 раз', 'Joined event 1 time', 5, join_event_id, 1), - ('JOIN_EVENT_5_TIMES', 'Приєднано до подій 5 разів', 'Joined events 5 times', 10, join_event_id, 5), - ('JOIN_EVENT_10_TIMES', 'Приєднано до подій 10 разів', 'Joined events 10 times', 25, join_event_id, 10), - ('JOIN_EVENT_25_TIMES', 'Приєднано до подій 25 разів', 'Joined events 25 times', 50, join_event_id, 25), - ('JOIN_EVENT_50_TIMES', 'Приєднано до подій 50 разів', 'Joined events 50 times', 100, join_event_id, 50), - ('JOIN_EVENT_100_TIMES', 'Приєднано до подій 100 разів', 'Joined events 100 times', 200, join_event_id, 100); - -END $$; From a03c73595afa28df05b58571ab36eb19dd90decb Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Wed, 27 Sep 2023 09:46:46 +0300 Subject: [PATCH 48/51] Fixed codesmell --- .../main/java/greencity/achievement/AchievementCalculation.java | 1 - 1 file changed, 1 deletion(-) diff --git a/service/src/main/java/greencity/achievement/AchievementCalculation.java b/service/src/main/java/greencity/achievement/AchievementCalculation.java index 7c1fd1d1df..bf05345b6a 100644 --- a/service/src/main/java/greencity/achievement/AchievementCalculation.java +++ b/service/src/main/java/greencity/achievement/AchievementCalculation.java @@ -19,7 +19,6 @@ import java.util.Optional; -import static greencity.enums.AchievementStatus.ACTIVE; import static greencity.enums.AchievementType.INCREMENT; @Component From 6acb8cf984779a6f521e1aa3dc64d736a03ef348 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 3 Oct 2023 09:51:22 +0300 Subject: [PATCH 49/51] Fixed codesmell --- .../src/main/java/greencity/constant/ErrorMessage.java | 4 ---- service/src/test/java/greencity/ModelUtils.java | 1 - 2 files changed, 5 deletions(-) diff --git a/service-api/src/main/java/greencity/constant/ErrorMessage.java b/service-api/src/main/java/greencity/constant/ErrorMessage.java index 43673125ae..6bcb557eb5 100644 --- a/service-api/src/main/java/greencity/constant/ErrorMessage.java +++ b/service-api/src/main/java/greencity/constant/ErrorMessage.java @@ -1,8 +1,6 @@ package greencity.constant; public final class ErrorMessage { - public static final String RATING_CALCULATION_ENUM_NOT_FOUND_BY_NAME = - "RatingCalculationEnum with such name does not exist: "; public static final String CUSTOM_SHOPPING_LIST_ITEM_NOT_FOUND_BY_ID = "Custom shopping list item with such id does not exist."; public static final String DUPLICATED_CUSTOM_SHOPPING_LIST_ITEM = "CustomShoppingListItems should be unique"; @@ -160,8 +158,6 @@ public final class ErrorMessage { public static final String TOKEN_FOR_RESTORE_IS_INVALID = "Token is null or it doesn't exist."; public static final String ACHIEVEMENT_NOT_DELETED = "Achievement not deleted "; public static final String ACHIEVEMENT_NOT_FOUND_BY_ID = "The achievement does not exist by this id: "; - public static final String ACHIEVEMENT_CATEGORY_NOT_FOUND_BY_ID = - "The achievement category does not exist by this id: "; public static final String PAGE_INDEX_IS_MORE_THAN_TOTAL_PAGES = "Page index is more than total pages: "; public static final String MULTIPART_FILE_BAD_REQUEST = "Can`t convert To Multipart Image. Bad inputed image string : "; diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 05708cb0da..2e8469caed 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -443,7 +443,6 @@ public static UserVO getUserVOWithData() { .userAchievements(List.of( UserAchievementVO.builder() .id(47L) - .user(UserVO.builder() .id(13L) .build()) From cca75092aae2309089438263278fe3c6ce18b66a Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 3 Oct 2023 12:06:32 +0300 Subject: [PATCH 50/51] Added verify and removed blank lines --- service/src/test/java/greencity/ModelUtils.java | 16 ++++++---------- .../service/AchievementServiceImplTest.java | 6 ------ .../service/EcoNewsServiceImplTest.java | 4 +++- .../service/HabitAssignServiceImplTest.java | 3 +++ 4 files changed, 12 insertions(+), 17 deletions(-) diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 2e8469caed..130bdfaa5a 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -9,7 +9,6 @@ import greencity.dto.PageableAdvancedDto; import greencity.dto.achievement.AchievementManagementDto; import greencity.dto.achievement.AchievementPostDto; - import greencity.dto.achievement.AchievementVO; import greencity.dto.achievement.UserAchievementVO; import greencity.dto.achievement.UserVOAchievement; @@ -162,7 +161,6 @@ import greencity.entity.event.EventComment; import greencity.entity.event.EventDateLocation; import greencity.entity.event.EventGrade; - import greencity.entity.localization.AdviceTranslation; import greencity.entity.localization.ShoppingListItemTranslation; import greencity.entity.localization.TagTranslation; @@ -178,7 +176,6 @@ import greencity.enums.UserStatus; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; - import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -452,7 +449,6 @@ public static UserVO getUserVOWithData() { .build(), UserAchievementVO.builder() .id(39L) - .user(UserVO.builder() .id(13L) .build()) @@ -1378,22 +1374,24 @@ public static AdvicePostDto getAdvicePostDto() { public static Achievement getAchievement() { return new Achievement(1L, - "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", + "ACQUIRED_HABIT_14_DAYS", "Набуття звички протягом 14 днів", "Acquired habit 14 days", Collections.emptyList(), new AchievementCategory(), 1); } public static AchievementCategory getAchievementCategory() { - return new AchievementCategory(1L, "Name", Collections.emptyList()); + return new AchievementCategory(1L, "HABIT", Collections.emptyList()); } public static AchievementVO getAchievementVO() { - return new AchievementVO(1L, "CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", new AchievementCategoryVO(), + return new AchievementVO(1L, "ACQUIRED_HABIT_14_DAYS", "Набуття звички протягом 14 днів", + "Acquired habit 14 days", new AchievementCategoryVO(), 1); } public static AchievementPostDto getAchievementPostDto() { - return new AchievementPostDto("CREATED_5_NEWS", "CREATED_5_NEWS", "CREATED_5_NEWS", getAchievementCategoryDto(), + return new AchievementPostDto("ACQUIRED_HABIT_14_DAYS", "Набуття звички протягом 14 днів", + "Acquired habit 14 days", getAchievementCategoryDto(), 1); } @@ -1702,7 +1700,6 @@ public static UserVO createUserVO2() { .build(), UserAchievementVO.builder() .id(39L) - .user(UserVO.builder() .id(1L) .build()) @@ -1770,7 +1767,6 @@ public static UserVO createUserVO2() { .userAchievements(List.of( UserAchievementVO.builder() .id(47L) - .user(UserVO.builder() .id(1L) .build()) diff --git a/service/src/test/java/greencity/service/AchievementServiceImplTest.java b/service/src/test/java/greencity/service/AchievementServiceImplTest.java index defd7181ac..15791af4a7 100644 --- a/service/src/test/java/greencity/service/AchievementServiceImplTest.java +++ b/service/src/test/java/greencity/service/AchievementServiceImplTest.java @@ -11,22 +11,16 @@ import greencity.dto.useraction.UserActionVO; import greencity.entity.Achievement; import greencity.entity.AchievementCategory; - import greencity.enums.AchievementCategoryType; - import greencity.enums.AchievementType; import greencity.exception.exceptions.NotDeletedException; import greencity.exception.exceptions.NotUpdatedException; import greencity.repository.AchievementRepo; - import java.util.*; - import greencity.repository.UserAchievementRepo; import greencity.repository.UserRepo; import org.junit.jupiter.api.Assertions; - import static org.junit.jupiter.api.Assertions.*; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; diff --git a/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java b/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java index 7c37939184..41a1079b5b 100644 --- a/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java +++ b/service/src/test/java/greencity/service/EcoNewsServiceImplTest.java @@ -13,6 +13,7 @@ import greencity.dto.PageableDto; import greencity.dto.econews.*; import greencity.dto.econewscomment.EcoNewsCommentVO; +import greencity.dto.habit.HabitDto; import greencity.dto.language.LanguageDTO; import greencity.dto.search.SearchNewsDto; import greencity.dto.tag.TagVO; @@ -140,6 +141,7 @@ void saveWithExistedImage() throws IOException { AddEcoNewsDtoResponse actual = ecoNewsService.save(addEcoNewsDtoRequest, image, TestConst.EMAIL); assertEquals(addEcoNewsDtoResponse, actual); + verify(modelMapper).map(ModelUtils.getUserVO(), User.class); } @Test @@ -180,7 +182,6 @@ void saveEcoNews() { when(tagService.findTagsByNamesAndType(anyList(), eq(TagType.ECO_NEWS))).thenReturn(tagVOList); when(ecoNewsRepo.save(any(EcoNews.class))).thenReturn(ecoNews); when(modelMapper.map(ecoNews, EcoNewsGenericDto.class)).thenReturn(ecoNewsGenericDto); - when(modelMapper.map(tagVOList, new TypeToken>() { }.getType())).thenReturn(tags); @@ -188,6 +189,7 @@ void saveEcoNews() { EcoNewsGenericDto actual = ecoNewsService.saveEcoNews(addEcoNewsDtoRequest, image, TestConst.EMAIL); assertEquals(ecoNewsGenericDto, actual); + verify(userService).findByEmail(anyString()); } @Test diff --git a/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java b/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java index 08f535c9aa..5be52f7e47 100644 --- a/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java +++ b/service/src/test/java/greencity/service/HabitAssignServiceImplTest.java @@ -482,6 +482,7 @@ void unenrollHabit() { verify(habitStatusCalendarRepo).findHabitStatusCalendarByEnrollDateAndHabitAssign(date, habitAssign); verify(habitStatusCalendarRepo).delete(habitStatusCalendar); verify(habitAssignRepo).save(habitAssign); + verify(userService).findById(any()); } @Test @@ -570,6 +571,7 @@ void deleteHabitAssign() { verify(userShoppingListItemRepo).deleteShoppingListItemsByHabitAssignId(habitAssignId); verify(customShoppingListItemRepo).deleteCustomShoppingListItemsByHabitId(habitId); verify(habitAssignRepo).delete(habitAssign); + verify(userService).findById(any()); } @Test @@ -896,6 +898,7 @@ void enrollHabit() { assertEquals(1, habitAssign.getWorkingDays()); assertEquals(habitAssignDto, actualDto); + verify(userService).findById(any()); verify(habitAssignRepo).findById(habitAssignId); verify(modelMapper).map(habitAssign, HabitAssignVO.class); verify(habitStatusCalendarService).findHabitStatusCalendarByEnrollDateAndHabitAssign(localDate, habitAssignVO); From 78a9f098b327b59677c8b14415f40653f72738b5 Mon Sep 17 00:00:00 2001 From: ospodaryk Date: Tue, 3 Oct 2023 12:10:01 +0300 Subject: [PATCH 51/51] Removed blank lines --- service/src/test/java/greencity/ModelUtils.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/service/src/test/java/greencity/ModelUtils.java b/service/src/test/java/greencity/ModelUtils.java index 130bdfaa5a..f3e520b425 100644 --- a/service/src/test/java/greencity/ModelUtils.java +++ b/service/src/test/java/greencity/ModelUtils.java @@ -1690,7 +1690,6 @@ public static UserVO createUserVO2() { .userAchievements(List.of( UserAchievementVO.builder() .id(47L) - .user(UserVO.builder() .id(1L) .build()) @@ -1776,7 +1775,6 @@ public static UserVO createUserVO2() { .build(), UserAchievementVO.builder() .id(39L) - .user(UserVO.builder() .id(1L) .build())