Display paginated reading sessions in the book metadata view (#2003)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+10
-92
@@ -1,19 +1,17 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.*;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionResponse;
|
||||
import com.adityachandel.booklore.service.ReadingSessionService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@AllArgsConstructor
|
||||
@RequestMapping("/api/v1/reading-sessions")
|
||||
@@ -32,95 +30,15 @@ public class ReadingSessionController {
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading session heatmap for a year", description = "Returns daily reading session counts for the authenticated user for a specific year")
|
||||
@Operation(summary = "Get reading sessions for a book", description = "Returns paginated reading sessions for a specific book for the authenticated user")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Heatmap data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
@ApiResponse(responseCode = "200", description = "Reading sessions retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized"),
|
||||
@ApiResponse(responseCode = "404", description = "Book not found")
|
||||
})
|
||||
@GetMapping("/heatmap/year/{year}")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getHeatmapForYear(@PathVariable int year) {
|
||||
List<ReadingSessionHeatmapResponse> heatmapData = readingSessionService.getSessionHeatmapForYear(year);
|
||||
return ResponseEntity.ok(heatmapData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading session timeline for a week", description = "Returns reading sessions grouped by book for calendar timeline view")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Timeline data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid week, month, or year"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/timeline/week/{year}/{month}/{week}")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSessionTimelineResponse>> getTimelineForWeek(
|
||||
@PathVariable int year,
|
||||
@PathVariable int month,
|
||||
@PathVariable int week) {
|
||||
List<ReadingSessionTimelineResponse> timelineData = readingSessionService.getSessionTimelineForWeek(year, month, week);
|
||||
return ResponseEntity.ok(timelineData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading speed analysis", description = "Returns average reading speed (progress per minute) over time for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Reading speed data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/speed/year/{year}")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSpeedResponse>> getReadingSpeedForYear(@PathVariable int year) {
|
||||
List<ReadingSpeedResponse> speedData = readingSessionService.getReadingSpeedForYear(year);
|
||||
return ResponseEntity.ok(speedData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get peak reading hours", description = "Returns reading activity distribution by hour of day. Can be filtered by year and/or month.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Peak reading hours retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/peak-hours")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<PeakReadingHoursResponse>> getPeakReadingHours(
|
||||
@RequestParam(required = false) Integer year,
|
||||
@RequestParam(required = false) Integer month) {
|
||||
List<PeakReadingHoursResponse> peakHours = readingSessionService.getPeakReadingHours(year, month);
|
||||
return ResponseEntity.ok(peakHours);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get favorite reading days", description = "Returns reading activity distribution by day of week. Can be filtered by year and/or month.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Favorite reading days retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/favorite-days")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<FavoriteReadingDaysResponse>> getFavoriteReadingDays(
|
||||
@RequestParam(required = false) Integer year,
|
||||
@RequestParam(required = false) Integer month) {
|
||||
List<FavoriteReadingDaysResponse> favoriteDays = readingSessionService.getFavoriteReadingDays(year, month);
|
||||
return ResponseEntity.ok(favoriteDays);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get genre statistics", description = "Returns reading statistics grouped by book genres/categories")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Genre statistics retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/genres")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<GenreStatisticsResponse>> getGenreStatistics() {
|
||||
List<GenreStatisticsResponse> genreStats = readingSessionService.getGenreStatistics();
|
||||
return ResponseEntity.ok(genreStats);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get completion timeline", description = "Returns reading completion statistics over time with status breakdown for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Completion timeline retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/stats/completion-timeline/year/{year}")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<CompletionTimelineResponse>> getCompletionTimeline(@PathVariable int year) {
|
||||
List<CompletionTimelineResponse> timeline = readingSessionService.getCompletionTimeline(year);
|
||||
return ResponseEntity.ok(timeline);
|
||||
@GetMapping("/book/{bookId}")
|
||||
public ResponseEntity<Page<ReadingSessionResponse>> getReadingSessionsForBook(@PathVariable Long bookId, @RequestParam(defaultValue = "0") int page) {
|
||||
Page<ReadingSessionResponse> sessions = readingSessionService.getReadingSessionsForBook(bookId, page);
|
||||
return ResponseEntity.ok(sessions);
|
||||
}
|
||||
}
|
||||
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.response.*;
|
||||
import com.adityachandel.booklore.service.ReadingSessionService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@AllArgsConstructor
|
||||
@RequestMapping("/api/v1/user-stats")
|
||||
public class UserStatsController {
|
||||
|
||||
private final ReadingSessionService readingSessionService;
|
||||
|
||||
@Operation(summary = "Get reading session heatmap for a year", description = "Returns daily reading session counts for the authenticated user for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Heatmap data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/heatmap")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getHeatmapForYear(@RequestParam int year) {
|
||||
List<ReadingSessionHeatmapResponse> heatmapData = readingSessionService.getSessionHeatmapForYear(year);
|
||||
return ResponseEntity.ok(heatmapData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading session timeline for a week", description = "Returns reading sessions grouped by book for calendar timeline view")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Timeline data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid week, month, or year"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/timeline")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSessionTimelineResponse>> getTimelineForWeek(
|
||||
@RequestParam int year,
|
||||
@RequestParam int month,
|
||||
@RequestParam int week) {
|
||||
List<ReadingSessionTimelineResponse> timelineData = readingSessionService.getSessionTimelineForWeek(year, month, week);
|
||||
return ResponseEntity.ok(timelineData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get reading speed analysis", description = "Returns average reading speed (progress per minute) over time for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Reading speed data retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/speed")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<ReadingSpeedResponse>> getReadingSpeedForYear(@RequestParam int year) {
|
||||
List<ReadingSpeedResponse> speedData = readingSessionService.getReadingSpeedForYear(year);
|
||||
return ResponseEntity.ok(speedData);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get peak reading hours", description = "Returns reading activity distribution by hour of day. Can be filtered by year and/or month.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Peak reading hours retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/peak-hours")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<PeakReadingHoursResponse>> getPeakReadingHours(
|
||||
@RequestParam(required = false) Integer year,
|
||||
@RequestParam(required = false) Integer month) {
|
||||
List<PeakReadingHoursResponse> peakHours = readingSessionService.getPeakReadingHours(year, month);
|
||||
return ResponseEntity.ok(peakHours);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get favorite reading days", description = "Returns reading activity distribution by day of week. Can be filtered by year and/or month.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Favorite reading days retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/favorite-days")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<FavoriteReadingDaysResponse>> getFavoriteReadingDays(
|
||||
@RequestParam(required = false) Integer year,
|
||||
@RequestParam(required = false) Integer month) {
|
||||
List<FavoriteReadingDaysResponse> favoriteDays = readingSessionService.getFavoriteReadingDays(year, month);
|
||||
return ResponseEntity.ok(favoriteDays);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get genre statistics", description = "Returns reading statistics grouped by book genres/categories")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Genre statistics retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/genres")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<GenreStatisticsResponse>> getGenreStatistics() {
|
||||
List<GenreStatisticsResponse> genreStats = readingSessionService.getGenreStatistics();
|
||||
return ResponseEntity.ok(genreStats);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get completion timeline", description = "Returns reading completion statistics over time with status breakdown for a specific year")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Completion timeline retrieved successfully"),
|
||||
@ApiResponse(responseCode = "401", description = "Unauthorized")
|
||||
})
|
||||
@GetMapping("/completion-timeline")
|
||||
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<CompletionTimelineResponse>> getCompletionTimeline(@RequestParam int year) {
|
||||
List<CompletionTimelineResponse> timeline = readingSessionService.getCompletionTimeline(year);
|
||||
return ResponseEntity.ok(timeline);
|
||||
}
|
||||
}
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ReadingSessionResponse {
|
||||
private Long id;
|
||||
private Long bookId;
|
||||
private String bookTitle;
|
||||
private BookFileType bookType;
|
||||
private Instant startTime;
|
||||
private Instant endTime;
|
||||
private Integer durationSeconds;
|
||||
private Float startProgress;
|
||||
private Float endProgress;
|
||||
private Float progressDelta;
|
||||
private String startLocation;
|
||||
private String endLocation;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
|
||||
+14
@@ -2,6 +2,8 @@ package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
@@ -109,4 +111,16 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
|
||||
ORDER BY totalSessions DESC
|
||||
""")
|
||||
List<GenreStatisticsDto> findGenreStatisticsByUser(@Param("userId") Long userId);
|
||||
|
||||
@Query("""
|
||||
SELECT rs
|
||||
FROM ReadingSessionEntity rs
|
||||
WHERE rs.user.id = :userId
|
||||
AND rs.book.id = :bookId
|
||||
ORDER BY rs.startTime DESC
|
||||
""")
|
||||
Page<ReadingSessionEntity> findByUserIdAndBookId(
|
||||
@Param("userId") Long userId,
|
||||
@Param("bookId") Long bookId,
|
||||
Pageable pageable);
|
||||
}
|
||||
|
||||
+31
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.model.dto.response.FavoriteReadingDaysResponse
|
||||
import com.adityachandel.booklore.model.dto.response.GenreStatisticsResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.PeakReadingHoursResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.ReadingSpeedResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
@@ -21,6 +22,9 @@ import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -210,4 +214,31 @@ public class ReadingSessionService {
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page) {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
Long userId = authenticatedUser.getId();
|
||||
|
||||
bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
Pageable pageable = PageRequest.of(page, 5);
|
||||
Page<ReadingSessionEntity> sessions = readingSessionRepository.findByUserIdAndBookId(userId, bookId, pageable);
|
||||
|
||||
return sessions.map(session -> ReadingSessionResponse.builder()
|
||||
.id(session.getId())
|
||||
.bookId(session.getBook().getId())
|
||||
.bookTitle(session.getBook().getMetadata().getTitle())
|
||||
.bookType(session.getBookType())
|
||||
.startTime(session.getStartTime())
|
||||
.endTime(session.getEndTime())
|
||||
.durationSeconds(session.getDurationSeconds())
|
||||
.startProgress(session.getStartProgress())
|
||||
.endProgress(session.getEndProgress())
|
||||
.progressDelta(session.getProgressDelta())
|
||||
.startLocation(session.getStartLocation())
|
||||
.endLocation(session.getEndLocation())
|
||||
.createdAt(session.getCreatedAt())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user