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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions app/src/Stats.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ function Finished({ list, titles }) {
)
}

function PagesAndBooks({ activity: all, books }) {
function PagesAndBooks({ activity: all, books, hasArticles }) {
const titles = new Map(books.map((b) => [b.document, b.title || b.filename || 'Untitled book']))
// Only books the library shows (metadata-less ones are hidden everywhere unless Settings shows them).
const shown = all.books.filter((b) => titles.has(b.document))
Expand All @@ -612,7 +612,7 @@ function PagesAndBooks({ activity: all, books }) {
const known = activity.books.filter((b) => b.page_count).length
const tiles = [
['Pages read', activity.pages_total.toLocaleString()],
['Books finished', activity.books.filter(b => b.completed || b.finished_at).length],
[hasArticles ? 'Titles finished' : 'Books finished', finished.length],
['Reading now', books.filter((b) => b.status === 'reading').length],
['Finished this year', finished.filter((b) => b.finished_at && new Date(b.finished_at * 1000).getFullYear() === new Date().getFullYear()).length],
['Pages per book', known ? Math.round(activity.books.reduce((n, b) => n + (b.page_count ?? 0), 0) / known) : '-'],
Expand Down Expand Up @@ -973,15 +973,15 @@ export default function Stats({ session, tab = '', summary, activity, books, goa
</button>
)}
</div>
{activity ? <PagesAndBooks activity={activity} books={books} /> : !activityError && <p className="py-6 text-sm text-stone-500">Loading…</p>}
{activity ? <PagesAndBooks activity={activity} books={books} hasArticles={summary?.has_articles} /> : !activityError && <p className="py-6 text-sm text-stone-500">Loading…</p>}
<WhatYouRead books={books} />

{summary?.bookorbit?.excluded_sessions > 0 && (
<p className="mt-4 text-sm text-stone-500">
Duplicate BookOrbit session records are counted once. Reading from your other devices is included.
</p>
)}
{hasTime ? (
{hasTime || summary?.has_articles ? (
<>
<h2 className="mt-10 font-display text-xl font-semibold text-stone-900">Reading time</h2>
<Tiles
Expand All @@ -997,7 +997,9 @@ export default function Stats({ session, tab = '', summary, activity, books, goa
['Time read', duration(summary.seconds)],
['Pages turned', summary.pages.toLocaleString()],
['Sessions', summary.sessions.toLocaleString()],
['Books finished', books.filter((b) => b.status === 'finished').length],
...(summary.has_articles
? [['Books finished', summary.completed_books], ['Articles finished', summary.completed_articles]]
: [['Books finished', books.filter((b) => b.status === 'finished').length]]),
]}
/>
</>
Expand Down
9 changes: 9 additions & 0 deletions app/src/Stats.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -496,3 +496,12 @@ it('pins every year-calendar day to its weekday row', () => {
const rows = { Mon: '1', Tue: '2', Wed: '3', Thu: '4', Fri: '5', Sat: '6', Sun: '7' }
for (const el of cells) expect(el.style.gridRow).toBe(rows[el.dataset.tip.slice(0, 3)])
})

it('shows finished articles after the first mark even without a reading session', () => {
const summary = { seconds: 0, sessions: 0, pages: 0, completed: 0, completed_books: 0, completed_articles: 0,
current_streak: 0, streak: 0, daily: [], devices: [], tod: [0, 0, 0, 0], dow: Array(7).fill(0) }
const { rerender, queryByText, getByText } = render(<Stats session={{}} books={[]} summary={summary} />)
expect(queryByText('Articles finished')).toBeNull()
rerender(<Stats session={{}} books={[]} summary={{ ...summary, has_articles: true }} />)
expect(getByText('Articles finished').parentElement.textContent).toContain('0')
})
8 changes: 8 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,14 @@ Imported time is never converted into progress-log entries or extra page/sync co
Unlinking removes imported stats; relinking clears the old import, and changing
the BookOrbit server/user also clears stale matches, queued exports, and EPUB maps.

Reading type is optional. Article-aware readers include `completed_books`,
`completed_articles`, and `has_articles` with a global snapshot. The two
counts add up to the existing `completed` total. Marking an unfinished article
can set `has_articles` before either completion count changes. Per-document
snapshots may include the boolean `is_article`. The book response retains the
type per device and shows an article in the combined view when any reporting
device classifies its copy that way. Older clients continue to use `completed`.

#### PUT /api/v1/stats/global

The device's `GlobalReadingStats` as JSON:
Expand Down
19 changes: 16 additions & 3 deletions src/models/stats-counters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@ function preserveCounters(old: Snapshot, incoming: Snapshot, book: boolean, lega
seconds: Math.max(old.seconds, incoming.seconds), pages: Math.max(old.pages, incoming.pages),
tod: maxArray(old.tod, incoming.tod), dow: maxArray(old.dow, incoming.dow) };
if (book) {
if (!legacyUpload) return result;
const a = old as BookStatsSnapshot, b = incoming as BookStatsSnapshot;
const current = result as BookStatsSnapshot;
// Older senders omit the type. Preserve the saved classification on their next upload.
current.is_article ??= a.is_article;
if (!legacyUpload) return current;
// Untagged uploads cannot distinguish metadata edits from resets, even once
// reading resumes. Library completions may have no reading counters at all.
const a = old as BookStatsSnapshot, b = incoming as BookStatsSnapshot;
const start = a.start_date && b.start_date ? Math.min(a.start_date, b.start_date) : a.start_date || b.start_date;
const finish = Math.max(a.finished_date, b.finished_date);
return { ...result, completed: a.completed || b.completed, start_date: start, finished_date: finish,
Expand All @@ -48,8 +51,16 @@ function preserveCounters(old: Snapshot, incoming: Snapshot, book: boolean, lega
}
const a = old as GlobalStatsSnapshot, global = incoming as GlobalStatsSnapshot;
const history = combineHistory([a, global]);
const completed = legacyUpload ? Math.max(a.completed, global.completed) : Number(result.completed);
const latest = result as GlobalStatsSnapshot;
const articles = latest.completed_articles ?? a.completed_articles;
const split = articles === undefined ? {} : {
completed_articles: Math.min(completed, articles),
completed_books: Math.max(0, completed - articles),
has_articles: latest.has_articles === true || a.has_articles === true,
};
return { ...result, anchor_day: history.anchorDay, history_b64: history.history.toString('base64'),
completed: legacyUpload ? Math.max(a.completed, global.completed) : result.completed,
completed, ...split,
streak: Math.max(a.streak, global.streak) } as GlobalStatsSnapshot;
}

Expand Down Expand Up @@ -78,6 +89,8 @@ export function storeStatsSnapshot(
db.prepare(`INSERT INTO stats_device_book VALUES (?, ?, ?, ?, ?)
ON CONFLICT(user_id, device_id, document) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at`)
.run(userId, deviceId, document, JSON.stringify({ ...snapshot, ...combined,
// Reading type is an edit to this device's copy. A retired lifetime must not pin it to Article.
is_article: (snapshot as BookStatsSnapshot).is_article ?? combined.is_article,
pace_n: snapshots.reduce((n, s) => n + s.pace_n, 0) }), now);
}
}
Expand Down
25 changes: 25 additions & 0 deletions src/models/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export interface GlobalStatsSnapshot {
seconds: number;
pages: number;
completed: number;
completed_books?: number;
completed_articles?: number;
has_articles?: boolean;
tod: number[]; // [morning, afternoon, evening, night] seconds
dow: number[]; // Mon..Sun seconds
/** Days since 2000-01-01 of the most recent day covered by the history bitmap. */
Expand All @@ -37,6 +40,7 @@ export interface BookStatsSnapshot {
seconds: number;
pages: number;
completed: boolean;
is_article?: boolean;
avg_fwd: number;
pace_n: number;
eta: number;
Expand Down Expand Up @@ -86,6 +90,14 @@ export function parseGlobalStats(raw: unknown): GlobalStatsSnapshot | null {
) {
return null;
}
// Older clients only send the combined total. Validate an explicit split as a unit.
const split = o.completed_books !== undefined || o.completed_articles !== undefined || o.has_articles !== undefined;
let categories: Pick<GlobalStatsSnapshot, 'completed_books' | 'completed_articles' | 'has_articles'> = {};
if (split) {
if (!isCount(o.completed_books) || !isCount(o.completed_articles) || typeof o.has_articles !== 'boolean' ||
o.completed !== o.completed_books + o.completed_articles || (o.completed_articles > 0 && !o.has_articles)) return null;
categories = { completed_books: o.completed_books, completed_articles: o.completed_articles, has_articles: o.has_articles };
}
let history: Buffer;
try {
history = Buffer.from(o.history_b64, 'base64');
Expand All @@ -99,6 +111,7 @@ export function parseGlobalStats(raw: unknown): GlobalStatsSnapshot | null {
seconds: o.seconds,
pages: o.pages,
completed: o.completed,
...categories,
tod: o.tod,
dow: o.dow,
anchor_day: o.anchor_day,
Expand All @@ -116,6 +129,7 @@ export function parseBookStats(raw: unknown): BookStatsSnapshot | null {
!isCount(o.seconds) ||
!isCount(o.pages) ||
typeof o.completed !== 'boolean' ||
(o.is_article !== undefined && typeof o.is_article !== 'boolean') ||
!isCount(o.avg_fwd) ||
!isCount(o.pace_n) ||
!isCount(o.eta) ||
Expand All @@ -134,6 +148,7 @@ export function parseBookStats(raw: unknown): BookStatsSnapshot | null {
seconds: o.seconds,
pages: o.pages,
completed: o.completed,
...(typeof o.is_article === 'boolean' && { is_article: o.is_article }),
avg_fwd: o.avg_fwd,
pace_n: o.pace_n,
eta: o.eta,
Expand Down Expand Up @@ -212,6 +227,9 @@ export interface GlobalStatsSummary {
seconds: number;
pages: number;
completed: number;
completed_books?: number;
completed_articles?: number;
has_articles?: boolean;
tod: number[];
dow: number[];
anchor_day: number;
Expand All @@ -238,9 +256,14 @@ export function combineGlobalStats(snapshots: GlobalStatsSnapshot[]): GlobalStat
sum.seconds += s.seconds;
sum.pages += s.pages;
sum.completed += s.completed;
if (s.completed_articles !== undefined) {
sum.completed_articles = (sum.completed_articles ?? 0) + s.completed_articles;
sum.has_articles = !!(sum.has_articles || s.has_articles);
}
for (let i = 0; i < 4; i++) sum.tod[i] += s.tod[i];
for (let i = 0; i < 7; i++) sum.dow[i] += s.dow[i];
}
if (sum.completed_articles !== undefined) sum.completed_books = sum.completed - sum.completed_articles;
const { anchorDay, history } = combineHistory(snapshots);
sum.anchor_day = anchorDay;
sum.history_b64 = history.toString('base64');
Expand All @@ -255,6 +278,7 @@ export interface BookStatsCombined {
seconds: number;
pages: number;
completed: boolean;
is_article?: boolean;
avg_fwd: number;
start_date: number;
finished_date: number;
Expand All @@ -281,6 +305,7 @@ export function combineBookStats(snapshots: BookStatsSnapshot[]): BookStatsCombi
out.seconds += s.seconds;
out.pages += s.pages;
out.completed = out.completed || s.completed;
if (s.is_article !== undefined) out.is_article = !!(out.is_article || s.is_article);
for (let i = 0; i < 4; i++) out.tod[i] += s.tod[i];
for (let i = 0; i < 7; i++) out.dow[i] += s.dow[i];
if (s.pace_n > 0) {
Expand Down
29 changes: 29 additions & 0 deletions test/stats-counters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,35 @@ async function fixture() {
}

describe('reset-aware reading stats (#80)', () => {
it('keeps article classification and inclusive totals through retries, reversal, and mixed devices', async () => {
const f = await fixture();
const split = (articles: number) => global(3600, {
counter_id: A, completed: 4, completed_books: 4 - articles, completed_articles: articles, has_articles: true,
});
await f.put('counters/global', { ...global(), device_id: 'old-reader', counter_id: B });
for (const articles of [0, 1, 1, 0]) {
expect((await f.put('counters/global', split(articles))).status).toBe(200);
expect((await f.put('counters/books', { device_id: 'reader', items: [book(3600, { counter_id: A, is_article: !!articles })] })).status).toBe(200);
expect(await f.get('summary')).toMatchObject({
completed: 5, completed_books: 5 - articles, completed_articles: articles, has_articles: true, seconds: 7200,
});
expect((await f.get(`books/${DOC}`)).combined).toMatchObject({ completed: true, is_article: !!articles });
}
expect((await f.put('counters/global', { ...split(1), completed_books: 4 })).status).toBe(403);
expect((await f.put('counters/books', { device_id: 'reader', items: [book(0, { is_article: 'yes' })] })).status).toBe(403);
});

it('keeps an existing split and type when a legacy sender omits both', async () => {
const f = await fixture();
const submit = (item: unknown) => f.put('counters/books', { device_id: 'reader', items: [item] });
await f.put('counters/global', global(3600, { counter_id: A, completed_books: 0, completed_articles: 1, has_articles: true }));
await submit(book(3600, { counter_id: A, is_article: true }));
await f.put('counters/global', global(3600, { counter_id: A, completed: 2 }));
await submit(book(3600, { counter_id: A }));
expect(await f.get('summary')).toMatchObject({ completed: 2, completed_books: 1, completed_articles: 1 });
expect((await f.get(`books/${DOC}`)).combined.is_article).toBe(true);
});

it('preserves a legacy baseline, adds fresh reading, and keeps retries/restored cards idempotent', async () => {
const f = await fixture();
const submit = async (counter: unknown) => expect((await f.put('counters/global', counter)).status).toBe(200);
Expand Down