feat(workouts): accept an optional HR series on the batch contract

Extend POST /api/workouts/batch with an optional per-workout `samples`
array — a route-independent heart-rate series so indoor workouts still
yield a strain-relevant signal. Each entry is `{ t, hr?, speedMs?,
power?, cadence? }`; the array is capped at 30 000 points
(MAX_WORKOUT_HR_SAMPLES), covering a long endurance session sampled at
1 Hz while bounding the largest new workout-side write stream the same
way the 20 000-point route cap bounds the geometry.

Persistence rides the existing route-attachment path: the freshly
written workout id is resolved once (by composite key, or the manual
tuple), then both the route geometry and the HR series attach by FK
with skipDuplicates so a re-submitted batch stays idempotent. A workout
may carry both a GPS route and a canonical HR series, or just one.

GET /api/workouts/{id} returns the series alongside the route. OpenAPI
regenerated.

`samples` keeps first-write-wins/overwrite parity with the workout row
it hangs off: the 1:1 FK plus skipDuplicates means a re-ingest of an
existing workout never duplicates or mutates its series.
This commit is contained in:
Marc-André Bombeck committed 2026-06-02 22:02:46 +02:00
1 parent d247f6966a
commit 30be0c4e0d
8 files changed
+463 -13

No files matched your search

@@ -21,6 +21,9 @@ vi.mock("@/lib/db", () => ({
workoutRoute: {
createMany: vi.fn(),
},
workoutSamples: {
createMany: vi.fn(),
},
user: {
findUnique: vi.fn(),
},
@@ -123,6 +126,7 @@ beforeEach(() => {
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 0 });
vi.mocked(prisma.workout.findFirst).mockResolvedValue(null);
vi.mocked(prisma.workoutRoute.createMany).mockResolvedValue({ count: 0 });
vi.mocked(prisma.workoutSamples.createMany).mockResolvedValue({ count: 0 });
// v1.4.43 W9 — default to no per-user source-priority override so
// the write-time picker walks the canonical default ladder. Tests
// that exercise a custom ladder override this in-line.
@@ -386,6 +390,122 @@ describe("POST /api/workouts/batch — nested route attachment", () => {
});
});
describe("POST /api/workouts/batch — per-workout HR series (v1.10.0)", () => {
it("creates a WorkoutSamples row for an indoor workout (samples, no route)", async () => {
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 1 });
vi.mocked(prisma.workout.findMany).mockImplementation((async (args: {
select?: { id?: true };
}) => {
if (args.select?.id) {
return [
{
id: "wkt-indoor-id",
source: "APPLE_HEALTH",
externalId: "uuid-indoor",
},
];
}
return [];
}) as never);
const res = await POST(
makeRequest({
workouts: [
validWorkout("uuid-indoor", {
sportType: "strength",
samples: [
{ t: "2026-05-14T06:30:00.000Z", hr: 110 },
{ t: "2026-05-14T06:30:05.000Z", hr: 118 },
{ t: "2026-05-14T06:30:10.000Z", hr: 124, power: 0, cadence: 0 },
],
}),
],
}),
);
expect(res.status).toBe(200);
// The route table is untouched — an indoor workout has no GPS route.
expect(prisma.workoutRoute.createMany).not.toHaveBeenCalled();
// The HR series lands in the dedicated child table by FK.
expect(prisma.workoutSamples.createMany).toHaveBeenCalledTimes(1);
const call = vi.mocked(prisma.workoutSamples.createMany).mock.calls[0]?.[0];
const rows = (
call as {
data: Array<{
workoutId: string;
sampleCount: number;
samples: unknown;
}>;
}
).data;
expect(rows[0]?.workoutId).toBe("wkt-indoor-id");
// `sampleCount` is the denormalised series length.
expect(rows[0]?.sampleCount).toBe(3);
expect((rows[0]?.samples as unknown[]).length).toBe(3);
});
it("attaches both a route and an HR series on one workout", async () => {
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 1 });
vi.mocked(prisma.workout.findMany).mockImplementation((async (args: {
select?: { id?: true };
}) => {
if (args.select?.id) {
return [
{
id: "wkt-both-id",
source: "APPLE_HEALTH",
externalId: "uuid-both",
},
];
}
return [];
}) as never);
const res = await POST(
makeRequest({
workouts: [
validWorkout("uuid-both", {
route: {
geometry: {
type: "LineString",
coordinates: [
[11.077, 49.452],
[11.078, 49.453],
],
},
},
samples: [{ t: "2026-05-14T06:30:00.000Z", hr: 142 }],
}),
],
}),
);
expect(res.status).toBe(200);
expect(prisma.workoutRoute.createMany).toHaveBeenCalledTimes(1);
expect(prisma.workoutSamples.createMany).toHaveBeenCalledTimes(1);
const routeRows = (
vi.mocked(prisma.workoutRoute.createMany).mock.calls[0]?.[0] as {
data: Array<{ workoutId: string }>;
}
).data;
const sampleRows = (
vi.mocked(prisma.workoutSamples.createMany).mock.calls[0]?.[0] as {
data: Array<{ workoutId: string }>;
}
).data;
// Both children attach to the SAME freshly-inserted workout id.
expect(routeRows[0]?.workoutId).toBe("wkt-both-id");
expect(sampleRows[0]?.workoutId).toBe("wkt-both-id");
});
it("does not touch the samples table when no workout ships a series", async () => {
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 1 });
const res = await POST(
makeRequest({ workouts: [validWorkout("uuid-no-series")] }),
);
expect(res.status).toBe(200);
expect(prisma.workoutSamples.createMany).not.toHaveBeenCalled();
});
});
describe("POST /api/workouts/batch — user source-priority (v1.4.43 W9)", () => {
it("looks up the user's source-priority blob exactly once per batch", async () => {
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 1 });