Skip to content

Commit

Permalink
feat: optimization of repos and AreaUtil
Browse files Browse the repository at this point in the history
  • Loading branch information
BulatRuslanovich committed Oct 15, 2024
1 parent 2abb2e6 commit 7e1f818
Show file tree
Hide file tree
Showing 17 changed files with 321 additions and 325 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
**/gradlew
**/gradlew.bat
**/gradle/**
**/build/**

# Compiled class file
*.class
Expand Down
3 changes: 1 addition & 2 deletions node/src/main/java/com/bipbup/dao/AppUserConfigDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

import com.bipbup.entity.AppUser;
import com.bipbup.entity.AppUserConfig;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AppUserConfigDAO extends JpaRepository<AppUserConfig, Long> {

Expand Down
5 changes: 2 additions & 3 deletions node/src/main/java/com/bipbup/entity/AppUser.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.CreationTimestamp;

@Getter
Expand Down Expand Up @@ -53,8 +52,8 @@ public class AppUser {
private String username;

@NotNull
@ColumnDefault("'USER'")
@Builder.Default
@Enumerated(EnumType.STRING)
@Column(name = "role", nullable = false, length = 32)
private Role role;
private Role role = Role.USER;
}
5 changes: 3 additions & 2 deletions node/src/main/java/com/bipbup/entity/AppUserConfig.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.bipbup.entity;

import com.bipbup.enums.impl.ExperienceParam;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
Expand Down Expand Up @@ -64,10 +65,10 @@ public class AppUserConfig {
private AppUser appUser;

@Builder.Default
@OneToMany(mappedBy = "config", fetch = FetchType.EAGER)
@OneToMany(mappedBy = "config", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<EducationLevel> educationLevels = new ArrayList<>();

@Builder.Default
@OneToMany(mappedBy = "config", fetch = FetchType.EAGER)
@OneToMany(mappedBy = "config", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<ScheduleType> scheduleTypes = new ArrayList<>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,22 @@
import com.bipbup.entity.EducationLevel;
import com.bipbup.entity.ScheduleType;
import com.bipbup.enums.AppUserState;
import static com.bipbup.enums.AppUserState.QUERY_DELETE_STATE;
import static com.bipbup.enums.AppUserState.QUERY_MENU_STATE;
import static com.bipbup.enums.AppUserState.QUERY_UPDATE_STATE;
import com.bipbup.enums.EnumParam;
import com.bipbup.handlers.StateHandler;
import com.bipbup.handlers.impl.message.BasicStateHandler;
import com.bipbup.service.db.ConfigService;
import com.bipbup.service.cache.UserStateCacheService;
import com.bipbup.service.db.ConfigService;
import com.bipbup.utils.Decoder;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import static com.bipbup.enums.AppUserState.QUERY_DELETE_STATE;
import static com.bipbup.enums.AppUserState.QUERY_MENU_STATE;
import static com.bipbup.enums.AppUserState.QUERY_UPDATE_STATE;
import static com.bipbup.utils.CommandMessageConstants.BotCommand.MYQUERIES;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.CONFIG_NOT_FOUND;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.DELETE_CONFIRMATION;
Expand All @@ -24,110 +32,110 @@
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_QUERY;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_SCHEDULE;
import static com.bipbup.utils.CommandMessageConstants.Prefix;
import com.bipbup.utils.Decoder;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@CallbackQualifier
@RequiredArgsConstructor
public class QueryMenuStateHandler implements StateHandler {

private final UserStateCacheService userStateCacheService;

private final ConfigService configService;

private final Decoder decoder;

private final BasicStateHandler basicStateHandler;

@Override
public String process(AppUser user, String input) {
if (isBackToQueryListCommand(input)) {
return processBackToQueryListCommand(user);
}
if (hasDeletePrefix(input)) {
return processConfigActionCommand(user, input, QUERY_DELETE_STATE);
}
if (hasUpdatePrefix(input)) {
return processConfigActionCommand(user, input, QUERY_UPDATE_STATE);
}

return "";
}

@Override
public AppUserState state() {
return QUERY_MENU_STATE;
}

private String processBackToQueryListCommand(AppUser user) {
return basicStateHandler.process(user, MYQUERIES.getCommand());
}

private boolean isBackToQueryListCommand(String input) {
return MYQUERIES.getCommand().equals(input);
}

private boolean hasUpdatePrefix(String input) {
return input.startsWith(Prefix.UPDATE);
}

private boolean hasDeletePrefix(String input) {
return input.startsWith(Prefix.DELETE);
}

private void appendEnumParams(StringBuilder output, List<? extends EnumParam> values, String prefix) {
if (!values.isEmpty()) {
output.append('\n').append(prefix).append('\n');

String paramNames =
values.stream().map(param -> " - " + param.getDescription())
.sorted()
.collect(Collectors.joining("\n"));

output.append(paramNames);
}
}

private String showDetailedQueryOutput(AppUserConfig config) {
StringBuilder output =
new StringBuilder().append(MENU_CONFIG_NAME.getTemplate()).append(config.getConfigName()).append("\n")
.append(MENU_QUERY.getTemplate()).append(config.getQueryText()).append("\n")
.append(MENU_AREA.getTemplate()).append(config.getArea() == null ? "Любой" : config.getArea())
.append("\n").append(MENU_EXPERIENCE.getTemplate())
.append(config.getExperience().getDescription());

var eduParams = config.getEducationLevels().stream().map(EducationLevel::getParam).toList();
var scheduleParams = config.getScheduleTypes().stream().map(ScheduleType::getParam).toList();

appendEnumParams(output, eduParams, MENU_EDUCATION.getTemplate());
appendEnumParams(output, scheduleParams, MENU_SCHEDULE.getTemplate());

return output.toString();
}

private String processConfigActionCommand(AppUser user, String input, AppUserState state) {
var configId = decoder.parseIdFromCallback(input);
var optionalConfig = configService.getConfigById(configId);

if (optionalConfig.isPresent()) {
var config = optionalConfig.get();
userStateCacheService.putUserState(user.getTelegramId(), state);
log.info("User {} selected menu action and state set to {}", user.getFirstName(), state);

if (state == QUERY_UPDATE_STATE) {
return showDetailedQueryOutput(config);
}

return String.format(DELETE_CONFIRMATION.getTemplate(), config.getConfigName());
} else {
log.debug("Configuration with id {} not found for user {}", configId, user.getFirstName());
return CONFIG_NOT_FOUND.getTemplate();
}
}
private final UserStateCacheService userStateCacheService;

private final ConfigService configService;

private final Decoder decoder;

private final BasicStateHandler basicStateHandler;

@Override
public String process(AppUser user, String input) {
if (isBackToQueryListCommand(input))
return processBackToQueryListCommand(user);
if (hasDeletePrefix(input))
return processConfigActionCommand(user, input, QUERY_DELETE_STATE);
if (hasUpdatePrefix(input))
return processConfigActionCommand(user, input, QUERY_UPDATE_STATE);

return "";
}

@Override
public AppUserState state() {
return QUERY_MENU_STATE;
}

private String processBackToQueryListCommand(AppUser user) {
return basicStateHandler.process(user, MYQUERIES.getCommand());
}

private boolean isBackToQueryListCommand(String input) {
return MYQUERIES.getCommand().equals(input);
}

private boolean hasUpdatePrefix(String input) {
return input.startsWith(Prefix.UPDATE);
}

private boolean hasDeletePrefix(String input) {
return input.startsWith(Prefix.DELETE);
}

private void appendEnumParams(StringBuilder output, List<? extends EnumParam> values, String prefix) {
if (!values.isEmpty()) {
output.append('\n')
.append(prefix)
.append('\n');

String paramNames = values.stream()
.map(param -> " - " + param.getDescription())
.sorted()
.collect(Collectors.joining("\n"));

output.append(paramNames);
}
}

private String showDetailedQueryOutput(AppUserConfig config) {
StringBuilder output = new StringBuilder().append(MENU_CONFIG_NAME.getTemplate())
.append(config.getConfigName()).append("\n")
.append(MENU_QUERY.getTemplate())
.append(config.getQueryText()).append("\n")
.append(MENU_AREA.getTemplate())
.append(config.getArea() == null ? "Любой" : config.getArea()).append("\n")
.append(MENU_EXPERIENCE.getTemplate())
.append(config.getExperience().getDescription());
var eduParams = config.getEducationLevels()
.stream()
.map(EducationLevel::getParam)
.toList();

var scheduleParams = config.getScheduleTypes()
.stream()
.map(ScheduleType::getParam)
.toList();

appendEnumParams(output, eduParams, MENU_EDUCATION.getTemplate());
appendEnumParams(output, scheduleParams, MENU_SCHEDULE.getTemplate());

return output.toString();
}

private String processConfigActionCommand(AppUser user, String input, AppUserState state) {
var configId = decoder.parseIdFromCallback(input);
var optionalConfig = configService.getConfigById(configId);

if (optionalConfig.isPresent()) {
var config = optionalConfig.get();
userStateCacheService.putUserState(user.getTelegramId(), state);
log.info("User {} selected menu action and state set to {}", user.getFirstName(), state);

if (state == QUERY_UPDATE_STATE)
return showDetailedQueryOutput(config);

return String.format(DELETE_CONFIRMATION.getTemplate(), config.getConfigName());
} else {
log.debug("Configuration with id {} not found for user {}", configId, user.getFirstName());
return CONFIG_NOT_FOUND.getTemplate();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@
import com.bipbup.entity.AppUser;
import com.bipbup.entity.EducationLevel;
import com.bipbup.enums.AppUserState;
import static com.bipbup.enums.AppUserState.WAIT_EDUCATION_STATE;
import com.bipbup.enums.impl.EducationLevelParam;
import com.bipbup.handlers.StateHandler;
import com.bipbup.service.db.ConfigService;
import com.bipbup.service.cache.EducationLevelCacheService;
import com.bipbup.service.cache.UserStateCacheService;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.CONFIG_NOT_FOUND;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.EDU_SAVE;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.SELECT_EDUCATION;
import static com.bipbup.utils.CommandMessageConstants.Prefix;
import com.bipbup.service.db.ConfigService;
import com.bipbup.utils.Decoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import static com.bipbup.enums.AppUserState.WAIT_EDUCATION_STATE;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.CONFIG_NOT_FOUND;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.EDU_SAVE;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.SELECT_EDUCATION;
import static com.bipbup.utils.CommandMessageConstants.Prefix;

@Slf4j
@Component
@CallbackQualifier
Expand Down Expand Up @@ -69,7 +71,8 @@ private String processSaveEducationLevelsCommand(AppUser user, String input) {
.toList();

config.setEducationLevels(educationLevels);
configService.saveConfig(config, true);

configService.saveConfig(config);

educationLevelCacheService.clearEducationLevels(user.getTelegramId());
userStateCacheService.clearUserState(user.getTelegramId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private String processSetExperienceCommand(AppUser user, String input) {
var config = optionalConfig.get();
var experience = ExperienceParam.valueOfPrefix(prefix);
config.setExperience(experience);
configService.saveConfig(config, false);
configService.saveConfig(config);

log.info("User {} selected experience level and state set to BASIC_STATE", user.getFirstName());
return String.format(EXP_SET.getTemplate(), experience.getDescription(), config.getConfigName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ protected String processSaveScheduleTypesCommand(AppUser user, String input) {
.toList();

config.setScheduleTypes(scheduleTypes);
configService.saveConfig(config, true);

configService.saveConfig(config);

scheduleTypeCacheService.clearScheduleTypes(telegramId);
userStateCacheService.clearUserState(telegramId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ private String processValidAreaName(AppUser user,
var area = normalizeAreaName(input);
var output = getOutputAndSetArea(config, input, area);

configService.saveConfig(config, false);
configService.saveConfig(config);
userStateCacheService.clearUserState(user.getTelegramId());

log.info("User {} set area '{}' in configuration '{}'", user.getFirstName(), area, config.getConfigName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private String updateConfigName(AppUser user,
String newConfigName) {
var oldConfigName = config.getConfigName();
config.setConfigName(newConfigName);
configService.saveConfig(config, false);
configService.saveConfig(config);
userStateCacheService.clearUserState(user.getTelegramId());
log.info("User {} updated name of config \"{}\" and state set to BASIC_STATE",
user.getFirstName(), oldConfigName);
Expand Down Expand Up @@ -115,7 +115,7 @@ private String processUpdatingConfig(AppUser user, String configName) {
private String processNewConfig(AppUser user, String configName) {
var telegramId = user.getTelegramId();
var newConfig = createConfigWithOnlyName(user, configName);
configService.saveConfig(newConfig, false);
configService.saveConfig(newConfig);
configCacheService.clearConfigId(telegramId);
userStateCacheService.putUserState(telegramId, WAIT_QUERY_STATE);
log.info("User {} created config \"{}\" and state set to WAIT_QUERY_STATE", user.getFirstName(), configName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ private String processValidQuery(AppUser user,
AppUserConfig config,
String input) {
config.setQueryText(input);
configService.saveConfig(config, false);
configService.saveConfig(config);
userStateCacheService.clearUserState(user.getTelegramId());
log.info("User {} set query '{}' in configuration '{}'", user.getFirstName(), input, config.getConfigName());
return String.format(QUERY_SET.getTemplate(), input, config.getConfigName());
Expand Down
Loading

0 comments on commit 7e1f818

Please sign in to comment.