fix(reading sessions): Split sessions, re-calculate times in book overview (#2393)

* do not group reading sessions on a per-day basis

* calculate actual duration for reading sessions

---------

Co-authored-by: WorldTeacher <coding_contact@pm.me>
This commit is contained in:
WorldTeacher
2026-01-22 13:04:17 -07:00
committed by GitHub
co-authored by WorldTeacher
parent 97343ee067
commit d137055b83
6 changed files with 74 additions and 31 deletions
@@ -25,24 +25,23 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
""")
List<ReadingSessionCountDto> findSessionCountsByUserAndYear(@Param("userId") Long userId, @Param("year") int year);
@Query("""
SELECT
b.id as bookId,
COALESCE(b.metadata.title,
(SELECT bf.fileName FROM BookFileEntity bf WHERE bf.book.id = b.id ORDER BY bf.id ASC LIMIT 1),
'Unknown Book') as bookTitle,
rs.bookType as bookFileType,
MIN(rs.startTime) as startDate,
MAX(rs.endTime) as endDate,
COUNT(rs) as totalSessions,
SUM(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs
JOIN rs.book b
WHERE rs.user.id = :userId
AND rs.startTime >= :startOfWeek AND rs.startTime < :endOfWeek
GROUP BY b.id, b.metadata.title, rs.bookType, CAST(rs.startTime AS LocalDate)
ORDER BY MIN(rs.startTime)
""")
@Query("""
SELECT
b.id as bookId,
COALESCE(b.metadata.title,
(SELECT bf.fileName FROM BookFileEntity bf WHERE bf.book.id = b.id ORDER BY bf.id ASC LIMIT 1),
'Unknown Book') as bookTitle,
rs.bookType as bookFileType,
rs.startTime as startDate,
rs.endTime as endDate,
1L as totalSessions,
rs.durationSeconds as totalDurationSeconds
FROM ReadingSessionEntity rs
JOIN rs.book b
WHERE rs.user.id = :userId
AND rs.startTime >= :startOfWeek AND rs.startTime < :endOfWeek
ORDER BY rs.startTime
""")
List<ReadingSessionTimelineDto> findSessionTimelineByUserAndWeek(
@Param("userId") Long userId,
@Param("startOfWeek") Instant startOfWeek,
@@ -36,7 +36,7 @@
<tr>
<td>{{ formatDate(session.startTime) }}</td>
<td>{{ formatDate(session.endTime) }}</td>
<td>{{ formatDuration(session.durationSeconds) }}</td>
<td>{{ getActualDuration(session) }}</td>
<td>
@if (session.startProgress !== null && session.startProgress !== undefined && session.endProgress !== null && session.endProgress !== undefined) {
<span>{{ session.startProgress }}% → {{ session.endProgress }}%</span>
@@ -69,6 +69,24 @@ export class BookReadingSessionsComponent implements OnInit, OnChanges {
return `${secs}s`;
}
calculateActualDuration(session: ReadingSessionResponse): number {
const startTime = new Date(session.startTime).getTime();
const endTime = new Date(session.endTime).getTime();
return Math.floor((endTime - startTime) / 1000);
}
getActualDuration(session: ReadingSessionResponse): string {
const actualDuration = this.calculateActualDuration(session);
const storedDuration = session.durationSeconds;
if (Math.abs(actualDuration - storedDuration) > 1) {
// Discrepancy detected - show both values
return `${this.formatDuration(actualDuration)}`;
}
return this.formatDuration(actualDuration);
}
formatDate(dateString: string): string {
return new Date(dateString).toLocaleString();
}
@@ -145,8 +145,8 @@ export class ReadingSessionTimelineComponent implements OnInit {
response.forEach((item) => {
const startTime = new Date(item.startDate);
const duration = item.totalDurationSeconds / 60;
const endTime = new Date(startTime.getTime() + item.totalDurationSeconds * 1000);
const endTime = item.endDate ? new Date(item.endDate) : new Date(startTime.getTime() + item.totalDurationSeconds * 1000);
const duration = (endTime.getTime() - startTime.getTime()) / (1000 * 60);
sessions.push({
startTime,
@@ -1,4 +1,4 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient, HttpEventType, HttpHeaders, HttpResponse} from '@angular/common/http';
@@ -38,6 +38,12 @@ describe('FileDownloadService', () => {
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
vi.useFakeTimers();
});
afterEach(() => {
vi.runAllTimers();
vi.useRealTimers();
});
it('should trigger download and handle progress and completion', () => {
@@ -58,15 +64,23 @@ describe('FileDownloadService', () => {
// Mock DOM for download
const appendChild = vi.fn();
const removeChild = vi.fn();
const link = {
setAttribute: vi.fn(),
click: vi.fn(),
style: {},
href: '',
download: '',
parentNode: {
removeChild: removeChild
}
};
(globalThis as any).document = {
createElement: vi.fn().mockReturnValue({
setAttribute: vi.fn(),
click: vi.fn(),
style: {},
href: '',
download: ''
}),
body: {appendChild, removeChild}
createElement: vi.fn().mockReturnValue(link),
body: {
appendChild: appendChild,
removeChild: removeChild,
contains: vi.fn().mockReturnValue(true)
}
};
(globalThis as any).window = {
URL: {
@@ -134,6 +148,12 @@ describe('FileDownloadService - API Contract Tests', () => {
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
vi.useFakeTimers();
});
afterEach(() => {
vi.runAllTimers();
vi.useRealTimers();
});
describe('API contract', () => {
@@ -94,7 +94,13 @@ export class FileDownloadService {
link.click();
setTimeout(() => {
document.body.removeChild(link);
try {
if (link && link.parentNode) {
link.parentNode.removeChild(link);
}
} catch (e) {
// Ignore errors during cleanup, may occur if DOM is not available
}
window.URL.revokeObjectURL(objectUrl);
}, 100);
}