feat(stats): per-device reading breakdown + device attribution on progress syncs

- Attribution: registered clients may now send their device token in
  X-Device-Token on PUT /api/media-items/:id/progress (the user JWT
  stays primary). The token must map to a device OWNED BY the caller —
  foreign/invalid/absent tokens soft-fail to plain web attribution so a
  stats decoration can never break a sync. Attributed pushes capture
  device_id (FK-safe), device_metadata.source = the registered device
  name ('Pixel 9', 'Kindle Paperwhite'), and last_sync surfaces show
  that device. Side effect worth having: app-vs-web pushes used to be
  LWW-invisible (both sources read 'web'); they now surface as
  legitimate cross-source progress conflicts when they diverge.
- /stats gains a By Device panel alongside By Library (grid 3-wide):
  reading minutes + sessions + books per registered device, plus one
  Web / unsynced bucket for device-less pushes so the panel always
  reconciles with the headline totals. Range-aware, family-lens
  scoped; renderBars shared between panels in stats.ts.
- The device identity IS the registered platform: devices rows already
  carry the name/type the client registered (app sends Build.MODEL +
  'mobile' at /api/devices/register, KOReader/Kobo likewise) — no new
  identity plumbing on the server.

Tests: capture attributed to the device (row device_id + source
metadata + last_sync_source), foreign/nonexistent tokens soft-fail,
device buckets reconcile (80 attributed + 75 unsynced = 155 total).
Full suite PASS.
This commit is contained in:
John O'Keefe committed 2026-10-14 13:04:34 -04:00
1 parent be10adc24b
commit 7a604c2fec
8 files changed
+399 -20

No files matched your search

+48 -2
View File
@@ -114,6 +114,18 @@ type LibraryStats struct {
Books int `json:"books"`
}
type DeviceStats struct {
// DeviceID is empty for the unattributed bucket (web reader pushes
// that carry no device credential) — Name then reads "Web / unsynced".
DeviceID string `json:"device_id"`
Name string `json:"name"`
Type string `json:"type"`
Minutes int `json:"minutes"`
Pages int `json:"pages"`
Sessions int `json:"sessions"`
Books int `json:"books"`
}
type UserSummaryStats struct {
Range string `json:"range"`
Days int `json:"days"`
@@ -131,8 +143,9 @@ type UserSummaryStats struct {
MostActiveWeekday string `json:"most_active_weekday"` // by minutes over the range; "" when nothing
MostActiveDay string `json:"most_active_day"` // date with the most minutes
MostActiveMinutes int `json:"most_active_day_minutes"`
TopBooks []TopBookStats `json:"top_books"`
LibraryBreakdown []LibraryStats `json:"library_breakdown"`
TopBooks []TopBookStats `json:"top_books"`
LibraryBreakdown []LibraryStats `json:"library_breakdown"`
DeviceBreakdown []DeviceStats `json:"device_breakdown"`
}
type WeekSummaryStats struct {
@@ -225,6 +238,7 @@ func (s *StatisticsService) UserSummary(ctx context.Context, userID pgtype.UUID,
Daily: make([]DailyStats, 0, statsRange.Days),
TopBooks: []TopBookStats{},
LibraryBreakdown: []LibraryStats{},
DeviceBreakdown: []DeviceStats{},
}
// Zero-filled calendar (inclusive of today).
@@ -380,6 +394,38 @@ func (s *StatisticsService) UserSummary(ctx context.Context, userID pgtype.UUID,
}
}
// Per-device breakdown in the range (LEFT JOIN devices: NULL-device
// pushes aggregate into one unattributed row so the panel reconciles
// with the totals).
deviceRows, err := s.db.GetUserDeviceBreakdown(ctx, database.GetUserDeviceBreakdownParams{
UserID: userID,
StartTime: pgtype.Timestamptz{Time: statsRange.Start, Valid: true},
EndTime: pgtype.Timestamptz{Time: statsRange.End, Valid: true},
VisibleLibraryIds: visibleOrNil(visibleIDs),
})
if err == nil {
for _, row := range deviceRows {
entry := DeviceStats{
Minutes: int(row.TotalSeconds) / 60,
Pages: int(row.TotalPages),
Sessions: int(row.SessionCount),
Books: int(row.BookCount),
Name: "Web / unsynced",
Type: "unattributed",
}
if row.DeviceName.Valid && row.DeviceName.String != "" {
entry.Name = row.DeviceName.String
}
if row.DeviceType.Valid && row.DeviceType.String != "" {
entry.Type = row.DeviceType.String
}
if row.ID.Valid {
entry.DeviceID = uuid.UUID(row.ID.Bytes).String()
}
summary.DeviceBreakdown = append(summary.DeviceBreakdown, entry)
}
}
return summary, nil
}