diff --git a/.gitignore b/.gitignore index f2d67c3..cfea594 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/**/target/ !**/src/test/**/target/ +secrets ### STS ### .apt_generated diff --git a/Dockerfile b/Dockerfile index dcc4853..c2f6a33 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,9 @@ -FROM tomcat:10.1.11 +FROM maven:3.9.7-eclipse-temurin-17 AS build +COPY src /home/app/src +COPY pom.xml /home/app +RUN mvn -f /home/app/pom.xml clean package -COPY ./target/RepCounterBot.war /usr/local/tomcat/webapps-javaee/ROOT.war - -EXPOSE 8080 - -CMD ["catalina.sh", "run"] \ No newline at end of file +FROM openjdk:17-jdk-alpine +LABEL maintainer="MykhailoTiutiun " +COPY --from=build /home/app/target/RepCounterBot.jar RepCounterBot.jar +ENTRYPOINT ["java", "-jar", "/RepCounterBot.jar"] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 84bcdcc..7d8534c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,12 +1,16 @@ version: "3.3" services: - rep-counter-bot: - container_name: rep-counter-bot - image: rep-counter-bot + repcounterbot: + container_name: repcounterbot + build: + dockerfile: Dockerfile ports: - "8080:8080" environment: - DATASOURCE_URI: "mongodb+srv://repcounterbot-app:rgEthTOPub2oDoJG@repcounterbotcluster.at0fumi.mongodb.net/?retryWrites=true&w=majority&appName=RepCounterBotCluster" + DATASOURCE_URL: "" + DATASOURCE_USER: "" + DATASOURCE_PASSWORD: "" + BOT_TOKEN: "" restart: unless-stopped deploy: resources: @@ -14,8 +18,27 @@ services: cpus: '1' memory: 300M networks: - - repcounterbot + - local + + postgres: + container_name: postgres + image: postgres + restart: always + shm_size: 128mb + ports: + - 5432:5432 + environment: + POSTGRES_DB: repcounterbot + POSTGRES_USER: "" + POSTGRES_PASSWORD: "" + volumes: + - repcounterbot-db:/var/lib/postgresql/data + networks: + - local networks: - repcounterbot: + local: driver: bridge + +volumes: + repcounterbot-db: diff --git a/pom.xml b/pom.xml index e204298..34f07d2 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ com.mykhailotiutiun RepCounterBot 1.0.1 - war + jar RepCounterBot RepCounterBot @@ -20,7 +20,11 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-jdbc + + + org.postgresql + postgresql org.springframework.boot @@ -75,9 +79,14 @@ org.apache.maven.plugins maven-surefire-plugin - - true - + 2.22.0 + + + org.apache.maven.surefire + surefire-junit4 + 2.22.0 + + RepCounterBot diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/ServletInitializer.java b/src/main/java/com/mykhailotiutiun/repcounterbot/ServletInitializer.java deleted file mode 100644 index 49a7e97..0000000 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/ServletInitializer.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.mykhailotiutiun.repcounterbot; - -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; - -public class ServletInitializer extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(RepCounterBotApplication.class); - } - -} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBot.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBot.java index 446cb1f..78b7ead 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBot.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBot.java @@ -8,14 +8,7 @@ import lombok.extern.slf4j.Slf4j; import org.telegram.telegrambots.bots.TelegramWebhookBot; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; -import org.telegram.telegrambots.meta.exceptions.TelegramApiException; - -import java.util.ArrayList; -import java.util.List; @Slf4j @Getter @@ -33,59 +26,8 @@ public RepCounterBot(RepCounterBotFacade repCounterBotFacade) { this.repCounterBotFacade = repCounterBotFacade; } - @Override public BotApiMethod onWebhookUpdateReceived(Update update) { return repCounterBotFacade.handleUpdate(update); } - - public void sendMessage(String chatId, String textMessage) { - SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(chatId); - sendMessage.setText(textMessage); - - try { - execute(sendMessage); - } catch (TelegramApiException e) { - e.printStackTrace(); - } - } - - public void sendMessage(SendMessage sendMessage) { - try { - execute(sendMessage); - } catch (TelegramApiException e) { - e.printStackTrace(); - } - } - - public void sendInlineKeyBoardMessage(String chatId, String text, String buttonText, String callbackData) { - InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(); - InlineKeyboardButton keyboardButton = new InlineKeyboardButton(); - - keyboardButton.setText(buttonText); - - if (callbackData != null) { - keyboardButton.setCallbackData(callbackData); - } - - List keyboardButtonsRow1 = new ArrayList<>(); - keyboardButtonsRow1.add(keyboardButton); - - List> rowList = new ArrayList<>(); - rowList.add(keyboardButtonsRow1); - - inlineKeyboardMarkup.setKeyboard(rowList); - - SendMessage sendMessage = new SendMessage(); - sendMessage.setChatId(chatId); - sendMessage.setText(text); - sendMessage.setReplyMarkup(inlineKeyboardMarkup); - - try { - execute(sendMessage); - } catch (TelegramApiException e) { - e.printStackTrace(); - } - } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBotFacade.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBotFacade.java index 9f7d35d..81abe98 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBotFacade.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/RepCounterBotFacade.java @@ -2,16 +2,15 @@ import com.mykhailotiutiun.repcounterbot.botapi.handler.CallbackQueryHandler; import com.mykhailotiutiun.repcounterbot.botapi.handler.MessageHandler; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; import com.mykhailotiutiun.repcounterbot.constants.CallbackHandlerType; import com.mykhailotiutiun.repcounterbot.constants.ChatState; import com.mykhailotiutiun.repcounterbot.constants.MessageHandlerType; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; @@ -27,14 +26,14 @@ public class RepCounterBotFacade { private final Map messageHandlers = new HashMap<>(); private final Map callbackQueryHandlers = new HashMap<>(); - private final LocaleMessageService localeMessageService; - private final ChatDataCache chatDataCache; + private final LocaleMessageUtil localeMessageUtil; + private final CurrentBotStateCache currentBotStateCache; - public RepCounterBotFacade(List messageHandlers, List callbackQueryHandlers, LocaleMessageService localeMessageService, ChatDataCache chatDataCache) { - this.localeMessageService = localeMessageService; + public RepCounterBotFacade(List messageHandlers, List callbackQueryHandlers, LocaleMessageUtil localeMessageUtil, CurrentBotStateCache currentBotStateCache) { + this.localeMessageUtil = localeMessageUtil; messageHandlers.forEach(handler -> this.messageHandlers.put(handler.getHandlerType(), handler)); callbackQueryHandlers.forEach(handler -> this.callbackQueryHandlers.put(handler.getHandlerType(), handler)); - this.chatDataCache = chatDataCache; + this.currentBotStateCache = currentBotStateCache; } public BotApiMethod handleUpdate(Update update) { @@ -43,14 +42,12 @@ public BotApiMethod handleUpdate(Update update) { } else { return handleMessage(update.getMessage()); } - - } private BotApiMethod handleCallbackQuery(CallbackQuery callbackQuery) { CallbackQueryHandler callbackQueryHandler = choseCallbackQueryHandler(callbackQuery); if (callbackQueryHandler == null) { - return new SendMessage(callbackQuery.getFrom().getId().toString(), localeMessageService.getMessage("reply.error", callbackQuery.getFrom().getId().toString())); + return new SendMessage(callbackQuery.getFrom().getId().toString(), localeMessageUtil.getMessage("reply.error", callbackQuery.getFrom().getId().toString())); } log.trace("CallbackQuery request from @{}, with text {}", callbackQuery.getFrom().getUserName(), callbackQuery.getData()); @@ -59,19 +56,19 @@ private BotApiMethod handleCallbackQuery(CallbackQuery callbackQuery) { private CallbackQueryHandler choseCallbackQueryHandler(CallbackQuery callbackQuery) { if (callbackQuery.getData().contains("Main")) { - chatDataCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); return callbackQueryHandlers.get(CallbackHandlerType.MAIN_MENU_HANDLER); } else if(callbackQuery.getData().contains("WorkoutWeek")) { - chatDataCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); return callbackQueryHandlers.get(CallbackHandlerType.WORKOUT_WEEK_HANDLER); } else if (callbackQuery.getData().contains("WorkoutDay")) { - chatDataCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); return callbackQueryHandlers.get(CallbackHandlerType.WORKOUT_DAY_HANDLER); } else if (callbackQuery.getData().contains("WorkoutExercise")) { - chatDataCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); return callbackQueryHandlers.get(CallbackHandlerType.WORKOUT_EXERCISE_HANDLER); } else if (callbackQuery.getData().contains("WorkoutSet")) { - chatDataCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(callbackQuery.getFrom().getId().toString(), ChatState.MAIN_MENU); return callbackQueryHandlers.get(CallbackHandlerType.WORKOUT_SET_HANDLER); } @@ -82,7 +79,7 @@ private CallbackQueryHandler choseCallbackQueryHandler(CallbackQuery callbackQue private BotApiMethod handleMessage(Message message) { MessageHandler messageHandler = choseMessageHandler(message); if (messageHandler == null) { - return new SendMessage(message.getChatId().toString(), localeMessageService.getMessage("reply.invalid-message", message.getChatId().toString())); + return new SendMessage(message.getChatId().toString(), localeMessageUtil.getMessage("reply.invalid-message", message.getChatId().toString())); } log.trace("Message request from @{}, with text {}", message.getFrom().getUserName(), message.getText()); @@ -98,19 +95,19 @@ private MessageHandler choseMessageHandler(Message message) { case ("/start"): case ("Choose a language"): case ("Обрати мову"): { - chatDataCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); return messageHandlers.get(MessageHandlerType.MAIN_MENU_HANDLER); } - case ("Поточний тиждень тренувань"): - case ("Current workout week"): { - chatDataCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); + case ("Поточний тиждень"): + case ("Current week"): { + currentBotStateCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); return messageHandlers.get(MessageHandlerType.CURRENT_WEEK_HANDLER); } default: break; } - switch (chatDataCache.getChatDataCurrentBotState(message.getChatId().toString())) { + switch (currentBotStateCache.getChatDataCurrentBotState(message.getChatId().toString())) { case SET_NAME_FOR_WORKOUT_DAY: return messageHandlers.get(MessageHandlerType.WORKOUT_DAY_HANDLER); case CREATE_WORKOUT_EXERCISE: diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/CallbackQueryHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/CallbackQueryHandler.java index a6f9373..d046bb8 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/CallbackQueryHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/CallbackQueryHandler.java @@ -2,7 +2,6 @@ import com.mykhailotiutiun.repcounterbot.constants.CallbackHandlerType; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; public interface CallbackQueryHandler { diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuCallbackQueryHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuCallbackQueryHandler.java index 8ebca09..5f41b81 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuCallbackQueryHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuCallbackQueryHandler.java @@ -2,7 +2,7 @@ import com.mykhailotiutiun.repcounterbot.botapi.handler.CallbackQueryHandler; import com.mykhailotiutiun.repcounterbot.constants.CallbackHandlerType; -import com.mykhailotiutiun.repcounterbot.service.MainMenuService; +import com.mykhailotiutiun.repcounterbot.message.MainMenuMessageGenerator; import com.mykhailotiutiun.repcounterbot.service.UserService; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; @@ -11,11 +11,11 @@ @Component public class MainMenuCallbackQueryHandler implements CallbackQueryHandler { - private final MainMenuService mainMenuService; + private final MainMenuMessageGenerator mainMenuMessageGenerator; private final UserService userService; - public MainMenuCallbackQueryHandler(MainMenuService mainMenuService, UserService userService) { - this.mainMenuService = mainMenuService; + public MainMenuCallbackQueryHandler(MainMenuMessageGenerator mainMenuMessageGenerator, UserService userService) { + this.mainMenuMessageGenerator = mainMenuMessageGenerator; this.userService = userService; } @@ -23,8 +23,8 @@ public MainMenuCallbackQueryHandler(MainMenuService mainMenuService, UserService public SendMessage handleCallbackQuery(CallbackQuery callbackQuery) { // 0 - command, 1 - userId, 2 - lang String[] splintedMessage = callbackQuery.getData().split(":"); - userService.setUserLang(splintedMessage[1], splintedMessage[2]); - return mainMenuService.getMainMenuMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getFrom().getFirstName()); + userService.setUserLang(Long.valueOf(splintedMessage[1]), splintedMessage[2]); + return mainMenuMessageGenerator.getMainMenuMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getFrom().getFirstName()); } @Override diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuMessageHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuMessageHandler.java index 1f783d0..8d9e74a 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuMessageHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/MainMenuMessageHandler.java @@ -3,10 +3,10 @@ import com.mykhailotiutiun.repcounterbot.botapi.handler.MessageHandler; import com.mykhailotiutiun.repcounterbot.constants.MessageHandlerType; import com.mykhailotiutiun.repcounterbot.exception.EntityAlreadyExistsException; +import com.mykhailotiutiun.repcounterbot.message.MainMenuMessageGenerator; import com.mykhailotiutiun.repcounterbot.model.User; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; -import com.mykhailotiutiun.repcounterbot.service.MainMenuService; import com.mykhailotiutiun.repcounterbot.service.UserService; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; @@ -20,14 +20,14 @@ @Component public class MainMenuMessageHandler implements MessageHandler { - private final MainMenuService mainMenuService; + private final MainMenuMessageGenerator mainMenuMessageGenerator; private final UserService userService; - private final LocaleMessageService localeMessageService; + private final LocaleMessageUtil localeMessageUtil; - public MainMenuMessageHandler(MainMenuService mainMenuService, UserService userService, LocaleMessageService localeMessageService) { - this.mainMenuService = mainMenuService; + public MainMenuMessageHandler(MainMenuMessageGenerator mainMenuMessageGenerator, UserService userService, LocaleMessageUtil localeMessageUtil) { + this.mainMenuMessageGenerator = mainMenuMessageGenerator; this.userService = userService; - this.localeMessageService = localeMessageService; + this.localeMessageUtil = localeMessageUtil; } @Override @@ -44,14 +44,18 @@ public BotApiMethod handleMessage(Message message) { private SendMessage handleStart(Message message) { try { - userService.create(new User(message.getFrom().getId(), message.getFrom().getFirstName())); + userService.create(User.builder() + .id(message.getFrom().getId()) + .username(message.getFrom().getFirstName()) + .localTag("en_EN") + .build()); } catch (EntityAlreadyExistsException ignored) { } - return mainMenuService.getMainMenuMessage(message.getChatId().toString(), message.getFrom().getFirstName()); + return mainMenuMessageGenerator.getMainMenuMessage(message.getChatId().toString(), message.getFrom().getFirstName()); } private SendMessage handleChooseLang(Message message) { - SendMessage sendMessage = new SendMessage(message.getChatId().toString(), localeMessageService.getMessage("reply.main-menu.keyboard.change-lang", message.getChatId().toString())); + SendMessage sendMessage = new SendMessage(message.getChatId().toString(), localeMessageUtil.getMessage("reply.main-menu.keyboard.change-lang", message.getChatId().toString())); sendMessage.setReplyMarkup(getKeyboardForLang(message.getChatId().toString())); return sendMessage; } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayCallbackQueryHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayCallbackQueryHandler.java index 8f5c340..f77b043 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayCallbackQueryHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayCallbackQueryHandler.java @@ -1,13 +1,16 @@ package com.mykhailotiutiun.repcounterbot.botapi.handler.Impl; import com.mykhailotiutiun.repcounterbot.botapi.handler.CallbackQueryHandler; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutDayCache; import com.mykhailotiutiun.repcounterbot.constants.CallbackHandlerType; import com.mykhailotiutiun.repcounterbot.constants.ChatState; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; -import com.mykhailotiutiun.repcounterbot.service.MainMenuService; +import com.mykhailotiutiun.repcounterbot.message.MainMenuMessageGenerator; +import com.mykhailotiutiun.repcounterbot.message.WorkoutDayMessageGenerator; +import com.mykhailotiutiun.repcounterbot.message.WorkoutWeekMessageGenerator; import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; @@ -17,23 +20,27 @@ public class WorkoutDayCallbackQueryHandler implements CallbackQueryHandler { private final WorkoutDayService workoutDayService; - private final WorkoutWeekService workoutWeekService; - private final MainMenuService mainMenuService; - private final ChatDataCache chatDataCache; - private final LocaleMessageService localeMessageService; + private final MainMenuMessageGenerator mainMenuMessageGenerator; + private final LocaleMessageUtil localeMessageUtil; + private final CurrentBotStateCache currentBotStateCache; + private final SelectedWorkoutDayCache selectedWorkoutDayCache; + private final WorkoutDayMessageGenerator workoutDayMessageGenerator; + private final WorkoutWeekMessageGenerator workoutWeekMessageGenerator; - public WorkoutDayCallbackQueryHandler(WorkoutDayService workoutDayService, WorkoutWeekService workoutWeekService, MainMenuService mainMenuService, ChatDataCache chatDataCache, LocaleMessageService localeMessageService) { + public WorkoutDayCallbackQueryHandler(WorkoutDayService workoutDayService, MainMenuMessageGenerator mainMenuMessageGenerator, LocaleMessageUtil localeMessageUtil, CurrentBotStateCache currentBotStateCache, SelectedWorkoutDayCache selectedWorkoutDayCache, WorkoutDayMessageGenerator workoutDayMessageGenerator, WorkoutWeekMessageGenerator workoutWeekMessageGenerator) { this.workoutDayService = workoutDayService; - this.workoutWeekService = workoutWeekService; - this.mainMenuService = mainMenuService; - this.chatDataCache = chatDataCache; - this.localeMessageService = localeMessageService; + this.mainMenuMessageGenerator = mainMenuMessageGenerator; + this.localeMessageUtil = localeMessageUtil; + this.currentBotStateCache = currentBotStateCache; + this.selectedWorkoutDayCache = selectedWorkoutDayCache; + this.workoutDayMessageGenerator = workoutDayMessageGenerator; + this.workoutWeekMessageGenerator = workoutWeekMessageGenerator; } @Override public BotApiMethod handleCallbackQuery(CallbackQuery callbackQuery) { if (callbackQuery.getData().startsWith("/select")) { - return workoutDayService.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), callbackQuery.getData().split(":")[1]); + return workoutDayMessageGenerator.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), Long.valueOf(callbackQuery.getData().split(":")[1])); } else if (callbackQuery.getData().startsWith("/set-name-request")) { return handelSetNameRequest(callbackQuery); } else if (callbackQuery.getData().startsWith("/set-rest-request")) { @@ -52,14 +59,13 @@ public CallbackHandlerType getHandlerType() { private EditMessageText handelSetNameRequest(CallbackQuery callbackQuery) { String chatId = callbackQuery.getFrom().getId().toString(); - chatDataCache.setChatDataCurrentBotState(chatId, ChatState.SET_NAME_FOR_WORKOUT_DAY); - chatDataCache.setSelectedMessageId(chatId, callbackQuery.getMessage().getMessageId()); - chatDataCache.setSelectedWorkoutDay(chatId, callbackQuery.getData().split(":")[1]); + currentBotStateCache.setChatDataCurrentBotState(chatId, ChatState.SET_NAME_FOR_WORKOUT_DAY); + selectedWorkoutDayCache.setSelectedWorkoutDay(chatId, callbackQuery.getData().split(":")[1]); - EditMessageText editMessageText = new EditMessageText(localeMessageService.getMessage("reply.workout-day.set-name-request", chatId)); + EditMessageText editMessageText = new EditMessageText(localeMessageUtil.getMessage("reply.workout-day.set-name-request", chatId)); editMessageText.setChatId(chatId); editMessageText.setMessageId(callbackQuery.getMessage().getMessageId()); - editMessageText.setReplyMarkup(mainMenuService.getBackButtonInlineKeyboard(chatId, "/select-WorkoutDay:" + callbackQuery.getData().split(":")[1])); + editMessageText.setReplyMarkup(mainMenuMessageGenerator.getBackButtonInlineKeyboard(chatId, "/select-WorkoutDay:" + callbackQuery.getData().split(":")[1])); return editMessageText; } @@ -67,12 +73,12 @@ private EditMessageText handelSetNameRequest(CallbackQuery callbackQuery) { private EditMessageText handelSetRestRequest(CallbackQuery callbackQuery){ String dayId = callbackQuery.getData().split(":")[1]; - return mainMenuService.getAreYouSureMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), "/set-rest-WorkoutDay:" + dayId, "/select-WorkoutDay:" + dayId); + return mainMenuMessageGenerator.getAreYouSureMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), "/set-rest-WorkoutDay:" + dayId, "/select-WorkoutDay:" + dayId); } private EditMessageText handelSetRest(CallbackQuery callbackQuery) { - workoutDayService.setRestWorkoutDay(callbackQuery.getData().split(":")[1]); - return workoutWeekService.getCurrentWorkoutWeekEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId()); + workoutDayService.setRestWorkoutDay(Long.valueOf(callbackQuery.getData().split(":")[1])); + return workoutWeekMessageGenerator.getCurrentWorkoutWeekEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId()); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayMessageHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayMessageHandler.java index 9e168c1..3ec3bdb 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayMessageHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutDayMessageHandler.java @@ -1,9 +1,11 @@ package com.mykhailotiutiun.repcounterbot.botapi.handler.Impl; import com.mykhailotiutiun.repcounterbot.botapi.handler.MessageHandler; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutDayCache; import com.mykhailotiutiun.repcounterbot.constants.ChatState; import com.mykhailotiutiun.repcounterbot.constants.MessageHandlerType; +import com.mykhailotiutiun.repcounterbot.message.WorkoutWeekMessageGenerator; import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; import org.springframework.stereotype.Component; @@ -13,22 +15,24 @@ @Component public class WorkoutDayMessageHandler implements MessageHandler { - private final ChatDataCache chatDataCache; private final WorkoutDayService workoutDayService; - private final WorkoutWeekService workoutWeekService; + private final CurrentBotStateCache currentBotStateCache; + private final SelectedWorkoutDayCache selectedWorkoutDayCache; + private final WorkoutWeekMessageGenerator workoutWeekMessageGenerator; - public WorkoutDayMessageHandler(ChatDataCache chatDataCache, WorkoutDayService workoutDayService, WorkoutWeekService workoutWeekService) { - this.chatDataCache = chatDataCache; + public WorkoutDayMessageHandler(WorkoutDayService workoutDayService, CurrentBotStateCache currentBotStateCache, SelectedWorkoutDayCache selectedWorkoutDayCache, WorkoutWeekMessageGenerator workoutWeekMessageGenerator) { this.workoutDayService = workoutDayService; - this.workoutWeekService = workoutWeekService; + this.currentBotStateCache = currentBotStateCache; + this.selectedWorkoutDayCache = selectedWorkoutDayCache; + this.workoutWeekMessageGenerator = workoutWeekMessageGenerator; } @Override public BotApiMethod handleMessage(Message message) { - workoutDayService.setWorkoutDayName(chatDataCache.getSelectedWorkoutDay(message.getChatId().toString()), message.getText()); + workoutDayService.setName(Long.valueOf(selectedWorkoutDayCache.getSelectedWorkoutDay(message.getChatId().toString())), message.getText()); - chatDataCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); - return workoutWeekService.getCurrentWorkoutWeekSendMessage(message.getChatId().toString()); + currentBotStateCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); + return workoutWeekMessageGenerator.getCurrentWorkoutWeekSendMessage(message.getChatId().toString()); } @Override diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseCallbackQueryHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseCallbackQueryHandler.java index 0bba4db..7308819 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseCallbackQueryHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseCallbackQueryHandler.java @@ -1,36 +1,44 @@ package com.mykhailotiutiun.repcounterbot.botapi.handler.Impl; import com.mykhailotiutiun.repcounterbot.botapi.handler.CallbackQueryHandler; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutDayCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutExerciseCache; import com.mykhailotiutiun.repcounterbot.constants.CallbackHandlerType; import com.mykhailotiutiun.repcounterbot.constants.ChatState; +import com.mykhailotiutiun.repcounterbot.message.MainMenuMessageGenerator; +import com.mykhailotiutiun.repcounterbot.message.WorkoutDayMessageGenerator; +import com.mykhailotiutiun.repcounterbot.message.WorkoutExerciseMessageGenerator; import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; -import com.mykhailotiutiun.repcounterbot.service.MainMenuService; -import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; @Component public class WorkoutExerciseCallbackQueryHandler implements CallbackQueryHandler { - private final ChatDataCache chatDataCache; + private final SelectedWorkoutExerciseCache selectedWorkoutExerciseCache; private final WorkoutExerciseService workoutExerciseService; - private final WorkoutDayService workoutDayService; - private final LocaleMessageService localeMessageService; - private final MainMenuService mainMenuService; + private final LocaleMessageUtil localeMessageUtil; + private final MainMenuMessageGenerator mainMenuMessageGenerator; + private final CurrentBotStateCache currentBotStateCache; + private final SelectedWorkoutDayCache selectedWorkoutDayCache; + private final WorkoutDayMessageGenerator workoutDayMessageGenerator; + private final WorkoutExerciseMessageGenerator workoutExerciseMessageGenerator; - public WorkoutExerciseCallbackQueryHandler(ChatDataCache chatDataCache, WorkoutExerciseService workoutExerciseService, WorkoutDayService workoutDayService, LocaleMessageService localeMessageService, MainMenuService mainMenuService) { - this.chatDataCache = chatDataCache; + public WorkoutExerciseCallbackQueryHandler(SelectedWorkoutExerciseCache selectedWorkoutExerciseCache, WorkoutExerciseService workoutExerciseService, LocaleMessageUtil localeMessageUtil, MainMenuMessageGenerator mainMenuMessageGenerator, CurrentBotStateCache currentBotStateCache, SelectedWorkoutDayCache selectedWorkoutDayCache, WorkoutDayMessageGenerator workoutDayMessageGenerator, WorkoutExerciseMessageGenerator workoutExerciseMessageGenerator) { + this.selectedWorkoutExerciseCache = selectedWorkoutExerciseCache; this.workoutExerciseService = workoutExerciseService; - this.workoutDayService = workoutDayService; - this.localeMessageService = localeMessageService; - this.mainMenuService = mainMenuService; + this.localeMessageUtil = localeMessageUtil; + this.mainMenuMessageGenerator = mainMenuMessageGenerator; + this.currentBotStateCache = currentBotStateCache; + this.selectedWorkoutDayCache = selectedWorkoutDayCache; + this.workoutDayMessageGenerator = workoutDayMessageGenerator; + this.workoutExerciseMessageGenerator = workoutExerciseMessageGenerator; } @Override @@ -62,14 +70,13 @@ public CallbackHandlerType getHandlerType() { private EditMessageText handleCreateRequest(CallbackQuery callbackQuery) { String chatId = callbackQuery.getFrom().getId().toString(); - chatDataCache.setChatDataCurrentBotState(chatId, ChatState.CREATE_WORKOUT_EXERCISE); - chatDataCache.setSelectedMessageId(chatId, callbackQuery.getMessage().getMessageId()); - chatDataCache.setSelectedWorkoutDay(chatId, callbackQuery.getData().split(":")[1]); + currentBotStateCache.setChatDataCurrentBotState(chatId, ChatState.CREATE_WORKOUT_EXERCISE); + selectedWorkoutDayCache.setSelectedWorkoutDay(chatId, callbackQuery.getData().split(":")[1]); - EditMessageText editMessageText = new EditMessageText(localeMessageService.getMessage("reply.workout-exercise.enter-the-name", chatId)); + EditMessageText editMessageText = new EditMessageText(localeMessageUtil.getMessage("reply.workout-exercise.enter-the-name", chatId)); editMessageText.setChatId(chatId); editMessageText.setMessageId(callbackQuery.getMessage().getMessageId()); - editMessageText.setReplyMarkup(mainMenuService.getBackButtonInlineKeyboard(chatId , "/select-WorkoutDay:" + callbackQuery.getData().split(":")[1])); + editMessageText.setReplyMarkup(mainMenuMessageGenerator.getBackButtonInlineKeyboard(chatId , "/select-WorkoutDay:" + callbackQuery.getData().split(":")[1])); return editMessageText; } @@ -78,49 +85,49 @@ private EditMessageText handleCreateRequest(CallbackQuery callbackQuery) { private EditMessageText handleSelect(CallbackQuery callbackQuery) { - return workoutExerciseService.getWorkoutExerciseEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), callbackQuery.getData().split(":")[1], false); + return workoutExerciseMessageGenerator.getWorkoutExerciseEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), Long.valueOf(callbackQuery.getData().split(":")[1]), false); } private EditMessageText handleEdit(CallbackQuery callbackQuery) { - return workoutExerciseService.getWorkoutExerciseEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), callbackQuery.getData().split(":")[1], true); + return workoutExerciseMessageGenerator.getWorkoutExerciseEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), Long.valueOf(callbackQuery.getData().split(":")[1]), true); } private EditMessageText moveUp(CallbackQuery callbackQuery){ - WorkoutExercise workoutExercise = workoutExerciseService.getWorkoutExerciseById(callbackQuery.getData().split(":")[1]); - workoutExerciseService.moveUpWorkoutExercise(callbackQuery.getData().split(":")[1]); - return workoutDayService.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), workoutExercise.getWorkoutDay().getId()); + WorkoutExercise workoutExercise = workoutExerciseService.getById(Long.valueOf(callbackQuery.getData().split(":")[1])); + workoutExerciseService.moveUp(Long.valueOf(callbackQuery.getData().split(":")[1])); + return workoutDayMessageGenerator.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), workoutExercise.getWorkoutDay().getId()); } private EditMessageText moveDown(CallbackQuery callbackQuery){ - workoutExerciseService.moveDownWorkoutExercise(callbackQuery.getData().split(":")[1]); - WorkoutExercise workoutExercise = workoutExerciseService.getWorkoutExerciseById(callbackQuery.getData().split(":")[1]); - return workoutDayService.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), workoutExercise.getWorkoutDay().getId()); + workoutExerciseService.moveDown(Long.valueOf(callbackQuery.getData().split(":")[1])); + WorkoutExercise workoutExercise = workoutExerciseService.getById(Long.valueOf(callbackQuery.getData().split(":")[1])); + return workoutDayMessageGenerator.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), workoutExercise.getWorkoutDay().getId()); } private EditMessageText handleChangeNameRequest(CallbackQuery callbackQuery){ String chatId = callbackQuery.getFrom().getId().toString(); - chatDataCache.setChatDataCurrentBotState(chatId, ChatState.CHANGE_WORKOUT_EXERCISE_NAME); - chatDataCache.setSelectedWorkoutExercise(chatId, callbackQuery.getData().split(":")[1]); + currentBotStateCache.setChatDataCurrentBotState(chatId, ChatState.CHANGE_WORKOUT_EXERCISE_NAME); + selectedWorkoutExerciseCache.setSelectedWorkoutExercise(chatId, callbackQuery.getData().split(":")[1]); - EditMessageText editMessageText = new EditMessageText(localeMessageService.getMessage("reply.workout-exercise.enter-the-name", chatId)); + EditMessageText editMessageText = new EditMessageText(localeMessageUtil.getMessage("reply.workout-exercise.enter-the-name", chatId)); editMessageText.setChatId(chatId); editMessageText.setMessageId(callbackQuery.getMessage().getMessageId()); - editMessageText.setReplyMarkup(mainMenuService.getBackButtonInlineKeyboard(chatId, "/edit-WorkoutExercise:" + callbackQuery.getData().split(":")[1])); + editMessageText.setReplyMarkup(mainMenuMessageGenerator.getBackButtonInlineKeyboard(chatId, "/edit-WorkoutExercise:" + callbackQuery.getData().split(":")[1])); return editMessageText; } private EditMessageText handleDeleteRequest(CallbackQuery callbackQuery){ String exerciseId = callbackQuery.getData().split(":")[1]; - return mainMenuService.getAreYouSureMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), "/delete-WorkoutExercise:" + exerciseId, "/select-WorkoutExercise:" + exerciseId); + return mainMenuMessageGenerator.getAreYouSureMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), "/delete-WorkoutExercise:" + exerciseId, "/select-WorkoutExercise:" + exerciseId); } private EditMessageText handleDelete(CallbackQuery callbackQuery) { - WorkoutExercise workoutExercise = workoutExerciseService.getWorkoutExerciseById(callbackQuery.getData().split(":")[1]); - String workoutDayId = workoutExercise.getWorkoutDay().getId(); + WorkoutExercise workoutExercise = workoutExerciseService.getById(Long.valueOf(callbackQuery.getData().split(":")[1])); + Long workoutDayId = workoutExercise.getWorkoutDay().getId(); workoutExerciseService.deleteById(workoutExercise.getId()); - return workoutDayService.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), workoutDayId); + return workoutDayMessageGenerator.getSelectWorkoutDayEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId(), workoutDayId); } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseMessageHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseMessageHandler.java index 93c29e0..4d62af2 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseMessageHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutExerciseMessageHandler.java @@ -1,34 +1,42 @@ package com.mykhailotiutiun.repcounterbot.botapi.handler.Impl; import com.mykhailotiutiun.repcounterbot.botapi.handler.MessageHandler; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutDayCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutExerciseCache; import com.mykhailotiutiun.repcounterbot.constants.ChatState; import com.mykhailotiutiun.repcounterbot.constants.MessageHandlerType; +import com.mykhailotiutiun.repcounterbot.message.WorkoutDayMessageGenerator; import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.Message; @Component public class WorkoutExerciseMessageHandler implements MessageHandler { - private final ChatDataCache chatDataCache; + private final CurrentBotStateCache currentBotStateCache; private final WorkoutDayService workoutDayService; private final WorkoutExerciseService workoutExerciseService; + private final SelectedWorkoutExerciseCache selectedWorkoutExerciseCache; + private final SelectedWorkoutDayCache selectedWorkoutDayCache; + private final WorkoutDayMessageGenerator workoutDayMessageGenerator; - public WorkoutExerciseMessageHandler(ChatDataCache chatDataCache, WorkoutDayService workoutDayService, WorkoutExerciseService workoutExerciseService) { - this.chatDataCache = chatDataCache; + public WorkoutExerciseMessageHandler(CurrentBotStateCache currentBotStateCache, WorkoutDayService workoutDayService, WorkoutExerciseService workoutExerciseService, SelectedWorkoutExerciseCache selectedWorkoutExerciseCache, SelectedWorkoutDayCache selectedWorkoutDayCache, WorkoutDayMessageGenerator workoutDayMessageGenerator) { + this.currentBotStateCache = currentBotStateCache; this.workoutDayService = workoutDayService; this.workoutExerciseService = workoutExerciseService; + this.selectedWorkoutExerciseCache = selectedWorkoutExerciseCache; + this.selectedWorkoutDayCache = selectedWorkoutDayCache; + this.workoutDayMessageGenerator = workoutDayMessageGenerator; } @Override public BotApiMethod handleMessage(Message message) { - switch (chatDataCache.getChatDataCurrentBotState(message.getChatId().toString())){ + switch (currentBotStateCache.getChatDataCurrentBotState(message.getChatId().toString())){ case CREATE_WORKOUT_EXERCISE: return handleCreateWorkoutExercise(message); case CHANGE_WORKOUT_EXERCISE_NAME: return handleChangeName(message); } @@ -42,18 +50,21 @@ public MessageHandlerType getHandlerType() { } private SendMessage handleCreateWorkoutExercise(Message message) { - chatDataCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); - workoutExerciseService.create(new WorkoutExercise(message.getText(), workoutDayService.getWorkoutDayById(chatDataCache.getSelectedWorkoutDay(message.getChatId().toString())))); + workoutExerciseService.create(WorkoutExercise.builder() + .name(message.getText()) + .workoutDay(workoutDayService.getById(Long.valueOf(selectedWorkoutDayCache.getSelectedWorkoutDay(message.getChatId().toString())))) + .build()); - return workoutDayService.getSelectWorkoutDaySendMessage(message.getChatId().toString(), chatDataCache.getSelectedWorkoutDay(message.getChatId().toString())); + return workoutDayMessageGenerator.getSelectWorkoutDaySendMessage(message.getChatId().toString(), Long.valueOf(selectedWorkoutDayCache.getSelectedWorkoutDay(message.getChatId().toString()))); } private SendMessage handleChangeName(Message message){ - chatDataCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); - workoutExerciseService.setNameToWorkoutExercise(chatDataCache.getSelectedWorkoutExercise(message.getChatId().toString()), message.getText()); + workoutExerciseService.setName(Long.valueOf(selectedWorkoutExerciseCache.getSelectedWorkoutExercise(message.getChatId().toString())), message.getText()); - return workoutDayService.getSelectWorkoutDaySendMessage(message.getChatId().toString(), chatDataCache.getSelectedWorkoutDay(message.getChatId().toString())); + return workoutDayMessageGenerator.getSelectWorkoutDaySendMessage(message.getChatId().toString(), Long.valueOf(selectedWorkoutDayCache.getSelectedWorkoutDay(message.getChatId().toString()))); } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetCallbackQueryHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetCallbackQueryHandler.java index fff72b7..ab10ce6 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetCallbackQueryHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetCallbackQueryHandler.java @@ -1,28 +1,30 @@ package com.mykhailotiutiun.repcounterbot.botapi.handler.Impl; import com.mykhailotiutiun.repcounterbot.botapi.handler.CallbackQueryHandler; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutExerciseCache; import com.mykhailotiutiun.repcounterbot.constants.CallbackHandlerType; import com.mykhailotiutiun.repcounterbot.constants.ChatState; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; -import com.mykhailotiutiun.repcounterbot.service.MainMenuService; +import com.mykhailotiutiun.repcounterbot.message.MainMenuMessageGenerator; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; @Component public class WorkoutSetCallbackQueryHandler implements CallbackQueryHandler { - private final ChatDataCache chatDataCache; - private final LocaleMessageService localeMessageService; - private final MainMenuService mainMenuService; + private final SelectedWorkoutExerciseCache selectedWorkoutExerciseCache; + private final LocaleMessageUtil localeMessageUtil; + private final MainMenuMessageGenerator mainMenuMessageGenerator; + private final CurrentBotStateCache currentBotStateCache; - public WorkoutSetCallbackQueryHandler(ChatDataCache chatDataCache, LocaleMessageService localeMessageService, MainMenuService mainMenuService) { - this.chatDataCache = chatDataCache; - this.localeMessageService = localeMessageService; - this.mainMenuService = mainMenuService; + public WorkoutSetCallbackQueryHandler(SelectedWorkoutExerciseCache selectedWorkoutExerciseCache, LocaleMessageUtil localeMessageUtil, MainMenuMessageGenerator mainMenuMessageGenerator, CurrentBotStateCache currentBotStateCache) { + this.selectedWorkoutExerciseCache = selectedWorkoutExerciseCache; + this.localeMessageUtil = localeMessageUtil; + this.mainMenuMessageGenerator = mainMenuMessageGenerator; + this.currentBotStateCache = currentBotStateCache; } @Override @@ -40,14 +42,13 @@ public CallbackHandlerType getHandlerType() { private EditMessageText handleFastSetsSetRequest(CallbackQuery callbackQuery) { String chatId = callbackQuery.getFrom().getId().toString(); - chatDataCache.setChatDataCurrentBotState(chatId, ChatState.FAST_SETS_SET); - chatDataCache.setSelectedMessageId(chatId, callbackQuery.getMessage().getMessageId()); - chatDataCache.setSelectedWorkoutExercise(chatId, callbackQuery.getData().split(":")[1]); + currentBotStateCache.setChatDataCurrentBotState(chatId, ChatState.FAST_SETS_SET); + selectedWorkoutExerciseCache.setSelectedWorkoutExercise(chatId, callbackQuery.getData().split(":")[1]); - EditMessageText editMessageText = new EditMessageText(localeMessageService.getMessage("reply.workout-set.set", chatId)); + EditMessageText editMessageText = new EditMessageText(localeMessageUtil.getMessage("reply.workout-set.set", chatId)); editMessageText.setChatId(chatId); editMessageText.setMessageId(callbackQuery.getMessage().getMessageId()); - editMessageText.setReplyMarkup(mainMenuService.getBackButtonInlineKeyboard(chatId, "/select-WorkoutExercise:" + callbackQuery.getData().split(":")[1])); + editMessageText.setReplyMarkup(mainMenuMessageGenerator.getBackButtonInlineKeyboard(chatId, "/select-WorkoutExercise:" + callbackQuery.getData().split(":")[1])); return editMessageText; } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetMessageHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetMessageHandler.java index f3e467c..8af7789 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetMessageHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutSetMessageHandler.java @@ -1,15 +1,16 @@ package com.mykhailotiutiun.repcounterbot.botapi.handler.Impl; import com.mykhailotiutiun.repcounterbot.botapi.handler.MessageHandler; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutExerciseCache; import com.mykhailotiutiun.repcounterbot.constants.ChatState; import com.mykhailotiutiun.repcounterbot.constants.MessageHandlerType; +import com.mykhailotiutiun.repcounterbot.message.WorkoutExerciseMessageGenerator; import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.Message; import java.util.ArrayList; @@ -18,17 +19,21 @@ @Component public class WorkoutSetMessageHandler implements MessageHandler { - private final ChatDataCache chatDataCache; + private final SelectedWorkoutExerciseCache selectedWorkoutExerciseCache; private final WorkoutExerciseService workoutExerciseService; + private final CurrentBotStateCache currentBotStateCache; + private final WorkoutExerciseMessageGenerator workoutExerciseMessageGenerator; - public WorkoutSetMessageHandler(ChatDataCache chatDataCache, WorkoutExerciseService workoutExerciseService) { - this.chatDataCache = chatDataCache; + public WorkoutSetMessageHandler(SelectedWorkoutExerciseCache selectedWorkoutExerciseCache, WorkoutExerciseService workoutExerciseService, CurrentBotStateCache currentBotStateCache, WorkoutExerciseMessageGenerator workoutExerciseMessageGenerator) { + this.selectedWorkoutExerciseCache = selectedWorkoutExerciseCache; this.workoutExerciseService = workoutExerciseService; + this.currentBotStateCache = currentBotStateCache; + this.workoutExerciseMessageGenerator = workoutExerciseMessageGenerator; } @Override public BotApiMethod handleMessage(Message message) { - chatDataCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); + currentBotStateCache.setChatDataCurrentBotState(message.getChatId().toString(), ChatState.MAIN_MENU); return handleFastSetsSetRequest(message); } @@ -44,12 +49,16 @@ private SendMessage handleFastSetsSetRequest(Message message) { for (int i = 0; i < setsString.size(); i++) { String s = setsString.get(i); - workoutSets.add(new WorkoutSet(i + 1, Integer.valueOf(s.split(":")[1]), Integer.valueOf(s.split(":")[0]))); + workoutSets.add(WorkoutSet.builder() + .number(i + 1) + .weight(Integer.valueOf(s.split(":")[0])) + .reps(Integer.valueOf(s.split(":")[1])) + .build()); } String chatId = message.getChatId().toString(); - workoutExerciseService.addSetsToWorkoutExercise(chatDataCache.getSelectedWorkoutExercise(chatId), workoutSets); + workoutExerciseService.addSets(Long.valueOf(selectedWorkoutExerciseCache.getSelectedWorkoutExercise(chatId)), workoutSets); - return workoutExerciseService.getWorkoutExerciseSendMessage(chatId, chatDataCache.getSelectedWorkoutExercise(chatId)); + return workoutExerciseMessageGenerator.getWorkoutExerciseSendMessage(chatId, Long.valueOf(selectedWorkoutExerciseCache.getSelectedWorkoutExercise(chatId))); } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekCallbackQueryHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekCallbackQueryHandler.java index d4453e9..df10f52 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekCallbackQueryHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekCallbackQueryHandler.java @@ -2,7 +2,7 @@ import com.mykhailotiutiun.repcounterbot.botapi.handler.CallbackQueryHandler; import com.mykhailotiutiun.repcounterbot.constants.CallbackHandlerType; -import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; +import com.mykhailotiutiun.repcounterbot.message.WorkoutWeekMessageGenerator; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; @@ -10,15 +10,15 @@ @Component public class WorkoutWeekCallbackQueryHandler implements CallbackQueryHandler { - private final WorkoutWeekService workoutWeekService; + private final WorkoutWeekMessageGenerator workoutWeekMessageGenerator; - public WorkoutWeekCallbackQueryHandler(WorkoutWeekService workoutWeekService) { - this.workoutWeekService = workoutWeekService; + public WorkoutWeekCallbackQueryHandler(WorkoutWeekMessageGenerator workoutWeekMessageGenerator) { + this.workoutWeekMessageGenerator = workoutWeekMessageGenerator; } @Override public BotApiMethod handleCallbackQuery(CallbackQuery callbackQuery) { - return workoutWeekService.getCurrentWorkoutWeekEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId()); + return workoutWeekMessageGenerator.getCurrentWorkoutWeekEditMessage(callbackQuery.getFrom().getId().toString(), callbackQuery.getMessage().getMessageId()); } @Override diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekMessageHandler.java b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekMessageHandler.java index 168ac70..e0cd290 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekMessageHandler.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/botapi/handler/Impl/WorkoutWeekMessageHandler.java @@ -2,7 +2,7 @@ import com.mykhailotiutiun.repcounterbot.botapi.handler.MessageHandler; import com.mykhailotiutiun.repcounterbot.constants.MessageHandlerType; -import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; +import com.mykhailotiutiun.repcounterbot.message.WorkoutWeekMessageGenerator; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.objects.Message; @@ -10,14 +10,15 @@ @Component public class WorkoutWeekMessageHandler implements MessageHandler { - private final WorkoutWeekService workoutWeekService; + private final WorkoutWeekMessageGenerator workoutWeekMessageGenerator; - public WorkoutWeekMessageHandler(WorkoutWeekService workoutWeekService) { - this.workoutWeekService = workoutWeekService;} + public WorkoutWeekMessageHandler(WorkoutWeekMessageGenerator workoutWeekMessageGenerator) { + this.workoutWeekMessageGenerator = workoutWeekMessageGenerator; + } @Override public BotApiMethod handleMessage(Message message) { - return workoutWeekService.getCurrentWorkoutWeekSendMessage(message.getChatId().toString()); + return workoutWeekMessageGenerator.getCurrentWorkoutWeekSendMessage(message.getChatId().toString()); } @Override diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/ChatDataCache.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/ChatDataCache.java deleted file mode 100644 index 6449dec..0000000 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/ChatDataCache.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.mykhailotiutiun.repcounterbot.cache; - -import com.mykhailotiutiun.repcounterbot.constants.ChatState; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.Map; - -@Service -public class ChatDataCache { - - private final Map usersBotStates = new HashMap<>(); - private final Map selectedMessageId = new HashMap<>(); - private final Map userSelectedLanguage = new HashMap<>(); - private final Map selectedWorkoutDays = new HashMap<>(); - private final Map selectedWorkoutExercises = new HashMap<>(); - - public void setChatDataCurrentBotState(String chatId, ChatState chatState) { - usersBotStates.put(chatId, chatState); - } - - public ChatState getChatDataCurrentBotState(String chatId) { - ChatState chatState = usersBotStates.get(chatId); - if (chatState == null) { - chatState = ChatState.MAIN_MENU; - } - - return chatState; - } - - public void setSelectedMessageId(String chatId, Integer messageId) { - selectedMessageId.put(chatId, messageId); - } - - public Integer getSelectedMessageId(String chatId) { - return selectedMessageId.get(chatId); - } - - public void setSelectedWorkoutDay(String chatId, String workoutDayId) { - selectedWorkoutDays.put(chatId, workoutDayId); - } - - public void setUserSelectedLanguage(String chatId, String localTag) { - userSelectedLanguage.put(chatId, localTag); - } - - public String getUserSelectedLanguage(String chatId) { - return userSelectedLanguage.get(chatId); - } - - public String getSelectedWorkoutDay(String chatId) { - return selectedWorkoutDays.get(chatId); - } - - public void setSelectedWorkoutExercise(String chatId, String workoutExerciseId) { - selectedWorkoutExercises.put(chatId, workoutExerciseId); - } - - public String getSelectedWorkoutExercise(String chatId) { - return selectedWorkoutExercises.get(chatId); - } - -} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/CurrentBotStateCache.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/CurrentBotStateCache.java new file mode 100644 index 0000000..42fe2a8 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/CurrentBotStateCache.java @@ -0,0 +1,10 @@ +package com.mykhailotiutiun.repcounterbot.cache; + +import com.mykhailotiutiun.repcounterbot.constants.ChatState; + +public interface CurrentBotStateCache { + + void setChatDataCurrentBotState(String chatId, ChatState chatState); + + ChatState getChatDataCurrentBotState(String chatId); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedLanguageCache.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedLanguageCache.java new file mode 100644 index 0000000..e146765 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedLanguageCache.java @@ -0,0 +1,7 @@ +package com.mykhailotiutiun.repcounterbot.cache; + +public interface SelectedLanguageCache { + + void setSelectedLanguage(String chatId, String localTag); + String getSelectedLanguage(String chatId); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedWorkoutDayCache.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedWorkoutDayCache.java new file mode 100644 index 0000000..06e1dd8 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedWorkoutDayCache.java @@ -0,0 +1,8 @@ +package com.mykhailotiutiun.repcounterbot.cache; + +public interface SelectedWorkoutDayCache { + + void setSelectedWorkoutDay(String chatId, String workoutDayId); + + String getSelectedWorkoutDay(String chatId); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedWorkoutExerciseCache.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedWorkoutExerciseCache.java new file mode 100644 index 0000000..da88a4c --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/SelectedWorkoutExerciseCache.java @@ -0,0 +1,9 @@ +package com.mykhailotiutiun.repcounterbot.cache; + + +public interface SelectedWorkoutExerciseCache { + + void setSelectedWorkoutExercise(String chatId, String workoutExerciseId); + + String getSelectedWorkoutExercise(String chatId); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/CurrentBotStateCacheImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/CurrentBotStateCacheImpl.java new file mode 100644 index 0000000..5d7525b --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/CurrentBotStateCacheImpl.java @@ -0,0 +1,29 @@ +package com.mykhailotiutiun.repcounterbot.cache.impl; + +import com.mykhailotiutiun.repcounterbot.cache.CurrentBotStateCache; +import com.mykhailotiutiun.repcounterbot.constants.ChatState; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CurrentBotStateCacheImpl implements CurrentBotStateCache { + + private final Map usersBotStates = new HashMap<>(); + + @Override + public void setChatDataCurrentBotState(String chatId, ChatState chatState) { + usersBotStates.put(chatId, chatState); + } + + @Override + public ChatState getChatDataCurrentBotState(String chatId) { + ChatState chatState = usersBotStates.get(chatId); + if (chatState == null) { + chatState = ChatState.MAIN_MENU; + } + + return chatState; + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedLanguageCacheImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedLanguageCacheImpl.java new file mode 100644 index 0000000..6ce513c --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedLanguageCacheImpl.java @@ -0,0 +1,23 @@ +package com.mykhailotiutiun.repcounterbot.cache.impl; + +import com.mykhailotiutiun.repcounterbot.cache.SelectedLanguageCache; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class SelectedLanguageCacheImpl implements SelectedLanguageCache { + + private final Map selectedLanguage = new HashMap<>(); + + @Override + public void setSelectedLanguage(String chatId, String localTag) { + selectedLanguage.put(chatId, localTag); + } + + @Override + public String getSelectedLanguage(String chatId) { + return selectedLanguage.get(chatId); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedWorkoutDayCacheImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedWorkoutDayCacheImpl.java new file mode 100644 index 0000000..08d1b27 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedWorkoutDayCacheImpl.java @@ -0,0 +1,25 @@ +package com.mykhailotiutiun.repcounterbot.cache.impl; + +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutDayCache; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class SelectedWorkoutDayCacheImpl implements SelectedWorkoutDayCache { + + + private final Map selectedWorkoutDays = new HashMap<>(); + + + @Override + public void setSelectedWorkoutDay(String chatId, String workoutDayId) { + selectedWorkoutDays.put(chatId, workoutDayId); + } + + @Override + public String getSelectedWorkoutDay(String chatId) { + return selectedWorkoutDays.get(chatId); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedWorkoutExerciseCacheImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedWorkoutExerciseCacheImpl.java new file mode 100644 index 0000000..a871354 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/cache/impl/SelectedWorkoutExerciseCacheImpl.java @@ -0,0 +1,25 @@ +package com.mykhailotiutiun.repcounterbot.cache.impl; + +import com.mykhailotiutiun.repcounterbot.cache.SelectedWorkoutExerciseCache; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +@Service +public class SelectedWorkoutExerciseCacheImpl implements SelectedWorkoutExerciseCache { + + private final Map selectedWorkoutExercises = new HashMap<>(); + + + @Override + public void setSelectedWorkoutExercise(String chatId, String workoutExerciseId) { + selectedWorkoutExercises.put(chatId, workoutExerciseId); + } + + @Override + public String getSelectedWorkoutExercise(String chatId) { + return selectedWorkoutExercises.get(chatId); + } + +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/config/JdbcConfig.java b/src/main/java/com/mykhailotiutiun/repcounterbot/config/JdbcConfig.java new file mode 100644 index 0000000..9693931 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/config/JdbcConfig.java @@ -0,0 +1,16 @@ +package com.mykhailotiutiun.repcounterbot.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +import javax.sql.DataSource; + +@Configuration +public class JdbcConfig { + + @Bean + public JdbcTemplate getJdbcTemplate(DataSource dataSource){ + return new JdbcTemplate(dataSource); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/controller/WebhookController.java b/src/main/java/com/mykhailotiutiun/repcounterbot/controller/MainController.java similarity index 88% rename from src/main/java/com/mykhailotiutiun/repcounterbot/controller/WebhookController.java rename to src/main/java/com/mykhailotiutiun/repcounterbot/controller/MainController.java index f063277..7719041 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/controller/WebhookController.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/controller/MainController.java @@ -10,11 +10,11 @@ @Slf4j @RestController -public class WebhookController { +public class MainController { private final RepCounterBot repCounterBot; - public WebhookController(RepCounterBot repCounterBot) { + public MainController(RepCounterBot repCounterBot) { this.repCounterBot = repCounterBot; } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/language/SelectedLanguageProvider.java b/src/main/java/com/mykhailotiutiun/repcounterbot/language/SelectedLanguageProvider.java new file mode 100644 index 0000000..78e4c1b --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/language/SelectedLanguageProvider.java @@ -0,0 +1,5 @@ +package com.mykhailotiutiun.repcounterbot.language; + +public interface SelectedLanguageProvider { + String getLocaleTag(String chatId); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/UserMapper.java b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/UserMapper.java new file mode 100644 index 0000000..faf79e8 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/UserMapper.java @@ -0,0 +1,18 @@ +package com.mykhailotiutiun.repcounterbot.mapper; + +import com.mykhailotiutiun.repcounterbot.model.User; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class UserMapper implements RowMapper { + @Override + public User mapRow(ResultSet rs, int rowNum) throws SQLException { + return User.builder() + .id(rs.getLong("id")) + .username(rs.getString("username")) + .localTag(rs.getString("local_tag")) + .build(); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutDayMapper.java b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutDayMapper.java new file mode 100644 index 0000000..e342164 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutDayMapper.java @@ -0,0 +1,21 @@ +package com.mykhailotiutiun.repcounterbot.mapper; + +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class WorkoutDayMapper implements RowMapper { + @Override + public WorkoutDay mapRow(ResultSet rs, int rowNum) throws SQLException { + return WorkoutDay.builder() + .id(rs.getLong("id")) + .name(rs.getString("name")) + .isWorkoutDay(rs.getBoolean("is_workout_day")) + .date(rs.getDate("date").toLocalDate()) + .workoutWeek(WorkoutWeek.builder().id(rs.getLong("workout_week_id")).build()) + .build(); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutExerciseMapper.java b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutExerciseMapper.java new file mode 100644 index 0000000..642c2c7 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutExerciseMapper.java @@ -0,0 +1,23 @@ +package com.mykhailotiutiun.repcounterbot.mapper; + +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; + +public class WorkoutExerciseMapper implements RowMapper { + @Override + public WorkoutExercise mapRow(ResultSet rs, int rowNum) throws SQLException { + return WorkoutExercise.builder() + .id(rs.getLong("id")) + .name(rs.getString("name")) + .number(rs.getByte("number")) + .workoutDay(WorkoutDay.builder().id(rs.getLong("workout_day_id")).build()) + .workoutSets(new ArrayList<>()) + .prevWorkoutSets(new ArrayList<>()) + .build(); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutSetMapper.java b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutSetMapper.java new file mode 100644 index 0000000..ed66585 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutSetMapper.java @@ -0,0 +1,19 @@ +package com.mykhailotiutiun.repcounterbot.mapper; + +import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class WorkoutSetMapper implements RowMapper { + @Override + public WorkoutSet mapRow(ResultSet rs, int rowNum) throws SQLException { + return WorkoutSet.builder() + .id(rs.getLong("id")) + .number(rs.getInt("number")) + .weight(rs.getInt("weight")) + .reps(rs.getInt("reps")) + .build(); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutWeekMapper.java b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutWeekMapper.java new file mode 100644 index 0000000..253fbf3 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/mapper/WorkoutWeekMapper.java @@ -0,0 +1,21 @@ +package com.mykhailotiutiun.repcounterbot.mapper; + +import com.mykhailotiutiun.repcounterbot.model.User; +import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class WorkoutWeekMapper implements RowMapper { + @Override + public WorkoutWeek mapRow(ResultSet rs, int rowNum) throws SQLException { + return WorkoutWeek.builder() + .id(rs.getLong("id")) + .current(rs.getBoolean("current")) + .weekStartDate(rs.getDate("week_start_date").toLocalDate()) + .weekEndDate(rs.getDate("week_end_date").toLocalDate()) + .user(User.builder().id(rs.getLong("user_id")).build()) + .build(); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/MainMenuService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/MainMenuMessageGenerator.java similarity index 77% rename from src/main/java/com/mykhailotiutiun/repcounterbot/service/MainMenuService.java rename to src/main/java/com/mykhailotiutiun/repcounterbot/message/MainMenuMessageGenerator.java index 4ee6b96..a84cf9d 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/MainMenuService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/MainMenuMessageGenerator.java @@ -1,11 +1,10 @@ -package com.mykhailotiutiun.repcounterbot.service; +package com.mykhailotiutiun.repcounterbot.message; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; -import org.telegram.telegrambots.meta.api.objects.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; -public interface MainMenuService { +public interface MainMenuMessageGenerator { SendMessage getMainMenuMessage(String chatId, String firstName); EditMessageText getAreYouSureMessage(String chatId, Integer messageId, String okCallback, String cancelCallback); InlineKeyboardMarkup getBackButtonInlineKeyboard(String chatId, String backButtonCallbackData); diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutDayMessageGenerator.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutDayMessageGenerator.java new file mode 100644 index 0000000..f788095 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutDayMessageGenerator.java @@ -0,0 +1,10 @@ +package com.mykhailotiutiun.repcounterbot.message; + +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; + +public interface WorkoutDayMessageGenerator { + + SendMessage getSelectWorkoutDaySendMessage(String chatId, Long workoutDayId); + EditMessageText getSelectWorkoutDayEditMessage(String chatId, Integer messageId, Long workoutDayId); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutExerciseMessageGenerator.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutExerciseMessageGenerator.java new file mode 100644 index 0000000..94c56d8 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutExerciseMessageGenerator.java @@ -0,0 +1,10 @@ +package com.mykhailotiutiun.repcounterbot.message; + +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; + +public interface WorkoutExerciseMessageGenerator { + + SendMessage getWorkoutExerciseSendMessage(String chatId, Long workoutExerciseId); + EditMessageText getWorkoutExerciseEditMessage(String chatId, Integer messageId, Long workoutExerciseId, Boolean isOnEditPage); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutWeekMessageGenerator.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutWeekMessageGenerator.java new file mode 100644 index 0000000..bf0e865 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/WorkoutWeekMessageGenerator.java @@ -0,0 +1,10 @@ +package com.mykhailotiutiun.repcounterbot.message; + +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; + +public interface WorkoutWeekMessageGenerator { + + SendMessage getCurrentWorkoutWeekSendMessage(String chatId); + EditMessageText getCurrentWorkoutWeekEditMessage(String chatId, Integer messageId); +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/MainMenuServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/MainMenuMessageGeneratorImpl.java similarity index 66% rename from src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/MainMenuServiceImpl.java rename to src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/MainMenuMessageGeneratorImpl.java index eae70ff..fa99645 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/MainMenuServiceImpl.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/MainMenuMessageGeneratorImpl.java @@ -1,9 +1,8 @@ -package com.mykhailotiutiun.repcounterbot.service.Impl; +package com.mykhailotiutiun.repcounterbot.message.impl; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; -import com.mykhailotiutiun.repcounterbot.service.MainMenuService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; +import com.mykhailotiutiun.repcounterbot.message.MainMenuMessageGenerator; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; +import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; @@ -15,29 +14,28 @@ import java.util.ArrayList; import java.util.List; -@Slf4j -@Service -public class MainMenuServiceImpl implements MainMenuService { +@Component +public class MainMenuMessageGeneratorImpl implements MainMenuMessageGenerator { - private final LocaleMessageService localeMessageService; + private final LocaleMessageUtil localeMessageUtil; - public MainMenuServiceImpl(LocaleMessageService localeMessageService) { - this.localeMessageService = localeMessageService; + public MainMenuMessageGeneratorImpl(LocaleMessageUtil localeMessageUtil) { + this.localeMessageUtil = localeMessageUtil; } @Override public SendMessage getMainMenuMessage(String chatId, String firstName) { - return createMessageWithKeyboard(chatId, localeMessageService.getMessage("reply.main-menu.greeting", chatId) + firstName, getMainMenuKeyboardMarkup(chatId)); + return createMessageWithKeyboard(chatId, localeMessageUtil.getMessage("reply.main-menu.greeting", chatId) + firstName, getMainMenuKeyboardMarkup(chatId)); } @Override public EditMessageText getAreYouSureMessage(String chatId, Integer messageId, String okCallback, String cancelCallback) { - EditMessageText editMessageText = new EditMessageText(localeMessageService.getMessage("reply.are-you-sure", chatId)); + EditMessageText editMessageText = new EditMessageText(localeMessageUtil.getMessage("reply.are-you-sure", chatId)); editMessageText.setChatId(chatId); editMessageText.setMessageId(messageId); - InlineKeyboardButton okButton = InlineKeyboardButton.builder().text(localeMessageService.getMessage("reply.are-you-sure.keyboard.ok", chatId)).callbackData(okCallback).build(); - InlineKeyboardButton cancelButton = InlineKeyboardButton.builder().text(localeMessageService.getMessage("reply.are-you-sure.keyboard.cancel", chatId)).callbackData(cancelCallback).build(); + InlineKeyboardButton okButton = InlineKeyboardButton.builder().text(localeMessageUtil.getMessage("reply.are-you-sure.keyboard.ok", chatId)).callbackData(okCallback).build(); + InlineKeyboardButton cancelButton = InlineKeyboardButton.builder().text(localeMessageUtil.getMessage("reply.are-you-sure.keyboard.cancel", chatId)).callbackData(cancelCallback).build(); editMessageText.setReplyMarkup(InlineKeyboardMarkup.builder().keyboardRow(List.of(okButton, cancelButton)).build()); @@ -46,7 +44,7 @@ public EditMessageText getAreYouSureMessage(String chatId, Integer messageId, St @Override public InlineKeyboardMarkup getBackButtonInlineKeyboard(String chatId, String backButtonCallbackData) { - InlineKeyboardButton backButton = new InlineKeyboardButton(localeMessageService.getMessage("reply.keyboard.back", chatId)); + InlineKeyboardButton backButton = new InlineKeyboardButton(localeMessageUtil.getMessage("reply.keyboard.back", chatId)); backButton.setCallbackData(backButtonCallbackData); return InlineKeyboardMarkup.builder().keyboardRow(List.of(backButton)).build(); } @@ -73,8 +71,8 @@ private ReplyKeyboardMarkup getMainMenuKeyboardMarkup(String chatId) { KeyboardRow row1 = new KeyboardRow(); KeyboardRow row2 = new KeyboardRow(); - row1.add(new KeyboardButton(localeMessageService.getMessage("reply.main-menu.keyboard.recent-week", chatId))); - row2.add(new KeyboardButton(localeMessageService.getMessage("reply.main-menu.keyboard.change-lang", chatId))); + row1.add(new KeyboardButton(localeMessageUtil.getMessage("reply.main-menu.keyboard.recent-week", chatId))); + row2.add(new KeyboardButton(localeMessageUtil.getMessage("reply.main-menu.keyboard.change-lang", chatId))); keyboard.add(row1); keyboard.add(row2); replyKeyboardMarkup.setKeyboard(keyboard); diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutDayMessageGeneratorImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutDayMessageGeneratorImpl.java new file mode 100644 index 0000000..c69b8e8 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutDayMessageGeneratorImpl.java @@ -0,0 +1,111 @@ +package com.mykhailotiutiun.repcounterbot.message.impl; + +import com.mykhailotiutiun.repcounterbot.message.WorkoutDayMessageGenerator; +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; +import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; +import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; +import org.springframework.stereotype.Component; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +@Component +public class WorkoutDayMessageGeneratorImpl implements WorkoutDayMessageGenerator { + + private final WorkoutDayService workoutDayService; + private final LocaleMessageUtil localeMessageUtil; + private final WorkoutExerciseService workoutExerciseService; + + public WorkoutDayMessageGeneratorImpl(WorkoutDayService workoutDayService, LocaleMessageUtil localeMessageUtil, WorkoutExerciseService workoutExerciseService) { + this.workoutDayService = workoutDayService; + this.localeMessageUtil = localeMessageUtil; + this.workoutExerciseService = workoutExerciseService; + } + + @Override + public SendMessage getSelectWorkoutDaySendMessage(String chatId, Long workoutDayId) { + WorkoutDay workoutDay = workoutDayService.getById(workoutDayId); + SendMessage sendMessage = new SendMessage(chatId, workoutDay.print(localeMessageUtil.getMessage("print.workout-day.is-rest-day", chatId), localeMessageUtil.getMessage("print.workout-day.type-not-set", chatId), localeMessageUtil.getLocalTag(chatId))); + sendMessage.setReplyMarkup(getInlineKeyboardMarkupForWorkoutDay(workoutDay, workoutExerciseService.getAllByWorkoutDay(workoutDay), chatId)); + + return sendMessage; + } + + @Override + public EditMessageText getSelectWorkoutDayEditMessage(String chatId, Integer messageId, Long workoutDayId) { + WorkoutDay workoutDay = workoutDayService.getById(workoutDayId); + EditMessageText editMessageText = new EditMessageText(workoutDay.print(localeMessageUtil.getMessage("print.workout-day.is-rest-day", chatId), localeMessageUtil.getMessage("print.workout-day.type-not-set", chatId), localeMessageUtil.getLocalTag(chatId))); + editMessageText.setChatId(chatId); + editMessageText.setMessageId(messageId); + editMessageText.setReplyMarkup(getInlineKeyboardMarkupForWorkoutDay(workoutDay, workoutExerciseService.getAllByWorkoutDay(workoutDay), chatId)); + + return editMessageText; + } + + private InlineKeyboardMarkup getInlineKeyboardMarkupForWorkoutDay(WorkoutDay workoutDay, List workoutExercises, String chatId) { + List> keyboard = new ArrayList<>(); + + if (!workoutExercises.isEmpty()) { + workoutExercises.sort(Comparator.comparingInt(WorkoutExercise::getNumber)); + + workoutExercises.forEach(workoutExercise -> { + List row = new ArrayList<>(); + + InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton(workoutExercise.printForWorkoutDayKeyboard()); + inlineKeyboardButton.setCallbackData("/select-WorkoutExercise:" + workoutExercise.getId()); + row.add(inlineKeyboardButton); + + keyboard.add(row); + }); + } + + // Add exercise + if ((workoutDay.isWorkoutDay() != null) && workoutDay.isWorkoutDay()) { + List rowCreateWorkoutExercise = new ArrayList<>(); + InlineKeyboardButton buttonCreateWorkoutExercise = new InlineKeyboardButton(localeMessageUtil.getMessage("reply.workout-day.keyboard.add-exercise", chatId)); + buttonCreateWorkoutExercise.setCallbackData("/create-request-WorkoutExercise:" + workoutDay.getId()); + rowCreateWorkoutExercise.add(buttonCreateWorkoutExercise); + keyboard.add(rowCreateWorkoutExercise); + } + + List lastRow = new ArrayList<>(); + + //Change name + if (workoutDay.getIsWorkoutDay() != null && workoutDay.getIsWorkoutDay()) { + InlineKeyboardButton setNameButton = new InlineKeyboardButton(localeMessageUtil.getMessage("reply.change-name", chatId)); + setNameButton.setCallbackData("/set-name-request-WorkoutDay:" + workoutDay.getId()); + lastRow.add(setNameButton); + } + + //Create workout + if (workoutDay.getIsWorkoutDay() == null || !workoutDay.getIsWorkoutDay()) { + InlineKeyboardButton setNameButton = new InlineKeyboardButton(localeMessageUtil.getMessage("reply.workout-day.keyboard.create-workout-request", chatId)); + setNameButton.setCallbackData("/set-name-request-WorkoutDay:" + workoutDay.getId()); + lastRow.add(setNameButton); + } + + //Set rest day + if (workoutDay.getIsWorkoutDay() == null || workoutDay.getIsWorkoutDay()) { + InlineKeyboardButton setRestDayButton = new InlineKeyboardButton(localeMessageUtil.getMessage("reply.workout-day.keyboard.set-as-rest-day", chatId)); + setRestDayButton.setCallbackData("/set-rest-request-WorkoutDay:" + workoutDay.getId()); + lastRow.add(setRestDayButton); + } + + keyboard.add(lastRow); + + List backButtonRow = new ArrayList<>(); + InlineKeyboardButton backButton = new InlineKeyboardButton(localeMessageUtil.getMessage("reply.keyboard.back", chatId)); + backButton.setCallbackData("/select-current-WorkoutWeek"); + backButtonRow.add(backButton); + + keyboard.add(backButtonRow); + return new InlineKeyboardMarkup(keyboard); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutExerciseMessageGeneratorImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutExerciseMessageGeneratorImpl.java new file mode 100644 index 0000000..3af3cf4 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutExerciseMessageGeneratorImpl.java @@ -0,0 +1,90 @@ +package com.mykhailotiutiun.repcounterbot.message.impl; + +import com.mykhailotiutiun.repcounterbot.message.WorkoutExerciseMessageGenerator; +import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; +import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; +import org.springframework.stereotype.Component; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class WorkoutExerciseMessageGeneratorImpl implements WorkoutExerciseMessageGenerator { + + private final LocaleMessageUtil localeMessageUtil; + private final WorkoutExerciseService workoutExerciseService; + + public WorkoutExerciseMessageGeneratorImpl(LocaleMessageUtil localeMessageUtil, WorkoutExerciseService workoutExerciseService) { + this.localeMessageUtil = localeMessageUtil; + this.workoutExerciseService = workoutExerciseService; + } + + @Override + public SendMessage getWorkoutExerciseSendMessage(String chatId, Long workoutExerciseId) { + WorkoutExercise workoutExercise = workoutExerciseService.getById(workoutExerciseId); + + SendMessage sendMessage = new SendMessage(chatId, workoutExercise.printForWorkoutExercise(localeMessageUtil.getMessage("print.workout-exercise.for-workout-exercise-reply", chatId), localeMessageUtil.getMessage("print.workout-set.pattern", chatId))); + sendMessage.setReplyMarkup(getInlineKeyboardMarkupForWorkoutExercise(chatId, workoutExercise)); + return sendMessage; + } + + @Override + public EditMessageText getWorkoutExerciseEditMessage(String chatId, Integer messageId, Long workoutExerciseId, Boolean isOnEditPage) { + WorkoutExercise workoutExercise = workoutExerciseService.getById(workoutExerciseId); + + EditMessageText editMessageText = new EditMessageText(workoutExercise.printForWorkoutExercise(localeMessageUtil.getMessage("print.workout-exercise.for-workout-exercise-reply", chatId), localeMessageUtil.getMessage("print.workout-set.pattern", chatId))); + editMessageText.setChatId(chatId); + editMessageText.setMessageId(messageId); + + if(isOnEditPage){ + editMessageText.setReplyMarkup(getInlineKeyboardMarkupForEditWorkoutExercise(chatId, workoutExercise)); + } else { + editMessageText.setReplyMarkup(getInlineKeyboardMarkupForWorkoutExercise(chatId, workoutExercise)); + } + return editMessageText; + } + + private InlineKeyboardMarkup getInlineKeyboardMarkupForWorkoutExercise(String chatId, WorkoutExercise workoutExercise) { + List> keyboard = new ArrayList<>(); + + workoutExercise.getWorkoutSets().forEach(workoutSet -> { + keyboard.add(getButtonRow(workoutSet.print(localeMessageUtil.getMessage("print.workout-set.pattern", chatId)), "/select-WorkoutSet:" + workoutSet.getId())); + }); + + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.workout-exercise.keyboard.set-sets-request", chatId), "/set-request-WorkoutSet:" + workoutExercise.getId())); + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.workout-exercise.keyboard.edit", chatId), "/edit-WorkoutExercise:" + workoutExercise.getId())); + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.keyboard.back", chatId), "/select-WorkoutDay:" + workoutExercise.getWorkoutDay().getId())); + + return new InlineKeyboardMarkup(keyboard); + } + + private InlineKeyboardMarkup getInlineKeyboardMarkupForEditWorkoutExercise(String chatId, WorkoutExercise workoutExercise) { + List> keyboard = new ArrayList<>(); + + if(workoutExercise.getNumber() > 1){ + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.keyboard.move-up", chatId), "/move-up-request-WorkoutExercise:" + workoutExercise.getId())); + } + + if(workoutExercise.getNumber() < workoutExerciseService.getLatestNumberByWorkoutDay(workoutExercise.getWorkoutDay())){ + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.keyboard.move-down", chatId), "/move-down-request-WorkoutExercise:" + workoutExercise.getId())); + } + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.change-name", chatId), "/change-name-request-WorkoutExercise:" + workoutExercise.getId())); + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.delete", chatId), "/delete-request-WorkoutExercise:" + workoutExercise.getId())); + keyboard.add(getButtonRow(localeMessageUtil.getMessage("reply.keyboard.back", chatId), "/select-WorkoutExercise:" + workoutExercise.getId())); + + return new InlineKeyboardMarkup(keyboard); + } + + private List getButtonRow(String buttonText, String buttonCallback){ + List buttonRow = new ArrayList<>(); + InlineKeyboardButton button = new InlineKeyboardButton(buttonText); + button.setCallbackData(buttonCallback); + buttonRow.add(button); + return buttonRow; + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutWeekMessageGeneratorImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutWeekMessageGeneratorImpl.java new file mode 100644 index 0000000..6037e27 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/message/impl/WorkoutWeekMessageGeneratorImpl.java @@ -0,0 +1,74 @@ +package com.mykhailotiutiun.repcounterbot.message.impl; + +import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; +import com.mykhailotiutiun.repcounterbot.message.WorkoutWeekMessageGenerator; +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; +import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; +import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; +import org.springframework.stereotype.Component; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class WorkoutWeekMessageGeneratorImpl implements WorkoutWeekMessageGenerator { + + private final LocaleMessageUtil localeMessageUtil; + private final WorkoutDayService workoutDayService; + private final WorkoutWeekService workoutWeekService; + + public WorkoutWeekMessageGeneratorImpl(LocaleMessageUtil localeMessageUtil, WorkoutDayService workoutDayService, WorkoutWeekService workoutWeekService) { + this.localeMessageUtil = localeMessageUtil; + this.workoutDayService = workoutDayService; + this.workoutWeekService = workoutWeekService; + } + + @Override + public SendMessage getCurrentWorkoutWeekSendMessage(String chatId) { + WorkoutWeek currentWorkoutWeek; + try { + currentWorkoutWeek = workoutWeekService.getCurrentWorkoutWeekByUserId(Long.valueOf(chatId)); + } catch (EntityNotFoundException e) { + return new SendMessage(chatId, localeMessageUtil.getMessage("reply.error", chatId)); + } + + SendMessage sendMessage = new SendMessage(chatId, currentWorkoutWeek.print(localeMessageUtil.getMessage("print.workout-week", chatId))); + + sendMessage.setReplyMarkup(getInlineKeyboardForWeek(workoutDayService.getAllByWorkoutWeek(currentWorkoutWeek), chatId)); + + return sendMessage; + } + + @Override + public EditMessageText getCurrentWorkoutWeekEditMessage(String chatId, Integer messageId){ + WorkoutWeek currentWorkoutWeek = workoutWeekService.getCurrentWorkoutWeekByUserId(Long.valueOf(chatId)); + + EditMessageText editMessageText =new EditMessageText(currentWorkoutWeek.print(localeMessageUtil.getMessage("print.workout-week", chatId))); + editMessageText.setChatId(chatId); + editMessageText.setMessageId(messageId); + editMessageText.setReplyMarkup(getInlineKeyboardForWeek(workoutDayService.getAllByWorkoutWeek(currentWorkoutWeek), chatId)); + return editMessageText; + } + + private InlineKeyboardMarkup getInlineKeyboardForWeek(List workoutDays, String chatId) { + List> keyboard = new ArrayList<>(); + + workoutDays.forEach(workoutDay -> { + InlineKeyboardButton keyboardButton = new InlineKeyboardButton(workoutDay.print(localeMessageUtil.getMessage("print.workout-day.is-rest-day", chatId), localeMessageUtil.getMessage("print.workout-day.type-not-set", chatId), localeMessageUtil.getLocalTag(chatId))); + keyboardButton.setCallbackData("/select-WorkoutDay:" + workoutDay.getId()); + + List inlineKeyboardButtons = new ArrayList<>(); + inlineKeyboardButtons.add(keyboardButton); + + keyboard.add(inlineKeyboardButtons); + }); + + return new InlineKeyboardMarkup(keyboard); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/model/User.java b/src/main/java/com/mykhailotiutiun/repcounterbot/model/User.java index 72d1a3b..57e37d0 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/model/User.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/model/User.java @@ -1,29 +1,18 @@ package com.mykhailotiutiun.repcounterbot.model; import lombok.*; -import lombok.experimental.FieldDefaults; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; @Getter @Setter @ToString -@Document(collection = "users") -@FieldDefaults(level = AccessLevel.PRIVATE) +@Builder @NoArgsConstructor @AllArgsConstructor public class User { - @Id - Long id; + private Long id; + private String username; + private String localTag = "en-US"; - String username; - - String localTag = "en-US"; - - public User(Long id, String username) { - this.id = id; - this.username = username; - } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutDay.java b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutDay.java index 5b0c5a9..7c56d5c 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutDay.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutDay.java @@ -1,10 +1,6 @@ package com.mykhailotiutiun.repcounterbot.model; import lombok.*; -import lombok.experimental.FieldDefaults; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; -import org.springframework.data.mongodb.core.mapping.DocumentReference; import org.springframework.util.StringUtils; import java.time.LocalDate; @@ -16,30 +12,16 @@ @Getter @Setter @ToString -@Document(collection = "workout-days") -@FieldDefaults(level = AccessLevel.PRIVATE) +@Builder @NoArgsConstructor @AllArgsConstructor public class WorkoutDay { - @Id - String id; - - @DocumentReference(lazy = true) - WorkoutWeek workoutWeek; - - String name; - - LocalDate date; - - Boolean isWorkoutDay; - - public WorkoutDay(WorkoutWeek workoutWeek, String name, LocalDate date, Boolean isWorkoutDay) { - this.workoutWeek = workoutWeek; - this.name = name; - this.date = date; - this.isWorkoutDay = isWorkoutDay; - } + private Long id; + private String name; + private LocalDate date; + private Boolean isWorkoutDay; + private WorkoutWeek workoutWeek; public Boolean isWorkoutDay() { return isWorkoutDay; diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutExercise.java b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutExercise.java index ab0a979..13b2442 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutExercise.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutExercise.java @@ -1,11 +1,6 @@ package com.mykhailotiutiun.repcounterbot.model; import lombok.*; -import lombok.experimental.FieldDefaults; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.DBRef; -import org.springframework.data.mongodb.core.mapping.Document; -import org.springframework.data.mongodb.core.mapping.DocumentReference; import java.util.ArrayList; import java.util.List; @@ -13,39 +8,18 @@ @Getter @Setter @ToString -@Document(collection = "workout-exercises") -@FieldDefaults(level = AccessLevel.PRIVATE) +@Builder @NoArgsConstructor @AllArgsConstructor public class WorkoutExercise { - @Id - String id; + private Long id; + private Byte number; + private String name; + private WorkoutDay workoutDay; - Byte number; - - String name; - - @DocumentReference(lazy = true) - WorkoutDay workoutDay; - - @DBRef(lazy = true) - List workoutSets = new ArrayList<>(); - - @DBRef(lazy = true) - List prevWorkoutSets = new ArrayList<>(); - - public WorkoutExercise(String name, WorkoutDay workoutDay) { - this.name = name; - this.workoutDay = workoutDay; - } - - public WorkoutExercise(Byte number, String name, WorkoutDay workoutDay, List prevWorkoutSets) { - this.number = number; - this.name = name; - this.workoutDay = workoutDay; - this.prevWorkoutSets = prevWorkoutSets; - } + private List workoutSets = new ArrayList<>(); + private List prevWorkoutSets = new ArrayList<>(); public String printForWorkoutExercise(String onPrevWorkoutMessage, String workoutSetsPrintPattern){ diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutSet.java b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutSet.java index 34d87da..dd3f265 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutSet.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutSet.java @@ -1,31 +1,19 @@ package com.mykhailotiutiun.repcounterbot.model; import lombok.*; -import lombok.experimental.FieldDefaults; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; @Getter @Setter @ToString -@Document(collection = "workout-set") -@FieldDefaults(level = AccessLevel.PRIVATE) +@Builder @NoArgsConstructor @AllArgsConstructor public class WorkoutSet { - @Id - String id; - - Integer number; - Integer reps; - Integer weight; - - public WorkoutSet(Integer number, Integer reps, Integer weight) { - this.number = number; - this.reps = reps; - this.weight = weight; - } + private Long id; + private Integer number; + private Integer reps; + private Integer weight; public String print(String pattern) { return String.format(pattern, number, weight, reps); diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutWeek.java b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutWeek.java index 2c5330a..d40db7f 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutWeek.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/model/WorkoutWeek.java @@ -1,10 +1,6 @@ package com.mykhailotiutiun.repcounterbot.model; import lombok.*; -import lombok.experimental.FieldDefaults; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; -import org.springframework.data.mongodb.core.mapping.DocumentReference; import java.time.LocalDate; import java.time.format.DateTimeFormatter; @@ -12,28 +8,16 @@ @Getter @Setter @ToString -@Document(collection = "workout-weeks") -@FieldDefaults(level = AccessLevel.PRIVATE) +@Builder @NoArgsConstructor @AllArgsConstructor public class WorkoutWeek { - @Id - String id; - - @DocumentReference(lazy = true) - User user; - - Boolean current = true; - - LocalDate weekStartDate; - LocalDate weekEndDate; - - public WorkoutWeek(User user, LocalDate weekStartDate, LocalDate weekEndDate) { - this.user = user; - this.weekStartDate = weekStartDate; - this.weekEndDate = weekEndDate; - } + private Long id; + private User user; + private Boolean current = true; + private LocalDate weekStartDate; + private LocalDate weekEndDate; public Boolean isCurrent() { return current; diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/UserRepository.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/UserRepository.java index 5263b9c..d01c858 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/UserRepository.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/UserRepository.java @@ -1,8 +1,13 @@ package com.mykhailotiutiun.repcounterbot.repository; import com.mykhailotiutiun.repcounterbot.model.User; -import org.springframework.data.mongodb.repository.MongoRepository; -public interface UserRepository extends MongoRepository { +import java.util.Optional; +public interface UserRepository { + + Optional findById(Long id); + boolean existsById(Long id); + + User save(User user); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutDayRepository.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutDayRepository.java index cc8de59..3f66d52 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutDayRepository.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutDayRepository.java @@ -2,11 +2,14 @@ import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; -import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; +import java.util.Optional; -public interface WorkoutDayRepository extends MongoRepository { +public interface WorkoutDayRepository { - List findAllByWorkoutWeek(WorkoutWeek WorkoutWeek); + Optional findById(Long id); + List findAllByWorkoutWeek(WorkoutWeek workoutWeek); + + WorkoutDay save(WorkoutDay workoutDay); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutExerciseRepository.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutExerciseRepository.java index a7bcc0a..36f9137 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutExerciseRepository.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutExerciseRepository.java @@ -2,16 +2,18 @@ import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; -import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; import java.util.Optional; -public interface WorkoutExerciseRepository extends MongoRepository { +public interface WorkoutExerciseRepository { + Optional findById(Long id); Optional findByNumberAndWorkoutDay(Byte number, WorkoutDay workoutDay); List findAllByWorkoutDayOrderByNumberDesc(WorkoutDay workoutDay); - List findAllByWorkoutDay(WorkoutDay workoutDay); + WorkoutExercise save(WorkoutExercise workoutExercise); + + void deleteById(Long id); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutSetRepository.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutSetRepository.java index be70401..5c8a37f 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutSetRepository.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutSetRepository.java @@ -1,7 +1,13 @@ package com.mykhailotiutiun.repcounterbot.repository; +import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; -import org.springframework.data.mongodb.repository.MongoRepository; -public interface WorkoutSetRepository extends MongoRepository { +import java.util.List; + +public interface WorkoutSetRepository { + + List findAllByWorkoutExercise(WorkoutExercise workoutExercise); + List findAllPrevSetsByWorkoutExercise(WorkoutExercise workoutExercise); + WorkoutSet save(WorkoutSet workoutSet); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutWeekRepository.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutWeekRepository.java index ccdca0b..28c51af 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutWeekRepository.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/WorkoutWeekRepository.java @@ -1,11 +1,13 @@ package com.mykhailotiutiun.repcounterbot.repository; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; -import org.springframework.data.mongodb.repository.MongoRepository; import java.util.Optional; -public interface WorkoutWeekRepository extends MongoRepository { +public interface WorkoutWeekRepository { + Optional findById(Long id); Optional findByUserIdAndCurrent(Long userId, Boolean isCurrent); + + WorkoutWeek save(WorkoutWeek workoutWeek); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/UserRepositoryImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/UserRepositoryImpl.java new file mode 100644 index 0000000..5fb07d0 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/UserRepositoryImpl.java @@ -0,0 +1,39 @@ +package com.mykhailotiutiun.repcounterbot.repository.impl; + +import com.mykhailotiutiun.repcounterbot.mapper.UserMapper; +import com.mykhailotiutiun.repcounterbot.model.User; +import com.mykhailotiutiun.repcounterbot.repository.UserRepository; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public class UserRepositoryImpl implements UserRepository { + + private final JdbcTemplate jdbcTemplate; + + public UserRepositoryImpl(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + @Override + public Optional findById(Long id) { + return Optional.ofNullable(jdbcTemplate.queryForObject("SELECT * FROM bot_users WHERE id = ?", new UserMapper(), id)); + } + + @Override + public boolean existsById(Long id) { + return Boolean.TRUE.equals(jdbcTemplate.queryForObject("SELECT EXISTS(SELECT id FROM bot_users WHERE id = ?)", Boolean.class, id)); + } + + @Override + public User save(User user) { + if (existsById(user.getId())) { + jdbcTemplate.update("UPDATE bot_users SET username = ?, local_tag = ? WHERE id = ?", user.getUsername(), user.getLocalTag(), user.getId()); + } else { + jdbcTemplate.update("INSERT INTO bot_users (id, username, local_tag) VALUES (?, ?, ?)", user.getId(), user.getUsername(), user.getLocalTag()); + } + return user; + } +} \ No newline at end of file diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutDayRepositoryImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutDayRepositoryImpl.java new file mode 100644 index 0000000..fd88a4b --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutDayRepositoryImpl.java @@ -0,0 +1,73 @@ +package com.mykhailotiutiun.repcounterbot.repository.impl; + +import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; +import com.mykhailotiutiun.repcounterbot.mapper.WorkoutDayMapper; +import com.mykhailotiutiun.repcounterbot.mapper.WorkoutWeekMapper; +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutDayRepository; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutWeekRepository; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.simple.SimpleJdbcInsert; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Repository +public class WorkoutDayRepositoryImpl implements WorkoutDayRepository { + + private final JdbcTemplate jdbcTemplate; + private final WorkoutWeekRepository workoutWeekRepository; + + public WorkoutDayRepositoryImpl(JdbcTemplate jdbcTemplate, WorkoutWeekRepository workoutWeekRepository) { + this.jdbcTemplate = jdbcTemplate; + this.workoutWeekRepository = workoutWeekRepository; + } + + private boolean existsById(Long id) { + return Boolean.TRUE.equals(jdbcTemplate.queryForObject("SELECT EXISTS(SELECT 1 FROM workout_days WHERE id = ?)", Boolean.class, id)); + } + + @Override + public Optional findById(Long id) { + WorkoutDay workoutDay = jdbcTemplate.queryForObject("SELECT * FROM workout_days WHERE id = ?", new WorkoutDayMapper(), id); + if (workoutDay != null) { + workoutDay.setWorkoutWeek(workoutWeekRepository.findById(workoutDay.getWorkoutWeek().getId()).orElseThrow(EntityNotFoundException::new)); + } + return Optional.ofNullable(workoutDay); + } + + @Override + public List findAllByWorkoutWeek(WorkoutWeek workoutWeek) { + List workoutDays = jdbcTemplate.query("SELECT * FROM workout_days WHERE workout_week_id = ?", new WorkoutDayMapper(), workoutWeek.getId()); + if (!workoutDays.isEmpty()){ + WorkoutWeek workoutWeekFromDb = jdbcTemplate.queryForObject("SELECT * FROM workout_weeks where id = ?", new WorkoutWeekMapper(), workoutWeek.getId()); + workoutDays.forEach(workoutDay -> workoutDay.setWorkoutWeek(workoutWeekFromDb)); + } + return workoutDays; + } + + @Override + public WorkoutDay save(WorkoutDay workoutDay) { + if(existsById(workoutDay.getId())){ + jdbcTemplate.update("UPDATE workout_days SET name = ?, is_workout_day = ?, date = ?, workout_week_id = ? WHERE id = ?", + workoutDay.getName(), + workoutDay.getIsWorkoutDay(), + workoutDay.getDate(), + workoutDay.getWorkoutWeek().getId(), + workoutDay.getId()); + } else { + SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("workout_days").usingGeneratedKeyColumns("id"); + Map parameters = new HashMap<>(4); + parameters.put("name", workoutDay.getName()); + parameters.put("date", workoutDay.getDate()); + parameters.put("is_workout_day", workoutDay.isWorkoutDay()); + parameters.put("workout_week_id", workoutDay.getWorkoutWeek().getId()); + workoutDay.setId((Long) simpleJdbcInsert.executeAndReturnKey(parameters)); + } + return workoutDay; + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutExerciseRepositoryImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutExerciseRepositoryImpl.java new file mode 100644 index 0000000..11e7585 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutExerciseRepositoryImpl.java @@ -0,0 +1,119 @@ +package com.mykhailotiutiun.repcounterbot.repository.impl; + +import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; +import com.mykhailotiutiun.repcounterbot.mapper.WorkoutExerciseMapper; +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; +import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutDayRepository; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutExerciseRepository; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutSetRepository; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.simple.SimpleJdbcInsert; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +@Repository +public class WorkoutExerciseRepositoryImpl implements WorkoutExerciseRepository { + + private final JdbcTemplate jdbcTemplate; + private final WorkoutDayRepository workoutDayRepository; + private final WorkoutSetRepository workoutSetRepository; + + public WorkoutExerciseRepositoryImpl(JdbcTemplate jdbcTemplate, WorkoutDayRepository workoutDayRepository, WorkoutSetRepository workoutSetRepository) { + this.jdbcTemplate = jdbcTemplate; + this.workoutDayRepository = workoutDayRepository; + this.workoutSetRepository = workoutSetRepository; + } + + @Override + public Optional findById(Long id) { + WorkoutExercise workoutExercise = jdbcTemplate.queryForObject("SELECT * FROM workout_exercises WHERE id = ?", new WorkoutExerciseMapper(), id); + if (workoutExercise != null) { + workoutExercise.setWorkoutDay(workoutDayRepository.findById(workoutExercise.getWorkoutDay().getId()).orElseThrow(EntityNotFoundException::new)); + workoutExercise.setWorkoutSets(workoutSetRepository.findAllByWorkoutExercise(workoutExercise)); + } + return Optional.ofNullable(workoutExercise); + } + + @Override + public Optional findByNumberAndWorkoutDay(Byte number, WorkoutDay workoutDay) { + WorkoutExercise workoutExercise = jdbcTemplate.queryForObject("SELECT * FROM workout_exercises WHERE number = ? AND workout_day_id = ?", new WorkoutExerciseMapper(), number, workoutDay.getId()); + if (workoutExercise != null) { + workoutExercise.setWorkoutDay(workoutDayRepository.findById(workoutExercise.getWorkoutDay().getId()).orElseThrow(EntityNotFoundException::new)); + workoutExercise.setWorkoutSets(workoutSetRepository.findAllByWorkoutExercise(workoutExercise)); + workoutExercise.setPrevWorkoutSets(workoutSetRepository.findAllPrevSetsByWorkoutExercise(workoutExercise)); + } + return Optional.ofNullable(workoutExercise); + } + + @Override + public List findAllByWorkoutDayOrderByNumberDesc(WorkoutDay workoutDay) { + return jdbcTemplate.query("SELECT * FROM workout_exercises WHERE workout_day_id = ? ORDER BY number DESC", new WorkoutExerciseMapper(), workoutDay.getId()); + } + + private boolean existsById(Long id) { + return Boolean.TRUE.equals(jdbcTemplate.queryForObject("SELECT EXISTS(SELECT 1 FROM workout_exercises WHERE id = ?)", Boolean.class, id)); + } + + @Override + public WorkoutExercise save(WorkoutExercise workoutExercise) { + if(existsById(workoutExercise.getId())){ + jdbcTemplate.update("UPDATE workout_exercises SET number = ?, name = ?, workout_day_id = ? WHERE id = ?", + workoutExercise.getNumber(), + workoutExercise.getName(), + workoutExercise.getWorkoutDay().getId(), + workoutExercise.getId()); + } else { + SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("workout_exercises").usingGeneratedKeyColumns("id"); + Map parameters = new HashMap<>(3); + parameters.put("number", workoutExercise.getNumber()); + parameters.put("workout_day_id", workoutExercise.getWorkoutDay().getId()); + parameters.put("name", workoutExercise.getName()); + workoutExercise.setId((Long) simpleJdbcInsert.executeAndReturnKey(parameters)); + } + updateWorkoutSets(workoutExercise); + updatePrevWorkoutSets(workoutExercise); + return workoutExercise; + } + + private void updateWorkoutSets(WorkoutExercise workoutExercise){ + if (workoutExercise.getWorkoutSets() == null || workoutExercise.getWorkoutSets().isEmpty()){ + return; + } + List workoutSets = workoutExercise.getWorkoutSets(); + String sql = "UPDATE workout_sets SET workout_ex_id = ? WHERE id IN (" + + workoutSets.stream().map(id -> "?").collect(Collectors.joining(",")) + ")"; + Object[] params = new Object[workoutSets.size() + 1]; + params[0] = workoutExercise.getId(); + for (int i = 0; i < workoutSets.size(); i++){ + params[i + 1] = workoutSets.get(i).getId(); + } + jdbcTemplate.update(sql, params); + } + + private void updatePrevWorkoutSets(WorkoutExercise workoutExercise) { + if (workoutExercise.getPrevWorkoutSets() == null || workoutExercise.getPrevWorkoutSets().isEmpty()){ + return; + } + List workoutSets = workoutExercise.getPrevWorkoutSets(); + String sql = "UPDATE workout_sets SET prev_workout_ex_id = ? WHERE id IN (" + + workoutSets.stream().map(id -> "?").collect(Collectors.joining(",")) + ")"; + Object[] params = new Object[workoutSets.size() + 1]; + params[0] = workoutExercise.getId(); + for (int i = 0; i < workoutSets.size(); i++){ + params[i + 1] = workoutSets.get(i).getId(); + } + jdbcTemplate.update(sql, params); + } + + @Override + public void deleteById(Long id) { + jdbcTemplate.update("DELETE FROM workout_exercises WHERE id = ?", id); + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutSetRepositoryImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutSetRepositoryImpl.java new file mode 100644 index 0000000..e81d944 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutSetRepositoryImpl.java @@ -0,0 +1,56 @@ +package com.mykhailotiutiun.repcounterbot.repository.impl; + +import com.mykhailotiutiun.repcounterbot.mapper.WorkoutSetMapper; +import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; +import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutSetRepository; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.simple.SimpleJdbcInsert; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Repository +public class WorkoutSetRepositoryImpl implements WorkoutSetRepository { + + private final JdbcTemplate jdbcTemplate; + + public WorkoutSetRepositoryImpl(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + private boolean existsById(Long id) { + return Boolean.TRUE.equals(jdbcTemplate.queryForObject("SELECT EXISTS(SELECT 1 FROM workout_sets WHERE id = ?)", Boolean.class, id)); + } + + @Override + public List findAllByWorkoutExercise(WorkoutExercise workoutExercise) { + return jdbcTemplate.query("SELECT * FROM workout_sets WHERE workout_ex_id = ?", new WorkoutSetMapper(), workoutExercise.getId()); + } + + @Override + public List findAllPrevSetsByWorkoutExercise(WorkoutExercise workoutExercise) { + return jdbcTemplate.query("SELECT * FROM workout_sets WHERE prev_workout_ex_id = ?", new WorkoutSetMapper(), workoutExercise.getId()); + } + + @Override + public WorkoutSet save(WorkoutSet workoutSet) { + if(existsById(workoutSet.getId())) { + jdbcTemplate.update("UPDATE workout_sets SET number = ?, weight = ?, reps = ? WHERE id = ?", + workoutSet.getNumber(), + workoutSet.getWeight(), + workoutSet.getReps(), + workoutSet.getId()); + } else { + SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("workout_sets").usingGeneratedKeyColumns("id"); + Map parameters = new HashMap<>(3); + parameters.put("number", workoutSet.getNumber()); + parameters.put("reps", workoutSet.getReps()); + parameters.put("weight", workoutSet.getWeight()); + workoutSet.setId((Long) simpleJdbcInsert.executeAndReturnKey(parameters)); + } + return workoutSet; + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutWeekRepositoryImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutWeekRepositoryImpl.java new file mode 100644 index 0000000..0fe6634 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/repository/impl/WorkoutWeekRepositoryImpl.java @@ -0,0 +1,66 @@ +package com.mykhailotiutiun.repcounterbot.repository.impl; + +import com.mykhailotiutiun.repcounterbot.mapper.UserMapper; +import com.mykhailotiutiun.repcounterbot.mapper.WorkoutWeekMapper; +import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutWeekRepository; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.simple.SimpleJdbcInsert; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +@Repository +public class WorkoutWeekRepositoryImpl implements WorkoutWeekRepository { + + private final JdbcTemplate jdbcTemplate; + + public WorkoutWeekRepositoryImpl(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + private boolean existsById(Long id) { + return Boolean.TRUE.equals(jdbcTemplate.queryForObject("SELECT EXISTS(SELECT 1 FROM workout_weeks WHERE id = ?)", Boolean.class, id)); + } + + @Override + public Optional findById(Long id) { + WorkoutWeek workoutWeek = jdbcTemplate.queryForObject("SELECT * FROM workout_weeks WHERE id = ?", new WorkoutWeekMapper(), id); + if(workoutWeek != null){ + workoutWeek.setUser(jdbcTemplate.queryForObject("SELECT * FROM bot_users WHERE id = ?", new UserMapper(), workoutWeek.getUser().getId())); + } + return Optional.ofNullable(workoutWeek); + } + + @Override + public Optional findByUserIdAndCurrent(Long userId, Boolean isCurrent) { + WorkoutWeek workoutWeek = jdbcTemplate.queryForObject("SELECT * FROM workout_weeks WHERE user_id = ? AND current = ?", new WorkoutWeekMapper(), userId, isCurrent); + if(workoutWeek != null){ + workoutWeek.setUser(jdbcTemplate.queryForObject("SELECT * FROM bot_users WHERE id = ?", new UserMapper(), userId)); + } + return Optional.ofNullable(workoutWeek); + } + + @Override + public WorkoutWeek save(WorkoutWeek workoutWeek) { + if(existsById(workoutWeek.getId())){ + jdbcTemplate.update("UPDATE workout_weeks SET current = ?, week_start_date = ?, week_end_date = ?, user_id = ? WHERE id = ?", + workoutWeek.getCurrent(), + workoutWeek.getWeekStartDate(), + workoutWeek.getWeekEndDate(), + workoutWeek.getUser().getId(), + workoutWeek.getId()); + } else { + SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("workout_weeks").usingGeneratedKeyColumns("id"); + Map parameters = new HashMap<>(4); + parameters.put("current", workoutWeek.getCurrent()); + parameters.put("week_start_date", workoutWeek.getWeekStartDate()); + parameters.put("week_end_date", workoutWeek.getWeekEndDate()); + parameters.put("user_id", workoutWeek.getUser().getId()); + workoutWeek.setId((Long) simpleJdbcInsert.executeAndReturnKey(parameters)); + } + return workoutWeek; + } +} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/LocaleMessageServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/LocaleMessageServiceImpl.java deleted file mode 100644 index 18d78ce..0000000 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/LocaleMessageServiceImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.mykhailotiutiun.repcounterbot.service.Impl; - -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; -import com.mykhailotiutiun.repcounterbot.service.UserService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; - -import java.util.Locale; - -@Slf4j -@Service -public class LocaleMessageServiceImpl implements LocaleMessageService { - - private final MessageSource messageSource; - private final ChatDataCache chatDataCache; - private final UserService userService; - - public LocaleMessageServiceImpl(MessageSource messageSource, ChatDataCache chatDataCache, @Lazy UserService userService) { - this.messageSource = messageSource; - this.chatDataCache = chatDataCache; - this.userService = userService; - } - - @Override - public String getMessage(String messageCode, String chatId) { - return messageSource.getMessage(messageCode, null, Locale.forLanguageTag(getLocalTag(chatId))); - } - - @Override - public String getLocalTag(String chatId) { - String localeTag = chatDataCache.getUserSelectedLanguage(chatId); - if (localeTag == null) { - localeTag = userService.getUserById(Long.valueOf(chatId)).getLocalTag(); - chatDataCache.setUserSelectedLanguage(chatId, localeTag); - } - return localeTag; - } - -} diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/UserServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/UserServiceImpl.java index a915a53..c237014 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/UserServiceImpl.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/UserServiceImpl.java @@ -1,83 +1,82 @@ package com.mykhailotiutiun.repcounterbot.service.Impl; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedLanguageCache; import com.mykhailotiutiun.repcounterbot.exception.EntityAlreadyExistsException; import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; +import com.mykhailotiutiun.repcounterbot.language.SelectedLanguageProvider; import com.mykhailotiutiun.repcounterbot.model.User; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; import com.mykhailotiutiun.repcounterbot.repository.UserRepository; -import com.mykhailotiutiun.repcounterbot.service.LocalDateWeekService; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; import com.mykhailotiutiun.repcounterbot.service.UserService; import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; +import com.mykhailotiutiun.repcounterbot.util.LocalDateWeekUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; -import java.util.List; @Slf4j @Service -public class UserServiceImpl implements UserService { +public class UserServiceImpl implements UserService, SelectedLanguageProvider { private final UserRepository userRepository; private final WorkoutWeekService workoutWeekService; - private final LocalDateWeekService localDateWeekService; - private final ChatDataCache chatDataCache; + private final LocalDateWeekUtil localDateWeekUtil; + private final SelectedLanguageCache selectedLanguageCache; - public UserServiceImpl(UserRepository userRepository, WorkoutWeekService workoutWeekService, LocalDateWeekService localDateWeekService, LocaleMessageService localeMessageService, ChatDataCache chatDataCache) { + public UserServiceImpl(UserRepository userRepository, WorkoutWeekService workoutWeekService, LocalDateWeekUtil localDateWeekUtil, SelectedLanguageCache selectedLanguageCache) { this.userRepository = userRepository; this.workoutWeekService = workoutWeekService; - this.localDateWeekService = localDateWeekService; - this.chatDataCache = chatDataCache; + this.localDateWeekUtil = localDateWeekUtil; + this.selectedLanguageCache = selectedLanguageCache; } @Override - public User getUserById(Long id) { - log.trace("Get User with id: {}", id); + public User getById(Long id) { + log.trace("Get User by id: {}", id); return userRepository.findById(id).orElseThrow(EntityNotFoundException::new); } @Override - public List getAllUsers() { - log.trace("Get all Users"); - return userRepository.findAll(); - } - - @Override + @Transactional public void create(User user) throws EntityAlreadyExistsException { if (userRepository.existsById(user.getId())) { - throw new EntityAlreadyExistsException(String.format("User with this id(%d) already exists", user.getId())); + throw new EntityAlreadyExistsException(String.format("User with id(%d) already exists", user.getId())); } log.trace("Create User: {}", user); save(user); - workoutWeekService.create(new WorkoutWeek(user, localDateWeekService.getFirstDateOfWeekFromDate(LocalDate.now()), localDateWeekService.getLastDateOfWeekFromDate(LocalDate.now()))); + workoutWeekService.create(WorkoutWeek.builder() + .user(user) + .current(true) + .weekStartDate(localDateWeekUtil.getFirstDateOfWeekFromDate(LocalDate.now())) + .weekEndDate(localDateWeekUtil.getLastDateOfWeekFromDate(LocalDate.now())) + .build()); } - @Override - public void save(User user) { + private void save(User user) { log.trace("Save User: {}", user); userRepository.save(user); } @Override - public void setUserLang(String userId, String localTag) { - User user = getUserById(Long.valueOf(userId)); + @Transactional + public void setUserLang(Long userId, String localTag) { + User user = getById(userId); - log.trace("Set localTag to User: {}", user); + log.trace("Set localTag for User: {}", user); user.setLocalTag(localTag); save(user); - chatDataCache.setUserSelectedLanguage(userId, localTag); + selectedLanguageCache.setSelectedLanguage(String.valueOf(userId), localTag); } @Override - public void deleteById(Long id) { - log.trace("Delete User with id: {}", id); - userRepository.deleteById(id); + public String getLocaleTag(String chatId) { + log.trace("Get User's local-tag by id: {}", chatId); + return userRepository.findById(Long.valueOf(chatId)).orElseThrow(EntityNotFoundException::new).getLocalTag(); } - } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutDayServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutDayServiceImpl.java index fcaced1..39bfad2 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutDayServiceImpl.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutDayServiceImpl.java @@ -2,20 +2,14 @@ import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; -import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; import com.mykhailotiutiun.repcounterbot.repository.WorkoutDayRepository; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; +import org.springframework.transaction.annotation.Transactional; -import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -25,39 +19,40 @@ public class WorkoutDayServiceImpl implements WorkoutDayService { private final WorkoutDayRepository workoutDayRepository; private final WorkoutExerciseService workoutExerciseService; - private final LocaleMessageService localeMessageService; - public WorkoutDayServiceImpl(WorkoutDayRepository workoutDayRepository, WorkoutExerciseService workoutExerciseService, LocaleMessageService localeMessageService) { + public WorkoutDayServiceImpl(WorkoutDayRepository workoutDayRepository, WorkoutExerciseService workoutExerciseService) { this.workoutDayRepository = workoutDayRepository; this.workoutExerciseService = workoutExerciseService; - this.localeMessageService = localeMessageService; } @Override - public WorkoutDay getWorkoutDayById(String id) { - log.trace("Get WorkoutDay with id: {}", id); + public WorkoutDay getById(Long id) { + log.trace("Get WorkoutDay by id: {}", id); return workoutDayRepository.findById(id).orElseThrow(EntityNotFoundException::new); } @Override - public List getAllWorkoutDaysByWorkoutWeek(WorkoutWeek workoutWeek) { + public List getAllByWorkoutWeek(WorkoutWeek workoutWeek) { log.trace("Get WorkoutDays by WorkoutWeek: {}", workoutWeek); - return workoutDayRepository.findAllByWorkoutWeek(workoutWeek); - } - - @Override - public List getAllWorkoutDays() { - log.trace("Get all WorkoutDays"); - return workoutDayRepository.findAll(); + List workoutDays = workoutDayRepository.findAllByWorkoutWeek(workoutWeek); + workoutDays.sort(Comparator.comparing(WorkoutDay::getDate)); + return workoutDays; } @Override + @Transactional public void createAllFromOldWorkoutWeek(WorkoutWeek oldWorkoutWeek, WorkoutWeek newWorkoutWeek) { - List workoutDays = getAllWorkoutDaysByWorkoutWeek(oldWorkoutWeek); + log.trace("Create all WorkoutDays from old WorkoutWeek: {}, {}", oldWorkoutWeek, newWorkoutWeek); + List workoutDays = getAllByWorkoutWeek(oldWorkoutWeek); for (int i = 0; i < workoutDays.size(); i++) { WorkoutDay workoutDayOld = workoutDays.get(i); - WorkoutDay workoutDay = new WorkoutDay(newWorkoutWeek, workoutDayOld.getName(), newWorkoutWeek.getWeekStartDate().plusDays(i), workoutDayOld.getIsWorkoutDay()); + WorkoutDay workoutDay = WorkoutDay.builder() + .workoutWeek(newWorkoutWeek) + .name(workoutDayOld.getName()) + .date(newWorkoutWeek.getWeekStartDate().plusDays(i)) + .isWorkoutDay(workoutDayOld.getIsWorkoutDay()) + .build(); save(workoutDay); workoutExerciseService.createAllFromOldWorkoutDay(workoutDayOld, workoutDay); @@ -73,10 +68,11 @@ public void save(WorkoutDay workoutWeek) { } @Override - public void setWorkoutDayName(String workoutDayId, String name) { - log.trace("Set workout name {} to WorkoutDay by id: {}", name, workoutDayId); + @Transactional + public void setName(Long workoutDayId, String name) { + log.trace("Set workout name {} for WorkoutDay by id: {}", name, workoutDayId); - WorkoutDay workoutDay = getWorkoutDayById(workoutDayId); + WorkoutDay workoutDay = getById(workoutDayId); workoutDay.setName(name); workoutDay.setIsWorkoutDay(true); @@ -84,98 +80,13 @@ public void setWorkoutDayName(String workoutDayId, String name) { } @Override - public void setRestWorkoutDay(String workoutDayId) { + @Transactional + public void setRestWorkoutDay(Long workoutDayId) { log.trace("Set rest for WorkoutDay by id: {}", workoutDayId); - WorkoutDay workoutDay = getWorkoutDayById(workoutDayId); + WorkoutDay workoutDay = getById(workoutDayId); workoutDay.setIsWorkoutDay(false); save(workoutDay); } - - @Override - public void deleteById(String id) { - log.trace("Delete WorkoutDay with id: {}", id); - workoutDayRepository.deleteById(id); - } - - @Override - public SendMessage getSelectWorkoutDaySendMessage(String chatId, String workoutDayId) { - WorkoutDay workoutDay = getWorkoutDayById(workoutDayId); - SendMessage sendMessage = new SendMessage(chatId, workoutDay.print(localeMessageService.getMessage("print.workout-day.is-rest-day", chatId), localeMessageService.getMessage("print.workout-day.type-not-set", chatId), localeMessageService.getLocalTag(chatId))); - sendMessage.setReplyMarkup(getInlineKeyboardMarkupForWorkoutDay(workoutDay, workoutExerciseService.getWorkoutExerciseByWorkoutDay(workoutDay), chatId)); - - return sendMessage; - } - - @Override - public EditMessageText getSelectWorkoutDayEditMessage(String chatId, Integer messageId, String workoutDayId) { - WorkoutDay workoutDay = getWorkoutDayById(workoutDayId); - EditMessageText editMessageText = new EditMessageText(workoutDay.print(localeMessageService.getMessage("print.workout-day.is-rest-day", chatId), localeMessageService.getMessage("print.workout-day.type-not-set", chatId), localeMessageService.getLocalTag(chatId))); - editMessageText.setChatId(chatId); - editMessageText.setMessageId(messageId); - editMessageText.setReplyMarkup(getInlineKeyboardMarkupForWorkoutDay(workoutDay, workoutExerciseService.getWorkoutExerciseByWorkoutDay(workoutDay), chatId)); - - return editMessageText; - } - - private InlineKeyboardMarkup getInlineKeyboardMarkupForWorkoutDay(WorkoutDay workoutDay, List workoutExercises, String chatId) { - List> keyboard = new ArrayList<>(); - - if (!workoutExercises.isEmpty()) { - workoutExercises.sort(Comparator.comparingInt(WorkoutExercise::getNumber)); - - workoutExercises.forEach(workoutExercise -> { - List row = new ArrayList<>(); - - InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton(workoutExercise.printForWorkoutDayKeyboard()); - inlineKeyboardButton.setCallbackData("/select-WorkoutExercise:" + workoutExercise.getId()); - row.add(inlineKeyboardButton); - - keyboard.add(row); - }); - } - - // Add exercise - if ((workoutDay.isWorkoutDay() != null) && workoutDay.isWorkoutDay()) { - List rowCreateWorkoutExercise = new ArrayList<>(); - InlineKeyboardButton buttonCreateWorkoutExercise = new InlineKeyboardButton(localeMessageService.getMessage("reply.workout-day.keyboard.add-exercise", chatId)); - buttonCreateWorkoutExercise.setCallbackData("/create-request-WorkoutExercise:" + workoutDay.getId()); - rowCreateWorkoutExercise.add(buttonCreateWorkoutExercise); - keyboard.add(rowCreateWorkoutExercise); - } - - List lastRow = new ArrayList<>(); - - //Change name - if (workoutDay.getIsWorkoutDay() != null && workoutDay.getIsWorkoutDay()) { - InlineKeyboardButton setNameButton = new InlineKeyboardButton(localeMessageService.getMessage("reply.change-name", chatId)); - setNameButton.setCallbackData("/set-name-request-WorkoutDay:" + workoutDay.getId()); - lastRow.add(setNameButton); - } - - //Create workout - if (workoutDay.getIsWorkoutDay() == null || !workoutDay.getIsWorkoutDay()) { - InlineKeyboardButton setNameButton = new InlineKeyboardButton(localeMessageService.getMessage("reply.workout-day.keyboard.create-workout-request", chatId)); - setNameButton.setCallbackData("/set-name-request-WorkoutDay:" + workoutDay.getId()); - lastRow.add(setNameButton); - } - - //Set rest day - if (workoutDay.getIsWorkoutDay() == null || workoutDay.getIsWorkoutDay()) { - InlineKeyboardButton setRestDayButton = new InlineKeyboardButton(localeMessageService.getMessage("reply.workout-day.keyboard.set-as-rest-day", chatId)); - setRestDayButton.setCallbackData("/set-rest-request-WorkoutDay:" + workoutDay.getId()); - lastRow.add(setRestDayButton); - } - - keyboard.add(lastRow); - - List backButtonRow = new ArrayList<>(); - InlineKeyboardButton backButton = new InlineKeyboardButton(localeMessageService.getMessage("reply.keyboard.back", chatId)); - backButton.setCallbackData("/select-current-WorkoutWeek"); - backButtonRow.add(backButton); - - keyboard.add(backButtonRow); - return new InlineKeyboardMarkup(keyboard); - } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutExerciseServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutExerciseServiceImpl.java index 917d0e5..ce22ec3 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutExerciseServiceImpl.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutExerciseServiceImpl.java @@ -5,17 +5,12 @@ import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; import com.mykhailotiutiun.repcounterbot.repository.WorkoutExerciseRepository; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; import com.mykhailotiutiun.repcounterbot.service.WorkoutSetService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; +import org.springframework.transaction.annotation.Transactional; -import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -25,18 +20,16 @@ public class WorkoutExerciseServiceImpl implements WorkoutExerciseService { private final WorkoutExerciseRepository workoutExerciseRepository; private final WorkoutSetService workoutSetService; - private final LocaleMessageService localeMessageService; - public WorkoutExerciseServiceImpl(WorkoutExerciseRepository workoutExerciseRepository, WorkoutSetService workoutSetService, LocaleMessageService localeMessageService) { + public WorkoutExerciseServiceImpl(WorkoutExerciseRepository workoutExerciseRepository, WorkoutSetService workoutSetService) { this.workoutExerciseRepository = workoutExerciseRepository; this.workoutSetService = workoutSetService; - this.localeMessageService = localeMessageService; } @Override - public WorkoutExercise getWorkoutExerciseById(String id) { - log.trace("Get WorkoutExercise with id: {}", id); + public WorkoutExercise getById(Long id) { + log.trace("Get WorkoutExercise by id: {}", id); return sortWorkoutSetsInWorkoutExercise(workoutExerciseRepository.findById(id).orElseThrow(EntityNotFoundException::new)); } @@ -47,7 +40,8 @@ private WorkoutExercise sortWorkoutSetsInWorkoutExercise(WorkoutExercise workout } @Override - public Byte getLatestWorkoutExerciseNumberByWorkoutDay(WorkoutDay workoutDay) { + public Byte getLatestNumberByWorkoutDay(WorkoutDay workoutDay) { + log.trace("Get WorkoutExercise latest number by WorkoutDay: {}", workoutDay); List workoutExercises = workoutExerciseRepository.findAllByWorkoutDayOrderByNumberDesc(workoutDay); if (workoutExercises.isEmpty()) { return 0; @@ -57,159 +51,100 @@ public Byte getLatestWorkoutExerciseNumberByWorkoutDay(WorkoutDay workoutDay) { } @Override - public WorkoutExercise getWorkoutExerciseByNumberAndWorkoutDay(Byte number, WorkoutDay workoutDay){ + public WorkoutExercise getByNumberAndWorkoutDay(Byte number, WorkoutDay workoutDay){ + log.trace("Get WorkoutExercise by number and WorkoutDay: {}, {}", number, workoutDay); return workoutExerciseRepository.findByNumberAndWorkoutDay(number, workoutDay).orElseThrow(EntityNotFoundException::new); } @Override - public List getWorkoutExerciseByWorkoutDay(WorkoutDay workoutDay) { + public List getAllByWorkoutDay(WorkoutDay workoutDay) { log.trace("Get WorkoutExercises by WorkoutDay: {}", workoutDay); - return workoutExerciseRepository.findAllByWorkoutDay(workoutDay); - } - - @Override - public List getAllWorkoutExercises() { - log.trace("Get all WorkoutExercises"); - return workoutExerciseRepository.findAll(); + return workoutExerciseRepository.findAllByWorkoutDayOrderByNumberDesc(workoutDay); } @Override + @Transactional public void create(WorkoutExercise workoutExercise) { log.trace("Create WorkoutExercise: {}", workoutExercise); - workoutExercise.setNumber((byte) (getLatestWorkoutExerciseNumberByWorkoutDay(workoutExercise.getWorkoutDay()) + 1)); + workoutExercise.setNumber((byte) (getLatestNumberByWorkoutDay(workoutExercise.getWorkoutDay()) + 1)); save(workoutExercise); } @Override + @Transactional public void createAllFromOldWorkoutDay(WorkoutDay oldWorkoutDay, WorkoutDay newWorkoutDay) { - List workoutExercises = getWorkoutExerciseByWorkoutDay(oldWorkoutDay); + log.trace("Create all WorkoutExercise from old WorkoutDay: {}, {}", oldWorkoutDay, newWorkoutDay); + List workoutExercises = getAllByWorkoutDay(oldWorkoutDay); workoutExercises.forEach(oldWorkoutExercise -> { - WorkoutExercise newWorkoutExercise = new WorkoutExercise(oldWorkoutExercise.getNumber(), oldWorkoutExercise.getName(), newWorkoutDay, oldWorkoutExercise.getWorkoutSets()); + WorkoutExercise newWorkoutExercise = WorkoutExercise.builder() + .number(oldWorkoutExercise.getNumber()) + .name(oldWorkoutExercise.getName()) + .workoutDay(newWorkoutDay) + .prevWorkoutSets(oldWorkoutExercise.getWorkoutSets()) + .build(); save(newWorkoutExercise); }); } - @Override - public void save(WorkoutExercise workoutExercise) { + private void save(WorkoutExercise workoutExercise) { log.trace("Save WorkoutExercise: {}", workoutExercise); workoutExerciseRepository.save(workoutExercise); } @Override - public void setNameToWorkoutExercise(String workoutExerciseId, String name){ - WorkoutExercise workoutExercise = getWorkoutExerciseById(workoutExerciseId); - log.trace("Save WorkoutExercise: {}", workoutExercise); + @Transactional + public void setName(Long workoutExerciseId, String name){ + WorkoutExercise workoutExercise = getById(workoutExerciseId); + log.trace("Set name WorkoutExercise: {}, {}", workoutExercise, name); workoutExercise.setName(name); save(workoutExercise); } @Override - public void moveUpWorkoutExercise(String workoutExerciseId){ - WorkoutExercise workoutExercise = getWorkoutExerciseById(workoutExerciseId); + @Transactional + public void moveUp(Long workoutExerciseId){ + WorkoutExercise workoutExercise = getById(workoutExerciseId); + log.trace("Move up WorkoutExercise: {}", workoutExercise); - try { - WorkoutExercise swappableWorkoutExercise = getWorkoutExerciseByNumberAndWorkoutDay((byte) (workoutExercise.getNumber() - 1), workoutExercise.getWorkoutDay()); - swappableWorkoutExercise.setNumber((byte) (swappableWorkoutExercise.getNumber() + 1)); - save(swappableWorkoutExercise); - } catch (EntityNotFoundException ignored) {} + WorkoutExercise swappableWorkoutExercise = getByNumberAndWorkoutDay((byte) (workoutExercise.getNumber() - 1), workoutExercise.getWorkoutDay()); + swappableWorkoutExercise.setNumber((byte) (swappableWorkoutExercise.getNumber() + 1)); + save(swappableWorkoutExercise); workoutExercise.setNumber((byte) (workoutExercise.getNumber() - 1)); save(workoutExercise); } @Override - public void moveDownWorkoutExercise(String workoutExerciseId){ - WorkoutExercise workoutExercise = getWorkoutExerciseById(workoutExerciseId); - - try { - WorkoutExercise swappableWorkoutExercise = getWorkoutExerciseByNumberAndWorkoutDay((byte) (workoutExercise.getNumber() + 1), workoutExercise.getWorkoutDay()); - swappableWorkoutExercise.setNumber((byte) (swappableWorkoutExercise.getNumber() - 1)); - save(swappableWorkoutExercise); - } catch (EntityNotFoundException ignored) {} - + @Transactional + public void moveDown(Long workoutExerciseId){ + WorkoutExercise workoutExercise = getById(workoutExerciseId); + log.trace("Move down WorkoutExercise: {}", workoutExercise); + + WorkoutExercise swappableWorkoutExercise = getByNumberAndWorkoutDay((byte) (workoutExercise.getNumber() + 1), workoutExercise.getWorkoutDay()); + swappableWorkoutExercise.setNumber((byte) (swappableWorkoutExercise.getNumber() - 1)); + save(swappableWorkoutExercise); workoutExercise.setNumber((byte) (workoutExercise.getNumber() + 1)); save(workoutExercise); } @Override - public void addSetsToWorkoutExercise(String workoutExerciseId, List workoutSets) { + @Transactional + public void addSets(Long workoutExerciseId, List workoutSets) { + WorkoutExercise workoutExercise = getById(workoutExerciseId); + log.trace("Add WorkoutSets to WorkoutExercise: {}, {}", workoutExercise, workoutSets); + workoutSets.forEach(workoutSetService::save); - WorkoutExercise workoutExercise = getWorkoutExerciseById(workoutExerciseId); workoutExercise.setWorkoutSets(workoutSets); save(workoutExercise); } @Override - public void deleteById(String id) { + public void deleteById(Long id) { log.trace("Delete WorkoutExercise with id: {}", id); workoutExerciseRepository.deleteById(id); } - - @Override - public SendMessage getWorkoutExerciseSendMessage(String chatId, String workoutExerciseId) { - WorkoutExercise workoutExercise = getWorkoutExerciseById(workoutExerciseId); - - SendMessage sendMessage = new SendMessage(chatId, workoutExercise.printForWorkoutExercise(localeMessageService.getMessage("print.workout-exercise.for-workout-exercise-reply", chatId), localeMessageService.getMessage("print.workout-set.pattern", chatId))); - sendMessage.setReplyMarkup(getInlineKeyboardMarkupForWorkoutExercise(chatId, workoutExercise)); - return sendMessage; - } - - @Override - public EditMessageText getWorkoutExerciseEditMessage(String chatId, Integer messageId, String workoutExerciseId, Boolean isOnEditPage) { - WorkoutExercise workoutExercise = getWorkoutExerciseById(workoutExerciseId); - - EditMessageText editMessageText = new EditMessageText(workoutExercise.printForWorkoutExercise(localeMessageService.getMessage("print.workout-exercise.for-workout-exercise-reply", chatId), localeMessageService.getMessage("print.workout-set.pattern", chatId))); - editMessageText.setChatId(chatId); - editMessageText.setMessageId(messageId); - - if(isOnEditPage){ - editMessageText.setReplyMarkup(getInlineKeyboardMarkupForEditWorkoutExercise(chatId, workoutExercise)); - } else { - editMessageText.setReplyMarkup(getInlineKeyboardMarkupForWorkoutExercise(chatId, workoutExercise)); - } - return editMessageText; - } - - private InlineKeyboardMarkup getInlineKeyboardMarkupForWorkoutExercise(String chatId, WorkoutExercise workoutExercise) { - List> keyboard = new ArrayList<>(); - - workoutExercise.getWorkoutSets().forEach(workoutSet -> { - keyboard.add(getButtonRow(workoutSet.print(localeMessageService.getMessage("print.workout-set.pattern", chatId)), "/select-WorkoutSet:" + workoutSet.getId())); - }); - - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.workout-exercise.keyboard.set-sets-request", chatId), "/set-request-WorkoutSet:" + workoutExercise.getId())); - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.workout-exercise.keyboard.edit", chatId), "/edit-WorkoutExercise:" + workoutExercise.getId())); - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.keyboard.back", chatId), "/select-WorkoutDay:" + workoutExercise.getWorkoutDay().getId())); - - return new InlineKeyboardMarkup(keyboard); - } - - private InlineKeyboardMarkup getInlineKeyboardMarkupForEditWorkoutExercise(String chatId, WorkoutExercise workoutExercise) { - List> keyboard = new ArrayList<>(); - - if(workoutExercise.getNumber() > 1){ - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.keyboard.move-up", chatId), "/move-up-request-WorkoutExercise:" + workoutExercise.getId())); - } - - if(workoutExercise.getNumber() < getLatestWorkoutExerciseNumberByWorkoutDay(workoutExercise.getWorkoutDay())){ - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.keyboard.move-down", chatId), "/move-down-request-WorkoutExercise:" + workoutExercise.getId())); - } - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.change-name", chatId), "/change-name-request-WorkoutExercise:" + workoutExercise.getId())); - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.delete", chatId), "/delete-request-WorkoutExercise:" + workoutExercise.getId())); - keyboard.add(getButtonRow(localeMessageService.getMessage("reply.keyboard.back", chatId), "/select-WorkoutExercise:" + workoutExercise.getId())); - - return new InlineKeyboardMarkup(keyboard); - } - - private List getButtonRow(String buttonText, String buttonCallback){ - List buttonRow = new ArrayList<>(); - InlineKeyboardButton button = new InlineKeyboardButton(buttonText); - button.setCallbackData(buttonCallback); - buttonRow.add(button); - return buttonRow; - } } \ No newline at end of file diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutSetServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutSetServiceImpl.java index f4eae91..bc09efe 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutSetServiceImpl.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutSetServiceImpl.java @@ -1,6 +1,5 @@ package com.mykhailotiutiun.repcounterbot.service.Impl; -import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; import com.mykhailotiutiun.repcounterbot.repository.WorkoutSetRepository; import com.mykhailotiutiun.repcounterbot.service.WorkoutSetService; @@ -17,18 +16,10 @@ public WorkoutSetServiceImpl(WorkoutSetRepository workoutSetRepository) { this.workoutSetRepository = workoutSetRepository; } - @Override - public WorkoutSet getWorkoutSetById(String id) { - return workoutSetRepository.findById(id).orElseThrow(EntityNotFoundException::new); - } - @Override public void save(WorkoutSet workoutSet) { + log.trace("Save WorkoutSet: {}", workoutSet); workoutSetRepository.save(workoutSet); } - @Override - public void deleteById(String id) { - workoutSetRepository.deleteById(id); - } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutWeekServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutWeekServiceImpl.java index cd871be..261d9bd 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutWeekServiceImpl.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/WorkoutWeekServiceImpl.java @@ -6,20 +6,14 @@ import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; import com.mykhailotiutiun.repcounterbot.repository.WorkoutWeekRepository; -import com.mykhailotiutiun.repcounterbot.service.LocalDateWeekService; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; +import com.mykhailotiutiun.repcounterbot.util.LocalDateWeekUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; -import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; +import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; @Slf4j @Service @@ -27,29 +21,22 @@ public class WorkoutWeekServiceImpl implements WorkoutWeekService { private final WorkoutWeekRepository workoutWeekRepository; private final WorkoutDayService workoutDayService; - private final LocalDateWeekService localDateWeekService; - private final LocaleMessageService localeMessageService; + private final LocalDateWeekUtil localDateWeekUtil; - public WorkoutWeekServiceImpl(WorkoutWeekRepository workoutWeekRepository, WorkoutDayService workoutDayService, LocalDateWeekService localDateWeekService, LocaleMessageService localeMessageService) { + public WorkoutWeekServiceImpl(WorkoutWeekRepository workoutWeekRepository, WorkoutDayService workoutDayService, LocalDateWeekUtil localDateWeekUtil) { this.workoutWeekRepository = workoutWeekRepository; this.workoutDayService = workoutDayService; - this.localDateWeekService = localDateWeekService; - this.localeMessageService = localeMessageService; - } - - @Override - public WorkoutWeek getWorkoutWeekById(String id) { - log.trace("Get WorkoutWeek with id: {}", id); - return workoutWeekRepository.findById(id).orElseThrow(EntityNotFoundException::new); + this.localDateWeekUtil = localDateWeekUtil; } @Override public WorkoutWeek getCurrentWorkoutWeekByUserId(Long userId) { - log.trace("Get current WorkoutWeek with user-id {}", userId); + log.trace("Get current WorkoutWeek by user-id {}", userId); WorkoutWeek workoutWeek = workoutWeekRepository.findByUserIdAndCurrent(userId, true).orElseThrow(EntityNotFoundException::new); - if (!localDateWeekService.isCurrentWeek(workoutWeek.getWeekStartDate(), workoutWeek.getWeekEndDate())) { + + if (!localDateWeekUtil.isCurrentWeek(workoutWeek.getWeekStartDate(), workoutWeek.getWeekEndDate())) { createFromOldWorkoutWeek(workoutWeek); workoutWeek = workoutWeekRepository.findByUserIdAndCurrent(userId, true).orElseThrow(EntityNotFoundException::new); } @@ -57,24 +44,27 @@ public WorkoutWeek getCurrentWorkoutWeekByUserId(Long userId) { } @Override - public List getAllWorkoutWeeks() { - log.trace("Get all WorkoutWeeks"); - return workoutWeekRepository.findAll(); - } - - @Override + @Transactional public void create(WorkoutWeek workoutWeek) throws EntityAlreadyExistsException { log.trace("Create WorkoutWeek: {}", workoutWeek); save(workoutWeek); for (int i = 0; i < 7; i++) { - workoutDayService.save(new WorkoutDay(workoutWeek, null, workoutWeek.getWeekStartDate().plusDays(i), null)); + workoutDayService.save(WorkoutDay.builder() + .workoutWeek(workoutWeek) + .date(workoutWeek.getWeekStartDate().plusDays(i)) + .build()); } } - @Override - public void createFromOldWorkoutWeek(WorkoutWeek oldWorkoutWeek) { - WorkoutWeek workoutWeek = new WorkoutWeek(oldWorkoutWeek.getUser(), localDateWeekService.getFirstDateOfWeekFromDate(LocalDate.now()), localDateWeekService.getLastDateOfWeekFromDate(LocalDate.now())); + private void createFromOldWorkoutWeek(WorkoutWeek oldWorkoutWeek) { + log.trace("Create from old WorkoutWeek: {}", oldWorkoutWeek); + WorkoutWeek workoutWeek = WorkoutWeek.builder() + .user(oldWorkoutWeek.getUser()) + .current(true) + .weekStartDate(localDateWeekUtil.getFirstDateOfWeekFromDate(LocalDate.now())) + .weekEndDate(localDateWeekUtil.getLastDateOfWeekFromDate(LocalDate.now())) + .build(); save(workoutWeek); oldWorkoutWeek.setCurrent(false); @@ -83,58 +73,8 @@ public void createFromOldWorkoutWeek(WorkoutWeek oldWorkoutWeek) { workoutDayService.createAllFromOldWorkoutWeek(oldWorkoutWeek, workoutWeek); } - @Override - public void save(WorkoutWeek workoutWeek) { + private void save(WorkoutWeek workoutWeek) { log.trace("Save WorkoutWeek: {}", workoutWeek); workoutWeekRepository.save(workoutWeek); } - - @Override - public void deleteById(String id) { - log.trace("Delete WorkoutWeek with id: {}", id); - workoutWeekRepository.deleteById(id); - } - - @Override - public SendMessage getCurrentWorkoutWeekSendMessage(String chatId) { - WorkoutWeek currentWorkoutWeek; - try { - currentWorkoutWeek = getCurrentWorkoutWeekByUserId(Long.valueOf(chatId)); - } catch (EntityNotFoundException e) { - return new SendMessage(chatId, localeMessageService.getMessage("reply.error", chatId)); - } - - SendMessage sendMessage = new SendMessage(chatId, currentWorkoutWeek.print(localeMessageService.getMessage("print.workout-week", chatId))); - - sendMessage.setReplyMarkup(getInlineKeyboardForWeek(workoutDayService.getAllWorkoutDaysByWorkoutWeek(currentWorkoutWeek), chatId)); - - return sendMessage; - } - - @Override - public EditMessageText getCurrentWorkoutWeekEditMessage(String chatId, Integer messageId){ - WorkoutWeek currentWorkoutWeek = getCurrentWorkoutWeekByUserId(Long.valueOf(chatId)); - - EditMessageText editMessageText =new EditMessageText(currentWorkoutWeek.print(localeMessageService.getMessage("print.workout-week", chatId))); - editMessageText.setChatId(chatId); - editMessageText.setMessageId(messageId); - editMessageText.setReplyMarkup(getInlineKeyboardForWeek(workoutDayService.getAllWorkoutDaysByWorkoutWeek(currentWorkoutWeek), chatId)); - return editMessageText; - } - - private InlineKeyboardMarkup getInlineKeyboardForWeek(List workoutDays, String chatId) { - List> keyboard = new ArrayList<>(); - - workoutDays.forEach(workoutDay -> { - InlineKeyboardButton keyboardButton = new InlineKeyboardButton(workoutDay.print(localeMessageService.getMessage("print.workout-day.is-rest-day", chatId), localeMessageService.getMessage("print.workout-day.type-not-set", chatId), localeMessageService.getLocalTag(chatId))); - keyboardButton.setCallbackData("/select-WorkoutDay:" + workoutDay.getId()); - - List inlineKeyboardButtons = new ArrayList<>(); - inlineKeyboardButtons.add(keyboardButton); - - keyboard.add(inlineKeyboardButtons); - }); - - return new InlineKeyboardMarkup(keyboard); - } } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/UserService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/UserService.java index 6fba62c..20487dd 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/UserService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/UserService.java @@ -3,18 +3,10 @@ import com.mykhailotiutiun.repcounterbot.exception.EntityAlreadyExistsException; import com.mykhailotiutiun.repcounterbot.model.User; -import java.util.List; public interface UserService { - User getUserById(Long id); - - List getAllUsers(); + User getById(Long id); void create(User user) throws EntityAlreadyExistsException; - - void save(User user); - - void setUserLang(String userId, String localTag); - - void deleteById(Long id); + void setUserLang(Long userId, String localTag); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutDayService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutDayService.java index 334600b..4aa1ece 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutDayService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutDayService.java @@ -2,28 +2,16 @@ import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import java.util.List; public interface WorkoutDayService { - WorkoutDay getWorkoutDayById(String id); - - List getAllWorkoutDaysByWorkoutWeek(WorkoutWeek workoutWeek); - - List getAllWorkoutDays(); + WorkoutDay getById(Long id); + List getAllByWorkoutWeek(WorkoutWeek workoutWeek); void createAllFromOldWorkoutWeek(WorkoutWeek oldWorkoutWeek, WorkoutWeek newWorkoutWeek); + void save(WorkoutDay workoutDay); + void setName(Long workoutDayId, String name); + void setRestWorkoutDay(Long workoutDayId); - void save(WorkoutDay workoutWeek); - - void setWorkoutDayName(String workoutDayId, String name); - - void setRestWorkoutDay(String workoutDayId); - - void deleteById(String id); - - SendMessage getSelectWorkoutDaySendMessage(String chatId, String workoutDayId); - EditMessageText getSelectWorkoutDayEditMessage(String chatId, Integer messageId, String workoutDayId); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutExerciseService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutExerciseService.java index 55da9c7..c1bfd3e 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutExerciseService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutExerciseService.java @@ -3,40 +3,22 @@ import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; -import org.springframework.boot.context.properties.bind.DefaultValue; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import java.util.List; public interface WorkoutExerciseService { - WorkoutExercise getWorkoutExerciseById(String id); - - Byte getLatestWorkoutExerciseNumberByWorkoutDay(WorkoutDay workoutDay); - - WorkoutExercise getWorkoutExerciseByNumberAndWorkoutDay(Byte number, WorkoutDay workoutDay); - - List getWorkoutExerciseByWorkoutDay(WorkoutDay workoutDay); - - List getAllWorkoutExercises(); + WorkoutExercise getById(Long id); + Byte getLatestNumberByWorkoutDay(WorkoutDay workoutDay); + WorkoutExercise getByNumberAndWorkoutDay(Byte number, WorkoutDay workoutDay); + List getAllByWorkoutDay(WorkoutDay workoutDay); void create(WorkoutExercise workoutExercise); - void createAllFromOldWorkoutDay(WorkoutDay oldWorkoutDay, WorkoutDay newWorkoutDay); - void save(WorkoutExercise workoutExercise); - - void setNameToWorkoutExercise(String workoutExerciseId, String name); - - void moveUpWorkoutExercise(String workoutExerciseId); - - void moveDownWorkoutExercise(String workoutExerciseId); - - void addSetsToWorkoutExercise(String workoutExerciseId, List workoutSets); - - void deleteById(String id); - - SendMessage getWorkoutExerciseSendMessage(String chatId, String workoutExerciseId); - EditMessageText getWorkoutExerciseEditMessage(String chatId, Integer messageId, String workoutExerciseId, Boolean isOnEditPage); + void setName(Long workoutExerciseId, String name); + void moveUp(Long workoutExerciseId); + void moveDown(Long workoutExerciseId); + void addSets(Long workoutExerciseId, List workoutSets); + void deleteById(Long id); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutSetService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutSetService.java index 9e4647f..bbbe584 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutSetService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutSetService.java @@ -3,9 +3,5 @@ import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; public interface WorkoutSetService { - WorkoutSet getWorkoutSetById(String id); - void save(WorkoutSet workoutSet); - - void deleteById(String id); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutWeekService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutWeekService.java index fd12920..6a4194b 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutWeekService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/service/WorkoutWeekService.java @@ -2,27 +2,10 @@ import com.mykhailotiutiun.repcounterbot.exception.EntityAlreadyExistsException; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; -import org.telegram.telegrambots.meta.api.methods.send.SendMessage; -import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; - -import java.util.List; public interface WorkoutWeekService { - WorkoutWeek getWorkoutWeekById(String id); WorkoutWeek getCurrentWorkoutWeekByUserId(Long userId); - List getAllWorkoutWeeks(); - void create(WorkoutWeek workoutWeek) throws EntityAlreadyExistsException; - - void createFromOldWorkoutWeek(WorkoutWeek oldWorkoutWeek); - - void save(WorkoutWeek workoutWeek); - - void deleteById(String id); - - SendMessage getCurrentWorkoutWeekSendMessage(String chatId); - - EditMessageText getCurrentWorkoutWeekEditMessage(String chatId, Integer messageId); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/LocalDateWeekService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/util/LocalDateWeekUtil.java similarity index 72% rename from src/main/java/com/mykhailotiutiun/repcounterbot/service/LocalDateWeekService.java rename to src/main/java/com/mykhailotiutiun/repcounterbot/util/LocalDateWeekUtil.java index baea308..224ef03 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/LocalDateWeekService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/util/LocalDateWeekUtil.java @@ -1,8 +1,8 @@ -package com.mykhailotiutiun.repcounterbot.service; +package com.mykhailotiutiun.repcounterbot.util; import java.time.LocalDate; -public interface LocalDateWeekService { +public interface LocalDateWeekUtil { LocalDate getFirstDateOfWeekFromDate(LocalDate localDate); LocalDate getLastDateOfWeekFromDate(LocalDate localDate); diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/LocaleMessageService.java b/src/main/java/com/mykhailotiutiun/repcounterbot/util/LocaleMessageUtil.java similarity index 52% rename from src/main/java/com/mykhailotiutiun/repcounterbot/service/LocaleMessageService.java rename to src/main/java/com/mykhailotiutiun/repcounterbot/util/LocaleMessageUtil.java index 53d371f..9f4b0c4 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/LocaleMessageService.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/util/LocaleMessageUtil.java @@ -1,6 +1,6 @@ -package com.mykhailotiutiun.repcounterbot.service; +package com.mykhailotiutiun.repcounterbot.util; -public interface LocaleMessageService { +public interface LocaleMessageUtil { String getMessage(String messageCode, String chatId); String getLocalTag(String chatId); diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/LocalDateWeekServiceImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/util/impl/LocalDateWeekUtilImpl.java similarity index 73% rename from src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/LocalDateWeekServiceImpl.java rename to src/main/java/com/mykhailotiutiun/repcounterbot/util/impl/LocalDateWeekUtilImpl.java index 310b418..4cdc935 100644 --- a/src/main/java/com/mykhailotiutiun/repcounterbot/service/Impl/LocalDateWeekServiceImpl.java +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/util/impl/LocalDateWeekUtilImpl.java @@ -1,34 +1,28 @@ -package com.mykhailotiutiun.repcounterbot.service.Impl; +package com.mykhailotiutiun.repcounterbot.util.impl; -import com.mykhailotiutiun.repcounterbot.service.LocalDateWeekService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; +import com.mykhailotiutiun.repcounterbot.util.LocalDateWeekUtil; +import org.springframework.stereotype.Component; import java.time.LocalDate; -@Slf4j -@Service -public class LocalDateWeekServiceImpl implements LocalDateWeekService { +@Component +public class LocalDateWeekUtilImpl implements LocalDateWeekUtil { @Override public LocalDate getFirstDateOfWeekFromDate(LocalDate localDate) { - int i = 0; while (localDate.getDayOfWeek().minus(i).getValue() != 1) { i++; } - return localDate.minusDays(i); } @Override public LocalDate getLastDateOfWeekFromDate(LocalDate localDate) { - int i = 0; while (localDate.getDayOfWeek().plus(i).getValue() != 7) { i++; } - return localDate.plusDays(i); } diff --git a/src/main/java/com/mykhailotiutiun/repcounterbot/util/impl/LocaleMessageUtilImpl.java b/src/main/java/com/mykhailotiutiun/repcounterbot/util/impl/LocaleMessageUtilImpl.java new file mode 100644 index 0000000..fcfd221 --- /dev/null +++ b/src/main/java/com/mykhailotiutiun/repcounterbot/util/impl/LocaleMessageUtilImpl.java @@ -0,0 +1,39 @@ +package com.mykhailotiutiun.repcounterbot.util.impl; + +import com.mykhailotiutiun.repcounterbot.cache.SelectedLanguageCache; +import com.mykhailotiutiun.repcounterbot.language.SelectedLanguageProvider; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; +import org.springframework.context.MessageSource; +import org.springframework.stereotype.Component; + +import java.util.Locale; + +@Component +public class LocaleMessageUtilImpl implements LocaleMessageUtil { + + private final MessageSource messageSource; + private final SelectedLanguageCache selectedLanguageCache; + private final SelectedLanguageProvider selectedLanguageProvider; + + public LocaleMessageUtilImpl(MessageSource messageSource, SelectedLanguageCache selectedLanguageCache, SelectedLanguageProvider selectedLanguageProvider) { + this.messageSource = messageSource; + this.selectedLanguageCache = selectedLanguageCache; + this.selectedLanguageProvider = selectedLanguageProvider; + } + + @Override + public String getMessage(String messageCode, String chatId) { + return messageSource.getMessage(messageCode, null, Locale.forLanguageTag(getLocalTag(chatId))); + } + + @Override + public String getLocalTag(String chatId) { + String localeTag = selectedLanguageCache.getSelectedLanguage(chatId); + if (localeTag == null) { + localeTag = selectedLanguageProvider.getLocaleTag(chatId); + selectedLanguageCache.setSelectedLanguage(chatId, localeTag); + } + return localeTag; + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a2889a2..2fcca77 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,8 +1,11 @@ server.port=8080 -spring.data.mongodb.uri=mongodb+srv://repcounterbot-app:${DATASOURCE_PASSWORD}@repcounterbotcluster.at0fumi.mongodb.net/?retryWrites=true&w=majority&appName=RepCounterBotCluster -spring.data.mongodb.database=rep-counter-bot +spring.datasource.driver-class-name=org.postgresql.Driver +spring.datasource.url=jdbc:postgresql://${DATASOURCE_URL}/repcounterbot +spring.datasource.username=${DATASOURCE_USER} +spring.datasource.password=${DATASOURCE_PASSWORD} +spring.sql.init.mode=always logging.level.com.mykhailotiutiun.repcounterbot=trace logging.level.root=info telegram.webhook-path=https://repcounterbot.serveo.net telegram.bot-name=@RepCounterBot -telegram.bot-token=6030179095:AAE1j3SaiUiZYh4tkY9lj4KfAppPTJLcyvU +telegram.bot-token=${BOT_TOKEN} diff --git a/src/main/resources/messages_en_US.properties b/src/main/resources/messages_en_US.properties index 57b8c02..428cf8b 100644 --- a/src/main/resources/messages_en_US.properties +++ b/src/main/resources/messages_en_US.properties @@ -14,12 +14,12 @@ reply.workout-day.keyboard.set-as-rest-day=Make a day of rest reply.workout-exercise.enter-the-name=Enter the name of the exercise reply.workout-exercise.keyboard.set-sets-request=Specify sets reply.workout-exercise.keyboard.edit=Edit -reply.workout-set.set=Use the pattern: \nWeight : number of reps, weight : number of reps, etc. +reply.workout-set.set=Use the pattern: \nweight:number of reps,weight:number of reps, etc. reply.main-menu.greeting=Hello -reply.main-menu.keyboard.recent-week=Current workout week +reply.main-menu.keyboard.recent-week=Current week reply.main-menu.keyboard.change-lang=Choose a language reply.keyboard.back=<< Back -print.workout-week=Current training week with %s, by %s +print.workout-week=Current week from %s, to %s print.workout-day.is-rest-day=Rest day print.workout-day.type-not-set=Not specified print.workout-exercise.for-workout-exercise-reply=Previous workout: diff --git a/src/main/resources/messages_uk_UA.properties b/src/main/resources/messages_uk_UA.properties index d32f02d..6e631ab 100644 --- a/src/main/resources/messages_uk_UA.properties +++ b/src/main/resources/messages_uk_UA.properties @@ -12,14 +12,14 @@ reply.workout-day.keyboard.add-exercise=Додати вправу reply.workout-day.keyboard.create-workout-request=Створити тренування reply.workout-day.keyboard.set-as-rest-day=Зробити день відпочинку reply.workout-exercise.enter-the-name=Введіть назву вправи -reply.workout-exercise.keyboard.set-sets-request=Вкажіть підходи +reply.workout-exercise.keyboard.set-sets-request=Вказать підходи reply.workout-exercise.keyboard.edit=Редагувати -reply.workout-set.set=Використовуйте шаблон: \nВага: кількість повторень, вага: кількість повторень, i т.д. +reply.workout-set.set=Використовуйте шаблон: \nвага:кількість повторень,вага:кількість повторень, i т.д. reply.main-menu.greeting=Привіт -reply.main-menu.keyboard.recent-week=Поточний тиждень тренувань +reply.main-menu.keyboard.recent-week=Поточний тиждень reply.main-menu.keyboard.change-lang=Обрати мову reply.keyboard.back=<< Назад -print.workout-week=Поточний тиждень тренувань з %s, по %s +print.workout-week=Поточний тиждень з %s, по %s print.workout-day.is-rest-day=День відпочинку print.workout-day.type-not-set=Не вказано print.workout-exercise.for-workout-exercise-reply=На попередньому тренуванні: diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql new file mode 100644 index 0000000..56e4c1a --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,63 @@ +create table if not exists bot_users +( + id bigint not null + constraint bot_users_pk + primary key, + username varchar(255) not null, + local_tag varchar(10) +); + +create table if not exists workout_weeks +( + id bigserial + constraint workout_weeks_pk + primary key, + current boolean, + week_start_date date not null, + week_end_date date not null, + user_id bigint not null + constraint user_id + references bot_users +); + +create table if not exists workout_days +( + id bigserial + constraint workout_day_pk + primary key, + name varchar(255), + date date not null, + is_workout_day boolean, + workout_week_id bigint not null + constraint workout_week_id + references workout_weeks +); + +create table if not exists workout_exercises +( + id bigserial + primary key, + number smallint, + workout_day_id bigint not null + constraint fk_workout_day + references workout_days, + name varchar(255) +); + +create table if not exists workout_sets +( + id bigserial + constraint workout_sets_pk + primary key, + number integer, + reps integer, + weight integer, + workout_ex_id bigint + constraint fk_workout_exercise + references workout_exercises + on delete cascade, + prev_workout_ex_id bigint + constraint fk_prev_workout_exercise + references workout_exercises + on delete cascade +); diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/RepCounterBotApplicationTests.java b/src/test/java/com/mykhailotiutiun/repcounterbot/RepCounterBotApplicationTests.java deleted file mode 100644 index ec047df..0000000 --- a/src/test/java/com/mykhailotiutiun/repcounterbot/RepCounterBotApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.mykhailotiutiun.repcounterbot; - -import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -class RepCounterBotApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/services/UserServiceImplTest.java b/src/test/java/com/mykhailotiutiun/repcounterbot/services/UserServiceImplTest.java index d10b0f6..9482a43 100644 --- a/src/test/java/com/mykhailotiutiun/repcounterbot/services/UserServiceImplTest.java +++ b/src/test/java/com/mykhailotiutiun/repcounterbot/services/UserServiceImplTest.java @@ -1,48 +1,41 @@ package com.mykhailotiutiun.repcounterbot.services; -import com.mykhailotiutiun.repcounterbot.cache.ChatDataCache; +import com.mykhailotiutiun.repcounterbot.cache.SelectedLanguageCache; +import com.mykhailotiutiun.repcounterbot.exception.EntityAlreadyExistsException; +import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; import com.mykhailotiutiun.repcounterbot.model.User; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; import com.mykhailotiutiun.repcounterbot.repository.UserRepository; import com.mykhailotiutiun.repcounterbot.service.Impl.UserServiceImpl; -import com.mykhailotiutiun.repcounterbot.service.LocalDateWeekService; import com.mykhailotiutiun.repcounterbot.service.WorkoutWeekService; +import com.mykhailotiutiun.repcounterbot.util.LocalDateWeekUtil; import org.junit.Test; import org.junit.jupiter.api.BeforeEach; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.mockito.junit.MockitoJUnitRunner; -import java.util.Collections; -import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(SpringRunner.class) -@SpringBootTest +@RunWith(MockitoJUnitRunner.class) public class UserServiceImplTest { - @Mock private UserRepository userRepository; - @Mock private WorkoutWeekService workoutWeekService; - @Mock - private LocalDateWeekService localDateWeekService; - + private LocalDateWeekUtil localDateWeekUtil; @Mock - private ChatDataCache chatDataCache; - + private SelectedLanguageCache selectedLanguageCache; @InjectMocks private UserServiceImpl userService; @@ -54,59 +47,45 @@ public void setUp() { @Test public void testGetUserById() { Long userId = 1L; - User expectedUser = new User(userId, "John Doe"); - + User expectedUser = User.builder().id(userId).build(); when(userRepository.findById(userId)).thenReturn(Optional.of(expectedUser)); - - User actualUser = userService.getUserById(userId); - + User actualUser = userService.getById(userId); assertEquals(expectedUser, actualUser); - } - - @Test - public void testGetAllUsers() { - List expectedUsers = Collections.singletonList(new User(1L, "Alice")); - when(userRepository.findAll()).thenReturn(expectedUsers); - - List actualUsers = userService.getAllUsers(); - - assertEquals(expectedUsers, actualUsers); + when(userRepository.findById(any())).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> { + userService.getById(2L); + }); } @Test public void testCreateUser() { - User newUser = new User(2L, "Bob"); - + User newUser = User.builder().id(1L).build(); when(userRepository.existsById(newUser.getId())).thenReturn(false); - userService.create(newUser); verify(userRepository).save(newUser); verify(workoutWeekService).create(any(WorkoutWeek.class)); + + when(userRepository.existsById(newUser.getId())).thenReturn(true); + + assertThrows(EntityAlreadyExistsException.class, () -> { + userService.create(newUser); + }); } @Test public void testSetUserLang() { - String userId = "3"; + Long userId = 3L; String localTag = "en_US"; - User user = new User(Long.valueOf(userId), "Eva"); + User user = User.builder().id(1L).build(); - when(userRepository.findById(Long.valueOf(userId))).thenReturn(Optional.of(user)); + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); userService.setUserLang(userId, localTag); verify(userRepository).save(user); - verify(chatDataCache).setUserSelectedLanguage(userId, localTag); - } - - @Test - public void testDeleteUserById() { - Long userId = 4L; - - userService.deleteById(userId); - - verify(userRepository).deleteById(userId); + verify(selectedLanguageCache).setSelectedLanguage(String.valueOf(userId), localTag); } } \ No newline at end of file diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutDayServiceImplTest.java b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutDayServiceImplTest.java new file mode 100644 index 0000000..a336718 --- /dev/null +++ b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutDayServiceImplTest.java @@ -0,0 +1,101 @@ +package com.mykhailotiutiun.repcounterbot.services; + +import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutDayRepository; +import com.mykhailotiutiun.repcounterbot.service.Impl.WorkoutDayServiceImpl; +import com.mykhailotiutiun.repcounterbot.service.WorkoutExerciseService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +@RunWith(MockitoJUnitRunner.class) +public class WorkoutDayServiceImplTest { + + @Mock + private WorkoutDayRepository workoutDayRepository; + @Mock + private WorkoutExerciseService workoutExerciseService; + @InjectMocks + private WorkoutDayServiceImpl workoutDayService; + + @Test + public void testGetWorkoutDayById(){ + long id = 1L; + WorkoutDay workoutDay = WorkoutDay.builder().id(id).build(); + when(workoutDayRepository.findById(id)).thenReturn(Optional.of(workoutDay)); + assertEquals(workoutDay, workoutDayService.getById(id)); + + when(workoutDayRepository.findById(id)).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> { + workoutDayService.getById(id); + }); + } + + @Test + public void testGetAllByWorkoutWeek(){ + WorkoutWeek workoutWeek = WorkoutWeek.builder().id(1L).build(); + + List workoutDays = new ArrayList<>(); + for (int i = 7; i > 0; i--){ + workoutDays.add(WorkoutDay.builder().id((long) (i)).date(LocalDate.now().plusDays(i)).build()); + } + when(workoutDayRepository.findAllByWorkoutWeek(workoutWeek)).thenReturn(workoutDays); + assertEquals(workoutDays.get(6), workoutDayService.getAllByWorkoutWeek(workoutWeek).get(0)); + } + + @Test + public void testCreateAllFromOldWorkoutWeek(){ + WorkoutWeek workoutWeek = WorkoutWeek.builder().id(1L).build(); + WorkoutWeek newWorkoutWeek = WorkoutWeek.builder().id(2L).weekStartDate(LocalDate.now()).build(); + List oldWorkoutDays = new ArrayList<>(); + for (int i = 0; i < 7; i++){ + oldWorkoutDays.add(WorkoutDay.builder().id((long) (i + 1)).date(LocalDate.now().plusDays(i)).build()); + } + when(workoutDayRepository.findAllByWorkoutWeek(workoutWeek)).thenReturn(oldWorkoutDays); + workoutDayService.createAllFromOldWorkoutWeek(workoutWeek, newWorkoutWeek); + verify(workoutDayRepository, times(7)).save(any()); + verify(workoutExerciseService, times(7)).createAllFromOldWorkoutDay(any(), any()); + } + + @Test + public void testSave(){ + WorkoutDay workoutDay = WorkoutDay.builder().id(1L).build(); + workoutDayService.save(workoutDay); + verify(workoutDayRepository).save(workoutDay); + } + + @Test + public void setWorkoutDayName(){ + long id = 1L; + String name = "Name"; + WorkoutDay workoutDay = WorkoutDay.builder().id(id).build(); + when(workoutDayRepository.findById(id)).thenReturn(Optional.of(workoutDay)); + workoutDayService.setName(id, name); + verify(workoutDayRepository).save(workoutDay); + assertEquals(workoutDay.getName(), name); + assertTrue(workoutDay.getIsWorkoutDay()); + } + + @Test + public void setRestWorkoutDay(){ + long id = 1L; + WorkoutDay workoutDay = WorkoutDay.builder().id(id).build(); + when(workoutDayRepository.findById(id)).thenReturn(Optional.of(workoutDay)); + workoutDayService.setRestWorkoutDay(id); + verify(workoutDayRepository).save(workoutDay); + assertFalse(workoutDay.getIsWorkoutDay()); + } + +} diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutExerciseServiceImplTest.java b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutExerciseServiceImplTest.java new file mode 100644 index 0000000..9116bbb --- /dev/null +++ b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutExerciseServiceImplTest.java @@ -0,0 +1,186 @@ +package com.mykhailotiutiun.repcounterbot.services; + +import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; +import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; +import com.mykhailotiutiun.repcounterbot.model.WorkoutExercise; +import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutExerciseRepository; +import com.mykhailotiutiun.repcounterbot.service.Impl.WorkoutExerciseServiceImpl; +import com.mykhailotiutiun.repcounterbot.service.WorkoutSetService; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@RunWith(MockitoJUnitRunner.class) +public class WorkoutExerciseServiceImplTest { + + @Mock + private WorkoutExerciseRepository workoutExerciseRepository; + @Mock + private WorkoutSetService workoutSetService; + @InjectMocks + private WorkoutExerciseServiceImpl workoutExerciseService; + + @Test + public void getById(){ + Long id = 1L; + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(id).build(); + workoutExercise.setWorkoutSets(new ArrayList<>(List.of(WorkoutSet.builder().number(2).build(), WorkoutSet.builder().number(1).build()))); + when(workoutExerciseRepository.findById(id)).thenReturn(Optional.of(workoutExercise)); + assertEquals(workoutExercise, workoutExerciseService.getById(id)); + assertEquals(1, (int) workoutExercise.getWorkoutSets().get(0).getNumber()); + assertEquals(2, (int) workoutExercise.getWorkoutSets().get(1).getNumber()); + + + when(workoutExerciseRepository.findById(id)).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> { + workoutExerciseService.getById(id); + }); + } + + @Test + public void getLatestNumberByWorkoutDay(){ + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(1L).number((byte) 1).build(); + WorkoutDay workoutDay = WorkoutDay.builder().id(2L).build(); + when(workoutExerciseRepository.findAllByWorkoutDayOrderByNumberDesc(workoutDay)).thenReturn(List.of(workoutExercise)); + assertEquals(workoutExercise.getNumber(), workoutExerciseService.getLatestNumberByWorkoutDay(workoutDay)); + + when(workoutExerciseRepository.findAllByWorkoutDayOrderByNumberDesc(workoutDay)).thenReturn(new ArrayList<>()); + assertEquals(Byte.valueOf((byte) 0), workoutExerciseService.getLatestNumberByWorkoutDay(workoutDay)); + } + + @Test + public void getByNumberAndWorkoutDay(){ + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(1L).number((byte) 1).build(); + WorkoutDay workoutDay = WorkoutDay.builder().id(2L).build(); + when(workoutExerciseRepository.findByNumberAndWorkoutDay(workoutExercise.getNumber(), workoutDay)).thenReturn(Optional.of(workoutExercise)); + assertEquals(workoutExercise, workoutExerciseService.getByNumberAndWorkoutDay((byte) 1, workoutDay)); + + when(workoutExerciseRepository.findByNumberAndWorkoutDay(workoutExercise.getNumber(), workoutDay)).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> { + workoutExerciseService.getByNumberAndWorkoutDay((byte) 1, workoutDay); + }); + } + + @Test + public void getAllByWorkoutDay(){ + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(1L).number((byte) 1).build(); + WorkoutDay workoutDay = WorkoutDay.builder().id(2L).build(); + when(workoutExerciseRepository.findAllByWorkoutDayOrderByNumberDesc(workoutDay)).thenReturn(List.of(workoutExercise)); + assertEquals(workoutExercise, workoutExerciseService.getAllByWorkoutDay(workoutDay).get(0)); + } + + @Test + public void create(){ + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(1L).build(); + WorkoutDay workoutDay = WorkoutDay.builder().id(2L).build(); + workoutExercise.setWorkoutDay(workoutDay); + when(workoutExerciseRepository.findAllByWorkoutDayOrderByNumberDesc(workoutDay)).thenReturn(List.of(WorkoutExercise.builder().number((byte) 1).build())); + workoutExerciseService.create(workoutExercise); + assertEquals(Byte.valueOf((byte) 2), workoutExercise.getNumber()); + verify(workoutExerciseRepository).save(workoutExercise); + } + + @Test + public void createAllFromOldWorkoutDay(){ + WorkoutDay workoutDay = WorkoutDay.builder().id(1L).build(); + WorkoutDay newWorkoutDay = WorkoutDay.builder().id(2L).build(); + List oldWorkoutExercises = new ArrayList<>(); + for (int i = 0; i < 7; i++){ + oldWorkoutExercises.add(WorkoutExercise.builder().id((long) (i + 1)).build()); + } + when(workoutExerciseRepository.findAllByWorkoutDayOrderByNumberDesc(workoutDay)).thenReturn(oldWorkoutExercises); + workoutExerciseService.createAllFromOldWorkoutDay(workoutDay, newWorkoutDay); + verify(workoutExerciseRepository, times(7)).save(any()); + } + + @Test + public void setName(){ + Long id = 1L; + String name = "Name"; + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(id).workoutSets(new ArrayList<>()).build(); + when(workoutExerciseRepository.findById(id)).thenReturn(Optional.of(workoutExercise)); + workoutExerciseService.setName(id, name); + verify(workoutExerciseRepository).save(workoutExercise); + Assertions.assertEquals(workoutExercise.getName(), name); + } + + @Test + public void moveUp(){ + Long id = 1L; + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(id).number((byte) 2).workoutSets(new ArrayList<>()).build(); + WorkoutExercise upperWorkoutExercise = WorkoutExercise.builder().id(id).number((byte) 1).workoutSets(new ArrayList<>()).build(); + when(workoutExerciseRepository.findById(workoutExercise.getId())).thenReturn(Optional.of(workoutExercise)); + when(workoutExerciseRepository.findByNumberAndWorkoutDay(eq((byte) 1), any())).thenReturn(Optional.of(upperWorkoutExercise)); + workoutExerciseService.moveUp(id); + verify(workoutExerciseRepository).save(workoutExercise); + verify(workoutExerciseRepository).save(upperWorkoutExercise); + assertEquals(Byte.valueOf((byte) 1), workoutExercise.getNumber()); + assertEquals(Byte.valueOf((byte) 2), upperWorkoutExercise.getNumber()); + + when(workoutExerciseRepository.findById(workoutExercise.getId())).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> { + workoutExerciseService.moveUp(id); + }); + + when(workoutExerciseRepository.findById(workoutExercise.getId())).thenReturn(Optional.of(workoutExercise)); + assertThrows(EntityNotFoundException.class, () -> { + workoutExerciseService.moveUp(id); + }); + } + + @Test + public void moveDown(){ + Long s = 1L; + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(s).number((byte) 1).workoutSets(new ArrayList<>()).build(); + WorkoutExercise lowerWorkoutExercise = WorkoutExercise.builder().id(s).number((byte) 2).workoutSets(new ArrayList<>()).build(); + when(workoutExerciseRepository.findById(workoutExercise.getId())).thenReturn(Optional.of(workoutExercise)); + when(workoutExerciseRepository.findByNumberAndWorkoutDay(eq((byte) 2), any())).thenReturn(Optional.of(lowerWorkoutExercise)); + workoutExerciseService.moveDown(s); + verify(workoutExerciseRepository).save(workoutExercise); + verify(workoutExerciseRepository).save(lowerWorkoutExercise); + assertEquals(Byte.valueOf((byte) 2), workoutExercise.getNumber()); + assertEquals(Byte.valueOf((byte) 1), lowerWorkoutExercise.getNumber()); + + when(workoutExerciseRepository.findById(workoutExercise.getId())).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> { + workoutExerciseService.moveDown(s); + }); + + when(workoutExerciseRepository.findById(workoutExercise.getId())).thenReturn(Optional.of(workoutExercise)); + assertThrows(EntityNotFoundException.class, () -> { + workoutExerciseService.moveDown(s); + }); + } + + @Test + public void addSets(){ + Long id = 1L; + WorkoutExercise workoutExercise = WorkoutExercise.builder().id(id).workoutSets(new ArrayList<>()).build(); + List workoutSets = List.of(WorkoutSet.builder().id(id).build(), WorkoutSet.builder().id(2L).build()); + when(workoutExerciseRepository.findById(id)).thenReturn(Optional.of(workoutExercise)); + workoutExerciseService.addSets(id, workoutSets); + verify(workoutSetService, times(2)).save(any()); + verify(workoutExerciseRepository).save(workoutExercise); + assertEquals(workoutSets, workoutExercise.getWorkoutSets()); + } + + @Test + public void deleteById(){ + long id = 1L; + workoutExerciseService.deleteById(id); + verify(workoutExerciseRepository).deleteById(id); + } +} diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutSetsServiceImplTest.java b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutSetsServiceImplTest.java new file mode 100644 index 0000000..c31cc03 --- /dev/null +++ b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutSetsServiceImplTest.java @@ -0,0 +1,28 @@ +package com.mykhailotiutiun.repcounterbot.services; + +import com.mykhailotiutiun.repcounterbot.model.WorkoutSet; +import com.mykhailotiutiun.repcounterbot.repository.WorkoutSetRepository; +import com.mykhailotiutiun.repcounterbot.service.Impl.WorkoutSetServiceImpl; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.mockito.Mockito.verify; + +@RunWith(MockitoJUnitRunner.class) +public class WorkoutSetsServiceImplTest { + + @Mock + private WorkoutSetRepository workoutSetRepository; + @InjectMocks + private WorkoutSetServiceImpl workoutSetService; + + @Test + public void save(){ + WorkoutSet workoutSet = WorkoutSet.builder().id(1L).build(); + workoutSetService.save(workoutSet); + verify(workoutSetRepository).save(workoutSet); + } +} diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutWeekServiceImplTest.java b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutWeekServiceImplTest.java index b586c36..e77523b 100644 --- a/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutWeekServiceImplTest.java +++ b/src/test/java/com/mykhailotiutiun/repcounterbot/services/WorkoutWeekServiceImplTest.java @@ -1,33 +1,30 @@ package com.mykhailotiutiun.repcounterbot.services; +import com.mykhailotiutiun.repcounterbot.exception.EntityNotFoundException; import com.mykhailotiutiun.repcounterbot.model.User; import com.mykhailotiutiun.repcounterbot.model.WorkoutDay; import com.mykhailotiutiun.repcounterbot.model.WorkoutWeek; import com.mykhailotiutiun.repcounterbot.repository.WorkoutWeekRepository; import com.mykhailotiutiun.repcounterbot.service.Impl.WorkoutWeekServiceImpl; -import com.mykhailotiutiun.repcounterbot.service.LocalDateWeekService; -import com.mykhailotiutiun.repcounterbot.service.LocaleMessageService; import com.mykhailotiutiun.repcounterbot.service.WorkoutDayService; -import org.junit.Assert; +import com.mykhailotiutiun.repcounterbot.util.LocalDateWeekUtil; +import com.mykhailotiutiun.repcounterbot.util.LocaleMessageUtil; import org.junit.Test; import org.junit.jupiter.api.BeforeEach; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.mockito.junit.MockitoJUnitRunner; import java.time.LocalDate; -import java.util.Objects; import java.util.Optional; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -@RunWith(SpringRunner.class) -@SpringBootTest +@RunWith(MockitoJUnitRunner.class) public class WorkoutWeekServiceImplTest { @Mock @@ -37,10 +34,7 @@ public class WorkoutWeekServiceImplTest { private WorkoutDayService workoutDayService; @Mock - private LocalDateWeekService localDateWeekService; - - @Mock - private LocaleMessageService localeMessageService; + private LocalDateWeekUtil localDateWeekUtil; @InjectMocks private WorkoutWeekServiceImpl workoutWeekService; @@ -50,36 +44,32 @@ void setUp() { MockitoAnnotations.openMocks(this); } - @Test - public void testGetWorkoutWeekById() { - String workoutWeekId = "1"; - WorkoutWeek expectedWorkoutWeek = new WorkoutWeek(workoutWeekId, new User(1L, "John"), true, LocalDate.of(20024, 4, 14), LocalDate.of(20024, 4, 20)); - - when(workoutWeekRepository.findById(workoutWeekId)).thenReturn(Optional.of(expectedWorkoutWeek)); - - WorkoutWeek actualWorkoutWeek = workoutWeekService.getWorkoutWeekById(workoutWeekId); - - assertEquals(expectedWorkoutWeek, actualWorkoutWeek); - } @Test public void testGetCurrentWorkoutWeekByUserId() { - Long userId = 123L; - WorkoutWeek expectedWorkoutWeek = new WorkoutWeek("2", new User(userId, "John"), true, LocalDate.of(20024, 4, 14), LocalDate.of(20024, 4, 20)); + Long userId = 1L; + WorkoutWeek expectedWorkoutWeek = WorkoutWeek.builder().id(2L).user(User.builder().id(userId).build()).weekEndDate(LocalDate.now()).build(); when(workoutWeekRepository.findByUserIdAndCurrent(userId, true)).thenReturn(Optional.of(expectedWorkoutWeek)); - when(localDateWeekService.isCurrentWeek(any(), any())).thenReturn(true); - + when(localDateWeekUtil.isCurrentWeek(any(), any())).thenReturn(true); WorkoutWeek actualWorkoutWeek = workoutWeekService.getCurrentWorkoutWeekByUserId(userId); - assertEquals(expectedWorkoutWeek, actualWorkoutWeek); + + when(workoutWeekRepository.findByUserIdAndCurrent(userId, true)).thenReturn(Optional.of(expectedWorkoutWeek)); + when(localDateWeekUtil.isCurrentWeek(any(), any())).thenReturn(false); + workoutWeekService.getCurrentWorkoutWeekByUserId(userId); + verify(workoutWeekRepository, times(2)).save(any()); + verify(workoutDayService).createAllFromOldWorkoutWeek(eq(expectedWorkoutWeek), any()); + + when(workoutWeekRepository.findByUserIdAndCurrent(userId, true)).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> { + workoutWeekService.getCurrentWorkoutWeekByUserId(userId); + }); } @Test public void testCreateWorkoutWeek() { - WorkoutWeek newWorkoutWeek = new WorkoutWeek("3", new User(1L, "John"), true, LocalDate.of(20024, 4, 14), LocalDate.of(20024, 4, 20)); - - when(workoutWeekRepository.existsById(newWorkoutWeek.getId())).thenReturn(false); + WorkoutWeek newWorkoutWeek = WorkoutWeek.builder().id(2L).weekStartDate(LocalDate.now()).build(); workoutWeekService.create(newWorkoutWeek); @@ -87,26 +77,4 @@ public void testCreateWorkoutWeek() { verify(workoutDayService, times(7)).save(any(WorkoutDay.class)); } - @Test - public void testCreateFromOldWorkoutWeek() { - WorkoutWeek oldWorkoutWeek = new WorkoutWeek("4", new User(142L, "John"), true, LocalDate.of(20024, 4, 14), LocalDate.of(20024, 4, 20)); - - when(localDateWeekService.getFirstDateOfWeekFromDate(any())).thenReturn(LocalDate.now()); - when(localDateWeekService.getLastDateOfWeekFromDate(any())).thenReturn(LocalDate.now()); - - workoutWeekService.create(oldWorkoutWeek); - workoutWeekService.createFromOldWorkoutWeek(oldWorkoutWeek); - - verify(workoutWeekRepository, times(3)).save(any(WorkoutWeek.class)); - } - - @Test - public void testDeleteWorkoutWeekById() { - String workoutWeekId = "6"; - - workoutWeekService.deleteById(workoutWeekId); - - verify(workoutWeekRepository).deleteById(workoutWeekId); - } - } \ No newline at end of file diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/util/LocalDateWeekUtilImplTest.java b/src/test/java/com/mykhailotiutiun/repcounterbot/util/LocalDateWeekUtilImplTest.java new file mode 100644 index 0000000..6346585 --- /dev/null +++ b/src/test/java/com/mykhailotiutiun/repcounterbot/util/LocalDateWeekUtilImplTest.java @@ -0,0 +1,51 @@ +package com.mykhailotiutiun.repcounterbot.util; + +import com.mykhailotiutiun.repcounterbot.util.impl.LocalDateWeekUtilImpl; +import org.junit.Test; + +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.*; + +public class LocalDateWeekUtilImplTest { + + private final LocalDateWeekUtilImpl localDateWeekUtil = new LocalDateWeekUtilImpl(); + + @Test + public void getFirstDateOfWeekFromDate(){ + LocalDate firstDoW = LocalDate.of(2024, 8, 12); + LocalDate middleDoW = LocalDate.of(2024, 8, 15); + LocalDate lastDow = LocalDate.of(2024, 8, 18); + + assertEquals(firstDoW, localDateWeekUtil.getFirstDateOfWeekFromDate(firstDoW)); + assertEquals(firstDoW, localDateWeekUtil.getFirstDateOfWeekFromDate(middleDoW)); + assertEquals(firstDoW, localDateWeekUtil.getFirstDateOfWeekFromDate(lastDow)); + } + + @Test + public void getLastDateOfWeekFromDate(){ + LocalDate firstDoW = LocalDate.of(2024, 8, 12); + LocalDate middleDoW = LocalDate.of(2024, 8, 15); + LocalDate lastDow = LocalDate.of(2024, 8, 18); + + assertEquals(lastDow, localDateWeekUtil.getLastDateOfWeekFromDate(firstDoW)); + assertEquals(lastDow, localDateWeekUtil.getLastDateOfWeekFromDate(middleDoW)); + assertEquals(lastDow, localDateWeekUtil.getLastDateOfWeekFromDate(lastDow)); + } + + @Test + public void isCurrentWeek(){ + assertFalse(localDateWeekUtil.isCurrentWeek( + localDateWeekUtil.getFirstDateOfWeekFromDate(LocalDate.now().minusDays(10)), + localDateWeekUtil.getLastDateOfWeekFromDate(LocalDate.now().minusDays(10)) + )); + assertTrue(localDateWeekUtil.isCurrentWeek( + localDateWeekUtil.getFirstDateOfWeekFromDate(LocalDate.now()), + localDateWeekUtil.getLastDateOfWeekFromDate(LocalDate.now()) + )); + assertFalse(localDateWeekUtil.isCurrentWeek( + localDateWeekUtil.getFirstDateOfWeekFromDate(LocalDate.now().plusDays(10)), + localDateWeekUtil.getLastDateOfWeekFromDate(LocalDate.now().plusDays(10)) + )); + } +} diff --git a/src/test/java/com/mykhailotiutiun/repcounterbot/util/LocaleMessageUtilImplTest.java b/src/test/java/com/mykhailotiutiun/repcounterbot/util/LocaleMessageUtilImplTest.java new file mode 100644 index 0000000..c2bfcda --- /dev/null +++ b/src/test/java/com/mykhailotiutiun/repcounterbot/util/LocaleMessageUtilImplTest.java @@ -0,0 +1,49 @@ +package com.mykhailotiutiun.repcounterbot.util; + +import com.mykhailotiutiun.repcounterbot.cache.SelectedLanguageCache; +import com.mykhailotiutiun.repcounterbot.language.SelectedLanguageProvider; +import com.mykhailotiutiun.repcounterbot.util.impl.LocaleMessageUtilImpl; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.context.MessageSource; + +import java.util.Locale; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class LocaleMessageUtilImplTest { + + @Mock + private SelectedLanguageCache selectedLanguageCache; + @Mock + private MessageSource messageSource; + @Mock + private SelectedLanguageProvider selectedLanguageProvider; + @InjectMocks + private LocaleMessageUtilImpl localeMessageUtil; + + @Test + public void getMessage(){ + when(messageSource.getMessage("test.code", null, Locale.forLanguageTag("en-EN"))).thenReturn("OK"); + when(selectedLanguageCache.getSelectedLanguage("1")).thenReturn("en-EN"); + assertEquals("OK", localeMessageUtil.getMessage("test.code", "1")); + } + + @Test + public void getLocalTag(){ + when(selectedLanguageCache.getSelectedLanguage("1")).thenReturn("en-EN"); + assertEquals("en-EN", localeMessageUtil.getLocalTag("1")); + + when(selectedLanguageCache.getSelectedLanguage("1")).thenReturn(null); + when(selectedLanguageProvider.getLocaleTag("1")).thenReturn("en-EN"); + assertEquals("en-EN", localeMessageUtil.getLocalTag("1")); + verify(selectedLanguageCache).setSelectedLanguage("1", "en-EN"); + } + +}