Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -264,12 +264,11 @@ public ResponseEntity<ApiResponder<PotdDto>> getCurrentPotd(final HttpServletReq
AuthenticationObject authenticationObject = protector.validateSession(request);
User user = authenticationObject.getUser();

POTD potd = potdRepository.getCurrentPOTD();

if (potd == null || !isSameDay(potd.getCreatedAt())) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponder.failure("Sorry, no problem of the day today!"));
}
POTD potd = potdRepository
.getCurrentPOTD()
.filter(p -> isSameDay(p.getCreatedAt()))
.orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Sorry, no problem of the day today!"));

boolean alreadyCompleted = questionRepository
.getQuestionBySlugAndUserId(potd.getSlug(), user.getId())
Expand Down Expand Up @@ -303,12 +302,11 @@ public ResponseEntity<ApiResponder<PotdDto>> getCurrentPotd(final HttpServletReq
public ResponseEntity<ApiResponder<PotdDto>> getCurrentPotdEmbed() {
FakeLag.sleep(750);

POTD potd = potdRepository.getCurrentPOTD();

if (potd == null || !isSameDay(potd.getCreatedAt())) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponder.failure("Sorry, no problem of the day today!"));
}
POTD potd = potdRepository
.getCurrentPOTD()
.filter(p -> isSameDay(p.getCreatedAt()))
.orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Sorry, no problem of the day today!"));

return ResponseEntity.ok()
.body(ApiResponder.success("Problem of the day has been fetched!", PotdDto.fromPOTD(potd)));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package org.patinanetwork.codebloom.common.db.repos.potd;

import java.util.ArrayList;
import java.util.Optional;
import org.patinanetwork.codebloom.common.db.models.potd.POTD;

public interface POTDRepository {
POTD createPOTD(POTD potd);

POTD getPOTDById(String id);
Optional<POTD> getPOTDById(String id);

POTD getCurrentPOTD();
Optional<POTD> getCurrentPOTD();

ArrayList<POTD> getAllPOTDS();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Optional;
import java.util.UUID;
import javax.sql.DataSource;
import org.patinanetwork.codebloom.common.db.models.potd.POTD;
Expand Down Expand Up @@ -56,22 +57,22 @@ public POTD createPOTD(final POTD potd) {
}

@Override
public POTD getPOTDById(final String id) {
public Optional<POTD> getPOTDById(final String id) {
String sql = "SELECT id, \"title\", \"slug\", \"multiplier\", \"createdAt\" FROM \"POTD\" WHERE id = ?";

try (Connection conn = ds.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setObject(1, UUID.fromString(id));
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return mapRowToPOTD(rs);
return Optional.of(mapRowToPOTD(rs));
}
}
} catch (SQLException e) {
throw new RuntimeException("Failed to get POTD by id", e);
}

return null;
return Optional.empty();
}

@Override
Expand Down Expand Up @@ -118,7 +119,7 @@ public void deletePOTD(final String id) {
}

@Override
public POTD getCurrentPOTD() {
public Optional<POTD> getCurrentPOTD() {
String sql = """
SELECT "id", "title", "slug", "multiplier", "createdAt"
FROM "POTD"
Expand All @@ -130,11 +131,11 @@ public POTD getCurrentPOTD() {
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return mapRowToPOTD(rs);
return Optional.of(mapRowToPOTD(rs));
}
} catch (SQLException e) {
throw new RuntimeException("Failed to get current POTD", e);
}
return null;
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public static <T> Predicate<T> distinctByKey(final Function<? super T, ?> keyExt
public ArrayList<AcceptedSubmission> handleSubmissions(
final List<LeetcodeSubmission> leetcodeSubmissions, final User user, boolean fast) {
ArrayList<AcceptedSubmission> acceptedSubmissions = new ArrayList<>();
POTD potd = potdRepository.getCurrentPOTD();
Optional<POTD> potd = potdRepository.getCurrentPOTD();

var questionMap = leetcodeSubmissions.parallelStream()
.filter(distinctByKey(LeetcodeSubmission::getTitleSlug))
Expand Down Expand Up @@ -154,14 +154,10 @@ public ArrayList<AcceptedSubmission> handleSubmissions(
.getQuestionBySlugAndUserId(leetcodeSubmission.getTitleSlug(), user.getId())
.isPresent();

float multiplier;
if (potd == null
|| !isValid(potd.getCreatedAt())
|| !Objects.equals(potd.getSlug(), leetcodeSubmission.getTitleSlug())) {
multiplier = 1.0f;
} else {
multiplier = potd.getMultiplier();
}
float multiplier = potd.filter(currentPotd -> isValid(currentPotd.getCreatedAt())
&& Objects.equals(currentPotd.getSlug(), leetcodeSubmission.getTitleSlug()))
.map(POTD::getMultiplier)
.orElse(1.0f);

QuestionBank bankQuestion = questionMap.get(leetcodeSubmission.getTitleSlug());

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.patinanetwork.codebloom.scheduled.potd;

import java.util.Optional;
import org.patinanetwork.codebloom.common.db.models.potd.POTD;
import org.patinanetwork.codebloom.common.db.repos.potd.POTDRepository;
import org.patinanetwork.codebloom.common.leetcode.LeetcodeClient;
Expand Down Expand Up @@ -35,8 +36,9 @@ public void setPotd() {
return;
}

POTD currentPotd = potdRepository.getCurrentPOTD();
if (currentPotd != null && currentPotd.getTitle().equals(leetcodePotd.getTitle())) {
Optional<POTD> potd = potdRepository.getCurrentPOTD();

if (potd.map(p -> p.getTitle().equals(leetcodePotd.getTitle())).orElse(false)) {
// It's already the latest POTD, don't want to do it again.
LOGGER.info("POTD has already been set before, will not be doing it again.");
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ void testGetCurrentPotdSuccess() {
when(auth.getUser()).thenReturn(user);
when(user.getId()).thenReturn("abcdefg123456");

when(potdRepository.getCurrentPOTD()).thenReturn(potd);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.of(potd));
when(potd.getCreatedAt()).thenReturn(LocalDateTime.now());
when(potd.getSlug()).thenReturn("two-sum");

Expand All @@ -240,19 +240,19 @@ void testGetCurrentPotdFailure() {

when(protector.validateSession(request)).thenReturn(auth);
when(auth.getUser()).thenReturn(user);
when(potdRepository.getCurrentPOTD()).thenReturn(null);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.empty());

ResponseEntity<ApiResponder<PotdDto>> response = submissionController.getCurrentPotd(request);
ResponseStatusException ex =
assertThrows(ResponseStatusException.class, () -> submissionController.getCurrentPotd(request));

assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
assertFalse(response.getBody().isSuccess());
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
}

@Test
void testGetCurrentPotdEmbedSuccess() {
POTD potd = mock(POTD.class);

when(potdRepository.getCurrentPOTD()).thenReturn(potd);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.of(potd));
when(potd.getCreatedAt()).thenReturn(LocalDateTime.now());

ResponseEntity<ApiResponder<PotdDto>> response = submissionController.getCurrentPotdEmbed();
Expand All @@ -265,12 +265,12 @@ void testGetCurrentPotdEmbedSuccess() {

@Test
void testGetCurrentPotdEmbedFailure() {
when(potdRepository.getCurrentPOTD()).thenReturn(null);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.empty());

ResponseEntity<ApiResponder<PotdDto>> response = submissionController.getCurrentPotdEmbed();
ResponseStatusException ex =
assertThrows(ResponseStatusException.class, () -> submissionController.getCurrentPotdEmbed());

assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
assertFalse(response.getBody().isSuccess());
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.patinanetwork.codebloom.common.db.repos.potd;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
Expand Down Expand Up @@ -55,24 +57,24 @@ void testCreatePOTD() {
@Test
@Order(2)
void testGetPOTDById() {
POTD fetched = potdRepository.getPOTDById(testPOTD.getId());
assertNotNull(fetched);
assertTrue(testPOTD.equals(fetched));
Optional<POTD> fetched = potdRepository.getPOTDById(testPOTD.getId());
assertTrue(fetched.isPresent());
assertTrue(Optional.of(testPOTD).equals(fetched));
}

@Test
@Order(3)
void testGetCurrentPOTD() {
POTD current = potdRepository.getCurrentPOTD();
assertNotNull(current);
assertTrue(testPOTD.equals(current));
Optional<POTD> current = potdRepository.getCurrentPOTD();
assertTrue(current.isPresent());
assertTrue(Optional.of(testPOTD).equals(current));
}

@Test
@Order(4)
void testGetAllPOTDS() {
List<POTD> all = potdRepository.getAllPOTDS();
assertNotNull(all);
assertFalse(all.isEmpty());
assertTrue(all.contains(testPOTD));
}

Expand All @@ -81,7 +83,7 @@ void testGetAllPOTDS() {
void testUpdatePOTD() {
testPOTD.setTitle("Updated Title");
potdRepository.updatePOTD(testPOTD);
POTD updated = potdRepository.getPOTDById(testPOTD.getId());
assertEquals("Updated Title", updated.getTitle());
Optional<POTD> updated = potdRepository.getPOTDById(testPOTD.getId());
assertEquals("Updated Title", updated.get().getTitle());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ private LeetcodeQuestion leetcodeQuestion(String slug, String difficulty, float
@BeforeEach
void commonStubs() {
when(leaderboardRepository.getRecentLeaderboardMetadata()).thenReturn(Optional.of(leaderboard));
when(potdRepository.getCurrentPOTD()).thenReturn(null);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.empty());

when(questionRepository.createQuestion(any(Question.class))).thenAnswer(inv -> {
Question q = inv.getArgument(0);
Expand Down Expand Up @@ -339,14 +339,14 @@ void appliesPotdMultiplier() {
.multiplier(2.0f)
.createdAt(LocalDateTime.now())
.build();
when(potdRepository.getCurrentPOTD()).thenReturn(potd);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.of(potd));

LeetcodeSubmission sub = acceptedSubmission(700, "two-sum", LocalDateTime.of(2025, 6, 1, 12, 0));
when(questionRepository.questionExistsBySubmissionId("700")).thenReturn(false);
when(questionRepository.getQuestionBySlugAndUserId("two-sum", USER_ID)).thenReturn(Optional.empty());
when(leetcodeClient.findQuestionBySlug("two-sum")).thenReturn(leetcodeQuestion("two-sum", "Easy", 50f));

when(potdRepository.getCurrentPOTD()).thenReturn(null);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.empty());
handler.handleSubmissions(
List.of(acceptedSubmission(701, "two-sum", LocalDateTime.of(2025, 6, 1, 12, 0))), user, false);

Expand All @@ -358,7 +358,7 @@ void appliesPotdMultiplier() {
q.setId("q-potd");
return q;
});
when(potdRepository.getCurrentPOTD()).thenReturn(potd);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.of(potd));

ArrayList<AcceptedSubmission> potdResult = handler.handleSubmissions(List.of(sub), user, false);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package org.patinanetwork.codebloom.scheduled.potd;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
Expand Down Expand Up @@ -31,7 +33,7 @@ void testPotdSetterSetPotdWherePotdIsNull() {
@Test
void testPotdSetterSetPotdWherePotdIsFoundButStillCurrentPotd() {
POTD potd = new POTD("Example title", "Example slug", QuestionDifficulty.Easy);
org.patinanetwork.codebloom.common.db.models.potd.POTD dbPotd = org.patinanetwork
Optional<org.patinanetwork.codebloom.common.db.models.potd.POTD> dbPotd = Optional.of(org.patinanetwork
.codebloom
.common
.db
Expand All @@ -44,7 +46,7 @@ void testPotdSetterSetPotdWherePotdIsFoundButStillCurrentPotd() {
.multiplier(1.3f)
.slug(potd.getTitleSlug())
.title(potd.getTitle())
.build();
.build());

when(leetcodeClient.getPotd()).thenReturn(potd);
when(potdRepository.getCurrentPOTD()).thenReturn(dbPotd);
Expand All @@ -59,7 +61,7 @@ void testPotdSetterSetPotdWherePotdIsFoundButStillCurrentPotd() {
void testPotdSetterSetPotdWherePotdIsFoundButNoCurrentPotdYet() {
POTD potd = new POTD("Example title", "Example slug", QuestionDifficulty.Easy);
when(leetcodeClient.getPotd()).thenReturn(potd);
when(potdRepository.getCurrentPOTD()).thenReturn(null);
when(potdRepository.getCurrentPOTD()).thenReturn(Optional.empty());

potdSetter.setPotd();

Expand All @@ -77,7 +79,7 @@ void testPotdSetterSetPotdWherePotdIsFoundButNoCurrentPotdYet() {
@Test
void testPotdSetterSetPotdWherePotdIsFoundAndDoesntMatchOldPotd() {
POTD potd = new POTD("Example title", "Example slug", QuestionDifficulty.Easy);
org.patinanetwork.codebloom.common.db.models.potd.POTD oldDbPotd = org.patinanetwork
Optional<org.patinanetwork.codebloom.common.db.models.potd.POTD> oldDbPotd = Optional.of(org.patinanetwork
.codebloom
.common
.db
Expand All @@ -90,7 +92,7 @@ void testPotdSetterSetPotdWherePotdIsFoundAndDoesntMatchOldPotd() {
.multiplier(1.3f)
.slug("old slug")
.title("old title")
.build();
.build());

when(leetcodeClient.getPotd()).thenReturn(potd);
when(potdRepository.getCurrentPOTD()).thenReturn(oldDbPotd);
Expand All @@ -105,6 +107,5 @@ void testPotdSetterSetPotdWherePotdIsFoundAndDoesntMatchOldPotd() {
assertNotNull(dbPotd);
assertEquals(potd.getTitle(), dbPotd.getTitle());
assertEquals(potd.getTitleSlug(), dbPotd.getSlug());
assertEquals(potd.getDifficulty(), potd.getDifficulty());
}
}
Loading