Skip to content

Commit

Permalink
S* JRTB-7: added the ability to delete group subscription. (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanLiVa authored Dec 20, 2023
1 parent 47b990f commit d218909
Show file tree
Hide file tree
Showing 18 changed files with 309 additions and 16 deletions.
3 changes: 3 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ JRTB-0: added SpringBoot skeleton project

* JRTB-5: added ability to subscribe on group
* JRTB-6: added ability to get a list of group subscriptions.
* ## 0.6.0-SNAPSHOT

* JRTB-7: added the ability to delete group subscription.

Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageServiceImpl;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.TelegramUserService;
import java.util.Map;

import java.util.Map;


import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandName.*;
Expand All @@ -18,16 +18,17 @@ public class CommandContainer {

public CommandContainer(SendBotMessageService sendBotMessageService, TelegramUserService telegramUserService, JavaRushGroupClient javaRushGroupClient, GroupSubService groupSubService) {
commandMap =
Map.ofEntries(Map.entry(START.getCommandName(), new StartCommand(sendBotMessageService,telegramUserService)),
Map.entry(STOP.getCommandName(), new StopCommand(sendBotMessageService,telegramUserService)),
Map.entry(HELP.getCommandName(), new HelpCommand(sendBotMessageService)),
Map.entry(NO.getCommandName(), new NoCommand(sendBotMessageService)),
Map.entry(STAT.getCommandName(),new StatCommand(sendBotMessageService,telegramUserService)),
Map.entry(ADD_GROUP_SUB.getCommandName(),new AddGroupSubCommand(sendBotMessageService, javaRushGroupClient, groupSubService)),
Map.entry(LIST_GROUP_SUB.getCommandName(),new ListGroupSubCommand(sendBotMessageService,telegramUserService)));
Map.ofEntries(Map.entry(START.getCommandName(), new StartCommand(sendBotMessageService, telegramUserService)),
Map.entry(STOP.getCommandName(), new StopCommand(sendBotMessageService, telegramUserService)),
Map.entry(HELP.getCommandName(), new HelpCommand(sendBotMessageService)),
Map.entry(NO.getCommandName(), new NoCommand(sendBotMessageService)),
Map.entry(STAT.getCommandName(), new StatCommand(sendBotMessageService, telegramUserService)),
Map.entry(ADD_GROUP_SUB.getCommandName(), new AddGroupSubCommand(sendBotMessageService, javaRushGroupClient, groupSubService)),
Map.entry(LIST_GROUP_SUB.getCommandName(), new ListGroupSubCommand(sendBotMessageService, telegramUserService)),
Map.entry(DELETE_GROUP_SUB.getCommandName(), new DeleteGroupSubCommand(sendBotMessageService, groupSubService, telegramUserService)));


unknownCommand = new UnknownCommand(sendBotMessageService);
unknownCommand = new UnknownCommand(sendBotMessageService);
}

public Command retrieveCommand(String commandIdentifier) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ public enum CommandName {

STAT("/stat"),
ADD_GROUP_SUB("/addgroupsub"),
LIST_GROUP_SUB("/listgroupsub");
LIST_GROUP_SUB("/listgroupsub"),
DELETE_GROUP_SUB("/deletegroupsub");


private final String commandName;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import com.github.JBolivarLi.javarushtelegrambot.bot.repository.entity.GroupSub;
import com.github.JBolivarLi.javarushtelegrambot.bot.repository.entity.TelegramUser;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.GroupSubService;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.TelegramUserService;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.meta.api.objects.Update;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandName.DELETE_GROUP_SUB;
import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandUtils.getChatId;
import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandUtils.getMessage;
import static java.lang.String.format;
import javax.ws.rs.NotFoundException;
import static org.apache.commons.lang3.StringUtils.SPACE;
import static org.apache.commons.lang3.StringUtils.isNumeric;

/**
* Delete Group subscription {@link Command}.
*/
public class DeleteGroupSubCommand implements Command {

private final SendBotMessageService sendBotMessageService;
private final TelegramUserService telegramUserService;
private final GroupSubService groupSubService;

public DeleteGroupSubCommand(SendBotMessageService sendBotMessageService, GroupSubService groupSubService,
TelegramUserService telegramUserService) {
this.sendBotMessageService = sendBotMessageService;
this.groupSubService = groupSubService;
this.telegramUserService = telegramUserService;
}

@Override
public void execute(Update update) {
if (getMessage(update).equalsIgnoreCase(DELETE_GROUP_SUB.getCommandName())) {
sendGroupIdList(getChatId(update));
return;
}
String groupId = getMessage(update).split(SPACE)[1];
String chatId = getChatId(update);
if (isNumeric(groupId)) {
Optional<GroupSub> optionalGroupSub = groupSubService.findById(Integer.valueOf(groupId));
if (optionalGroupSub.isPresent()) {
GroupSub groupSub = optionalGroupSub.get();
TelegramUser telegramUser = telegramUserService.findByChatId(chatId).orElseThrow(NotFoundException::new);
groupSub.getUsers().remove(telegramUser);
groupSubService.save(groupSub);
sendBotMessageService.sendMessage(chatId, format("Удалил подписку на группу: %s", groupSub.getTitle()));
} else {
sendBotMessageService.sendMessage(chatId, "Не нашел такой группы =/");
}
} else {
sendBotMessageService.sendMessage(chatId, "неправильный формат ID группы.\n " +
"ID должно быть целым положительным числом");
}
}

private void sendGroupIdList(String chatId) {
String message;
List<GroupSub> groupSubs = telegramUserService.findByChatId(chatId)
.orElseThrow(NotFoundException::new)
.getGroupSubs();
if (CollectionUtils.isEmpty(groupSubs)) {
message = "Пока нет подписок на группы. Чтобы добавить подписку напиши /addGroupSub";
} else {
message = "Чтобы удалить подписку на группу - передай комадну вместе с ID группы. \n" +
"Например: /deleteGroupSub 16 \n\n" +
"я подготовил список всех групп, на которые ты подписан) \n\n" +
"имя группы - ID группы \n\n" +
"%s";

}
String userGroupSubData = groupSubs.stream()
.map(group -> format("%s - %s \n", group.getTitle(), group.getId()))
.collect(Collectors.joining());

sendBotMessageService.sendMessage(chatId, format(message, userGroupSubData));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@ public class HelpCommand implements Command {

+ "Работа с подписками на группы:\n"
+ "%s - подписаться на группу статей\n"
+ "%s - отписаться от группы статей\n"
+ "%s - получить список групп, на которые подписан\n\n"

+ "%s - получить помощь в работе со мной\n"
+ "%s - получить мою статистику использования\n",
+ "%s - получить помощь в работе со мной\n",
START.getCommandName(), STOP.getCommandName(), ADD_GROUP_SUB.getCommandName(),
LIST_GROUP_SUB.getCommandName(), HELP.getCommandName(), STAT.getCommandName());

DELETE_GROUP_SUB.getCommandName(), LIST_GROUP_SUB.getCommandName(), HELP.getCommandName());


public HelpCommand(SendBotMessageService sendBotMessageService) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
@Data
@Entity
@Table(name = "tg_user")
@EqualsAndHashCode(exclude = "groupSubs")
public class TelegramUser {
@Id
@Column(name = "chat_id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.github.JBolivarLi.javarushtelegrambot.bot.javarushclient.dto.GroupDiscussionInfo;
import com.github.JBolivarLi.javarushtelegrambot.bot.repository.entity.GroupSub;

import java.util.Optional;

/**
* Service for manipulating with {@link GroupSub}.
*/
Expand All @@ -13,4 +15,8 @@ public interface GroupSubService {

GroupSub save(String chatId, GroupDiscussionInfo groupDiscussionInfo);

GroupSub save(GroupSub groupSub);

Optional<GroupSub> findById(Integer id);

}
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,15 @@ public GroupSub save(String chatId, GroupDiscussionInfo groupDiscussionInfo) {
}
return groupSubRepository.save(groupSub);
}


@Override
public GroupSub save(GroupSub groupSub) {
return groupSubRepository.save(groupSub);
}

@Override
public Optional<GroupSub> findById(Integer id) {
return groupSubRepository.findById(id);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package command;

import com.github.JBolivarLi.javarushtelegrambot.bot.bot.JavarushTelegramBot;
import com.github.JBolivarLi.javarushtelegrambot.bot.command.Command;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
Expand Down Expand Up @@ -47,4 +49,13 @@ public void shouldProperlyExecuteCommand() throws TelegramApiException {
//then
Mockito.verify(javarushBot).execute(sendMessage);
}
public static Update prepareUpdate(Long chatId, String commandName) {
Update update = new Update();
Message message = Mockito.mock(Message.class);
Mockito.when(message.getChatId()).thenReturn(chatId);
Mockito.when(message.getText()).thenReturn(commandName);
update.setMessage(message);
return update;
}

}
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package command;

import com.github.JBolivarLi.javarushtelegrambot.bot.command.Command;
import com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandContainer;
import com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandName;
Expand Down
161 changes: 161 additions & 0 deletions src/test/command/DeleteGroupSubCommandTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package command;

import com.github.JBolivarLi.javarushtelegrambot.bot.command.Command;
import com.github.JBolivarLi.javarushtelegrambot.bot.command.DeleteGroupSubCommand;
import com.github.JBolivarLi.javarushtelegrambot.bot.repository.entity.GroupSub;
import com.github.JBolivarLi.javarushtelegrambot.bot.repository.entity.TelegramUser;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.GroupSubService;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.TelegramUserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.telegram.telegrambots.meta.api.objects.Update;

import java.util.ArrayList;
import java.util.Optional;

import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandName.DELETE_GROUP_SUB;
import static command.AbstractCommandTest.prepareUpdate;
import static java.util.Collections.singletonList;
@DisplayName("Unit-level testing for DeleteGroupSubCommand")
class DeleteGroupSubCommandTest {

private Command command;
private SendBotMessageService sendBotMessageService;
GroupSubService groupSubService;
TelegramUserService telegramUserService;


@BeforeEach
public void init() {
sendBotMessageService = Mockito.mock(SendBotMessageService.class);
groupSubService = Mockito.mock(GroupSubService.class);
telegramUserService = Mockito.mock(TelegramUserService.class);

command = new DeleteGroupSubCommand(sendBotMessageService, groupSubService, telegramUserService);
}

@Test
public void shouldProperlyReturnEmptySubscriptionList() {
//given
Long chatId = 23456L;
Update update = prepareUpdate(chatId, DELETE_GROUP_SUB.getCommandName());

Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId)))
.thenReturn(Optional.of(new TelegramUser()));

String expectedMessage = "Пока нет подписок на группы. Чтобы добавить подписку напиши /addGroupSub";

//when
command.execute(update);

//then
Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage);
}

@Test
public void shouldProperlyReturnSubscriptionLit() {
//given
Long chatId = 23456L;
Update update = prepareUpdate(chatId, DELETE_GROUP_SUB.getCommandName());
TelegramUser telegramUser = new TelegramUser();
GroupSub gs1 = new GroupSub();
gs1.setId(123);
gs1.setTitle("GS1 Title");
telegramUser.setGroupSubs(singletonList(gs1));
Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId)))
.thenReturn(Optional.of(telegramUser));

String expectedMessage = "Чтобы удалить подписку на группу - передай комадну вместе с ID группы. \n" +
"Например: /deleteGroupSub 16 \n\n" +
"я подготовил список всех групп, на которые ты подписан) \n\n" +
"имя группы - ID группы \n\n" +
"GS1 Title - 123 \n";

//when
command.execute(update);

//then
Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage);
}

@Test
public void shouldRejectByInvalidGroupId() {
//given
Long chatId = 23456L;
Update update = prepareUpdate(chatId, String.format("%s %s", DELETE_GROUP_SUB.getCommandName(), "groupSubId"));
TelegramUser telegramUser = new TelegramUser();
GroupSub gs1 = new GroupSub();
gs1.setId(123);
gs1.setTitle("GS1 Title");
telegramUser.setGroupSubs(singletonList(gs1));
Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId)))
.thenReturn(Optional.of(telegramUser));

String expectedMessage = "неправильный формат ID группы.\n " +
"ID должно быть целым положительным числом";

//when
command.execute(update);

//then
Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage);
}

@Test
public void shouldProperlyDeleteByGroupId() {
//given

/// prepare update object
Long chatId = 23456L;
Integer groupId = 1234;
Update update = prepareUpdate(chatId, String.format("%s %s", DELETE_GROUP_SUB.getCommandName(), groupId));


GroupSub gs1 = new GroupSub();
gs1.setId(123);
gs1.setTitle("GS1 Title");
TelegramUser telegramUser = new TelegramUser();
telegramUser.setChatId(chatId.toString());
telegramUser.setGroupSubs(singletonList(gs1));
ArrayList<TelegramUser> users = new ArrayList<>();
users.add(telegramUser);
gs1.setUsers(users);
Mockito.when(groupSubService.findById(groupId)).thenReturn(Optional.of(gs1));
Mockito.when(telegramUserService.findByChatId(String.valueOf(chatId)))
.thenReturn(Optional.of(telegramUser));

String expectedMessage = "Удалил подписку на группу: GS1 Title";

//when
command.execute(update);

//then
users.remove(telegramUser);
Mockito.verify(groupSubService).save(gs1);
Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage);
}

@Test
public void shouldDoesNotExistByGroupId() {
//given
Long chatId = 23456L;
Integer groupId = 1234;
Update update = prepareUpdate(chatId, String.format("%s %s", DELETE_GROUP_SUB.getCommandName(), groupId));


Mockito.when(groupSubService.findById(groupId)).thenReturn(Optional.empty());

String expectedMessage = "Не нашел такой группы =/";

//when
command.execute(update);

//then
Mockito.verify(groupSubService).findById(groupId);
Mockito.verify(sendBotMessageService).sendMessage(chatId.toString(), expectedMessage);
}
}

Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package command;

import com.github.JBolivarLi.javarushtelegrambot.bot.command.Command;
import com.github.JBolivarLi.javarushtelegrambot.bot.command.HelpCommand;
import org.junit.jupiter.api.DisplayName;
Expand Down
Loading

0 comments on commit d218909

Please sign in to comment.