From 2c1e8a99e3cb365ce66c7a5c78957bc7e40cb278 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Fri, 26 Dec 2025 12:08:27 -0700 Subject: [PATCH] Add more user-specific charts (#1991) Co-authored-by: acx10 --- .../controller/ReadingSessionController.java | 76 +++- .../model/dto/CompletionTimelineDto.java | 11 + .../model/dto/FavoriteReadingDayDto.java | 8 + .../model/dto/GenreStatisticsDto.java | 9 + .../model/dto/PeakReadingHourDto.java | 8 + .../booklore/model/dto/ReadingSpeedDto.java | 11 + .../response/CompletionTimelineResponse.java | 23 ++ .../response/FavoriteReadingDaysResponse.java | 18 + .../dto/response/GenreStatisticsResponse.java | 19 + .../response/PeakReadingHoursResponse.java | 17 + .../dto/response/ReadingSpeedResponse.java | 19 + .../repository/ReadingSessionRepository.java | 73 +++- .../UserBookProgressRepository.java | 20 + .../service/ReadingSessionService.java | 124 +++++- .../user-management/user-stats.service.ts | 76 +++- .../completion-timeline-chart.component.html | 34 ++ .../completion-timeline-chart.component.scss | 132 ++++++ .../completion-timeline-chart.component.ts | 235 +++++++++++ .../favorite-days-chart.component.html | 38 ++ .../favorite-days-chart.component.scss | 95 +++++ .../favorite-days-chart.component.ts | 261 ++++++++++++ .../genre-stats-chart.component.html | 18 + .../genre-stats-chart.component.scss | 57 +++ .../genre-stats-chart.component.ts | 199 +++++++++ .../peak-hours-chart.component.html | 38 ++ .../peak-hours-chart.component.scss | 95 +++++ .../peak-hours-chart.component.ts | 278 +++++++++++++ .../reading-dna-chart.component.html | 37 ++ .../reading-dna-chart.component.scss | 137 +++++++ .../reading-dna-chart.component.ts} | 113 +++--- .../reading-habits-chart.component.html | 37 ++ .../reading-habits-chart.component.scss | 137 +++++++ .../reading-habits-chart.component.ts} | 173 ++++---- .../reading-session-heatmap.component.html | 3 +- .../reading-session-heatmap.component.scss | 102 +++-- .../reading-session-heatmap.component.ts | 11 +- .../reading-session-timeline.component.html | 26 +- .../reading-session-timeline.component.scss | 215 ++++++++-- .../reading-session-timeline.component.ts | 77 +++- .../stats/component/stats-component.html | 64 --- .../stats/component/stats-component.scss | 4 +- .../stats/component/stats-component.ts | 4 - .../user-stats/user-stats.component.html | 102 ++++- .../user-stats/user-stats.component.scss | 328 ++++++++++++++- .../user-stats/user-stats.component.ts | 76 +++- .../author-series-portfolio-chart.service.ts | 355 ---------------- .../stats/service/chart-config.service.ts | 4 +- .../finished-books-timeline-chart.service.ts | 54 --- .../service/reading-velocity-chart.service.ts | 380 ------------------ ...eries-completion-progress-chart.service.ts | 327 --------------- ...eries-length-distribution-chart.service.ts | 298 -------------- .../series-standalone-chart.service.ts | 309 -------------- .../service/user-chart-config.service.ts | 166 ++++++++ 53 files changed, 3411 insertions(+), 2120 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CompletionTimelineDto.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/FavoriteReadingDayDto.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/GenreStatisticsDto.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/PeakReadingHourDto.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/ReadingSpeedDto.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/CompletionTimelineResponse.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/FavoriteReadingDaysResponse.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/GenreStatisticsResponse.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/PeakReadingHoursResponse.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSpeedResponse.java create mode 100644 booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.ts create mode 100644 booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.ts create mode 100644 booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.ts create mode 100644 booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.ts create mode 100644 booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.scss rename booklore-ui/src/app/features/stats/{service/reading-dna-chart.service.ts => component/reading-dna-chart/reading-dna-chart.component.ts} (81%) create mode 100644 booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.scss rename booklore-ui/src/app/features/stats/{service/reading-habits-chart.service.ts => component/reading-habits-chart/reading-habits-chart.component.ts} (76%) delete mode 100644 booklore-ui/src/app/features/stats/service/author-series-portfolio-chart.service.ts delete mode 100644 booklore-ui/src/app/features/stats/service/finished-books-timeline-chart.service.ts delete mode 100644 booklore-ui/src/app/features/stats/service/reading-velocity-chart.service.ts delete mode 100644 booklore-ui/src/app/features/stats/service/series-completion-progress-chart.service.ts delete mode 100644 booklore-ui/src/app/features/stats/service/series-length-distribution-chart.service.ts delete mode 100644 booklore-ui/src/app/features/stats/service/series-standalone-chart.service.ts create mode 100644 booklore-ui/src/app/features/stats/service/user-chart-config.service.ts diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java index 19c33b34f..1c7ba343e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java @@ -1,20 +1,17 @@ package com.adityachandel.booklore.controller; import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest; -import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse; -import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse; +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 jakarta.validation.Valid; import lombok.AllArgsConstructor; -import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import java.time.LocalDateTime; import java.util.List; @RestController @@ -50,15 +47,80 @@ public class ReadingSessionController { @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 or year"), + @ApiResponse(responseCode = "400", description = "Invalid week, month, or year"), @ApiResponse(responseCode = "401", description = "Unauthorized") }) - @GetMapping("/timeline/week/{year}/{week}") + @GetMapping("/timeline/week/{year}/{month}/{week}") @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") public ResponseEntity> getTimelineForWeek( @PathVariable int year, + @PathVariable int month, @PathVariable int week) { - List timelineData = readingSessionService.getSessionTimelineForWeek(year, week); + List 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> getReadingSpeedForYear(@PathVariable int year) { + List 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> getPeakReadingHours( + @RequestParam(required = false) Integer year, + @RequestParam(required = false) Integer month) { + List 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> getFavoriteReadingDays( + @RequestParam(required = false) Integer year, + @RequestParam(required = false) Integer month) { + List 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> getGenreStatistics() { + List 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> getCompletionTimeline(@PathVariable int year) { + List timeline = readingSessionService.getCompletionTimeline(year); + return ResponseEntity.ok(timeline); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CompletionTimelineDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CompletionTimelineDto.java new file mode 100644 index 000000000..68981db82 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CompletionTimelineDto.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.model.dto; + +import com.adityachandel.booklore.model.enums.ReadStatus; + +public interface CompletionTimelineDto { + Integer getYear(); + Integer getMonth(); + ReadStatus getReadStatus(); + Long getBookCount(); +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/FavoriteReadingDayDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/FavoriteReadingDayDto.java new file mode 100644 index 000000000..90baff4c9 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/FavoriteReadingDayDto.java @@ -0,0 +1,8 @@ +package com.adityachandel.booklore.model.dto; + +public interface FavoriteReadingDayDto { + Integer getDayOfWeek(); + Long getSessionCount(); + Long getTotalDurationSeconds(); +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/GenreStatisticsDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/GenreStatisticsDto.java new file mode 100644 index 000000000..b77867593 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/GenreStatisticsDto.java @@ -0,0 +1,9 @@ +package com.adityachandel.booklore.model.dto; + +public interface GenreStatisticsDto { + String getGenre(); + Long getBookCount(); + Long getTotalSessions(); + Long getTotalDurationSeconds(); +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/PeakReadingHourDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/PeakReadingHourDto.java new file mode 100644 index 000000000..4c6dfa5d0 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/PeakReadingHourDto.java @@ -0,0 +1,8 @@ +package com.adityachandel.booklore.model.dto; + +public interface PeakReadingHourDto { + Integer getHourOfDay(); + Long getSessionCount(); + Long getTotalDurationSeconds(); +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/ReadingSpeedDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/ReadingSpeedDto.java new file mode 100644 index 000000000..5c75e7e93 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/ReadingSpeedDto.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.model.dto; + +import java.time.LocalDate; + + +public interface ReadingSpeedDto { + Integer getTotalSessions(); + Double getAvgProgressPerMinute(); + LocalDate getDate(); +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/CompletionTimelineResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/CompletionTimelineResponse.java new file mode 100644 index 000000000..45cc21100 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/CompletionTimelineResponse.java @@ -0,0 +1,23 @@ +package com.adityachandel.booklore.model.dto.response; + +import com.adityachandel.booklore.model.enums.ReadStatus; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CompletionTimelineResponse { + private Integer year; + private Integer month; + private Long totalBooks; + private Map statusBreakdown; + private Long finishedBooks; + private Double completionRate; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/FavoriteReadingDaysResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/FavoriteReadingDaysResponse.java new file mode 100644 index 000000000..8ec4363e8 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/FavoriteReadingDaysResponse.java @@ -0,0 +1,18 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class FavoriteReadingDaysResponse { + private Integer dayOfWeek; // 1=Monday, 7=Sunday + private String dayName; + private Long sessionCount; + private Long totalDurationSeconds; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/GenreStatisticsResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/GenreStatisticsResponse.java new file mode 100644 index 000000000..1bd8d91e2 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/GenreStatisticsResponse.java @@ -0,0 +1,19 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class GenreStatisticsResponse { + private String genre; + private Long bookCount; + private Long totalSessions; + private Long totalDurationSeconds; + private Double averageSessionsPerBook; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/PeakReadingHoursResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/PeakReadingHoursResponse.java new file mode 100644 index 000000000..148428d6a --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/PeakReadingHoursResponse.java @@ -0,0 +1,17 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PeakReadingHoursResponse { + private Integer hourOfDay; + private Long sessionCount; + private Long totalDurationSeconds; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSpeedResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSpeedResponse.java new file mode 100644 index 000000000..30ff34a37 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSpeedResponse.java @@ -0,0 +1,19 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ReadingSpeedResponse { + private LocalDate date; + private Double avgProgressPerMinute; + private Integer totalSessions; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java index e6002c32f..3bfbc41c1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java @@ -1,7 +1,6 @@ package com.adityachandel.booklore.repository; -import com.adityachandel.booklore.model.dto.ReadingSessionCountDto; -import com.adityachandel.booklore.model.dto.ReadingSessionTimelineDto; +import com.adityachandel.booklore.model.dto.*; import com.adityachandel.booklore.model.entity.ReadingSessionEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -36,12 +35,78 @@ public interface ReadingSessionRepository extends JpaRepository findSessionTimelineByUserAndWeek( @Param("userId") Long userId, @Param("year") int year, - @Param("weekOfYear") int weekOfYear); + @Param("month") int month, + @Param("week") int week); + + @Query(""" + SELECT + CAST(rs.createdAt AS LocalDate) as date, + AVG(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute, + COUNT(rs) as totalSessions + FROM ReadingSessionEntity rs + WHERE rs.user.id = :userId + AND rs.durationSeconds > 0 + AND rs.progressDelta > 0 + AND YEAR(rs.createdAt) = :year + GROUP BY CAST(rs.createdAt AS LocalDate) + ORDER BY date + """) + List findReadingSpeedByUserAndYear(@Param("userId") Long userId, @Param("year") int year); + + @Query(""" + SELECT + HOUR(rs.startTime) as hourOfDay, + COUNT(rs) as sessionCount, + SUM(rs.durationSeconds) as totalDurationSeconds + FROM ReadingSessionEntity rs + WHERE rs.user.id = :userId + AND (:year IS NULL OR YEAR(rs.startTime) = :year) + AND (:month IS NULL OR MONTH(rs.startTime) = :month) + GROUP BY HOUR(rs.startTime) + ORDER BY hourOfDay + """) + List findPeakReadingHoursByUser( + @Param("userId") Long userId, + @Param("year") Integer year, + @Param("month") Integer month); + + @Query(""" + SELECT + DAYOFWEEK(rs.startTime) as dayOfWeek, + COUNT(rs) as sessionCount, + SUM(rs.durationSeconds) as totalDurationSeconds + FROM ReadingSessionEntity rs + WHERE rs.user.id = :userId + AND (:year IS NULL OR YEAR(rs.startTime) = :year) + AND (:month IS NULL OR MONTH(rs.startTime) = :month) + GROUP BY DAYOFWEEK(rs.startTime) + ORDER BY dayOfWeek + """) + List findFavoriteReadingDaysByUser( + @Param("userId") Long userId, + @Param("year") Integer year, + @Param("month") Integer month); + + @Query(""" + SELECT + c.name as genre, + COUNT(DISTINCT b.id) as bookCount, + COUNT(rs) as totalSessions, + SUM(rs.durationSeconds) as totalDurationSeconds + FROM ReadingSessionEntity rs + JOIN rs.book b + JOIN b.metadata.categories c + WHERE rs.user.id = :userId + GROUP BY c.name + ORDER BY totalSessions DESC + """) + List findGenreStatisticsByUser(@Param("userId") Long userId); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java index 312f1b716..ca6a358a3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java @@ -1,5 +1,6 @@ package com.adityachandel.booklore.repository; +import com.adityachandel.booklore.model.dto.CompletionTimelineDto; import com.adityachandel.booklore.model.entity.UserBookProgressEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -40,4 +41,23 @@ public interface UserBookProgressRepository extends JpaRepository findCompletionTimelineByUser(@Param("userId") Long userId, @Param("year") int year); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java index e3883fbd5..b423117b5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java @@ -4,13 +4,20 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.dto.BookLoreUser; import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest; +import com.adityachandel.booklore.model.dto.response.CompletionTimelineResponse; +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.ReadingSessionTimelineResponse; +import com.adityachandel.booklore.model.dto.response.ReadingSpeedResponse; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.model.entity.ReadingSessionEntity; +import com.adityachandel.booklore.model.enums.ReadStatus; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.ReadingSessionRepository; +import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -18,7 +25,9 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; @Slf4j @@ -30,6 +39,7 @@ public class ReadingSessionService { private final ReadingSessionRepository readingSessionRepository; private final BookRepository bookRepository; private final UserRepository userRepository; + private final UserBookProgressRepository userBookProgressRepository; @Transactional public void recordSession(ReadingSessionRequest request) { @@ -73,11 +83,11 @@ public class ReadingSessionService { } @Transactional(readOnly = true) - public List getSessionTimelineForWeek(int year, int week) { + public List getSessionTimelineForWeek(int year, int month, int week) { BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); Long userId = authenticatedUser.getId(); - return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, year, week) + return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, year, month, week) .stream() .map(dto -> ReadingSessionTimelineResponse.builder() .bookId(dto.getBookId()) @@ -90,4 +100,114 @@ public class ReadingSessionService { .build()) .collect(Collectors.toList()); } + + @Transactional(readOnly = true) + public List getReadingSpeedForYear(int year) { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + Long userId = authenticatedUser.getId(); + + return readingSessionRepository.findReadingSpeedByUserAndYear(userId, year) + .stream() + .map(dto -> ReadingSpeedResponse.builder() + .date(dto.getDate()) + .avgProgressPerMinute(dto.getAvgProgressPerMinute()) + .totalSessions(dto.getTotalSessions()) + .build()) + .collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public List getPeakReadingHours(Integer year, Integer month) { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + Long userId = authenticatedUser.getId(); + + return readingSessionRepository.findPeakReadingHoursByUser(userId, year, month) + .stream() + .map(dto -> PeakReadingHoursResponse.builder() + .hourOfDay(dto.getHourOfDay()) + .sessionCount(dto.getSessionCount()) + .totalDurationSeconds(dto.getTotalDurationSeconds()) + .build()) + .collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public List getFavoriteReadingDays(Integer year, Integer month) { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + Long userId = authenticatedUser.getId(); + + String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + + return readingSessionRepository.findFavoriteReadingDaysByUser(userId, year, month) + .stream() + .map(dto -> FavoriteReadingDaysResponse.builder() + .dayOfWeek(dto.getDayOfWeek()) + .dayName(dayNames[dto.getDayOfWeek() - 1]) + .sessionCount(dto.getSessionCount()) + .totalDurationSeconds(dto.getTotalDurationSeconds()) + .build()) + .collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public List getGenreStatistics() { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + Long userId = authenticatedUser.getId(); + + return readingSessionRepository.findGenreStatisticsByUser(userId) + .stream() + .map(dto -> { + double avgSessionsPerBook = dto.getBookCount() > 0 + ? (double) dto.getTotalSessions() / dto.getBookCount() + : 0.0; + + return GenreStatisticsResponse.builder() + .genre(dto.getGenre()) + .bookCount(dto.getBookCount()) + .totalSessions(dto.getTotalSessions()) + .totalDurationSeconds(dto.getTotalDurationSeconds()) + .averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0) + .build(); + }) + .collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public List getCompletionTimeline(int year) { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + Long userId = authenticatedUser.getId(); + Map> timelineMap = new HashMap<>(); + + userBookProgressRepository.findCompletionTimelineByUser(userId, year).forEach(dto -> { + String key = dto.getYear() + "-" + dto.getMonth(); + timelineMap.computeIfAbsent(key, k -> new HashMap<>()) + .put(dto.getReadStatus(), dto.getBookCount()); + }); + + return timelineMap.entrySet().stream() + .map(entry -> { + String[] parts = entry.getKey().split("-"); + int yearPart = Integer.parseInt(parts[0]); + int month = Integer.parseInt(parts[1]); + Map statusBreakdown = entry.getValue(); + + long totalBooks = statusBreakdown.values().stream().mapToLong(Long::longValue).sum(); + long finishedBooks = statusBreakdown.getOrDefault(ReadStatus.READ, 0L); + double completionRate = totalBooks > 0 ? (finishedBooks * 100.0 / totalBooks) : 0.0; + + return CompletionTimelineResponse.builder() + .year(yearPart) + .month(month) + .totalBooks(totalBooks) + .statusBreakdown(statusBreakdown) + .finishedBooks(finishedBooks) + .completionRate(Math.round(completionRate * 100.0) / 100.0) + .build(); + }) + .sorted((a, b) -> { + int cmp = b.getYear().compareTo(a.getYear()); + return cmp != 0 ? cmp : b.getMonth().compareTo(a.getMonth()); + }) + .collect(Collectors.toList()); + } } diff --git a/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts b/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts index addbbc9e3..daf2113dc 100644 --- a/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts +++ b/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts @@ -19,6 +19,36 @@ export interface ReadingSessionTimelineResponse { totalDurationSeconds: number; } +export interface GenreStatsResponse { + genre: string; + bookCount: number; + totalSessions: number; + totalDurationSeconds: number; + averageSessionsPerBook: number; +} + +export interface CompletionTimelineResponse { + year: number; + month: number; + totalBooks: number; + statusBreakdown: { [key: string]: number }; + finishedBooks: number; + completionRate: number; +} + +export interface FavoriteDaysResponse { + dayOfWeek: number; + dayName: string; + sessionCount: number; + totalDurationSeconds: number; +} + +export interface PeakHoursResponse { + hourOfDay: number; + sessionCount: number; + totalDurationSeconds: number; +} + @Injectable({ providedIn: 'root' }) @@ -32,9 +62,51 @@ export class UserStatsService { ); } - getTimelineForWeek(year: number, week: number): Observable { + getTimelineForWeek(year: number, month: number, week: number): Observable { return this.http.get( - `${this.readingSessionsUrl}/timeline/week/${year}/${week}` + `${this.readingSessionsUrl}/timeline/week/${year}/${month}/${week}` + ); + } + + getGenreStats(): Observable { + return this.http.get( + `${this.readingSessionsUrl}/stats/genres` + ); + } + + getCompletionTimelineForYear(year: number): Observable { + return this.http.get( + `${this.readingSessionsUrl}/stats/completion-timeline/year/${year}` + ); + } + + getFavoriteDays(year?: number, month?: number): Observable { + let params: any = {}; + if (year !== undefined && year !== null) { + params.year = year.toString(); + } + if (month !== undefined && month !== null) { + params.month = month.toString(); + } + + return this.http.get( + `${this.readingSessionsUrl}/stats/favorite-days`, + {params} + ); + } + + getPeakHours(year?: number, month?: number): Observable { + let params: any = {}; + if (year !== undefined && year !== null) { + params.year = year.toString(); + } + if (month !== undefined && month !== null) { + params.month = month.toString(); + } + + return this.http.get( + `${this.readingSessionsUrl}/stats/peak-hours`, + {params} ); } } diff --git a/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.html b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.html new file mode 100644 index 000000000..65a29df7f --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.html @@ -0,0 +1,34 @@ +
+
+
+

+ + Reading Progress +

+

Monthly book completion statistics

+
+
+ + {{ currentYear }} + +
+
+
+ + +
+
+ diff --git a/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.scss b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.scss new file mode 100644 index 000000000..eded2fdc3 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.scss @@ -0,0 +1,132 @@ +.completion-timeline-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + gap: 1rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.year-selector { + display: flex; + align-items: center; + gap: 0.5rem; + flex-shrink: 0; + + .year-nav-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 6px; + padding: 0.6rem 0.6rem; + color: #ffffff; + cursor: pointer; + transition: all 0.3s ease; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + background: rgba(255, 255, 255, 0.2); + border-color: rgba(255, 255, 255, 0.3); + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } + + i { + font-size: 0.875rem; + } + } + + .current-year { + font-size: 1.125rem; + font-weight: 600; + color: #ffffff; + min-width: 4.5rem; + text-align: center; + } +} + +.completion-title-icon { + font-size: 1.5rem; + color: rgba(251, 191, 36, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + .chart-header { + flex-direction: column; + align-items: stretch; + + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + + .year-selector { + justify-content: center; + margin-top: 0.5rem; + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } + + .year-selector { + .current-year { + font-size: 1rem; + min-width: 4rem; + } + + .year-nav-btn { + padding: 0.6rem 0.6rem; + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.ts b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.ts new file mode 100644 index 000000000..92361dc17 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.ts @@ -0,0 +1,235 @@ +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {CompletionTimelineResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; + +type CompletionChartData = ChartData<'bar', number[], string>; + +@Component({ + selector: 'app-completion-timeline-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './completion-timeline-chart.component.html', + styleUrls: ['./completion-timeline-chart.component.scss'] +}) +export class CompletionTimelineChartComponent implements OnInit, OnDestroy { + @Input() initialYear: number = new Date().getFullYear(); + + public currentYear: number = new Date().getFullYear(); + public readonly chartType = 'bar' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + private readonly monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: { + display: true, + position: 'top', + labels: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + boxWidth: 12, + padding: 10 + } + }, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const label = context.dataset.label || ''; + const value = context.parsed.y; + return `${label}: ${value} book${value !== 1 ? 's' : ''}`; + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Month', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11} + }, + grid: {display: false}, + border: {display: false} + }, + y: { + title: { + display: true, + text: 'Number of Books', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + stepSize: 1 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + } + } + }; + } + + ngOnInit(): void { + this.currentYear = this.initialYear; + this.loadCompletionTimeline(this.currentYear); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + public changeYear(delta: number): void { + this.currentYear += delta; + this.loadCompletionTimeline(this.currentYear); + } + + private loadCompletionTimeline(year: number): void { + this.userStatsService.getCompletionTimelineForYear(year) + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading completion timeline:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(timeline: CompletionTimelineResponse[]): void { + const monthlyData = new Map(); + timeline.forEach(item => { + monthlyData.set(item.month, item); + }); + + const labels = this.monthNames; + + const completedBooks = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + if (!monthData) return 0; + const read = monthData.statusBreakdown['READ'] || 0; + const partiallyRead = monthData.statusBreakdown['PARTIALLY_READ'] || 0; + return read + partiallyRead; + }); + + const activeReading = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + if (!monthData) return 0; + const reading = monthData.statusBreakdown['READING'] || 0; + const reReading = monthData.statusBreakdown['RE_READING'] || 0; + return reading + reReading; + }); + + const pausedBooks = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + return monthData?.statusBreakdown['PAUSED'] || 0; + }); + + const discontinuedBooks = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + if (!monthData) return 0; + const abandoned = monthData.statusBreakdown['ABANDONED'] || 0; + const wontRead = monthData.statusBreakdown['WONT_READ'] || 0; + return abandoned + wontRead; + }); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Completed', + data: completedBooks, + backgroundColor: 'rgba(106, 176, 76, 0.8)', + borderColor: 'rgba(106, 176, 76, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + }, + { + label: 'Active Reading', + data: activeReading, + backgroundColor: 'rgba(59, 130, 246, 0.8)', + borderColor: 'rgba(59, 130, 246, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + }, + { + label: 'Paused', + data: pausedBooks, + backgroundColor: 'rgba(255, 193, 7, 0.8)', + borderColor: 'rgba(255, 193, 7, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + }, + { + label: 'Discontinued', + data: discontinuedBooks, + backgroundColor: 'rgba(239, 68, 68, 0.8)', + borderColor: 'rgba(239, 68, 68, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + } + ] + }); + } +} diff --git a/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.html b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.html new file mode 100644 index 000000000..3552a1ac0 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.html @@ -0,0 +1,38 @@ +
+
+
+

+ + Favorite Reading Days +

+

Reading sessions and duration by day of the week

+
+
+ + + + +
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.scss b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.scss new file mode 100644 index 000000000..ef2fc6ec3 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.scss @@ -0,0 +1,95 @@ +.favorite-days-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + gap: 1rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } + + .filter-controls { + display: flex; + gap: 0.75rem; + align-items: center; + flex-shrink: 0; + } +} + +.favorite-days-icon { + font-size: 1.5rem; + color: rgba(139, 92, 246, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + .chart-header { + flex-direction: column; + align-items: stretch; + + .filter-controls { + width: 100%; + flex-direction: column; + gap: 0.5rem; + + ::ng-deep p-select { + width: 100%; + + .p-select { + width: 100% !important; + } + } + } + + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.ts b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.ts new file mode 100644 index 000000000..d105918ba --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.ts @@ -0,0 +1,261 @@ +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {FavoriteDaysResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; +import {Select} from 'primeng/select'; +import {FormsModule} from '@angular/forms'; + +type FavoriteDaysChartData = ChartData<'bar', number[], string>; + +@Component({ + selector: 'app-favorite-days-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective, Select, FormsModule], + templateUrl: './favorite-days-chart.component.html', + styleUrls: ['./favorite-days-chart.component.scss'] +}) +export class FavoriteDaysChartComponent implements OnInit, OnDestroy { + public readonly chartType = 'bar' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + private readonly allDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; + + public selectedYear: number | null = null; + public selectedMonth: number | null = null; + public yearOptions: { label: string; value: number | null }[] = []; + public monthOptions: { label: string; value: number | null }[] = [ + { label: 'All Months', value: null }, + { label: 'January', value: 1 }, + { label: 'February', value: 2 }, + { label: 'March', value: 3 }, + { label: 'April', value: 4 }, + { label: 'May', value: 5 }, + { label: 'June', value: 6 }, + { label: 'July', value: 7 }, + { label: 'August', value: 8 }, + { label: 'September', value: 9 }, + { label: 'October', value: 10 }, + { label: 'November', value: 11 }, + { label: 'December', value: 12 } + ]; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: { + display: true, + position: 'top', + labels: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + boxWidth: 12, + padding: 10 + } + }, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const label = context.dataset.label || ''; + const value = context.parsed.y; + if (label === 'Sessions') { + return `${label}: ${value} session${value !== 1 ? 's' : ''}`; + } else { + const hours = Math.floor(value / 3600); + const minutes = Math.floor((value % 3600) / 60); + return `${label}: ${hours}h ${minutes}m`; + } + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Day of Week', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11} + }, + grid: {display: false}, + border: {display: false} + }, + y: { + type: 'linear', + display: true, + position: 'left', + title: { + display: true, + text: 'Number of Sessions', + color: 'rgba(139, 92, 246, 1)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + stepSize: 1 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + }, + y1: { + type: 'linear', + display: true, + position: 'right', + title: { + display: true, + text: 'Duration (hours)', + color: 'rgba(236, 72, 153, 1)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + callback: function(value) { + return (typeof value === 'number' ? value.toFixed(1) : '0.0') + 'h'; + } + }, + grid: { + drawOnChartArea: false + }, + border: {display: false} + } + } + }; + this.initializeYearOptions(); + } + + ngOnInit(): void { + this.loadFavoriteDays(); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private initializeYearOptions(): void { + const currentYear = new Date().getFullYear(); + this.yearOptions = [{ label: 'All Years', value: null }]; + for (let year = currentYear; year >= currentYear - 10; year--) { + this.yearOptions.push({ label: year.toString(), value: year }); + } + } + + public onFilterChange(): void { + this.loadFavoriteDays(); + } + + private loadFavoriteDays(): void { + const year = this.selectedYear ?? undefined; + const month = this.selectedMonth ?? undefined; + + this.userStatsService.getFavoriteDays(year, month) + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading favorite days:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(favoriteDays: FavoriteDaysResponse[]): void { + const dayMap = new Map(); + favoriteDays.forEach(item => { + dayMap.set(item.dayOfWeek, item); + }); + + const labels = this.allDays; + const sessionCounts = this.allDays.map((_, index) => { + const dayData = dayMap.get(index); + return dayData?.sessionCount || 0; + }); + + const durations = this.allDays.map((_, index) => { + const dayData = dayMap.get(index); + return dayData ? dayData.totalDurationSeconds / 3600 : 0; // Convert to hours + }); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Sessions', + data: sessionCounts, + backgroundColor: 'rgba(139, 92, 246, 0.8)', + borderColor: 'rgba(139, 92, 246, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6, + yAxisID: 'y' + }, + { + label: 'Duration (hours)', + data: durations, + backgroundColor: 'rgba(236, 72, 153, 0.8)', + borderColor: 'rgba(236, 72, 153, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6, + yAxisID: 'y1' + } + ] + }); + } +} diff --git a/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.html b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.html new file mode 100644 index 000000000..ee415eb5a --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.html @@ -0,0 +1,18 @@ +
+
+
+

+ + Reading by Genre +

+

Top genres by total reading time

+
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.scss b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.scss new file mode 100644 index 000000000..6881f034b --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.scss @@ -0,0 +1,57 @@ +.genre-stats-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 1.5rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.genre-title-icon { + font-size: 1.5rem; + color: rgba(34, 197, 94, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + + .chart-header { + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.ts b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.ts new file mode 100644 index 000000000..3f51e23fd --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.ts @@ -0,0 +1,199 @@ +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {GenreStatsResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; + +type GenreChartData = ChartData<'bar', number[], string>; + +@Component({ + selector: 'app-genre-stats-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './genre-stats-chart.component.html', + styleUrls: ['./genre-stats-chart.component.scss'] +}) +export class GenreStatsChartComponent implements OnInit, OnDestroy { + @Input() maxGenres: number = 35; + + public readonly chartType = 'bar' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: {display: false}, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const dataIndex = context.dataIndex; + const dataset = context.dataset; + const label = context.chart.data.labels?.[dataIndex] as string; + const minutes = Math.floor((dataset.data[dataIndex] as number) / 60); + const hours = Math.floor(minutes / 60); + const mins = minutes % 60; + + const timeStr = hours > 0 + ? `${hours}h ${mins}m` + : `${mins}m`; + + return `${label}: ${timeStr}`; + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Genres', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 12 + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + maxRotation: 90, + minRotation: 90, + callback: (value, index) => { + const label = this.chartDataSubject.value.labels?.[index] as string; + const maxLength = 12; + if (label && label.length > maxLength) { + return label.substring(0, maxLength) + '...'; + } + return label; + } + }, + grid: {display: false}, + border: {display: false} + }, + y: { + title: { + display: true, + text: 'Time Read', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 12 + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + callback: (value) => { + const seconds = value as number; + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + + if (days > 0) { + const remainingHours = hours % 24; + if (remainingHours > 0) { + return `${days} ${days === 1 ? 'day' : 'days'} ${remainingHours} ${remainingHours === 1 ? 'hr' : 'hrs'}`; + } + return `${days} ${days === 1 ? 'day' : 'days'}`; + } else if (hours > 0) { + const remainingMinutes = minutes % 60; + if (remainingMinutes > 0) { + return `${hours} ${hours === 1 ? 'hr' : 'hrs'} ${remainingMinutes} min`; + } + return `${hours} ${hours === 1 ? 'hr' : 'hrs'}`; + } else if (minutes > 0) { + return `${minutes} min`; + } + return `${seconds} sec`; + }, + stepSize: undefined, + maxTicksLimit: 8 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + } + } + }; + } + + ngOnInit(): void { + this.loadGenreStats(); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private loadGenreStats(): void { + this.userStatsService.getGenreStats() + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading genre stats:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(genreStats: GenreStatsResponse[]): void { + const sortedStats = [...genreStats] + .sort((a, b) => b.totalDurationSeconds - a.totalDurationSeconds) + .slice(0, this.maxGenres); + + const labels = sortedStats.map(stat => stat.genre); + const durations = sortedStats.map(stat => stat.totalDurationSeconds); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Reading Time', + data: durations, + backgroundColor: 'rgba(34, 197, 94, 0.8)', + borderColor: 'rgba(34, 197, 94, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + } + ] + }); + } +} diff --git a/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.html b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.html new file mode 100644 index 000000000..59df2e711 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.html @@ -0,0 +1,38 @@ +
+
+
+

+ + Peak Reading Hours +

+

Reading activity by hour of the day

+
+
+ + + + +
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.scss b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.scss new file mode 100644 index 000000000..a2672e615 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.scss @@ -0,0 +1,95 @@ +.peak-hours-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + gap: 1rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } + + .filter-controls { + display: flex; + gap: 0.75rem; + align-items: center; + flex-shrink: 0; + } +} + +.peak-hours-icon { + font-size: 1.5rem; + color: rgba(34, 197, 94, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + .chart-header { + flex-direction: column; + align-items: stretch; + + .filter-controls { + width: 100%; + flex-direction: column; + gap: 0.5rem; + + ::ng-deep p-select { + width: 100%; + + .p-select { + width: 100% !important; + } + } + } + + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.ts b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.ts new file mode 100644 index 000000000..1dab8237c --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.ts @@ -0,0 +1,278 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {PeakHoursResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; +import {Select} from 'primeng/select'; +import {FormsModule} from '@angular/forms'; + +type PeakHoursChartData = ChartData<'line', number[], string>; + +@Component({ + selector: 'app-peak-hours-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective, Select, FormsModule], + templateUrl: './peak-hours-chart.component.html', + styleUrls: ['./peak-hours-chart.component.scss'] +}) +export class PeakHoursChartComponent implements OnInit, OnDestroy { + public readonly chartType = 'line' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + public selectedYear: number | null = null; + public selectedMonth: number | null = null; + public yearOptions: { label: string; value: number | null }[] = []; + public monthOptions: { label: string; value: number | null }[] = [ + { label: 'All Months', value: null }, + { label: 'January', value: 1 }, + { label: 'February', value: 2 }, + { label: 'March', value: 3 }, + { label: 'April', value: 4 }, + { label: 'May', value: 5 }, + { label: 'June', value: 6 }, + { label: 'July', value: 7 }, + { label: 'August', value: 8 }, + { label: 'September', value: 9 }, + { label: 'October', value: 10 }, + { label: 'November', value: 11 }, + { label: 'December', value: 12 } + ]; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: { + display: true, + position: 'top', + labels: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + boxWidth: 12, + padding: 10 + } + }, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const label = context.dataset.label || ''; + const value = context.parsed.y; + if (label === 'Sessions') { + return `${label}: ${value} session${value !== 1 ? 's' : ''}`; + } else { + const hours = Math.floor(value / 3600); + const minutes = Math.floor((value % 3600) / 60); + return `${label}: ${hours}h ${minutes}m`; + } + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Hour of Day', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11} + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + }, + y: { + type: 'linear', + display: true, + position: 'left', + title: { + display: true, + text: 'Number of Sessions', + color: 'rgba(34, 197, 94, 0.9)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + stepSize: 1 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + }, + y1: { + type: 'linear', + display: true, + position: 'right', + title: { + display: true, + text: 'Duration (minutes)', + color: 'rgba(251, 191, 36, 0.9)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + callback: function (value) { + return (typeof value === 'number' ? Math.round(value) : '0') + 'm'; + } + }, + grid: { + drawOnChartArea: false + }, + border: {display: false} + } + } + }; + this.initializeYearOptions(); + } + + ngOnInit(): void { + this.loadPeakHours(); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private initializeYearOptions(): void { + const currentYear = new Date().getFullYear(); + this.yearOptions = [{ label: 'All Years', value: null }]; + for (let year = currentYear; year >= currentYear - 10; year--) { + this.yearOptions.push({ label: year.toString(), value: year }); + } + } + + public onFilterChange(): void { + this.loadPeakHours(); + } + + private loadPeakHours(): void { + const year = this.selectedYear ?? undefined; + const month = this.selectedMonth ?? undefined; + + this.userStatsService.getPeakHours(year, month) + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading peak hours:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(peakHours: PeakHoursResponse[]): void { + const hourMap = new Map(); + peakHours.forEach(item => { + hourMap.set(item.hourOfDay, item); + }); + + const allHours = Array.from({length: 24}, (_, i) => i); + const labels = allHours.map(h => this.formatHour(h)); + + const sessionCounts = allHours.map(hour => { + const hourData = hourMap.get(hour); + return hourData?.sessionCount || 0; + }); + + const durations = allHours.map(hour => { + const hourData = hourMap.get(hour); + return hourData ? hourData.totalDurationSeconds / 60 : 0; // Convert to minutes + }); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Sessions', + data: sessionCounts, + borderColor: 'rgba(34, 197, 94, 0.9)', + backgroundColor: 'rgba(34, 197, 94, 0.1)', + borderWidth: 2, + tension: 0.4, + fill: true, + pointRadius: 4, + pointHoverRadius: 6, + pointBackgroundColor: 'rgba(34, 197, 94, 0.9)', + pointBorderColor: '#ffffff', + pointBorderWidth: 2, + yAxisID: 'y' + }, + { + label: 'Duration (minutes)', + data: durations, + borderColor: 'rgba(251, 191, 36, 0.9)', + backgroundColor: 'rgba(251, 191, 36, 0.1)', + borderWidth: 2, + tension: 0.4, + fill: true, + pointRadius: 4, + pointHoverRadius: 6, + pointBackgroundColor: 'rgba(251, 191, 36, 0.9)', + pointBorderColor: '#ffffff', + pointBorderWidth: 2, + yAxisID: 'y1' + } + ] + }); + } + + private formatHour(hour: number): string { + if (hour === 0) return '12 AM'; + if (hour === 12) return '12 PM'; + if (hour < 12) return `${hour} AM`; + return `${hour - 12} PM`; + } +} diff --git a/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.html b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.html new file mode 100644 index 000000000..d7328d158 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.html @@ -0,0 +1,37 @@ +
+
+
+

+ + Reading DNA Profile +

+

Your unique reading personality across 8 key dimensions

+
+
+
+ + +
+ @if (personalityInsights.length > 0) { +
+

Your Reading Personality Traits

+
+ @for (insight of personalityInsights; track insight.trait) { +
+
+ {{ insight.trait }} + {{ insight.score.toFixed(0) }}% +
+
+
+
+

{{ insight.description }}

+
+ } +
+
+ } +
diff --git a/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.scss b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.scss new file mode 100644 index 000000000..26cce315e --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.scss @@ -0,0 +1,137 @@ +.reading-dna-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.reading-dna-icon { + font-size: 1.5rem; + color: rgba(79, 195, 247, 1); +} + +.chart-wrapper { + position: relative; + height: 450px; + width: 100%; + margin-bottom: 2rem; +} + +.personality-insights { + margin-top: 2rem; + + h4 { + color: var(--text-color, #ffffff); + font-size: 1.1rem; + font-weight: 500; + margin: 0 0 1rem 0; + } + + .insights-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 1rem; + } + + .insight-card { + background: rgba(255, 255, 255, 0.05); + border-radius: 8px; + padding: 1rem; + border: 1px solid rgba(255, 255, 255, 0.1); + + .insight-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 0.5rem; + + .insight-trait { + color: var(--text-color, #ffffff); + font-weight: 500; + font-size: 0.95rem; + } + + .insight-score { + font-weight: 600; + font-size: 1rem; + } + } + + .insight-progress { + height: 6px; + background: rgba(255, 255, 255, 0.1); + border-radius: 3px; + overflow: hidden; + margin-bottom: 0.5rem; + + .progress-bar { + height: 100%; + border-radius: 3px; + transition: width 0.3s ease; + } + } + + .insight-description { + color: var(--text-secondary-color); + font-size: 0.85rem; + margin: 0; + line-height: 1.4; + } + } +} + +@media (max-width: 768px) { + .chart-wrapper { + height: 350px; + } + + .personality-insights { + .insights-grid { + grid-template-columns: 1fr; + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } + + .chart-wrapper { + height: 300px; + } +} + diff --git a/booklore-ui/src/app/features/stats/service/reading-dna-chart.service.ts b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.ts similarity index 81% rename from booklore-ui/src/app/features/stats/service/reading-dna-chart.service.ts rename to booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.ts index 8246de8bc..3ec6f76e8 100644 --- a/booklore-ui/src/app/features/stats/service/reading-dna-chart.service.ts +++ b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.ts @@ -1,21 +1,21 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, EMPTY, Observable, Subject, of} from 'rxjs'; -import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators'; +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, filter, first, takeUntil} from 'rxjs/operators'; import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; +import {BookService} from '../../../book/service/book.service'; +import {Book, ReadStatus} from '../../../book/model/book.model'; interface ReadingDNAProfile { - adventurous: number; // Genre diversity and experimental reading - perfectionist: number; // Completion rate and quality focus - intellectual: number; // Non-fiction preference and complex books - emotional: number; // Fiction preference and rating engagement - patient: number; // Long book preference and series completion - social: number; // Popular books and mainstream choices - nostalgic: number; // Older books and classic literature - ambitious: number; // Reading volume and challenging material + adventurous: number; + perfectionist: number; + intellectual: number; + emotional: number; + patient: number; + social: number; + nostalgic: number; + ambitious: number; } interface PersonalityInsight { @@ -27,17 +27,20 @@ interface PersonalityInsight { type ReadingDNAChartData = ChartData<'radar', number[], string>; -@Injectable({ - providedIn: 'root' +@Component({ + selector: 'app-reading-dna-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './reading-dna-chart.component.html', + styleUrls: ['./reading-dna-chart.component.scss'] }) -export class ReadingDNAChartService implements OnDestroy { +export class ReadingDNAChartComponent implements OnInit, OnDestroy { private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); private readonly destroy$ = new Subject(); - public readonly readingDNAChartType = 'radar' as const; + public readonly chartType = 'radar' as const; - public readonly readingDNAChartOptions: ChartConfiguration<'radar'>['options'] = { + public readonly chartOptions: ChartConfiguration<'radar'>['options'] = { responsive: true, maintainAspectRatio: false, scales: { @@ -107,8 +110,7 @@ export class ReadingDNAChartService implements OnDestroy { }, label: (context) => { const score = context.parsed.r; - const insights = this.getPersonalityInsights(); - const insight = insights.find(i => i.trait === context.label); + const insight = this.personalityInsights.find(i => i.trait === context.label); return [ `Score: ${score.toFixed(1)}/100`, @@ -137,7 +139,7 @@ export class ReadingDNAChartService implements OnDestroy { } }; - private readonly readingDNAChartDataSubject = new BehaviorSubject({ + private readonly chartDataSubject = new BehaviorSubject({ labels: [ 'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional', 'Patient', 'Social', 'Nostalgic', 'Ambitious' @@ -145,23 +147,19 @@ export class ReadingDNAChartService implements OnDestroy { datasets: [] }); - public readonly readingDNAChartData$: Observable = this.readingDNAChartDataSubject.asObservable(); - private lastCalculatedInsights: PersonalityInsight[] = []; + public readonly chartData$: Observable = this.chartDataSubject.asObservable(); + public personalityInsights: PersonalityInsight[] = []; - constructor() { + ngOnInit(): void { this.bookService.bookState$ .pipe( filter(state => state.loaded), first(), - switchMap(() => - this.libraryFilterService.selectedLibrary$.pipe( - takeUntil(this.destroy$) - ) - ), catchError((error) => { console.error('Error processing reading DNA data:', error); return EMPTY; - }) + }), + takeUntil(this.destroy$) ) .subscribe(() => { const profile = this.calculateReadingDNAData(); @@ -177,10 +175,11 @@ export class ReadingDNAChartService implements OnDestroy { private updateChartData(profile: ReadingDNAProfile | null): void { try { if (!profile) { - this.readingDNAChartDataSubject.next({ + this.chartDataSubject.next({ labels: [], datasets: [] }); + this.personalityInsights = []; return; } @@ -195,13 +194,12 @@ export class ReadingDNAChartService implements OnDestroy { profile.ambitious ]; - // Create gradient effect colors const gradientColors = [ '#ff6b9d', '#45aaf2', '#96f7d2', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3' ]; - this.readingDNAChartDataSubject.next({ + this.chartDataSubject.next({ labels: [ 'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional', 'Patient', 'Social', 'Nostalgic', 'Ambitious' @@ -221,8 +219,7 @@ export class ReadingDNAChartService implements OnDestroy { }] }); - // Store insights for tooltip - this.lastCalculatedInsights = this.convertToPersonalityInsights(profile); + this.personalityInsights = this.convertToPersonalityInsights(profile); } catch (error) { console.error('Error updating reading DNA chart data:', error); } @@ -230,26 +227,18 @@ export class ReadingDNAChartService implements OnDestroy { private calculateReadingDNAData(): ReadingDNAProfile | null { const currentState = this.bookService.getCurrentBookState(); - const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary(); if (!this.isValidBookState(currentState)) { return null; } - const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId)); - return this.analyzeReadingDNA(filteredBooks); + return this.analyzeReadingDNA(currentState.books!); } private isValidBookState(state: any): boolean { return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; } - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - private analyzeReadingDNA(books: Book[]): ReadingDNAProfile { if (books.length === 0) { return this.getDefaultProfile(); @@ -268,7 +257,6 @@ export class ReadingDNAChartService implements OnDestroy { } private calculateAdventurousScore(books: Book[]): number { - // Genre diversity + experimental choices + different formats const genres = new Set(); const languages = new Set(); const formats = new Set(); @@ -279,9 +267,9 @@ export class ReadingDNAChartService implements OnDestroy { formats.add(book.bookType); }); - const genreScore = Math.min(60, genres.size * 4); // Max 60 for 15+ genres - const languageScore = Math.min(20, languages.size * 10); // Max 20 for 2+ languages - const formatScore = Math.min(20, formats.size * 7); // Max 20 for 3+ formats + const genreScore = Math.min(60, genres.size * 4); + const languageScore = Math.min(20, languages.size * 10); + const formatScore = Math.min(20, formats.size * 7); return genreScore + languageScore + formatScore; } @@ -290,7 +278,6 @@ export class ReadingDNAChartService implements OnDestroy { const completedBooks = books.filter(b => b.readStatus === ReadStatus.READ); const completionRate = completedBooks.length / books.length; - // High-quality book preference const qualityBooks = books.filter(book => { const metadata = book.metadata; if (!metadata) return false; @@ -300,8 +287,8 @@ export class ReadingDNAChartService implements OnDestroy { }); const qualityRate = qualityBooks.length / books.length; - const completionScore = completionRate * 60; // Max 60 - const qualityScore = qualityRate * 40; // Max 40 + const completionScore = completionRate * 60; + const qualityScore = qualityRate * 40; return Math.min(100, completionScore + qualityScore); } @@ -329,7 +316,6 @@ export class ReadingDNAChartService implements OnDestroy { ); }); - // Long books indicate patience for complex material const longBooks = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 400 ); @@ -365,7 +351,6 @@ export class ReadingDNAChartService implements OnDestroy { ); }); - // Personal rating engagement shows emotional connection const personallyRatedBooks = books.filter(book => book.personalRating); const emotionalRate = emotionalBooks.length / books.length; @@ -375,7 +360,6 @@ export class ReadingDNAChartService implements OnDestroy { } private calculatePatienceScore(books: Book[]): number { - // Long books + series completion + slow reading pace const longBooks = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 500 ); @@ -384,7 +368,6 @@ export class ReadingDNAChartService implements OnDestroy { book.metadata?.seriesName && book.metadata?.seriesNumber ); - // Books with high progress indicate patience to work through them const progressBooks = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -404,7 +387,6 @@ export class ReadingDNAChartService implements OnDestroy { } private calculateSocialScore(books: Book[]): number { - // Popular books (high ratings, many reviews) + mainstream genres const popularBooks = books.filter(book => { const metadata = book.metadata; if (!metadata) return false; @@ -446,7 +428,7 @@ export class ReadingDNAChartService implements OnDestroy { private calculateNostalgicScore(books: Book[]): number { const currentYear = new Date().getFullYear(); - const classicThreshold = currentYear - 30; // Books older than 30 years + const classicThreshold = currentYear - 30; const oldBooks = books.filter(book => { if (!book.metadata?.publishedDate) return false; @@ -480,9 +462,8 @@ export class ReadingDNAChartService implements OnDestroy { } private calculateAmbitiousScore(books: Book[]): number { - // Volume + challenging material + completion of difficult books const totalBooks = books.length; - const volumeScore = Math.min(40, totalBooks * 2); // Max 40 for 20+ books + const volumeScore = Math.min(40, totalBooks * 2); const challengingBooks = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 600 @@ -496,8 +477,8 @@ export class ReadingDNAChartService implements OnDestroy { const completionRate = challengingBooks.length > 0 ? completedChallenging.length / challengingBooks.length : 0; - const challengingScore = challengingRate * 35; // Max 35 - const completionBonus = completionRate * 25; // Max 25 + const challengingScore = challengingRate * 35; + const completionBonus = completionRate * 25; return Math.min(100, volumeScore + challengingScore + completionBonus); } @@ -567,8 +548,4 @@ export class ReadingDNAChartService implements OnDestroy { } ]; } - - public getPersonalityInsights(): PersonalityInsight[] { - return this.lastCalculatedInsights; - } } diff --git a/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.html b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.html new file mode 100644 index 000000000..9b60e17e1 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.html @@ -0,0 +1,37 @@ +
+
+
+

+ + Reading Habits Analysis +

+

Your behavioral reading patterns across 8 key dimensions

+
+
+
+ + +
+ @if (habitInsights.length > 0) { +
+

Your Reading Habit Patterns

+
+ @for (insight of habitInsights; track insight.habit) { +
+
+ {{ insight.habit }} + {{ insight.score.toFixed(0) }}% +
+
+
+
+

{{ insight.description }}

+
+ } +
+
+ } +
diff --git a/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.scss b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.scss new file mode 100644 index 000000000..8f197c4bd --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.scss @@ -0,0 +1,137 @@ +.reading-habits-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.reading-habits-icon { + font-size: 1.5rem; + color: rgba(156, 39, 176, 1); +} + +.chart-wrapper { + position: relative; + height: 450px; + width: 100%; + margin-bottom: 2rem; +} + +.habit-insights { + margin-top: 2rem; + + h4 { + color: var(--text-color, #ffffff); + font-size: 1.1rem; + font-weight: 500; + margin: 0 0 1rem 0; + } + + .insights-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 1rem; + } + + .insight-card { + background: rgba(255, 255, 255, 0.05); + border-radius: 8px; + padding: 1rem; + border: 1px solid rgba(255, 255, 255, 0.1); + + .insight-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 0.5rem; + + .insight-trait { + color: var(--text-color, #ffffff); + font-weight: 500; + font-size: 0.95rem; + } + + .insight-score { + font-weight: 600; + font-size: 1rem; + } + } + + .insight-progress { + height: 6px; + background: rgba(255, 255, 255, 0.1); + border-radius: 3px; + overflow: hidden; + margin-bottom: 0.5rem; + + .progress-bar { + height: 100%; + border-radius: 3px; + transition: width 0.3s ease; + } + } + + .insight-description { + color: var(--text-secondary-color); + font-size: 0.85rem; + margin: 0; + line-height: 1.4; + } + } +} + +@media (max-width: 768px) { + .chart-wrapper { + height: 350px; + } + + .habit-insights { + .insights-grid { + grid-template-columns: 1fr; + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } + + .chart-wrapper { + height: 300px; + } +} + diff --git a/booklore-ui/src/app/features/stats/service/reading-habits-chart.service.ts b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.ts similarity index 76% rename from booklore-ui/src/app/features/stats/service/reading-habits-chart.service.ts rename to booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.ts index 9b3a60e1a..0f08422cb 100644 --- a/booklore-ui/src/app/features/stats/service/reading-habits-chart.service.ts +++ b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.ts @@ -1,21 +1,21 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, EMPTY, Observable, Subject, of} from 'rxjs'; -import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators'; +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, filter, first, takeUntil} from 'rxjs/operators'; import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; +import {BookService} from '../../../book/service/book.service'; +import {Book, ReadStatus} from '../../../book/model/book.model'; interface ReadingHabitsProfile { - consistency: number; // Regular reading patterns vs sporadic - multitasking: number; // Multiple books at once - completionism: number; // Finishing vs abandoning books - exploration: number; // Trying new vs sticking to familiar - organization: number; // Series order, metadata attention - intensity: number; // Reading session length preferences - methodology: number; // Systematic vs random book selection - momentum: number; // Reading streaks and continuity + consistency: number; + multitasking: number; + completionism: number; + exploration: number; + organization: number; + intensity: number; + methodology: number; + momentum: number; } interface HabitInsight { @@ -27,17 +27,20 @@ interface HabitInsight { type ReadingHabitsChartData = ChartData<'radar', number[], string>; -@Injectable({ - providedIn: 'root' +@Component({ + selector: 'app-reading-habits-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './reading-habits-chart.component.html', + styleUrls: ['./reading-habits-chart.component.scss'] }) -export class ReadingHabitsChartService implements OnDestroy { +export class ReadingHabitsChartComponent implements OnInit, OnDestroy { private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); private readonly destroy$ = new Subject(); - public readonly readingHabitsChartType = 'radar' as const; + public readonly chartType = 'radar' as const; - public readonly readingHabitsChartOptions: ChartConfiguration<'radar'>['options'] = { + public readonly chartOptions: ChartConfiguration<'radar'>['options'] = { responsive: true, maintainAspectRatio: false, scales: { @@ -107,8 +110,7 @@ export class ReadingHabitsChartService implements OnDestroy { }, label: (context) => { const score = context.parsed.r; - const insights = this.getHabitInsights(); - const insight = insights.find(i => i.habit === context.label); + const insight = this.habitInsights.find(i => i.habit === context.label); return [ `Score: ${score.toFixed(1)}/100`, @@ -137,7 +139,7 @@ export class ReadingHabitsChartService implements OnDestroy { } }; - private readonly readingHabitsChartDataSubject = new BehaviorSubject({ + private readonly chartDataSubject = new BehaviorSubject({ labels: [ 'Consistency', 'Multitasking', 'Completionism', 'Exploration', 'Organization', 'Intensity', 'Methodology', 'Momentum' @@ -145,23 +147,19 @@ export class ReadingHabitsChartService implements OnDestroy { datasets: [] }); - public readonly readingHabitsChartData$: Observable = this.readingHabitsChartDataSubject.asObservable(); - private lastCalculatedInsights: HabitInsight[] = []; + public readonly chartData$: Observable = this.chartDataSubject.asObservable(); + public habitInsights: HabitInsight[] = []; - constructor() { + ngOnInit(): void { this.bookService.bookState$ .pipe( filter(state => state.loaded), first(), - switchMap(() => - this.libraryFilterService.selectedLibrary$.pipe( - takeUntil(this.destroy$) - ) - ), catchError((error) => { console.error('Error processing reading habits data:', error); return EMPTY; - }) + }), + takeUntil(this.destroy$) ) .subscribe(() => { const profile = this.calculateReadingHabitsData(); @@ -177,10 +175,11 @@ export class ReadingHabitsChartService implements OnDestroy { private updateChartData(profile: ReadingHabitsProfile | null): void { try { if (!profile) { - this.readingHabitsChartDataSubject.next({ + this.chartDataSubject.next({ labels: [], datasets: [] }); + this.habitInsights = []; return; } @@ -195,13 +194,12 @@ export class ReadingHabitsChartService implements OnDestroy { profile.momentum ]; - // Purple gradient colors for habits theme const habitColors = [ '#9c27b0', '#e91e63', '#ff5722', '#ff9800', '#ffc107', '#4caf50', '#2196f3', '#673ab7' ]; - this.readingHabitsChartDataSubject.next({ + this.chartDataSubject.next({ labels: [ 'Consistency', 'Multitasking', 'Completionism', 'Exploration', 'Organization', 'Intensity', 'Methodology', 'Momentum' @@ -221,8 +219,7 @@ export class ReadingHabitsChartService implements OnDestroy { }] }); - // Store insights for tooltip - this.lastCalculatedInsights = this.convertToHabitInsights(profile); + this.habitInsights = this.convertToHabitInsights(profile); } catch (error) { console.error('Error updating reading habits chart data:', error); } @@ -230,26 +227,18 @@ export class ReadingHabitsChartService implements OnDestroy { private calculateReadingHabitsData(): ReadingHabitsProfile | null { const currentState = this.bookService.getCurrentBookState(); - const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary(); if (!this.isValidBookState(currentState)) { return null; } - const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId)); - return this.analyzeReadingHabits(filteredBooks); + return this.analyzeReadingHabits(currentState.books!); } private isValidBookState(state: any): boolean { return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; } - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - private analyzeReadingHabits(books: Book[]): ReadingHabitsProfile { if (books.length === 0) { return this.getDefaultProfile(); @@ -268,28 +257,24 @@ export class ReadingHabitsChartService implements OnDestroy { } private calculateConsistencyScore(books: Book[]): number { - // Look for consistent reading patterns through completion dates and progress + // ...existing code from service... const booksWithDates = books.filter(book => book.dateFinished || book.addedOn); if (booksWithDates.length === 0) return 30; - // Books completed in sequence suggest consistent reading habits const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ && book.dateFinished); if (completedBooks.length < 2) return 25; - // Calculate time intervals between completed books - const sortedByCompletion = completedBooks - .sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime()); - let consistencyScore = 50; - // Books in progress suggest active reading habit const inProgress = books.filter(book => book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING ); const progressRate = inProgress.length / books.length; consistencyScore += progressRate * 30; - // Regular completion pattern + const sortedByCompletion = completedBooks + .sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime()); + if (sortedByCompletion.length >= 3) { consistencyScore += 20; } @@ -298,12 +283,11 @@ export class ReadingHabitsChartService implements OnDestroy { } private calculateMultitaskingScore(books: Book[]): number { - // Multiple books in reading status indicates multitasking + // ...existing code from service... const currentlyReading = books.filter(book => book.readStatus === ReadStatus.READING); const reReading = books.filter(book => book.readStatus === ReadStatus.RE_READING); const activeBooks = currentlyReading.length + reReading.length; - // Books with partial progress suggest juggling multiple reads const booksWithProgress = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -315,14 +299,14 @@ export class ReadingHabitsChartService implements OnDestroy { return progress > 0 && progress < 100; }); - const multitaskingScore = Math.min(60, activeBooks * 15); // Max 60 for 4+ concurrent books - const progressScore = Math.min(40, (booksWithProgress.length / books.length) * 80); // Max 40 + const multitaskingScore = Math.min(60, activeBooks * 15); + const progressScore = Math.min(40, (booksWithProgress.length / books.length) * 80); return Math.min(100, multitaskingScore + progressScore); } private calculateCompletionismScore(books: Book[]): number { - // High completion rate vs abandonment + // ...existing code from service... const completed = books.filter(book => book.readStatus === ReadStatus.READ); const abandoned = books.filter(book => book.readStatus === ReadStatus.ABANDONED); const unfinished = books.filter(book => book.readStatus === ReadStatus.UNREAD || book.readStatus === ReadStatus.UNSET); @@ -330,14 +314,14 @@ export class ReadingHabitsChartService implements OnDestroy { const completionRate = completed.length / (books.length - unfinished.length); const abandonmentRate = abandoned.length / books.length; - const completionScore = completionRate * 70; // Max 70 - const abandonmentPenalty = abandonmentRate * 30; // Max 30 penalty + const completionScore = completionRate * 70; + const abandonmentPenalty = abandonmentRate * 30; return Math.max(0, Math.min(100, completionScore - abandonmentPenalty + 30)); } private calculateExplorationScore(books: Book[]): number { - // Trying new authors vs sticking to favorites + // ...existing code from service... const authors = new Set(); const authorCounts = new Map(); @@ -349,38 +333,32 @@ export class ReadingHabitsChartService implements OnDestroy { }); }); - // Calculate author diversity - const authorDiversityScore = Math.min(50, authors.size * 2); // Max 50 - - // Penalty for too many books by same author (indicates less exploration) + const authorDiversityScore = Math.min(50, authors.size * 2); const maxBooksPerAuthor = Math.max(...Array.from(authorCounts.values())); - const concentrationPenalty = Math.max(0, (maxBooksPerAuthor - 3) * 5); // Penalty after 3 books per author + const concentrationPenalty = Math.max(0, (maxBooksPerAuthor - 3) * 5); - // Different publication years indicate temporal exploration const years = new Set(); books.forEach(book => { if (book.metadata?.publishedDate) { years.add(new Date(book.metadata.publishedDate).getFullYear()); } }); - const temporalScore = Math.min(30, years.size * 2); // Max 30 + const temporalScore = Math.min(30, years.size * 2); - // Different languages indicate linguistic exploration const languages = new Set(); books.forEach(book => { if (book.metadata?.language) languages.add(book.metadata.language); }); - const languageScore = Math.min(20, (languages.size - 1) * 10); // Max 20 + const languageScore = Math.min(20, (languages.size - 1) * 10); return Math.max(10, Math.min(100, authorDiversityScore + temporalScore + languageScore - concentrationPenalty)); } private calculateOrganizationScore(books: Book[]): number { - // Series reading in order, metadata completion + // ...existing code from service... const seriesBooks = books.filter(book => book.metadata?.seriesName && book.metadata?.seriesNumber); - const seriesScore = (seriesBooks.length / books.length) * 40; // Max 40 + const seriesScore = (seriesBooks.length / books.length) * 40; - // Books with comprehensive metadata suggest organized approach const wellOrganizedBooks = books.filter(book => { const metadata = book.metadata; if (!metadata) return false; @@ -392,24 +370,22 @@ export class ReadingHabitsChartService implements OnDestroy { return hasBasicInfo && (hasDetailedInfo || hasCategories); }); - const metadataScore = (wellOrganizedBooks.length / books.length) * 35; // Max 35 + const metadataScore = (wellOrganizedBooks.length / books.length) * 35; - // Personal ratings suggest systematic tracking const ratedBooks = books.filter(book => book.personalRating); - const ratingScore = (ratedBooks.length / books.length) * 25; // Max 25 + const ratingScore = (ratedBooks.length / books.length) * 25; return Math.min(100, seriesScore + metadataScore + ratingScore); } private calculateIntensityScore(books: Book[]): number { - // Preference for longer books suggests intensive reading sessions + // ...existing code from service... const booksWithPages = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 0); if (booksWithPages.length === 0) return 40; const averagePages = booksWithPages.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0) / booksWithPages.length; - const intensityFromLength = Math.min(50, averagePages / 8); // Max 50 for 400+ page average + const intensityFromLength = Math.min(50, averagePages / 8); - // High progress percentages on multiple books suggest intensive reading const highProgressBooks = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -420,19 +396,18 @@ export class ReadingHabitsChartService implements OnDestroy { return progress > 75; }); - const progressScore = (highProgressBooks.length / books.length) * 30; // Max 30 + const progressScore = (highProgressBooks.length / books.length) * 30; - // Series completion suggests sustained intensive reading const completedSeriesBooks = books.filter(book => book.metadata?.seriesName && book.readStatus === ReadStatus.READ ); - const seriesIntensityScore = (completedSeriesBooks.length / books.length) * 20; // Max 20 + const seriesIntensityScore = (completedSeriesBooks.length / books.length) * 20; return Math.min(100, intensityFromLength + progressScore + seriesIntensityScore); } private calculateMethodologyScore(books: Book[]): number { - // Series reading in order vs random selection + // ...existing code from service... const seriesBooks = books.filter(book => book.metadata?.seriesName); const seriesGroups = new Map(); @@ -456,7 +431,6 @@ export class ReadingHabitsChartService implements OnDestroy { } }); - // Author exploration in systematic way (multiple books per favored author) const authorBooks = new Map(); books.forEach(book => { book.metadata?.authors?.forEach(author => { @@ -469,9 +443,8 @@ export class ReadingHabitsChartService implements OnDestroy { }); const systematicAuthors = Array.from(authorBooks.values()).filter(books => books.length >= 2).length; - const authorMethodologyScore = Math.min(30, systematicAuthors * 5); // Max 30 + const authorMethodologyScore = Math.min(30, systematicAuthors * 5); - // Genre consistency suggests methodical selection const categoryBooks = new Map(); books.forEach(book => { book.metadata?.categories?.forEach(category => { @@ -481,33 +454,30 @@ export class ReadingHabitsChartService implements OnDestroy { }); const majorCategories = Array.from(categoryBooks.values()).filter(count => count >= 3).length; - const categoryMethodologyScore = Math.min(25, majorCategories * 8); // Max 25 + const categoryMethodologyScore = Math.min(25, majorCategories * 8); - const baseMethodologyScore = books.length >= 10 ? 15 : Math.max(5, books.length); // Base score + const baseMethodologyScore = books.length >= 10 ? 15 : Math.max(5, books.length); return Math.min(100, systematicSeriesScore + authorMethodologyScore + categoryMethodologyScore + baseMethodologyScore); } private calculateMomentumScore(books: Book[]): number { - // Reading streaks and continuity + // ...existing code from service... const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ && book.dateFinished); if (completedBooks.length === 0) { - // Score based on current activity const activeBooks = books.filter(book => book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING ); return Math.min(40, activeBooks.length * 10); } - // Sort by completion date const sortedBooks = completedBooks.sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime() ); - let momentumScore = 20; // Base score + let momentumScore = 20; - // Recent completion activity (last 6 months) const sixMonthsAgo = new Date(); sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); @@ -515,16 +485,14 @@ export class ReadingHabitsChartService implements OnDestroy { new Date(book.dateFinished!) > sixMonthsAgo ); - momentumScore += Math.min(40, recentCompletions.length * 5); // Max 40 + momentumScore += Math.min(40, recentCompletions.length * 5); - // Currently reading books add to momentum const currentlyReading = books.filter(book => book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING ); - momentumScore += Math.min(25, currentlyReading.length * 8); // Max 25 + momentumScore += Math.min(25, currentlyReading.length * 8); - // High progress books indicate active momentum const highProgressBooks = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -535,7 +503,7 @@ export class ReadingHabitsChartService implements OnDestroy { return progress > 50 && progress < 100; }); - momentumScore += Math.min(15, highProgressBooks.length * 3); // Max 15 + momentumScore += Math.min(15, highProgressBooks.length * 3); return Math.min(100, momentumScore); } @@ -605,8 +573,5 @@ export class ReadingHabitsChartService implements OnDestroy { } ]; } - - public getHabitInsights(): HabitInsight[] { - return this.lastCalculatedInsights; - } } + diff --git a/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html b/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html index c5e44c0e9..5190aa567 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html +++ b/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html @@ -3,7 +3,7 @@

- {{ getTitle() }} + Reading Session Activity

Daily overview of your reading sessions across the year

@@ -22,6 +22,7 @@ +
; }) export class ReadingSessionHeatmapComponent implements OnInit, OnDestroy { @Input() initialYear: number = new Date().getFullYear(); - @Input() userName: string = ''; public currentYear: number = new Date().getFullYear(); public readonly chartType = 'matrix' as const; @@ -212,8 +211,8 @@ export class ReadingSessionHeatmapComponent implements OnInit, OnDestroy { if (!point?.v) return 'rgba(255, 255, 255, 0.05)'; const intensity = point.v / this.maxSessionCount; - const alpha = Math.max(0.2, Math.min(1.0, intensity * 0.8 + 0.2)); - return `rgba(106, 176, 76, ${alpha})`; + const alpha = Math.max(0.3, Math.min(0.9, intensity * 0.6 + 0.3)); + return `rgba(59, 130, 246, ${alpha})`; }, borderColor: 'rgba(255, 255, 255, 0.1)', borderWidth: 1 @@ -226,10 +225,4 @@ export class ReadingSessionHeatmapComponent implements OnInit, OnDestroy { date.setDate(date.getDate() + (week * 7) - date.getDay()); return date; } - - public getTitle(): string { - return this.userName - ? `${this.userName}'s Reading Session Activity` - : 'Reading Session Activity'; - } } diff --git a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html index 715ff0910..fdecb466c 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html +++ b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html @@ -3,18 +3,18 @@

- {{ getTitle() }} + Reading Session Timeline

Weekly overview of your reading sessions and patterns

-
+
-
+
Week {{ currentWeek }} {{ getWeekDateRange() }}
@@ -25,6 +25,26 @@
+
+ + + + +
diff --git a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss index 86a42bf37..7ff6f9ddd 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss +++ b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss @@ -3,15 +3,13 @@ } .timeline-header { - display: flex; - justify-content: space-between; + display: grid; + grid-template-columns: 1fr auto 1fr; align-items: flex-start; - margin-bottom: 0.5rem; + margin-bottom: 1rem; gap: 1rem; .header-title { - flex: 1; - h3 { color: var(--text-color, #ffffff); font-size: 1.25rem; @@ -27,17 +25,16 @@ } } - .week-selector { + .week-info { display: flex; align-items: center; - gap: 1rem; - flex-shrink: 0; + justify-self: center; .week-nav-btn { background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 6px; - padding: 0.5rem 0.75rem; + padding: 0.6rem 0.6rem; color: #ffffff; cursor: pointer; transition: all 0.3s ease; @@ -60,26 +57,96 @@ } } - .week-info { + .week-display { display: flex; flex-direction: column; align-items: center; - min-width: 100px; + min-width: 120px; .week-label { - font-size: 1.125rem; + font-size: 1rem; font-weight: 600; color: #ffffff; white-space: nowrap; + line-height: 1.2; } .week-dates { - font-size: 0.8rem; + font-size: 0.75rem; color: var(--text-secondary-color); white-space: nowrap; + margin-top: 0.1rem; + line-height: 1.2; } } } + + .filter-controls { + display: flex; + gap: 0.75rem; + align-items: center; + justify-self: end; + } +} + +.week-info-bar { + display: flex; + align-items: center; + justify-content: center; + gap: 1rem; + margin-bottom: 1rem; + padding: 0.75rem; + background: rgba(255, 255, 255, 0.05); + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.1); + + .week-nav-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 6px; + padding: 0.6rem 6rem; + color: #ffffff; + cursor: pointer; + transition: all 0.3s ease; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + background: rgba(255, 255, 255, 0.2); + border-color: rgba(255, 255, 255, 0.3); + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } + + i { + font-size: 0.875rem; + } + } + + .week-display { + display: flex; + flex-direction: column; + align-items: center; + min-width: 150px; + + .week-label { + font-size: 1.125rem; + font-weight: 600; + color: #ffffff; + white-space: nowrap; + } + + .week-dates { + font-size: 0.85rem; + color: var(--text-secondary-color); + white-space: nowrap; + margin-top: 0.25rem; + } + } } .timeline-content { @@ -153,7 +220,7 @@ background: rgba(255, 255, 255, 0.02); border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.1); - min-height: 40px; + min-height: 35px; } } @@ -188,29 +255,32 @@ box-sizing: border-box; &.book-type-epub, &.book-type-default { - background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%); - box-shadow: 0 2px 8px rgba(74, 144, 226, 0.3); + background: rgba(59, 130, 246, 0.8); + border: 1px solid rgba(59, 130, 246, 1); + box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3); &:hover { - box-shadow: 0 4px 16px rgba(74, 144, 226, 0.5); + box-shadow: 0 4px 8px rgba(59, 130, 246, 0.5); } } &.book-type-pdf { - background: linear-gradient(135deg, #e24a4a 0%, #bd3535 100%); - box-shadow: 0 2px 8px rgba(226, 74, 74, 0.3); + background: rgba(239, 68, 68, 0.8); + border: 1px solid rgba(239, 68, 68, 1); + box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3); &:hover { - box-shadow: 0 4px 16px rgba(226, 74, 74, 0.5); + box-shadow: 0 4px 8px rgba(239, 68, 68, 0.5); } } &.book-type-cbx { - background: linear-gradient(135deg, #e2b74a 0%, #bd9635 100%); - box-shadow: 0 2px 8px rgba(226, 183, 74, 0.3); + background: rgba(255, 193, 7, 0.8); + border: 1px solid rgba(255, 193, 7, 1); + box-shadow: 0 2px 4px rgba(255, 193, 7, 0.3); &:hover { - box-shadow: 0 4px 16px rgba(226, 183, 74, 0.5); + box-shadow: 0 4px 8px rgba(255, 193, 7, 0.5); } } @@ -311,7 +381,7 @@ i { font-size: 1.1rem; - color: #4a90e2; + color: rgba(239, 68, 68, 1); } .tooltip-title { @@ -384,22 +454,77 @@ .timeline-title-icon { font-size: 1.5rem; - color: var(--primary-color); + color: rgba(239, 68, 68, 1); vertical-align: middle; margin-right: 0.25em; } +@media (max-width: 1024px) { + .timeline-header { + grid-template-columns: 1fr; + gap: 0.75rem; + + .header-title { + grid-column: 1; + } + + .week-info { + grid-column: 1; + justify-self: stretch; + justify-content: center; + } + + .filter-controls { + grid-column: 1; + justify-self: stretch; + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.5rem; + + ::ng-deep p-select { + width: 100%; + + .p-select { + width: 100% !important; + } + } + } + } +} + @media (max-width: 768px) { .timeline-header { - flex-direction: column; - align-items: stretch; + .header-title { + h3 { + font-size: 1.1rem; + } - .week-selector { - justify-content: center; - margin-top: 0.5rem; + .timeline-subtitle { + font-size: 0.85rem; + } + } - .week-info { - min-width: 120px; + .week-info { + padding: 0.6rem 0.6rem; + + .week-display { + min-width: 100px; + + .week-label { + font-size: 0.9rem; + } + + .week-dates { + font-size: 0.7rem; + } + } + + .week-nav-btn { + padding: 0.35rem 0.5rem; + + i { + font-size: 0.8rem; + } } } } @@ -467,24 +592,30 @@ .timeline-header { .header-title { h3 { - font-size: 1.1rem; + font-size: 1rem; } .timeline-subtitle { - font-size: 0.85rem; + font-size: 0.8rem; } } - } - .week-selector { + .filter-controls { + grid-template-columns: 1fr; + } + .week-info { - .week-label { - font-size: 1rem; - } - } + .week-display { + min-width: 90px; - .week-nav-btn { - padding: 0.4rem 0.6rem; + .week-label { + font-size: 0.85rem; + } + + .week-dates { + font-size: 0.65rem; + } + } } } } diff --git a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts index 9a0f72a99..863247940 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts +++ b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts @@ -3,6 +3,10 @@ import {CommonModule} from '@angular/common'; import {ReadingSessionTimelineResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; import {UrlHelperService} from '../../../../shared/service/url-helper.service'; import {BookType} from '../../../book/model/book.model'; +import {catchError} from 'rxjs/operators'; +import {of} from 'rxjs'; +import {Select} from 'primeng/select'; +import {FormsModule} from '@angular/forms'; interface ReadingSession { startTime: Date; @@ -37,14 +41,13 @@ interface DayTimeline { @Component({ selector: 'app-reading-session-timeline', standalone: true, - imports: [CommonModule], + imports: [CommonModule, Select, FormsModule], templateUrl: './reading-session-timeline.component.html', styleUrls: ['./reading-session-timeline.component.scss'] }) export class ReadingSessionTimelineComponent implements OnInit { @Input() initialYear: number = new Date().getFullYear(); @Input() weekNumber: number = this.getCurrentWeekNumber(); - @Input() userName: string = ''; private userStatsService = inject(UserStatsService); private urlHelperService = inject(UrlHelperService); @@ -54,14 +57,52 @@ export class ReadingSessionTimelineComponent implements OnInit { public timelineData: DayTimeline[] = []; public currentYear: number = new Date().getFullYear(); public currentWeek: number = this.getCurrentWeekNumber(); + public currentMonth: number = new Date().getMonth() + 1; + + public yearOptions: { label: string; value: number }[] = []; + public weekOptions: { label: string; value: number }[] = []; ngOnInit(): void { this.currentYear = this.initialYear; this.currentWeek = this.weekNumber; + this.updateCurrentMonth(); + this.initializeYearOptions(); + this.updateWeekOptions(); this.initializeHourLabels(); this.loadReadingSessions(); } + private initializeYearOptions(): void { + const currentYear = new Date().getFullYear(); + this.yearOptions = []; + for (let year = currentYear; year >= currentYear - 10; year--) { + this.yearOptions.push({ label: year.toString(), value: year }); + } + } + + private updateWeekOptions(): void { + const weeksInYear = this.getWeeksInYear(this.currentYear); + this.weekOptions = []; + for (let week = 1; week <= weeksInYear; week++) { + this.weekOptions.push({ label: `Week ${week}`, value: week }); + } + } + + public onYearChange(): void { + this.updateWeekOptions(); + const maxWeeks = this.getWeeksInYear(this.currentYear); + if (this.currentWeek > maxWeeks) { + this.currentWeek = maxWeeks; + } + this.updateCurrentMonth(); + this.loadReadingSessions(); + } + + public onWeekChange(): void { + this.updateCurrentMonth(); + this.loadReadingSessions(); + } + private initializeHourLabels(): void { for (let i = 0; i < 24; i++) { const hour = i === 0 ? 12 : i > 12 ? i - 12 : i; @@ -71,15 +112,17 @@ export class ReadingSessionTimelineComponent implements OnInit { } private loadReadingSessions(): void { - this.userStatsService.getTimelineForWeek(this.currentYear, this.currentWeek) + this.userStatsService.getTimelineForWeek(this.currentYear, this.currentMonth, this.currentWeek) + .pipe( + catchError((error) => { + console.error('Error loading reading sessions:', error); + return of([]); + }) + ) .subscribe({ next: (response) => { const sessions = this.convertResponseToSessions(response); this.processSessionData(sessions); - }, - error: (error) => { - console.error('Error loading reading sessions:', error); - this.processSessionData([]); } }); } @@ -119,14 +162,28 @@ export class ReadingSessionTimelineComponent implements OnInit { if (this.currentWeek > weeksInYear) { this.currentWeek = 1; this.currentYear++; + this.updateWeekOptions(); } else if (this.currentWeek < 1) { this.currentYear--; this.currentWeek = this.getWeeksInYear(this.currentYear); + this.updateWeekOptions(); } + this.updateCurrentMonth(); this.loadReadingSessions(); } + private updateCurrentMonth(): void { + const startOfYear = new Date(this.currentYear, 0, 1); + const daysToAdd = (this.currentWeek - 1) * 7; + const weekStart = new Date(startOfYear.getTime() + daysToAdd * 24 * 60 * 60 * 1000); + + const dayOfWeek = weekStart.getDay(); + weekStart.setDate(weekStart.getDate() - dayOfWeek); + + this.currentMonth = weekStart.getMonth() + 1; + } + private getWeeksInYear(year: number): number { const lastDay = new Date(year, 11, 31); const startOfYear = new Date(year, 0, 1); @@ -325,10 +382,4 @@ export class ReadingSessionTimelineComponent implements OnInit { public getCoverUrl(bookId: number): string { return this.urlHelperService.getThumbnailUrl1(bookId); } - - public getTitle(): string { - return this.userName - ? `${this.userName}'s Reading Session Timeline` - : 'Reading Session Timeline'; - } } diff --git a/booklore-ui/src/app/features/stats/component/stats-component.html b/booklore-ui/src/app/features/stats/component/stats-component.html index 0f4197391..1c87f1d22 100644 --- a/booklore-ui/src/app/features/stats/component/stats-component.html +++ b/booklore-ui/src/app/features/stats/component/stats-component.html @@ -328,70 +328,6 @@
} - @case ('readingDNA') { -

Your Reading DNA Profile

-
- Discover your unique reading personality based on behavioral patterns and preferences -
-
- - -
-
- @if ((readingDNAChartService.readingDNAChartData$ | async)?.datasets?.[0]?.data?.length) { -
- @for (insight of readingDNAChartService.getPersonalityInsights(); track trackByTrait($index, insight)) { -
-
-
- {{ insight.trait }} - {{ insight.score.toFixed(0) }}% -
-
-
-
-

{{ insight.description }}

-
- } -
- } -
- } - @case ('readingHabits') { -

Reading Habits Analysis

-
- Analyze your behavioral reading patterns, routines, and systematic approaches -
-
- - -
-
- @if ((readingHabitsChartService.readingHabitsChartData$ | async)?.datasets?.[0]?.data?.length) { -
- @for (habit of readingHabitsChartService.getHabitInsights(); track trackByHabit($index, habit)) { -
-
-
- {{ habit.habit }} - {{ habit.score.toFixed(0) }}% -
-
-
-
-

{{ habit.description }}

-
- } -
- } -
- } }
} diff --git a/booklore-ui/src/app/features/stats/component/stats-component.scss b/booklore-ui/src/app/features/stats/component/stats-component.scss index 0e8deb826..3d46106e1 100644 --- a/booklore-ui/src/app/features/stats/component/stats-component.scss +++ b/booklore-ui/src/app/features/stats/component/stats-component.scss @@ -715,7 +715,7 @@ display: flex; align-items: center; justify-content: center; - gap: 1rem; + gap: 0.5rem; .year-nav-btn { background: rgba(255, 255, 255, 0.1); @@ -908,7 +908,7 @@ &.publisher-chart, &.author-rating-chart, &.book-size-chart { - height: 350px; + height: 100px; } &.year-chart, diff --git a/booklore-ui/src/app/features/stats/component/stats-component.ts b/booklore-ui/src/app/features/stats/component/stats-component.ts index 88a1b0cf1..d7801c41c 100644 --- a/booklore-ui/src/app/features/stats/component/stats-component.ts +++ b/booklore-ui/src/app/features/stats/component/stats-component.ts @@ -28,8 +28,6 @@ import {BookSizeChartService} from '../service/book-size-chart.service'; import {ReadingVelocityTimelineChartService} from '../service/reading-velocity-timeline-chart.service'; import {MonthlyReadingPatternsChartService} from '../service/monthly-reading-patterns-chart.service'; import {TopSeriesChartService} from '../service/top-series-chart.service'; -import {ReadingDNAChartService} from '../service/reading-dna-chart.service'; -import {ReadingHabitsChartService} from '../service/reading-habits-chart.service'; import {ChartConfig, ChartConfigService} from '../service/chart-config.service'; @Component({ @@ -67,8 +65,6 @@ export class StatsComponent implements OnInit, OnDestroy { protected readonly readingVelocityTimelineChartService = inject(ReadingVelocityTimelineChartService); protected readonly monthlyReadingPatternsChartService = inject(MonthlyReadingPatternsChartService); protected readonly topSeriesChartService = inject(TopSeriesChartService); - protected readonly readingDNAChartService = inject(ReadingDNAChartService); - protected readonly readingHabitsChartService = inject(ReadingHabitsChartService); protected readonly chartConfigService = inject(ChartConfigService); private readonly pageTitle = inject(PageTitleService); diff --git a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html index 400165534..bfc8e2e43 100644 --- a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html +++ b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html @@ -1,11 +1,99 @@
-
-
- -
- -
- +
+
+
+ +

{{ userName }}'s Reading Statistics

+
+
+ + + +
+
+ @for (chart of charts; track chart.id) { +
+
+ +
+ {{ chart.title }} + +
+ } +
+
+ + + + + Reset Layout + + + + Hide All + + + + Show All + + + Close + + +
+ + +
+ @for (chart of visibleCharts; track chart.id) { +
+
+ +
+ + @switch (chart.id) { + @case ('heatmap') { + + } + @case ('timeline') { + + } + @case ('genre-stats') { + + } + @case ('completion-timeline') { + + } + @case ('favorite-days') { + + } + @case ('peak-hours') { + + } + @case ('reading-dna') { + + } + @case ('reading-habits') { + + } + } +
+ } +
diff --git a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss index 432d5ae9c..9a48607bc 100644 --- a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss +++ b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss @@ -9,16 +9,12 @@ .header-section { background: var(--card-background); border-radius: 12px; - padding: 1.5rem; + padding: 1rem; backdrop-filter: blur(10px); border: 1px solid var(--p-content-border-color); box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); margin-bottom: 2rem; - margin-left: auto; - margin-right: auto; transition: all 0.3s ease; - width: fit-content; - max-width: 100%; &:hover { border-color: rgba(255, 255, 255, 0.2); @@ -27,16 +23,19 @@ .header-content { display: flex; - flex-direction: column; - gap: 0.5rem; + justify-content: center; align-items: center; - text-align: center; + gap: 2rem; + position: relative; } .greeting { display: flex; align-items: center; gap: 0.75rem; + position: absolute; + left: 50%; + transform: translateX(-50%); i { font-size: 1.5rem; @@ -51,12 +50,147 @@ white-space: nowrap; } } + + .config-toggle-btn { + margin-left: auto; + } +} + +.config-header { + display: flex; + justify-content: flex-end; + margin-bottom: 1rem; +} + +.config-toggle-btn { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.75rem 1.25rem; + background: var(--card-background); + border: 1px solid var(--p-content-border-color); + border-radius: 8px; + color: var(--text-color); + cursor: pointer; + transition: all 0.3s ease; + font-size: 0.9rem; + white-space: nowrap; + + &:hover { + background: var(--p-primary-color); + color: white; + border-color: var(--p-primary-color); + } + + i { + font-size: 1rem; + } +} + +// Dialog styles +::ng-deep .config-dialog { + .p-dialog-header { + border-bottom: 1px solid var(--p-content-border-color); + } + + .p-dialog-content { + background: var(--card-background); + padding: 1.5rem; + } + + .p-dialog-footer { + border-top: 1px solid var(--p-content-border-color); + padding: 1rem 1.5rem; + display: flex; + gap: 0.75rem; + justify-content: flex-end; + + .reset-btn { + margin-right: auto; + } + + .hide-all-btn, + .show-all-btn { + display: flex; + align-items: center; + gap: 0.5rem; + } + } +} + +.config-dialog-content { + .config-list { + display: flex; + flex-direction: column; + gap: 0.75rem; + } + + .config-item { + display: flex; + align-items: center; + gap: 1rem; + padding: 0.5rem 1.25rem; + background: rgba(255, 255, 255, 0.03); + border: 1px solid var(--p-content-border-color); + border-radius: 8px; + cursor: move; + transition: all 0.2s ease; + + &:hover { + background: rgba(255, 255, 255, 0.05); + border-color: var(--p-primary-color); + } + + .drag-handle { + cursor: grab; + color: var(--text-color-secondary); + display: flex; + align-items: center; + + &:active { + cursor: grabbing; + } + } + + .chart-title { + flex: 1; + color: var(--text-color); + font-size: 0.95rem; + } + + .visibility-toggle { + padding: 0.5rem; + background: transparent; + border: 1px solid var(--p-content-border-color); + border-radius: 6px; + color: var(--p-primary-color); + cursor: pointer; + transition: all 0.2s ease; + + &:hover { + background: var(--p-primary-color); + color: white; + border-color: var(--p-primary-color); + } + + &.disabled { + color: var(--text-color-secondary); + opacity: 0.5; + + &:hover { + background: transparent; + color: var(--text-color-secondary); + border-color: var(--p-content-border-color); + } + } + } + } } .charts-container { - display: flex; - flex-direction: column; - gap: 2rem; + display: grid; + grid-template-columns: repeat(12, 1fr); + gap: 1.5rem; } .chart-card { @@ -67,11 +201,77 @@ border: 1px solid var(--p-content-border-color); box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; + position: relative; + overflow: hidden; &:hover { border-color: rgba(255, 255, 255, 0.2); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15); + + .chart-drag-handle { + opacity: 1; + } } + + .chart-drag-handle { + position: absolute; + top: 0.5rem; + right: 0.5rem; + padding: 0.5rem; + background: rgba(0, 0, 0, 0.3); + border-radius: 6px; + cursor: grab; + opacity: 0; + transition: opacity 0.2s ease; + z-index: 10; + color: var(--text-color); + + &:active { + cursor: grabbing; + } + + &:hover { + background: rgba(0, 0, 0, 0.5); + } + } + + &.chart-small-square { + grid-column: span 3; + } + + &.chart-small { + grid-column: span 4; + } + + &.chart-medium { + grid-column: span 6; + } + + &.chart-large { + grid-column: span 8; + } + + &.chart-wide { + grid-column: span 9; + } + + &.chart-full { + grid-column: span 12; + } +} + +.cdk-drag-preview { + opacity: 0.8; + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3); +} + +.cdk-drag-placeholder { + opacity: 0.3; + border: 2px dashed var(--p-primary-color); +} + +.cdk-drag-animating { + transition: transform 250ms cubic-bezier(0, 0, 0.2, 1); } @media (max-width: 768px) { @@ -79,10 +279,60 @@ padding: 1rem; } + .config-toggle-btn { + span { + display: none; + } + } + + ::ng-deep .config-dialog { + .p-dialog-content { + padding: 1rem; + } + + .p_dialog_footer { + flex-direction: column; + gap: 0.5rem; + + .reset-btn { + margin-right: 0; + width: 100%; + } + + button { + width: 100%; + } + } + } + + .config-panel { + padding: 1rem; + + .config-panel-header { + flex-direction: column; + align-items: flex-start; + gap: 1rem; + + .reset-btn { + width: 100%; + justify-content: center; + } + } + } + .header-section { padding: 1rem; + .header-content { + flex-direction: column; + gap: 1rem; + position: static; + } + .greeting { + position: static; + transform: none; + i { font-size: 1.25rem; } @@ -94,8 +344,36 @@ } } + .config-toggle-btn { + width: 100%; + justify-content: center; + margin-left: 0; + + span { + display: inline; + } + } + + .charts-container { + grid-template-columns: repeat(6, 1fr); + gap: 1rem; + } + .chart-card { padding: 1rem; + + .chart-drag-handle { + opacity: 1; + } + + &.chart-small-square, + &.chart-small, + &.chart-medium, + &.chart-large, + &.chart-wide, + &.chart-full { + grid-column: span 6; + } } } @@ -104,6 +382,20 @@ padding: 0.75rem; } + .config-toggle-btn { + padding: 0.5rem 0.75rem; + } + + ::ng-deep .config-dialog { + .p-dialog-content { + padding: 0.75rem; + } + } + + .config-panel { + padding: 0.75rem; + } + .header-section { padding: 0.75rem; @@ -121,7 +413,21 @@ } } + .charts-container { + grid-template-columns: 1fr; + gap: 0.75rem; + } + .chart-card { padding: 0.75rem; + + &.chart-small-square, + &.chart-small, + &.chart-medium, + &.chart-large, + &.chart-wide, + &.chart-full { + grid-column: span 1; + } } } diff --git a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts index 55069ea59..ad8a9fbe2 100644 --- a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts +++ b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts @@ -1,22 +1,38 @@ import {Component, inject, OnDestroy, OnInit} from '@angular/core'; import {CommonModule} from '@angular/common'; import {Subject} from 'rxjs'; +import {CdkDragDrop, DragDropModule} from '@angular/cdk/drag-drop'; +import {DialogModule} from 'primeng/dialog'; +import {ButtonModule} from 'primeng/button'; import {ReadingSessionHeatmapComponent} from '../reading-session-heatmap/reading-session-heatmap.component'; import {ReadingSessionTimelineComponent} from '../reading-session-timeline/reading-session-timeline.component'; +import {GenreStatsChartComponent} from '../genre-stats-chart/genre-stats-chart.component'; +import {CompletionTimelineChartComponent} from '../completion-timeline-chart/completion-timeline-chart.component'; import {UserService} from '../../../settings/user-management/user.service'; import {takeUntil} from 'rxjs/operators'; - -interface UserChartConfig { - id: string; - component: any; - enabled: boolean; - order: number; -} +import {FavoriteDaysChartComponent} from '../favorite-days-chart/favorite-days-chart.component'; +import {PeakHoursChartComponent} from '../peak-hours-chart/peak-hours-chart.component'; +import {ReadingDNAChartComponent} from '../reading-dna-chart/reading-dna-chart.component'; +import {ReadingHabitsChartComponent} from '../reading-habits-chart/reading-habits-chart.component'; +import {UserChartConfig, UserChartConfigService} from '../../service/user-chart-config.service'; @Component({ selector: 'app-user-stats', standalone: true, - imports: [CommonModule, ReadingSessionHeatmapComponent, ReadingSessionTimelineComponent], + imports: [ + CommonModule, + DragDropModule, + DialogModule, + ButtonModule, + ReadingSessionHeatmapComponent, + ReadingSessionTimelineComponent, + GenreStatsChartComponent, + CompletionTimelineChartComponent, + FavoriteDaysChartComponent, + PeakHoursChartComponent, + ReadingDNAChartComponent, + ReadingHabitsChartComponent + ], templateUrl: './user-stats.component.html', styleUrls: ['./user-stats.component.scss'] }) @@ -24,10 +40,22 @@ export class UserStatsComponent implements OnInit, OnDestroy { private readonly destroy$ = new Subject(); private userService = inject(UserService); + private chartConfigService = inject(UserChartConfigService); + public currentYear = new Date().getFullYear(); public userName: string = ''; + public showConfigPanel = false; + public charts: UserChartConfig[] = []; + public visibleCharts: UserChartConfig[] = []; ngOnInit(): void { + this.chartConfigService.charts$ + .pipe(takeUntil(this.destroy$)) + .subscribe(charts => { + this.charts = charts; + this.visibleCharts = this.chartConfigService.getVisibleCharts(); + }); + this.userService.userState$ .pipe(takeUntil(this.destroy$)) .subscribe(state => { @@ -41,4 +69,36 @@ export class UserStatsComponent implements OnInit, OnDestroy { this.destroy$.next(); this.destroy$.complete(); } + + toggleChart(chartId: string): void { + this.chartConfigService.toggleChart(chartId); + } + + drop(event: CdkDragDrop): void { + this.chartConfigService.reorderCharts(event.previousIndex, event.currentIndex); + } + + toggleConfigPanel(): void { + this.showConfigPanel = !this.showConfigPanel; + } + + resetLayout(): void { + this.chartConfigService.resetLayout(); + } + + hideAllCharts(): void { + this.charts.forEach(chart => { + if (chart.enabled) { + this.chartConfigService.toggleChart(chart.id); + } + }); + } + + showAllCharts(): void { + this.charts.forEach(chart => { + if (!chart.enabled) { + this.chartConfigService.toggleChart(chart.id); + } + }); + } } diff --git a/booklore-ui/src/app/features/stats/service/author-series-portfolio-chart.service.ts b/booklore-ui/src/app/features/stats/service/author-series-portfolio-chart.service.ts deleted file mode 100644 index 2bebec38d..000000000 --- a/booklore-ui/src/app/features/stats/service/author-series-portfolio-chart.service.ts +++ /dev/null @@ -1,355 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book} from '../../book/model/book.model'; - -interface AuthorSeriesStats { - category: string; - count: number; - authorNames: string[]; - totalSeries: number; - averageSeriesLength: number; - description: string; -} - -const CHART_COLORS = [ - '#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', - '#e67e22', '#1abc9c', '#34495e', '#95a5a6', '#27ae60', - '#2980b9', '#c0392b', '#d35400', '#8e44ad', '#16a085' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type AuthorSeriesChartData = ChartData<'polarArea', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class AuthorSeriesPortfolioChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly authorSeriesChartType = 'polarArea' as const; - - public readonly authorSeriesChartOptions: ChartConfiguration<'polarArea'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - ticks: { - color: '#ffffff', - font: { - family: "'Inter', sans-serif", - size: 11 - }, - stepSize: 1, - backdropColor: 'transparent' - }, - grid: { - color: 'rgba(255, 255, 255, 0.15)' - }, - angleLines: { - color: 'rgba(255, 255, 255, 0.15)' - }, - pointLabels: { - color: '#ffffff', - font: { - family: "'Inter', sans-serif", - size: 11 - }, - } - } - }, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: { - family: "'Inter', sans-serif", - size: 11 - }, - padding: 10, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: {size: 14, weight: 'bold'}, - bodyFont: {size: 12}, - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'point' - } - }; - - private readonly authorSeriesChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly authorSeriesChartData$: Observable = this.authorSeriesChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getAuthorSeriesStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing author series stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: AuthorSeriesStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.authorSeriesChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating author series chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getAuthorSeriesStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processAuthorSeriesStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting author series stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processAuthorSeriesStats(books: Book[]): AuthorSeriesStats[] { - if (books.length === 0) { - return []; - } - - const authorSeriesMap = new Map>(); - - books.forEach(book => { - if (!book.metadata?.authors || !book.metadata.seriesName) return; - - book.metadata.authors.forEach(author => { - if (!authorSeriesMap.has(author)) { - authorSeriesMap.set(author, new Map()); - } - - const authorSeries = authorSeriesMap.get(author)!; - const seriesName = book.metadata!.seriesName!; - - if (!authorSeries.has(seriesName)) { - authorSeries.set(seriesName, []); - } - authorSeries.get(seriesName)!.push(book); - }); - }); - - const authorPatterns = new Map(); - - const categories = [ - 'Single Series Masters', - 'Prolific Series Writers', - 'Multi-Series Creators', - 'Series Experimenters', - 'Franchise Builders', - 'Diverse Portfolio Authors' - ]; - - categories.forEach(cat => { - authorPatterns.set(cat, {authors: [], totalSeries: 0, totalSeriesLength: 0}); - }); - - for (const [author, authorSeries] of authorSeriesMap) { - const seriesCount = authorSeries.size; - const seriesLengths: number[] = []; - let totalBooks = 0; - - for (const [_, seriesBooks] of authorSeries) { - const seriesTotals = seriesBooks - .map(book => book.metadata?.seriesTotal) - .filter((total): total is number => total != null && total > 0); - - const seriesLength = seriesTotals.length > 0 - ? Math.max(...seriesTotals) - : seriesBooks.length; - - seriesLengths.push(seriesLength); - totalBooks += seriesBooks.length; - } - - const averageSeriesLength = seriesLengths.reduce((sum, length) => sum + length, 0) / seriesLengths.length; - const maxSeriesLength = Math.max(...seriesLengths); - - let category: string; - - if (seriesCount === 1 && maxSeriesLength >= 10) { - category = 'Single Series Masters'; - } else if (seriesCount >= 5 && averageSeriesLength >= 5) { - category = 'Prolific Series Writers'; - } else if (seriesCount >= 3 && seriesCount <= 4) { - category = 'Multi-Series Creators'; - } else if (seriesCount >= 2 && averageSeriesLength <= 3) { - category = 'Series Experimenters'; - } else if (seriesCount >= 2 && maxSeriesLength >= 15) { - category = 'Franchise Builders'; - } else { - category = 'Diverse Portfolio Authors'; - } - - const categoryData = authorPatterns.get(category)!; - categoryData.authors.push(author); - categoryData.totalSeries += seriesCount; - categoryData.totalSeriesLength += Math.round(averageSeriesLength); - } - - const descriptions: Record = { - 'Single Series Masters': 'Authors focused on one long-running series', - 'Prolific Series Writers': 'Authors with multiple substantial series', - 'Multi-Series Creators': 'Authors balancing several series', - 'Series Experimenters': 'Authors exploring shorter series formats', - 'Franchise Builders': 'Authors creating extensive fictional universes', - 'Diverse Portfolio Authors': 'Authors with varied series approaches' - }; - - return Array.from(authorPatterns.entries()) - .filter(([_, data]) => data.authors.length > 0) - .map(([category, data]) => ({ - category, - count: data.authors.length, - authorNames: data.authors, - totalSeries: data.totalSeries, - averageSeriesLength: data.authors.length > 0 - ? Math.round(data.totalSeriesLength / data.authors.length) - : 0, - description: descriptions[category] || 'Various series approaches' - })) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const stats = this.getLastCalculatedStats(); - - if (!stats || dataIndex >= stats.length) { - return `${context.parsed} authors`; - } - - const categoryStats = stats[dataIndex]; - const exampleAuthors = categoryStats.authorNames.slice(0, 3).join(', '); - const moreAuthors = categoryStats.authorNames.length > 3 ? `... +${categoryStats.authorNames.length - 3} more` : ''; - - return `${categoryStats.count} authors | ${categoryStats.totalSeries} total series | Avg ${categoryStats.averageSeriesLength} books/series | ${categoryStats.description} | Examples: ${exampleAuthors}${moreAuthors}`; - } - - private lastCalculatedStats: AuthorSeriesStats[] = []; - - private getLastCalculatedStats(): AuthorSeriesStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/chart-config.service.ts b/booklore-ui/src/app/features/stats/service/chart-config.service.ts index 177da01eb..1296b6b1b 100644 --- a/booklore-ui/src/app/features/stats/service/chart-config.service.ts +++ b/booklore-ui/src/app/features/stats/service/chart-config.service.ts @@ -30,9 +30,7 @@ export class ChartConfigService { {id: 'pageCount', name: 'Page Count Distribution', enabled: true, category: 'medium', order: 11}, {id: 'topBooksBySize', name: 'Top 20 Largest Books', enabled: true, category: 'large', order: 12}, {id: 'topSeries', name: 'Top 20 Series', enabled: true, category: 'large', order: 13}, - {id: 'readingDNA', name: 'Reading DNA Profile', enabled: true, category: 'large', order: 14}, - {id: 'readingHabits', name: 'Reading Habits Analysis', enabled: true, category: 'large', order: 15}, - {id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 16} + {id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 14} ]; private chartsConfigSubject = new BehaviorSubject(this.loadConfig()); diff --git a/booklore-ui/src/app/features/stats/service/finished-books-timeline-chart.service.ts b/booklore-ui/src/app/features/stats/service/finished-books-timeline-chart.service.ts deleted file mode 100644 index 939f5e928..000000000 --- a/booklore-ui/src/app/features/stats/service/finished-books-timeline-chart.service.ts +++ /dev/null @@ -1,54 +0,0 @@ -// ...existing code... - - private processFinishedBooksStats(books: Book[]): FinishedBooksStats[] { - const yearMonthMap = new Map(); - - books.forEach(book => { - if (book.dateFinished) { - const finishedDate = new Date(book.dateFinished); - const yearMonth = `${finishedDate.getFullYear()}-${(finishedDate.getMonth() + 1).toString().padStart(2, '0')}`; - yearMonthMap.set(yearMonth, (yearMonthMap.get(yearMonth) || 0) + 1); - } - }); - - // Get the range of months - const monthsWithData = Array.from(yearMonthMap.keys()).sort(); - - if (monthsWithData.length === 0) { - return []; - } - - // Fill in all missing months between first and last data points - const startDate = this.parseYearMonth(monthsWithData[0]); - const endDate = this.parseYearMonth(monthsWithData[monthsWithData.length - 1]); - - const completeStats: FinishedBooksStats[] = []; - let currentDate = new Date(startDate.year, startDate.month - 1, 1); - const endDateObj = new Date(endDate.year, endDate.month - 1, 1); - - while (currentDate <= endDateObj) { - const year = currentDate.getFullYear(); - const month = currentDate.getMonth() + 1; - const yearMonth = `${year}-${month.toString().padStart(2, '0')}`; - - completeStats.push({ - yearMonth, - count: yearMonthMap.get(yearMonth) || 0, - year, - month - }); - - // Move to next month - currentDate.setMonth(currentDate.getMonth() + 1); - } - - return completeStats.sort((a, b) => a.yearMonth.localeCompare(b.yearMonth)); - } - - private parseYearMonth(yearMonthStr: string): { year: number, month: number } { - const [year, month] = yearMonthStr.split('-').map(Number); - return { year, month }; - } - -// ...existing code... - diff --git a/booklore-ui/src/app/features/stats/service/reading-velocity-chart.service.ts b/booklore-ui/src/app/features/stats/service/reading-velocity-chart.service.ts deleted file mode 100644 index 250c93f2e..000000000 --- a/booklore-ui/src/app/features/stats/service/reading-velocity-chart.service.ts +++ /dev/null @@ -1,380 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; - -interface ReadingVelocityStats { - category: string; - count: number; - averagePages: number; - averageRating: number; - description: string; -} - -const CHART_COLORS = [ - '#ff6b9d', '#45aaf2', '#96f7d2', '#feca57', '#ff9ff3', - '#54a0ff', '#5f27cd', '#00d2d3', '#ff9f43', '#10ac84', - '#ee5a6f', '#60a3bc', '#130f40', '#30336b', '#535c68' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type VelocityChartData = ChartData<'polarArea', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class ReadingVelocityChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly velocityChartType = 'polarArea' as const; - - public readonly velocityChartOptions: ChartConfiguration<'polarArea'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - ticks: { - color: '#ffffff', - font: {size: 10}, - stepSize: 1, - backdropColor: 'transparent' - }, - grid: { - color: 'rgba(255, 255, 255, 0.15)' - }, - angleLines: { - color: 'rgba(255, 255, 255, 0.15)' - }, - pointLabels: { - color: '#ffffff', - font: {size: 10} - } - } - }, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: {size: 10}, - padding: 10, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - enabled: true, - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: {size: 14, weight: 'bold'}, - bodyFont: {size: 12}, - position: 'nearest', - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'point' - } - }; - - private readonly velocityChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly velocityChartData$: Observable = this.velocityChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getReadingVelocityStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing reading velocity stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: ReadingVelocityStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.velocityChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating velocity chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getReadingVelocityStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processReadingVelocityStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting reading velocity stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processReadingVelocityStats(books: Book[]): ReadingVelocityStats[] { - if (books.length === 0) { - return []; - } - - const velocityCategories = this.categorizeByReadingVelocity(books); - return this.convertToVelocityStats(velocityCategories); - } - - private categorizeByReadingVelocity(books: Book[]): Map { - const categories = new Map(); - - // Initialize categories - categories.set('Speed Readers', []); - categories.set('Consistent Readers', []); - categories.set('Selective Readers', []); - categories.set('Exploratory Readers', []); - categories.set('Deep Readers', []); - categories.set('Casual Readers', []); - categories.set('Quality Seekers', []); - - const readBooks = books.filter(book => - book.readStatus === ReadStatus.READ && - book.metadata?.pageCount && - book.metadata.pageCount > 0 - ); - - const completedBooks = readBooks.length; - const totalBooks = books.length; - const completionRate = completedBooks / totalBooks; - - const averagePageCount = readBooks.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0) / readBooks.length || 0; - const averageRating = this.calculateAverageRating(readBooks); - - for (const book of books) { - const pageCount = book.metadata?.pageCount || 0; - const hasHighRating = this.hasHighQualityRating(book); - const isCompleted = book.readStatus === ReadStatus.READ; - const isCurrentlyReading = book.readStatus === ReadStatus.READING; - const progress = this.getReadingProgress(book); - - // Speed Readers: High completion rate + prefer shorter books - if (completionRate > 0.6 && pageCount > 0 && pageCount < averagePageCount * 0.8) { - categories.get('Speed Readers')!.push(book); - } - // Deep Readers: Prefer longer, high-quality books - else if (pageCount > averagePageCount * 1.5 && hasHighRating) { - categories.get('Deep Readers')!.push(book); - } - // Quality Seekers: Focus on highly-rated books regardless of length - else if (hasHighRating && (isCompleted || progress > 0.5)) { - categories.get('Quality Seekers')!.push(book); - } - // Exploratory Readers: Wide variety of books, many started but not finished - else if (!isCompleted && (progress > 0.1 && progress < 0.8)) { - categories.get('Exploratory Readers')!.push(book); - } - // Consistent Readers: Steady reading pattern, average book length - else if (isCompleted && pageCount > averagePageCount * 0.8 && pageCount < averagePageCount * 1.2) { - categories.get('Consistent Readers')!.push(book); - } - // Selective Readers: Few books but high completion rate - else if (completionRate > 0.4 && totalBooks < 50) { - categories.get('Selective Readers')!.push(book); - } - // Casual Readers: Everything else - else { - categories.get('Casual Readers')!.push(book); - } - } - - return categories; - } - - private hasHighQualityRating(book: Book): boolean { - const metadata = book.metadata; - if (!metadata) return false; - - const goodreadsRating = metadata.goodreadsRating || 0; - const amazonRating = metadata.amazonRating || 0; - const personalRating = book.personalRating || 0; - - return goodreadsRating >= 4.0 || amazonRating >= 4.0 || personalRating >= 4; - } - - private getReadingProgress(book: Book): number { - if (book.readStatus === ReadStatus.READ) return 1.0; - - const epubProgress = book.epubProgress?.percentage || 0; - const pdfProgress = book.pdfProgress?.percentage || 0; - const cbxProgress = book.cbxProgress?.percentage || 0; - const koreaderProgress = book.koreaderProgress?.percentage || 0; - const koboProgress = book.koboProgress?.percentage || 0; - - return Math.max(epubProgress, pdfProgress, cbxProgress, koreaderProgress, koboProgress) / 100; - } - - private calculateAverageRating(books: Book[]): number { - const ratingsBooks = books.filter(book => { - const metadata = book.metadata; - return metadata && (metadata.goodreadsRating || metadata.amazonRating || book.personalRating); - }); - - if (ratingsBooks.length === 0) return 0; - - const totalRating = ratingsBooks.reduce((sum, book) => { - const metadata = book.metadata!; - const rating = metadata.goodreadsRating || metadata.amazonRating || book.personalRating || 0; - return sum + rating; - }, 0); - - return totalRating / ratingsBooks.length; - } - - private convertToVelocityStats(categoriesMap: Map): ReadingVelocityStats[] { - const descriptions: Record = { - 'Speed Readers': 'High completion rate with shorter books', - 'Consistent Readers': 'Steady reading pattern with average-length books', - 'Selective Readers': 'Few books but high completion rate', - 'Exploratory Readers': 'Wide variety, many started but not finished', - 'Deep Readers': 'Prefer longer, high-quality books', - 'Casual Readers': 'Mixed reading patterns', - 'Quality Seekers': 'Focus on highly-rated books' - }; - - return Array.from(categoriesMap.entries()) - .filter(([_, books]) => books.length > 0) - .map(([category, books]) => { - const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ); - const averagePages = books.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0) / books.length; - const averageRating = this.calculateAverageRating(books); - - return { - category, - count: books.length, - averagePages: Math.round(averagePages), - averageRating: Number(averageRating.toFixed(1)), - description: descriptions[category] || 'Mixed reading patterns' - }; - }) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const velocityStats = this.getLastCalculatedStats(); - - if (!velocityStats || dataIndex >= velocityStats.length) { - return `${context.parsed} books`; - } - - const stats = velocityStats[dataIndex]; - return `${stats.count} books | Avg. ${stats.averagePages} pages | Avg. rating: ${stats.averageRating}/5 | ${stats.description}`; - } - - private lastCalculatedStats: ReadingVelocityStats[] = []; - - private getLastCalculatedStats(): ReadingVelocityStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/series-completion-progress-chart.service.ts b/booklore-ui/src/app/features/stats/service/series-completion-progress-chart.service.ts deleted file mode 100644 index dd4e52799..000000000 --- a/booklore-ui/src/app/features/stats/service/series-completion-progress-chart.service.ts +++ /dev/null @@ -1,327 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; - -interface SeriesCompletionStats { - seriesName: string; - totalBooks: number; - ownedBooks: number; - readBooks: number; - completionPercentage: number; - collectionPercentage: number; - isComplete: boolean; - averageRating: number; -} - -const CHART_COLORS = [ - '#2ecc71', '#3498db', '#e74c3c', '#f39c12', '#9b59b6', - '#1abc9c', '#34495e', '#e67e22', '#95a5a6', '#27ae60', - '#2980b9', '#c0392b', '#d35400', '#8e44ad', '#16a085' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 1, - hoverBorderWidth: 2, - hoverBorderColor: '#ffffff' -} as const; - -type SeriesCompletionChartData = ChartData<'bar', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class SeriesCompletionProgressChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly seriesCompletionChartType = 'bar' as const; - - public readonly seriesCompletionChartOptions: ChartConfiguration<'bar'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - x: { - ticks: { - color: '#ffffff', - font: { size: 10 }, - maxRotation: 45 - }, - grid: { - color: 'rgba(255, 255, 255, 0.1)' - }, - title: { - display: true, - text: 'Series', - color: '#ffffff', - font: { size: 12 } - } - }, - y: { - beginAtZero: true, - max: 100, - ticks: { - color: '#ffffff', - font: { size: 10 }, - callback: function(value) { - return value + '%'; - } - }, - grid: { - color: 'rgba(255, 255, 255, 0.1)' - }, - title: { - display: true, - text: 'Completion %', - color: '#ffffff', - font: { size: 12 } - } - } - }, - plugins: { - legend: { - display: true, - position: 'top', - labels: { - color: '#ffffff', - font: { size: 11 }, - padding: 15, - usePointStyle: true - } - }, - tooltip: { - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: { size: 14, weight: 'bold' }, - bodyFont: { size: 12 }, - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'index' - } - }; - - private readonly seriesCompletionChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [] - }); - - public readonly seriesCompletionChartData$: Observable = this.seriesCompletionChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getSeriesCompletionStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing series completion stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: SeriesCompletionStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => this.truncateSeriesName(s.seriesName, 20)); - - const datasets = [ - { - label: 'Reading Progress', - data: stats.map(s => s.completionPercentage), - backgroundColor: '#2ecc71', - ...CHART_DEFAULTS - }, - { - label: 'Collection Progress', - data: stats.map(s => s.collectionPercentage), - backgroundColor: '#3498db', - ...CHART_DEFAULTS - } - ]; - - this.seriesCompletionChartDataSubject.next({ - labels, - datasets - }); - } catch (error) { - console.error('Error updating series completion chart data:', error); - } - } - - private truncateSeriesName(name: string, maxLength: number): string { - if (name.length <= maxLength) return name; - return name.substring(0, maxLength - 3) + '...'; - } - - public getSeriesCompletionStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processSeriesCompletionStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting series completion stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processSeriesCompletionStats(books: Book[]): SeriesCompletionStats[] { - if (books.length === 0) { - return []; - } - - // Group books by series - const seriesMap = new Map(); - - books.forEach(book => { - const seriesName = book.metadata?.seriesName; - if (seriesName && seriesName.trim()) { - if (!seriesMap.has(seriesName)) { - seriesMap.set(seriesName, []); - } - seriesMap.get(seriesName)!.push(book); - } - }); - - // Calculate completion stats for each series - const seriesStats: SeriesCompletionStats[] = []; - - for (const [seriesName, seriesBooks] of seriesMap) { - const stats = this.calculateSeriesStats(seriesName, seriesBooks); - if (stats.totalBooks > 1) { // Only include actual series (more than 1 book) - seriesStats.push(stats); - } - } - - return seriesStats - .sort((a, b) => { - // Sort by completion percentage, then by collection percentage - if (a.completionPercentage !== b.completionPercentage) { - return b.completionPercentage - a.completionPercentage; - } - return b.collectionPercentage - a.collectionPercentage; - }) - .slice(0, 15); // Top 15 series - } - - private calculateSeriesStats(seriesName: string, books: Book[]): SeriesCompletionStats { - // Determine total books in series - const seriesTotals = books - .map(book => book.metadata?.seriesTotal) - .filter((total): total is number => total != null && total > 0); - - const totalBooks = seriesTotals.length > 0 - ? Math.max(...seriesTotals) - : books.length; // Fallback to owned books count - - const ownedBooks = books.length; - const readBooks = books.filter(book => book.readStatus === ReadStatus.READ).length; - - // Calculate completion and collection percentages - const completionPercentage = totalBooks > 0 - ? Math.round((readBooks / totalBooks) * 100) - : 0; - - const collectionPercentage = totalBooks > 0 - ? Math.round((ownedBooks / totalBooks) * 100) - : 100; - - const isComplete = ownedBooks >= totalBooks; - - // Calculate average rating - const ratedBooks = books.filter(book => { - const rating = book.personalRating || book.metadata?.goodreadsRating; - return rating && rating > 0; - }); - - const averageRating = ratedBooks.length > 0 - ? Number((ratedBooks.reduce((sum, book) => { - const rating = book.personalRating || book.metadata?.goodreadsRating || 0; - return sum + rating; - }, 0) / ratedBooks.length).toFixed(1)) - : 0; - - return { - seriesName, - totalBooks, - ownedBooks, - readBooks, - completionPercentage, - collectionPercentage, - isComplete, - averageRating - }; - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const datasetLabel = context.dataset.label; - const value = context.parsed.y; - const stats = this.getLastCalculatedStats(); - - if (!stats || dataIndex >= stats.length) { - return `${datasetLabel}: ${value}%`; - } - - const series = stats[dataIndex]; - - if (datasetLabel === 'Reading Progress') { - return `${value}% read (${series.readBooks}/${series.totalBooks} books) | Avg rating: ${series.averageRating}/5`; - } else if (datasetLabel === 'Collection Progress') { - return `${value}% collected (${series.ownedBooks}/${series.totalBooks} books) | ${series.isComplete ? 'Complete!' : 'Incomplete'}`; - } - - return `${datasetLabel}: ${value}%`; - } - - private lastCalculatedStats: SeriesCompletionStats[] = []; - - private getLastCalculatedStats(): SeriesCompletionStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/series-length-distribution-chart.service.ts b/booklore-ui/src/app/features/stats/service/series-length-distribution-chart.service.ts deleted file mode 100644 index 181f2b9a5..000000000 --- a/booklore-ui/src/app/features/stats/service/series-length-distribution-chart.service.ts +++ /dev/null @@ -1,298 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book} from '../../book/model/book.model'; - -interface SeriesLengthStats { - category: string; - count: number; - percentage: number; - seriesNames: string[]; - averageBooksOwned: number; -} - -const CHART_COLORS = [ - '#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6', - '#1abc9c', '#34495e', '#e67e22', '#95a5a6', '#27ae60' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type SeriesLengthChartData = ChartData<'doughnut', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class SeriesLengthDistributionChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly seriesLengthChartType = 'doughnut' as const; - - public readonly seriesLengthChartOptions: ChartConfiguration<'doughnut'>['options'] = { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: { size: 11 }, - padding: 12, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: { size: 14, weight: 'bold' }, - bodyFont: { size: 12 }, - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'point' - }, - cutout: '50%' - }; - - private readonly seriesLengthChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly seriesLengthChartData$: Observable = this.seriesLengthChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getSeriesLengthStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing series length stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: SeriesLengthStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.seriesLengthChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating series length chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getSeriesLengthStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processSeriesLengthStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting series length stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processSeriesLengthStats(books: Book[]): SeriesLengthStats[] { - if (books.length === 0) { - return []; - } - - // Group books by series - const seriesMap = new Map(); - - books.forEach(book => { - const seriesName = book.metadata?.seriesName; - if (seriesName && seriesName.trim()) { - if (!seriesMap.has(seriesName)) { - seriesMap.set(seriesName, []); - } - seriesMap.get(seriesName)!.push(book); - } - }); - - // Categorize series by length - const categories = new Map(); - - // Initialize categories - const categoryRanges = [ - { name: 'Duologies (2 books)', min: 2, max: 2 }, - { name: 'Trilogies (3 books)', min: 3, max: 3 }, - { name: 'Short Series (4-5 books)', min: 4, max: 5 }, - { name: 'Medium Series (6-10 books)', min: 6, max: 10 }, - { name: 'Long Series (11-20 books)', min: 11, max: 20 }, - { name: 'Epic Series (21+ books)', min: 21, max: Infinity }, - { name: 'Unknown Length', min: 0, max: 0 } - ]; - - categoryRanges.forEach(range => { - categories.set(range.name, { count: 0, seriesNames: [], totalBooksOwned: 0 }); - }); - - // Categorize each series - for (const [seriesName, seriesBooks] of seriesMap) { - if (seriesBooks.length < 2) continue; // Skip single books - - // Determine series total length - const seriesTotals = seriesBooks - .map(book => book.metadata?.seriesTotal) - .filter((total): total is number => typeof total === 'number' && total > 0); - - const seriesLength = seriesTotals.length > 0 - ? Math.max(...seriesTotals) - : 0; // Unknown length - - let categoryName = 'Unknown Length'; - - if (seriesLength > 0) { - for (const range of categoryRanges) { - if (seriesLength >= range.min && seriesLength <= range.max) { - categoryName = range.name; - break; - } - } - } - - const categoryData = categories.get(categoryName)!; - categoryData.count++; - categoryData.seriesNames.push(seriesName); - categoryData.totalBooksOwned += seriesBooks.length; - } - - // Convert to stats array - const totalSeries = Array.from(categories.values()).reduce((sum, cat) => sum + cat.count, 0); - - return Array.from(categories.entries()) - .filter(([_, data]) => data.count > 0) - .map(([category, data]) => ({ - category, - count: data.count, - percentage: Number(((data.count / totalSeries) * 100).toFixed(1)), - seriesNames: data.seriesNames, - averageBooksOwned: data.count > 0 ? Math.round(data.totalBooksOwned / data.count) : 0 - })) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const stats = this.getLastCalculatedStats(); - - if (!stats || dataIndex >= stats.length) { - return `${context.parsed} series`; - } - - const categoryStats = stats[dataIndex]; - const total = context.chart.data.datasets[0].data.reduce((a: number, b: number) => a + b, 0); - const percentage = ((categoryStats.count / total) * 100).toFixed(1); - - return `${categoryStats.count} series (${percentage}%) | Avg ${categoryStats.averageBooksOwned} books owned | Examples: ${categoryStats.seriesNames.slice(0, 3).join(', ')}${categoryStats.seriesNames.length > 3 ? '...' : ''}`; - } - - private lastCalculatedStats: SeriesLengthStats[] = []; - - private getLastCalculatedStats(): SeriesLengthStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/series-standalone-chart.service.ts b/booklore-ui/src/app/features/stats/service/series-standalone-chart.service.ts deleted file mode 100644 index 5bd9b6ab7..000000000 --- a/booklore-ui/src/app/features/stats/service/series-standalone-chart.service.ts +++ /dev/null @@ -1,309 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book} from '../../book/model/book.model'; - -interface SeriesStats { - category: string; - count: number; - percentage: number; - description: string; -} - -const CHART_COLORS = [ - '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7', - '#dda0dd', '#98d8c8', '#ff7675', '#74b9ff', '#fdcb6e' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type SeriesChartData = ChartData<'polarArea', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class SeriesStandaloneChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly seriesChartType = 'polarArea' as const; - - public readonly seriesChartOptions: ChartConfiguration<'polarArea'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - ticks: { - color: '#ffffff', - font: {size: 10}, - stepSize: 1 - }, - grid: { - color: 'rgba(255, 255, 255, 0.2)' - }, - angleLines: { - color: 'rgba(255, 255, 255, 0.2)' - }, - pointLabels: { - color: '#ffffff', - font: {size: 11} - } - } - }, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: {size: 11}, - padding: 12, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - enabled: true, - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: {size: 14, weight: 'bold'}, - bodyFont: {size: 13}, - position: 'nearest', - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel - } - } - }, - interaction: { - intersect: false, - mode: 'point' - } - }; - - private readonly seriesChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly seriesChartData$: Observable = this.seriesChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getSeriesStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing series stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: SeriesStats[]): void { - try { - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.seriesChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating series chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getSeriesStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processSeriesStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting series stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processSeriesStats(books: Book[]): SeriesStats[] { - if (books.length === 0) { - return []; - } - - const stats = this.categorizeBooks(books); - return this.convertToStats(stats, books.length); - } - - private categorizeBooks(books: Book[]): Map { - const categories = new Map(); - - // Initialize categories - categories.set('Standalone Books', { count: 0, description: 'Books not part of any series' }); - categories.set('Series Books', { count: 0, description: 'Books that are part of a series' }); - categories.set('Complete Series', { count: 0, description: 'Books in complete series' }); - categories.set('Incomplete Series', { count: 0, description: 'Books in incomplete series' }); - categories.set('Unknown Series Status', { count: 0, description: 'Books with unclear series information' }); - - // Group books by series - const seriesMap = new Map(); - const standaloneBooks: Book[] = []; - - for (const book of books) { - const seriesName = book.metadata?.seriesName; - if (seriesName && seriesName.trim()) { - if (!seriesMap.has(seriesName)) { - seriesMap.set(seriesName, []); - } - seriesMap.get(seriesName)!.push(book); - } else { - standaloneBooks.push(book); - } - } - - // Count standalone books - categories.get('Standalone Books')!.count = standaloneBooks.length; - - // Process series books - let seriesBooks = 0; - let completeSeriesBooks = 0; - let incompleteSeriesBooks = 0; - let unknownSeriesBooks = 0; - - for (const [seriesName, seriesBookList] of seriesMap) { - seriesBooks += seriesBookList.length; - - // Check if series is complete - const seriesTotal = seriesBookList[0]?.metadata?.seriesTotal; - const hasSeriesNumbers = seriesBookList.every(book => book.metadata?.seriesNumber); - - if (seriesTotal && hasSeriesNumbers) { - const uniqueNumbers = new Set(seriesBookList.map(book => book.metadata?.seriesNumber)); - if (uniqueNumbers.size === seriesTotal) { - completeSeriesBooks += seriesBookList.length; - } else { - incompleteSeriesBooks += seriesBookList.length; - } - } else { - unknownSeriesBooks += seriesBookList.length; - } - } - - categories.get('Series Books')!.count = seriesBooks; - categories.get('Complete Series')!.count = completeSeriesBooks; - categories.get('Incomplete Series')!.count = incompleteSeriesBooks; - categories.get('Unknown Series Status')!.count = unknownSeriesBooks; - - return categories; - } - - private convertToStats(categoriesMap: Map, totalBooks: number): SeriesStats[] { - return Array.from(categoriesMap.entries()) - .filter(([_, data]) => data.count > 0) // Only include categories with books - .map(([category, data]) => ({ - category, - count: data.count, - percentage: Number(((data.count / totalBooks) * 100).toFixed(1)), - description: data.description - })) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const dataset = context.dataset; - const value = dataset.data[dataIndex] as number; - const label = context.chart.data.labels?.[dataIndex] || 'Unknown'; - const total = (dataset.data as number[]).reduce((a: number, b: number) => a + b, 0); - const percentage = ((value / total) * 100).toFixed(1); - return `${label}: ${value} books (${percentage}%)`; - } -} - diff --git a/booklore-ui/src/app/features/stats/service/user-chart-config.service.ts b/booklore-ui/src/app/features/stats/service/user-chart-config.service.ts new file mode 100644 index 000000000..973a91e5f --- /dev/null +++ b/booklore-ui/src/app/features/stats/service/user-chart-config.service.ts @@ -0,0 +1,166 @@ +import {Injectable} from '@angular/core'; +import {BehaviorSubject, Observable} from 'rxjs'; +import {ReadingSessionHeatmapComponent} from '../component/reading-session-heatmap/reading-session-heatmap.component'; +import {ReadingSessionTimelineComponent} from '../component/reading-session-timeline/reading-session-timeline.component'; +import {GenreStatsChartComponent} from '../component/genre-stats-chart/genre-stats-chart.component'; +import {CompletionTimelineChartComponent} from '../component/completion-timeline-chart/completion-timeline-chart.component'; +import {FavoriteDaysChartComponent} from '../component/favorite-days-chart/favorite-days-chart.component'; +import {PeakHoursChartComponent} from '../component/peak-hours-chart/peak-hours-chart.component'; +import {ReadingDNAChartComponent} from '../component/reading-dna-chart/reading-dna-chart.component'; +import {ReadingHabitsChartComponent} from '../component/reading-habits-chart/reading-habits-chart.component'; + +export interface UserChartConfig { + id: string; + title: string; + component: any; + enabled: boolean; + sizeClass: string; + order: number; +} + +@Injectable({ + providedIn: 'root' +}) +export class UserChartConfigService { + private readonly STORAGE_KEY = 'userStatsChartConfig'; + private readonly defaultCharts: UserChartConfig[] = [ + { + id: 'heatmap', + title: 'Reading Session Heatmap', + component: ReadingSessionHeatmapComponent, + enabled: true, + sizeClass: 'chart-full', + order: 0 + }, + { + id: 'favorite-days', + title: 'Favorite Reading Days', + component: FavoriteDaysChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 1 + }, + { + id: 'peak-hours', + title: 'Peak Reading Hours', + component: PeakHoursChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 2 + }, + { + id: 'genre-stats', + title: 'Genre Statistics', + component: GenreStatsChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 3 + }, + { + id: 'completion-timeline', + title: 'Completion Timeline', + component: CompletionTimelineChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 4 + }, + { + id: 'reading-dna', + title: 'Reading DNA Profile', + component: ReadingDNAChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 5 + }, + { + id: 'reading-habits', + title: 'Reading Habits Analysis', + component: ReadingHabitsChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 6 + }, + { + id: 'timeline', + title: 'Reading Session Timeline', + component: ReadingSessionTimelineComponent, + enabled: true, + sizeClass: 'chart-full', + order: 7 + }, + ]; + + private chartsSubject = new BehaviorSubject(this.loadChartConfig()); + public charts$: Observable = this.chartsSubject.asObservable(); + + getVisibleCharts(): UserChartConfig[] { + return this.chartsSubject.value.filter(chart => chart.enabled); + } + + toggleChart(chartId: string): void { + const charts = this.chartsSubject.value; + const chart = charts.find(c => c.id === chartId); + if (chart) { + chart.enabled = !chart.enabled; + this.saveChartConfig(charts); + this.chartsSubject.next([...charts]); + } + } + + reorderCharts(previousIndex: number, currentIndex: number): void { + const charts = [...this.chartsSubject.value]; + const [movedChart] = charts.splice(previousIndex, 1); + charts.splice(currentIndex, 0, movedChart); + + charts.forEach((chart, index) => { + chart.order = index; + }); + + this.saveChartConfig(charts); + this.chartsSubject.next(charts); + } + + resetLayout(): void { + const resetCharts = JSON.parse(JSON.stringify(this.defaultCharts)); + this.saveChartConfig(resetCharts); + this.chartsSubject.next(resetCharts); + } + + private saveChartConfig(charts: UserChartConfig[]): void { + const config = charts.map(chart => ({ + id: chart.id, + enabled: chart.enabled, + sizeClass: chart.sizeClass, + order: chart.order + })); + localStorage.setItem(this.STORAGE_KEY, JSON.stringify(config)); + } + + private loadChartConfig(): UserChartConfig[] { + const savedConfig = localStorage.getItem(this.STORAGE_KEY); + if (!savedConfig) { + return JSON.parse(JSON.stringify(this.defaultCharts)); + } + + try { + const config = JSON.parse(savedConfig); + const charts = JSON.parse(JSON.stringify(this.defaultCharts)); + + config.forEach((saved: any) => { + const chart = charts.find((c: UserChartConfig) => c.id === saved.id); + if (chart) { + chart.enabled = saved.enabled; + chart.sizeClass = saved.sizeClass; + chart.order = saved.order ?? chart.order; + } + }); + + charts.sort((a: UserChartConfig, b: UserChartConfig) => a.order - b.order); + + return charts; + } catch (e) { + console.error('Failed to load chart config', e); + return JSON.parse(JSON.stringify(this.defaultCharts)); + } + } +}