-
-
Notifications
You must be signed in to change notification settings - Fork 1
feat: notify on chat when new record is established #22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
95fe92d
feat: notify on chat when new record is established
daimonbot 65189b1
test: add unit tests for RecordNotificationService
daimonbot 63c63b9
fix: use Stream-based query for previous best duration
daimonbot 78522d9
fix: add missing Stream import in RecordNotificationServiceTest
daimonbot 4081ec5
test: mock CustomTelegramClient in ApplicationTests
daimonbot a79075b
fix: replace Stream with List in findDistinctDurationsOrderedAsc
daimonbot 4d74038
fix: replace MIN() aggregate with list-based query in GameSessionRepo…
daimonbot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
src/main/java/dev/rubasace/linkedin/games/ldrbot/chat/RecordNotificationService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| package dev.rubasace.linkedin.games.ldrbot.chat; | ||
|
|
||
| import dev.rubasace.linkedin.games.ldrbot.configuration.ExecutorsConfiguration; | ||
| import dev.rubasace.linkedin.games.ldrbot.session.GameSessionRegistrationEvent; | ||
| import dev.rubasace.linkedin.games.ldrbot.session.GameSessionRepository; | ||
| import dev.rubasace.linkedin.games.ldrbot.util.FormatUtils; | ||
| import org.springframework.core.annotation.Order; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.event.TransactionPhase; | ||
| import org.springframework.transaction.event.TransactionalEventListener; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| /** | ||
| * Sends a notification to the group chat when a user establishes a new record | ||
| * (i.e., the fastest time ever registered for a given game in the group). | ||
| */ | ||
| @Component | ||
| public class RecordNotificationService { | ||
|
|
||
| private static final String NEW_RECORD_MESSAGE_TEMPLATE = "\uD83C\uDFC6 <b>New %s record!</b>\n%s set a new group record with a time of <b>%s</b>! \uD83C\uDF89"; | ||
| private static final String RECORD_BROKEN_MESSAGE_TEMPLATE = "\uD83C\uDFC6 <b>New %s record!</b>\n%s set a new group record with a time of <b>%s</b> (previous record: %s)! \uD83C\uDF89"; | ||
|
|
||
| private static final int RECORD_NOTIFICATION_ORDER = NotificationService.USER_INTERACTION_NOTIFICATION_ORDER + 1; | ||
|
|
||
| private final CustomTelegramClient customTelegramClient; | ||
| private final GameSessionRepository gameSessionRepository; | ||
|
|
||
| RecordNotificationService(final CustomTelegramClient customTelegramClient, final GameSessionRepository gameSessionRepository) { | ||
| this.customTelegramClient = customTelegramClient; | ||
| this.gameSessionRepository = gameSessionRepository; | ||
| } | ||
|
|
||
| @Order(RECORD_NOTIFICATION_ORDER) | ||
| @Async(ExecutorsConfiguration.NOTIFICATION_LISTENER_EXECUTOR_NAME) | ||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) | ||
| void handleSessionRegistration(final GameSessionRegistrationEvent event) { | ||
| Duration submittedDuration = event.getDuration(); | ||
| Long chatId = event.getChatId(); | ||
|
|
||
| // Get all distinct durations ordered ascending (best first) | ||
| List<Duration> distinctDurations = gameSessionRepository.findDistinctDurationsOrderedAsc(chatId, event.getGameType()); | ||
|
|
||
| if (distinctDurations.isEmpty()) { | ||
| return; // No durations found (should not happen) | ||
| } | ||
|
|
||
| Duration bestDuration = distinctDurations.get(0); | ||
|
|
||
| // If the best duration in the DB is not the submitted one, this is not a record | ||
| if (submittedDuration.compareTo(bestDuration) != 0) { | ||
| return; | ||
| } | ||
|
|
||
| // Find the previous best (second best duration after the current record) | ||
| Optional<Duration> previousBest = distinctDurations.size() > 1 | ||
| ? Optional.of(distinctDurations.get(1)) // Get the second one (previous best) | ||
| : Optional.empty(); | ||
|
|
||
| String gameName = event.getGameInfo().name(); | ||
| String userMention = FormatUtils.formatUserMention(event.getUserInfo()); | ||
| String formattedDuration = FormatUtils.formatDuration(submittedDuration); | ||
|
|
||
| if (previousBest.isPresent()) { | ||
| // There was a previous record — show it | ||
| customTelegramClient.sendMessage( | ||
| RECORD_BROKEN_MESSAGE_TEMPLATE.formatted(gameName, userMention, formattedDuration, FormatUtils.formatDuration(previousBest.get())), | ||
| event.getChatInfo().chatId() | ||
| ); | ||
| } else { | ||
| // First ever submission for this game — it's the first record | ||
| customTelegramClient.sendMessage( | ||
| NEW_RECORD_MESSAGE_TEMPLATE.formatted(gameName, userMention, formattedDuration), | ||
| event.getChatInfo().chatId() | ||
| ); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
src/test/java/dev/rubasace/linkedin/games/ldrbot/chat/RecordNotificationServiceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| package dev.rubasace.linkedin.games.ldrbot.chat; | ||
|
|
||
| import dev.rubasace.linkedin.games.ldrbot.group.ChatInfo; | ||
| import dev.rubasace.linkedin.games.ldrbot.session.*; | ||
| import dev.rubasace.linkedin.games.ldrbot.user.UserInfo; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.extension.ExtendWith; | ||
| import org.mockito.ArgumentCaptor; | ||
| import org.mockito.Mock; | ||
| import org.mockito.junit.jupiter.MockitoExtension; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.LocalDate; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.*; | ||
| import static org.mockito.Mockito.*; | ||
|
|
||
| @ExtendWith(MockitoExtension.class) | ||
| class RecordNotificationServiceTest { | ||
|
|
||
| @Mock | ||
| private CustomTelegramClient customTelegramClient; | ||
|
|
||
| @Mock | ||
| private GameSessionRepository gameSessionRepository; | ||
|
|
||
| private RecordNotificationService service; | ||
|
|
||
| private static final Long CHAT_ID = 123L; | ||
| private static final GameType GAME = GameType.QUEENS; | ||
| private static final ChatInfo CHAT_INFO = new ChatInfo(CHAT_ID, "Test Group", true); | ||
| private static final UserInfo USER_INFO = new UserInfo(1L, "testuser", "Test", "User"); | ||
| private static final GameInfo GAME_INFO = new GameInfo("Queens", "👑"); | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| service = new RecordNotificationService(customTelegramClient, gameSessionRepository); | ||
| } | ||
|
|
||
| private GameSessionRegistrationEvent createEvent(Duration duration) { | ||
| return new GameSessionRegistrationEvent(this, CHAT_INFO, USER_INFO, GAME_INFO, GAME, duration, LocalDate.now(), CHAT_ID); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldNotNotifyWhenSubmittedDurationIsNotTheBest() { | ||
| Duration submitted = Duration.ofSeconds(120); | ||
| Duration best = Duration.ofSeconds(60); | ||
| when(gameSessionRepository.findDistinctDurationsOrderedAsc(CHAT_ID, GAME)).thenReturn(List.of(best, submitted)); | ||
|
|
||
| service.handleSessionRegistration(createEvent(submitted)); | ||
|
|
||
| verifyNoInteractions(customTelegramClient); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldNotNotifyWhenNoBestDurationFound() { | ||
| when(gameSessionRepository.findDistinctDurationsOrderedAsc(CHAT_ID, GAME)).thenReturn(List.of()); | ||
|
|
||
| service.handleSessionRegistration(createEvent(Duration.ofSeconds(60))); | ||
|
|
||
| verifyNoInteractions(customTelegramClient); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldNotifyFirstRecordEver() { | ||
| Duration submitted = Duration.ofSeconds(90); | ||
| when(gameSessionRepository.findDistinctDurationsOrderedAsc(CHAT_ID, GAME)).thenReturn(List.of(submitted)); | ||
|
|
||
| service.handleSessionRegistration(createEvent(submitted)); | ||
|
|
||
| ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class); | ||
| verify(customTelegramClient).sendMessage(messageCaptor.capture(), eq(CHAT_ID)); | ||
| String message = messageCaptor.getValue(); | ||
| assertTrue(message.contains("New Queens record!")); | ||
| assertTrue(message.contains("@testuser")); | ||
| assertTrue(message.contains("01:30")); | ||
| assertFalse(message.contains("previous record")); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldNotifyRecordBrokenWithPreviousBest() { | ||
| Duration submitted = Duration.ofSeconds(45); | ||
| Duration previous = Duration.ofSeconds(90); | ||
| when(gameSessionRepository.findDistinctDurationsOrderedAsc(CHAT_ID, GAME)).thenReturn(List.of(submitted, previous)); | ||
|
|
||
| service.handleSessionRegistration(createEvent(submitted)); | ||
|
|
||
| ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class); | ||
| verify(customTelegramClient).sendMessage(messageCaptor.capture(), eq(CHAT_ID)); | ||
| String message = messageCaptor.getValue(); | ||
| assertTrue(message.contains("New Queens record!")); | ||
| assertTrue(message.contains("@testuser")); | ||
| assertTrue(message.contains("00:45")); | ||
| assertTrue(message.contains("previous record: 01:30")); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldFormatUserWithoutUsernameAsMention() { | ||
| UserInfo noUsername = new UserInfo(42L, null, "John", "Doe"); | ||
| Duration submitted = Duration.ofSeconds(30); | ||
| GameSessionRegistrationEvent event = new GameSessionRegistrationEvent(this, CHAT_INFO, noUsername, GAME_INFO, GAME, submitted, LocalDate.now(), CHAT_ID); | ||
| when(gameSessionRepository.findDistinctDurationsOrderedAsc(CHAT_ID, GAME)).thenReturn(List.of(submitted)); | ||
|
|
||
| service.handleSessionRegistration(event); | ||
|
|
||
| ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class); | ||
| verify(customTelegramClient).sendMessage(messageCaptor.capture(), eq(CHAT_ID)); | ||
| String message = messageCaptor.getValue(); | ||
| assertTrue(message.contains("tg://user?id=42")); | ||
| assertTrue(message.contains("John Doe")); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what's the reason for this change?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The visibility was changed from
privateto package-private so thatRecordNotificationService(in the same package) can referenceUSER_INTERACTION_NOTIFICATION_ORDERto define its ownRECORD_NOTIFICATION_ORDER = USER_INTERACTION_NOTIFICATION_ORDER + 1. This ensures the record notification is sent after the user interaction notification, maintaining a consistent ordering.