Skip to content

Commit

Permalink
feat: (big update) add new filter parameter exclusion
Browse files Browse the repository at this point in the history
  • Loading branch information
BulatRuslanovich committed Oct 18, 2024
1 parent 189c921 commit c6ea749
Show file tree
Hide file tree
Showing 24 changed files with 215 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ private void sendStickerToTelegram(SendSticker sticker) {
private void deactivateUser(User user) {
var callbackQuery = new CallbackQuery();
callbackQuery.setFrom(user);
callbackQuery.setData("delete_me_from_db");
callbackQuery.setData("deactivate_me");

var update = new Update();
update.setCallbackQuery(callbackQuery);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ public class EasterEggService {
"javascript" , "CAACAgIAAxkBAAIFdmbI5bDHR6rHgpLIXtLtIPy8ro-tAAL2QQACctF4S6_e0ZZv1pzyNQQ",
"python" , "CAACAgIAAxkBAAIFd2bI5hnwHgT_BL5jTZtoeT1aL9JwAALISAAC5PF5S7Se8n5ySpqANQQ",
"c#" , "CAACAgIAAxkBAAIFeGbI5kjF58JJGk4yeE-hYI6RwyvuAAJfQwACJad4SypZPWXZRAYeNQQ",
"котик" , "CAACAgIAAxkBAAIFeWbI5mG6zqA00c19q65qlyCqqJE2AAJ4FAACiQ5BS8wYzPDMMcXINQQ"
"котик" , "CAACAgIAAxkBAAIFeWbI5mG6zqA00c19q65qlyCqqJE2AAJ4FAACiQ5BS8wYzPDMMcXINQQ",
"assembler", "CAACAgIAAxkBAAIO8GcRrXoCcvRQp6FqPFwy9NhxDO4GAAL3IwACXpZISL-caYTJXWsLNgQ",
"spring", "CAACAgIAAxkBAAIO72cRrWWo_T_CDtDoIAKpZb5S2kTGAALARwACx9DJS1jIpYXzWxeJNgQ",
"1с", "CAACAgIAAxkBAAIO82cRrkssAAE5ROLBqlWz0PlUiLwnfQACV0AAAohqSUjWTTvAooLXNTYE",
"authors", "CAACAgIAAxkBAAIO9GcRrmF87jiheDcRgr-5-s-dpO7WAAKCTgACv9p4SN-YAf7zsPlCNgQ"
);

public Optional<SendSticker> getSendSticker(Update update) {
Expand Down
4 changes: 2 additions & 2 deletions dispatcher/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ server:
enabled: false

bot:
url: ${BOT_URI:unset}
url: ${BOT_URI:https://b33d-87-117-189-157.ngrok-free.app}
username: ${BOT_USERNAME:headh_v2_bot}
token: ${BOT_TOKEN:token}
token: ${BOT_TOKEN:7361235631:AAGgia9VqWY6Q_o1pW2WTaLQ4d6vzLgRcOg}

spring:
kafka:
Expand Down
3 changes: 1 addition & 2 deletions node/src/main/java/com/bipbup/dao/AppUserDAO.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package com.bipbup.dao;

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

import java.util.Optional;

@Repository
public interface AppUserDAO extends JpaRepository<AppUser, Long> {

Expand Down
10 changes: 10 additions & 0 deletions node/src/main/java/com/bipbup/entity/AppUser.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
package com.bipbup.entity;

import com.bipbup.enums.Role;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
Expand Down Expand Up @@ -51,9 +55,15 @@ public class AppUser {
@Column(name = "username")
private String username;

@Column(name = "active")
private Boolean active;

@NotNull
@Builder.Default
@Enumerated(EnumType.STRING)
@Column(name = "role", nullable = false, length = 32)
private Role role = Role.USER;

@OneToMany(mappedBy = "appUser", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private List<AppUserConfig> configs;
}
5 changes: 4 additions & 1 deletion node/src/main/java/com/bipbup/entity/AppUserConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ public class AppUserConfig {
@Column(name = "area")
private String area;

@ManyToOne
@Column(name = "exclusion")
private String exclusion;

@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "app_user_id")
private AppUser appUser;

Expand Down
3 changes: 2 additions & 1 deletion node/src/main/java/com/bipbup/entity/EducationLevel.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
Expand Down Expand Up @@ -37,7 +38,7 @@ public class EducationLevel {
@Enumerated(EnumType.STRING)
private EducationLevelParam param;

@ManyToOne
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "config_id")
private AppUserConfig config;
}
3 changes: 2 additions & 1 deletion node/src/main/java/com/bipbup/entity/ScheduleType.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
Expand Down Expand Up @@ -37,7 +38,7 @@ public class ScheduleType {
@Enumerated(EnumType.STRING)
private ScheduleTypeParam param;

@ManyToOne
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "config_id")
private AppUserConfig config;
}
2 changes: 2 additions & 0 deletions node/src/main/java/com/bipbup/enums/AppUserState.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public enum AppUserState {

WAIT_QUERY_STATE(true),

WAIT_EXCLUSION_STATE(true),

QUERY_LIST_STATE(false),

QUERY_MENU_STATE(false),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_AREA;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_CONFIG_NAME;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_EDUCATION;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_EXCLUSION;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_EXPERIENCE;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_QUERY;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.MENU_SCHEDULE;
Expand Down Expand Up @@ -100,10 +101,21 @@ private String showDetailedQueryOutput(AppUserConfig config) {
.append(config.getConfigName()).append("\n")
.append(MENU_QUERY)
.append(config.getQueryText()).append("\n")
.append(MENU_AREA)
.append(config.getArea() == null ? "Любой" : config.getArea()).append("\n")
.append(MENU_EXPERIENCE)
.append(config.getExperience().getDescription());
.append(config.getExperience().getDescription()).append("\n");

if (config.getArea() != null) {
output.append(MENU_AREA)
.append(config.getArea())
.append("\n");
}

if (config.getExclusion() != null) {
output.append(MENU_EXCLUSION)
.append(config.getExclusion())
.append("\n");
}

var eduParams = config.getEducationLevels()
.stream()
.map(EducationLevel::getParam)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import static com.bipbup.enums.AppUserState.WAIT_AREA_STATE;
import static com.bipbup.enums.AppUserState.WAIT_CONFIG_NAME_STATE;
import static com.bipbup.enums.AppUserState.WAIT_EDUCATION_STATE;
import static com.bipbup.enums.AppUserState.WAIT_EXCLUSION_STATE;
import static com.bipbup.enums.AppUserState.WAIT_EXPERIENCE_STATE;
import static com.bipbup.enums.AppUserState.WAIT_QUERY_STATE;
import static com.bipbup.enums.AppUserState.WAIT_SCHEDULE_STATE;
Expand All @@ -17,6 +18,7 @@
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.CONFIG_NOT_FOUND;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.ENTER_AREA;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.ENTER_CONFIG_NAME;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.ENTER_EXCLUSION;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.ENTER_QUERY;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.SELECT_EDUCATION;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.SELECT_EXPERIENCE;
Expand Down Expand Up @@ -49,6 +51,8 @@ public class QueryUpdateStateHandler implements StateHandler {
new ActionInfo(WAIT_CONFIG_NAME_STATE, ENTER_CONFIG_NAME.toString(), true),
Prefix.UPDATE_QUERY,
new ActionInfo(WAIT_QUERY_STATE, ENTER_QUERY.toString(), true),
Prefix.UPDATE_EXCLUSION,
new ActionInfo(WAIT_EXCLUSION_STATE, ENTER_EXCLUSION.toString(), true),
Prefix.UPDATE_EXPERIENCE,
new ActionInfo(WAIT_EXPERIENCE_STATE, SELECT_EXPERIENCE.toString(), false),
Prefix.UPDATE_AREA,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.bipbup.handlers.impl.message;

import com.bipbup.annotation.MessageQualifier;
import com.bipbup.entity.AppUser;
import com.bipbup.entity.AppUserConfig;
import com.bipbup.enums.AppUserState;
import com.bipbup.handlers.StateHandler;
import com.bipbup.service.cache.UserStateCacheService;
import com.bipbup.service.db.ConfigService;
import com.bipbup.utils.HandlerUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import static com.bipbup.enums.AppUserState.WAIT_EXCLUSION_STATE;
import static com.bipbup.utils.CommandMessageConstants.EMPTY;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.EMPTY_EXCLUSION_SET;
import static com.bipbup.utils.CommandMessageConstants.MessageTemplate.EXCLUSION_SET;

@Slf4j
@Component
@MessageQualifier
@RequiredArgsConstructor
public class WaitExclusionStateHandler implements StateHandler {

protected static final int MAX_QUERY_LENGTH = 50;

private final ConfigService configService;

private final UserStateCacheService userStateCacheService;

private final HandlerUtils handlerUtils;

@Override
public String process(AppUser user, String input) {
if (handlerUtils.isCancelCommand(input))
return handlerUtils.processCancelCommand(user);
if (handlerUtils.isBasicCommand(input))
return handlerUtils.processBasicCommand(user, input);
if (isInvalidExclusionText(input))
return handlerUtils.processInvalidInput(user);

var optionalConfig = handlerUtils.fetchConfig(user);

if (optionalConfig.isPresent()) {
var config = optionalConfig.get();
return processValidExclusion(user, config, input);
} else {
return handlerUtils.processInvalidInput(user);
}
}

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

private boolean isInvalidExclusionText(String input) {
return !(input != null && !input.trim()
.isEmpty() && input.length() <= MAX_QUERY_LENGTH);
}

private String processValidExclusion(AppUser user, AppUserConfig config, String input) {
String output;

if (EMPTY.equalsIgnoreCase(input)) {
config.setExclusion(null);
output = String.format(EMPTY_EXCLUSION_SET.toString(), config.getConfigName());
} else {
config.setExclusion(input);
output = String.format(EXCLUSION_SET.toString(), input, config.getConfigName());
}

configService.saveConfig(config);
userStateCacheService.clearUserState(user.getTelegramId());
log.info("User {} set exclusion '{}' in configuration '{}'", user.getFirstName(), input, config.getConfigName());
return output;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

/**
* This service handles fetching vacancy data from the API. It uses the user configuration to query for new vacancies
* and processes the results.
*/
@Slf4j
@Service
@RequiredArgsConstructor
Expand All @@ -42,16 +38,8 @@ public class VacancyServiceImpl implements VacancyService {

private AppUserConfig config;

/**
* Fetches new vacancies based on user configuration.
*
* @param config The user configuration containing query parameters.
*
* @return A list of new vacancies.
*/
@Override
public List<Vacancy> fetchNewVacancies(AppUserConfig config) {
// TODO: будет ли работать на синглтоне бина
this.config = config;
var pageCount = fetchPageCount();
vacancyList = new ArrayList<>();
Expand Down Expand Up @@ -83,7 +71,7 @@ private String createVacanciesGetUri(int pageNumber) {
var builder = UriComponentsBuilder.fromUriString(headHunterProperties.vacanciesGetUrl())
.queryParam("page", pageNumber)
.queryParam("per_page", headHunterProperties.countVacanciesInPage())
.queryParam("text", encodeQueryText(config.getQueryText()))
.queryParam("text", encodeForURLForm(config.getQueryText()))
.queryParam("search_field", "name")
.queryParam("period", headHunterProperties.periodOfDays())
.queryParam("order_by", "publication_time");
Expand All @@ -92,11 +80,12 @@ private String createVacanciesGetUri(int pageNumber) {
addExperience(builder);
addEducation(builder);
addSchedule(builder);
addExclusion(builder);

return builder.build().toString();
}

private String encodeQueryText(String queryText) {
private String encodeForURLForm(String queryText) {
return URLEncoder.encode(queryText, StandardCharsets.UTF_8);
}

Expand Down Expand Up @@ -134,6 +123,13 @@ private void addSchedule(UriComponentsBuilder builder) {
builder.queryParam("schedule", types);
}

private void addExclusion(UriComponentsBuilder builder) {
var exclusion = config.getExclusion();

if (exclusion != null)
builder.queryParam("excluded_text", encodeForURLForm(exclusion));
}

private void processVacancyPage(int pageNum) {
var optionalPage = fetchVacancyPage(pageNum);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ public void processCallbackQuery(Update update) {
var user = userService.findOrSaveAppUser(update);
var state = userStateCacheService.getUserState(user.getTelegramId());

if (callbackData.equals("delete_me_from_db")) {
userService.deleteAppUser(user);
if (callbackData.equals("deactivate_me")) {
userService.deactivate(user);
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.methods.ParseMode;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.LinkPreviewOptions;

@Slf4j
@RequiredArgsConstructor
Expand Down Expand Up @@ -94,15 +95,16 @@ private void sendVacancyMessage(Vacancy vacancy, AppUserConfig config) {
String.format("• <i>Роль:</i> <b>%s</b>", roles),
String.format("• <i>Опыт:</i> <b>%s</b>", experience),
String.format("• <i>Тип занятости:</i> <b>%s</b>", employmentType),
String.format("• <i>График:</i> <b>%s</b>", workSchedule),
String.format("• (Ссылка)[%s]", jobLink));
String.format("• <i>График:</i> <b>%s</b>", workSchedule));

var telegramId = config.getAppUser()
.getTelegramId();

var sendMessage = SendMessage.builder()
.text(message)
.parseMode(ParseMode.HTML)
.disableWebPagePreview(false)
.linkPreviewOptions(new LinkPreviewOptions(false, jobLink, true, false, true))
.chatId(telegramId)
.build();

Expand Down
2 changes: 1 addition & 1 deletion node/src/main/java/com/bipbup/service/db/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

public interface UserService {

void deleteAppUser(AppUser user);
void deactivate(AppUser user);

AppUser findOrSaveAppUser(Update update);

Expand Down
Loading

0 comments on commit c6ea749

Please sign in to comment.