BUS-30: improvements (#11)

* BUS-30: improvements

* BUS-30: improvements

* fix typo

* fix typo
This commit is contained in:
malkoas 2023-06-29 17:08:38 +03:00 committed by GitHub
parent c3e57540ff
commit 2705bf24d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 717 additions and 174 deletions

View File

@ -48,7 +48,7 @@
<dependency>
<groupId>dev.vality</groupId>
<artifactId>mayday-proto</artifactId>
<version>1.6-44df908</version>
<version>1.7-b2b2b3b</version>
</dependency>
<dependency>
<groupId>dev.vality</groupId>

View File

@ -0,0 +1,23 @@
package dev.vality.alert.tg.bot.constants;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.Arrays;
@Getter
@RequiredArgsConstructor
public enum InlineCommands {
SELECT_ALERT("selectAlert"),
SELECT_PARAM("selectParam");
private final String command;
public static InlineCommands valueOfStartInlineCommand(String value) {
return Arrays.stream(InlineCommands.values())
.filter(inlineCommand -> value.startsWith(inlineCommand.getCommand()))
.findFirst().orElse(SELECT_PARAM);
}
}

View File

@ -16,7 +16,11 @@ public enum TextConstants {
SELECT_ALERT("Выберите алерт"),
ALERT_REMOVED("Алерт удален"),
ALERTS_REMOVED("Алерты удалены"),
DELETE_ALL_ALERTS("Удалить все алерты");
DELETE_ALL_ALERTS("Удалить все алерты"),
SELECT_PARAM_FROM_LIST("Выберите из списка параметр: "),
ENTER_PARAM_TO_REPLY("Введите в ответе параметр: "),
EMPTY_PARAM("-"),
SELECT("Выбрать");
private final String text;

View File

@ -8,4 +8,6 @@ public interface ParametersDao {
ParametersData getByAlertIdAndParamName(String alertId, String paramName);
ParametersData getByAlertIdAndParamId(String alertId, String paramId);
}

View File

@ -52,4 +52,13 @@ public class ParametersDaoImpl extends AbstractDao implements ParametersDao {
.and(PARAMETERS_DATA.PARAM_NAME.eq(paramName));
return fetchOne(get, parameterTypeRecordRowMapper);
}
@Override
public ParametersData getByAlertIdAndParamId(String alertId, String paramId) {
var get = getDslContext()
.selectFrom(PARAMETERS_DATA)
.where(PARAMETERS_DATA.ALERT_ID.eq(alertId))
.and(PARAMETERS_DATA.PARAM_ID.eq(paramId));
return fetchOne(get, parameterTypeRecordRowMapper);
}
}

View File

@ -14,7 +14,7 @@ import org.telegram.telegrambots.meta.api.objects.Update;
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CallbackHandler implements CommonHandler {
public class CallbackHandler implements CommonHandler<SendMessage> {
private final MenuCallbackMapper menuCallbackMapper;
private final ParametersCallbackMapper parametersCallbackMapper;

View File

@ -1,13 +1,12 @@
package dev.vality.alert.tg.bot.handler;
import org.apache.thrift.TException;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
public interface CommonHandler {
public interface CommonHandler<T> {
boolean filter(final Update update);
SendMessage handle(Update update, long userId) throws TException;
T handle(Update update, long userId) throws TException;
}

View File

@ -0,0 +1,40 @@
package dev.vality.alert.tg.bot.handler;
import dev.vality.alert.tg.bot.constants.TextConstants;
import dev.vality.alert.tg.bot.mapper.CreateParamsRequestMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import static dev.vality.alert.tg.bot.utils.UserUtils.isUserInBot;
@Slf4j
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ForceReplyHandler implements CommonHandler<SendMessage> {
private final CreateParamsRequestMapper createParamsRequestMapper;
@Override
public boolean filter(Update update) {
return update.hasMessage()
&& update.getMessage().getReplyToMessage() != null
&& isUserInBot(update);
}
@Override
public SendMessage handle(Update update, long userId) throws TException {
return createParamsRequestMapper.createRequest(
userId,
update.getMessage().getReplyToMessage().getText()
.substring(TextConstants.ENTER_PARAM_TO_REPLY.getText().length()),
update.getMessage().getText());
}
}

View File

@ -0,0 +1,96 @@
package dev.vality.alert.tg.bot.handler;
import dev.vality.alert.tg.bot.constants.InlineCommands;
import dev.vality.alert.tg.bot.dao.ParametersDao;
import dev.vality.alert.tg.bot.domain.tables.pojos.ParametersData;
import dev.vality.alert.tg.bot.exeptions.AlertTgBotException;
import dev.vality.alert.tg.bot.mapper.JsonMapper;
import dev.vality.alert.tg.bot.service.MayDayService;
import dev.vality.alerting.mayday.UserAlert;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.thrift.TException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputTextMessageContent;
import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult;
import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResultArticle;
import java.util.ArrayList;
import java.util.List;
import static dev.vality.alert.tg.bot.utils.StringSearchUtils.*;
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class InlineHandler implements CommonHandler<AnswerInlineQuery> {
private final MayDayService mayDayService;
private final JsonMapper jsonMapper;
private final ParametersDao parametersDao;
@Override
public boolean filter(Update update) {
return update.hasInlineQuery();
}
@SneakyThrows
@Override
public AnswerInlineQuery handle(Update update, long userId) throws TException {
String inlineQuery = update.getInlineQuery().getQuery();
List<InlineQueryResult> queryResultArticleList = new ArrayList<>();
switch (InlineCommands.valueOfStartInlineCommand(inlineQuery)) {
case SELECT_ALERT -> {
List<UserAlert> userAlerts = mayDayService.getUserAlerts(
String.valueOf(update.getInlineQuery().getFrom().getId()));
userAlerts.forEach(option -> {
if (isAlertInList(option, inlineQuery)) {
queryResultArticleList.add(fillInlineQueryResultArticle(
option.getId(),
option.getName(),
new InputTextMessageContent(
InlineCommands.SELECT_ALERT.getCommand() + option.getId())));
}
});
}
case SELECT_PARAM -> {
String alertId = substringAlertId(inlineQuery);
String paramId = substringParamId(inlineQuery);
ParametersData parametersData = parametersDao.getByAlertIdAndParamId(alertId, paramId);
List<String> options = jsonMapper.toList(parametersData.getOptionsValues());
options.forEach(optionValue -> {
if (isParamInList(optionValue, inlineQuery, alertId, paramId)) {
queryResultArticleList.add(fillInlineQueryResultArticle(
optionValue,
null,
new InputTextMessageContent(
getAnswerValueParamsInlineQuery(
alertId,
parametersData.getParamName(),
optionValue))));
}
});
}
default -> throw new AlertTgBotException("Unknown InlineQuery value: " + inlineQuery);
}
return new AnswerInlineQuery(update.getInlineQuery().getId(), queryResultArticleList);
}
private InlineQueryResultArticle fillInlineQueryResultArticle(String id,
String description,
InputTextMessageContent inputTextMessageContent) {
InlineQueryResultArticle inlineQueryResultArticle = new InlineQueryResultArticle();
inlineQueryResultArticle.setId(id);
inlineQueryResultArticle.setTitle(id);
inlineQueryResultArticle.setDescription(description);
inlineQueryResultArticle.setInputMessageContent(inputTextMessageContent);
return inlineQueryResultArticle;
}
}

View File

@ -13,7 +13,7 @@ import static dev.vality.alert.tg.bot.utils.MainMenuBuilder.buildMainInlineKeybo
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class MainMenuHandler implements CommonHandler {
public class MainMenuHandler implements CommonHandler<SendMessage> {
@Override
public boolean filter(Update update) {

View File

@ -10,14 +10,13 @@ import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.Objects;
import static dev.vality.alert.tg.bot.utils.MainMenuBuilder.buildMainInlineKeyboardMarkup;
import static dev.vality.alert.tg.bot.utils.UserUtils.isUserInBot;
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MessageHandler implements CommonHandler {
public class MessageHandler implements CommonHandler<SendMessage> {
private final StateDataDao stateDataDao;
@ -26,7 +25,8 @@ public class MessageHandler implements CommonHandler {
return update.hasMessage()
&& update.getMessage().hasText()
&& update.getMessage().getReplyToMessage() == null
&& Objects.equals(update.getMessage().getChatId(), update.getMessage().getFrom().getId());
&& !update.getMessage().hasViaBot()
&& isUserInBot(update);
}
@Override

View File

@ -1,69 +0,0 @@
package dev.vality.alert.tg.bot.handler;
import dev.vality.alert.tg.bot.constants.TextConstants;
import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.domain.tables.pojos.StateData;
import dev.vality.alert.tg.bot.mapper.JsonMapper;
import dev.vality.alert.tg.bot.mapper.ReplyMessagesMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.Map;
import java.util.Objects;
@Slf4j
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ReplyHandler implements CommonHandler {
private final StateDataDao stateDataDao;
private final ReplyMessagesMapper replyMessagesMapper;
private final JsonMapper jsonMapper;
@Override
public boolean filter(Update update) {
return update.hasMessage()
&& update.getMessage().getReplyToMessage() != null
&& Objects.equals(update.getMessage().getChatId(), update.getMessage().getFrom().getId());
}
@Override
public SendMessage handle(Update update, long userId) throws TException {
if (isReplyMessageDeleteAlert(update)) {
log.info("Delete alert {} for user {}", update.getMessage().getText(), userId);
return replyMessagesMapper.deleteAlert(userId, update.getMessage().getText());
} else {
StateData stateData = stateDataDao.getByUserId(userId);
Map<String, String> paramMap = jsonMapper.toMap(stateData.getMapParams());
paramMap.put(update.getMessage().getReplyToMessage().getText(), update.getMessage().getText());
stateData.setMapParams(jsonMapper.toJson(paramMap));
stateDataDao.updateParams(userId, stateData.getMapParams());
String nextKey = getNextKeyForFill(paramMap);
if (nextKey != null) {
return replyMessagesMapper.createNextParameterRequest(nextKey);
} else {
return replyMessagesMapper.createAlertRequest(userId);
}
}
}
private boolean isReplyMessageDeleteAlert(Update update) {
return update.getMessage().getReplyToMessage().getText()
.equals(TextConstants.ENTER_ALERT_ID_FOR_REMOVED.getText());
}
private static String getNextKeyForFill(Map<String, String> map) {
return map.entrySet().stream()
.filter(entry -> null == entry.getValue())
.findFirst().map(Map.Entry::getKey)
.orElse(null);
}
}

View File

@ -0,0 +1,49 @@
package dev.vality.alert.tg.bot.handler;
import dev.vality.alert.tg.bot.constants.InlineCommands;
import dev.vality.alert.tg.bot.mapper.CreateParamsRequestMapper;
import dev.vality.alert.tg.bot.mapper.ReplyMessagesMapper;
import lombok.RequiredArgsConstructor;
import org.apache.thrift.TException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import static dev.vality.alert.tg.bot.utils.StringSearchUtils.substringParamId;
import static dev.vality.alert.tg.bot.utils.StringSearchUtils.substringParamValue;
import static dev.vality.alert.tg.bot.utils.UserUtils.isUserInBot;
@Component
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ViaBotReplyHandler implements CommonHandler<SendMessage> {
private final ReplyMessagesMapper replyMessagesMapper;
private final CreateParamsRequestMapper createParamsRequestMapper;
@Override
public boolean filter(Update update) {
return update.hasMessage()
&& update.getMessage().hasText()
&& update.getMessage().getReplyToMessage() == null
&& update.getMessage().hasViaBot()
&& isUserInBot(update);
}
@Override
public SendMessage handle(Update update, long userId) throws TException {
String text = update.getMessage().getText();
return switch (InlineCommands.valueOfStartInlineCommand(text)) {
case SELECT_ALERT -> replyMessagesMapper.deleteAlert(
userId,
text.substring(InlineCommands.SELECT_ALERT.getCommand().length()).trim());
case SELECT_PARAM -> createParamsRequestMapper.createRequest(
userId,
substringParamId(text),
substringParamValue(text));
};
}
}

View File

@ -0,0 +1,64 @@
package dev.vality.alert.tg.bot.mapper;
import dev.vality.alert.tg.bot.constants.TextConstants;
import dev.vality.alert.tg.bot.dao.ParametersDao;
import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.domain.tables.pojos.ParametersData;
import dev.vality.alert.tg.bot.domain.tables.pojos.StateData;
import lombok.RequiredArgsConstructor;
import org.apache.thrift.TException;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import java.util.Map;
import java.util.regex.Pattern;
@Component
@RequiredArgsConstructor
public class CreateParamsRequestMapper {
private final StateDataDao stateDataDao;
private final ParametersDao parametersDao;
private final ReplyMessagesMapper replyMessagesMapper;
private final JsonMapper jsonMapper;
public SendMessage createRequest(Long userId, String paramName, String paramValue) throws TException {
StateData stateData = stateDataDao.getByUserId(userId);
Map<String, String> paramMap = jsonMapper.toMap(stateData.getMapParams());
ParametersData parametersData = parametersDao.getByAlertIdAndParamName(stateData.getAlertId(), paramName);
if (isParamValueMatchToProcess(parametersData, paramValue)) {
paramMap.put(paramName, paramValue);
stateData.setMapParams(jsonMapper.toJson(paramMap));
stateDataDao.updateParams(userId, stateData.getMapParams());
}
String nextKey = getNextKeyForFill(paramMap);
if (nextKey != null) {
return replyMessagesMapper.createNextParameterRequest(nextKey, stateData);
} else {
return replyMessagesMapper.createAlertRequest(userId);
}
}
private boolean isParamValueMatchToProcess(ParametersData parametersData, String paramValue) {
return (!parametersData.getMandatory()
&& (isValuePattern(paramValue, parametersData)
|| paramValue.equals(TextConstants.EMPTY_PARAM.getText())))
|| (parametersData.getMandatory() && !paramValue.equals(TextConstants.EMPTY_PARAM.getText())
&& isValuePattern(paramValue, parametersData));
}
private boolean isValuePattern(String value, ParametersData parametersData) {
if (parametersData.getValueRegexp() != null) {
Pattern pattern = Pattern.compile(parametersData.getValueRegexp());
return pattern.matcher(value).matches();
}
return true;
}
private static String getNextKeyForFill(Map<String, String> map) {
return map.entrySet().stream()
.filter(entry -> null == entry.getValue())
.findFirst().map(Map.Entry::getKey)
.orElse(null);
}
}

View File

@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
@ -17,7 +18,7 @@ public class JsonMapper {
@SneakyThrows(JsonProcessingException.class)
public String toJson(Object data) {
return objectMapper.writeValueAsString(data);
return data != null ? objectMapper.writeValueAsString(data) : null;
}
@SneakyThrows(JsonProcessingException.class)
@ -25,4 +26,10 @@ public class JsonMapper {
return objectMapper.readValue(json, new TypeReference<>() {
});
}
@SneakyThrows(JsonProcessingException.class)
public List<String> toList(String json) {
return objectMapper.readValue(json, new TypeReference<>() {
});
}
}

View File

@ -57,13 +57,16 @@ public class MenuCallbackMapper {
public SendMessage getAllAlertsCallback(long userId) throws TException {
SendMessage message = new SendMessage();
List<UserAlert> userAlerts = mayDayService.getUserAlerts(String.valueOf(userId));
StringBuilder text = new StringBuilder("Ваши алерты:\n");
userAlerts.forEach(userAlert -> {
text.append("id: ").append(userAlert.getId())
.append(" Название: ").append(userAlert.getName())
.append("\n");
});
message.setText(text.toString());
if (!userAlerts.isEmpty()) {
StringBuilder text = new StringBuilder("Ваши алерты:\n");
userAlerts.forEach(userAlert -> text.append("*id:* ").append(userAlert.getId())
.append("\n*Название:* ").append(userAlert.getName())
.append("\n"));
message.setText(text.toString());
message.setParseMode("MarkdownV2");
} else {
message.setText("У вас нет созданных алертов");
}
message.setReplyMarkup(buildMainInlineKeyboardMarkup());
return message;
}

View File

@ -1,19 +1,20 @@
package dev.vality.alert.tg.bot.mapper;
import dev.vality.alert.tg.bot.constants.TextConstants;
import dev.vality.alert.tg.bot.dao.ParametersDao;
import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.domain.enums.ParameterType;
import dev.vality.alert.tg.bot.domain.tables.pojos.ParametersData;
import dev.vality.alert.tg.bot.domain.tables.pojos.StateData;
import dev.vality.alert.tg.bot.service.MayDayService;
import dev.vality.alert.tg.bot.utils.ParamKeyboardBuilder;
import dev.vality.alerting.mayday.AlertConfiguration;
import dev.vality.alerting.mayday.ParameterConfiguration;
import lombok.RequiredArgsConstructor;
import org.apache.thrift.TException;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -28,15 +29,17 @@ public class ParametersCallbackMapper {
private final JsonMapper jsonMapper;
public SendMessage mapParametersCallback(String callData, long userId) throws TException {
SendMessage message = new SendMessage();
AlertConfiguration alertConfiguration = mayDayService.getAlertConfiguration(callData);
String alertId = alertConfiguration.getId();
List<ParameterConfiguration> parameterConfigurations = alertConfiguration.getParameters();
fillStateDataAndSave(userId, alertId, parameterConfigurations);
parameterConfigurations.forEach(param -> convertParameterConfigurationsAndSave(alertId, param));
message.setText(parameterConfigurations.get(0).getName());
message.setReplyMarkup(new ForceReplyKeyboard());
return message;
return ParamKeyboardBuilder.buildParamKeyboard(
parameterConfigurations.get(0).isSetOptions(),
alertId,
parameterConfigurations.get(0).getId(),
parameterConfigurations.get(0).getName(),
parameterConfigurations.get(0).getName());
}
private void fillStateDataAndSave(long userId, String alertId,
@ -44,9 +47,7 @@ public class ParametersCallbackMapper {
StateData stateData = stateDataDao.getByUserId(userId);
stateData.setAlertId(alertId);
Map<String, String> mapParams = new HashMap<>();
parameterConfigurations.forEach(param -> {
mapParams.put(param.getName(), null);
});
parameterConfigurations.forEach(param -> mapParams.put(param.getName(), null));
stateData.setMapParams(jsonMapper.toJson(mapParams));
stateDataDao.save(stateData);
}
@ -56,16 +57,15 @@ public class ParametersCallbackMapper {
parametersData.setAlertId(alertId);
parametersData.setParamId(param.getId());
parametersData.setParamName(param.getName());
parametersData.setParamType(getParamType(param.getType()));
List<String> options = param.isSetOptions() ? new ArrayList<>(param.getOptions()) : null;
if (options != null && !param.isMandatory()) {
options.add(TextConstants.EMPTY_PARAM.getText());
}
String optionsValues = jsonMapper.toJson(options);
parametersData.setOptionsValues(optionsValues);
parametersData.setMandatory(param.isMandatory());
parametersData.setValueRegexp(param.getValueRegexp());
parametersDao.save(parametersData);
}
private ParameterType getParamType(dev.vality.alerting.mayday.ParameterType parameterType) {
return switch (parameterType) {
case integer -> ParameterType.integer;
case str -> ParameterType.str;
case bl -> ParameterType.bl;
case fl -> ParameterType.fl;
};
}
}

View File

@ -6,15 +6,14 @@ import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.domain.tables.pojos.ParametersData;
import dev.vality.alert.tg.bot.domain.tables.pojos.StateData;
import dev.vality.alert.tg.bot.service.MayDayService;
import dev.vality.alert.tg.bot.utils.ParamKeyboardBuilder;
import dev.vality.alerting.mayday.CreateAlertRequest;
import dev.vality.alerting.mayday.ParameterInfo;
import dev.vality.alerting.mayday.ParameterValue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
import java.util.ArrayList;
import java.util.List;
@ -44,7 +43,7 @@ public class ReplyMessagesMapper {
ParametersData parametersData = parametersDao.getByAlertIdAndParamName(stateData.getAlertId(), key);
ParameterInfo parameterInfo = new ParameterInfo();
parameterInfo.setId(parametersData.getParamId());
parameterInfo.setType(mapParameterValue(parametersData, paramMap, key));
parameterInfo.setValue(paramMap.get(key));
parameterInfos.add(parameterInfo);
}
createAlertRequest.setParameters(parameterInfos);
@ -56,27 +55,24 @@ public class ReplyMessagesMapper {
return message;
}
public SendMessage createNextParameterRequest(String text) {
SendMessage message = new SendMessage();
message.setReplyMarkup(new ForceReplyKeyboard());
message.setText(text);
return message;
public SendMessage createNextParameterRequest(String nextValue, StateData stateData) {
ParametersData parametersData = parametersDao.getByAlertIdAndParamName(
stateData.getAlertId(),
nextValue);
return ParamKeyboardBuilder.buildParamKeyboard(
parametersData.getOptionsValues() != null,
parametersData.getAlertId(),
parametersData.getParamId(),
parametersData.getParamName(),
nextValue);
}
public SendMessage deleteAlert(long userId, String text) throws TException {
public SendMessage deleteAlert(long userId, String userAlertId) throws TException {
log.info("Delete alert {} for user {}", userAlertId, userId);
SendMessage message = new SendMessage();
mayDayService.deleteAlert(String.valueOf(userId), text);
mayDayService.deleteAlert(String.valueOf(userId), userAlertId);
message.setText(TextConstants.ALERT_REMOVED.getText());
message.setReplyMarkup(buildMainInlineKeyboardMarkup());
return message;
}
private ParameterValue mapParameterValue(ParametersData parametersData, Map<String, String> paramMap, String key) {
return switch (parametersData.getParamType()) {
case str -> ParameterValue.str(paramMap.get(key));
case integer -> ParameterValue.integer(Long.parseLong(paramMap.get(key)));
case fl -> ParameterValue.fl(Double.parseDouble(paramMap.get(key)));
case bl -> ParameterValue.bl(Boolean.parseBoolean(paramMap.get(key)));
};
}
}

View File

@ -8,15 +8,21 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery;
import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand;
import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScopeDefault;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.List;
import static dev.vality.alert.tg.bot.constants.UserStatuses.ALLOWED_USER_STATUSES;
import static dev.vality.alert.tg.bot.utils.UserUtils.getUserId;
import static dev.vality.alert.tg.bot.utils.UserUtils.getUserName;
@Slf4j
@Service
@ -28,11 +34,13 @@ public class AlertBot extends TelegramLongPollingBot {
public AlertBot(AlertBotProperties alertBotProperties,
List<CommonHandler> handlers,
MayDayService mayDayService) {
MayDayService mayDayService) throws TelegramApiException {
super(alertBotProperties.getToken());
this.handlers = handlers;
this.alertBotProperties = alertBotProperties;
this.mayDayService = mayDayService;
this.execute(new SetMyCommands(List.of(
new BotCommand("/start", "Main Menu")), new BotCommandScopeDefault(), null));
}
@Override
@ -44,17 +52,19 @@ public class AlertBot extends TelegramLongPollingBot {
public void onUpdateReceived(Update update) {
try {
if (isUserPermission(update)) {
long userId = update.hasMessage()
? update.getMessage().getFrom().getId()
: update.getCallbackQuery().getFrom().getId();
SendMessage message = handlers.stream()
long userId = getUserId(update);
var answer = handlers.stream()
.filter(handler -> handler.filter(update))
.findFirst()
.orElseThrow(UnknownHandlerException::new)
.handle(update, userId);
if (message != null) {
message.setChatId(userId);
execute(message);
if (answer instanceof SendMessage sendMessage) {
sendMessage.setChatId(userId);
execute(sendMessage);
} else if (answer instanceof AnswerInlineQuery answerInlineQuery) {
answerInlineQuery.setIsPersonal(true);
answerInlineQuery.setCacheTime(0);
execute(answerInlineQuery);
}
}
} catch (TelegramApiException | TException ex) {
@ -63,12 +73,8 @@ public class AlertBot extends TelegramLongPollingBot {
}
public boolean isUserPermission(Update update) throws TException {
Long userId = update.hasMessage()
? update.getMessage().getFrom().getId()
: update.getCallbackQuery().getMessage().getFrom().getId();
String userName = update.hasMessage()
? update.getMessage().getFrom().getUserName()
: update.getCallbackQuery().getMessage().getFrom().getUserName();
Long userId = getUserId(update);
String userName = getUserName(update);
try {
return isChatMemberPermission(userId);
} catch (TelegramApiException e) {

View File

@ -1,5 +1,6 @@
package dev.vality.alert.tg.bot.utils;
import dev.vality.alert.tg.bot.constants.InlineCommands;
import dev.vality.alert.tg.bot.constants.MainMenu;
import lombok.RequiredArgsConstructor;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
@ -25,7 +26,7 @@ public class MainMenuBuilder {
.build()));
rowsInline.add(Collections.singletonList(InlineKeyboardButton.builder()
.text(MainMenu.DELETE_ALERT.getText())
.callbackData(MainMenu.DELETE_ALERT.getCallbackData())
.switchInlineQueryCurrentChat(InlineCommands.SELECT_ALERT.getCommand())
.build()));
rowsInline.add(Collections.singletonList(InlineKeyboardButton.builder()
.text(MainMenu.DELETE_ALL_ALERTS.getText())

View File

@ -0,0 +1,45 @@
package dev.vality.alert.tg.bot.utils;
import lombok.RequiredArgsConstructor;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
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.Collections;
import java.util.List;
import static dev.vality.alert.tg.bot.constants.TextConstants.*;
import static dev.vality.alert.tg.bot.utils.StringSearchUtils.getSelectParamsInlineQuery;
@RequiredArgsConstructor
public class ParamKeyboardBuilder {
public static SendMessage buildParamKeyboard(boolean isSetOptions,
String alertId,
String paramId,
String paramNameForSelect,
String paramNameForReply) {
SendMessage message = new SendMessage();
if (isSetOptions) {
List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();
List<InlineKeyboardButton> rowInline = new ArrayList<>();
rowsInline.add(Collections.singletonList(InlineKeyboardButton.builder()
.text(SELECT.getText())
.switchInlineQueryCurrentChat(
getSelectParamsInlineQuery(alertId, paramId))
.build()));
rowsInline.add(rowInline);
InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
markupInline.setKeyboard(rowsInline);
message.setReplyMarkup(markupInline);
message.setText(SELECT_PARAM_FROM_LIST.getText() + paramNameForSelect);
} else {
message.setReplyMarkup(new ForceReplyKeyboard());
message.setText(ENTER_PARAM_TO_REPLY.getText() + paramNameForReply);
}
return message;
}
}

View File

@ -0,0 +1,47 @@
package dev.vality.alert.tg.bot.utils;
import dev.vality.alert.tg.bot.constants.InlineCommands;
import dev.vality.alerting.mayday.UserAlert;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
@RequiredArgsConstructor
public class StringSearchUtils {
public static String getSelectParamsInlineQuery(String alertId, String paramId) {
return String.format("%s[%s]{%s}", InlineCommands.SELECT_PARAM.getCommand(), alertId, paramId);
}
public static String getAnswerValueParamsInlineQuery(String alertId, String paramName, String optionValue) {
return String.format("%s[%s]{%s}<%s>",
InlineCommands.SELECT_PARAM.getCommand(),
alertId,
paramName,
optionValue);
}
public static String substringAlertId(String str) {
return StringUtils.substringBetween(str, "[", "]");
}
public static String substringParamId(String str) {
return StringUtils.substringBetween(str, "{", "}");
}
public static String substringParamValue(String str) {
return StringUtils.substringBetween(str, "<", ">");
}
public static boolean isAlertInList(UserAlert userAlert, String inlineQueryString) {
return StringUtils.containsIgnoreCase(userAlert.getName(),
inlineQueryString.substring(InlineCommands.SELECT_ALERT.getCommand().length()).trim())
|| StringUtils.containsIgnoreCase(userAlert.getId(),
inlineQueryString.substring(InlineCommands.SELECT_ALERT.getCommand().length()).trim());
}
public static boolean isParamInList(String option, String inlineQueryString, String alertId, String paramId) {
return StringUtils.containsIgnoreCase(
option,
inlineQueryString.substring(getSelectParamsInlineQuery(alertId, paramId).length()).trim());
}
}

View File

@ -0,0 +1,30 @@
package dev.vality.alert.tg.bot.utils;
import lombok.RequiredArgsConstructor;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.Objects;
@RequiredArgsConstructor
public class UserUtils {
public static long getUserId(Update update) {
return update.hasMessage()
? update.getMessage().getFrom().getId()
: update.hasCallbackQuery()
? update.getCallbackQuery().getFrom().getId()
: update.getInlineQuery().getFrom().getId();
}
public static String getUserName(Update update) {
return update.hasMessage()
? update.getMessage().getFrom().getUserName()
: update.hasCallbackQuery()
? update.getCallbackQuery().getMessage().getFrom().getUserName()
: update.getInlineQuery().getFrom().getUserName();
}
public static boolean isUserInBot(Update update) {
return Objects.equals(update.getMessage().getChatId(), update.getMessage().getFrom().getId());
}
}

View File

@ -0,0 +1,8 @@
ALTER TABLE alert_tg_bot.parameters_data DROP COLUMN IF EXISTS param_type;
DROP TYPE IF EXISTS alert_tg_bot.parameter_type;
ALTER TABLE alert_tg_bot.parameters_data
ADD COLUMN IF NOT EXISTS options_values CHARACTER VARYING;
ALTER TABLE alert_tg_bot.parameters_data
ADD COLUMN IF NOT EXISTS mandatory BOOL DEFAULT false;
ALTER TABLE alert_tg_bot.parameters_data
ADD COLUMN IF NOT EXISTS value_regexp CHARACTER VARYING;

View File

@ -1,9 +1,12 @@
package dev.vality.alert.tg.bot;
import dev.vality.alert.tg.bot.domain.enums.ParameterType;
import dev.vality.alert.tg.bot.domain.tables.pojos.ParametersData;
import dev.vality.alert.tg.bot.domain.tables.pojos.StateData;
import dev.vality.alerting.mayday.UserAlert;
import org.telegram.telegrambots.meta.api.objects.*;
import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
import java.util.List;
public abstract class TestObjectFactory {
@ -21,10 +24,21 @@ public abstract class TestObjectFactory {
params.setAlertId("32");
params.setParamName("Терминал");
params.setParamId("14");
params.setParamType(ParameterType.str);
params.setOptionsValues("[\"test1\",\"test2\"]");
params.setMandatory(false);
return params;
}
public static List<UserAlert> testUserAlerts() {
UserAlert userAlert = new UserAlert();
userAlert.setId("testId");
userAlert.setName("testName");
UserAlert userAlert2 = new UserAlert();
userAlert2.setId("testId2");
userAlert2.setName("testName2");
return List.of(userAlert, userAlert2);
}
public static Update testUpdateMessage() {
Chat chat = new Chat();
chat.setId(123L);
@ -59,7 +73,7 @@ public abstract class TestObjectFactory {
Chat chat = new Chat();
chat.setId(123L);
Message message = new Message();
message.setText("test");
message.setText("Введите в ответе параметр: test");
message.setReplyToMessage(message);
message.setChat(chat);
message.setFrom(user);
@ -68,13 +82,13 @@ public abstract class TestObjectFactory {
return update;
}
public static Update testUpdateReplyDeleteAlert() {
public static Update testUpdateViaBotSelectAlert() {
User user = new User();
user.setId(123L);
Chat chat = new Chat();
chat.setId(123L);
Message message = new Message();
message.setText("Введите id алерта для удаления");
message.setText("selectAlert test");
message.setReplyToMessage(message);
message.setChat(chat);
message.setFrom(user);
@ -83,6 +97,45 @@ public abstract class TestObjectFactory {
return update;
}
public static Update testUpdateViaBotSelectParam() {
User user = new User();
user.setId(123L);
Chat chat = new Chat();
chat.setId(123L);
Message message = new Message();
message.setText("selectParam{32}<14>");
message.setReplyToMessage(message);
message.setChat(chat);
message.setFrom(user);
Update update = new Update();
update.setMessage(message);
return update;
}
public static Update testUpdateInlineQuerySelectAlert() {
User user = new User();
user.setId(123L);
InlineQuery inlineQuery = new InlineQuery();
inlineQuery.setId("123");
inlineQuery.setFrom(user);
inlineQuery.setQuery("selectAlert");
Update update = new Update();
update.setInlineQuery(inlineQuery);
return update;
}
public static Update testUpdateInlineQuerySelectParam() {
User user = new User();
user.setId(123L);
InlineQuery inlineQuery = new InlineQuery();
inlineQuery.setId("123");
inlineQuery.setFrom(user);
inlineQuery.setQuery("selectParam[test1]{test2}");
Update update = new Update();
update.setInlineQuery(inlineQuery);
return update;
}
public static Update testUpdateDeleteAllCallback() {
User user = new User();
user.setId(123L);

View File

@ -54,4 +54,17 @@ class ParametersDaoImplTest {
assertEquals(parameters.getParamId(), params.getParamId());
}
@Test
void getByAlertIdAndParamId() {
ParametersData parameters = TestObjectFactory.testParameters();
dslContext.insertInto(PARAMETERS_DATA)
.set(dslContext.newRecord(PARAMETERS_DATA, parameters))
.execute();
ParametersData params =
parametersDao.getByAlertIdAndParamId(parameters.getAlertId(), parameters.getParamId());
assertEquals(parameters.getParamId(), params.getParamId());
}
}

View File

@ -9,7 +9,6 @@ import dev.vality.alert.tg.bot.mapper.ParametersCallbackMapper;
import dev.vality.alert.tg.bot.service.MayDayService;
import dev.vality.alerting.mayday.AlertConfiguration;
import dev.vality.alerting.mayday.ParameterConfiguration;
import dev.vality.alerting.mayday.ParameterType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -89,7 +88,7 @@ public class CallbackHandlerTest {
void testCallbackMessageHandler() throws Exception {
List<ParameterConfiguration> parameterConfigurations =
Collections.singletonList(new ParameterConfiguration()
.setId("2").setName("test").setType(ParameterType.str));
.setId("2").setName("test"));
when(mayDayService.getAlertConfiguration(any()))
.thenReturn(new AlertConfiguration().setId("test").setParameters(parameterConfigurations));
when(stateDataDao.getByUserId(any())).thenReturn(testStateData());

View File

@ -0,0 +1,59 @@
package dev.vality.alert.tg.bot.handler;
import dev.vality.alert.tg.bot.config.ExcludeDataSourceConfiguration;
import dev.vality.alert.tg.bot.dao.ParametersDao;
import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.mapper.CreateParamsRequestMapper;
import dev.vality.alert.tg.bot.mapper.JsonMapper;
import dev.vality.alert.tg.bot.mapper.ReplyMessagesMapper;
import dev.vality.alert.tg.bot.service.MayDayService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import static dev.vality.alert.tg.bot.TestObjectFactory.*;
import static dev.vality.alert.tg.bot.constants.TextConstants.ALERT_CREATED;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(SpringExtension.class)
@Import(ExcludeDataSourceConfiguration.class)
@ContextConfiguration(classes = {ForceReplyHandler.class,
ReplyMessagesMapper.class, JsonMapper.class, CreateParamsRequestMapper.class})
@SpringBootTest(properties = {"spring.config.location=classpath:/application.yml"})
public class ForceReplyHandlerTest {
@MockBean
private ParametersDao parametersDao;
@MockBean
private StateDataDao stateDataDao;
@MockBean
private MayDayService mayDayService;
@Autowired
private CreateParamsRequestMapper createParamsRequestMapper;
@Autowired
private ForceReplyHandler replyHandler;
@Test
void testReplyHandle() throws Exception {
when(stateDataDao.getByUserId(anyLong())).thenReturn(testStateData());
when(parametersDao.getByAlertIdAndParamName(anyString(), anyString())).thenReturn(testParameters());
Update update = testUpdateReply();
SendMessage sendMessage = replyHandler.handle(update, 123L);
assertNotNull(sendMessage);
assertEquals(ALERT_CREATED.getText(), sendMessage.getText());
verify(mayDayService, times(1)).createAlert(any());
verify(stateDataDao, times(2)).getByUserId(any());
verify(stateDataDao, times(1)).updateParams(any(), any());
}
}

View File

@ -0,0 +1,59 @@
package dev.vality.alert.tg.bot.handler;
import dev.vality.alert.tg.bot.config.ExcludeDataSourceConfiguration;
import dev.vality.alert.tg.bot.dao.ParametersDao;
import dev.vality.alert.tg.bot.mapper.JsonMapper;
import dev.vality.alert.tg.bot.service.MayDayService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery;
import org.telegram.telegrambots.meta.api.objects.Update;
import static dev.vality.alert.tg.bot.TestObjectFactory.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(SpringExtension.class)
@Import(ExcludeDataSourceConfiguration.class)
@ContextConfiguration(classes = {InlineHandler.class, JsonMapper.class})
@SpringBootTest(properties = {"spring.config.location=classpath:/application.yml"})
public class InlineHandlerTest {
@MockBean
private ParametersDao parametersDao;
@MockBean
private MayDayService mayDayService;
@Autowired
private InlineHandler inlineHandler;
@Test
void testSelectAlert() throws Exception {
when(mayDayService.getUserAlerts(anyString())).thenReturn(testUserAlerts());
Update update = testUpdateInlineQuerySelectAlert();
AnswerInlineQuery answerInlineQuery = inlineHandler.handle(update, 123L);
assertNotNull(answerInlineQuery);
assertEquals(2, answerInlineQuery.getResults().size());
verify(mayDayService, times(1)).getUserAlerts(any());
}
@Test
void testSelectParam() throws Exception {
when(parametersDao.getByAlertIdAndParamId(any(), any())).thenReturn(testParameters());
Update update = testUpdateInlineQuerySelectParam();
AnswerInlineQuery answerInlineQuery = inlineHandler.handle(update, 123L);
assertNotNull(answerInlineQuery);
assertEquals(2, answerInlineQuery.getResults().size());
verify(parametersDao, times(1)).getByAlertIdAndParamId(any(), any());
}
}

View File

@ -3,6 +3,7 @@ package dev.vality.alert.tg.bot.handler;
import dev.vality.alert.tg.bot.config.ExcludeDataSourceConfiguration;
import dev.vality.alert.tg.bot.dao.ParametersDao;
import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.mapper.CreateParamsRequestMapper;
import dev.vality.alert.tg.bot.mapper.JsonMapper;
import dev.vality.alert.tg.bot.mapper.ReplyMessagesMapper;
import dev.vality.alert.tg.bot.service.MayDayService;
@ -22,14 +23,15 @@ import static dev.vality.alert.tg.bot.constants.TextConstants.ALERT_CREATED;
import static dev.vality.alert.tg.bot.constants.TextConstants.ALERT_REMOVED;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(SpringExtension.class)
@Import(ExcludeDataSourceConfiguration.class)
@ContextConfiguration(classes = {ReplyHandler.class, ReplyMessagesMapper.class, JsonMapper.class})
@ContextConfiguration(classes = {ViaBotReplyHandler.class,
ReplyMessagesMapper.class, JsonMapper.class, CreateParamsRequestMapper.class})
@SpringBootTest(properties = {"spring.config.location=classpath:/application.yml"})
public class ReplyHandlerTest {
public class ViaBotReplyHandlerTest {
@MockBean
private ParametersDao parametersDao;
@ -38,14 +40,25 @@ public class ReplyHandlerTest {
@MockBean
private MayDayService mayDayService;
@Autowired
private ReplyHandler replyHandler;
private CreateParamsRequestMapper createParamsRequestMapper;
@Autowired
private ViaBotReplyHandler replyHandler;
@Test
void testReplyHandle() throws Exception {
void testSelectAlert() throws Exception {
Update update = testUpdateViaBotSelectAlert();
SendMessage sendMessage = replyHandler.handle(update, 123L);
assertNotNull(sendMessage);
assertEquals(ALERT_REMOVED.getText(), sendMessage.getText());
verify(mayDayService, times(1)).deleteAlert(any(), any());
}
@Test
void testSelectParam() throws Exception {
when(stateDataDao.getByUserId(anyLong())).thenReturn(testStateData());
when(parametersDao.getByAlertIdAndParamName(anyString(), anyString())).thenReturn(testParameters());
Update update = testUpdateReply();
Update update = testUpdateViaBotSelectParam();
SendMessage sendMessage = replyHandler.handle(update, 123L);
assertNotNull(sendMessage);
assertEquals(ALERT_CREATED.getText(), sendMessage.getText());
@ -53,16 +66,4 @@ public class ReplyHandlerTest {
verify(stateDataDao, times(2)).getByUserId(any());
verify(stateDataDao, times(1)).updateParams(any(), any());
}
@Test
void testReplyDeleteAlertHandle() throws Exception {
when(stateDataDao.getByUserId(anyLong())).thenReturn(testStateData());
when(parametersDao.getByAlertIdAndParamName(anyString(), anyString())).thenReturn(testParameters());
Update update = testUpdateReplyDeleteAlert();
SendMessage sendMessage = replyHandler.handle(update, 123L);
assertNotNull(sendMessage);
assertEquals(ALERT_REMOVED.getText(), sendMessage.getText());
verify(mayDayService, times(1)).deleteAlert(any(), any());
}
}

View File

@ -47,8 +47,8 @@ public class MenuCallbackMapperTest {
assertNotNull(sendMessage.getReplyMarkup());
StringBuilder text = new StringBuilder("Ваши алерты:\n");
userAlertsList.forEach(userAlert -> {
text.append("id: ").append(userAlert.getId())
.append(" Название: ").append(userAlert.getName())
text.append("*id:* ").append(userAlert.getId())
.append("\n*Название:* ").append(userAlert.getName())
.append("\n");
});
assertEquals(text.toString(), sendMessage.getText());

View File

@ -6,7 +6,6 @@ import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.service.MayDayService;
import dev.vality.alerting.mayday.AlertConfiguration;
import dev.vality.alerting.mayday.ParameterConfiguration;
import dev.vality.alerting.mayday.ParameterType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -45,14 +44,14 @@ public class ParametersCallbackMapperTest {
void testMapParametersCallback() throws Exception {
List<ParameterConfiguration> parameterConfigurations =
Collections.singletonList(new ParameterConfiguration()
.setId("2").setName("test").setType(ParameterType.str));
.setId("2").setName("test").setOptions(List.of("test")));
when(mayDayService.getAlertConfiguration(any()))
.thenReturn(new AlertConfiguration().setId("test").setParameters(parameterConfigurations));
when(stateDataDao.getByUserId(any())).thenReturn(testStateData());
SendMessage sendMessage = parametersCallbackMapper.mapParametersCallback("test", 123L);
assertNotNull(sendMessage);
assertNotNull(sendMessage.getReplyMarkup());
assertEquals("test", sendMessage.getText());
assertEquals("Выберите из списка параметр: test", sendMessage.getText());
verify(mayDayService, times(1)).getAlertConfiguration(any());
verify(stateDataDao, times(1)).getByUserId(any());
verify(stateDataDao, times(1)).save(any());

View File

@ -6,7 +6,6 @@ import dev.vality.alert.tg.bot.dao.StateDataDao;
import dev.vality.alert.tg.bot.service.MayDayService;
import dev.vality.alerting.mayday.AlertConfiguration;
import dev.vality.alerting.mayday.ParameterConfiguration;
import dev.vality.alerting.mayday.ParameterType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -48,7 +47,7 @@ public class ReplyMessageMapperTest {
void testCreateAlertRequest() throws Exception {
List<ParameterConfiguration> parameterConfigurations =
Collections.singletonList(new ParameterConfiguration()
.setId("2").setName("test").setType(ParameterType.str));
.setId("2").setName("test").setOptions(List.of("test")));
when(mayDayService.getAlertConfiguration(any()))
.thenReturn(new AlertConfiguration().setId("test").setParameters(parameterConfigurations));
when(stateDataDao.getByUserId(any())).thenReturn(testStateData());
@ -63,10 +62,11 @@ public class ReplyMessageMapperTest {
@Test
void testCreateNextParameterRequest() {
SendMessage sendMessage = replyMessagesMapper.createNextParameterRequest("test");
when(parametersDao.getByAlertIdAndParamName(any(), any())).thenReturn(testParameters());
SendMessage sendMessage = replyMessagesMapper.createNextParameterRequest("test", testStateData());
assertNotNull(sendMessage);
assertNotNull(sendMessage.getReplyMarkup());
assertEquals("test", sendMessage.getText());
assertEquals("Выберите из списка параметр: Терминал", sendMessage.getText());
}
@Test