mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-08 12:32:43 +00:00
The summaries slice and the comprehensive aggregator took their JS windows (the DAY-bucket bounds, the rollup slope anchors, lastSeen staleness) from the process clock and their SQL windows (avg7, avg30, the month before, the median, the 90-day canonical pick, the cold-path slope evidence) from NOW(), the database's clock. One response mixed two clocks, so a reading on a window's edge fell in or out with whichever host answered, and with the process clock pinned the analytics parity walk changed its avg7 with the hour it ran at. Each read now takes one `now` and binds it into its statements (`request-clock-sql.ts`): `$N::timestamp`, which keeps the driver's offset-free UTC string as written in any session zone. The canonical-pick helper takes its window as an instant plus an interval instead of reading NOW(); the series and calendar readers anchor it on their own `since`, the BP-in-target read on its 365-day start. The window-mean and live-slope columns the two aggregates each spelled out now come from one builder. The streak's local day series read its bounds through `::timestamptz`, which follows the session zone: outside a UTC session today's reading fell out of the streak. It reads them as UTC first. The parity walks for analytics, the dashboard summary and the comprehensive overview pin a fixed day instead of today: their records are laid out from the anchor day, so the chronotype's work and free nights and the weight-by-weekday points moved with the weekday the walk ran on. The snapshots are unchanged. A new suite pins the clock to four times of day, far from the database clock, with readings ten minutes either side of every edge, on both read paths, in a UTC and an Auckland session.
172 lines
4.7 KiB
TypeScript
172 lines
4.7 KiB
TypeScript
/**
|
|
* The activity calendar's reader against a real Postgres (D1036).
|
|
*
|
|
* - steps resolve to the source the person's ladder picks per day, so a day
|
|
* two devices counted shows one device's total, never the sum;
|
|
* - the day is the person's local day: a reading at 23:30 Berlin time lands
|
|
* on that day, not on the UTC day after;
|
|
* - a workout two devices recorded counts once, its minutes once;
|
|
* - the window is exact: nothing before `fromKey` or after `toKey`.
|
|
*/
|
|
import { beforeAll, describe, expect, it, vi } from "vitest";
|
|
|
|
import { getPrismaClient, truncateAllTables } from "./setup";
|
|
import { readActivityDays } from "@/lib/activity/calendar-read";
|
|
import { invalidateUserTimezone } from "@/lib/tz/resolver";
|
|
import { userDayKey } from "@/lib/tz/format";
|
|
|
|
vi.mock("@/lib/db-compat", () => ({
|
|
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
|
}));
|
|
|
|
const prisma = getPrismaClient();
|
|
const TZ = "Europe/Berlin";
|
|
const USER = "activity-reader";
|
|
const DAY = 86_400_000;
|
|
const NOW = new Date();
|
|
|
|
function daysAgo(n: number, hourUtc = 10): Date {
|
|
const d = new Date(NOW.getTime() - n * DAY);
|
|
d.setUTCHours(hourUtc, 0, 0, 0);
|
|
return d;
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
await truncateAllTables(prisma);
|
|
await prisma.user.create({
|
|
data: {
|
|
id: USER,
|
|
username: USER,
|
|
timezone: TZ,
|
|
sourcePriorityJson: {
|
|
metricPriority: { steps: ["FITBIT", "APPLE_HEALTH"] },
|
|
},
|
|
},
|
|
});
|
|
invalidateUserTimezone(USER);
|
|
|
|
await prisma.measurement.createMany({
|
|
data: [
|
|
// Day 3: both devices; the ladder picks Fitbit's 8 000.
|
|
{
|
|
userId: USER,
|
|
type: "ACTIVITY_STEPS",
|
|
value: 9500,
|
|
unit: "steps",
|
|
source: "APPLE_HEALTH",
|
|
measuredAt: daysAgo(3),
|
|
},
|
|
{
|
|
userId: USER,
|
|
type: "ACTIVITY_STEPS",
|
|
value: 8000,
|
|
unit: "steps",
|
|
source: "FITBIT",
|
|
measuredAt: daysAgo(3),
|
|
},
|
|
// Day 2: Apple only, two slices that add up.
|
|
{
|
|
userId: USER,
|
|
type: "ACTIVITY_STEPS",
|
|
value: 3000,
|
|
unit: "steps",
|
|
source: "APPLE_HEALTH",
|
|
measuredAt: daysAgo(2, 8),
|
|
},
|
|
{
|
|
userId: USER,
|
|
type: "ACTIVITY_STEPS",
|
|
value: 4000,
|
|
unit: "steps",
|
|
source: "APPLE_HEALTH",
|
|
measuredAt: daysAgo(2, 15),
|
|
},
|
|
// 21:30 UTC is 23:30 in Berlin (summer) or 22:30 (winter): still day 5 locally.
|
|
{
|
|
userId: USER,
|
|
type: "ACTIVITY_STEPS",
|
|
value: 1200,
|
|
unit: "steps",
|
|
source: "APPLE_HEALTH",
|
|
measuredAt: daysAgo(5, 21),
|
|
},
|
|
{
|
|
userId: USER,
|
|
type: "EXERCISE_MINUTES",
|
|
value: 25,
|
|
unit: "min",
|
|
source: "APPLE_HEALTH",
|
|
measuredAt: daysAgo(3, 9),
|
|
},
|
|
{
|
|
userId: USER,
|
|
type: "EXERCISE_MINUTES",
|
|
value: 15,
|
|
unit: "min",
|
|
source: "APPLE_HEALTH",
|
|
measuredAt: daysAgo(3, 17),
|
|
},
|
|
// Outside the window asked for below.
|
|
{
|
|
userId: USER,
|
|
type: "ACTIVITY_STEPS",
|
|
value: 777,
|
|
unit: "steps",
|
|
source: "APPLE_HEALTH",
|
|
measuredAt: daysAgo(40),
|
|
},
|
|
],
|
|
});
|
|
|
|
const start = daysAgo(3, 7);
|
|
await prisma.workout.createMany({
|
|
data: [
|
|
{
|
|
userId: USER,
|
|
sportType: "running",
|
|
startedAt: start,
|
|
endedAt: new Date(start.getTime() + 40 * 60_000),
|
|
durationSec: 2400,
|
|
source: "APPLE_HEALTH",
|
|
externalId: "hk-1",
|
|
},
|
|
{
|
|
userId: USER,
|
|
sportType: "running",
|
|
startedAt: new Date(start.getTime() + 30_000),
|
|
endedAt: new Date(start.getTime() + 40 * 60_000),
|
|
durationSec: 2370,
|
|
source: "FITBIT",
|
|
externalId: "fb-1",
|
|
},
|
|
],
|
|
});
|
|
});
|
|
|
|
describe("readActivityDays", () => {
|
|
it("follows the ladder, the local day and the workout collapse", async () => {
|
|
const fromKey = userDayKey(daysAgo(10), TZ);
|
|
const toKey = userDayKey(NOW, TZ);
|
|
const { days } = await readActivityDays({
|
|
userId: USER,
|
|
tz: TZ,
|
|
fromKey,
|
|
toKey,
|
|
includeWorkouts: true,
|
|
});
|
|
const by = new Map(days.map((d) => [d.date, d]));
|
|
|
|
const d3 = by.get(userDayKey(daysAgo(3), TZ));
|
|
expect(d3?.steps).toBe(8000);
|
|
expect(d3?.exerciseMinutes).toBe(40);
|
|
expect(d3?.workoutCount).toBe(1);
|
|
expect(d3?.workoutsBySport).toEqual({ running: 1 });
|
|
expect(d3?.workoutMinutes).toBe(40);
|
|
|
|
expect(by.get(userDayKey(daysAgo(2), TZ))?.steps).toBe(7000);
|
|
expect(by.get(userDayKey(daysAgo(5, 21), TZ))?.steps).toBe(1200);
|
|
expect(days.every((d) => d.date >= fromKey && d.date <= toKey)).toBe(true);
|
|
expect(days.some((d) => d.steps === 777)).toBe(false);
|
|
});
|
|
});
|