From 4e14b7a8e8f0456de49da8a5bcb333c0b1323ffe Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sun, 22 Feb 2026 16:39:22 -0700 Subject: [PATCH] Add 10 advanced stats charts (#2850) * Add 10 advanced stats charts with new API endpoints and visualizations * Fix chart rendering and visual readability across all new stats charts * Remove 6 charts, fix session archetypes outliers, make book flow half-width * Revert book flow to full width * Remove avg rating from book flow chart, reorder charts, cleanup unused imports --- .../controller/UserStatsController.java | 12 + .../booklore/model/dto/SessionScatterDto.java | 7 + .../dto/response/SessionScatterResponse.java | 16 + .../repository/ReadingSessionRepository.java | 19 +- .../service/ReadingSessionService.java | 28 +- .../series-page/series-page.component.ts | 2 - .../user-management/user-stats.service.ts | 13 + .../book-flow-chart.component.html | 48 +++ .../book-flow-chart.component.scss | 95 ++++++ .../book-flow-chart.component.ts | 300 ++++++++++++++++++ .../publication-era-chart.component.html | 43 +++ .../publication-era-chart.component.scss | 32 ++ .../publication-era-chart.component.ts | 149 +++++++++ .../reading-debt-chart.component.html | 39 +++ .../reading-debt-chart.component.scss | 31 ++ .../reading-debt-chart.component.ts | 162 ++++++++++ .../session-archetypes-chart.component.html | 44 +++ .../session-archetypes-chart.component.scss | 41 +++ .../session-archetypes-chart.component.ts | 160 ++++++++++ .../service/user-chart-config.service.ts | 16 +- .../user-stats/user-stats.component.html | 12 + .../user-stats/user-stats.component.ts | 8 + booklore-ui/src/i18n/en/stats-user.json | 58 +++- booklore-ui/src/i18n/es/stats-user.json | 58 +++- 24 files changed, 1373 insertions(+), 20 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/SessionScatterDto.java create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/response/SessionScatterResponse.java create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.ts create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.ts create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.ts create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.html create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.scss create mode 100644 booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.ts diff --git a/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java b/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java index 0ac1a3fae..30dd3496b 100644 --- a/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java +++ b/booklore-api/src/main/java/org/booklore/controller/UserStatsController.java @@ -171,4 +171,16 @@ public class UserStatsController { List data = readingSessionService.getReadingDates(); return ResponseEntity.ok(data); } + + @Operation(summary = "Get session scatter data", description = "Returns individual session data points for scatter plot visualization") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Session scatter data retrieved successfully"), + @ApiResponse(responseCode = "401", description = "Unauthorized") + }) + @GetMapping("/session-scatter") + @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") + public ResponseEntity> getSessionScatter(@RequestParam int year) { + List data = readingSessionService.getSessionScatter(year); + return ResponseEntity.ok(data); + } } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/SessionScatterDto.java b/booklore-api/src/main/java/org/booklore/model/dto/SessionScatterDto.java new file mode 100644 index 000000000..dfb255e8a --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/SessionScatterDto.java @@ -0,0 +1,7 @@ +package org.booklore.model.dto; + +public interface SessionScatterDto { + Double getHourOfDay(); + Double getDurationMinutes(); + Integer getDayOfWeek(); +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/response/SessionScatterResponse.java b/booklore-api/src/main/java/org/booklore/model/dto/response/SessionScatterResponse.java new file mode 100644 index 000000000..1b4bb6db9 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/response/SessionScatterResponse.java @@ -0,0 +1,16 @@ +package org.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SessionScatterResponse { + private Double hourOfDay; + private Double durationMinutes; + private Integer dayOfWeek; +} diff --git a/booklore-api/src/main/java/org/booklore/repository/ReadingSessionRepository.java b/booklore-api/src/main/java/org/booklore/repository/ReadingSessionRepository.java index bef5c6597..c3b2e46d2 100644 --- a/booklore-api/src/main/java/org/booklore/repository/ReadingSessionRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/ReadingSessionRepository.java @@ -1,8 +1,6 @@ package org.booklore.repository; import org.booklore.model.dto.*; -import org.booklore.model.dto.CompletionRaceSessionDto; -import org.booklore.model.dto.PageTurnerSessionDto; import org.booklore.model.entity.ReadingSessionEntity; import org.springframework.data.domain.Page; @@ -198,4 +196,21 @@ public interface ReadingSessionRepository extends JpaRepository findAllSessionCountsByUser( @Param("userId") Long userId, @Param("tzOffset") String tzOffset); + + @Query(value = """ + SELECT + HOUR(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) + + MINUTE(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) / 60.0 as hourOfDay, + rs.duration_seconds / 60.0 as durationMinutes, + DAYOFWEEK(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) as dayOfWeek + FROM reading_sessions rs + WHERE rs.user_id = :userId + AND YEAR(CONVERT_TZ(rs.start_time, '+00:00', :tzOffset)) = :year + ORDER BY rs.start_time DESC + LIMIT 500 + """, nativeQuery = true) + List findSessionScatterByUserAndYear( + @Param("userId") Long userId, + @Param("year") int year, + @Param("tzOffset") String tzOffset); } diff --git a/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java b/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java index 736815d96..7da92d86d 100644 --- a/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java +++ b/booklore-api/src/main/java/org/booklore/service/ReadingSessionService.java @@ -6,18 +6,7 @@ import org.booklore.model.dto.BookLoreUser; import org.booklore.model.dto.CompletionRaceSessionDto; import org.booklore.model.dto.request.ReadingSessionRequest; import org.booklore.model.dto.PageTurnerSessionDto; -import org.booklore.model.dto.response.BookCompletionHeatmapResponse; -import org.booklore.model.dto.response.CompletionRaceResponse; -import org.booklore.model.dto.response.CompletionTimelineResponse; -import org.booklore.model.dto.response.FavoriteReadingDaysResponse; -import org.booklore.model.dto.response.GenreStatisticsResponse; -import org.booklore.model.dto.response.PageTurnerScoreResponse; -import org.booklore.model.dto.response.PeakReadingHoursResponse; - -import org.booklore.model.dto.response.ReadingSessionHeatmapResponse; -import org.booklore.model.dto.response.ReadingSessionResponse; -import org.booklore.model.dto.response.ReadingSessionTimelineResponse; -import org.booklore.model.dto.response.ReadingSpeedResponse; +import org.booklore.model.dto.response.*; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookLoreUserEntity; import org.booklore.model.entity.CategoryEntity; @@ -429,6 +418,21 @@ public class ReadingSessionService { .collect(Collectors.toList()); } + @Transactional(readOnly = true) + public List getSessionScatter(int year) { + BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); + Long userId = authenticatedUser.getId(); + + return readingSessionRepository.findSessionScatterByUserAndYear(userId, year, getTimezoneOffset()) + .stream() + .map(dto -> SessionScatterResponse.builder() + .hourOfDay(dto.getHourOfDay()) + .durationMinutes(dto.getDurationMinutes()) + .dayOfWeek(dto.getDayOfWeek()) + .build()) + .collect(Collectors.toList()); + } + private double linearRegressionSlope(List values) { int n = values.size(); if (n < 2) return 0.0; diff --git a/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts b/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts index 294351377..29f0580b5 100644 --- a/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts +++ b/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts @@ -10,7 +10,6 @@ import {BookMetadataManageService} from "../../service/book-metadata-manage.serv import {BookCardComponent} from "../book-browser/book-card/book-card.component"; import {CoverScalePreferenceService} from "../book-browser/cover-scale-preference.service"; import {Tab, TabList, TabPanel, TabPanels, Tabs} from "primeng/tabs"; -import {Tag} from "primeng/tag"; import {VirtualScrollerModule} from "@iharbeck/ngx-virtual-scroller"; import {ProgressSpinner} from "primeng/progressspinner"; import {ProgressBar} from "primeng/progressbar"; @@ -84,7 +83,6 @@ interface SeriesStats { Tab, TabPanels, TabPanel, - Tag, VirtualScrollerModule, TieredMenu, Tooltip, 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 30392ca69..04769c19a 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 @@ -70,6 +70,12 @@ export interface CompletionRaceResponse { endProgress: number; } +export interface SessionScatterResponse { + hourOfDay: number; + durationMinutes: number; + dayOfWeek: number; +} + @Injectable({ providedIn: 'root' }) @@ -152,4 +158,11 @@ export class UserStatsService { `${this.readingSessionsUrl}/reading-dates` ); } + + getSessionScatter(year: number): Observable { + return this.http.get( + `${this.readingSessionsUrl}/session-scatter`, + {params: {year: year.toString()}} + ); + } } diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.html b/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.html new file mode 100644 index 000000000..7ae50a6f1 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.html @@ -0,0 +1,48 @@ + +
+
+
+

+ + {{ t('title') }} + +

+

{{ t('description') }}

+
+
+ + @if (hasData) { +
+
+ {{ totalBooks }} + {{ t('totalBooks') }} +
+
+ {{ topQuarter }} + {{ t('busiestQuarter') }} +
+
+ {{ topStatus }} + {{ t('topStatus') }} +
+
+ {{ completionRate }} + {{ t('completionRate') }} +
+
+
+ +
+ } @else { +
+ +

{{ t('noData') }}

+ {{ t('noDataHint') }} +
+ } +
+
diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.scss b/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.scss new file mode 100644 index 000000000..591d60970 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.scss @@ -0,0 +1,95 @@ +.book-flow-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; + } + } +} + +.book-flow-icon { + font-size: 1.5rem; + color: #26c6da; +} + +.stats-row { + display: flex; + gap: 0.75rem; + margin-bottom: 1rem; + flex-wrap: wrap; + + .stat-card { + display: flex; + flex-direction: column; + align-items: center; + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 8px; + padding: 0.5rem 1rem; + flex: 1; + min-width: 80px; + + .stat-value { + font-size: 1.3rem; + font-weight: 600; + color: var(--text-color, #ffffff); + } + .stat-label { + font-size: 0.75rem; + color: var(--text-secondary-color); + text-transform: uppercase; + letter-spacing: 0.5px; + margin-top: 0.25rem; + } + &.total .stat-value { color: #42a5f5; } + &.quarter .stat-value { color: #26c6da; } + &.status .stat-value { color: #66bb6a; } + &.rating .stat-value { color: #ffc107; } + &.completion .stat-value { color: #ab47bc; } + } +} + +.canvas-wrapper { + position: relative; + width: 100%; + height: 500px; + canvas { display: block; } +} + +.no-data-message { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 3rem; + text-align: center; + color: var(--text-secondary-color); + i { font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5; } + p { font-size: 1rem; margin: 0 0 0.5rem 0; color: var(--text-color, #ffffff); } + small { font-size: 0.85rem; opacity: 0.7; } +} + +@media (max-width: 768px) { + .canvas-wrapper { height: 400px; } +} diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.ts b/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.ts new file mode 100644 index 000000000..c40a8d92f --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/book-flow-chart/book-flow-chart.component.ts @@ -0,0 +1,300 @@ +import {Component, ElementRef, inject, OnDestroy, OnInit, ViewChild, AfterViewInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {Tooltip} from 'primeng/tooltip'; +import {Subject} from 'rxjs'; +import {filter, first, takeUntil} from 'rxjs/operators'; +import {BookService} from '../../../../../book/service/book.service'; +import {ReadStatus} from '../../../../../book/model/book.model'; +import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; + +interface SankeyNode { + id: string; + label: string; + column: number; + y: number; + height: number; + color: string; + count: number; +} + +interface SankeyLink { + source: SankeyNode; + target: SankeyNode; + value: number; + color: string; +} + +@Component({ + selector: 'app-book-flow-chart', + standalone: true, + imports: [CommonModule, Tooltip, TranslocoDirective], + templateUrl: './book-flow-chart.component.html', + styleUrls: ['./book-flow-chart.component.scss'] +}) +export class BookFlowChartComponent implements OnInit, OnDestroy, AfterViewInit { + @ViewChild('flowCanvas', {static: false}) canvasRef!: ElementRef; + + private readonly bookService = inject(BookService); + private readonly t = inject(TranslocoService); + private readonly destroy$ = new Subject(); + + public hasData = false; + public totalBooks = 0; + public topQuarter = ''; + public topStatus = ''; + public completionRate = ''; + + private nodes: SankeyNode[] = []; + private links: SankeyLink[] = []; + private canvasReady = false; + private dataReady = false; + + ngOnInit(): void { + this.bookService.bookState$ + .pipe(filter(state => state.loaded), first(), takeUntil(this.destroy$)) + .subscribe(() => { + this.processData(); + this.dataReady = true; + this.tryRender(); + }); + } + + ngAfterViewInit(): void { + this.canvasReady = true; + this.tryRender(); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private tryRender(): void { + if (this.canvasReady && this.dataReady && this.hasData) { + requestAnimationFrame(() => this.draw()); + } + } + + private processData(): void { + const currentState = this.bookService.getCurrentBookState(); + const books = currentState.books; + if (!books || books.length === 0) return; + + const quarterMap = new Map(); + const statusMap = new Map(); + const ratingMap = new Map(); + const quarterToStatus = new Map>(); + const statusToRating = new Map>(); + + const statusColors: Record = { + 'Read': '#66bb6a', 'Reading': '#42a5f5', 'Unread': '#78909c', + 'Paused': '#ffa726', 'Abandoned': '#ef5350', 'Other': '#ab47bc' + }; + + const ratingColors: Record = { + 'Rated 4-5': '#66bb6a', 'Rated 3': '#ffc107', + 'Rated 1-2': '#ef5350', 'Unrated': '#78909c' + }; + + for (const book of books) { + const addedOn = book.addedOn; + let quarter = 'Unknown'; + if (addedOn) { + const date = new Date(addedOn); + const q = Math.ceil((date.getMonth() + 1) / 3); + quarter = `${date.getFullYear()} Q${q}`; + } + + let status = 'Other'; + switch (book.readStatus) { + case ReadStatus.READ: status = 'Read'; break; + case ReadStatus.READING: case ReadStatus.RE_READING: status = 'Reading'; break; + case ReadStatus.UNREAD: case ReadStatus.UNSET: status = 'Unread'; break; + case ReadStatus.PAUSED: status = 'Paused'; break; + case ReadStatus.ABANDONED: case ReadStatus.WONT_READ: status = 'Abandoned'; break; + } + + let ratingBucket = 'Unrated'; + const rating = book.personalRating; + if (rating && rating > 0) { + const normalized = rating / 2; + if (normalized >= 4) ratingBucket = 'Rated 4-5'; + else if (normalized >= 3) ratingBucket = 'Rated 3'; + else ratingBucket = 'Rated 1-2'; + } + + quarterMap.set(quarter, (quarterMap.get(quarter) || 0) + 1); + statusMap.set(status, (statusMap.get(status) || 0) + 1); + ratingMap.set(ratingBucket, (ratingMap.get(ratingBucket) || 0) + 1); + + if (!quarterToStatus.has(quarter)) quarterToStatus.set(quarter, new Map()); + const qsMap = quarterToStatus.get(quarter)!; + qsMap.set(status, (qsMap.get(status) || 0) + 1); + + if (!statusToRating.has(status)) statusToRating.set(status, new Map()); + const srMap = statusToRating.get(status)!; + srMap.set(ratingBucket, (srMap.get(ratingBucket) || 0) + 1); + } + + if (quarterMap.size === 0) return; + this.hasData = true; + this.totalBooks = books.length; + + const sortedQuarters = [...quarterMap.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, 8); + + this.topQuarter = sortedQuarters[0]?.[0] || ''; + const topStatusEntry = [...statusMap.entries()].sort((a, b) => b[1] - a[1])[0]; + this.topStatus = topStatusEntry?.[0] || ''; + + const readCount = statusMap.get('Read') || 0; + this.completionRate = books.length > 0 ? Math.round((readCount / books.length) * 100) + '%' : '0%'; + + const quarterColors = ['#42a5f5', '#26c6da', '#66bb6a', '#ffa726', '#ab47bc', '#ef5350', '#ec407a', '#7e57c2']; + + const totalHeight = 420; + const padding = 6; + + const createColumnNodes = ( + entries: [string, number][], + column: number, + colors: Record | string[] + ): SankeyNode[] => { + const total = entries.reduce((s, e) => s + e[1], 0); + let currentY = 30; + return entries.map(([id, count], i) => { + const height = Math.max(10, (count / total) * (totalHeight - entries.length * padding)); + const node: SankeyNode = { + id, label: id, column, + y: currentY, height, + color: Array.isArray(colors) ? colors[i % colors.length] : (colors[id] || '#78909c'), + count + }; + currentY += height + padding; + return node; + }); + }; + + const quarterNodes = createColumnNodes(sortedQuarters, 0, quarterColors); + const statusEntries = [...statusMap.entries()].sort((a, b) => b[1] - a[1]); + const statusNodes = createColumnNodes(statusEntries, 1, statusColors); + const ratingEntries = [...ratingMap.entries()].sort((a, b) => b[1] - a[1]); + const ratingNodes = createColumnNodes(ratingEntries, 2, ratingColors); + + this.nodes = [...quarterNodes, ...statusNodes, ...ratingNodes]; + this.links = []; + + const findNode = (id: string, col: number) => this.nodes.find(n => n.id === id && n.column === col); + + for (const [quarter, statusCounts] of quarterToStatus) { + const qNode = findNode(quarter, 0); + if (!qNode) continue; + for (const [status, count] of statusCounts) { + const sNode = findNode(status, 1); + if (sNode) { + this.links.push({source: qNode, target: sNode, value: count, color: qNode.color}); + } + } + } + + for (const [status, ratingCounts] of statusToRating) { + const sNode = findNode(status, 1); + if (!sNode) continue; + for (const [rating, count] of ratingCounts) { + const rNode = findNode(rating, 2); + if (rNode) { + this.links.push({source: sNode, target: rNode, value: count, color: sNode.color}); + } + } + } + } + + private draw(): void { + const canvas = this.canvasRef?.nativeElement; + if (!canvas) return; + const ctx = canvas.getContext('2d'); + if (!ctx) return; + + const rect = canvas.parentElement!.getBoundingClientRect(); + const dpr = window.devicePixelRatio || 1; + canvas.width = rect.width * dpr; + canvas.height = 480 * dpr; + canvas.style.width = rect.width + 'px'; + canvas.style.height = '480px'; + ctx.scale(dpr, dpr); + + const width = rect.width; + const nodeWidth = 18; + const leftMargin = 100; + const rightMargin = 110; + const colX = [leftMargin, width * 0.45, width - rightMargin]; + + ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'; + ctx.font = '11px Inter, sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(this.t.translate('statsUser.bookFlow.colAdded'), colX[0] + nodeWidth / 2, 18); + ctx.fillText(this.t.translate('statsUser.bookFlow.colStatus'), colX[1] + nodeWidth / 2, 18); + ctx.fillText(this.t.translate('statsUser.bookFlow.colRating'), colX[2] + nodeWidth / 2, 18); + + const sourceOffsets = new Map(); + const targetOffsets = new Map(); + + for (const link of this.links) { + const sKey = `${link.source.id}-${link.source.column}`; + const tKey = `${link.target.id}-${link.target.column}`; + const sOff = sourceOffsets.get(sKey) || 0; + const tOff = targetOffsets.get(tKey) || 0; + + const linkHeight = Math.max(1, (link.value / link.source.count) * link.source.height); + const tLinkHeight = Math.max(1, (link.value / link.target.count) * link.target.height); + + const x0 = colX[link.source.column] + nodeWidth; + const y0 = link.source.y + sOff + linkHeight / 2; + const x1 = colX[link.target.column]; + const y1 = link.target.y + tOff + tLinkHeight / 2; + + ctx.beginPath(); + ctx.moveTo(x0, y0 - linkHeight / 2); + const cpx = (x0 + x1) / 2; + ctx.bezierCurveTo(cpx, y0 - linkHeight / 2, cpx, y1 - tLinkHeight / 2, x1, y1 - tLinkHeight / 2); + ctx.lineTo(x1, y1 + tLinkHeight / 2); + ctx.bezierCurveTo(cpx, y1 + tLinkHeight / 2, cpx, y0 + linkHeight / 2, x0, y0 + linkHeight / 2); + ctx.closePath(); + + ctx.fillStyle = link.color + '55'; + ctx.fill(); + ctx.strokeStyle = link.color + '30'; + ctx.lineWidth = 0.5; + ctx.stroke(); + + sourceOffsets.set(sKey, sOff + linkHeight); + targetOffsets.set(tKey, tOff + tLinkHeight); + } + + for (const node of this.nodes) { + const x = colX[node.column]; + + ctx.fillStyle = node.color; + ctx.globalAlpha = 0.92; + ctx.beginPath(); + ctx.roundRect(x, node.y, nodeWidth, node.height, 3); + ctx.fill(); + ctx.globalAlpha = 1; + + ctx.strokeStyle = 'rgba(255, 255, 255, 0.15)'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.roundRect(x, node.y, nodeWidth, node.height, 3); + ctx.stroke(); + + ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'; + ctx.font = '11px Inter, sans-serif'; + const labelX = node.column === 2 ? x + nodeWidth + 8 : x - 8; + ctx.textAlign = node.column === 2 ? 'left' : 'right'; + ctx.textBaseline = 'middle'; + const label = node.label.length > 18 ? node.label.substring(0, 16) + '..' : node.label; + ctx.fillText(`${label} (${node.count})`, labelX, node.y + node.height / 2); + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.html b/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.html new file mode 100644 index 000000000..4e779e032 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.html @@ -0,0 +1,43 @@ + +
+
+
+

+ + {{ t('title') }} + +

+

{{ t('description') }}

+
+
+ @if (hasData) { +
+
+ {{ bestDecade }} + {{ t('bestDecade') }} +
+
+ {{ bestAvgRating }}/10 + {{ t('avgRating') }} +
+
+ {{ totalRated }} + {{ t('booksRated') }} +
+
+
+ +
+ } @else { +
+ +

{{ t('noData') }}

+ {{ t('noDataHint') }} +
+ } +
+
diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.scss b/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.scss new file mode 100644 index 000000000..738e0ae89 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.scss @@ -0,0 +1,32 @@ +.publication-era-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; } + } +} +.publication-era-icon { font-size: 1.5rem; color: #673ab7; } +.stats-row { + display: flex; gap: 0.75rem; margin-bottom: 1rem; flex-wrap: wrap; + .stat-card { + display: flex; flex-direction: column; align-items: center; + background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 8px; padding: 0.5rem 1rem; flex: 1; min-width: 80px; + .stat-value { font-size: 1.5rem; font-weight: 600; color: var(--text-color, #ffffff); } + .stat-label { font-size: 0.75rem; color: var(--text-secondary-color); text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.25rem; } + &.best .stat-value { color: #673ab7; } + &.avg .stat-value { color: #ffc107; } + &.total .stat-value { color: #42a5f5; } + } +} +.chart-wrapper { position: relative; height: 350px; width: 100%; } +.no-data-message { + display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 3rem; text-align: center; color: var(--text-secondary-color); + i { font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5; } + p { font-size: 1rem; margin: 0 0 0.5rem 0; color: var(--text-color, #ffffff); } + small { font-size: 0.85rem; opacity: 0.7; } +} +@media (max-width: 768px) { .chart-wrapper { height: 280px; } } +@media (max-width: 480px) { .chart-header .chart-title h3 { font-size: 1rem; } } diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.ts b/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.ts new file mode 100644 index 000000000..b7489033b --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/publication-era-chart/publication-era-chart.component.ts @@ -0,0 +1,149 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {Tooltip} from 'primeng/tooltip'; +import {EMPTY, Subject} from 'rxjs'; +import {catchError, filter, first, takeUntil} from 'rxjs/operators'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BookService} from '../../../../../book/service/book.service'; +import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; + +@Component({ + selector: 'app-publication-era-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective], + templateUrl: './publication-era-chart.component.html', + styleUrls: ['./publication-era-chart.component.scss'] +}) +export class PublicationEraChartComponent implements OnInit, OnDestroy { + private readonly bookService = inject(BookService); + private readonly t = inject(TranslocoService); + private readonly destroy$ = new Subject(); + + public readonly chartType = 'line' as const; + public hasData = false; + public bestDecade = ''; + public bestAvgRating = 0; + public totalRated = 0; + + private readonly DECADE_COLORS = [ + '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', + '#2196f3', '#00bcd4', '#009688', '#4caf50', + '#8bc34a', '#ff9800' + ]; + + public chartData: ChartData<'line', number[], string> = {labels: [], datasets: []}; + + public readonly chartOptions: ChartConfiguration<'line'>['options'] = { + responsive: true, + maintainAspectRatio: false, + animation: {duration: 400}, + layout: {padding: {top: 10, right: 10}}, + plugins: { + legend: { + display: true, position: 'bottom', + labels: {color: 'rgba(255, 255, 255, 0.8)', font: {family: "'Inter', sans-serif", size: 11}, boxWidth: 12, padding: 12} + }, + tooltip: { + enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', bodyColor: '#ffffff', + borderColor: '#ffffff', borderWidth: 1, cornerRadius: 6, padding: 10, + callbacks: { + label: (ctx) => { + return `${ctx.dataset.label}: ${ctx.parsed.y} books`; + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + grid: {color: 'rgba(255, 255, 255, 0.08)'}, + ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}}, + title: {display: true, text: 'Rating Range', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}} + }, + y: { + beginAtZero: true, + grid: {color: 'rgba(255, 255, 255, 0.08)'}, + ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}, stepSize: 1}, + title: {display: true, text: 'Books', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}} + } + }, + interaction: {mode: 'index', intersect: false} + }; + + ngOnInit(): void { + this.bookService.bookState$ + .pipe(filter(state => state.loaded), first(), catchError(() => EMPTY), takeUntil(this.destroy$)) + .subscribe(() => this.processData()); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private processData(): void { + const state = this.bookService.getCurrentBookState(); + const books = state.books; + if (!books || books.length === 0) return; + + const ratedBooks = books.filter(b => b.metadata?.publishedDate && b.personalRating && b.personalRating > 0); + if (ratedBooks.length < 3) return; + + this.totalRated = ratedBooks.length; + + const decadeData = new Map>(); + const decadeAvg = new Map(); + const ratingLabels = ['1-2', '3-4', '5-6', '7-8', '9-10']; + + for (const book of ratedBooks) { + const pubYear = new Date(book.metadata!.publishedDate!).getFullYear(); + if (pubYear < 1900 || pubYear > 2030) continue; + const decade = `${Math.floor(pubYear / 10) * 10}s`; + const rating = book.personalRating!; + const bucket = Math.min(4, Math.floor((rating - 1) / 2)); + + if (!decadeData.has(decade)) decadeData.set(decade, new Map()); + const dMap = decadeData.get(decade)!; + dMap.set(bucket, (dMap.get(bucket) || 0) + 1); + + if (!decadeAvg.has(decade)) decadeAvg.set(decade, {total: 0, count: 0}); + const avg = decadeAvg.get(decade)!; + avg.total += rating; + avg.count++; + } + + if (decadeData.size === 0) return; + + const decades = [...decadeData.keys()].sort(); + let bestDec = ''; + let bestAvg = 0; + for (const [dec, avg] of decadeAvg) { + const a = avg.total / avg.count; + if (a > bestAvg) { bestAvg = a; bestDec = dec; } + } + this.bestDecade = bestDec; + this.bestAvgRating = Math.round(bestAvg * 10) / 10; + + const datasets = decades.map((decade, i) => { + const dMap = decadeData.get(decade)!; + return { + label: decade, + data: ratingLabels.map((_, idx) => dMap.get(idx) || 0), + borderColor: this.DECADE_COLORS[i % this.DECADE_COLORS.length], + backgroundColor: this.DECADE_COLORS[i % this.DECADE_COLORS.length] + '20', + borderWidth: 2.5, + pointRadius: 5, + pointBackgroundColor: this.DECADE_COLORS[i % this.DECADE_COLORS.length], + pointBorderColor: '#ffffff', + pointBorderWidth: 1.5, + tension: 0.3, + fill: false + }; + }); + + this.chartData = {labels: ratingLabels, datasets}; + this.hasData = true; + } +} diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.html b/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.html new file mode 100644 index 000000000..83cf3b76c --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.html @@ -0,0 +1,39 @@ + +
+
+
+

+ + {{ t('title') }} + +

+

{{ t('description') }}

+
+
+ @if (hasData) { +
+
+ {{ currentBacklog }} + {{ t('currentBacklog') }} +
+
+ {{ trend }} + {{ t('trendLabel') }} +
+
+
+ +
+ } @else { +
+ +

{{ t('noData') }}

+ {{ t('noDataHint') }} +
+ } +
+
diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.scss b/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.scss new file mode 100644 index 000000000..91cff272f --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.scss @@ -0,0 +1,31 @@ +.reading-debt-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-debt-icon { font-size: 1.5rem; color: #ef5350; } +.stats-row { + display: flex; gap: 0.75rem; margin-bottom: 1rem; flex-wrap: wrap; + .stat-card { + display: flex; flex-direction: column; align-items: center; + background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 8px; padding: 0.5rem 1rem; flex: 1; min-width: 80px; + .stat-value { font-size: 1.5rem; font-weight: 600; color: var(--text-color, #ffffff); } + .stat-label { font-size: 0.75rem; color: var(--text-secondary-color); text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.25rem; } + &.backlog .stat-value { color: #ffc107; } + &.trend .stat-value { color: #42a5f5; } + } +} +.chart-wrapper { position: relative; height: 350px; width: 100%; } +.no-data-message { + display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 3rem; text-align: center; color: var(--text-secondary-color); + i { font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5; } + p { font-size: 1rem; margin: 0 0 0.5rem 0; color: var(--text-color, #ffffff); } + small { font-size: 0.85rem; opacity: 0.7; } +} +@media (max-width: 768px) { .chart-wrapper { height: 280px; } } +@media (max-width: 480px) { .chart-header .chart-title h3 { font-size: 1rem; } } diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.ts b/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.ts new file mode 100644 index 000000000..4b09b6663 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/reading-debt-chart/reading-debt-chart.component.ts @@ -0,0 +1,162 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {Tooltip} from 'primeng/tooltip'; +import {EMPTY, Subject} from 'rxjs'; +import {catchError, filter, first, takeUntil} from 'rxjs/operators'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BookService} from '../../../../../book/service/book.service'; +import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; + +@Component({ + selector: 'app-reading-debt-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective], + templateUrl: './reading-debt-chart.component.html', + styleUrls: ['./reading-debt-chart.component.scss'] +}) +export class ReadingDebtChartComponent implements OnInit, OnDestroy { + private readonly bookService = inject(BookService); + private readonly t = inject(TranslocoService); + private readonly destroy$ = new Subject(); + + public readonly chartType = 'bar' as const; + public hasData = false; + public currentBacklog = 0; + public trend = ''; + + public chartData: ChartData<'bar', number[], string> = {labels: [], datasets: []}; + + public chartOptions: ChartConfiguration<'bar'>['options'] = { + responsive: true, + maintainAspectRatio: false, + animation: {duration: 400}, + layout: {padding: {top: 10}}, + plugins: { + legend: { + display: true, position: 'bottom', + labels: {color: 'rgba(255, 255, 255, 0.8)', font: {family: "'Inter', sans-serif", size: 11}, boxWidth: 12, padding: 15} + }, + tooltip: { + enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', bodyColor: '#ffffff', borderColor: '#ffffff', + borderWidth: 1, cornerRadius: 6, padding: 10 + }, + datalabels: {display: false} + }, + scales: { + x: { + grid: {color: 'rgba(255, 255, 255, 0.08)'}, + ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 10}} + }, + y: { + grid: {color: 'rgba(255, 255, 255, 0.08)'}, + ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}} + }, + y1: { + position: 'right', + grid: {drawOnChartArea: false}, + ticks: {color: 'rgba(255, 193, 7, 0.8)', font: {size: 11}} + } + } + }; + + ngOnInit(): void { + this.bookService.bookState$ + .pipe(filter(state => state.loaded), first(), catchError(() => EMPTY), takeUntil(this.destroy$)) + .subscribe(() => this.processData()); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private processData(): void { + const state = this.bookService.getCurrentBookState(); + const books = state.books; + if (!books || books.length === 0) return; + + const now = new Date(); + const monthlyAdded = new Map(); + const monthlyFinished = new Map(); + const months: string[] = []; + const monthLabels: string[] = []; + const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; + + for (let i = 11; i >= 0; i--) { + const d = new Date(now.getFullYear(), now.getMonth() - i, 1); + const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; + months.push(key); + monthLabels.push(`${monthNames[d.getMonth()]} ${String(d.getFullYear()).slice(2)}`); + monthlyAdded.set(key, 0); + monthlyFinished.set(key, 0); + } + + for (const book of books) { + if (book.addedOn) { + const d = new Date(book.addedOn); + const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; + if (monthlyAdded.has(key)) monthlyAdded.set(key, monthlyAdded.get(key)! + 1); + } + if (book.dateFinished) { + const d = new Date(book.dateFinished); + const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; + if (monthlyFinished.has(key)) monthlyFinished.set(key, monthlyFinished.get(key)! + 1); + } + } + + const added = months.map(m => monthlyAdded.get(m) || 0); + const finished = months.map(m => monthlyFinished.get(m) || 0); + + if (added.every(v => v === 0) && finished.every(v => v === 0)) return; + + const backlog: number[] = []; + let running = 0; + for (let i = 0; i < months.length; i++) { + running += added[i] - finished[i]; + backlog.push(running); + } + this.currentBacklog = running; + this.trend = running > (backlog[0] || 0) ? this.t.translate('statsUser.readingDebt.growing') : this.t.translate('statsUser.readingDebt.shrinking'); + + this.chartData = { + labels: monthLabels, + datasets: [ + { + label: this.t.translate('statsUser.readingDebt.booksAdded'), + data: added, + backgroundColor: 'rgba(239, 83, 80, 0.7)', + borderColor: '#ef5350', + borderWidth: 1, + borderRadius: 4, + order: 2 + }, + { + label: this.t.translate('statsUser.readingDebt.booksFinished'), + data: finished, + backgroundColor: 'rgba(102, 187, 106, 0.7)', + borderColor: '#66bb6a', + borderWidth: 1, + borderRadius: 4, + order: 2 + }, + { + label: this.t.translate('statsUser.readingDebt.backlog'), + data: backlog, + type: 'line' as const, + borderColor: '#ffc107', + backgroundColor: 'rgba(255, 193, 7, 0.1)', + borderWidth: 2, + pointRadius: 3, + pointBackgroundColor: '#ffc107', + fill: false, + tension: 0.3, + yAxisID: 'y1', + order: 1 + } as any + ] + }; + this.hasData = true; + } +} diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.html b/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.html new file mode 100644 index 000000000..5ae568903 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.html @@ -0,0 +1,44 @@ + +
+
+
+

+ + {{ t('title') }} + +

+

{{ t('description') }}

+
+
+ + {{ currentYear }} + +
+
+ @if (hasData) { +
+
+ {{ sessionCount }} + {{ t('sessions') }} +
+
+ {{ dominantArchetype }} + {{ t('dominantType') }} +
+
+
+ +
+ } @else { +
+ +

{{ t('noData') }}

+ {{ t('noDataHint') }} +
+ } +
+
diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.scss b/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.scss new file mode 100644 index 000000000..53e32e04f --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.scss @@ -0,0 +1,41 @@ +.session-archetypes-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; } + } + .year-nav { + display: flex; align-items: center; gap: 0.5rem; + .nav-btn { + background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 6px; color: var(--text-color, #ffffff); padding: 0.3rem 0.5rem; + cursor: pointer; transition: background 0.2s; + &:hover { background: rgba(255, 255, 255, 0.2); } + } + .year-label { color: var(--text-color, #ffffff); font-weight: 600; font-size: 1.1rem; min-width: 50px; text-align: center; } + } +} +.session-archetypes-icon { font-size: 1.5rem; color: #ff9800; } +.stats-row { + display: flex; gap: 0.75rem; margin-bottom: 1rem; flex-wrap: wrap; + .stat-card { + display: flex; flex-direction: column; align-items: center; + background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 8px; padding: 0.5rem 1rem; flex: 1; min-width: 80px; + .stat-value { font-size: 1.5rem; font-weight: 600; color: var(--text-color, #ffffff); } + .stat-label { font-size: 0.75rem; color: var(--text-secondary-color); text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.25rem; } + &.sessions .stat-value { color: #ff9800; } + &.archetype .stat-value { color: #42a5f5; font-size: 1.1rem; } + } +} +.chart-wrapper { position: relative; height: 350px; width: 100%; } +.no-data-message { + display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 3rem; text-align: center; color: var(--text-secondary-color); + i { font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5; } + p { font-size: 1rem; margin: 0 0 0.5rem 0; color: var(--text-color, #ffffff); } + small { font-size: 0.85rem; opacity: 0.7; } +} +@media (max-width: 768px) { .chart-wrapper { height: 280px; } } +@media (max-width: 480px) { .chart-header .chart-title h3 { font-size: 1rem; } } diff --git a/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.ts b/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.ts new file mode 100644 index 000000000..3e1f3166d --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/user-stats/charts/session-archetypes-chart/session-archetypes-chart.component.ts @@ -0,0 +1,160 @@ +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {Tooltip} from 'primeng/tooltip'; +import {EMPTY, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {UserStatsService, SessionScatterResponse} from '../../../../../settings/user-management/user-stats.service'; +import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; + +const DAY_COLORS = [ + '#ef5350', '#ff9800', '#ffc107', '#66bb6a', '#42a5f5', '#7e57c2', '#ec407a' +]; +const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + +@Component({ + selector: 'app-session-archetypes-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective, Tooltip, TranslocoDirective], + templateUrl: './session-archetypes-chart.component.html', + styleUrls: ['./session-archetypes-chart.component.scss'] +}) +export class SessionArchetypesChartComponent implements OnInit, OnDestroy { + @Input() initialYear = new Date().getFullYear(); + + private readonly userStatsService = inject(UserStatsService); + private readonly t = inject(TranslocoService); + private readonly destroy$ = new Subject(); + + public readonly chartType = 'scatter' as const; + public currentYear: number = new Date().getFullYear(); + public hasData = false; + public sessionCount = 0; + public dominantArchetype = ''; + + public chartData: ChartData<'scatter', {x: number; y: number}[], string> = {labels: [], datasets: []}; + + public readonly chartOptions: ChartConfiguration<'scatter'>['options'] = { + responsive: true, + maintainAspectRatio: false, + animation: {duration: 400}, + layout: {padding: {top: 10, right: 20}}, + plugins: { + legend: { + display: true, position: 'bottom', + labels: {color: 'rgba(255, 255, 255, 0.8)', font: {family: "'Inter', sans-serif", size: 11}, boxWidth: 10, padding: 12} + }, + tooltip: { + enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', bodyColor: '#ffffff', + cornerRadius: 6, padding: 10, + callbacks: { + label: (ctx) => { + const hour = ctx.parsed.x ?? 0; + const h = Math.floor(hour); + const m = Math.round((hour - h) * 60); + const duration = Math.round(ctx.parsed.y ?? 0); + return `${ctx.dataset.label}: ${h}:${String(m).padStart(2, '0')} - ${duration} min`; + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + min: 0, max: 24, + grid: {color: 'rgba(255, 255, 255, 0.08)'}, + ticks: { + color: 'rgba(255, 255, 255, 0.6)', font: {size: 10}, stepSize: 3, + callback: (val) => { + const h = Number(val); + if (h === 0) return '12am'; + if (h === 12) return '12pm'; + return h < 12 ? `${h}am` : `${h - 12}pm`; + } + }, + title: {display: true, text: 'Time of Day', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}} + }, + y: { + min: 0, + grid: {color: 'rgba(255, 255, 255, 0.08)'}, + ticks: {color: 'rgba(255, 255, 255, 0.6)', font: {size: 11}}, + title: {display: true, text: 'Duration (min)', color: 'rgba(255, 255, 255, 0.5)', font: {size: 11}} + } + } + }; + + ngOnInit(): void { + this.currentYear = this.initialYear; + this.loadData(this.currentYear); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + changeYear(delta: number): void { + this.currentYear += delta; + this.loadData(this.currentYear); + } + + private loadData(year: number): void { + this.userStatsService.getSessionScatter(year) + .pipe(takeUntil(this.destroy$), catchError(() => EMPTY)) + .subscribe(data => this.processData(data)); + } + + private processData(data: SessionScatterResponse[]): void { + if (!data || data.length === 0) { + this.hasData = false; + this.chartData = {labels: [], datasets: []}; + return; + } + + const durations = data.map(s => s.durationMinutes).sort((a, b) => a - b); + const q1 = durations[Math.floor(durations.length * 0.25)]; + const q3 = durations[Math.floor(durations.length * 0.75)]; + const iqr = q3 - q1; + const upperFence = q3 + 1.5 * iqr; + const filtered = data.filter(s => s.durationMinutes <= upperFence); + + this.sessionCount = filtered.length; + + const byDay = new Map(); + for (let d = 1; d <= 7; d++) byDay.set(d, []); + + const quadrants = {morning: 0, afternoon: 0, evening: 0, night: 0}; + + for (const s of filtered) { + const points = byDay.get(s.dayOfWeek) || []; + points.push({x: s.hourOfDay, y: s.durationMinutes}); + byDay.set(s.dayOfWeek, points); + + if (s.hourOfDay >= 5 && s.hourOfDay < 12) quadrants.morning++; + else if (s.hourOfDay >= 12 && s.hourOfDay < 17) quadrants.afternoon++; + else if (s.hourOfDay >= 17 && s.hourOfDay < 22) quadrants.evening++; + else quadrants.night++; + } + + const maxQ = Object.entries(quadrants).sort((a, b) => b[1] - a[1])[0]; + this.dominantArchetype = this.t.translate(`statsUser.sessionArchetypes.archetype_${maxQ[0]}`); + + const datasets = DAY_NAMES.map((name, i) => { + const dayNum = i + 1; + return { + label: name, + data: byDay.get(dayNum) || [], + backgroundColor: DAY_COLORS[i] + 'AA', + borderColor: DAY_COLORS[i], + borderWidth: 1, + pointRadius: 5, + pointHoverRadius: 8 + }; + }).filter(ds => ds.data.length > 0); + + this.chartData = {datasets}; + this.hasData = true; + } +} diff --git a/booklore-ui/src/app/features/stats/component/user-stats/service/user-chart-config.service.ts b/booklore-ui/src/app/features/stats/component/user-stats/service/user-chart-config.service.ts index 5474a5941..02ca88196 100644 --- a/booklore-ui/src/app/features/stats/component/user-stats/service/user-chart-config.service.ts +++ b/booklore-ui/src/app/features/stats/component/user-stats/service/user-chart-config.service.ts @@ -20,6 +20,10 @@ import {CompletionRaceChartComponent} from '../charts/completion-race-chart/comp import {ReadingSurvivalChartComponent} from '../charts/reading-survival-chart/reading-survival-chart.component'; import {ReadingClockChartComponent} from '../charts/reading-clock-chart/reading-clock-chart.component'; import {BookLengthChartComponent} from '../charts/book-length-chart/book-length-chart.component'; +import {BookFlowChartComponent} from '../charts/book-flow-chart/book-flow-chart.component'; +import {ReadingDebtChartComponent} from '../charts/reading-debt-chart/reading-debt-chart.component'; +import {PublicationEraChartComponent} from '../charts/publication-era-chart/publication-era-chart.component'; +import {SessionArchetypesChartComponent} from '../charts/session-archetypes-chart/session-archetypes-chart.component'; export interface UserChartConfig { id: string; @@ -57,6 +61,10 @@ export class UserChartConfigService { 'series-progress': 'statsUser.chartNames.seriesProgress', 'reading-dna': 'statsUser.chartNames.readingDna', 'reading-habits': 'statsUser.chartNames.readingHabits', + 'book-flow': 'statsUser.chartNames.bookFlow', + 'reading-debt': 'statsUser.chartNames.readingDebt', + 'publication-era': 'statsUser.chartNames.publicationEra', + 'session-archetypes': 'statsUser.chartNames.sessionArchetypes', }; private readonly defaultCharts: UserChartConfig[] = [ @@ -77,8 +85,12 @@ export class UserChartConfigService { {id: 'book-length', title: 'Book Length Sweet Spot', component: BookLengthChartComponent, enabled: true, sizeClass: 'chart-medium', order: 14}, {id: 'rating-taste', title: 'Rating Taste Comparison', component: RatingTasteChartComponent, enabled: true, sizeClass: 'chart-medium', order: 15}, {id: 'series-progress', title: 'Series Progress Tracker', component: SeriesProgressChartComponent, enabled: true, sizeClass: 'chart-medium', order: 16}, - {id: 'reading-dna', title: 'Reading DNA Profile', component: ReadingDNAChartComponent, enabled: true, sizeClass: 'chart-medium', order: 17}, - {id: 'reading-habits', title: 'Reading Habits Analysis', component: ReadingHabitsChartComponent, enabled: true, sizeClass: 'chart-medium', order: 18}, + {id: 'reading-debt', title: 'Reading Debt Waterfall', component: ReadingDebtChartComponent, enabled: true, sizeClass: 'chart-medium', order: 17}, + {id: 'publication-era', title: 'Publication Era vs Rating', component: PublicationEraChartComponent, enabled: true, sizeClass: 'chart-medium', order: 18}, + {id: 'session-archetypes', title: 'Session Archetypes', component: SessionArchetypesChartComponent, enabled: true, sizeClass: 'chart-medium', order: 19}, + {id: 'book-flow', title: 'Book Flow', component: BookFlowChartComponent, enabled: true, sizeClass: 'chart-medium', order: 20}, + {id: 'reading-habits', title: 'Reading Habits Analysis', component: ReadingHabitsChartComponent, enabled: true, sizeClass: 'chart-medium', order: 21}, + {id: 'reading-dna', title: 'Reading DNA Profile', component: ReadingDNAChartComponent, enabled: true, sizeClass: 'chart-medium', order: 22} ]; private chartsSubject = new BehaviorSubject(this.loadChartConfig()); 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 003697d89..4d2434f77 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 @@ -126,6 +126,18 @@ @case ('book-length') { } + @case ('book-flow') { + + } + @case ('reading-debt') { + + } + @case ('publication-era') { + + } + @case ('session-archetypes') { + + } } } 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 5667dac5c..d349b5243 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 @@ -26,6 +26,10 @@ import {CompletionRaceChartComponent} from './charts/completion-race-chart/compl import {ReadingSurvivalChartComponent} from './charts/reading-survival-chart/reading-survival-chart.component'; import {ReadingClockChartComponent} from './charts/reading-clock-chart/reading-clock-chart.component'; import {BookLengthChartComponent} from './charts/book-length-chart/book-length-chart.component'; +import {BookFlowChartComponent} from './charts/book-flow-chart/book-flow-chart.component'; +import {ReadingDebtChartComponent} from './charts/reading-debt-chart/reading-debt-chart.component'; +import {PublicationEraChartComponent} from './charts/publication-era-chart/publication-era-chart.component'; +import {SessionArchetypesChartComponent} from './charts/session-archetypes-chart/session-archetypes-chart.component'; import {UserChartConfig, UserChartConfigService} from './service/user-chart-config.service'; @Component({ @@ -55,6 +59,10 @@ import {UserChartConfig, UserChartConfigService} from './service/user-chart-conf ReadingSurvivalChartComponent, ReadingClockChartComponent, BookLengthChartComponent, + BookFlowChartComponent, + ReadingDebtChartComponent, + PublicationEraChartComponent, + SessionArchetypesChartComponent, TranslocoDirective ], templateUrl: './user-stats.component.html', diff --git a/booklore-ui/src/i18n/en/stats-user.json b/booklore-ui/src/i18n/en/stats-user.json index 4c50b0cdb..eefceb687 100644 --- a/booklore-ui/src/i18n/en/stats-user.json +++ b/booklore-ui/src/i18n/en/stats-user.json @@ -27,7 +27,11 @@ "ratingTaste": "Rating Taste Comparison", "seriesProgress": "Series Progress Tracker", "readingDna": "Reading DNA Profile", - "readingHabits": "Reading Habits Analysis" + "readingHabits": "Reading Habits Analysis", + "bookFlow": "Book Flow", + "readingDebt": "Reading Debt Waterfall", + "publicationEra": "Publication Era vs Rating", + "sessionArchetypes": "Session Archetypes" }, "sessionHeatmap": { "title": "Reading Session Activity", @@ -470,5 +474,57 @@ "statusAbandoned": "Abandoned", "statusOther": "Other", "trend": "Trend" + }, + "bookFlow": { + "title": "Book Flow", + "tooltip": "An alluvial diagram showing how books flow from when they were added (left) through their reading status (middle) to their rating bucket (right). Follow the streams to see patterns in how your acquisitions turn into reads and ratings.", + "description": "How books flow from acquisition to status to rating", + "totalBooks": "Total Books", + "busiestQuarter": "Busiest Quarter", + "topStatus": "Top Status", + "avgRating": "Avg Rating", + "completionRate": "Completion", + "colAdded": "Added", + "colStatus": "Status", + "colRating": "Rating", + "noData": "No books found in your library.", + "noDataHint": "Add some books to see the flow diagram." + }, + "readingDebt": { + "title": "Reading Debt Waterfall", + "tooltip": "Each month shows books added (red) and books finished (green) over the last 12 months. The yellow line tracks your running backlog, which is the cumulative difference between added and finished. A rising line means your to-read pile is growing.", + "description": "Monthly books added vs finished with running backlog", + "booksAdded": "Books Added", + "booksFinished": "Books Finished", + "backlog": "Backlog", + "currentBacklog": "Current Backlog", + "trendLabel": "Trend", + "growing": "Growing", + "shrinking": "Shrinking", + "noData": "No book activity data found.", + "noDataHint": "Add and finish books to see your reading debt trend." + }, + "publicationEra": { + "title": "Publication Era vs Rating", + "tooltip": "Each line represents a decade of publication, showing how many books from that era you gave each rating range. Compare lines to see which decades you rate highest. Helps reveal whether you prefer classic or contemporary works.", + "description": "Which publication decades do you rate highest", + "bestDecade": "Best Decade", + "avgRating": "Avg Rating", + "booksRated": "Books Rated", + "noData": "Not enough rated books with publication dates.", + "noDataHint": "Rate books that have publication date metadata to see era comparisons." + }, + "sessionArchetypes": { + "title": "Session Archetypes", + "tooltip": "Each dot is a reading session plotted by time of day (X) and duration in minutes (Y), colored by day of week. Natural clusters reveal your reading patterns, like morning quick reads or evening deep dives.", + "description": "Your reading session patterns by time and duration", + "sessions": "Sessions", + "dominantType": "Dominant Type", + "archetype_morning": "Morning Reader", + "archetype_afternoon": "Afternoon Reader", + "archetype_evening": "Evening Reader", + "archetype_night": "Night Owl", + "noData": "No reading sessions found for this year.", + "noDataHint": "Track reading sessions to discover your session archetypes." } } diff --git a/booklore-ui/src/i18n/es/stats-user.json b/booklore-ui/src/i18n/es/stats-user.json index 9aca19edb..f4fd9b46a 100644 --- a/booklore-ui/src/i18n/es/stats-user.json +++ b/booklore-ui/src/i18n/es/stats-user.json @@ -27,7 +27,11 @@ "ratingTaste": "Comparacion de gusto en calificaciones", "seriesProgress": "Seguimiento de progreso de series", "readingDna": "Perfil de ADN lector", - "readingHabits": "Analisis de habitos de lectura" + "readingHabits": "Analisis de habitos de lectura", + "bookFlow": "Flujo de libros", + "readingDebt": "Deuda de lectura", + "publicationEra": "Era de publicacion vs calificacion", + "sessionArchetypes": "Arquetipos de sesiones" }, "sessionHeatmap": { "title": "Actividad de sesiones de lectura", @@ -470,5 +474,57 @@ "statusAbandoned": "Abandonado", "statusOther": "Otro", "trend": "Tendencia" + }, + "bookFlow": { + "title": "Flujo de libros", + "tooltip": "Un diagrama aluvial que muestra como fluyen los libros desde cuando se agregaron (izquierda) a traves de su estado de lectura (centro) hasta su rango de calificacion (derecha). Sigue los flujos para ver patrones en como tus adquisiciones se convierten en lecturas y calificaciones.", + "description": "Como fluyen los libros desde la adquisicion al estado y la calificacion", + "totalBooks": "Total de libros", + "busiestQuarter": "Trimestre mas activo", + "topStatus": "Estado principal", + "avgRating": "Calif. promedio", + "completionRate": "Completados", + "colAdded": "Agregado", + "colStatus": "Estado", + "colRating": "Calificacion", + "noData": "No se encontraron libros en tu biblioteca.", + "noDataHint": "Agrega algunos libros para ver el diagrama de flujo." + }, + "readingDebt": { + "title": "Deuda de lectura", + "tooltip": "Cada mes muestra libros agregados (rojo) y libros terminados (verde) en los ultimos 12 meses. La linea amarilla rastrea tu acumulacion pendiente. Una linea ascendente significa que tu pila por leer esta creciendo.", + "description": "Libros agregados vs terminados mensualmente con acumulacion pendiente", + "booksAdded": "Libros agregados", + "booksFinished": "Libros terminados", + "backlog": "Pendientes", + "currentBacklog": "Pendientes actuales", + "trendLabel": "Tendencia", + "growing": "Creciendo", + "shrinking": "Reduciendose", + "noData": "No se encontraron datos de actividad de libros.", + "noDataHint": "Agrega y termina libros para ver tu tendencia de deuda de lectura." + }, + "publicationEra": { + "title": "Era de publicacion vs calificacion", + "tooltip": "Cada linea representa una decada de publicacion, mostrando cuantos libros de esa era le diste a cada rango de calificacion. Compara lineas para ver que decadas calificas mas alto.", + "description": "Que decadas de publicacion calificas mas alto", + "bestDecade": "Mejor decada", + "avgRating": "Calif. promedio", + "booksRated": "Libros calificados", + "noData": "No hay suficientes libros calificados con fechas de publicacion.", + "noDataHint": "Califica libros que tengan metadatos de fecha de publicacion para ver comparaciones por era." + }, + "sessionArchetypes": { + "title": "Arquetipos de sesiones", + "tooltip": "Cada punto es una sesion de lectura graficada por hora del dia (X) y duracion en minutos (Y), coloreada por dia de la semana. Los grupos naturales revelan tus patrones de lectura.", + "description": "Tus patrones de sesiones de lectura por hora y duracion", + "sessions": "Sesiones", + "dominantType": "Tipo dominante", + "archetype_morning": "Lector matutino", + "archetype_afternoon": "Lector vespertino", + "archetype_evening": "Lector nocturno", + "archetype_night": "Noctambulo", + "noData": "No se encontraron sesiones de lectura para este ano.", + "noDataHint": "Rastrea sesiones de lectura para descubrir tus arquetipos de sesion." } }